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/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/GammaEvaluator.java
package com.airbnb.lottie.utils; /** * Use this instead of {@link android.animation.ArgbEvaluator} because it interpolates through the gamma color * space which looks better to us humans. * <p> * Written by Romain Guy and Francois Blavoet. * https://androidstudygroup.slack.com/archives/animation/p1476461064000335 */ public class GammaEvaluator { // Opto-electronic conversion function for the sRGB color space // Takes a gamma-encoded sRGB value and converts it to a linear sRGB value private static float OECF_sRGB(float linear) { // IEC 61966-2-1:1999 return linear <= 0.0031308f ? linear * 12.92f : (float) ((Math.pow(linear, 1.0f / 2.4f) * 1.055f) - 0.055f); } // Electro-optical conversion function for the sRGB color space // Takes a linear sRGB value and converts it to a gamma-encoded sRGB value private static float EOCF_sRGB(float srgb) { // IEC 61966-2-1:1999 return srgb <= 0.04045f ? srgb / 12.92f : (float) Math.pow((srgb + 0.055f) / 1.055f, 2.4f); } public static int evaluate(float fraction, int startInt, int endInt) { if (startInt == endInt) { return startInt; } float startA = ((startInt >> 24) & 0xff) / 255.0f; float startR = ((startInt >> 16) & 0xff) / 255.0f; float startG = ((startInt >> 8) & 0xff) / 255.0f; float startB = (startInt & 0xff) / 255.0f; float endA = ((endInt >> 24) & 0xff) / 255.0f; float endR = ((endInt >> 16) & 0xff) / 255.0f; float endG = ((endInt >> 8) & 0xff) / 255.0f; float endB = (endInt & 0xff) / 255.0f; // convert from sRGB to linear startR = EOCF_sRGB(startR); startG = EOCF_sRGB(startG); startB = EOCF_sRGB(startB); endR = EOCF_sRGB(endR); endG = EOCF_sRGB(endG); endB = EOCF_sRGB(endB); // compute the interpolated color in linear space float a = startA + fraction * (endA - startA); float r = startR + fraction * (endR - startR); float g = startG + fraction * (endG - startG); float b = startB + fraction * (endB - startB); // convert back to sRGB in the [0..255] range a = a * 255.0f; r = OECF_sRGB(r) * 255.0f; g = OECF_sRGB(g) * 255.0f; b = OECF_sRGB(b) * 255.0f; return Math.round(a) << 24 | Math.round(r) << 16 | Math.round(g) << 8 | Math.round(b); } }
2,500
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/LogcatLogger.java
package com.airbnb.lottie.utils; import android.util.Log; import com.airbnb.lottie.L; import com.airbnb.lottie.LottieLogger; import java.util.HashSet; import java.util.Set; /** * Default logger. * Warnings with same message will only be logged once. */ public class LogcatLogger implements LottieLogger { /** * Set to ensure that we only log each message one time max. */ private static final Set<String> loggedMessages = new HashSet<>(); public void debug(String message) { debug(message, null); } public void debug(String message, Throwable exception) { if (L.DBG) { Log.d(L.TAG, message, exception); } } public void warning(String message) { warning(message, null); } public void warning(String message, Throwable exception) { if (loggedMessages.contains(message)) { return; } Log.w(L.TAG, message, exception); loggedMessages.add(message); } @Override public void error(String message, Throwable exception) { if (L.DBG) { Log.d(L.TAG, message, exception); } } }
2,501
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/MiscUtils.java
package com.airbnb.lottie.utils; import android.graphics.Path; import android.graphics.PointF; import androidx.annotation.FloatRange; import com.airbnb.lottie.animation.content.KeyPathElementContent; import com.airbnb.lottie.model.CubicCurveData; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.model.content.ShapeData; import java.util.List; public class MiscUtils { private static final PointF pathFromDataCurrentPoint = new PointF(); public static PointF addPoints(PointF p1, PointF p2) { return new PointF(p1.x + p2.x, p1.y + p2.y); } public static void getPathFromData(ShapeData shapeData, Path outPath) { outPath.reset(); PointF initialPoint = shapeData.getInitialPoint(); outPath.moveTo(initialPoint.x, initialPoint.y); pathFromDataCurrentPoint.set(initialPoint.x, initialPoint.y); for (int i = 0; i < shapeData.getCurves().size(); i++) { CubicCurveData curveData = shapeData.getCurves().get(i); PointF cp1 = curveData.getControlPoint1(); PointF cp2 = curveData.getControlPoint2(); PointF vertex = curveData.getVertex(); if (cp1.equals(pathFromDataCurrentPoint) && cp2.equals(vertex)) { // On some phones like Samsung phones, zero valued control points can cause artifacting. // https://github.com/airbnb/lottie-android/issues/275 // // This does its best to add a tiny value to the vertex without affecting the final // animation as much as possible. // outPath.rMoveTo(0.01f, 0.01f); outPath.lineTo(vertex.x, vertex.y); } else { outPath.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, vertex.x, vertex.y); } pathFromDataCurrentPoint.set(vertex.x, vertex.y); } if (shapeData.isClosed()) { outPath.close(); } } public static float lerp(float a, float b, @FloatRange(from = 0f, to = 1f) float percentage) { return a + percentage * (b - a); } public static double lerp(double a, double b, @FloatRange(from = 0f, to = 1f) double percentage) { return a + percentage * (b - a); } public static int lerp(int a, int b, @FloatRange(from = 0f, to = 1f) float percentage) { return (int) (a + percentage * (b - a)); } static int floorMod(float x, float y) { return floorMod((int) x, (int) y); } private static int floorMod(int x, int y) { return x - y * floorDiv(x, y); } private static int floorDiv(int x, int y) { int r = x / y; boolean sameSign = (x ^ y) >= 0; int mod = x % y; if (!sameSign && mod != 0) { r--; } return r; } public static int clamp(int number, int min, int max) { return Math.max(min, Math.min(max, number)); } public static float clamp(float number, float min, float max) { return Math.max(min, Math.min(max, number)); } public static double clamp(double number, double min, double max) { return Math.max(min, Math.min(max, number)); } public static boolean contains(float number, float rangeMin, float rangeMax) { return number >= rangeMin && number <= rangeMax; } /** * Helper method for any {@link KeyPathElementContent} that will check if the content * fully matches the keypath then will add itself as the final key, resolve it, and add * it to the accumulator list. * <p> * Any {@link KeyPathElementContent} should call through to this as its implementation of * {@link KeyPathElementContent#resolveKeyPath(KeyPath, int, List, KeyPath)}. */ public static void resolveKeyPath(KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath, KeyPathElementContent content) { if (keyPath.fullyResolvesTo(content.getName(), depth)) { currentPartialKeyPath = currentPartialKeyPath.addKey(content.getName()); accumulator.add(currentPartialKeyPath.resolve(content)); } } }
2,502
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/LottieThreadFactory.java
package com.airbnb.lottie.utils; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class LottieThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public LottieThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); namePrefix = "lottie-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); // Don't prevent this thread from letting Android kill the app process if it wants to. t.setDaemon(false); // This will block the main thread if it isn't high enough priority // so this thread should be as close to the main thread priority as possible. t.setPriority(Thread.MAX_PRIORITY); return t; } }
2,503
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/utils/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.utils; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,504
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/DropShadowEffectParser.java
package com.airbnb.lottie.parser; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class DropShadowEffectParser { private static final JsonReader.Options DROP_SHADOW_EFFECT_NAMES = JsonReader.Options.of( "ef" ); private static final JsonReader.Options INNER_EFFECT_NAMES = JsonReader.Options.of( "nm", "v" ); private AnimatableColorValue color; private AnimatableFloatValue opacity; private AnimatableFloatValue direction; private AnimatableFloatValue distance; private AnimatableFloatValue radius; @Nullable DropShadowEffect parse(JsonReader reader, LottieComposition composition) throws IOException { while (reader.hasNext()) { switch (reader.selectName(DROP_SHADOW_EFFECT_NAMES)) { case 0: reader.beginArray(); while (reader.hasNext()) { maybeParseInnerEffect(reader, composition); } reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } if (color != null && opacity != null && direction != null && distance != null && radius != null) { return new DropShadowEffect(color, opacity, direction, distance, radius); } return null; } private void maybeParseInnerEffect(JsonReader reader, LottieComposition composition) throws IOException { String currentEffectName = ""; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(INNER_EFFECT_NAMES)) { case 0: currentEffectName = reader.nextString(); break; case 1: switch (currentEffectName) { case "Shadow Color": color = AnimatableValueParser.parseColor(reader, composition); break; case "Opacity": opacity = AnimatableValueParser.parseFloat(reader, composition, false); break; case "Direction": direction = AnimatableValueParser.parseFloat(reader, composition, false); break; case "Distance": distance = AnimatableValueParser.parseFloat(reader, composition); break; case "Softness": radius = AnimatableValueParser.parseFloat(reader, composition); break; default: reader.skipValue(); break; } break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); } }
2,505
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/PolystarShapeParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.content.PolystarShape; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class PolystarShapeParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "sy", "pt", "p", "r", "or", "os", "ir", "is", "hd", "d" ); private PolystarShapeParser() { } static PolystarShape parse( JsonReader reader, LottieComposition composition, int d) throws IOException { String name = null; PolystarShape.Type type = null; AnimatableFloatValue points = null; AnimatableValue<PointF, PointF> position = null; AnimatableFloatValue rotation = null; AnimatableFloatValue outerRadius = null; AnimatableFloatValue outerRoundedness = null; AnimatableFloatValue innerRadius = null; AnimatableFloatValue innerRoundedness = null; boolean hidden = false; boolean reversed = d == 3; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: type = PolystarShape.Type.forValue(reader.nextInt()); break; case 2: points = AnimatableValueParser.parseFloat(reader, composition, false); break; case 3: position = AnimatablePathValueParser.parseSplitPath(reader, composition); break; case 4: rotation = AnimatableValueParser.parseFloat(reader, composition, false); break; case 5: outerRadius = AnimatableValueParser.parseFloat(reader, composition); break; case 6: outerRoundedness = AnimatableValueParser.parseFloat(reader, composition, false); break; case 7: innerRadius = AnimatableValueParser.parseFloat(reader, composition); break; case 8: innerRoundedness = AnimatableValueParser.parseFloat(reader, composition, false); break; case 9: hidden = reader.nextBoolean(); break; case 10: // "d" is 2 for normal and 3 for reversed. reversed = reader.nextInt() == 3; break; default: reader.skipName(); reader.skipValue(); } } return new PolystarShape( name, type, points, position, rotation, innerRadius, outerRadius, innerRoundedness, outerRoundedness, hidden, reversed); } }
2,506
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapeTrimPathParser.java
package com.airbnb.lottie.parser; import static com.airbnb.lottie.parser.moshi.JsonReader.Options; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.content.ShapeTrimPath; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class ShapeTrimPathParser { private ShapeTrimPathParser() { } private static final Options NAMES = Options.of( "s", "e", "o", "nm", "m", "hd" ); static ShapeTrimPath parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; ShapeTrimPath.Type type = null; AnimatableFloatValue start = null; AnimatableFloatValue end = null; AnimatableFloatValue offset = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: start = AnimatableValueParser.parseFloat(reader, composition, false); break; case 1: end = AnimatableValueParser.parseFloat(reader, composition, false); break; case 2: offset = AnimatableValueParser.parseFloat(reader, composition, false); break; case 3: name = reader.nextString(); break; case 4: type = ShapeTrimPath.Type.forId(reader.nextInt()); break; case 5: hidden = reader.nextBoolean(); break; default: reader.skipValue(); } } return new ShapeTrimPath(name, type, start, end, offset, hidden); } }
2,507
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/LayerParser.java
package com.airbnb.lottie.parser; import android.graphics.Color; import android.graphics.Rect; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableTextFrame; import com.airbnb.lottie.model.animatable.AnimatableTextProperties; import com.airbnb.lottie.model.animatable.AnimatableTransform; import com.airbnb.lottie.model.content.BlurEffect; import com.airbnb.lottie.model.content.ContentModel; import com.airbnb.lottie.model.content.Mask; import com.airbnb.lottie.model.layer.Layer; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LayerParser { private LayerParser() { } private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", // 0 "ind", // 1 "refId", // 2 "ty", // 3 "parent", // 4 "sw", // 5 "sh", // 6 "sc", // 7 "ks", // 8 "tt", // 9 "masksProperties", // 10 "shapes", // 11 "t", // 12 "ef", // 13 "sr", // 14 "st", // 15 "w", // 16 "h", // 17 "ip", // 18 "op", // 19 "tm", // 20 "cl", // 21 "hd" // 22 ); public static Layer parse(LottieComposition composition) { Rect bounds = composition.getBounds(); return new Layer( Collections.<ContentModel>emptyList(), composition, "__container", -1, Layer.LayerType.PRE_COMP, -1, null, Collections.<Mask>emptyList(), new AnimatableTransform(), 0, 0, 0, 0, 0, bounds.width(), bounds.height(), null, null, Collections.<Keyframe<Float>>emptyList(), Layer.MatteType.NONE, null, false, null, null); } private static final JsonReader.Options TEXT_NAMES = JsonReader.Options.of( "d", "a" ); private static final JsonReader.Options EFFECTS_NAMES = JsonReader.Options.of( "ty", "nm" ); public static Layer parse(JsonReader reader, LottieComposition composition) throws IOException { // This should always be set by After Effects. However, if somebody wants to minify // and optimize their json, the name isn't critical for most cases so it can be removed. String layerName = "UNSET"; Layer.LayerType layerType = null; String refId = null; long layerId = 0; int solidWidth = 0; int solidHeight = 0; int solidColor = 0; float preCompWidth = 0; float preCompHeight = 0; long parentId = -1; float timeStretch = 1f; float startFrame = 0f; float inFrame = 0f; float outFrame = 0f; String cl = null; boolean hidden = false; BlurEffect blurEffect = null; DropShadowEffect dropShadowEffect = null; Layer.MatteType matteType = Layer.MatteType.NONE; AnimatableTransform transform = null; AnimatableTextFrame text = null; AnimatableTextProperties textProperties = null; AnimatableFloatValue timeRemapping = null; List<Mask> masks = new ArrayList<>(); List<ContentModel> shapes = new ArrayList<>(); reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: layerName = reader.nextString(); break; case 1: layerId = reader.nextInt(); break; case 2: refId = reader.nextString(); break; case 3: int layerTypeInt = reader.nextInt(); if (layerTypeInt < Layer.LayerType.UNKNOWN.ordinal()) { layerType = Layer.LayerType.values()[layerTypeInt]; } else { layerType = Layer.LayerType.UNKNOWN; } break; case 4: parentId = reader.nextInt(); break; case 5: solidWidth = (int) (reader.nextInt() * Utils.dpScale()); break; case 6: solidHeight = (int) (reader.nextInt() * Utils.dpScale()); break; case 7: solidColor = Color.parseColor(reader.nextString()); break; case 8: transform = AnimatableTransformParser.parse(reader, composition); break; case 9: int matteTypeIndex = reader.nextInt(); if (matteTypeIndex >= Layer.MatteType.values().length) { composition.addWarning("Unsupported matte type: " + matteTypeIndex); break; } matteType = Layer.MatteType.values()[matteTypeIndex]; switch (matteType) { case LUMA: composition.addWarning("Unsupported matte type: Luma"); break; case LUMA_INVERTED: composition.addWarning("Unsupported matte type: Luma Inverted"); break; } composition.incrementMatteOrMaskCount(1); break; case 10: reader.beginArray(); while (reader.hasNext()) { masks.add(MaskParser.parse(reader, composition)); } composition.incrementMatteOrMaskCount(masks.size()); reader.endArray(); break; case 11: reader.beginArray(); while (reader.hasNext()) { ContentModel shape = ContentModelParser.parse(reader, composition); if (shape != null) { shapes.add(shape); } } reader.endArray(); break; case 12: reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(TEXT_NAMES)) { case 0: text = AnimatableValueParser.parseDocumentData(reader, composition); break; case 1: reader.beginArray(); if (reader.hasNext()) { textProperties = AnimatableTextPropertiesParser.parse(reader, composition); } while (reader.hasNext()) { reader.skipValue(); } reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 13: reader.beginArray(); List<String> effectNames = new ArrayList<>(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(EFFECTS_NAMES)) { case 0: int type = reader.nextInt(); if (type == 29) { blurEffect = BlurEffectParser.parse(reader, composition); } else if (type == 25) { dropShadowEffect = new DropShadowEffectParser().parse(reader, composition); } break; case 1: String effectName = reader.nextString(); effectNames.add(effectName); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); } reader.endArray(); composition.addWarning("Lottie doesn't support layer effects. If you are using them for " + " fills, strokes, trim paths etc. then try adding them directly as contents " + " in your shape. Found: " + effectNames); break; case 14: timeStretch = (float) reader.nextDouble(); break; case 15: startFrame = (float) reader.nextDouble(); break; case 16: preCompWidth = (float) (reader.nextDouble() * Utils.dpScale()); break; case 17: preCompHeight = (float) (reader.nextDouble() * Utils.dpScale()); break; case 18: inFrame = (float) reader.nextDouble(); break; case 19: outFrame = (float) reader.nextDouble(); break; case 20: timeRemapping = AnimatableValueParser.parseFloat(reader, composition, false); break; case 21: cl = reader.nextString(); break; case 22: hidden = reader.nextBoolean(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); List<Keyframe<Float>> inOutKeyframes = new ArrayList<>(); // Before the in frame if (inFrame > 0) { Keyframe<Float> preKeyframe = new Keyframe<>(composition, 0f, 0f, null, 0f, inFrame); inOutKeyframes.add(preKeyframe); } // The + 1 is because the animation should be visible on the out frame itself. outFrame = (outFrame > 0 ? outFrame : composition.getEndFrame()); Keyframe<Float> visibleKeyframe = new Keyframe<>(composition, 1f, 1f, null, inFrame, outFrame); inOutKeyframes.add(visibleKeyframe); Keyframe<Float> outKeyframe = new Keyframe<>( composition, 0f, 0f, null, outFrame, Float.MAX_VALUE); inOutKeyframes.add(outKeyframe); if (layerName.endsWith(".ai") || "ai".equals(cl)) { composition.addWarning("Convert your Illustrator layers to shape layers."); } return new Layer(shapes, composition, layerName, layerId, layerType, parentId, refId, masks, transform, solidWidth, solidHeight, solidColor, timeStretch, startFrame, preCompWidth, preCompHeight, text, textProperties, inOutKeyframes, matteType, timeRemapping, hidden, blurEffect, dropShadowEffect); } }
2,508
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ScaleXYParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.ScaleXY; import java.io.IOException; public class ScaleXYParser implements ValueParser<ScaleXY> { public static final ScaleXYParser INSTANCE = new ScaleXYParser(); private ScaleXYParser() { } @Override public ScaleXY parse(JsonReader reader, float scale) throws IOException { boolean isArray = reader.peek() == JsonReader.Token.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } float sx = (float) reader.nextDouble(); float sy = (float) reader.nextDouble(); while (reader.hasNext()) { reader.skipValue(); } if (isArray) { reader.endArray(); } return new ScaleXY(sx / 100f * scale, sy / 100f * scale); } }
2,509
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapeDataParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.model.CubicCurveData; import com.airbnb.lottie.model.content.ShapeData; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.MiscUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ShapeDataParser implements ValueParser<ShapeData> { public static final ShapeDataParser INSTANCE = new ShapeDataParser(); private static final JsonReader.Options NAMES = JsonReader.Options.of( "c", "v", "i", "o" ); private ShapeDataParser() { } @Override public ShapeData parse(JsonReader reader, float scale) throws IOException { // Sometimes the points data is in a array of length 1. Sometimes the data is at the top // level. if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray(); } boolean closed = false; List<PointF> pointsArray = null; List<PointF> inTangents = null; List<PointF> outTangents = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: closed = reader.nextBoolean(); break; case 1: pointsArray = JsonUtils.jsonToPoints(reader, scale); break; case 2: inTangents = JsonUtils.jsonToPoints(reader, scale); break; case 3: outTangents = JsonUtils.jsonToPoints(reader, scale); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (reader.peek() == JsonReader.Token.END_ARRAY) { reader.endArray(); } if (pointsArray == null || inTangents == null || outTangents == null) { throw new IllegalArgumentException("Shape data was missing information."); } if (pointsArray.isEmpty()) { return new ShapeData(new PointF(), false, Collections.<CubicCurveData>emptyList()); } int length = pointsArray.size(); PointF vertex = pointsArray.get(0); PointF initialPoint = vertex; List<CubicCurveData> curves = new ArrayList<>(length); for (int i = 1; i < length; i++) { vertex = pointsArray.get(i); PointF previousVertex = pointsArray.get(i - 1); PointF cp1 = outTangents.get(i - 1); PointF cp2 = inTangents.get(i); PointF shapeCp1 = MiscUtils.addPoints(previousVertex, cp1); PointF shapeCp2 = MiscUtils.addPoints(vertex, cp2); curves.add(new CubicCurveData(shapeCp1, shapeCp2, vertex)); } if (closed) { vertex = pointsArray.get(0); PointF previousVertex = pointsArray.get(length - 1); PointF cp1 = outTangents.get(length - 1); PointF cp2 = inTangents.get(0); PointF shapeCp1 = MiscUtils.addPoints(previousVertex, cp1); PointF shapeCp2 = MiscUtils.addPoints(vertex, cp2); curves.add(new CubicCurveData(shapeCp1, shapeCp2, vertex)); } return new ShapeData(initialPoint, closed, curves); } }
2,510
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/AnimatableValueParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.animatable.AnimatableScaleValue; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; import com.airbnb.lottie.model.animatable.AnimatableTextFrame; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.List; public class AnimatableValueParser { private AnimatableValueParser() { } public static AnimatableFloatValue parseFloat( JsonReader reader, LottieComposition composition) throws IOException { return parseFloat(reader, composition, true); } public static AnimatableFloatValue parseFloat( JsonReader reader, LottieComposition composition, boolean isDp) throws IOException { return new AnimatableFloatValue( parse(reader, isDp ? Utils.dpScale() : 1f, composition, FloatParser.INSTANCE)); } static AnimatableIntegerValue parseInteger( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableIntegerValue(parse(reader, composition, IntegerParser.INSTANCE)); } static AnimatablePointValue parsePoint( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatablePointValue(KeyframesParser.parse(reader, composition, Utils.dpScale(), PointFParser.INSTANCE, true)); } static AnimatableScaleValue parseScale( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableScaleValue(parse(reader, composition, ScaleXYParser.INSTANCE)); } static AnimatableShapeValue parseShapeData( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableShapeValue( parse(reader, Utils.dpScale(), composition, ShapeDataParser.INSTANCE)); } static AnimatableTextFrame parseDocumentData( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableTextFrame(parse(reader, Utils.dpScale(), composition, DocumentDataParser.INSTANCE)); } static AnimatableColorValue parseColor( JsonReader reader, LottieComposition composition) throws IOException { return new AnimatableColorValue(parse(reader, composition, ColorParser.INSTANCE)); } static AnimatableGradientColorValue parseGradientColor( JsonReader reader, LottieComposition composition, int points) throws IOException { AnimatableGradientColorValue animatableGradientColorValue = new AnimatableGradientColorValue( parse(reader, composition, new GradientColorParser(points))); return animatableGradientColorValue; } /** * Will return null if the animation can't be played such as if it has expressions. */ private static <T> List<Keyframe<T>> parse(JsonReader reader, LottieComposition composition, ValueParser<T> valueParser) throws IOException { return KeyframesParser.parse(reader, composition, 1, valueParser, false); } /** * Will return null if the animation can't be played such as if it has expressions. */ private static <T> List<Keyframe<T>> parse( JsonReader reader, float scale, LottieComposition composition, ValueParser<T> valueParser) throws IOException { return KeyframesParser.parse(reader, composition, scale, valueParser, false); } }
2,511
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/FontCharacterParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.FontCharacter; import com.airbnb.lottie.model.content.ShapeGroup; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; class FontCharacterParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "ch", "size", "w", "style", "fFamily", "data" ); private static final JsonReader.Options DATA_NAMES = JsonReader.Options.of("shapes"); private FontCharacterParser() { } static FontCharacter parse( JsonReader reader, LottieComposition composition) throws IOException { char character = '\0'; double size = 0; double width = 0; String style = null; String fontFamily = null; List<ShapeGroup> shapes = new ArrayList<>(); reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: character = reader.nextString().charAt(0); break; case 1: size = reader.nextDouble(); break; case 2: width = reader.nextDouble(); break; case 3: style = reader.nextString(); break; case 4: fontFamily = reader.nextString(); break; case 5: reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(DATA_NAMES)) { case 0: reader.beginArray(); while (reader.hasNext()) { shapes.add((ShapeGroup) ContentModelParser.parse(reader, composition)); } reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return new FontCharacter(shapes, character, size, width, style, fontFamily); } }
2,512
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/RoundedCornersParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.content.RectangleShape; import com.airbnb.lottie.model.content.RoundedCorners; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class RoundedCornersParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", // 0 "r", // 1 "hd" // 1 ); private RoundedCornersParser() { } @Nullable static RoundedCorners parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableValue<Float, Float> cornerRadius = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: //nm name = reader.nextString(); break; case 1: // r cornerRadius = AnimatableValueParser.parseFloat(reader, composition, true); break; case 2: // hd hidden = reader.nextBoolean(); break; default: reader.skipValue(); } } return hidden ? null : new RoundedCorners(name, cornerRadius); } }
2,513
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/KeyframesParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.animation.keyframe.PathKeyframe; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.List; class KeyframesParser { static JsonReader.Options NAMES = JsonReader.Options.of("k"); private KeyframesParser() { } static <T> List<Keyframe<T>> parse(JsonReader reader, LottieComposition composition, float scale, ValueParser<T> valueParser, boolean multiDimensional) throws IOException { List<Keyframe<T>> keyframes = new ArrayList<>(); if (reader.peek() == JsonReader.Token.STRING) { composition.addWarning("Lottie doesn't support expressions."); return keyframes; } reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray(); if (reader.peek() == JsonReader.Token.NUMBER) { // For properties in which the static value is an array of numbers. keyframes.add(KeyframeParser.parse(reader, composition, scale, valueParser, false, multiDimensional)); } else { while (reader.hasNext()) { keyframes.add(KeyframeParser.parse(reader, composition, scale, valueParser, true, multiDimensional)); } } reader.endArray(); } else { keyframes.add(KeyframeParser.parse(reader, composition, scale, valueParser, false, multiDimensional)); } break; default: reader.skipValue(); } } reader.endObject(); setEndFrames(keyframes); return keyframes; } /** * The json doesn't include end frames. The data can be taken from the start frame of the next * keyframe though. */ public static <T> void setEndFrames(List<? extends Keyframe<T>> keyframes) { int size = keyframes.size(); for (int i = 0; i < size - 1; i++) { // In the json, the keyframes only contain their starting frame. Keyframe<T> keyframe = keyframes.get(i); Keyframe<T> nextKeyframe = keyframes.get(i + 1); keyframe.endFrame = nextKeyframe.startFrame; if (keyframe.endValue == null && nextKeyframe.startValue != null) { keyframe.endValue = nextKeyframe.startValue; if (keyframe instanceof PathKeyframe) { ((PathKeyframe) keyframe).createPath(); } } } Keyframe<?> lastKeyframe = keyframes.get(size - 1); if ((lastKeyframe.startValue == null || lastKeyframe.endValue == null) && keyframes.size() > 1) { // The only purpose the last keyframe has is to provide the end frame of the previous // keyframe. keyframes.remove(lastKeyframe); } } }
2,514
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/BlurEffectParser.java
package com.airbnb.lottie.parser; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.content.BlurEffect; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class BlurEffectParser { private static final JsonReader.Options BLUR_EFFECT_NAMES = JsonReader.Options.of( "ef" ); private static final JsonReader.Options INNER_BLUR_EFFECT_NAMES = JsonReader.Options.of( "ty", "v" ); @Nullable static BlurEffect parse(JsonReader reader, LottieComposition composition) throws IOException { BlurEffect blurEffect = null; while (reader.hasNext()) { switch (reader.selectName(BLUR_EFFECT_NAMES)) { case 0: reader.beginArray(); while (reader.hasNext()) { BlurEffect be = maybeParseInnerEffect(reader, composition); if (be != null) { blurEffect = be; } } reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } return blurEffect; } @Nullable private static BlurEffect maybeParseInnerEffect(JsonReader reader, LottieComposition composition) throws IOException { BlurEffect blurEffect = null; boolean isCorrectType = false; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(INNER_BLUR_EFFECT_NAMES)) { case 0: isCorrectType = reader.nextInt() == 0; break; case 1: if (isCorrectType) { blurEffect = new BlurEffect(AnimatableValueParser.parseFloat(reader, composition)); } else { reader.skipValue(); } break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return blurEffect; } }
2,515
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/PathKeyframeParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.animation.keyframe.PathKeyframe; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; class PathKeyframeParser { private PathKeyframeParser() { } static PathKeyframe parse( JsonReader reader, LottieComposition composition) throws IOException { boolean animated = reader.peek() == JsonReader.Token.BEGIN_OBJECT; Keyframe<PointF> keyframe = KeyframeParser.parse( reader, composition, Utils.dpScale(), PathParser.INSTANCE, animated, false); return new PathKeyframe(composition, keyframe); } }
2,516
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/DropShadowEffect.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; public class DropShadowEffect { private final AnimatableColorValue color; private final AnimatableFloatValue opacity; private final AnimatableFloatValue direction; private final AnimatableFloatValue distance; private final AnimatableFloatValue radius; DropShadowEffect(AnimatableColorValue color, AnimatableFloatValue opacity, AnimatableFloatValue direction, AnimatableFloatValue distance, AnimatableFloatValue radius) { this.color = color; this.opacity = opacity; this.direction = direction; this.distance = distance; this.radius = radius; } public AnimatableColorValue getColor() { return color; } public AnimatableFloatValue getOpacity() { return opacity; } public AnimatableFloatValue getDirection() { return direction; } public AnimatableFloatValue getDistance() { return distance; } public AnimatableFloatValue getRadius() { return radius; } }
2,517
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/AnimatableTransformParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePathValue; import com.airbnb.lottie.model.animatable.AnimatableScaleValue; import com.airbnb.lottie.model.animatable.AnimatableSplitDimensionPathValue; import com.airbnb.lottie.model.animatable.AnimatableTransform; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; public class AnimatableTransformParser { private AnimatableTransformParser() { } private static final JsonReader.Options NAMES = JsonReader.Options.of( "a", // 1 "p", // 2 "s", // 3 "rz", // 4 "r", // 5 "o", // 6 "so", // 7 "eo", // 8 "sk", // 9 "sa" // 10 ); private static final JsonReader.Options ANIMATABLE_NAMES = JsonReader.Options.of("k"); public static AnimatableTransform parse( JsonReader reader, LottieComposition composition) throws IOException { AnimatablePathValue anchorPoint = null; AnimatableValue<PointF, PointF> position = null; AnimatableScaleValue scale = null; AnimatableFloatValue rotation = null; AnimatableIntegerValue opacity = null; AnimatableFloatValue startOpacity = null; AnimatableFloatValue endOpacity = null; AnimatableFloatValue skew = null; AnimatableFloatValue skewAngle = null; boolean isObject = reader.peek() == JsonReader.Token.BEGIN_OBJECT; if (isObject) { reader.beginObject(); } while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: // a reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(ANIMATABLE_NAMES)) { case 0: anchorPoint = AnimatablePathValueParser.parse(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 1: // p position = AnimatablePathValueParser.parseSplitPath(reader, composition); break; case 2: // s scale = AnimatableValueParser.parseScale(reader, composition); break; case 3: // rz composition.addWarning("Lottie doesn't support 3D layers."); case 4: // r /* * Sometimes split path rotation gets exported like: * "rz": { * "a": 1, * "k": [ * {} * ] * }, * which doesn't parse to a real keyframe. */ rotation = AnimatableValueParser.parseFloat(reader, composition, false); if (rotation.getKeyframes().isEmpty()) { rotation.getKeyframes().add(new Keyframe<>(composition, 0f, 0f, null, 0f, composition.getEndFrame())); } else if (rotation.getKeyframes().get(0).startValue == null) { rotation.getKeyframes().set(0, new Keyframe<>(composition, 0f, 0f, null, 0f, composition.getEndFrame())); } break; case 5: // o opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 6: // so startOpacity = AnimatableValueParser.parseFloat(reader, composition, false); break; case 7: // eo endOpacity = AnimatableValueParser.parseFloat(reader, composition, false); break; case 8: // sk skew = AnimatableValueParser.parseFloat(reader, composition, false); break; case 9: // sa skewAngle = AnimatableValueParser.parseFloat(reader, composition, false); break; default: reader.skipName(); reader.skipValue(); } } if (isObject) { reader.endObject(); } if (isAnchorPointIdentity(anchorPoint)) { anchorPoint = null; } if (isPositionIdentity(position)) { position = null; } if (isRotationIdentity(rotation)) { rotation = null; } if (isScaleIdentity(scale)) { scale = null; } if (isSkewIdentity(skew)) { skew = null; } if (isSkewAngleIdentity(skewAngle)) { skewAngle = null; } return new AnimatableTransform(anchorPoint, position, scale, rotation, opacity, startOpacity, endOpacity, skew, skewAngle); } private static boolean isAnchorPointIdentity(AnimatablePathValue anchorPoint) { return anchorPoint == null || (anchorPoint.isStatic() && anchorPoint.getKeyframes().get(0).startValue.equals(0f, 0f)); } private static boolean isPositionIdentity(AnimatableValue<PointF, PointF> position) { return position == null || ( !(position instanceof AnimatableSplitDimensionPathValue) && position.isStatic() && position.getKeyframes().get(0).startValue.equals(0f, 0f)); } private static boolean isRotationIdentity(AnimatableFloatValue rotation) { return rotation == null || (rotation.isStatic() && rotation.getKeyframes().get(0).startValue == 0f); } private static boolean isScaleIdentity(AnimatableScaleValue scale) { return scale == null || (scale.isStatic() && scale.getKeyframes().get(0).startValue.equals(1f, 1f)); } private static boolean isSkewIdentity(AnimatableFloatValue skew) { return skew == null || (skew.isStatic() && skew.getKeyframes().get(0).startValue == 0f); } private static boolean isSkewAngleIdentity(AnimatableFloatValue skewAngle) { return skewAngle == null || (skewAngle.isStatic() && skewAngle.getKeyframes().get(0).startValue == 0f); } }
2,518
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ContentModelParser.java
package com.airbnb.lottie.parser; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.content.ContentModel; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Logger; import java.io.IOException; class ContentModelParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "ty", "d" ); private ContentModelParser() { } @Nullable static ContentModel parse(JsonReader reader, LottieComposition composition) throws IOException { String type = null; reader.beginObject(); // Unfortunately, for an ellipse, d is before "ty" which means that it will get parsed // before we are in the ellipse parser. // "d" is 2 for normal and 3 for reversed. int d = 2; typeLoop: while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: type = reader.nextString(); break typeLoop; case 1: d = reader.nextInt(); break; default: reader.skipName(); reader.skipValue(); } } if (type == null) { return null; } ContentModel model = null; switch (type) { case "gr": model = ShapeGroupParser.parse(reader, composition); break; case "st": model = ShapeStrokeParser.parse(reader, composition); break; case "gs": model = GradientStrokeParser.parse(reader, composition); break; case "fl": model = ShapeFillParser.parse(reader, composition); break; case "gf": model = GradientFillParser.parse(reader, composition); break; case "tr": model = AnimatableTransformParser.parse(reader, composition); break; case "sh": model = ShapePathParser.parse(reader, composition); break; case "el": model = CircleShapeParser.parse(reader, composition, d); break; case "rc": model = RectangleShapeParser.parse(reader, composition); break; case "tm": model = ShapeTrimPathParser.parse(reader, composition); break; case "sr": model = PolystarShapeParser.parse(reader, composition, d); break; case "mm": model = MergePathsParser.parse(reader); composition.addWarning("Animation contains merge paths. Merge paths are only " + "supported on KitKat+ and must be manually enabled by calling " + "enableMergePathsForKitKatAndAbove()."); break; case "rp": model = RepeaterParser.parse(reader, composition); break; case "rd": model = RoundedCornersParser.parse(reader, composition); break; default: Logger.warning("Unknown shape type " + type); } while (reader.hasNext()) { reader.skipValue(); } reader.endObject(); return model; } }
2,519
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapeStrokeParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.content.ShapeStroke; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; class ShapeStrokeParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "c", "w", "o", "lc", "lj", "ml", "hd", "d" ); private static final JsonReader.Options DASH_PATTERN_NAMES = JsonReader.Options.of( "n", "v" ); private ShapeStrokeParser() { } static ShapeStroke parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableColorValue color = null; AnimatableFloatValue width = null; AnimatableIntegerValue opacity = null; ShapeStroke.LineCapType capType = null; ShapeStroke.LineJoinType joinType = null; AnimatableFloatValue offset = null; float miterLimit = 0f; boolean hidden = false; List<AnimatableFloatValue> lineDashPattern = new ArrayList<>(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: color = AnimatableValueParser.parseColor(reader, composition); break; case 2: width = AnimatableValueParser.parseFloat(reader, composition); break; case 3: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 4: capType = ShapeStroke.LineCapType.values()[reader.nextInt() - 1]; break; case 5: joinType = ShapeStroke.LineJoinType.values()[reader.nextInt() - 1]; break; case 6: miterLimit = (float) reader.nextDouble(); break; case 7: hidden = reader.nextBoolean(); break; case 8: reader.beginArray(); while (reader.hasNext()) { String n = null; AnimatableFloatValue val = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(DASH_PATTERN_NAMES)) { case 0: n = reader.nextString(); break; case 1: val = AnimatableValueParser.parseFloat(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); switch (n) { case "o": offset = val; break; case "d": case "g": composition.setHasDashPattern(true); lineDashPattern.add(val); break; } } reader.endArray(); if (lineDashPattern.size() == 1) { // If there is only 1 value then it is assumed to be equal parts on and off. lineDashPattern.add(lineDashPattern.get(0)); } break; default: reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; // Unclear why these are omitted sometimes but default to After Effects default value // https://github.com/airbnb/lottie-android/issues/2325 capType = capType == null ? ShapeStroke.LineCapType.BUTT : capType; joinType = joinType == null ? ShapeStroke.LineJoinType.MITER : joinType; return new ShapeStroke( name, offset, lineDashPattern, color, opacity, width, capType, joinType, miterLimit, hidden); } }
2,520
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapePathParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; import com.airbnb.lottie.model.content.ShapePath; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class ShapePathParser { static JsonReader.Options NAMES = JsonReader.Options.of( "nm", "ind", "ks", "hd" ); private ShapePathParser() { } static ShapePath parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; int ind = 0; AnimatableShapeValue shape = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: ind = reader.nextInt(); break; case 2: shape = AnimatableValueParser.parseShapeData(reader, composition); break; case 3: hidden = reader.nextBoolean(); break; default: reader.skipValue(); } } return new ShapePath(name, ind, shape, hidden); } }
2,521
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/GradientStrokeParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.content.GradientStroke; import com.airbnb.lottie.model.content.GradientType; import com.airbnb.lottie.model.content.ShapeStroke; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; class GradientStrokeParser { private GradientStrokeParser() { } private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "g", "o", "t", "s", "e", "w", "lc", "lj", "ml", "hd", "d" ); private static final JsonReader.Options GRADIENT_NAMES = JsonReader.Options.of( "p", "k" ); private static final JsonReader.Options DASH_PATTERN_NAMES = JsonReader.Options.of( "n", "v" ); static GradientStroke parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableGradientColorValue color = null; AnimatableIntegerValue opacity = null; GradientType gradientType = null; AnimatablePointValue startPoint = null; AnimatablePointValue endPoint = null; AnimatableFloatValue width = null; ShapeStroke.LineCapType capType = null; ShapeStroke.LineJoinType joinType = null; AnimatableFloatValue offset = null; float miterLimit = 0f; boolean hidden = false; List<AnimatableFloatValue> lineDashPattern = new ArrayList<>(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: int points = -1; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(GRADIENT_NAMES)) { case 0: points = reader.nextInt(); break; case 1: color = AnimatableValueParser.parseGradientColor(reader, composition, points); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 2: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 3: gradientType = reader.nextInt() == 1 ? GradientType.LINEAR : GradientType.RADIAL; break; case 4: startPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 5: endPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 6: width = AnimatableValueParser.parseFloat(reader, composition); break; case 7: capType = ShapeStroke.LineCapType.values()[reader.nextInt() - 1]; break; case 8: joinType = ShapeStroke.LineJoinType.values()[reader.nextInt() - 1]; break; case 9: miterLimit = (float) reader.nextDouble(); break; case 10: hidden = reader.nextBoolean(); break; case 11: reader.beginArray(); while (reader.hasNext()) { String n = null; AnimatableFloatValue val = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(DASH_PATTERN_NAMES)) { case 0: n = reader.nextString(); break; case 1: val = AnimatableValueParser.parseFloat(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (n.equals("o")) { offset = val; } else if (n.equals("d") || n.equals("g")) { composition.setHasDashPattern(true); lineDashPattern.add(val); } } reader.endArray(); if (lineDashPattern.size() == 1) { // If there is only 1 value then it is assumed to be equal parts on and off. lineDashPattern.add(lineDashPattern.get(0)); } break; default: reader.skipName(); reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; return new GradientStroke( name, gradientType, color, opacity, startPoint, endPoint, width, capType, joinType, miterLimit, lineDashPattern, offset, hidden); } }
2,522
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/MergePathsParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.model.content.MergePaths; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class MergePathsParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "mm", "hd" ); private MergePathsParser() { } static MergePaths parse(JsonReader reader) throws IOException { String name = null; MergePaths.MergePathsMode mode = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: mode = MergePaths.MergePathsMode.forId(reader.nextInt()); break; case 2: hidden = reader.nextBoolean(); break; default: reader.skipName(); reader.skipValue(); } } return new MergePaths(name, mode, hidden); } }
2,523
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/PathParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class PathParser implements ValueParser<PointF> { public static final PathParser INSTANCE = new PathParser(); private PathParser() { } @Override public PointF parse(JsonReader reader, float scale) throws IOException { return JsonUtils.jsonToPoint(reader, scale); } }
2,524
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/PointFParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class PointFParser implements ValueParser<PointF> { public static final PointFParser INSTANCE = new PointFParser(); private PointFParser() { } @Override public PointF parse(JsonReader reader, float scale) throws IOException { JsonReader.Token token = reader.peek(); if (token == JsonReader.Token.BEGIN_ARRAY) { return JsonUtils.jsonToPoint(reader, scale); } else if (token == JsonReader.Token.BEGIN_OBJECT) { return JsonUtils.jsonToPoint(reader, scale); } else if (token == JsonReader.Token.NUMBER) { // This is the case where the static value for a property is an array of numbers. // We begin the array to see if we have an array of keyframes but it's just an array // of static numbers instead. PointF point = new PointF((float) reader.nextDouble() * scale, (float) reader.nextDouble() * scale); while (reader.hasNext()) { reader.skipValue(); } return point; } else { throw new IllegalArgumentException("Cannot convert json to point. Next token is " + token); } } }
2,525
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/AnimatablePathValueParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatablePathValue; import com.airbnb.lottie.model.animatable.AnimatableSplitDimensionPathValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class AnimatablePathValueParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "k", "x", "y" ); private AnimatablePathValueParser() { } public static AnimatablePathValue parse( JsonReader reader, LottieComposition composition) throws IOException { List<Keyframe<PointF>> keyframes = new ArrayList<>(); if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray(); while (reader.hasNext()) { keyframes.add(PathKeyframeParser.parse(reader, composition)); } reader.endArray(); KeyframesParser.setEndFrames(keyframes); } else { keyframes.add(new Keyframe<>(JsonUtils.jsonToPoint(reader, Utils.dpScale()))); } return new AnimatablePathValue(keyframes); } /** * Returns either an {@link AnimatablePathValue} or an {@link AnimatableSplitDimensionPathValue}. */ static AnimatableValue<PointF, PointF> parseSplitPath( JsonReader reader, LottieComposition composition) throws IOException { AnimatablePathValue pathAnimation = null; AnimatableFloatValue xAnimation = null; AnimatableFloatValue yAnimation = null; boolean hasExpressions = false; reader.beginObject(); while (reader.peek() != JsonReader.Token.END_OBJECT) { switch (reader.selectName(NAMES)) { case 0: pathAnimation = AnimatablePathValueParser.parse(reader, composition); break; case 1: if (reader.peek() == JsonReader.Token.STRING) { hasExpressions = true; reader.skipValue(); } else { xAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; case 2: if (reader.peek() == JsonReader.Token.STRING) { hasExpressions = true; reader.skipValue(); } else { yAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (hasExpressions) { composition.addWarning("Lottie doesn't support expressions."); } if (pathAnimation != null) { return pathAnimation; } return new AnimatableSplitDimensionPathValue(xAnimation, yAnimation); } }
2,526
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/RepeaterParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableTransform; import com.airbnb.lottie.model.content.Repeater; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class RepeaterParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "c", "o", "tr", "hd" ); private RepeaterParser() { } static Repeater parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableFloatValue copies = null; AnimatableFloatValue offset = null; AnimatableTransform transform = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: copies = AnimatableValueParser.parseFloat(reader, composition, false); break; case 2: offset = AnimatableValueParser.parseFloat(reader, composition, false); break; case 3: transform = AnimatableTransformParser.parse(reader, composition); break; case 4: hidden = reader.nextBoolean(); break; default: reader.skipValue(); } } return new Repeater(name, copies, offset, transform, hidden); } }
2,527
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/GradientFillParser.java
package com.airbnb.lottie.parser; import android.graphics.Path; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.content.GradientFill; import com.airbnb.lottie.model.content.GradientType; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.Collections; class GradientFillParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "g", "o", "t", "s", "e", "r", "hd" ); private static final JsonReader.Options GRADIENT_NAMES = JsonReader.Options.of( "p", "k" ); private GradientFillParser() { } static GradientFill parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableGradientColorValue color = null; AnimatableIntegerValue opacity = null; GradientType gradientType = null; AnimatablePointValue startPoint = null; AnimatablePointValue endPoint = null; Path.FillType fillType = Path.FillType.WINDING; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: int points = -1; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(GRADIENT_NAMES)) { case 0: points = reader.nextInt(); break; case 1: color = AnimatableValueParser.parseGradientColor(reader, composition, points); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); break; case 2: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 3: gradientType = reader.nextInt() == 1 ? GradientType.LINEAR : GradientType.RADIAL; break; case 4: startPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 5: endPoint = AnimatableValueParser.parsePoint(reader, composition); break; case 6: fillType = reader.nextInt() == 1 ? Path.FillType.WINDING : Path.FillType.EVEN_ODD; break; case 7: hidden = reader.nextBoolean(); break; default: reader.skipName(); reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; return new GradientFill( name, gradientType, fillType, color, opacity, startPoint, endPoint, null, null, hidden); } }
2,528
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ColorParser.java
package com.airbnb.lottie.parser; import android.graphics.Color; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class ColorParser implements ValueParser<Integer> { public static final ColorParser INSTANCE = new ColorParser(); private ColorParser() { } @Override public Integer parse(JsonReader reader, float scale) throws IOException { boolean isArray = reader.peek() == JsonReader.Token.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } double r = reader.nextDouble(); double g = reader.nextDouble(); double b = reader.nextDouble(); double a = 1; // Sometimes, Lottie editors only export rgb instead of rgba. // https://github.com/airbnb/lottie-android/issues/1601 if (reader.peek() == JsonReader.Token.NUMBER) { a = reader.nextDouble(); } if (isArray) { reader.endArray(); } if (r <= 1 && g <= 1 && b <= 1) { r *= 255; g *= 255; b *= 255; // It appears as if sometimes, Telegram Lottie stickers are exported with rgb [0,1] and a [0,255]. // This shouldn't happen but we can gracefully handle it when it does. // https://github.com/airbnb/lottie-android/issues/1478 if (a <= 1) { a *= 255; } } return Color.argb((int) a, (int) r, (int) g, (int) b); } }
2,529
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ValueParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; interface ValueParser<V> { V parse(JsonReader reader, float scale) throws IOException; }
2,530
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/FontParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.model.Font; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class FontParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "fFamily", "fName", "fStyle", "ascent" ); private FontParser() { } static Font parse(JsonReader reader) throws IOException { String family = null; String name = null; String style = null; float ascent = 0; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: family = reader.nextString(); break; case 1: name = reader.nextString(); break; case 2: style = reader.nextString(); break; case 3: ascent = (float) reader.nextDouble(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return new Font(family, name, style, ascent); } }
2,531
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapeFillParser.java
package com.airbnb.lottie.parser; import android.graphics.Path; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.content.ShapeFill; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.util.Collections; class ShapeFillParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "c", "o", "fillEnabled", "r", "hd" ); private ShapeFillParser() { } static ShapeFill parse( JsonReader reader, LottieComposition composition) throws IOException { AnimatableColorValue color = null; boolean fillEnabled = false; AnimatableIntegerValue opacity = null; String name = null; int fillTypeInt = 1; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: color = AnimatableValueParser.parseColor(reader, composition); break; case 2: opacity = AnimatableValueParser.parseInteger(reader, composition); break; case 3: fillEnabled = reader.nextBoolean(); break; case 4: fillTypeInt = reader.nextInt(); break; case 5: hidden = reader.nextBoolean(); break; default: reader.skipName(); reader.skipValue(); } } // Telegram sometimes omits opacity. // https://github.com/airbnb/lottie-android/issues/1600 opacity = opacity == null ? new AnimatableIntegerValue(Collections.singletonList(new Keyframe<>(100))) : opacity; Path.FillType fillType = fillTypeInt == 1 ? Path.FillType.WINDING : Path.FillType.EVEN_ODD; return new ShapeFill(name, fillEnabled, fillType, color, opacity, hidden); } }
2,532
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/GradientColorParser.java
package com.airbnb.lottie.parser; import android.graphics.Color; import com.airbnb.lottie.model.content.GradientColor; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.GammaEvaluator; import com.airbnb.lottie.utils.MiscUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GradientColorParser implements com.airbnb.lottie.parser.ValueParser<GradientColor> { /** * The number of colors if it exists in the json or -1 if it doesn't (legacy bodymovin) */ private int colorPoints; public GradientColorParser(int colorPoints) { this.colorPoints = colorPoints; } /** * Both the color stops and opacity stops are in the same array. * There are {@link #colorPoints} colors sequentially as: * [ * ..., * position, * red, * green, * blue, * ... * ] * <p> * The remainder of the array is the opacity stops sequentially as: * [ * ..., * position, * opacity, * ... * ] */ @Override public GradientColor parse(JsonReader reader, float scale) throws IOException { List<Float> array = new ArrayList<>(); // The array was started by Keyframe because it thought that this may be an array of keyframes // but peek returned a number so it considered it a static array of numbers. boolean isArray = reader.peek() == JsonReader.Token.BEGIN_ARRAY; if (isArray) { reader.beginArray(); } while (reader.hasNext()) { array.add((float) reader.nextDouble()); } if (array.size() == 4 && array.get(0) == 1f) { // If a gradient color only contains one color at position 1, add a second stop with the same // color at position 0. Android's LinearGradient shader requires at least two colors. // https://github.com/airbnb/lottie-android/issues/1967 array.set(0, 0f); array.add(1f); array.add(array.get(1)); array.add(array.get(2)); array.add(array.get(3)); colorPoints = 2; } if (isArray) { reader.endArray(); } if (colorPoints == -1) { colorPoints = array.size() / 4; } float[] positions = new float[colorPoints]; int[] colors = new int[colorPoints]; int r = 0; int g = 0; for (int i = 0; i < colorPoints * 4; i++) { int colorIndex = i / 4; double value = array.get(i); switch (i % 4) { case 0: // Positions should monotonically increase. If they don't, it can cause rendering problems on some phones. // https://github.com/airbnb/lottie-android/issues/1675 if (colorIndex > 0 && positions[colorIndex - 1] >= (float) value) { positions[colorIndex] = (float) value + 0.01f; } else { positions[colorIndex] = (float) value; } break; case 1: r = (int) (value * 255); break; case 2: g = (int) (value * 255); break; case 3: int b = (int) (value * 255); colors[colorIndex] = Color.argb(255, r, g, b); break; } } GradientColor gradientColor = new GradientColor(positions, colors); gradientColor = addOpacityStopsToGradientIfNeeded(gradientColor, array); return gradientColor; } /** * This cheats a little bit. * Opacity stops can be at arbitrary intervals independent of color stops. * This uses the existing color stops and modifies the opacity at each existing color stop * based on what the opacity would be. * <p> * This should be a good approximation is nearly all cases. However, if there are many more * opacity stops than color stops, information will be lost. */ private GradientColor addOpacityStopsToGradientIfNeeded(GradientColor gradientColor, List<Float> array) { int startIndex = colorPoints * 4; if (array.size() <= startIndex) { return gradientColor; } // When there are opacity stops, we create a merged list of color stops and opacity stops. // For a given color stop, we linearly interpolate the opacity for the two opacity stops around it. // For a given opacity stop, we linearly interpolate the color for the two color stops around it. float[] colorStopPositions = gradientColor.getPositions(); int[] colorStopColors = gradientColor.getColors(); int opacityStops = (array.size() - startIndex) / 2; float[] opacityStopPositions = new float[opacityStops]; float[] opacityStopOpacities = new float[opacityStops]; for (int i = startIndex, j = 0; i < array.size(); i++) { if (i % 2 == 0) { opacityStopPositions[j] = array.get(i); } else { opacityStopOpacities[j] = array.get(i); j++; } } // Pre-SKIA (Oreo) devices render artifacts when there is two stops in the same position. // As a result, we have to de-dupe the merge color and opacity stop positions. float[] newPositions = mergeUniqueElements(gradientColor.getPositions(), opacityStopPositions); int newColorPoints = newPositions.length; int[] newColors = new int[newColorPoints]; for (int i = 0; i < newColorPoints; i++) { float position = newPositions[i]; int colorStopIndex = Arrays.binarySearch(colorStopPositions, position); int opacityIndex = Arrays.binarySearch(opacityStopPositions, position); if (colorStopIndex < 0 || opacityIndex > 0) { // This is a stop derived from an opacity stop. if (opacityIndex < 0) { // The formula here is derived from the return value for binarySearch. When an item isn't found, it returns -insertionPoint - 1. opacityIndex = -(opacityIndex + 1); } newColors[i] = getColorInBetweenColorStops(position, opacityStopOpacities[opacityIndex], colorStopPositions, colorStopColors); } else { // This os a step derived from a color stop. newColors[i] = getColorInBetweenOpacityStops(position, colorStopColors[colorStopIndex], opacityStopPositions, opacityStopOpacities); } } return new GradientColor(newPositions, newColors); } int getColorInBetweenColorStops(float position, float opacity, float[] colorStopPositions, int[] colorStopColors) { if (colorStopColors.length < 2 || position == colorStopPositions[0]) { return colorStopColors[0]; } for (int i = 1; i < colorStopPositions.length; i++) { float colorStopPosition = colorStopPositions[i]; if (colorStopPosition < position && i != colorStopPositions.length - 1) { continue; } if (i == colorStopPositions.length - 1 && position >= colorStopPosition) { return Color.argb( (int) (opacity * 255), Color.red(colorStopColors[i]), Color.green(colorStopColors[i]), Color.blue(colorStopColors[i]) ); } // We found the position in which position is between i - 1 and i. float distanceBetweenColors = colorStopPositions[i] - colorStopPositions[i - 1]; float distanceToLowerColor = position - colorStopPositions[i - 1]; float percentage = distanceToLowerColor / distanceBetweenColors; int upperColor = colorStopColors[i]; int lowerColor = colorStopColors[i - 1]; int a = (int) (opacity * 255); int r = GammaEvaluator.evaluate(percentage, Color.red(lowerColor), Color.red(upperColor)); int g = GammaEvaluator.evaluate(percentage, Color.green(lowerColor), Color.green(upperColor)); int b = GammaEvaluator.evaluate(percentage, Color.blue(lowerColor), Color.blue(upperColor)); return Color.argb(a, r, g, b); } throw new IllegalArgumentException("Unreachable code."); } private int getColorInBetweenOpacityStops(float position, int color, float[] opacityStopPositions, float[] opacityStopOpacities) { if (opacityStopOpacities.length < 2 || position <= opacityStopPositions[0]) { int a = (int) (opacityStopOpacities[0] * 255); int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); return Color.argb(a, r, g, b); } for (int i = 1; i < opacityStopPositions.length; i++) { float opacityStopPosition = opacityStopPositions[i]; if (opacityStopPosition < position && i != opacityStopPositions.length - 1) { continue; } final int a; if (opacityStopPosition <= position) { a = (int) (opacityStopOpacities[i] * 255); } else { // We found the position in which position in between i - 1 and i. float distanceBetweenOpacities = opacityStopPositions[i] - opacityStopPositions[i - 1]; float distanceToLowerOpacity = position - opacityStopPositions[i - 1]; float percentage = distanceToLowerOpacity / distanceBetweenOpacities; a = (int) (MiscUtils.lerp(opacityStopOpacities[i - 1], opacityStopOpacities[i], percentage) * 255); } int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); return Color.argb(a, r, g, b); } throw new IllegalArgumentException("Unreachable code."); } /** * Takes two sorted float arrays and merges their elements while removing duplicates. */ protected static float[] mergeUniqueElements(float[] arrayA, float[] arrayB) { if (arrayA.length == 0) { return arrayB; } else if (arrayB.length == 0) { return arrayA; } int aIndex = 0; int bIndex = 0; int numDuplicates = 0; // This will be the merged list but may be longer than what is needed if there are duplicates. // If there are, the 0 elements at the end need to be truncated. float[] mergedNotTruncated = new float[arrayA.length + arrayB.length]; for (int i = 0; i < mergedNotTruncated.length; i++) { final float a = aIndex < arrayA.length ? arrayA[aIndex] : Float.NaN; final float b = bIndex < arrayB.length ? arrayB[bIndex] : Float.NaN; if (Float.isNaN(b) || a < b) { mergedNotTruncated[i] = a; aIndex++; } else if (Float.isNaN(a) || b < a) { mergedNotTruncated[i] = b; bIndex++; } else { mergedNotTruncated[i] = a; aIndex++; bIndex++; numDuplicates++; } } if (numDuplicates == 0) { return mergedNotTruncated; } return Arrays.copyOf(mergedNotTruncated, mergedNotTruncated.length - numDuplicates); } }
2,533
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/RectangleShapeParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.content.RectangleShape; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class RectangleShapeParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "p", "s", "r", "hd" ); private RectangleShapeParser() { } static RectangleShape parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; AnimatableValue<PointF, PointF> position = null; AnimatableValue<PointF, PointF> size = null; AnimatableFloatValue roundedness = null; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: position = AnimatablePathValueParser.parseSplitPath(reader, composition); break; case 2: size = AnimatableValueParser.parsePoint(reader, composition); break; case 3: roundedness = AnimatableValueParser.parseFloat(reader, composition); break; case 4: hidden = reader.nextBoolean(); break; default: reader.skipValue(); } } return new RectangleShape(name, position, size, roundedness, hidden); } }
2,534
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/KeyframeParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import androidx.annotation.Nullable; import androidx.collection.SparseArrayCompat; import androidx.core.view.animation.PathInterpolatorCompat; import com.airbnb.lottie.L; import com.airbnb.lottie.Lottie; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.MiscUtils; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.Keyframe; import java.io.IOException; import java.lang.ref.WeakReference; class KeyframeParser { /** * Some animations get exported with insane cp values in the tens of thousands. * PathInterpolator fails to create the interpolator in those cases and hangs. * Clamping the cp helps prevent that. */ private static final float MAX_CP_VALUE = 100; private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator(); private static SparseArrayCompat<WeakReference<Interpolator>> pathInterpolatorCache; static JsonReader.Options NAMES = JsonReader.Options.of( "t", // 1 "s", // 2 "e", // 3 "o", // 4 "i", // 5 "h", // 6 "to", // 7 "ti" // 8 ); static JsonReader.Options INTERPOLATOR_NAMES = JsonReader.Options.of( "x", // 1 "y" // 2 ); // https://github.com/airbnb/lottie-android/issues/464 private static SparseArrayCompat<WeakReference<Interpolator>> pathInterpolatorCache() { if (pathInterpolatorCache == null) { pathInterpolatorCache = new SparseArrayCompat<>(); } return pathInterpolatorCache; } @Nullable private static WeakReference<Interpolator> getInterpolator(int hash) { // This must be synchronized because get and put isn't thread safe because // SparseArrayCompat has to create new sized arrays sometimes. synchronized (KeyframeParser.class) { return pathInterpolatorCache().get(hash); } } private static void putInterpolator(int hash, WeakReference<Interpolator> interpolator) { // This must be synchronized because get and put isn't thread safe because // SparseArrayCompat has to create new sized arrays sometimes. synchronized (KeyframeParser.class) { pathInterpolatorCache.put(hash, interpolator); } } /** * @param multiDimensional When true, the keyframe interpolators can be independent for the X and Y axis. */ static <T> Keyframe<T> parse(JsonReader reader, LottieComposition composition, float scale, ValueParser<T> valueParser, boolean animated, boolean multiDimensional) throws IOException { if (animated && multiDimensional) { return parseMultiDimensionalKeyframe(composition, reader, scale, valueParser); } else if (animated) { return parseKeyframe(composition, reader, scale, valueParser); } else { return parseStaticValue(reader, scale, valueParser); } } /** * beginObject will already be called on the keyframe so it can be differentiated with * a non animated value. */ private static <T> Keyframe<T> parseKeyframe(LottieComposition composition, JsonReader reader, float scale, ValueParser<T> valueParser) throws IOException { PointF cp1 = null; PointF cp2 = null; float startFrame = 0; T startValue = null; T endValue = null; boolean hold = false; Interpolator interpolator = null; // Only used by PathKeyframe PointF pathCp1 = null; PointF pathCp2 = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: // t startFrame = (float) reader.nextDouble(); break; case 1: // s startValue = valueParser.parse(reader, scale); break; case 2: // e endValue = valueParser.parse(reader, scale); break; case 3: // o cp1 = JsonUtils.jsonToPoint(reader, 1f); break; case 4: // i cp2 = JsonUtils.jsonToPoint(reader, 1f); break; case 5: // h hold = reader.nextInt() == 1; break; case 6: // to pathCp1 = JsonUtils.jsonToPoint(reader, scale); break; case 7: // ti pathCp2 = JsonUtils.jsonToPoint(reader, scale); break; default: reader.skipValue(); } } reader.endObject(); if (hold) { endValue = startValue; // TODO: create a HoldInterpolator so progress changes don't invalidate. interpolator = LINEAR_INTERPOLATOR; } else if (cp1 != null && cp2 != null) { interpolator = interpolatorFor(cp1, cp2); } else { interpolator = LINEAR_INTERPOLATOR; } Keyframe<T> keyframe = new Keyframe<>(composition, startValue, endValue, interpolator, startFrame, null); keyframe.pathCp1 = pathCp1; keyframe.pathCp2 = pathCp2; return keyframe; } private static <T> Keyframe<T> parseMultiDimensionalKeyframe(LottieComposition composition, JsonReader reader, float scale, ValueParser<T> valueParser) throws IOException { PointF cp1 = null; PointF cp2 = null; PointF xCp1 = null; PointF xCp2 = null; PointF yCp1 = null; PointF yCp2 = null; float startFrame = 0; T startValue = null; T endValue = null; boolean hold = false; Interpolator interpolator = null; Interpolator xInterpolator = null; Interpolator yInterpolator = null; // Only used by PathKeyframe PointF pathCp1 = null; PointF pathCp2 = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: // t startFrame = (float) reader.nextDouble(); break; case 1: // s startValue = valueParser.parse(reader, scale); break; case 2: // e endValue = valueParser.parse(reader, scale); break; case 3: // o if (reader.peek() == JsonReader.Token.BEGIN_OBJECT) { reader.beginObject(); float xCp1x = 0f; float xCp1y = 0f; float yCp1x = 0f; float yCp1y = 0f; while (reader.hasNext()) { switch (reader.selectName(INTERPOLATOR_NAMES)) { case 0: // x if (reader.peek() == JsonReader.Token.NUMBER) { xCp1x = (float) reader.nextDouble(); yCp1x = xCp1x; } else { reader.beginArray(); xCp1x = (float) reader.nextDouble(); if (reader.peek() == JsonReader.Token.NUMBER) { yCp1x = (float) reader.nextDouble(); } else { yCp1x = xCp1x; } reader.endArray(); } break; case 1: // y if (reader.peek() == JsonReader.Token.NUMBER) { xCp1y = (float) reader.nextDouble(); yCp1y = xCp1y; } else { reader.beginArray(); xCp1y = (float) reader.nextDouble(); if (reader.peek() == JsonReader.Token.NUMBER) { yCp1y = (float) reader.nextDouble(); } else { yCp1y = xCp1y; } reader.endArray(); } break; default: reader.skipValue(); } } xCp1 = new PointF(xCp1x, xCp1y); yCp1 = new PointF(yCp1x, yCp1y); reader.endObject(); } else { cp1 = JsonUtils.jsonToPoint(reader, scale); } break; case 4: // i if (reader.peek() == JsonReader.Token.BEGIN_OBJECT) { reader.beginObject(); float xCp2x = 0f; float xCp2y = 0f; float yCp2x = 0f; float yCp2y = 0f; while (reader.hasNext()) { switch (reader.selectName(INTERPOLATOR_NAMES)) { case 0: // x if (reader.peek() == JsonReader.Token.NUMBER) { xCp2x = (float) reader.nextDouble(); yCp2x = xCp2x; } else { reader.beginArray(); xCp2x = (float) reader.nextDouble(); if (reader.peek() == JsonReader.Token.NUMBER) { yCp2x = (float) reader.nextDouble(); } else { yCp2x = xCp2x; } reader.endArray(); } break; case 1: // y if (reader.peek() == JsonReader.Token.NUMBER) { xCp2y = (float) reader.nextDouble(); yCp2y = xCp2y; } else { reader.beginArray(); xCp2y = (float) reader.nextDouble(); if (reader.peek() == JsonReader.Token.NUMBER) { yCp2y = (float) reader.nextDouble(); } else { yCp2y = xCp2y; } reader.endArray(); } break; default: reader.skipValue(); } } xCp2 = new PointF(xCp2x, xCp2y); yCp2 = new PointF(yCp2x, yCp2y); reader.endObject(); } else { cp2 = JsonUtils.jsonToPoint(reader, scale); } break; case 5: // h hold = reader.nextInt() == 1; break; case 6: // to pathCp1 = JsonUtils.jsonToPoint(reader, scale); break; case 7: // ti pathCp2 = JsonUtils.jsonToPoint(reader, scale); break; default: reader.skipValue(); } } reader.endObject(); if (hold) { endValue = startValue; // TODO: create a HoldInterpolator so progress changes don't invalidate. interpolator = LINEAR_INTERPOLATOR; } else if (cp1 != null && cp2 != null) { interpolator = interpolatorFor(cp1, cp2); } else if (xCp1 != null && yCp1 != null && xCp2 != null && yCp2 != null) { xInterpolator = interpolatorFor(xCp1, xCp2); yInterpolator = interpolatorFor(yCp1, yCp2); } else { interpolator = LINEAR_INTERPOLATOR; } Keyframe<T> keyframe; if (xInterpolator != null && yInterpolator != null) { keyframe = new Keyframe<>(composition, startValue, endValue, xInterpolator, yInterpolator, startFrame, null); } else { keyframe = new Keyframe<>(composition, startValue, endValue, interpolator, startFrame, null); } keyframe.pathCp1 = pathCp1; keyframe.pathCp2 = pathCp2; return keyframe; } private static Interpolator interpolatorFor(PointF cp1, PointF cp2) { Interpolator interpolator = null; cp1.x = MiscUtils.clamp(cp1.x, -1f, 1f); cp1.y = MiscUtils.clamp(cp1.y, -MAX_CP_VALUE, MAX_CP_VALUE); cp2.x = MiscUtils.clamp(cp2.x, -1f, 1f); cp2.y = MiscUtils.clamp(cp2.y, -MAX_CP_VALUE, MAX_CP_VALUE); int hash = Utils.hashFor(cp1.x, cp1.y, cp2.x, cp2.y); WeakReference<Interpolator> interpolatorRef = L.getDisablePathInterpolatorCache() ? null : getInterpolator(hash); if (interpolatorRef != null) { interpolator = interpolatorRef.get(); } if (interpolatorRef == null || interpolator == null) { try { interpolator = PathInterpolatorCompat.create(cp1.x, cp1.y, cp2.x, cp2.y); } catch (IllegalArgumentException e) { if ("The Path cannot loop back on itself.".equals(e.getMessage())) { // If a control point extends beyond the previous/next point then it will cause the value of the interpolator to no // longer monotonously increase. This clips the control point bounds to prevent that from happening. // NOTE: this will make the rendered animation behave slightly differently than the original. interpolator = PathInterpolatorCompat.create(Math.min(cp1.x, 1f), cp1.y, Math.max(cp2.x, 0f), cp2.y); } else { // We failed to create the interpolator. Fall back to linear. interpolator = new LinearInterpolator(); } } if (!L.getDisablePathInterpolatorCache()) { try { putInterpolator(hash, new WeakReference<>(interpolator)); } catch (ArrayIndexOutOfBoundsException e) { // It is not clear why but SparseArrayCompat sometimes fails with this: // https://github.com/airbnb/lottie-android/issues/452 // Because this is not a critical operation, we can safely just ignore it. // I was unable to repro this to attempt a proper fix. } } } return interpolator; } private static <T> Keyframe<T> parseStaticValue(JsonReader reader, float scale, ValueParser<T> valueParser) throws IOException { T value = valueParser.parse(reader, scale); return new Keyframe<>(value); } }
2,535
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/AnimatableTextPropertiesParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableTextProperties; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class AnimatableTextPropertiesParser { private static final JsonReader.Options PROPERTIES_NAMES = JsonReader.Options.of("a"); private static final JsonReader.Options ANIMATABLE_PROPERTIES_NAMES = JsonReader.Options.of( "fc", "sc", "sw", "t" ); private AnimatableTextPropertiesParser() { } public static AnimatableTextProperties parse( JsonReader reader, LottieComposition composition) throws IOException { AnimatableTextProperties anim = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(PROPERTIES_NAMES)) { case 0: anim = parseAnimatableTextProperties(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (anim == null) { // Not sure if this is possible. return new AnimatableTextProperties(null, null, null, null); } return anim; } private static AnimatableTextProperties parseAnimatableTextProperties( JsonReader reader, LottieComposition composition) throws IOException { AnimatableColorValue color = null; AnimatableColorValue stroke = null; AnimatableFloatValue strokeWidth = null; AnimatableFloatValue tracking = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(ANIMATABLE_PROPERTIES_NAMES)) { case 0: color = AnimatableValueParser.parseColor(reader, composition); break; case 1: stroke = AnimatableValueParser.parseColor(reader, composition); break; case 2: strokeWidth = AnimatableValueParser.parseFloat(reader, composition); break; case 3: tracking = AnimatableValueParser.parseFloat(reader, composition); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return new AnimatableTextProperties(color, stroke, strokeWidth, tracking); } }
2,536
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/ShapeGroupParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.content.ContentModel; import com.airbnb.lottie.model.content.ShapeGroup; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; class ShapeGroupParser { private ShapeGroupParser() { } private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "hd", "it" ); static ShapeGroup parse( JsonReader reader, LottieComposition composition) throws IOException { String name = null; boolean hidden = false; List<ContentModel> items = new ArrayList<>(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: hidden = reader.nextBoolean(); break; case 2: reader.beginArray(); while (reader.hasNext()) { ContentModel newItem = ContentModelParser.parse(reader, composition); if (newItem != null) { items.add(newItem); } } reader.endArray(); break; default: reader.skipValue(); } } return new ShapeGroup(name, items, hidden); } }
2,537
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/MaskParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; import com.airbnb.lottie.model.content.Mask; import com.airbnb.lottie.parser.moshi.JsonReader; import com.airbnb.lottie.utils.Logger; import java.io.IOException; class MaskParser { private MaskParser() { } static Mask parse( JsonReader reader, LottieComposition composition) throws IOException { Mask.MaskMode maskMode = null; AnimatableShapeValue maskPath = null; AnimatableIntegerValue opacity = null; boolean inverted = false; reader.beginObject(); while (reader.hasNext()) { String mode = reader.nextName(); switch (mode) { case "mode": switch (reader.nextString()) { case "a": maskMode = Mask.MaskMode.MASK_MODE_ADD; break; case "s": maskMode = Mask.MaskMode.MASK_MODE_SUBTRACT; break; case "n": maskMode = Mask.MaskMode.MASK_MODE_NONE; break; case "i": composition.addWarning( "Animation contains intersect masks. They are not supported but will be treated like add masks."); maskMode = Mask.MaskMode.MASK_MODE_INTERSECT; break; default: Logger.warning("Unknown mask mode " + mode + ". Defaulting to Add."); maskMode = Mask.MaskMode.MASK_MODE_ADD; } break; case "pt": maskPath = AnimatableValueParser.parseShapeData(reader, composition); break; case "o": opacity = AnimatableValueParser.parseInteger(reader, composition); break; case "inv": inverted = reader.nextBoolean(); break; default: reader.skipValue(); } } reader.endObject(); return new Mask(maskMode, maskPath, opacity, inverted); } }
2,538
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/CircleShapeParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.content.CircleShape; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; class CircleShapeParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "nm", "p", "s", "hd", "d" ); private CircleShapeParser() { } static CircleShape parse( JsonReader reader, LottieComposition composition, int d) throws IOException { String name = null; AnimatableValue<PointF, PointF> position = null; AnimatablePointValue size = null; boolean reversed = d == 3; boolean hidden = false; while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: name = reader.nextString(); break; case 1: position = AnimatablePathValueParser.parseSplitPath(reader, composition); break; case 2: size = AnimatableValueParser.parsePoint(reader, composition); break; case 3: hidden = reader.nextBoolean(); break; case 4: // "d" is 2 for normal and 3 for reversed. reversed = reader.nextInt() == 3; break; default: reader.skipName(); reader.skipValue(); } } return new CircleShape(name, position, size, reversed, hidden); } }
2,539
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/FloatParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class FloatParser implements ValueParser<Float> { public static final FloatParser INSTANCE = new FloatParser(); private FloatParser() { } @Override public Float parse(JsonReader reader, float scale) throws IOException { return JsonUtils.valueFromObject(reader) * scale; } }
2,540
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/JsonUtils.java
package com.airbnb.lottie.parser; import android.graphics.Color; import android.graphics.PointF; import androidx.annotation.ColorInt; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; class JsonUtils { private JsonUtils() { } /** * [r,g,b] */ @ColorInt static int jsonToColor(JsonReader reader) throws IOException { reader.beginArray(); int r = (int) (reader.nextDouble() * 255); int g = (int) (reader.nextDouble() * 255); int b = (int) (reader.nextDouble() * 255); while (reader.hasNext()) { reader.skipValue(); } reader.endArray(); return Color.argb(255, r, g, b); } static List<PointF> jsonToPoints(JsonReader reader, float scale) throws IOException { List<PointF> points = new ArrayList<>(); reader.beginArray(); while (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray(); points.add(jsonToPoint(reader, scale)); reader.endArray(); } reader.endArray(); return points; } static PointF jsonToPoint(JsonReader reader, float scale) throws IOException { switch (reader.peek()) { case NUMBER: return jsonNumbersToPoint(reader, scale); case BEGIN_ARRAY: return jsonArrayToPoint(reader, scale); case BEGIN_OBJECT: return jsonObjectToPoint(reader, scale); default: throw new IllegalArgumentException("Unknown point starts with " + reader.peek()); } } private static PointF jsonNumbersToPoint(JsonReader reader, float scale) throws IOException { float x = (float) reader.nextDouble(); float y = (float) reader.nextDouble(); while (reader.hasNext()) { reader.skipValue(); } return new PointF(x * scale, y * scale); } private static PointF jsonArrayToPoint(JsonReader reader, float scale) throws IOException { float x; float y; reader.beginArray(); x = (float) reader.nextDouble(); y = (float) reader.nextDouble(); while (reader.peek() != JsonReader.Token.END_ARRAY) { reader.skipValue(); } reader.endArray(); return new PointF(x * scale, y * scale); } private static final JsonReader.Options POINT_NAMES = JsonReader.Options.of("x", "y"); private static PointF jsonObjectToPoint(JsonReader reader, float scale) throws IOException { float x = 0f; float y = 0f; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(POINT_NAMES)) { case 0: x = valueFromObject(reader); break; case 1: y = valueFromObject(reader); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return new PointF(x * scale, y * scale); } static float valueFromObject(JsonReader reader) throws IOException { JsonReader.Token token = reader.peek(); switch (token) { case NUMBER: return (float) reader.nextDouble(); case BEGIN_ARRAY: reader.beginArray(); float val = (float) reader.nextDouble(); while (reader.hasNext()) { reader.skipValue(); } reader.endArray(); return val; default: throw new IllegalArgumentException("Unknown value for token of type " + token); } } }
2,541
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/LottieCompositionMoshiParser.java
package com.airbnb.lottie.parser; import android.graphics.Rect; import androidx.collection.LongSparseArray; import androidx.collection.SparseArrayCompat; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieImageAsset; 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.Utils; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LottieCompositionMoshiParser { private static final JsonReader.Options NAMES = JsonReader.Options.of( "w", // 0 "h", // 1 "ip", // 2 "op", // 3 "fr", // 4 "v", // 5 "layers", // 6 "assets", // 7 "fonts", // 8 "chars", // 9 "markers" // 10 ); public static LottieComposition parse(JsonReader reader) throws IOException { float scale = Utils.dpScale(); float startFrame = 0f; float endFrame = 0f; float frameRate = 0f; final LongSparseArray<Layer> layerMap = new LongSparseArray<>(); final List<Layer> layers = new ArrayList<>(); int width = 0; int height = 0; Map<String, List<Layer>> precomps = new HashMap<>(); Map<String, LottieImageAsset> images = new HashMap<>(); Map<String, Font> fonts = new HashMap<>(); List<Marker> markers = new ArrayList<>(); SparseArrayCompat<FontCharacter> characters = new SparseArrayCompat<>(); LottieComposition composition = new LottieComposition(); reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: width = reader.nextInt(); break; case 1: height = reader.nextInt(); break; case 2: startFrame = (float) reader.nextDouble(); break; case 3: endFrame = (float) reader.nextDouble() - 0.01f; break; case 4: frameRate = (float) reader.nextDouble(); break; case 5: String version = reader.nextString(); String[] versions = version.split("\\."); int majorVersion = Integer.parseInt(versions[0]); int minorVersion = Integer.parseInt(versions[1]); int patchVersion = Integer.parseInt(versions[2]); if (!Utils.isAtLeastVersion(majorVersion, minorVersion, patchVersion, 4, 4, 0)) { composition.addWarning("Lottie only supports bodymovin >= 4.4.0"); } break; case 6: parseLayers(reader, composition, layers, layerMap); break; case 7: parseAssets(reader, composition, precomps, images); break; case 8: parseFonts(reader, fonts); break; case 9: parseChars(reader, composition, characters); break; case 10: parseMarkers(reader, markers); break; default: reader.skipName(); reader.skipValue(); } } int scaledWidth = (int) (width * scale); int scaledHeight = (int) (height * scale); Rect bounds = new Rect(0, 0, scaledWidth, scaledHeight); composition.init(bounds, startFrame, endFrame, frameRate, layers, layerMap, precomps, images, characters, fonts, markers); return composition; } private static void parseLayers(JsonReader reader, LottieComposition composition, List<Layer> layers, LongSparseArray<Layer> layerMap) throws IOException { int imageCount = 0; reader.beginArray(); while (reader.hasNext()) { Layer layer = LayerParser.parse(reader, composition); if (layer.getLayerType() == Layer.LayerType.IMAGE) { imageCount++; } layers.add(layer); layerMap.put(layer.getId(), layer); if (imageCount > 4) { Logger.warning("You have " + imageCount + " images. Lottie should primarily be " + "used with shapes. If you are using Adobe Illustrator, convert the Illustrator layers" + " to shape layers."); } } reader.endArray(); } static JsonReader.Options ASSETS_NAMES = JsonReader.Options.of( "id", // 0 "layers", // 1 "w", // 2 "h", // 3 "p", // 4 "u" // 5 ); private static void parseAssets(JsonReader reader, LottieComposition composition, Map<String, List<Layer>> precomps, Map<String, LottieImageAsset> images) throws IOException { reader.beginArray(); while (reader.hasNext()) { String id = null; // For precomps List<Layer> layers = new ArrayList<>(); LongSparseArray<Layer> layerMap = new LongSparseArray<>(); // For images int width = 0; int height = 0; String imageFileName = null; String relativeFolder = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(ASSETS_NAMES)) { case 0: id = reader.nextString(); break; case 1: reader.beginArray(); while (reader.hasNext()) { Layer layer = LayerParser.parse(reader, composition); layerMap.put(layer.getId(), layer); layers.add(layer); } reader.endArray(); break; case 2: width = reader.nextInt(); break; case 3: height = reader.nextInt(); break; case 4: imageFileName = reader.nextString(); break; case 5: relativeFolder = reader.nextString(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); if (imageFileName != null) { LottieImageAsset image = new LottieImageAsset(width, height, id, imageFileName, relativeFolder); images.put(image.getId(), image); } else { precomps.put(id, layers); } } reader.endArray(); } private static final JsonReader.Options FONT_NAMES = JsonReader.Options.of("list"); private static void parseFonts(JsonReader reader, Map<String, Font> fonts) throws IOException { reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(FONT_NAMES)) { case 0: reader.beginArray(); while (reader.hasNext()) { Font font = FontParser.parse(reader); fonts.put(font.getName(), font); } reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); } private static void parseChars( JsonReader reader, LottieComposition composition, SparseArrayCompat<FontCharacter> characters) throws IOException { reader.beginArray(); while (reader.hasNext()) { FontCharacter character = FontCharacterParser.parse(reader, composition); characters.put(character.hashCode(), character); } reader.endArray(); } private static final JsonReader.Options MARKER_NAMES = JsonReader.Options.of( "cm", "tm", "dr" ); private static void parseMarkers(JsonReader reader, List<Marker> markers) throws IOException { reader.beginArray(); while (reader.hasNext()) { String comment = null; float frame = 0f; float durationFrames = 0f; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(MARKER_NAMES)) { case 0: comment = reader.nextString(); break; case 1: frame = (float) reader.nextDouble(); break; case 2: durationFrames = (float) reader.nextDouble(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); markers.add(new Marker(comment, frame, durationFrames)); } reader.endArray(); } }
2,542
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/IntegerParser.java
package com.airbnb.lottie.parser; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class IntegerParser implements ValueParser<Integer> { public static final IntegerParser INSTANCE = new IntegerParser(); private IntegerParser() { } @Override public Integer parse(JsonReader reader, float scale) throws IOException { return Math.round(JsonUtils.valueFromObject(reader) * scale); } }
2,543
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.parser; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,544
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/DocumentDataParser.java
package com.airbnb.lottie.parser; import android.graphics.PointF; import com.airbnb.lottie.model.DocumentData; import com.airbnb.lottie.model.DocumentData.Justification; import com.airbnb.lottie.parser.moshi.JsonReader; import java.io.IOException; public class DocumentDataParser implements ValueParser<DocumentData> { public static final DocumentDataParser INSTANCE = new DocumentDataParser(); private static final JsonReader.Options NAMES = JsonReader.Options.of( "t", // 0 "f", // 1 "s", // 2 "j", // 3 "tr", // 4 "lh", // 5 "ls", // 6 "fc", // 7 "sc", // 8 "sw", // 9 "of", // 10 "ps", // 11 "sz" // 12 ); private DocumentDataParser() { } @Override public DocumentData parse(JsonReader reader, float scale) throws IOException { String text = null; String fontName = null; float size = 0f; Justification justification = Justification.CENTER; int tracking = 0; float lineHeight = 0f; float baselineShift = 0f; int fillColor = 0; int strokeColor = 0; float strokeWidth = 0f; boolean strokeOverFill = true; PointF boxPosition = null; PointF boxSize = null; reader.beginObject(); while (reader.hasNext()) { switch (reader.selectName(NAMES)) { case 0: text = reader.nextString(); break; case 1: fontName = reader.nextString(); break; case 2: size = (float) reader.nextDouble(); break; case 3: int justificationInt = reader.nextInt(); if (justificationInt > Justification.CENTER.ordinal() || justificationInt < 0) { justification = Justification.CENTER; } else { justification = Justification.values()[justificationInt]; } break; case 4: tracking = reader.nextInt(); break; case 5: lineHeight = (float) reader.nextDouble(); break; case 6: baselineShift = (float) reader.nextDouble(); break; case 7: fillColor = JsonUtils.jsonToColor(reader); break; case 8: strokeColor = JsonUtils.jsonToColor(reader); break; case 9: strokeWidth = (float) reader.nextDouble(); break; case 10: strokeOverFill = reader.nextBoolean(); break; case 11: reader.beginArray(); boxPosition = new PointF((float) reader.nextDouble() * scale, (float) reader.nextDouble() * scale); reader.endArray(); break; case 12: reader.beginArray(); boxSize = new PointF((float) reader.nextDouble() * scale, (float) reader.nextDouble() * scale); reader.endArray(); break; default: reader.skipName(); reader.skipValue(); } } reader.endObject(); return new DocumentData(text, fontName, size, justification, tracking, lineHeight, baselineShift, fillColor, strokeColor, strokeWidth, strokeOverFill, boxPosition, boxSize); } }
2,545
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/JsonScope.java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; /** * Lexical scoping elements within a JSON reader or writer. */ final class JsonScope { private JsonScope() { } /** * An array with no elements requires no separators or newlines before it is closed. */ static final int EMPTY_ARRAY = 1; /** * A array with at least one value requires a comma and newline before the next element. */ static final int NONEMPTY_ARRAY = 2; /** * An object with no name/value pairs requires no separators or newlines before it is closed. */ static final int EMPTY_OBJECT = 3; /** * An object whose most recent element is a key. The next element must be a value. */ static final int DANGLING_NAME = 4; /** * An object with at least one name/value pair requires a separator before the next element. */ static final int NONEMPTY_OBJECT = 5; /** * No object or array has been started. */ static final int EMPTY_DOCUMENT = 6; /** * A document with at an array or object. */ static final int NONEMPTY_DOCUMENT = 7; /** * A document that's been closed and cannot be accessed. */ static final int CLOSED = 8; /** * Renders the path in a JSON document to a string. The {@code pathNames} and {@code pathIndices} * parameters corresponds directly to stack: At indices where the stack contains an object * (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT), pathNames contains the name at this scope. * Where it contains an array (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index * in that array. Otherwise the value is undefined, and we take advantage of that by incrementing * pathIndices when doing so isn't useful. */ static String getPath(int stackSize, int[] stack, String[] pathNames, int[] pathIndices) { StringBuilder result = new StringBuilder().append('$'); for (int i = 0; i < stackSize; i++) { switch (stack[i]) { case EMPTY_ARRAY: case NONEMPTY_ARRAY: result.append('[').append(pathIndices[i]).append(']'); break; case EMPTY_OBJECT: case DANGLING_NAME: case NONEMPTY_OBJECT: result.append('.'); if (pathNames[i] != null) { result.append(pathNames[i]); } break; case NONEMPTY_DOCUMENT: case EMPTY_DOCUMENT: case CLOSED: break; } } return result.toString(); } }
2,546
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/LinkedHashTreeMap.java
/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.NoSuchElementException; import java.util.Set; /** * A map of comparable keys to values. Unlike {@code TreeMap}, this class uses * insertion order for iteration order. Comparison order is only used as an * optimization for efficient insertion and removal. * * <p>This implementation was derived from Android 4.1's TreeMap and * LinkedHashMap classes. */ final class LinkedHashTreeMap<K, V> extends AbstractMap<K, V> implements Serializable { @SuppressWarnings({"unchecked", "rawtypes"}) // to avoid Comparable<Comparable<Comparable<...>>> private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() { public int compare(Comparable a, Comparable b) { return a.compareTo(b); } }; Comparator<? super K> comparator; Node<K, V>[] table; final Node<K, V> header; int size = 0; int modCount = 0; int threshold; /** * Create a natural order, empty tree map whose keys must be mutually * comparable and non-null. */ LinkedHashTreeMap() { this(null); } /** * Create a tree map ordered by {@code comparator}. This map's keys may only * be null if {@code comparator} permits. * * @param comparator the comparator to order elements with, or {@code null} to * use the natural ordering. */ @SuppressWarnings({ "unchecked", "rawtypes" // Unsafe! if comparator is null, this assumes K is comparable. }) LinkedHashTreeMap(Comparator<? super K> comparator) { this.comparator = comparator != null ? comparator : (Comparator) NATURAL_ORDER; this.header = new Node<>(); this.table = new Node[16]; // TODO: sizing/resizing policies this.threshold = (table.length / 2) + (table.length / 4); // 3/4 capacity } @Override public int size() { return size; } @Override public V get(Object key) { Node<K, V> node = findByObject(key); return node != null ? node.value : null; } @Override public boolean containsKey(Object key) { return findByObject(key) != null; } @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } Node<K, V> created = find(key, true); V result = created.value; created.value = value; return result; } @Override public void clear() { Arrays.fill(table, null); size = 0; modCount++; // Clear all links to help GC Node<K, V> header = this.header; for (Node<K, V> e = header.next; e != header; ) { Node<K, V> next = e.next; e.next = e.prev = null; e = next; } header.next = header.prev = header; } @Override public V remove(Object key) { Node<K, V> node = removeInternalByKey(key); return node != null ? node.value : null; } /** * Returns the node at or adjacent to the given key, creating it if requested. * * @throws ClassCastException if {@code key} and the tree's keys aren't * mutually comparable. */ Node<K, V> find(K key, boolean create) { Comparator<? super K> comparator = this.comparator; Node<K, V>[] table = this.table; int hash = secondaryHash(key.hashCode()); int index = hash & (table.length - 1); Node<K, V> nearest = table[index]; int comparison = 0; if (nearest != null) { // Micro-optimization: avoid polymorphic calls to Comparator.compare(). @SuppressWarnings("unchecked") // Throws a ClassCastException below if there's trouble. Comparable<Object> comparableKey = (comparator == NATURAL_ORDER) ? (Comparable<Object>) key : null; while (true) { comparison = (comparableKey != null) ? comparableKey.compareTo(nearest.key) : comparator.compare(key, nearest.key); // We found the requested key. if (comparison == 0) { return nearest; } // If it exists, the key is in a subtree. Go deeper. Node<K, V> child = (comparison < 0) ? nearest.left : nearest.right; if (child == null) { break; } nearest = child; } } // The key doesn't exist in this tree. if (!create) { return null; } // Create the node and add it to the tree or the table. Node<K, V> header = this.header; Node<K, V> created; if (nearest == null) { // Check that the value is comparable if we didn't do any comparisons. if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) { throw new ClassCastException(key.getClass().getName() + " is not Comparable"); } created = new Node<>(nearest, key, hash, header, header.prev); table[index] = created; } else { created = new Node<>(nearest, key, hash, header, header.prev); if (comparison < 0) { // nearest.key is higher nearest.left = created; } else { // comparison > 0, nearest.key is lower nearest.right = created; } rebalance(nearest, true); } if (size++ > threshold) { doubleCapacity(); } modCount++; return created; } @SuppressWarnings("unchecked") Node<K, V> findByObject(Object key) { try { return key != null ? find((K) key, false) : null; } catch (ClassCastException e) { return null; } } /** * Returns this map's entry that has the same key and value as {@code * entry}, or null if this map has no such entry. * * <p>This method uses the comparator for key equality rather than {@code * equals}. If this map's comparator isn't consistent with equals (such as * {@code String.CASE_INSENSITIVE_ORDER}), then {@code remove()} and {@code * contains()} will violate the collections API. */ Node<K, V> findByEntry(Entry<?, ?> entry) { Node<K, V> mine = findByObject(entry.getKey()); boolean valuesEqual = mine != null && equal(mine.value, entry.getValue()); return valuesEqual ? mine : null; } private boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because HashMap * uses power-of-two length hash tables, that otherwise encounter collisions * for hashCodes that do not differ in lower or upper bits. */ private static int secondaryHash(int h) { // Doug Lea's supplemental hash function h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } /** * Removes {@code node} from this tree, rearranging the tree's structure as * necessary. * * @param unlink true to also unlink this node from the iteration linked list. */ void removeInternal(Node<K, V> node, boolean unlink) { if (unlink) { node.prev.next = node.next; node.next.prev = node.prev; node.next = node.prev = null; // Help the GC (for performance) } Node<K, V> left = node.left; Node<K, V> right = node.right; Node<K, V> originalParent = node.parent; if (left != null && right != null) { /* * To remove a node with both left and right subtrees, move an * adjacent node from one of those subtrees into this node's place. * * Removing the adjacent node may change this node's subtrees. This * node may no longer have two subtrees once the adjacent node is * gone! */ Node<K, V> adjacent = (left.height > right.height) ? left.last() : right.first(); removeInternal(adjacent, false); // takes care of rebalance and size-- int leftHeight = 0; left = node.left; if (left != null) { leftHeight = left.height; adjacent.left = left; left.parent = adjacent; node.left = null; } int rightHeight = 0; right = node.right; if (right != null) { rightHeight = right.height; adjacent.right = right; right.parent = adjacent; node.right = null; } adjacent.height = Math.max(leftHeight, rightHeight) + 1; replaceInParent(node, adjacent); return; } else if (left != null) { replaceInParent(node, left); node.left = null; } else if (right != null) { replaceInParent(node, right); node.right = null; } else { replaceInParent(node, null); } rebalance(originalParent, false); size--; modCount++; } Node<K, V> removeInternalByKey(Object key) { Node<K, V> node = findByObject(key); if (node != null) { removeInternal(node, true); } return node; } private void replaceInParent(Node<K, V> node, Node<K, V> replacement) { Node<K, V> parent = node.parent; node.parent = null; if (replacement != null) { replacement.parent = parent; } if (parent != null) { if (parent.left == node) { parent.left = replacement; } else { assert (parent.right == node); parent.right = replacement; } } else { int index = node.hash & (table.length - 1); table[index] = replacement; } } /** * Rebalances the tree by making any AVL rotations necessary between the * newly-unbalanced node and the tree's root. * * @param insert true if the node was unbalanced by an insert; false if it * was by a removal. */ private void rebalance(Node<K, V> unbalanced, boolean insert) { for (Node<K, V> node = unbalanced; node != null; node = node.parent) { Node<K, V> left = node.left; Node<K, V> right = node.right; int leftHeight = left != null ? left.height : 0; int rightHeight = right != null ? right.height : 0; int delta = leftHeight - rightHeight; if (delta == -2) { Node<K, V> rightLeft = right.left; Node<K, V> rightRight = right.right; int rightRightHeight = rightRight != null ? rightRight.height : 0; int rightLeftHeight = rightLeft != null ? rightLeft.height : 0; int rightDelta = rightLeftHeight - rightRightHeight; if (rightDelta == -1 || (rightDelta == 0 && !insert)) { rotateLeft(node); // AVL right right } else { assert (rightDelta == 1); rotateRight(right); // AVL right left rotateLeft(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 2) { Node<K, V> leftLeft = left.left; Node<K, V> leftRight = left.right; int leftRightHeight = leftRight != null ? leftRight.height : 0; int leftLeftHeight = leftLeft != null ? leftLeft.height : 0; int leftDelta = leftLeftHeight - leftRightHeight; if (leftDelta == 1 || (leftDelta == 0 && !insert)) { rotateRight(node); // AVL left left } else { assert (leftDelta == -1); rotateLeft(left); // AVL left right rotateRight(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 0) { node.height = leftHeight + 1; // leftHeight == rightHeight if (insert) { break; // the insert caused balance, so rebalancing is done! } } else { assert (delta == -1 || delta == 1); node.height = Math.max(leftHeight, rightHeight) + 1; if (!insert) { break; // the height hasn't changed, so rebalancing is done! } } } } /** * Rotates the subtree so that its root's right child is the new root. */ private void rotateLeft(Node<K, V> root) { Node<K, V> left = root.left; Node<K, V> pivot = root.right; Node<K, V> pivotLeft = pivot.left; Node<K, V> pivotRight = pivot.right; // move the pivot's left child to the root's right root.right = pivotLeft; if (pivotLeft != null) { pivotLeft.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's left pivot.left = root; root.parent = pivot; // fix heights root.height = Math.max(left != null ? left.height : 0, pivotLeft != null ? pivotLeft.height : 0) + 1; pivot.height = Math.max(root.height, pivotRight != null ? pivotRight.height : 0) + 1; } /** * Rotates the subtree so that its root's left child is the new root. */ private void rotateRight(Node<K, V> root) { Node<K, V> pivot = root.left; Node<K, V> right = root.right; Node<K, V> pivotLeft = pivot.left; Node<K, V> pivotRight = pivot.right; // move the pivot's right child to the root's left root.left = pivotRight; if (pivotRight != null) { pivotRight.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's right pivot.right = root; root.parent = pivot; // fixup heights root.height = Math.max(right != null ? right.height : 0, pivotRight != null ? pivotRight.height : 0) + 1; pivot.height = Math.max(root.height, pivotLeft != null ? pivotLeft.height : 0) + 1; } private EntrySet entrySet; private KeySet keySet; @Override public Set<Entry<K, V>> entrySet() { EntrySet result = entrySet; return result != null ? result : (entrySet = new EntrySet()); } @Override public Set<K> keySet() { KeySet result = keySet; return result != null ? result : (keySet = new KeySet()); } static final class Node<K, V> implements Entry<K, V> { Node<K, V> parent; Node<K, V> left; Node<K, V> right; Node<K, V> next; Node<K, V> prev; final K key; final int hash; V value; int height; /** * Create the header entry. */ Node() { key = null; hash = -1; next = prev = this; } /** * Create a regular entry. */ Node(Node<K, V> parent, K key, int hash, Node<K, V> next, Node<K, V> prev) { this.parent = parent; this.key = key; this.hash = hash; this.height = 1; this.next = next; this.prev = prev; prev.next = this; next.prev = this; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { if (o instanceof Entry) { Entry other = (Entry) o; return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } return false; } @Override public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } /** * Returns the first node in this subtree. */ public Node<K, V> first() { Node<K, V> node = this; Node<K, V> child = node.left; while (child != null) { node = child; child = node.left; } return node; } /** * Returns the last node in this subtree. */ public Node<K, V> last() { Node<K, V> node = this; Node<K, V> child = node.right; while (child != null) { node = child; child = node.right; } return node; } } private void doubleCapacity() { table = doubleCapacity(table); threshold = (table.length / 2) + (table.length / 4); // 3/4 capacity } /** * Returns a new array containing the same nodes as {@code oldTable}, but with * twice as many trees, each of (approximately) half the previous size. */ static <K, V> Node<K, V>[] doubleCapacity(Node<K, V>[] oldTable) { // TODO: don't do anything if we're already at MAX_CAPACITY int oldCapacity = oldTable.length; @SuppressWarnings("unchecked") // Arrays and generics don't get along. Node<K, V>[] newTable = new Node[oldCapacity * 2]; AvlIterator<K, V> iterator = new AvlIterator<>(); AvlBuilder<K, V> leftBuilder = new AvlBuilder<>(); AvlBuilder<K, V> rightBuilder = new AvlBuilder<>(); // Split each tree into two trees. for (int i = 0; i < oldCapacity; i++) { Node<K, V> root = oldTable[i]; if (root == null) { continue; } // Compute the sizes of the left and right trees. iterator.reset(root); int leftSize = 0; int rightSize = 0; for (Node<K, V> node; (node = iterator.next()) != null; ) { if ((node.hash & oldCapacity) == 0) { leftSize++; } else { rightSize++; } } // Split the tree into two. leftBuilder.reset(leftSize); rightBuilder.reset(rightSize); iterator.reset(root); for (Node<K, V> node; (node = iterator.next()) != null; ) { if ((node.hash & oldCapacity) == 0) { leftBuilder.add(node); } else { rightBuilder.add(node); } } // Populate the enlarged array with these new roots. newTable[i] = leftSize > 0 ? leftBuilder.root() : null; newTable[i + oldCapacity] = rightSize > 0 ? rightBuilder.root() : null; } return newTable; } /** * Walks an AVL tree in iteration order. Once a node has been returned, its * left, right and parent links are <strong>no longer used</strong>. For this * reason it is safe to transform these links as you walk a tree. * * <p><strong>Warning:</strong> this iterator is destructive. It clears the * parent node of all nodes in the tree. It is an error to make a partial * iteration of a tree. */ static class AvlIterator<K, V> { /** * This stack is a singly linked list, linked by the 'parent' field. */ private Node<K, V> stackTop; void reset(Node<K, V> root) { Node<K, V> stackTop = null; for (Node<K, V> n = root; n != null; n = n.left) { n.parent = stackTop; stackTop = n; // Stack push. } this.stackTop = stackTop; } public Node<K, V> next() { Node<K, V> stackTop = this.stackTop; if (stackTop == null) { return null; } Node<K, V> result = stackTop; stackTop = result.parent; result.parent = null; for (Node<K, V> n = result.right; n != null; n = n.left) { n.parent = stackTop; stackTop = n; // Stack push. } this.stackTop = stackTop; return result; } } /** * Builds AVL trees of a predetermined size by accepting nodes of increasing * value. To use: * <ol> * <li>Call {@link #reset} to initialize the target size <i>size</i>. * <li>Call {@link #add} <i>size</i> times with increasing values. * <li>Call {@link #root} to get the root of the balanced tree. * </ol> * * <p>The returned tree will satisfy the AVL constraint: for every node * <i>N</i>, the height of <i>N.left</i> and <i>N.right</i> is different by at * most 1. It accomplishes this by omitting deepest-level leaf nodes when * building trees whose size isn't a power of 2 minus 1. * * <p>Unlike rebuilding a tree from scratch, this approach requires no value * comparisons. Using this class to create a tree of size <i>S</i> is * {@code O(S)}. */ static final class AvlBuilder<K, V> { /** * This stack is a singly linked list, linked by the 'parent' field. */ private Node<K, V> stack; private int leavesToSkip; private int leavesSkipped; private int size; void reset(int targetSize) { // compute the target tree size. This is a power of 2 minus one, like 15 or 31. int treeCapacity = Integer.highestOneBit(targetSize) * 2 - 1; leavesToSkip = treeCapacity - targetSize; size = 0; leavesSkipped = 0; stack = null; } void add(Node<K, V> node) { node.left = node.parent = node.right = null; node.height = 1; // Skip a leaf if necessary. if (leavesToSkip > 0 && (size & 1) == 0) { size++; leavesToSkip--; leavesSkipped++; } node.parent = stack; stack = node; // Stack push. size++; // Skip a leaf if necessary. if (leavesToSkip > 0 && (size & 1) == 0) { size++; leavesToSkip--; leavesSkipped++; } /* * Combine 3 nodes into subtrees whenever the size is one less than a * multiple of 4. For example we combine the nodes A, B, C into a * 3-element tree with B as the root. * * Combine two subtrees and a spare single value whenever the size is one * less than a multiple of 8. For example at 8 we may combine subtrees * (A B C) and (E F G) with D as the root to form ((A B C) D (E F G)). * * Just as we combine single nodes when size nears a multiple of 4, and * 3-element trees when size nears a multiple of 8, we combine subtrees of * size (N-1) whenever the total size is 2N-1 whenever N is a power of 2. */ for (int scale = 4; (size & scale - 1) == scale - 1; scale *= 2) { if (leavesSkipped == 0) { // Pop right, center and left, then make center the top of the stack. Node<K, V> right = stack; Node<K, V> center = right.parent; Node<K, V> left = center.parent; center.parent = left.parent; stack = center; // Construct a tree. center.left = left; center.right = right; center.height = right.height + 1; left.parent = center; right.parent = center; } else if (leavesSkipped == 1) { // Pop right and center, then make center the top of the stack. Node<K, V> right = stack; Node<K, V> center = right.parent; stack = center; // Construct a tree with no left child. center.right = right; center.height = right.height + 1; right.parent = center; leavesSkipped = 0; } else if (leavesSkipped == 2) { leavesSkipped = 0; } } } Node<K, V> root() { Node<K, V> stackTop = this.stack; if (stackTop.parent != null) { throw new IllegalStateException(); } return stackTop; } } abstract class LinkedTreeMapIterator<T> implements Iterator<T> { Node<K, V> next = header.next; Node<K, V> lastReturned = null; int expectedModCount = modCount; public final boolean hasNext() { return next != header; } final Node<K, V> nextNode() { Node<K, V> e = next; if (e == header) { throw new NoSuchElementException(); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } next = e.next; return lastReturned = e; } public final void remove() { if (lastReturned == null) { throw new IllegalStateException(); } removeInternal(lastReturned, true); lastReturned = null; expectedModCount = modCount; } } final class EntrySet extends AbstractSet<Entry<K, V>> { @Override public int size() { return size; } @Override public Iterator<Entry<K, V>> iterator() { return new LinkedTreeMapIterator<Entry<K, V>>() { public Entry<K, V> next() { return nextNode(); } }; } @Override public boolean contains(Object o) { return o instanceof Entry && findByEntry((Entry<?, ?>) o) != null; } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Node<K, V> node = findByEntry((Entry<?, ?>) o); if (node == null) { return false; } removeInternal(node, true); return true; } @Override public void clear() { LinkedHashTreeMap.this.clear(); } } final class KeySet extends AbstractSet<K> { @Override public int size() { return size; } @Override public Iterator<K> iterator() { return new LinkedTreeMapIterator<K>() { public K next() { return nextNode().key; } }; } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object key) { return removeInternalByKey(key) != null; } @Override public void clear() { LinkedHashTreeMap.this.clear(); } } /** * If somebody is unlucky enough to have to serialize one of these, serialize * it as a LinkedHashMap so that they won't need Gson on the other side to * deserialize it. Using serialization defeats our DoS defence, so most apps * shouldn't use it. */ private Object writeReplace() throws ObjectStreamException { return new LinkedHashMap<>(this); } }
2,547
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/JsonDataException.java
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; import androidx.annotation.Nullable; /** * Thrown when the data in a JSON document doesn't match the data expected by the caller. For * example, suppose the application expects a boolean but the JSON document contains a string. When * the call to {@link JsonReader#nextBoolean} is made, a {@code JsonDataException} is thrown. * * <p>Exceptions of this type should be fixed by either changing the application code to accept * the unexpected JSON, or by changing the JSON to conform to the application's expectations. * * <p>This exception may also be triggered if a document's nesting exceeds 31 levels. This depth is * sufficient for all practical applications, but shallow enough to avoid uglier failures like * {@link StackOverflowError}. */ final class JsonDataException extends RuntimeException { JsonDataException(@Nullable String message) { super(message); } }
2,548
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/JsonReader.java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; /** * Reads a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>) * encoded value as a stream of tokens. This stream includes both literal * values (strings, numbers, booleans, and nulls) as well as the begin and * end delimiters of objects and arrays. The tokens are traversed in * depth-first order, the same order that they appear in the JSON document. * Within JSON objects, name/value pairs are represented by a single token. * * <h3>Parsing JSON</h3> * To create a recursive descent parser for your own JSON streams, first create * an entry point method that creates a {@code JsonReader}. * * <p>Next, create handler methods for each structure in your JSON text. You'll * need a method for each object type and for each array type. * <ul> * <li>Within <strong>array handling</strong> methods, first call {@link * #beginArray} to consume the array's opening bracket. Then create a * while loop that accumulates values, terminating when {@link #hasNext} * is false. Finally, read the array's closing bracket by calling {@link * #endArray}. * <li>Within <strong>object handling</strong> methods, first call {@link * #beginObject} to consume the object's opening brace. Then create a * while loop that assigns values to local variables based on their name. * This loop should terminate when {@link #hasNext} is false. Finally, * read the object's closing brace by calling {@link #endObject}. * </ul> * <p>When a nested object or array is encountered, delegate to the * corresponding handler method. * * <p>When an unknown name is encountered, strict parsers should fail with an * exception. Lenient parsers should call {@link #skipValue()} to recursively * skip the value's nested tokens, which may otherwise conflict. * * <p>If a value may be null, you should first check using {@link #peek()}. * Null literals can be consumed using {@link #skipValue()}. * * <h3>Example</h3> * Suppose we'd like to parse a stream of messages such as the following: <pre> {@code * [ * { * "id": 912345678901, * "text": "How do I read a JSON stream in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonReader!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ]}</pre> * This code implements the parser for the above structure: <pre> {@code * * public List<Message> readJsonStream(BufferedSource source) throws IOException { * JsonReader reader = JsonReader.of(source); * try { * return readMessagesArray(reader); * } finally { * reader.close(); * } * } * * public List<Message> readMessagesArray(JsonReader reader) throws IOException { * List<Message> messages = new ArrayList<Message>(); * * reader.beginArray(); * while (reader.hasNext()) { * messages.add(readMessage(reader)); * } * reader.endArray(); * return messages; * } * * public Message readMessage(JsonReader reader) throws IOException { * long id = -1; * String text = null; * User user = null; * List<Double> geo = null; * * reader.beginObject(); * while (reader.hasNext()) { * String name = reader.nextName(); * if (name.equals("id")) { * id = reader.nextLong(); * } else if (name.equals("text")) { * text = reader.nextString(); * } else if (name.equals("geo") && reader.peek() != Token.NULL) { * geo = readDoublesArray(reader); * } else if (name.equals("user")) { * user = readUser(reader); * } else { * reader.skipValue(); * } * } * reader.endObject(); * return new Message(id, text, user, geo); * } * * public List<Double> readDoublesArray(JsonReader reader) throws IOException { * List<Double> doubles = new ArrayList<Double>(); * * reader.beginArray(); * while (reader.hasNext()) { * doubles.add(reader.nextDouble()); * } * reader.endArray(); * return doubles; * } * * public User readUser(JsonReader reader) throws IOException { * String username = null; * int followersCount = -1; * * reader.beginObject(); * while (reader.hasNext()) { * String name = reader.nextName(); * if (name.equals("name")) { * username = reader.nextString(); * } else if (name.equals("followers_count")) { * followersCount = reader.nextInt(); * } else { * reader.skipValue(); * } * } * reader.endObject(); * return new User(username, followersCount); * }}</pre> * * <h3>Number Handling</h3> * This reader permits numeric values to be read as strings and string values to * be read as numbers. For example, both elements of the JSON array {@code * [1, "1"]} may be read using either {@link #nextInt} or {@link #nextString}. * This behavior is intended to prevent lossy numeric conversions: double is * JavaScript's only numeric type and very large values like {@code * 9007199254740993} cannot be represented exactly on that platform. To minimize * precision loss, extremely large values should be written and read as strings * in JSON. * * <p>Each {@code JsonReader} may be used to read a single JSON stream. Instances * of this class are not thread safe. */ public abstract class JsonReader implements Closeable { /* * From RFC 7159, "All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." * * We also escape '\u2028' and '\u2029', which JavaScript interprets as * newline characters. This prevents eval() from failing with a syntax * error. http://code.google.com/p/google-gson/issues/detail?id=341 */ private static final String[] REPLACEMENT_CHARS; static { REPLACEMENT_CHARS = new String[128]; for (int i = 0; i <= 0x1f; i++) { REPLACEMENT_CHARS[i] = String.format("\\u%04x", (int) i); } REPLACEMENT_CHARS['"'] = "\\\""; REPLACEMENT_CHARS['\\'] = "\\\\"; REPLACEMENT_CHARS['\t'] = "\\t"; REPLACEMENT_CHARS['\b'] = "\\b"; REPLACEMENT_CHARS['\n'] = "\\n"; REPLACEMENT_CHARS['\r'] = "\\r"; REPLACEMENT_CHARS['\f'] = "\\f"; } // The nesting stack. Using a manual array rather than an ArrayList saves 20%. This stack will // grow itself up to 256 levels of nesting including the top-level document. Deeper nesting is // prone to trigger StackOverflowErrors. int stackSize; int[] scopes; String[] pathNames; int[] pathIndices; /** * True to accept non-spec compliant JSON. */ boolean lenient; /** * True to throw a {@link JsonDataException} on any attempt to call {@link #skipValue()}. */ boolean failOnUnknown; /** * Returns a new instance that reads UTF-8 encoded JSON from {@code source}. */ public static JsonReader of(BufferedSource source) { return new JsonUtf8Reader(source); } // Package-private to control subclasses. JsonReader() { scopes = new int[32]; pathNames = new String[32]; pathIndices = new int[32]; } final void pushScope(int newTop) { if (stackSize == scopes.length) { if (stackSize == 256) { throw new JsonDataException("Nesting too deep at " + getPath()); } scopes = Arrays.copyOf(scopes, scopes.length * 2); pathNames = Arrays.copyOf(pathNames, pathNames.length * 2); pathIndices = Arrays.copyOf(pathIndices, pathIndices.length * 2); } scopes[stackSize++] = newTop; } /** * Throws a new IO exception with the given message and a context snippet * with this reader's content. */ final JsonEncodingException syntaxError(String message) throws JsonEncodingException { throw new JsonEncodingException(message + " at path " + getPath()); } /** * Consumes the next token from the JSON stream and asserts that it is the beginning of a new * array. */ public abstract void beginArray() throws IOException; /** * Consumes the next token from the JSON stream and asserts that it is the * end of the current array. */ public abstract void endArray() throws IOException; /** * Consumes the next token from the JSON stream and asserts that it is the beginning of a new * object. */ public abstract void beginObject() throws IOException; /** * Consumes the next token from the JSON stream and asserts that it is the end of the current * object. */ public abstract void endObject() throws IOException; /** * Returns true if the current array or object has another element. */ public abstract boolean hasNext() throws IOException; /** * Returns the type of the next token without consuming it. */ public abstract Token peek() throws IOException; /** * Returns the next token, a {@linkplain Token#NAME property name}, and consumes it. * * @throws JsonDataException if the next token in the stream is not a property name. */ public abstract String nextName() throws IOException; /** * If the next token is a {@linkplain Token#NAME property name} that's in {@code options}, this * consumes it and returns its index. Otherwise this returns -1 and no name is consumed. */ public abstract int selectName(Options options) throws IOException; /** * Skips the next token, consuming it. This method is intended for use when the JSON token stream * contains unrecognized or unhandled names. * * <p>This throws a {@link JsonDataException} if this parser has been configured to {@linkplain * #failOnUnknown fail on unknown} names. */ public abstract void skipName() throws IOException; /** * Returns the {@linkplain Token#STRING string} value of the next token, consuming it. If the next * token is a number, this method will return its string form. * * @throws JsonDataException if the next token is not a string or if this reader is closed. */ public abstract String nextString() throws IOException; /** * Returns the {@linkplain Token#BOOLEAN boolean} value of the next token, consuming it. * * @throws JsonDataException if the next token is not a boolean or if this reader is closed. */ public abstract boolean nextBoolean() throws IOException; /** * Returns the {@linkplain Token#NUMBER double} value of the next token, consuming it. If the next * token is a string, this method will attempt to parse it as a double using {@link * Double#parseDouble(String)}. * * @throws JsonDataException if the next token is not a literal value, or if the next literal * value cannot be parsed as a double, or is non-finite. */ public abstract double nextDouble() throws IOException; /** * Returns the {@linkplain Token#NUMBER int} value of the next token, consuming it. If the next * token is a string, this method will attempt to parse it as an int. If the next token's numeric * value cannot be exactly represented by a Java {@code int}, this method throws. * * @throws JsonDataException if the next token is not a literal value, if the next literal value * cannot be parsed as a number, or exactly represented as an int. */ public abstract int nextInt() throws IOException; /** * Skips the next value recursively. If it is an object or array, all nested elements are skipped. * This method is intended for use when the JSON token stream contains unrecognized or unhandled * values. * * <p>This throws a {@link JsonDataException} if this parser has been configured to {@linkplain * #failOnUnknown fail on unknown} values. */ public abstract void skipValue() throws IOException; /** * Returns a <a href="http://goessner.net/articles/JsonPath/">JsonPath</a> to * the current location in the JSON value. */ public final String getPath() { return JsonScope.getPath(stackSize, scopes, pathNames, pathIndices); } /** * A set of strings to be chosen with {@link #selectName}. This prepares * the encoded values of the strings so they can be read directly from the input source. */ public static final class Options { final String[] strings; final okio.Options doubleQuoteSuffix; private Options(String[] strings, okio.Options doubleQuoteSuffix) { this.strings = strings; this.doubleQuoteSuffix = doubleQuoteSuffix; } public static Options of(String... strings) { try { ByteString[] result = new ByteString[strings.length]; Buffer buffer = new Buffer(); for (int i = 0; i < strings.length; i++) { string(buffer, strings[i]); buffer.readByte(); // Skip the leading double quote (but leave the trailing one). result[i] = buffer.readByteString(); } return new Options(strings.clone(), okio.Options.of(result)); } catch (IOException e) { throw new AssertionError(e); } } } /** * Writes {@code value} as a string literal to {@code sink}. This wraps the value in double quotes * and escapes those characters that require it. */ private static void string(BufferedSink sink, String value) throws IOException { String[] replacements = REPLACEMENT_CHARS; sink.writeByte('"'); int last = 0; int length = value.length(); for (int i = 0; i < length; i++) { char c = value.charAt(i); String replacement; if (c < 128) { replacement = replacements[c]; if (replacement == null) { continue; } } else if (c == '\u2028') { replacement = "\\u2028"; } else if (c == '\u2029') { replacement = "\\u2029"; } else { continue; } if (last < i) { sink.writeUtf8(value, last, i); } sink.writeUtf8(replacement); last = i + 1; } if (last < length) { sink.writeUtf8(value, last, length); } sink.writeByte('"'); } /** * A structure, name, or value type in a JSON-encoded string. */ public enum Token { /** * The opening of a JSON array. * and read using {@link JsonReader#beginArray}. */ BEGIN_ARRAY, /** * The closing of a JSON array. * and read using {@link JsonReader#endArray}. */ END_ARRAY, /** * The opening of a JSON object. * and read using {@link JsonReader#beginObject}. */ BEGIN_OBJECT, /** * The closing of a JSON object. * and read using {@link JsonReader#endObject}. */ END_OBJECT, /** * A JSON property name. Within objects, tokens alternate between names and * their values. */ NAME, /** * A JSON string. */ STRING, /** * A JSON number represented in this API by a Java {@code double}, {@code * long}, or {@code int}. */ NUMBER, /** * A JSON {@code true} or {@code false}. */ BOOLEAN, /** * A JSON {@code null}. */ NULL, /** * The end of the JSON stream. This sentinel value is returned by {@link * JsonReader#peek()} to signal that the JSON-encoded value has no more * tokens. */ END_DOCUMENT } }
2,549
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/JsonUtf8Reader.java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; import androidx.annotation.Nullable; import java.io.EOFException; import java.io.IOException; import okio.Buffer; import okio.BufferedSource; import okio.ByteString; final class JsonUtf8Reader extends JsonReader { private static final long MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10; private static final ByteString SINGLE_QUOTE_OR_SLASH = ByteString.encodeUtf8("'\\"); private static final ByteString DOUBLE_QUOTE_OR_SLASH = ByteString.encodeUtf8("\"\\"); private static final ByteString UNQUOTED_STRING_TERMINALS = ByteString.encodeUtf8("{}[]:, \n\t\r\f/\\;#="); private static final ByteString LINEFEED_OR_CARRIAGE_RETURN = ByteString.encodeUtf8("\n\r"); private static final ByteString CLOSING_BLOCK_COMMENT = ByteString.encodeUtf8("*/"); private static final int PEEKED_NONE = 0; private static final int PEEKED_BEGIN_OBJECT = 1; private static final int PEEKED_END_OBJECT = 2; private static final int PEEKED_BEGIN_ARRAY = 3; private static final int PEEKED_END_ARRAY = 4; private static final int PEEKED_TRUE = 5; private static final int PEEKED_FALSE = 6; private static final int PEEKED_NULL = 7; private static final int PEEKED_SINGLE_QUOTED = 8; private static final int PEEKED_DOUBLE_QUOTED = 9; private static final int PEEKED_UNQUOTED = 10; /** * When this is returned, the string value is stored in peekedString. */ private static final int PEEKED_BUFFERED = 11; private static final int PEEKED_SINGLE_QUOTED_NAME = 12; private static final int PEEKED_DOUBLE_QUOTED_NAME = 13; private static final int PEEKED_UNQUOTED_NAME = 14; private static final int PEEKED_BUFFERED_NAME = 15; /** * When this is returned, the integer value is stored in peekedLong. */ private static final int PEEKED_LONG = 16; private static final int PEEKED_NUMBER = 17; private static final int PEEKED_EOF = 18; /* State machine when parsing numbers */ private static final int NUMBER_CHAR_NONE = 0; private static final int NUMBER_CHAR_SIGN = 1; private static final int NUMBER_CHAR_DIGIT = 2; private static final int NUMBER_CHAR_DECIMAL = 3; private static final int NUMBER_CHAR_FRACTION_DIGIT = 4; private static final int NUMBER_CHAR_EXP_E = 5; private static final int NUMBER_CHAR_EXP_SIGN = 6; private static final int NUMBER_CHAR_EXP_DIGIT = 7; /** * The input JSON. */ private final BufferedSource source; private final Buffer buffer; private int peeked = PEEKED_NONE; /** * A peeked value that was composed entirely of digits with an optional * leading dash. Positive values may not have a leading 0. */ private long peekedLong; /** * The number of characters in a peeked number literal. */ private int peekedNumberLength; /** * A peeked string that should be parsed on the next double, long or string. * This is populated before a numeric value is parsed and used if that parsing * fails. */ private @Nullable String peekedString; JsonUtf8Reader(BufferedSource source) { if (source == null) { throw new NullPointerException("source == null"); } this.source = source; // Don't use source.getBuffer(). Because android studio use old version okio instead of your own okio. this.buffer = source.buffer(); pushScope(JsonScope.EMPTY_DOCUMENT); } @Override public void beginArray() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_BEGIN_ARRAY) { pushScope(JsonScope.EMPTY_ARRAY); pathIndices[stackSize - 1] = 0; peeked = PEEKED_NONE; } else { throw new JsonDataException("Expected BEGIN_ARRAY but was " + peek() + " at path " + getPath()); } } @Override public void endArray() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_END_ARRAY) { stackSize--; pathIndices[stackSize - 1]++; peeked = PEEKED_NONE; } else { throw new JsonDataException("Expected END_ARRAY but was " + peek() + " at path " + getPath()); } } @Override public void beginObject() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_BEGIN_OBJECT) { pushScope(JsonScope.EMPTY_OBJECT); peeked = PEEKED_NONE; } else { throw new JsonDataException("Expected BEGIN_OBJECT but was " + peek() + " at path " + getPath()); } } @Override public void endObject() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_END_OBJECT) { stackSize--; pathNames[stackSize] = null; // Free the last path name so that it can be garbage collected! pathIndices[stackSize - 1]++; peeked = PEEKED_NONE; } else { throw new JsonDataException("Expected END_OBJECT but was " + peek() + " at path " + getPath()); } } @Override public boolean hasNext() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY && p != PEEKED_EOF; } @Override public Token peek() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } switch (p) { case PEEKED_BEGIN_OBJECT: return Token.BEGIN_OBJECT; case PEEKED_END_OBJECT: return Token.END_OBJECT; case PEEKED_BEGIN_ARRAY: return Token.BEGIN_ARRAY; case PEEKED_END_ARRAY: return Token.END_ARRAY; case PEEKED_SINGLE_QUOTED_NAME: case PEEKED_DOUBLE_QUOTED_NAME: case PEEKED_UNQUOTED_NAME: case PEEKED_BUFFERED_NAME: return Token.NAME; case PEEKED_TRUE: case PEEKED_FALSE: return Token.BOOLEAN; case PEEKED_NULL: return Token.NULL; case PEEKED_SINGLE_QUOTED: case PEEKED_DOUBLE_QUOTED: case PEEKED_UNQUOTED: case PEEKED_BUFFERED: return Token.STRING; case PEEKED_LONG: case PEEKED_NUMBER: return Token.NUMBER; case PEEKED_EOF: return Token.END_DOCUMENT; default: throw new AssertionError(); } } private int doPeek() throws IOException { int peekStack = scopes[stackSize - 1]; if (peekStack == JsonScope.EMPTY_ARRAY) { scopes[stackSize - 1] = JsonScope.NONEMPTY_ARRAY; } else if (peekStack == JsonScope.NONEMPTY_ARRAY) { // Look for a comma before the next element. int c = nextNonWhitespace(true); buffer.readByte(); // consume ']' or ','. switch (c) { case ']': return peeked = PEEKED_END_ARRAY; case ';': checkLenient(); // fall-through case ',': break; default: throw syntaxError("Unterminated array"); } } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) { scopes[stackSize - 1] = JsonScope.DANGLING_NAME; // Look for a comma before the next element. if (peekStack == JsonScope.NONEMPTY_OBJECT) { int c = nextNonWhitespace(true); buffer.readByte(); // Consume '}' or ','. switch (c) { case '}': return peeked = PEEKED_END_OBJECT; case ';': checkLenient(); // fall-through case ',': break; default: throw syntaxError("Unterminated object"); } } int c = nextNonWhitespace(true); switch (c) { case '"': buffer.readByte(); // consume the '\"'. return peeked = PEEKED_DOUBLE_QUOTED_NAME; case '\'': buffer.readByte(); // consume the '\''. checkLenient(); return peeked = PEEKED_SINGLE_QUOTED_NAME; case '}': if (peekStack != JsonScope.NONEMPTY_OBJECT) { buffer.readByte(); // consume the '}'. return peeked = PEEKED_END_OBJECT; } else { throw syntaxError("Expected name"); } default: checkLenient(); if (isLiteral((char) c)) { return peeked = PEEKED_UNQUOTED_NAME; } else { throw syntaxError("Expected name"); } } } else if (peekStack == JsonScope.DANGLING_NAME) { scopes[stackSize - 1] = JsonScope.NONEMPTY_OBJECT; // Look for a colon before the value. int c = nextNonWhitespace(true); buffer.readByte(); // Consume ':'. switch (c) { case ':': break; case '=': checkLenient(); if (source.request(1) && buffer.getByte(0) == '>') { buffer.readByte(); // Consume '>'. } break; default: throw syntaxError("Expected ':'"); } } else if (peekStack == JsonScope.EMPTY_DOCUMENT) { scopes[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT; } else if (peekStack == JsonScope.NONEMPTY_DOCUMENT) { int c = nextNonWhitespace(false); if (c == -1) { return peeked = PEEKED_EOF; } else { checkLenient(); } } else if (peekStack == JsonScope.CLOSED) { throw new IllegalStateException("JsonReader is closed"); } int c = nextNonWhitespace(true); switch (c) { case ']': if (peekStack == JsonScope.EMPTY_ARRAY) { buffer.readByte(); // Consume ']'. return peeked = PEEKED_END_ARRAY; } // fall-through to handle ",]" case ';': case ',': // In lenient mode, a 0-length literal in an array means 'null'. if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) { checkLenient(); return peeked = PEEKED_NULL; } else { throw syntaxError("Unexpected value"); } case '\'': checkLenient(); buffer.readByte(); // Consume '\''. return peeked = PEEKED_SINGLE_QUOTED; case '"': buffer.readByte(); // Consume '\"'. return peeked = PEEKED_DOUBLE_QUOTED; case '[': buffer.readByte(); // Consume '['. return peeked = PEEKED_BEGIN_ARRAY; case '{': buffer.readByte(); // Consume '{'. return peeked = PEEKED_BEGIN_OBJECT; default: } int result = peekKeyword(); if (result != PEEKED_NONE) { return result; } result = peekNumber(); if (result != PEEKED_NONE) { return result; } if (!isLiteral(buffer.getByte(0))) { throw syntaxError("Expected value"); } checkLenient(); return peeked = PEEKED_UNQUOTED; } private int peekKeyword() throws IOException { // Figure out which keyword we're matching against by its first character. byte c = buffer.getByte(0); String keyword; String keywordUpper; int peeking; if (c == 't' || c == 'T') { keyword = "true"; keywordUpper = "TRUE"; peeking = PEEKED_TRUE; } else if (c == 'f' || c == 'F') { keyword = "false"; keywordUpper = "FALSE"; peeking = PEEKED_FALSE; } else if (c == 'n' || c == 'N') { keyword = "null"; keywordUpper = "NULL"; peeking = PEEKED_NULL; } else { return PEEKED_NONE; } // Confirm that chars [1..length) match the keyword. int length = keyword.length(); for (int i = 1; i < length; i++) { if (!source.request(i + 1)) { return PEEKED_NONE; } c = buffer.getByte(i); if (c != keyword.charAt(i) && c != keywordUpper.charAt(i)) { return PEEKED_NONE; } } if (source.request(length + 1) && isLiteral(buffer.getByte(length))) { return PEEKED_NONE; // Don't match trues, falsey or nullsoft! } // We've found the keyword followed either by EOF or by a non-literal character. buffer.skip(length); return peeked = peeking; } private int peekNumber() throws IOException { long value = 0; // Negative to accommodate Long.MIN_VALUE more easily. boolean negative = false; boolean fitsInLong = true; int last = NUMBER_CHAR_NONE; int i = 0; charactersOfNumber: for (; true; i++) { if (!source.request(i + 1)) { break; } byte c = buffer.getByte(i); switch (c) { case '-': if (last == NUMBER_CHAR_NONE) { negative = true; last = NUMBER_CHAR_SIGN; continue; } else if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case '+': if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case 'e': case 'E': if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) { last = NUMBER_CHAR_EXP_E; continue; } return PEEKED_NONE; case '.': if (last == NUMBER_CHAR_DIGIT) { last = NUMBER_CHAR_DECIMAL; continue; } return PEEKED_NONE; default: if (c < '0' || c > '9') { if (!isLiteral(c)) { break charactersOfNumber; } return PEEKED_NONE; } if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) { value = -(c - '0'); last = NUMBER_CHAR_DIGIT; } else if (last == NUMBER_CHAR_DIGIT) { if (value == 0) { return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal). } long newValue = value * 10 - (c - '0'); fitsInLong &= value > MIN_INCOMPLETE_INTEGER || (value == MIN_INCOMPLETE_INTEGER && newValue < value); value = newValue; } else if (last == NUMBER_CHAR_DECIMAL) { last = NUMBER_CHAR_FRACTION_DIGIT; } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) { last = NUMBER_CHAR_EXP_DIGIT; } } } // We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER. if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value != 0 || !negative)) { peekedLong = negative ? value : -value; buffer.skip(i); return peeked = PEEKED_LONG; } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) { peekedNumberLength = i; return peeked = PEEKED_NUMBER; } else { return PEEKED_NONE; } } private boolean isLiteral(int c) throws IOException { switch (c) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': return false; default: return true; } } @Override public String nextName() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED_NAME) { result = nextUnquotedValue(); } else if (p == PEEKED_DOUBLE_QUOTED_NAME) { result = nextQuotedValue(DOUBLE_QUOTE_OR_SLASH); } else if (p == PEEKED_SINGLE_QUOTED_NAME) { result = nextQuotedValue(SINGLE_QUOTE_OR_SLASH); } else if (p == PEEKED_BUFFERED_NAME) { result = peekedString; } else { throw new JsonDataException("Expected a name but was " + peek() + " at path " + getPath()); } peeked = PEEKED_NONE; pathNames[stackSize - 1] = result; return result; } @Override public int selectName(Options options) throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p < PEEKED_SINGLE_QUOTED_NAME || p > PEEKED_BUFFERED_NAME) { return -1; } if (p == PEEKED_BUFFERED_NAME) { return findName(peekedString, options); } int result = source.select(options.doubleQuoteSuffix); if (result != -1) { peeked = PEEKED_NONE; pathNames[stackSize - 1] = options.strings[result]; return result; } // The next name may be unnecessary escaped. Save the last recorded path name, so that we // can restore the peek state in case we fail to find a match. String lastPathName = pathNames[stackSize - 1]; String nextName = nextName(); result = findName(nextName, options); if (result == -1) { peeked = PEEKED_BUFFERED_NAME; peekedString = nextName; // We can't push the path further, make it seem like nothing happened. pathNames[stackSize - 1] = lastPathName; } return result; } @Override public void skipName() throws IOException { if (failOnUnknown) { throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath()); } int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_UNQUOTED_NAME) { skipUnquotedValue(); } else if (p == PEEKED_DOUBLE_QUOTED_NAME) { skipQuotedValue(DOUBLE_QUOTE_OR_SLASH); } else if (p == PEEKED_SINGLE_QUOTED_NAME) { skipQuotedValue(SINGLE_QUOTE_OR_SLASH); } else if (p != PEEKED_BUFFERED_NAME) { throw new JsonDataException("Expected a name but was " + peek() + " at path " + getPath()); } peeked = PEEKED_NONE; pathNames[stackSize - 1] = "null"; } /** * If {@code name} is in {@code options} this consumes it and returns its index. * Otherwise this returns -1 and no name is consumed. */ private int findName(String name, Options options) { for (int i = 0, size = options.strings.length; i < size; i++) { if (name.equals(options.strings[i])) { peeked = PEEKED_NONE; pathNames[stackSize - 1] = name; return i; } } return -1; } @Override public String nextString() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED) { result = nextUnquotedValue(); } else if (p == PEEKED_DOUBLE_QUOTED) { result = nextQuotedValue(DOUBLE_QUOTE_OR_SLASH); } else if (p == PEEKED_SINGLE_QUOTED) { result = nextQuotedValue(SINGLE_QUOTE_OR_SLASH); } else if (p == PEEKED_BUFFERED) { result = peekedString; peekedString = null; } else if (p == PEEKED_LONG) { result = Long.toString(peekedLong); } else if (p == PEEKED_NUMBER) { result = buffer.readUtf8(peekedNumberLength); } else { throw new JsonDataException("Expected a string but was " + peek() + " at path " + getPath()); } peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return result; } @Override public boolean nextBoolean() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_TRUE) { peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return true; } else if (p == PEEKED_FALSE) { peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return false; } throw new JsonDataException("Expected a boolean but was " + peek() + " at path " + getPath()); } @Override public double nextDouble() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_LONG) { peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return (double) peekedLong; } if (p == PEEKED_NUMBER) { peekedString = buffer.readUtf8(peekedNumberLength); } else if (p == PEEKED_DOUBLE_QUOTED) { peekedString = nextQuotedValue(DOUBLE_QUOTE_OR_SLASH); } else if (p == PEEKED_SINGLE_QUOTED) { peekedString = nextQuotedValue(SINGLE_QUOTE_OR_SLASH); } else if (p == PEEKED_UNQUOTED) { peekedString = nextUnquotedValue(); } else if (p != PEEKED_BUFFERED) { throw new JsonDataException("Expected a double but was " + peek() + " at path " + getPath()); } peeked = PEEKED_BUFFERED; double result; try { result = Double.parseDouble(peekedString); } catch (NumberFormatException e) { throw new JsonDataException("Expected a double but was " + peekedString + " at path " + getPath()); } if (!lenient && (Double.isNaN(result) || Double.isInfinite(result))) { throw new JsonEncodingException("JSON forbids NaN and infinities: " + result + " at path " + getPath()); } peekedString = null; peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return result; } /** * Returns the string up to but not including {@code quote}, unescaping any character escape * sequences encountered along the way. The opening quote should have already been read. This * consumes the closing quote, but does not include it in the returned string. * * @throws IOException if any unicode escape sequences are malformed. */ private String nextQuotedValue(ByteString runTerminator) throws IOException { StringBuilder builder = null; while (true) { long index = source.indexOfElement(runTerminator); if (index == -1L) { throw syntaxError("Unterminated string"); } // If we've got an escape character, we're going to need a string builder. if (buffer.getByte(index) == '\\') { if (builder == null) { builder = new StringBuilder(); } builder.append(buffer.readUtf8(index)); buffer.readByte(); // '\' builder.append(readEscapeCharacter()); continue; } // If it isn't the escape character, it's the quote. Return the string. if (builder == null) { String result = buffer.readUtf8(index); buffer.readByte(); // Consume the quote character. return result; } else { builder.append(buffer.readUtf8(index)); buffer.readByte(); // Consume the quote character. return builder.toString(); } } } /** * Returns an unquoted value as a string. */ private String nextUnquotedValue() throws IOException { long i = source.indexOfElement(UNQUOTED_STRING_TERMINALS); return i != -1 ? buffer.readUtf8(i) : buffer.readUtf8(); } private void skipQuotedValue(ByteString runTerminator) throws IOException { while (true) { long index = source.indexOfElement(runTerminator); if (index == -1L) { throw syntaxError("Unterminated string"); } if (buffer.getByte(index) == '\\') { buffer.skip(index + 1); readEscapeCharacter(); } else { buffer.skip(index + 1); return; } } } private void skipUnquotedValue() throws IOException { long i = source.indexOfElement(UNQUOTED_STRING_TERMINALS); buffer.skip(i != -1L ? i : buffer.size()); } @Override public int nextInt() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } int result; if (p == PEEKED_LONG) { result = (int) peekedLong; if (peekedLong != result) { // Make sure no precision was lost casting to 'int'. throw new JsonDataException("Expected an int but was " + peekedLong + " at path " + getPath()); } peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return result; } if (p == PEEKED_NUMBER) { peekedString = buffer.readUtf8(peekedNumberLength); } else if (p == PEEKED_DOUBLE_QUOTED || p == PEEKED_SINGLE_QUOTED) { peekedString = p == PEEKED_DOUBLE_QUOTED ? nextQuotedValue(DOUBLE_QUOTE_OR_SLASH) : nextQuotedValue(SINGLE_QUOTE_OR_SLASH); try { result = Integer.parseInt(peekedString); peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return result; } catch (NumberFormatException ignored) { // Fall back to parse as a double below. } } else if (p != PEEKED_BUFFERED) { throw new JsonDataException("Expected an int but was " + peek() + " at path " + getPath()); } peeked = PEEKED_BUFFERED; double asDouble; try { asDouble = Double.parseDouble(peekedString); } catch (NumberFormatException e) { throw new JsonDataException("Expected an int but was " + peekedString + " at path " + getPath()); } result = (int) asDouble; if (result != asDouble) { // Make sure no precision was lost casting to 'int'. throw new JsonDataException("Expected an int but was " + peekedString + " at path " + getPath()); } peekedString = null; peeked = PEEKED_NONE; pathIndices[stackSize - 1]++; return result; } @Override public void close() throws IOException { peeked = PEEKED_NONE; scopes[0] = JsonScope.CLOSED; stackSize = 1; buffer.clear(); source.close(); } @Override public void skipValue() throws IOException { if (failOnUnknown) { throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath()); } int count = 0; do { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_BEGIN_ARRAY) { pushScope(JsonScope.EMPTY_ARRAY); count++; } else if (p == PEEKED_BEGIN_OBJECT) { pushScope(JsonScope.EMPTY_OBJECT); count++; } else if (p == PEEKED_END_ARRAY) { count--; if (count < 0) { throw new JsonDataException( "Expected a value but was " + peek() + " at path " + getPath()); } stackSize--; } else if (p == PEEKED_END_OBJECT) { count--; if (count < 0) { throw new JsonDataException( "Expected a value but was " + peek() + " at path " + getPath()); } stackSize--; } else if (p == PEEKED_UNQUOTED_NAME || p == PEEKED_UNQUOTED) { skipUnquotedValue(); } else if (p == PEEKED_DOUBLE_QUOTED || p == PEEKED_DOUBLE_QUOTED_NAME) { skipQuotedValue(DOUBLE_QUOTE_OR_SLASH); } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_SINGLE_QUOTED_NAME) { skipQuotedValue(SINGLE_QUOTE_OR_SLASH); } else if (p == PEEKED_NUMBER) { buffer.skip(peekedNumberLength); } else if (p == PEEKED_EOF) { throw new JsonDataException( "Expected a value but was " + peek() + " at path " + getPath()); } peeked = PEEKED_NONE; } while (count != 0); pathIndices[stackSize - 1]++; pathNames[stackSize - 1] = "null"; } /** * Returns the next character in the stream that is neither whitespace nor a * part of a comment. When this returns, the returned character is always at * {@code buffer.getByte(0)}. */ private int nextNonWhitespace(boolean throwOnEof) throws IOException { /* * This code uses ugly local variables 'p' and 'l' representing the 'pos' * and 'limit' fields respectively. Using locals rather than fields saves * a few field reads for each whitespace character in a pretty-printed * document, resulting in a 5% speedup. We need to flush 'p' to its field * before any (potentially indirect) call to fillBuffer() and reread both * 'p' and 'l' after any (potentially indirect) call to the same method. */ int p = 0; while (source.request(p + 1)) { int c = buffer.getByte(p++); if (c == '\n' || c == ' ' || c == '\r' || c == '\t') { continue; } buffer.skip(p - 1); if (c == '/') { if (!source.request(2)) { return c; } checkLenient(); byte peek = buffer.getByte(1); switch (peek) { case '*': // skip a /* c-style comment */ buffer.readByte(); // '/' buffer.readByte(); // '*' if (!skipToEndOfBlockComment()) { throw syntaxError("Unterminated comment"); } p = 0; continue; case '/': // skip a // end-of-line comment buffer.readByte(); // '/' buffer.readByte(); // '/' skipToEndOfLine(); p = 0; continue; default: return c; } } else if (c == '#') { // Skip a # hash end-of-line comment. The JSON RFC doesn't specify this behaviour, but it's // required to parse existing documents. checkLenient(); skipToEndOfLine(); p = 0; } else { return c; } } if (throwOnEof) { throw new EOFException("End of input"); } else { return -1; } } private void checkLenient() throws IOException { if (!lenient) { throw syntaxError("Use JsonReader.setLenient(true) to accept malformed JSON"); } } /** * Advances the position until after the next newline character. If the line * is terminated by "\r\n", the '\n' must be consumed as whitespace by the * caller. */ private void skipToEndOfLine() throws IOException { long index = source.indexOfElement(LINEFEED_OR_CARRIAGE_RETURN); buffer.skip(index != -1 ? index + 1 : buffer.size()); } /** * Skips through the next closing block comment. */ private boolean skipToEndOfBlockComment() throws IOException { long index = source.indexOf(CLOSING_BLOCK_COMMENT); boolean found = index != -1; buffer.skip(found ? index + CLOSING_BLOCK_COMMENT.size() : buffer.size()); return found; } @Override public String toString() { return "JsonReader(" + source + ")"; } /** * Unescapes the character identified by the character or characters that immediately follow a * backslash. The backslash '\' should have already been read. This supports both unicode escapes * "u000A" and two-character escapes "\n". * * @throws IOException if any unicode escape sequences are malformed. */ private char readEscapeCharacter() throws IOException { if (!source.request(1)) { throw syntaxError("Unterminated escape sequence"); } byte escaped = buffer.readByte(); switch (escaped) { case 'u': if (!source.request(4)) { throw new EOFException("Unterminated escape sequence at path " + getPath()); } // Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16); char result = 0; for (int i = 0, end = i + 4; i < end; i++) { byte c = buffer.getByte(i); result <<= 4; if (c >= '0' && c <= '9') { result += (c - '0'); } else if (c >= 'a' && c <= 'f') { result += (c - 'a' + 10); } else if (c >= 'A' && c <= 'F') { result += (c - 'A' + 10); } else { throw syntaxError("\\u" + buffer.readUtf8(4)); } } buffer.skip(4); return result; case 't': return '\t'; case 'b': return '\b'; case 'n': return '\n'; case 'r': return '\r'; case 'f': return '\f'; case '\n': case '\'': case '"': case '\\': case '/': return (char) escaped; default: if (!lenient) { throw syntaxError("Invalid escape sequence: \\" + (char) escaped); } return (char) escaped; } } }
2,550
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/JsonEncodingException.java
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.lottie.parser.moshi; import androidx.annotation.Nullable; import java.io.IOException; /** * Thrown when the data being parsed is not encoded as valid JSON. */ final class JsonEncodingException extends IOException { JsonEncodingException(@Nullable String message) { super(message); } }
2,551
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/parser/moshi/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.parser.moshi; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,552
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/manager/ImageAssetManager.java
package com.airbnb.lottie.manager; import android.app.Application; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.Base64; import android.view.View; import androidx.annotation.Nullable; import com.airbnb.lottie.ImageAssetDelegate; import com.airbnb.lottie.LottieImageAsset; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.util.Map; public class ImageAssetManager { private static final Object bitmapHashLock = new Object(); @Nullable private final Context context; private final String imagesFolder; @Nullable private ImageAssetDelegate delegate; private final Map<String, LottieImageAsset> imageAssets; public ImageAssetManager(Drawable.Callback callback, String imagesFolder, ImageAssetDelegate delegate, Map<String, LottieImageAsset> imageAssets) { if (!TextUtils.isEmpty(imagesFolder) && imagesFolder.charAt(imagesFolder.length() - 1) != '/') { this.imagesFolder = imagesFolder + '/'; } else { this.imagesFolder = imagesFolder; } this.imageAssets = imageAssets; setDelegate(delegate); if (!(callback instanceof View)) { context = null; return; } context = ((View) callback).getContext().getApplicationContext(); } public void setDelegate(@Nullable ImageAssetDelegate assetDelegate) { this.delegate = assetDelegate; } /** * Returns the previously set bitmap or null. */ @Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { if (bitmap == null) { LottieImageAsset asset = imageAssets.get(id); Bitmap ret = asset.getBitmap(); asset.setBitmap(null); return ret; } Bitmap prevBitmap = imageAssets.get(id).getBitmap(); putBitmap(id, bitmap); return prevBitmap; } @Nullable public LottieImageAsset getImageAssetById(String id) { return imageAssets.get(id); } @Nullable public Bitmap bitmapForId(String id) { LottieImageAsset asset = imageAssets.get(id); if (asset == null) { return null; } Bitmap bitmap = asset.getBitmap(); if (bitmap != null) { return bitmap; } if (delegate != null) { bitmap = delegate.fetchBitmap(asset); if (bitmap != null) { putBitmap(id, bitmap); } return bitmap; } Context context = this.context; if (context == null) { // If there is no context, the image has to be embedded or provided via // a delegate. 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; } bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts); return putBitmap(id, bitmap); } InputStream is; try { if (TextUtils.isEmpty(imagesFolder)) { throw new IllegalStateException("You must set an images folder before loading an image." + " Set it with LottieComposition#setImagesFolder or LottieDrawable#setImagesFolder"); } is = context.getAssets().open(imagesFolder + filename); } catch (IOException e) { Logger.warning("Unable to open asset.", e); return null; } try { bitmap = BitmapFactory.decodeStream(is, null, opts); } catch (IllegalArgumentException e) { Logger.warning("Unable to decode image `" + id + "`.", e); return null; } if (bitmap == null) { Logger.warning("Decoded image `" + id + "` is null."); return null; } bitmap = Utils.resizeBitmapIfNeeded(bitmap, asset.getWidth(), asset.getHeight()); return putBitmap(id, bitmap); } public boolean hasSameContext(Context context) { Context contextToCompare = this.context instanceof Application ? context.getApplicationContext() : context; return contextToCompare == this.context; } private Bitmap putBitmap(String key, @Nullable Bitmap bitmap) { synchronized (bitmapHashLock) { imageAssets.get(key).setBitmap(bitmap); return bitmap; } } }
2,553
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/manager/FontAssetManager.java
package com.airbnb.lottie.manager; import android.content.res.AssetManager; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.view.View; import androidx.annotation.Nullable; import com.airbnb.lottie.FontAssetDelegate; import com.airbnb.lottie.model.Font; import com.airbnb.lottie.model.MutablePair; import com.airbnb.lottie.utils.Logger; import java.util.HashMap; import java.util.Map; public class FontAssetManager { private final MutablePair<String> tempPair = new MutablePair<>(); /** * Pair is (fontName, fontStyle) */ private final Map<MutablePair<String>, Typeface> fontMap = new HashMap<>(); /** * Map of font families to their fonts. Necessary to create a font with a different style */ private final Map<String, Typeface> fontFamilies = new HashMap<>(); private final AssetManager assetManager; @Nullable private FontAssetDelegate delegate; private String defaultFontFileExtension = ".ttf"; public FontAssetManager(Drawable.Callback callback, @Nullable FontAssetDelegate delegate) { this.delegate = delegate; if (!(callback instanceof View)) { Logger.warning("LottieDrawable must be inside of a view for images to work."); assetManager = null; return; } assetManager = ((View) callback).getContext().getAssets(); } public void setDelegate(@Nullable FontAssetDelegate assetDelegate) { this.delegate = assetDelegate; } /** * Sets the default file extension (include the `.`). * <p> * e.g. `.ttf` `.otf` * <p> * Defaults to `.ttf` */ @SuppressWarnings("unused") public void setDefaultFontFileExtension(String defaultFontFileExtension) { this.defaultFontFileExtension = defaultFontFileExtension; } public Typeface getTypeface(Font font) { tempPair.set(font.getFamily(), font.getStyle()); Typeface typeface = fontMap.get(tempPair); if (typeface != null) { return typeface; } Typeface typefaceWithDefaultStyle = getFontFamily(font); typeface = typefaceForStyle(typefaceWithDefaultStyle, font.getStyle()); fontMap.put(tempPair, typeface); return typeface; } private Typeface getFontFamily(Font font) { String fontFamily = font.getFamily(); Typeface defaultTypeface = fontFamilies.get(fontFamily); if (defaultTypeface != null) { return defaultTypeface; } Typeface typeface = null; String fontStyle = font.getStyle(); String fontName = font.getName(); if (delegate != null) { typeface = delegate.fetchFont(fontFamily, fontStyle, fontName); if (typeface == null) { typeface = delegate.fetchFont(fontFamily); } } if (delegate != null && typeface == null) { String path = delegate.getFontPath(fontFamily, fontStyle, fontName); if (path == null) { path = delegate.getFontPath(fontFamily); } if (path != null) { typeface = Typeface.createFromAsset(assetManager, path); } } if (font.getTypeface() != null) { return font.getTypeface(); } if (typeface == null) { String path = "fonts/" + fontFamily + defaultFontFileExtension; typeface = Typeface.createFromAsset(assetManager, path); } fontFamilies.put(fontFamily, typeface); return typeface; } private Typeface typefaceForStyle(Typeface typeface, String style) { int styleInt = Typeface.NORMAL; boolean containsItalic = style.contains("Italic"); boolean containsBold = style.contains("Bold"); if (containsItalic && containsBold) { styleInt = Typeface.BOLD_ITALIC; } else if (containsItalic) { styleInt = Typeface.ITALIC; } else if (containsBold) { styleInt = Typeface.BOLD; } if (typeface.getStyle() == styleInt) { return typeface; } return Typeface.create(typeface, styleInt); } }
2,554
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/manager/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.manager; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,555
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/LottieCompositionCache.java
package com.airbnb.lottie.model; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import androidx.collection.LruCache; import com.airbnb.lottie.LottieComposition; @RestrictTo(RestrictTo.Scope.LIBRARY) public class LottieCompositionCache { private static final LottieCompositionCache INSTANCE = new LottieCompositionCache(); public static LottieCompositionCache getInstance() { return INSTANCE; } private final LruCache<String, LottieComposition> cache = new LruCache<>(20); @VisibleForTesting LottieCompositionCache() { } @Nullable public LottieComposition get(@Nullable String cacheKey) { if (cacheKey == null) { return null; } return cache.get(cacheKey); } public void put(@Nullable String cacheKey, LottieComposition composition) { if (cacheKey == null) { return; } cache.put(cacheKey, composition); } public void clear() { cache.evictAll(); } /** * Set the maximum number of compositions to keep cached in memory. * This must be {@literal >} 0. */ public void resize(int size) { cache.resize(size); } }
2,556
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/Font.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import android.graphics.Typeface; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; @RestrictTo(LIBRARY) public class Font { private final String family; private final String name; private final String style; private final float ascent; @Nullable private Typeface typeface; public Font(String family, String name, String style, float ascent) { this.family = family; this.name = name; this.style = style; this.ascent = ascent; } @SuppressWarnings("unused") public String getFamily() { return family; } public String getName() { return name; } public String getStyle() { return style; } @SuppressWarnings("unused") float getAscent() { return ascent; } @Nullable public Typeface getTypeface() { return typeface; } public void setTypeface(@Nullable Typeface typeface) { this.typeface = typeface; } }
2,557
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/MutablePair.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.util.Pair; /** * Non final version of {@link Pair}. */ @RestrictTo(LIBRARY) public class MutablePair<T> { @Nullable T first; @Nullable T second; public void set(T first, T second) { this.first = first; this.second = second; } /** * Checks the two objects for equality by delegating to their respective * {@link Object#equals(Object)} methods. * * @param o the {@link Pair} to which this one is to be checked for equality * @return true if the underlying objects of the Pair are both considered * equal */ @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return objectsEqual(p.first, first) && objectsEqual(p.second, second); } private static boolean objectsEqual(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Compute a hash code using the hash codes of the underlying objects * * @return a hashcode of the Pair */ @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } @Override public String toString() { return "Pair{" + first + " " + second + "}"; } }
2,558
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/KeyPath.java
package com.airbnb.lottie.model; import androidx.annotation.CheckResult; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Defines which content to target. * The keypath can contain wildcards ('*') with match exactly 1 item. * or globstars ('**') which match 0 or more items. or KeyPath.COMPOSITION * to represent the root composition layer. * <p> * For example, if your content were arranged like this: * Gabriel (Shape Layer) * Body (Shape Group) * Left Hand (Shape) * Fill (Fill) * Transform (Transform) * ... * Brandon (Shape Layer) * Body (Shape Group) * Left Hand (Shape) * Fill (Fill) * Transform (Transform) * ... * <p> * <p> * You could: * Match Gabriel left hand fill: * new KeyPath("Gabriel", "Body", "Left Hand", "Fill"); * Match Gabriel and Brandon's left hand fill: * new KeyPath("*", "Body", Left Hand", "Fill"); * Match anything with the name Fill: * new KeyPath("**", "Fill"); * Target the the root composition layer: * KeyPath.COMPOSITION * <p> * <p> * NOTE: Content that are part of merge paths or repeaters cannot currently be resolved with * a {@link KeyPath}. This may be fixed in the future. */ public class KeyPath { /** * A singleton KeyPath that targets on the root composition layer. * This is useful if you want to apply transformer to the animation as a whole. */ public final static KeyPath COMPOSITION = new KeyPath("COMPOSITION"); private final List<String> keys; @Nullable private KeyPathElement resolvedElement; public KeyPath(String... keys) { this.keys = Arrays.asList(keys); } /** * Copy constructor. Copies keys as well. */ private KeyPath(KeyPath keyPath) { keys = new ArrayList<>(keyPath.keys); resolvedElement = keyPath.resolvedElement; } /** * Returns a new KeyPath with the key added. * This is used during keypath resolution. Children normally don't know about all of their parent * elements so this is used to keep track of the fully qualified keypath. * This returns a key keypath because during resolution, the full keypath element tree is walked * and if this modified the original copy, it would remain after popping back up the element tree. */ @CheckResult @RestrictTo(RestrictTo.Scope.LIBRARY) public KeyPath addKey(String key) { KeyPath newKeyPath = new KeyPath(this); newKeyPath.keys.add(key); return newKeyPath; } /** * Return a new KeyPath with the element resolved to the specified {@link KeyPathElement}. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public KeyPath resolve(KeyPathElement element) { KeyPath keyPath = new KeyPath(this); keyPath.resolvedElement = element; return keyPath; } /** * Returns a {@link KeyPathElement} that this has been resolved to. KeyPaths get resolved with * resolveKeyPath on LottieDrawable or LottieAnimationView. */ @RestrictTo(RestrictTo.Scope.LIBRARY) @Nullable public KeyPathElement getResolvedElement() { return resolvedElement; } /** * Returns whether they key matches at the specified depth. */ @SuppressWarnings("RedundantIfStatement") @RestrictTo(RestrictTo.Scope.LIBRARY) public boolean matches(String key, int depth) { if (isContainer(key)) { // This is an artificial layer we programatically create. return true; } if (depth >= keys.size()) { return false; } if (keys.get(depth).equals(key) || keys.get(depth).equals("**") || keys.get(depth).equals("*")) { return true; } return false; } /** * For a given key and depth, returns how much the depth should be incremented by when * resolving a keypath to children. * <p> * This can be 0 or 2 when there is a globstar and the next key either matches or doesn't match * the current key. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public int incrementDepthBy(String key, int depth) { if (isContainer(key)) { // If it's a container then we added programatically and it isn't a part of the keypath. return 0; } if (!keys.get(depth).equals("**")) { // If it's not a globstar then it is part of the keypath. return 1; } if (depth == keys.size() - 1) { // The last key is a globstar. return 0; } if (keys.get(depth + 1).equals(key)) { // We are a globstar and the next key is our current key so consume both. return 2; } return 0; } /** * Returns whether the key at specified depth is fully specific enough to match the full set of * keys in this keypath. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public boolean fullyResolvesTo(String key, int depth) { if (depth >= keys.size()) { return false; } boolean isLastDepth = depth == keys.size() - 1; String keyAtDepth = keys.get(depth); boolean isGlobstar = keyAtDepth.equals("**"); if (!isGlobstar) { boolean matches = keyAtDepth.equals(key) || keyAtDepth.equals("*"); return (isLastDepth || (depth == keys.size() - 2 && endsWithGlobstar())) && matches; } boolean isGlobstarButNextKeyMatches = !isLastDepth && keys.get(depth + 1).equals(key); if (isGlobstarButNextKeyMatches) { return depth == keys.size() - 2 || (depth == keys.size() - 3 && endsWithGlobstar()); } if (isLastDepth) { return true; } if (depth + 1 < keys.size() - 1) { // We are a globstar but there is more than 1 key after the globstar we we can't fully match. return false; } // Return whether the next key (which we now know is the last one) is the same as the current // key. return keys.get(depth + 1).equals(key); } /** * Returns whether the keypath resolution should propagate to children. Some keypaths resolve * to content other than leaf contents (such as a layer or content group transform) so sometimes * this will return false. */ @SuppressWarnings("SimplifiableIfStatement") @RestrictTo(RestrictTo.Scope.LIBRARY) public boolean propagateToChildren(String key, int depth) { if ("__container".equals(key)) { return true; } return depth < keys.size() - 1 || keys.get(depth).equals("**"); } /** * We artificially create some container groups (like a root ContentGroup for the entire animation * and for the contents of a ShapeLayer). */ private boolean isContainer(String key) { return "__container".equals(key); } private boolean endsWithGlobstar() { return keys.get(keys.size() - 1).equals("**"); } public String keysToString() { return keys.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KeyPath keyPath = (KeyPath) o; if (!keys.equals(keyPath.keys)) { return false; } return resolvedElement != null ? resolvedElement.equals(keyPath.resolvedElement) : keyPath.resolvedElement == null; } @Override public int hashCode() { int result = keys.hashCode(); result = 31 * result + (resolvedElement != null ? resolvedElement.hashCode() : 0); return result; } @Override public String toString() { return "KeyPath{" + "keys=" + keys + ",resolved=" + (resolvedElement != null) + '}'; } }
2,559
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/KeyPathElement.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.airbnb.lottie.value.LottieValueCallback; import java.util.List; /** * Any item that can be a part of a {@link KeyPath} should implement this. */ @RestrictTo(LIBRARY) public interface KeyPathElement { /** * Called recursively during keypath resolution. * <p> * The overridden method should just call: * MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this); * * @param keyPath The full keypath being resolved. * @param depth The current depth that this element should be checked at in the keypath. * @param accumulator A list of fully resolved keypaths. If this element fully matches the * keypath then it should add itself to this list. * @param currentPartialKeyPath A keypath that contains all parent element of this one. * This element should create a copy of this and append itself * with KeyPath#addKey when it adds itself to the accumulator * or propagates resolution to its children. */ void resolveKeyPath( KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath); /** * The overridden method should handle appropriate properties and set value callbacks on their * animations. */ <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback); }
2,560
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/DocumentData.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import android.graphics.PointF; import androidx.annotation.ColorInt; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; @RestrictTo(LIBRARY) public class DocumentData { public enum Justification { LEFT_ALIGN, RIGHT_ALIGN, CENTER } public String text; public String fontName; public float size; public Justification justification; public int tracking; /** Extra space in between lines. */ public float lineHeight; public float baselineShift; @ColorInt public int color; @ColorInt public int strokeColor; public float strokeWidth; public boolean strokeOverFill; @Nullable public PointF boxPosition; @Nullable public PointF boxSize; public DocumentData(String text, String fontName, float size, Justification justification, int tracking, float lineHeight, float baselineShift, @ColorInt int color, @ColorInt int strokeColor, float strokeWidth, boolean strokeOverFill, PointF boxPosition, PointF boxSize) { set(text, fontName, size, justification, tracking, lineHeight, baselineShift, color, strokeColor, strokeWidth, strokeOverFill, boxPosition, boxSize); } public DocumentData() { } public void set(String text, String fontName, float size, Justification justification, int tracking, float lineHeight, float baselineShift, @ColorInt int color, @ColorInt int strokeColor, float strokeWidth, boolean strokeOverFill, PointF boxPosition, PointF boxSize) { this.text = text; this.fontName = fontName; this.size = size; this.justification = justification; this.tracking = tracking; this.lineHeight = lineHeight; this.baselineShift = baselineShift; this.color = color; this.strokeColor = strokeColor; this.strokeWidth = strokeWidth; this.strokeOverFill = strokeOverFill; this.boxPosition = boxPosition; this.boxSize = boxSize; } @Override public int hashCode() { int result; long temp; result = text.hashCode(); result = 31 * result + fontName.hashCode(); result = (int) (31 * result + size); result = 31 * result + justification.ordinal(); result = 31 * result + tracking; temp = Float.floatToRawIntBits(lineHeight); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + color; return result; } }
2,561
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/FontCharacter.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo; import com.airbnb.lottie.model.content.ShapeGroup; import java.util.List; @RestrictTo(LIBRARY) public class FontCharacter { public static int hashFor(char character, String fontFamily, String style) { int result = (int) character; result = 31 * result + fontFamily.hashCode(); result = 31 * result + style.hashCode(); return result; } private final List<ShapeGroup> shapes; private final char character; private final double size; private final double width; private final String style; private final String fontFamily; public FontCharacter(List<ShapeGroup> shapes, char character, double size, double width, String style, String fontFamily) { this.shapes = shapes; this.character = character; this.size = size; this.width = width; this.style = style; this.fontFamily = fontFamily; } public List<ShapeGroup> getShapes() { return shapes; } public double getWidth() { return width; } @Override public int hashCode() { return hashFor(character, fontFamily, style); } }
2,562
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/Marker.java
package com.airbnb.lottie.model; public class Marker { private static final String CARRIAGE_RETURN = "\r"; private final String name; public final float startFrame; public final float durationFrames; public Marker(String name, float startFrame, float durationFrames) { this.name = name; this.durationFrames = durationFrames; this.startFrame = startFrame; } public String getName() { return name; } public float getStartFrame() { return startFrame; } public float getDurationFrames() { return durationFrames; } public boolean matchesName(String name) { if (this.name.equalsIgnoreCase(name)) { return true; } // It is easy for a designer to accidentally include an extra newline which will cause the name to not match what they would // expect. This is a convenience to precent unneccesary confusion. return this.name.endsWith(CARRIAGE_RETURN) && this.name.substring(0, this.name.length() - 1).equalsIgnoreCase(name); } }
2,563
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/CubicCurveData.java
package com.airbnb.lottie.model; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import android.annotation.SuppressLint; import android.graphics.PointF; import androidx.annotation.NonNull; import androidx.annotation.RestrictTo; /** * One cubic path operation. CubicCurveData is structured such that it is easy to iterate through * it and build a path. However, it is modeled differently than most path operations. * * CubicCurveData * | - vertex * | / * | cp1 cp2 * | / * | | * | / * -------------------------- * * When incrementally building a path, it will already have a "current point" so that is * not captured in this data structure. * The control points here represent {@link android.graphics.Path#cubicTo(float, float, float, float, float, float)}. * * Most path operations are centered around a vertex and its in control point and out control point like this: * | outCp * | / * | | * | v * | / * | inCp * -------------------------- */ @RestrictTo(LIBRARY) public class CubicCurveData { private final PointF controlPoint1; private final PointF controlPoint2; private final PointF vertex; public CubicCurveData() { controlPoint1 = new PointF(); controlPoint2 = new PointF(); vertex = new PointF(); } public CubicCurveData(PointF controlPoint1, PointF controlPoint2, PointF vertex) { this.controlPoint1 = controlPoint1; this.controlPoint2 = controlPoint2; this.vertex = vertex; } public void setControlPoint1(float x, float y) { controlPoint1.set(x, y); } public PointF getControlPoint1() { return controlPoint1; } public void setControlPoint2(float x, float y) { controlPoint2.set(x, y); } public PointF getControlPoint2() { return controlPoint2; } public void setVertex(float x, float y) { vertex.set(x, y); } public void setFrom(CubicCurveData curveData) { setVertex(curveData.vertex.x, curveData.vertex.y); setControlPoint1(curveData.controlPoint1.x, curveData.controlPoint1.y); setControlPoint2(curveData.controlPoint2.x, curveData.controlPoint2.y); } public PointF getVertex() { return vertex; } @SuppressLint("DefaultLocale") @NonNull @Override public String toString() { return String.format("v=%.2f,%.2f cp1=%.2f,%.2f cp2=%.2f,%.2f", vertex.x, vertex.y, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y); } }
2,564
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableShapeValue.java
package com.airbnb.lottie.model.animatable; import android.graphics.Path; import com.airbnb.lottie.animation.keyframe.ShapeKeyframeAnimation; import com.airbnb.lottie.model.content.ShapeData; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableShapeValue extends BaseAnimatableValue<ShapeData, Path> { public AnimatableShapeValue(List<Keyframe<ShapeData>> keyframes) { super(keyframes); } @Override public ShapeKeyframeAnimation createAnimation() { return new ShapeKeyframeAnimation(keyframes); } }
2,565
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableScaleValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ScaleKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import com.airbnb.lottie.value.ScaleXY; import java.util.List; public class AnimatableScaleValue extends BaseAnimatableValue<ScaleXY, ScaleXY> { public AnimatableScaleValue(ScaleXY value) { super(value); } public AnimatableScaleValue(List<Keyframe<ScaleXY>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<ScaleXY, ScaleXY> createAnimation() { return new ScaleKeyframeAnimation(keyframes); } }
2,566
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatablePointValue.java
package com.airbnb.lottie.model.animatable; import android.graphics.PointF; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.PointKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatablePointValue extends BaseAnimatableValue<PointF, PointF> { public AnimatablePointValue(List<Keyframe<PointF>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<PointF, PointF> createAnimation() { return new PointKeyframeAnimation(keyframes); } }
2,567
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableTextProperties.java
package com.airbnb.lottie.model.animatable; import androidx.annotation.Nullable; public class AnimatableTextProperties { @Nullable public final AnimatableColorValue color; @Nullable public final AnimatableColorValue stroke; @Nullable public final AnimatableFloatValue strokeWidth; @Nullable public final AnimatableFloatValue tracking; public AnimatableTextProperties(@Nullable AnimatableColorValue color, @Nullable AnimatableColorValue stroke, @Nullable AnimatableFloatValue strokeWidth, @Nullable AnimatableFloatValue tracking) { this.color = color; this.stroke = stroke; this.strokeWidth = strokeWidth; this.tracking = tracking; } }
2,568
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableColorValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableColorValue extends BaseAnimatableValue<Integer, Integer> { public AnimatableColorValue(List<Keyframe<Integer>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<Integer, Integer> createAnimation() { return new ColorKeyframeAnimation(keyframes); } }
2,569
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableGradientColorValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.GradientColorKeyframeAnimation; import com.airbnb.lottie.model.content.GradientColor; import com.airbnb.lottie.value.Keyframe; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AnimatableGradientColorValue extends BaseAnimatableValue<GradientColor, GradientColor> { public AnimatableGradientColorValue(List<Keyframe<GradientColor>> keyframes) { super(ensureInterpolatableKeyframes(keyframes)); } private static List<Keyframe<GradientColor>> ensureInterpolatableKeyframes(List<Keyframe<GradientColor>> keyframes) { for (int i = 0; i < keyframes.size(); i++) { keyframes.set(i, ensureInterpolatableKeyframe(keyframes.get(i))); } return keyframes; } private static Keyframe<GradientColor> ensureInterpolatableKeyframe(Keyframe<GradientColor> keyframe) { GradientColor startValue = keyframe.startValue; GradientColor endValue = keyframe.endValue; if (startValue == null || endValue == null || startValue.getPositions().length == endValue.getPositions().length) { return keyframe; } float[] mergedPositions = mergePositions(startValue.getPositions(), endValue.getPositions()); // The start/end has opacity stops which required adding extra positions in between the existing colors. return keyframe.copyWith(startValue.copyWithPositions(mergedPositions), endValue.copyWithPositions(mergedPositions)); } static float[] mergePositions(float[] startPositions, float[] endPositions) { float[] mergedArray = new float[startPositions.length + endPositions.length]; System.arraycopy(startPositions, 0, mergedArray, 0, startPositions.length); System.arraycopy(endPositions, 0, mergedArray, startPositions.length, endPositions.length); Arrays.sort(mergedArray); int uniqueValues = 0; float lastValue = Float.NaN; for (int i = 0; i < mergedArray.length; i++) { if (mergedArray[i] != lastValue) { mergedArray[uniqueValues] = mergedArray[i]; uniqueValues++; lastValue = mergedArray[i]; } } return Arrays.copyOfRange(mergedArray, 0, uniqueValues); } @Override public BaseKeyframeAnimation<GradientColor, GradientColor> createAnimation() { return new GradientColorKeyframeAnimation(keyframes); } }
2,570
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableTextFrame.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.TextKeyframeAnimation; import com.airbnb.lottie.model.DocumentData; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableTextFrame extends BaseAnimatableValue<DocumentData, DocumentData> { public AnimatableTextFrame(List<Keyframe<DocumentData>> keyframes) { super(keyframes); } @Override public TextKeyframeAnimation createAnimation() { return new TextKeyframeAnimation(keyframes); } }
2,571
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableSplitDimensionPathValue.java
package com.airbnb.lottie.model.animatable; import android.graphics.PointF; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.SplitDimensionPathKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableSplitDimensionPathValue implements AnimatableValue<PointF, PointF> { private final AnimatableFloatValue animatableXDimension; private final AnimatableFloatValue animatableYDimension; public AnimatableSplitDimensionPathValue( AnimatableFloatValue animatableXDimension, AnimatableFloatValue animatableYDimension) { this.animatableXDimension = animatableXDimension; this.animatableYDimension = animatableYDimension; } @Override public List<Keyframe<PointF>> getKeyframes() { throw new UnsupportedOperationException("Cannot call getKeyframes on AnimatableSplitDimensionPathValue."); } @Override public boolean isStatic() { return animatableXDimension.isStatic() && animatableYDimension.isStatic(); } @Override public BaseKeyframeAnimation<PointF, PointF> createAnimation() { return new SplitDimensionPathKeyframeAnimation( animatableXDimension.createAnimation(), animatableYDimension.createAnimation()); } }
2,572
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableTransform.java
package com.airbnb.lottie.model.animatable; import android.graphics.PointF; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.ModifierContent; import com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation; import com.airbnb.lottie.model.content.ContentModel; import com.airbnb.lottie.model.layer.BaseLayer; public class AnimatableTransform implements ModifierContent, ContentModel { @Nullable private final AnimatablePathValue anchorPoint; @Nullable private final AnimatableValue<PointF, PointF> position; @Nullable private final AnimatableScaleValue scale; @Nullable private final AnimatableFloatValue rotation; @Nullable private final AnimatableIntegerValue opacity; @Nullable private final AnimatableFloatValue skew; @Nullable private final AnimatableFloatValue skewAngle; // Used for repeaters @Nullable private final AnimatableFloatValue startOpacity; @Nullable private final AnimatableFloatValue endOpacity; public AnimatableTransform() { this(null, null, null, null, null, null, null, null, null); } public AnimatableTransform(@Nullable AnimatablePathValue anchorPoint, @Nullable AnimatableValue<PointF, PointF> position, @Nullable AnimatableScaleValue scale, @Nullable AnimatableFloatValue rotation, @Nullable AnimatableIntegerValue opacity, @Nullable AnimatableFloatValue startOpacity, @Nullable AnimatableFloatValue endOpacity, @Nullable AnimatableFloatValue skew, @Nullable AnimatableFloatValue skewAngle) { this.anchorPoint = anchorPoint; this.position = position; this.scale = scale; this.rotation = rotation; this.opacity = opacity; this.startOpacity = startOpacity; this.endOpacity = endOpacity; this.skew = skew; this.skewAngle = skewAngle; } @Nullable public AnimatablePathValue getAnchorPoint() { return anchorPoint; } @Nullable public AnimatableValue<PointF, PointF> getPosition() { return position; } @Nullable public AnimatableScaleValue getScale() { return scale; } @Nullable public AnimatableFloatValue getRotation() { return rotation; } @Nullable public AnimatableIntegerValue getOpacity() { return opacity; } @Nullable public AnimatableFloatValue getStartOpacity() { return startOpacity; } @Nullable public AnimatableFloatValue getEndOpacity() { return endOpacity; } @Nullable public AnimatableFloatValue getSkew() { return skew; } @Nullable public AnimatableFloatValue getSkewAngle() { return skewAngle; } public TransformKeyframeAnimation createAnimation() { return new TransformKeyframeAnimation(this); } @Nullable @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return null; } }
2,573
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatablePathValue.java
package com.airbnb.lottie.model.animatable; import android.graphics.PointF; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.PathKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.PointKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatablePathValue implements AnimatableValue<PointF, PointF> { private final List<Keyframe<PointF>> keyframes; public AnimatablePathValue(List<Keyframe<PointF>> keyframes) { this.keyframes = keyframes; } @Override public List<Keyframe<PointF>> getKeyframes() { return keyframes; } @Override public boolean isStatic() { return keyframes.size() == 1 && keyframes.get(0).isStatic(); } @Override public BaseKeyframeAnimation<PointF, PointF> createAnimation() { if (keyframes.get(0).isStatic()) { return new PointKeyframeAnimation(keyframes); } return new PathKeyframeAnimation(keyframes); } }
2,574
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableFloatValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableFloatValue extends BaseAnimatableValue<Float, Float> { public AnimatableFloatValue(List<Keyframe<Float>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<Float, Float> createAnimation() { return new FloatKeyframeAnimation(keyframes); } }
2,575
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/BaseAnimatableValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.value.Keyframe; import java.util.Arrays; import java.util.Collections; import java.util.List; abstract class BaseAnimatableValue<V, O> implements AnimatableValue<V, O> { final List<Keyframe<V>> keyframes; /** * Create a default static animatable path. */ BaseAnimatableValue(V value) { this(Collections.singletonList(new Keyframe<>(value))); } BaseAnimatableValue(List<Keyframe<V>> keyframes) { this.keyframes = keyframes; } public List<Keyframe<V>> getKeyframes() { return keyframes; } @Override public boolean isStatic() { return keyframes.isEmpty() || (keyframes.size() == 1 && keyframes.get(0).isStatic()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); if (!keyframes.isEmpty()) { sb.append("values=").append(Arrays.toString(keyframes.toArray())); } return sb.toString(); } }
2,576
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableIntegerValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.IntegerKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public class AnimatableIntegerValue extends BaseAnimatableValue<Integer, Integer> { public AnimatableIntegerValue(List<Keyframe<Integer>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<Integer, Integer> createAnimation() { return new IntegerKeyframeAnimation(keyframes); } }
2,577
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/AnimatableValue.java
package com.airbnb.lottie.model.animatable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.value.Keyframe; import java.util.List; public interface AnimatableValue<K, A> { List<Keyframe<K>> getKeyframes(); boolean isStatic(); BaseKeyframeAnimation<K, A> createAnimation(); }
2,578
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/animatable/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.model.animatable; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,579
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/RectangleShape.java
package com.airbnb.lottie.model.content; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.RectangleContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.layer.BaseLayer; public class RectangleShape implements ContentModel { private final String name; private final AnimatableValue<PointF, PointF> position; private final AnimatableValue<PointF, PointF> size; private final AnimatableFloatValue cornerRadius; private final boolean hidden; public RectangleShape(String name, AnimatableValue<PointF, PointF> position, AnimatableValue<PointF, PointF> size, AnimatableFloatValue cornerRadius, boolean hidden) { this.name = name; this.position = position; this.size = size; this.cornerRadius = cornerRadius; this.hidden = hidden; } public String getName() { return name; } public AnimatableFloatValue getCornerRadius() { return cornerRadius; } public AnimatableValue<PointF, PointF> getSize() { return size; } public AnimatableValue<PointF, PointF> getPosition() { return position; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new RectangleContent(drawable, layer, this); } @Override public String toString() { return "RectangleShape{position=" + position + ", size=" + size + '}'; } }
2,580
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/MergePaths.java
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.MergePathsContent; import com.airbnb.lottie.model.layer.BaseLayer; import com.airbnb.lottie.utils.Logger; public class MergePaths implements ContentModel { public enum MergePathsMode { MERGE, ADD, SUBTRACT, INTERSECT, EXCLUDE_INTERSECTIONS; public static MergePathsMode forId(int id) { switch (id) { case 1: return MERGE; case 2: return ADD; case 3: return SUBTRACT; case 4: return INTERSECT; case 5: return EXCLUDE_INTERSECTIONS; default: return MERGE; } } } private final String name; private final MergePathsMode mode; private final boolean hidden; public MergePaths(String name, MergePathsMode mode, boolean hidden) { this.name = name; this.mode = mode; this.hidden = hidden; } public String getName() { return name; } public MergePathsMode getMode() { return mode; } public boolean isHidden() { return hidden; } @Override @Nullable public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { if (!drawable.enableMergePathsForKitKatAndAbove()) { Logger.warning("Animation contains merge paths but they are disabled."); return null; } return new MergePathsContent(this); } @Override public String toString() { return "MergePaths{" + "mode=" + mode + '}'; } }
2,581
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/Repeater.java
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.RepeaterContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableTransform; import com.airbnb.lottie.model.layer.BaseLayer; public class Repeater implements ContentModel { private final String name; private final AnimatableFloatValue copies; private final AnimatableFloatValue offset; private final AnimatableTransform transform; private final boolean hidden; public Repeater(String name, AnimatableFloatValue copies, AnimatableFloatValue offset, AnimatableTransform transform, boolean hidden) { this.name = name; this.copies = copies; this.offset = offset; this.transform = transform; this.hidden = hidden; } public String getName() { return name; } public AnimatableFloatValue getCopies() { return copies; } public AnimatableFloatValue getOffset() { return offset; } public AnimatableTransform getTransform() { return transform; } public boolean isHidden() { return hidden; } @Nullable @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new RepeaterContent(drawable, layer, this); } }
2,582
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/BlurEffect.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; public class BlurEffect { final AnimatableFloatValue blurriness; public BlurEffect(AnimatableFloatValue blurriness) { this.blurriness = blurriness; } public AnimatableFloatValue getBlurriness() { return blurriness; } }
2,583
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/GradientStroke.java
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.GradientStrokeContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.layer.BaseLayer; import java.util.List; public class GradientStroke implements ContentModel { private final String name; private final GradientType gradientType; private final AnimatableGradientColorValue gradientColor; private final AnimatableIntegerValue opacity; private final AnimatablePointValue startPoint; private final AnimatablePointValue endPoint; private final AnimatableFloatValue width; private final ShapeStroke.LineCapType capType; private final ShapeStroke.LineJoinType joinType; private final float miterLimit; private final List<AnimatableFloatValue> lineDashPattern; @Nullable private final AnimatableFloatValue dashOffset; private final boolean hidden; public GradientStroke(String name, GradientType gradientType, AnimatableGradientColorValue gradientColor, AnimatableIntegerValue opacity, AnimatablePointValue startPoint, AnimatablePointValue endPoint, AnimatableFloatValue width, ShapeStroke.LineCapType capType, ShapeStroke.LineJoinType joinType, float miterLimit, List<AnimatableFloatValue> lineDashPattern, @Nullable AnimatableFloatValue dashOffset, boolean hidden) { this.name = name; this.gradientType = gradientType; this.gradientColor = gradientColor; this.opacity = opacity; this.startPoint = startPoint; this.endPoint = endPoint; this.width = width; this.capType = capType; this.joinType = joinType; this.miterLimit = miterLimit; this.lineDashPattern = lineDashPattern; this.dashOffset = dashOffset; this.hidden = hidden; } public String getName() { return name; } public GradientType getGradientType() { return gradientType; } public AnimatableGradientColorValue getGradientColor() { return gradientColor; } public AnimatableIntegerValue getOpacity() { return opacity; } public AnimatablePointValue getStartPoint() { return startPoint; } public AnimatablePointValue getEndPoint() { return endPoint; } public AnimatableFloatValue getWidth() { return width; } public ShapeStroke.LineCapType getCapType() { return capType; } public ShapeStroke.LineJoinType getJoinType() { return joinType; } public List<AnimatableFloatValue> getLineDashPattern() { return lineDashPattern; } @Nullable public AnimatableFloatValue getDashOffset() { return dashOffset; } public float getMiterLimit() { return miterLimit; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new GradientStrokeContent(drawable, layer, this); } }
2,584
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ContentModel.java
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.model.layer.BaseLayer; public interface ContentModel { @Nullable Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer); }
2,585
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapeGroup.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.ContentGroup; import com.airbnb.lottie.model.layer.BaseLayer; import java.util.Arrays; import java.util.List; public class ShapeGroup implements ContentModel { private final String name; private final List<ContentModel> items; private final boolean hidden; public ShapeGroup(String name, List<ContentModel> items, boolean hidden) { this.name = name; this.items = items; this.hidden = hidden; } public String getName() { return name; } public List<ContentModel> getItems() { return items; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new ContentGroup(drawable, layer, this, composition); } @Override public String toString() { return "ShapeGroup{" + "name='" + name + "\' Shapes: " + Arrays.toString(items.toArray()) + '}'; } }
2,586
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/GradientColor.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.utils.GammaEvaluator; import com.airbnb.lottie.utils.MiscUtils; import java.util.Arrays; public class GradientColor { private final float[] positions; private final int[] colors; public GradientColor(float[] positions, int[] colors) { this.positions = positions; this.colors = colors; } public float[] getPositions() { return positions; } public int[] getColors() { return colors; } public int getSize() { return colors.length; } public void lerp(GradientColor gc1, GradientColor gc2, float progress) { if (gc1.colors.length != gc2.colors.length) { throw new IllegalArgumentException("Cannot interpolate between gradients. Lengths vary (" + gc1.colors.length + " vs " + gc2.colors.length + ")"); } for (int i = 0; i < gc1.colors.length; i++) { positions[i] = MiscUtils.lerp(gc1.positions[i], gc2.positions[i], progress); colors[i] = GammaEvaluator.evaluate(progress, gc1.colors[i], gc2.colors[i]); } // 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. // If there are extra positions here, just duplicate the last value in the gradient. for (int i = gc1.colors.length; i < positions.length; i++) { positions[i] = positions[gc1.colors.length - 1]; colors[i] = colors[gc1.colors.length - 1]; } } public GradientColor copyWithPositions(float[] positions) { int[] colors = new int[positions.length]; for (int i = 0; i < positions.length; i++) { colors[i] = getColorForPosition(positions[i]); } return new GradientColor(positions, colors); } private int getColorForPosition(float position) { int existingIndex = Arrays.binarySearch(positions, position); if (existingIndex >= 0) { return colors[existingIndex]; } // binarySearch returns -insertionPoint - 1 if it is not found. int insertionPoint = -(existingIndex + 1); if (insertionPoint == 0) { return colors[0]; } else if (insertionPoint == colors.length - 1) { return colors[colors.length - 1]; } float startPosition = positions[insertionPoint - 1]; float endPosition = positions[insertionPoint]; int startColor = colors[insertionPoint - 1]; int endColor = colors[insertionPoint]; float fraction = (position - startPosition) / (endPosition - startPosition); return GammaEvaluator.evaluate(fraction, startColor, endColor); } }
2,587
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/CircleShape.java
package com.airbnb.lottie.model.content; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.EllipseContent; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.layer.BaseLayer; public class CircleShape implements ContentModel { private final String name; private final AnimatableValue<PointF, PointF> position; private final AnimatablePointValue size; private final boolean isReversed; private final boolean hidden; public CircleShape(String name, AnimatableValue<PointF, PointF> position, AnimatablePointValue size, boolean isReversed, boolean hidden) { this.name = name; this.position = position; this.size = size; this.isReversed = isReversed; this.hidden = hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new EllipseContent(drawable, layer, this); } public String getName() { return name; } public AnimatableValue<PointF, PointF> getPosition() { return position; } public AnimatablePointValue getSize() { return size; } public boolean isReversed() { return isReversed; } public boolean isHidden() { return hidden; } }
2,588
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapeTrimPath.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.TrimPathContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.layer.BaseLayer; public class ShapeTrimPath implements ContentModel { public enum Type { SIMULTANEOUSLY, INDIVIDUALLY; public static Type forId(int id) { switch (id) { case 1: return SIMULTANEOUSLY; case 2: return INDIVIDUALLY; default: throw new IllegalArgumentException("Unknown trim path type " + id); } } } private final String name; private final Type type; private final AnimatableFloatValue start; private final AnimatableFloatValue end; private final AnimatableFloatValue offset; private final boolean hidden; public ShapeTrimPath(String name, Type type, AnimatableFloatValue start, AnimatableFloatValue end, AnimatableFloatValue offset, boolean hidden) { this.name = name; this.type = type; this.start = start; this.end = end; this.offset = offset; this.hidden = hidden; } public String getName() { return name; } public Type getType() { return type; } public AnimatableFloatValue getEnd() { return end; } public AnimatableFloatValue getStart() { return start; } public AnimatableFloatValue getOffset() { return offset; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new TrimPathContent(layer, this); } @Override public String toString() { return "Trim Path: {start: " + start + ", end: " + end + ", offset: " + offset + "}"; } }
2,589
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/Mask.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; public class Mask { public enum MaskMode { MASK_MODE_ADD, MASK_MODE_SUBTRACT, MASK_MODE_INTERSECT, MASK_MODE_NONE } private final MaskMode maskMode; private final AnimatableShapeValue maskPath; private final AnimatableIntegerValue opacity; private final boolean inverted; public Mask(MaskMode maskMode, AnimatableShapeValue maskPath, AnimatableIntegerValue opacity, boolean inverted) { this.maskMode = maskMode; this.maskPath = maskPath; this.opacity = opacity; this.inverted = inverted; } public MaskMode getMaskMode() { return maskMode; } public AnimatableShapeValue getMaskPath() { return maskPath; } public AnimatableIntegerValue getOpacity() { return opacity; } public boolean isInverted() { return inverted; } }
2,590
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapePath.java
package com.airbnb.lottie.model.content; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.ShapeContent; import com.airbnb.lottie.model.animatable.AnimatableShapeValue; import com.airbnb.lottie.model.layer.BaseLayer; public class ShapePath implements ContentModel { private final String name; private final int index; private final AnimatableShapeValue shapePath; private final boolean hidden; public ShapePath(String name, int index, AnimatableShapeValue shapePath, boolean hidden) { this.name = name; this.index = index; this.shapePath = shapePath; this.hidden = hidden; } public String getName() { return name; } public AnimatableShapeValue getShapePath() { return shapePath; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new ShapeContent(drawable, layer, this); } public boolean isHidden() { return hidden; } @Override public String toString() { return "ShapePath{" + "name=" + name + ", index=" + index + '}'; } }
2,591
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/GradientType.java
package com.airbnb.lottie.model.content; public enum GradientType { LINEAR, RADIAL }
2,592
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/GradientFill.java
package com.airbnb.lottie.model.content; import android.graphics.Path; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.GradientFillContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.animatable.AnimatablePointValue; import com.airbnb.lottie.model.layer.BaseLayer; public class GradientFill implements ContentModel { private final GradientType gradientType; private final Path.FillType fillType; private final AnimatableGradientColorValue gradientColor; private final AnimatableIntegerValue opacity; private final AnimatablePointValue startPoint; private final AnimatablePointValue endPoint; private final String name; @Nullable private final AnimatableFloatValue highlightLength; @Nullable private final AnimatableFloatValue highlightAngle; private final boolean hidden; public GradientFill(String name, GradientType gradientType, Path.FillType fillType, AnimatableGradientColorValue gradientColor, AnimatableIntegerValue opacity, AnimatablePointValue startPoint, AnimatablePointValue endPoint, AnimatableFloatValue highlightLength, AnimatableFloatValue highlightAngle, boolean hidden) { this.gradientType = gradientType; this.fillType = fillType; this.gradientColor = gradientColor; this.opacity = opacity; this.startPoint = startPoint; this.endPoint = endPoint; this.name = name; this.highlightLength = highlightLength; this.highlightAngle = highlightAngle; this.hidden = hidden; } public String getName() { return name; } public GradientType getGradientType() { return gradientType; } public Path.FillType getFillType() { return fillType; } public AnimatableGradientColorValue getGradientColor() { return gradientColor; } public AnimatableIntegerValue getOpacity() { return opacity; } public AnimatablePointValue getStartPoint() { return startPoint; } public AnimatablePointValue getEndPoint() { return endPoint; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new GradientFillContent(drawable, composition, layer, this); } }
2,593
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/PolystarShape.java
package com.airbnb.lottie.model.content; import android.graphics.PointF; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.PolystarContent; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.layer.BaseLayer; public class PolystarShape implements ContentModel { public enum Type { STAR(1), POLYGON(2); private final int value; Type(int value) { this.value = value; } public static Type forValue(int value) { for (Type type : Type.values()) { if (type.value == value) { return type; } } return null; } } private final String name; private final Type type; private final AnimatableFloatValue points; private final AnimatableValue<PointF, PointF> position; private final AnimatableFloatValue rotation; private final AnimatableFloatValue innerRadius; private final AnimatableFloatValue outerRadius; private final AnimatableFloatValue innerRoundedness; private final AnimatableFloatValue outerRoundedness; private final boolean hidden; private final boolean isReversed; public PolystarShape(String name, Type type, AnimatableFloatValue points, AnimatableValue<PointF, PointF> position, AnimatableFloatValue rotation, AnimatableFloatValue innerRadius, AnimatableFloatValue outerRadius, AnimatableFloatValue innerRoundedness, AnimatableFloatValue outerRoundedness, boolean hidden, boolean isReversed) { this.name = name; this.type = type; this.points = points; this.position = position; this.rotation = rotation; this.innerRadius = innerRadius; this.outerRadius = outerRadius; this.innerRoundedness = innerRoundedness; this.outerRoundedness = outerRoundedness; this.hidden = hidden; this.isReversed = isReversed; } public String getName() { return name; } public Type getType() { return type; } public AnimatableFloatValue getPoints() { return points; } public AnimatableValue<PointF, PointF> getPosition() { return position; } public AnimatableFloatValue getRotation() { return rotation; } public AnimatableFloatValue getInnerRadius() { return innerRadius; } public AnimatableFloatValue getOuterRadius() { return outerRadius; } public AnimatableFloatValue getInnerRoundedness() { return innerRoundedness; } public AnimatableFloatValue getOuterRoundedness() { return outerRoundedness; } public boolean isHidden() { return hidden; } public boolean isReversed() { return isReversed; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new PolystarContent(drawable, layer, this); } }
2,594
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapeFill.java
package com.airbnb.lottie.model.content; import android.graphics.Path; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.FillContent; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.layer.BaseLayer; public class ShapeFill implements ContentModel { private final boolean fillEnabled; private final Path.FillType fillType; private final String name; @Nullable private final AnimatableColorValue color; @Nullable private final AnimatableIntegerValue opacity; private final boolean hidden; public ShapeFill(String name, boolean fillEnabled, Path.FillType fillType, @Nullable AnimatableColorValue color, @Nullable AnimatableIntegerValue opacity, boolean hidden) { this.name = name; this.fillEnabled = fillEnabled; this.fillType = fillType; this.color = color; this.opacity = opacity; this.hidden = hidden; } public String getName() { return name; } @Nullable public AnimatableColorValue getColor() { return color; } @Nullable public AnimatableIntegerValue getOpacity() { return opacity; } public Path.FillType getFillType() { return fillType; } public boolean isHidden() { return hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new FillContent(drawable, layer, this); } @Override public String toString() { return "ShapeFill{" + "color=" + ", fillEnabled=" + fillEnabled + '}'; } }
2,595
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapeStroke.java
package com.airbnb.lottie.model.content; import android.graphics.Paint; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.StrokeContent; import com.airbnb.lottie.model.animatable.AnimatableColorValue; import com.airbnb.lottie.model.animatable.AnimatableFloatValue; import com.airbnb.lottie.model.animatable.AnimatableIntegerValue; import com.airbnb.lottie.model.layer.BaseLayer; import java.util.List; public class ShapeStroke implements ContentModel { public enum LineCapType { BUTT, ROUND, UNKNOWN; public Paint.Cap toPaintCap() { switch (this) { case BUTT: return Paint.Cap.BUTT; case ROUND: return Paint.Cap.ROUND; case UNKNOWN: default: return Paint.Cap.SQUARE; } } } public enum LineJoinType { MITER, ROUND, BEVEL; public Paint.Join toPaintJoin() { switch (this) { case BEVEL: return Paint.Join.BEVEL; case MITER: return Paint.Join.MITER; case ROUND: return Paint.Join.ROUND; } return null; } } private final String name; @Nullable private final AnimatableFloatValue offset; private final List<AnimatableFloatValue> lineDashPattern; private final AnimatableColorValue color; private final AnimatableIntegerValue opacity; private final AnimatableFloatValue width; private final LineCapType capType; private final LineJoinType joinType; private final float miterLimit; private final boolean hidden; public ShapeStroke(String name, @Nullable AnimatableFloatValue offset, List<AnimatableFloatValue> lineDashPattern, AnimatableColorValue color, AnimatableIntegerValue opacity, AnimatableFloatValue width, LineCapType capType, LineJoinType joinType, float miterLimit, boolean hidden) { this.name = name; this.offset = offset; this.lineDashPattern = lineDashPattern; this.color = color; this.opacity = opacity; this.width = width; this.capType = capType; this.joinType = joinType; this.miterLimit = miterLimit; this.hidden = hidden; } @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new StrokeContent(drawable, layer, this); } public String getName() { return name; } public AnimatableColorValue getColor() { return color; } public AnimatableIntegerValue getOpacity() { return opacity; } public AnimatableFloatValue getWidth() { return width; } public List<AnimatableFloatValue> getLineDashPattern() { return lineDashPattern; } public AnimatableFloatValue getDashOffset() { return offset; } public LineCapType getCapType() { return capType; } public LineJoinType getJoinType() { return joinType; } public float getMiterLimit() { return miterLimit; } public boolean isHidden() { return hidden; } }
2,596
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/ShapeData.java
package com.airbnb.lottie.model.content; import android.graphics.PointF; import androidx.annotation.FloatRange; import com.airbnb.lottie.model.CubicCurveData; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.MiscUtils; import java.util.ArrayList; import java.util.List; public class ShapeData { private final List<CubicCurveData> curves; private PointF initialPoint; private boolean closed; public ShapeData(PointF initialPoint, boolean closed, List<CubicCurveData> curves) { this.initialPoint = initialPoint; this.closed = closed; this.curves = new ArrayList<>(curves); } public ShapeData() { curves = new ArrayList<>(); } public void setInitialPoint(float x, float y) { if (initialPoint == null) { initialPoint = new PointF(); } initialPoint.set(x, y); } public PointF getInitialPoint() { return initialPoint; } public void setClosed(boolean closed) { this.closed = closed; } public boolean isClosed() { return closed; } public List<CubicCurveData> getCurves() { return curves; } public void interpolateBetween(ShapeData shapeData1, ShapeData shapeData2, @FloatRange(from = 0f, to = 1f) float percentage) { if (initialPoint == null) { initialPoint = new PointF(); } closed = shapeData1.isClosed() || shapeData2.isClosed(); if (shapeData1.getCurves().size() != shapeData2.getCurves().size()) { Logger.warning("Curves must have the same number of control points. Shape 1: " + shapeData1.getCurves().size() + "\tShape 2: " + shapeData2.getCurves().size()); } int points = Math.min(shapeData1.getCurves().size(), shapeData2.getCurves().size()); if (curves.size() < points) { for (int i = curves.size(); i < points; i++) { curves.add(new CubicCurveData()); } } else if (curves.size() > points) { for (int i = curves.size() - 1; i >= points; i--) { curves.remove(curves.size() - 1); } } PointF initialPoint1 = shapeData1.getInitialPoint(); PointF initialPoint2 = shapeData2.getInitialPoint(); setInitialPoint(MiscUtils.lerp(initialPoint1.x, initialPoint2.x, percentage), MiscUtils.lerp(initialPoint1.y, initialPoint2.y, percentage)); for (int i = curves.size() - 1; i >= 0; i--) { CubicCurveData curve1 = shapeData1.getCurves().get(i); CubicCurveData curve2 = shapeData2.getCurves().get(i); PointF cp11 = curve1.getControlPoint1(); PointF cp21 = curve1.getControlPoint2(); PointF vertex1 = curve1.getVertex(); PointF cp12 = curve2.getControlPoint1(); PointF cp22 = curve2.getControlPoint2(); PointF vertex2 = curve2.getVertex(); curves.get(i).setControlPoint1( MiscUtils.lerp(cp11.x, cp12.x, percentage), MiscUtils.lerp(cp11.y, cp12.y, percentage)); curves.get(i).setControlPoint2( MiscUtils.lerp(cp21.x, cp22.x, percentage), MiscUtils.lerp(cp21.y, cp22.y, percentage)); curves.get(i).setVertex( MiscUtils.lerp(vertex1.x, vertex2.x, percentage), MiscUtils.lerp(vertex1.y, vertex2.y, percentage)); } } @Override public String toString() { return "ShapeData{" + "numCurves=" + curves.size() + "closed=" + closed + '}'; } }
2,597
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/RoundedCorners.java
package com.airbnb.lottie.model.content; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieComposition; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.content.Content; import com.airbnb.lottie.animation.content.RoundedCornersContent; import com.airbnb.lottie.model.animatable.AnimatableValue; import com.airbnb.lottie.model.layer.BaseLayer; public class RoundedCorners implements ContentModel { private final String name; private final AnimatableValue<Float, Float> cornerRadius; public RoundedCorners(String name, AnimatableValue<Float, Float> cornerRadius) { this.name = name; this.cornerRadius = cornerRadius; } public String getName() { return name; } public AnimatableValue<Float, Float> getCornerRadius() { return cornerRadius; } @Nullable @Override public Content toContent(LottieDrawable drawable, LottieComposition composition, BaseLayer layer) { return new RoundedCornersContent(drawable, layer, this); } }
2,598
0
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model
Create_ds/lottie-android/lottie/src/main/java/com/airbnb/lottie/model/content/package-info.java
@RestrictTo(LIBRARY) package com.airbnb.lottie.model.content; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.RestrictTo;
2,599