id
int32 0
165k
| repo
stringlengths 7
58
| path
stringlengths 12
218
| func_name
stringlengths 3
140
| original_string
stringlengths 73
34.1k
| language
stringclasses 1
value | code
stringlengths 73
34.1k
| code_tokens
list | docstring
stringlengths 3
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 105
339
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,600
|
facebook/fresco
|
fbcore/src/main/java/com/facebook/common/internal/Files.java
|
Files.toByteArray
|
public static byte[] toByteArray(File file) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readFile(in, in.getChannel().size());
} finally {
if (in != null) {
in.close();
}
}
}
|
java
|
public static byte[] toByteArray(File file) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readFile(in, in.getChannel().size());
} finally {
if (in != null) {
in.close();
}
}
}
|
[
"public",
"static",
"byte",
"[",
"]",
"toByteArray",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"FileInputStream",
"in",
"=",
"null",
";",
"try",
"{",
"in",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"return",
"readFile",
"(",
"in",
",",
"in",
".",
"getChannel",
"(",
")",
".",
"size",
"(",
")",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"in",
"!=",
"null",
")",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] |
Reads all bytes from a file into a byte array.
@param file the file to read from
@return a byte array containing all the bytes from file
@throws IllegalArgumentException if the file is bigger than the largest
possible byte array (2^31 - 1)
@throws IOException if an I/O error occurs
|
[
"Reads",
"all",
"bytes",
"from",
"a",
"file",
"into",
"a",
"byte",
"array",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/internal/Files.java#L64-L74
|
14,601
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java
|
PlatformBitmapFactory.getSuitableBitmapConfig
|
private static Bitmap.Config getSuitableBitmapConfig(Bitmap source) {
Bitmap.Config finalConfig = Bitmap.Config.ARGB_8888;
final Bitmap.Config sourceConfig = source.getConfig();
// GIF files generate null configs, assume ARGB_8888
if (sourceConfig != null) {
switch (sourceConfig) {
case RGB_565:
finalConfig = Bitmap.Config.RGB_565;
break;
case ALPHA_8:
finalConfig = Bitmap.Config.ALPHA_8;
break;
case ARGB_4444:
case ARGB_8888:
default:
finalConfig = Bitmap.Config.ARGB_8888;
break;
}
}
return finalConfig;
}
|
java
|
private static Bitmap.Config getSuitableBitmapConfig(Bitmap source) {
Bitmap.Config finalConfig = Bitmap.Config.ARGB_8888;
final Bitmap.Config sourceConfig = source.getConfig();
// GIF files generate null configs, assume ARGB_8888
if (sourceConfig != null) {
switch (sourceConfig) {
case RGB_565:
finalConfig = Bitmap.Config.RGB_565;
break;
case ALPHA_8:
finalConfig = Bitmap.Config.ALPHA_8;
break;
case ARGB_4444:
case ARGB_8888:
default:
finalConfig = Bitmap.Config.ARGB_8888;
break;
}
}
return finalConfig;
}
|
[
"private",
"static",
"Bitmap",
".",
"Config",
"getSuitableBitmapConfig",
"(",
"Bitmap",
"source",
")",
"{",
"Bitmap",
".",
"Config",
"finalConfig",
"=",
"Bitmap",
".",
"Config",
".",
"ARGB_8888",
";",
"final",
"Bitmap",
".",
"Config",
"sourceConfig",
"=",
"source",
".",
"getConfig",
"(",
")",
";",
"// GIF files generate null configs, assume ARGB_8888",
"if",
"(",
"sourceConfig",
"!=",
"null",
")",
"{",
"switch",
"(",
"sourceConfig",
")",
"{",
"case",
"RGB_565",
":",
"finalConfig",
"=",
"Bitmap",
".",
"Config",
".",
"RGB_565",
";",
"break",
";",
"case",
"ALPHA_8",
":",
"finalConfig",
"=",
"Bitmap",
".",
"Config",
".",
"ALPHA_8",
";",
"break",
";",
"case",
"ARGB_4444",
":",
"case",
"ARGB_8888",
":",
"default",
":",
"finalConfig",
"=",
"Bitmap",
".",
"Config",
".",
"ARGB_8888",
";",
"break",
";",
"}",
"}",
"return",
"finalConfig",
";",
"}"
] |
Returns suitable Bitmap Config for the new Bitmap based on the source Bitmap configurations.
@param source the source Bitmap
@return the Bitmap Config for the new Bitmap
|
[
"Returns",
"suitable",
"Bitmap",
"Config",
"for",
"the",
"new",
"Bitmap",
"based",
"on",
"the",
"source",
"Bitmap",
"configurations",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L681-L702
|
14,602
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java
|
PlatformBitmapFactory.checkFinalImageBounds
|
private static void checkFinalImageBounds(Bitmap source, int x, int y, int width, int height) {
Preconditions.checkArgument(
x + width <= source.getWidth(),
"x + width must be <= bitmap.width()");
Preconditions.checkArgument(
y + height <= source.getHeight(),
"y + height must be <= bitmap.height()");
}
|
java
|
private static void checkFinalImageBounds(Bitmap source, int x, int y, int width, int height) {
Preconditions.checkArgument(
x + width <= source.getWidth(),
"x + width must be <= bitmap.width()");
Preconditions.checkArgument(
y + height <= source.getHeight(),
"y + height must be <= bitmap.height()");
}
|
[
"private",
"static",
"void",
"checkFinalImageBounds",
"(",
"Bitmap",
"source",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"x",
"+",
"width",
"<=",
"source",
".",
"getWidth",
"(",
")",
",",
"\"x + width must be <= bitmap.width()\"",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"y",
"+",
"height",
"<=",
"source",
".",
"getHeight",
"(",
")",
",",
"\"y + height must be <= bitmap.height()\"",
")",
";",
"}"
] |
Common code for checking that x + width and y + height are within image bounds
@param source the source Bitmap
@param x starting x coordinate of source image subset
@param y starting y coordinate of source image subset
@param width width of the source image subset
@param height height of the source image subset
|
[
"Common",
"code",
"for",
"checking",
"that",
"x",
"+",
"width",
"and",
"y",
"+",
"height",
"are",
"within",
"image",
"bounds"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L735-L742
|
14,603
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java
|
PlatformBitmapFactory.setPropertyFromSourceBitmap
|
private static void setPropertyFromSourceBitmap(Bitmap source, Bitmap destination) {
// The new bitmap was created from a known bitmap source so assume that
// they use the same density
destination.setDensity(source.getDensity());
if (Build.VERSION.SDK_INT >= 12) {
destination.setHasAlpha(source.hasAlpha());
}
if (Build.VERSION.SDK_INT >= 19) {
destination.setPremultiplied(source.isPremultiplied());
}
}
|
java
|
private static void setPropertyFromSourceBitmap(Bitmap source, Bitmap destination) {
// The new bitmap was created from a known bitmap source so assume that
// they use the same density
destination.setDensity(source.getDensity());
if (Build.VERSION.SDK_INT >= 12) {
destination.setHasAlpha(source.hasAlpha());
}
if (Build.VERSION.SDK_INT >= 19) {
destination.setPremultiplied(source.isPremultiplied());
}
}
|
[
"private",
"static",
"void",
"setPropertyFromSourceBitmap",
"(",
"Bitmap",
"source",
",",
"Bitmap",
"destination",
")",
"{",
"// The new bitmap was created from a known bitmap source so assume that",
"// they use the same density",
"destination",
".",
"setDensity",
"(",
"source",
".",
"getDensity",
"(",
")",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"12",
")",
"{",
"destination",
".",
"setHasAlpha",
"(",
"source",
".",
"hasAlpha",
"(",
")",
")",
";",
"}",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"19",
")",
"{",
"destination",
".",
"setPremultiplied",
"(",
"source",
".",
"isPremultiplied",
"(",
")",
")",
";",
"}",
"}"
] |
Set some property of the source bitmap to the destination bitmap
@param source the source bitmap
@param destination the destination bitmap
|
[
"Set",
"some",
"property",
"of",
"the",
"source",
"bitmap",
"to",
"the",
"destination",
"bitmap"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L750-L761
|
14,604
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java
|
BitmapUtil.decodeDimensions
|
public static @Nullable Pair<Integer, Integer> decodeDimensions(Uri uri) {
Preconditions.checkNotNull(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(uri.getPath(), options);
return (options.outWidth == -1 || options.outHeight == -1)
? null
: new Pair<>(options.outWidth, options.outHeight);
}
|
java
|
public static @Nullable Pair<Integer, Integer> decodeDimensions(Uri uri) {
Preconditions.checkNotNull(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(uri.getPath(), options);
return (options.outWidth == -1 || options.outHeight == -1)
? null
: new Pair<>(options.outWidth, options.outHeight);
}
|
[
"public",
"static",
"@",
"Nullable",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"decodeDimensions",
"(",
"Uri",
"uri",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"uri",
")",
";",
"BitmapFactory",
".",
"Options",
"options",
"=",
"new",
"BitmapFactory",
".",
"Options",
"(",
")",
";",
"options",
".",
"inJustDecodeBounds",
"=",
"true",
";",
"BitmapFactory",
".",
"decodeFile",
"(",
"uri",
".",
"getPath",
"(",
")",
",",
"options",
")",
";",
"return",
"(",
"options",
".",
"outWidth",
"==",
"-",
"1",
"||",
"options",
".",
"outHeight",
"==",
"-",
"1",
")",
"?",
"null",
":",
"new",
"Pair",
"<>",
"(",
"options",
".",
"outWidth",
",",
"options",
".",
"outHeight",
")",
";",
"}"
] |
Decodes the bounds of an image from its Uri and returns a pair of the dimensions
@param uri the Uri of the image
@return dimensions of the image
|
[
"Decodes",
"the",
"bounds",
"of",
"an",
"image",
"from",
"its",
"Uri",
"and",
"returns",
"a",
"pair",
"of",
"the",
"dimensions"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java#L90-L98
|
14,605
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java
|
BitmapUtil.decodeDimensions
|
public static @Nullable Pair<Integer, Integer> decodeDimensions(InputStream is) {
Preconditions.checkNotNull(is);
ByteBuffer byteBuffer = DECODE_BUFFERS.acquire();
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
options.inTempStorage = byteBuffer.array();
BitmapFactory.decodeStream(is, null, options);
return (options.outWidth == -1 || options.outHeight == -1)
? null
: new Pair<>(options.outWidth, options.outHeight);
} finally {
DECODE_BUFFERS.release(byteBuffer);
}
}
|
java
|
public static @Nullable Pair<Integer, Integer> decodeDimensions(InputStream is) {
Preconditions.checkNotNull(is);
ByteBuffer byteBuffer = DECODE_BUFFERS.acquire();
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
options.inTempStorage = byteBuffer.array();
BitmapFactory.decodeStream(is, null, options);
return (options.outWidth == -1 || options.outHeight == -1)
? null
: new Pair<>(options.outWidth, options.outHeight);
} finally {
DECODE_BUFFERS.release(byteBuffer);
}
}
|
[
"public",
"static",
"@",
"Nullable",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"decodeDimensions",
"(",
"InputStream",
"is",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"is",
")",
";",
"ByteBuffer",
"byteBuffer",
"=",
"DECODE_BUFFERS",
".",
"acquire",
"(",
")",
";",
"if",
"(",
"byteBuffer",
"==",
"null",
")",
"{",
"byteBuffer",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"DECODE_BUFFER_SIZE",
")",
";",
"}",
"BitmapFactory",
".",
"Options",
"options",
"=",
"new",
"BitmapFactory",
".",
"Options",
"(",
")",
";",
"options",
".",
"inJustDecodeBounds",
"=",
"true",
";",
"try",
"{",
"options",
".",
"inTempStorage",
"=",
"byteBuffer",
".",
"array",
"(",
")",
";",
"BitmapFactory",
".",
"decodeStream",
"(",
"is",
",",
"null",
",",
"options",
")",
";",
"return",
"(",
"options",
".",
"outWidth",
"==",
"-",
"1",
"||",
"options",
".",
"outHeight",
"==",
"-",
"1",
")",
"?",
"null",
":",
"new",
"Pair",
"<>",
"(",
"options",
".",
"outWidth",
",",
"options",
".",
"outHeight",
")",
";",
"}",
"finally",
"{",
"DECODE_BUFFERS",
".",
"release",
"(",
"byteBuffer",
")",
";",
"}",
"}"
] |
Decodes the bounds of an image and returns its width and height or null if the size can't be
determined
@param is the InputStream containing the image data
@return dimensions of the image
|
[
"Decodes",
"the",
"bounds",
"of",
"an",
"image",
"and",
"returns",
"its",
"width",
"and",
"height",
"or",
"null",
"if",
"the",
"size",
"can",
"t",
"be",
"determined"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java#L107-L125
|
14,606
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java
|
BitmapUtil.decodeDimensionsAndColorSpace
|
public static ImageMetaData decodeDimensionsAndColorSpace(InputStream is) {
Preconditions.checkNotNull(is);
ByteBuffer byteBuffer = DECODE_BUFFERS.acquire();
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
options.inTempStorage = byteBuffer.array();
BitmapFactory.decodeStream(is, null, options);
ColorSpace colorSpace = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
colorSpace = options.outColorSpace;
}
return new ImageMetaData(options.outWidth, options.outHeight, colorSpace);
} finally {
DECODE_BUFFERS.release(byteBuffer);
}
}
|
java
|
public static ImageMetaData decodeDimensionsAndColorSpace(InputStream is) {
Preconditions.checkNotNull(is);
ByteBuffer byteBuffer = DECODE_BUFFERS.acquire();
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
options.inTempStorage = byteBuffer.array();
BitmapFactory.decodeStream(is, null, options);
ColorSpace colorSpace = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
colorSpace = options.outColorSpace;
}
return new ImageMetaData(options.outWidth, options.outHeight, colorSpace);
} finally {
DECODE_BUFFERS.release(byteBuffer);
}
}
|
[
"public",
"static",
"ImageMetaData",
"decodeDimensionsAndColorSpace",
"(",
"InputStream",
"is",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"is",
")",
";",
"ByteBuffer",
"byteBuffer",
"=",
"DECODE_BUFFERS",
".",
"acquire",
"(",
")",
";",
"if",
"(",
"byteBuffer",
"==",
"null",
")",
"{",
"byteBuffer",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"DECODE_BUFFER_SIZE",
")",
";",
"}",
"BitmapFactory",
".",
"Options",
"options",
"=",
"new",
"BitmapFactory",
".",
"Options",
"(",
")",
";",
"options",
".",
"inJustDecodeBounds",
"=",
"true",
";",
"try",
"{",
"options",
".",
"inTempStorage",
"=",
"byteBuffer",
".",
"array",
"(",
")",
";",
"BitmapFactory",
".",
"decodeStream",
"(",
"is",
",",
"null",
",",
"options",
")",
";",
"ColorSpace",
"colorSpace",
"=",
"null",
";",
"if",
"(",
"android",
".",
"os",
".",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"android",
".",
"os",
".",
"Build",
".",
"VERSION_CODES",
".",
"O",
")",
"{",
"colorSpace",
"=",
"options",
".",
"outColorSpace",
";",
"}",
"return",
"new",
"ImageMetaData",
"(",
"options",
".",
"outWidth",
",",
"options",
".",
"outHeight",
",",
"colorSpace",
")",
";",
"}",
"finally",
"{",
"DECODE_BUFFERS",
".",
"release",
"(",
"byteBuffer",
")",
";",
"}",
"}"
] |
Decodes the bounds of an image and returns its width and height or null if the size can't be
determined. It also recovers the color space of the image, or null if it can't be determined.
@param is the InputStream containing the image data
@return the metadata of the image
|
[
"Decodes",
"the",
"bounds",
"of",
"an",
"image",
"and",
"returns",
"its",
"width",
"and",
"height",
"or",
"null",
"if",
"the",
"size",
"can",
"t",
"be",
"determined",
".",
"It",
"also",
"recovers",
"the",
"color",
"space",
"of",
"the",
"image",
"or",
"null",
"if",
"it",
"can",
"t",
"be",
"determined",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/BitmapUtil.java#L134-L154
|
14,607
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/common/CacheKeyUtil.java
|
CacheKeyUtil.getResourceIds
|
public static List<String> getResourceIds(final CacheKey key) {
try {
final List<String> ids;
if (key instanceof MultiCacheKey) {
List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
ids = new ArrayList<>(keys.size());
for (int i = 0; i < keys.size(); i++) {
ids.add(secureHashKey(keys.get(i)));
}
} else {
ids = new ArrayList<>(1);
ids.add(secureHashKey(key));
}
return ids;
} catch (UnsupportedEncodingException e) {
// This should never happen. All VMs support UTF-8
throw new RuntimeException(e);
}
}
|
java
|
public static List<String> getResourceIds(final CacheKey key) {
try {
final List<String> ids;
if (key instanceof MultiCacheKey) {
List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
ids = new ArrayList<>(keys.size());
for (int i = 0; i < keys.size(); i++) {
ids.add(secureHashKey(keys.get(i)));
}
} else {
ids = new ArrayList<>(1);
ids.add(secureHashKey(key));
}
return ids;
} catch (UnsupportedEncodingException e) {
// This should never happen. All VMs support UTF-8
throw new RuntimeException(e);
}
}
|
[
"public",
"static",
"List",
"<",
"String",
">",
"getResourceIds",
"(",
"final",
"CacheKey",
"key",
")",
"{",
"try",
"{",
"final",
"List",
"<",
"String",
">",
"ids",
";",
"if",
"(",
"key",
"instanceof",
"MultiCacheKey",
")",
"{",
"List",
"<",
"CacheKey",
">",
"keys",
"=",
"(",
"(",
"MultiCacheKey",
")",
"key",
")",
".",
"getCacheKeys",
"(",
")",
";",
"ids",
"=",
"new",
"ArrayList",
"<>",
"(",
"keys",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"ids",
".",
"add",
"(",
"secureHashKey",
"(",
"keys",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"}",
"else",
"{",
"ids",
"=",
"new",
"ArrayList",
"<>",
"(",
"1",
")",
";",
"ids",
".",
"add",
"(",
"secureHashKey",
"(",
"key",
")",
")",
";",
"}",
"return",
"ids",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// This should never happen. All VMs support UTF-8",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Get a list of possible resourceIds from MultiCacheKey or get single resourceId from CacheKey.
|
[
"Get",
"a",
"list",
"of",
"possible",
"resourceIds",
"from",
"MultiCacheKey",
"or",
"get",
"single",
"resourceId",
"from",
"CacheKey",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/common/CacheKeyUtil.java#L19-L37
|
14,608
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/common/CacheKeyUtil.java
|
CacheKeyUtil.getFirstResourceId
|
public static String getFirstResourceId(final CacheKey key) {
try {
if (key instanceof MultiCacheKey) {
List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
return secureHashKey(keys.get(0));
} else {
return secureHashKey(key);
}
} catch (UnsupportedEncodingException e) {
// This should never happen. All VMs support UTF-8
throw new RuntimeException(e);
}
}
|
java
|
public static String getFirstResourceId(final CacheKey key) {
try {
if (key instanceof MultiCacheKey) {
List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
return secureHashKey(keys.get(0));
} else {
return secureHashKey(key);
}
} catch (UnsupportedEncodingException e) {
// This should never happen. All VMs support UTF-8
throw new RuntimeException(e);
}
}
|
[
"public",
"static",
"String",
"getFirstResourceId",
"(",
"final",
"CacheKey",
"key",
")",
"{",
"try",
"{",
"if",
"(",
"key",
"instanceof",
"MultiCacheKey",
")",
"{",
"List",
"<",
"CacheKey",
">",
"keys",
"=",
"(",
"(",
"MultiCacheKey",
")",
"key",
")",
".",
"getCacheKeys",
"(",
")",
";",
"return",
"secureHashKey",
"(",
"keys",
".",
"get",
"(",
"0",
")",
")",
";",
"}",
"else",
"{",
"return",
"secureHashKey",
"(",
"key",
")",
";",
"}",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// This should never happen. All VMs support UTF-8",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Get the resourceId from the first key in MultiCacheKey or get single resourceId from CacheKey.
|
[
"Get",
"the",
"resourceId",
"from",
"the",
"first",
"key",
"in",
"MultiCacheKey",
"or",
"get",
"single",
"resourceId",
"from",
"CacheKey",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/common/CacheKeyUtil.java#L42-L54
|
14,609
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.fetchImageFromBitmapCache
|
public DataSource<CloseableReference<CloseableImage>> fetchImageFromBitmapCache(
ImageRequest imageRequest,
Object callerContext) {
return fetchDecodedImage(
imageRequest,
callerContext,
ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
}
|
java
|
public DataSource<CloseableReference<CloseableImage>> fetchImageFromBitmapCache(
ImageRequest imageRequest,
Object callerContext) {
return fetchDecodedImage(
imageRequest,
callerContext,
ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
}
|
[
"public",
"DataSource",
"<",
"CloseableReference",
"<",
"CloseableImage",
">",
">",
"fetchImageFromBitmapCache",
"(",
"ImageRequest",
"imageRequest",
",",
"Object",
"callerContext",
")",
"{",
"return",
"fetchDecodedImage",
"(",
"imageRequest",
",",
"callerContext",
",",
"ImageRequest",
".",
"RequestLevel",
".",
"BITMAP_MEMORY_CACHE",
")",
";",
"}"
] |
Submits a request for bitmap cache lookup.
@param imageRequest the request to submit
@param callerContext the caller context for image request
@return a DataSource representing the image
|
[
"Submits",
"a",
"request",
"for",
"bitmap",
"cache",
"lookup",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L195-L202
|
14,610
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.prefetchToBitmapCache
|
public DataSource<Void> prefetchToBitmapCache(
ImageRequest imageRequest,
Object callerContext) {
if (!mIsPrefetchEnabledSupplier.get()) {
return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
}
try {
final Boolean shouldDecodePrefetches = imageRequest.shouldDecodePrefetches();
final boolean skipBitmapCache =
shouldDecodePrefetches != null
? !shouldDecodePrefetches // use imagerequest param if specified
: mSuppressBitmapPrefetchingSupplier
.get(); // otherwise fall back to pipeline's default
Producer<Void> producerSequence =
skipBitmapCache
? mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest)
: mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest);
return submitPrefetchRequest(
producerSequence,
imageRequest,
ImageRequest.RequestLevel.FULL_FETCH,
callerContext,
Priority.MEDIUM);
} catch (Exception exception) {
return DataSources.immediateFailedDataSource(exception);
}
}
|
java
|
public DataSource<Void> prefetchToBitmapCache(
ImageRequest imageRequest,
Object callerContext) {
if (!mIsPrefetchEnabledSupplier.get()) {
return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
}
try {
final Boolean shouldDecodePrefetches = imageRequest.shouldDecodePrefetches();
final boolean skipBitmapCache =
shouldDecodePrefetches != null
? !shouldDecodePrefetches // use imagerequest param if specified
: mSuppressBitmapPrefetchingSupplier
.get(); // otherwise fall back to pipeline's default
Producer<Void> producerSequence =
skipBitmapCache
? mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest)
: mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest);
return submitPrefetchRequest(
producerSequence,
imageRequest,
ImageRequest.RequestLevel.FULL_FETCH,
callerContext,
Priority.MEDIUM);
} catch (Exception exception) {
return DataSources.immediateFailedDataSource(exception);
}
}
|
[
"public",
"DataSource",
"<",
"Void",
">",
"prefetchToBitmapCache",
"(",
"ImageRequest",
"imageRequest",
",",
"Object",
"callerContext",
")",
"{",
"if",
"(",
"!",
"mIsPrefetchEnabledSupplier",
".",
"get",
"(",
")",
")",
"{",
"return",
"DataSources",
".",
"immediateFailedDataSource",
"(",
"PREFETCH_EXCEPTION",
")",
";",
"}",
"try",
"{",
"final",
"Boolean",
"shouldDecodePrefetches",
"=",
"imageRequest",
".",
"shouldDecodePrefetches",
"(",
")",
";",
"final",
"boolean",
"skipBitmapCache",
"=",
"shouldDecodePrefetches",
"!=",
"null",
"?",
"!",
"shouldDecodePrefetches",
"// use imagerequest param if specified",
":",
"mSuppressBitmapPrefetchingSupplier",
".",
"get",
"(",
")",
";",
"// otherwise fall back to pipeline's default",
"Producer",
"<",
"Void",
">",
"producerSequence",
"=",
"skipBitmapCache",
"?",
"mProducerSequenceFactory",
".",
"getEncodedImagePrefetchProducerSequence",
"(",
"imageRequest",
")",
":",
"mProducerSequenceFactory",
".",
"getDecodedImagePrefetchProducerSequence",
"(",
"imageRequest",
")",
";",
"return",
"submitPrefetchRequest",
"(",
"producerSequence",
",",
"imageRequest",
",",
"ImageRequest",
".",
"RequestLevel",
".",
"FULL_FETCH",
",",
"callerContext",
",",
"Priority",
".",
"MEDIUM",
")",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"return",
"DataSources",
".",
"immediateFailedDataSource",
"(",
"exception",
")",
";",
"}",
"}"
] |
Submits a request for prefetching to the bitmap cache.
<p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow
down images which are immediately required on screen.
@param imageRequest the request to submit
@return a DataSource that can safely be ignored.
|
[
"Submits",
"a",
"request",
"for",
"prefetching",
"to",
"the",
"bitmap",
"cache",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L350-L376
|
14,611
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.prefetchToDiskCache
|
public DataSource<Void> prefetchToDiskCache(
ImageRequest imageRequest,
Object callerContext) {
return prefetchToDiskCache(imageRequest, callerContext, Priority.MEDIUM);
}
|
java
|
public DataSource<Void> prefetchToDiskCache(
ImageRequest imageRequest,
Object callerContext) {
return prefetchToDiskCache(imageRequest, callerContext, Priority.MEDIUM);
}
|
[
"public",
"DataSource",
"<",
"Void",
">",
"prefetchToDiskCache",
"(",
"ImageRequest",
"imageRequest",
",",
"Object",
"callerContext",
")",
"{",
"return",
"prefetchToDiskCache",
"(",
"imageRequest",
",",
"callerContext",
",",
"Priority",
".",
"MEDIUM",
")",
";",
"}"
] |
Submits a request for prefetching to the disk cache with a default priority.
<p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow
down images which are immediately required on screen.
@param imageRequest the request to submit
@return a DataSource that can safely be ignored.
|
[
"Submits",
"a",
"request",
"for",
"prefetching",
"to",
"the",
"disk",
"cache",
"with",
"a",
"default",
"priority",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L387-L391
|
14,612
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.prefetchToDiskCache
|
public DataSource<Void> prefetchToDiskCache(
ImageRequest imageRequest,
Object callerContext,
Priority priority) {
if (!mIsPrefetchEnabledSupplier.get()) {
return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
}
try {
Producer<Void> producerSequence =
mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest);
return submitPrefetchRequest(
producerSequence,
imageRequest,
ImageRequest.RequestLevel.FULL_FETCH,
callerContext,
priority);
} catch (Exception exception) {
return DataSources.immediateFailedDataSource(exception);
}
}
|
java
|
public DataSource<Void> prefetchToDiskCache(
ImageRequest imageRequest,
Object callerContext,
Priority priority) {
if (!mIsPrefetchEnabledSupplier.get()) {
return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
}
try {
Producer<Void> producerSequence =
mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest);
return submitPrefetchRequest(
producerSequence,
imageRequest,
ImageRequest.RequestLevel.FULL_FETCH,
callerContext,
priority);
} catch (Exception exception) {
return DataSources.immediateFailedDataSource(exception);
}
}
|
[
"public",
"DataSource",
"<",
"Void",
">",
"prefetchToDiskCache",
"(",
"ImageRequest",
"imageRequest",
",",
"Object",
"callerContext",
",",
"Priority",
"priority",
")",
"{",
"if",
"(",
"!",
"mIsPrefetchEnabledSupplier",
".",
"get",
"(",
")",
")",
"{",
"return",
"DataSources",
".",
"immediateFailedDataSource",
"(",
"PREFETCH_EXCEPTION",
")",
";",
"}",
"try",
"{",
"Producer",
"<",
"Void",
">",
"producerSequence",
"=",
"mProducerSequenceFactory",
".",
"getEncodedImagePrefetchProducerSequence",
"(",
"imageRequest",
")",
";",
"return",
"submitPrefetchRequest",
"(",
"producerSequence",
",",
"imageRequest",
",",
"ImageRequest",
".",
"RequestLevel",
".",
"FULL_FETCH",
",",
"callerContext",
",",
"priority",
")",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"return",
"DataSources",
".",
"immediateFailedDataSource",
"(",
"exception",
")",
";",
"}",
"}"
] |
Submits a request for prefetching to the disk cache.
<p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow
down images which are immediately required on screen.
@param imageRequest the request to submit
@param priority custom priority for the fetch
@return a DataSource that can safely be ignored.
|
[
"Submits",
"a",
"request",
"for",
"prefetching",
"to",
"the",
"disk",
"cache",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L403-L422
|
14,613
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.clearMemoryCaches
|
public void clearMemoryCaches() {
Predicate<CacheKey> allPredicate =
new Predicate<CacheKey>() {
@Override
public boolean apply(CacheKey key) {
return true;
}
};
mBitmapMemoryCache.removeAll(allPredicate);
mEncodedMemoryCache.removeAll(allPredicate);
}
|
java
|
public void clearMemoryCaches() {
Predicate<CacheKey> allPredicate =
new Predicate<CacheKey>() {
@Override
public boolean apply(CacheKey key) {
return true;
}
};
mBitmapMemoryCache.removeAll(allPredicate);
mEncodedMemoryCache.removeAll(allPredicate);
}
|
[
"public",
"void",
"clearMemoryCaches",
"(",
")",
"{",
"Predicate",
"<",
"CacheKey",
">",
"allPredicate",
"=",
"new",
"Predicate",
"<",
"CacheKey",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"CacheKey",
"key",
")",
"{",
"return",
"true",
";",
"}",
"}",
";",
"mBitmapMemoryCache",
".",
"removeAll",
"(",
"allPredicate",
")",
";",
"mEncodedMemoryCache",
".",
"removeAll",
"(",
"allPredicate",
")",
";",
"}"
] |
Clear the memory caches
|
[
"Clear",
"the",
"memory",
"caches"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L473-L483
|
14,614
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.isInDiskCacheSync
|
public boolean isInDiskCacheSync(final ImageRequest imageRequest) {
final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice();
switch (cacheChoice) {
case DEFAULT:
return mMainBufferedDiskCache.diskCheckSync(cacheKey);
case SMALL:
return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey);
default:
return false;
}
}
|
java
|
public boolean isInDiskCacheSync(final ImageRequest imageRequest) {
final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice();
switch (cacheChoice) {
case DEFAULT:
return mMainBufferedDiskCache.diskCheckSync(cacheKey);
case SMALL:
return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey);
default:
return false;
}
}
|
[
"public",
"boolean",
"isInDiskCacheSync",
"(",
"final",
"ImageRequest",
"imageRequest",
")",
"{",
"final",
"CacheKey",
"cacheKey",
"=",
"mCacheKeyFactory",
".",
"getEncodedCacheKey",
"(",
"imageRequest",
",",
"null",
")",
";",
"final",
"ImageRequest",
".",
"CacheChoice",
"cacheChoice",
"=",
"imageRequest",
".",
"getCacheChoice",
"(",
")",
";",
"switch",
"(",
"cacheChoice",
")",
"{",
"case",
"DEFAULT",
":",
"return",
"mMainBufferedDiskCache",
".",
"diskCheckSync",
"(",
"cacheKey",
")",
";",
"case",
"SMALL",
":",
"return",
"mSmallImageBufferedDiskCache",
".",
"diskCheckSync",
"(",
"cacheKey",
")",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Performs disk cache check synchronously. It is not recommended to use this
unless you know what exactly you are doing. Disk cache check is a costly operation,
the call will block the caller thread until the cache check is completed.
@param imageRequest the imageRequest for the image to be looked up.
@return true if the image was found in the disk cache, false otherwise.
|
[
"Performs",
"disk",
"cache",
"check",
"synchronously",
".",
"It",
"is",
"not",
"recommended",
"to",
"use",
"this",
"unless",
"you",
"know",
"what",
"exactly",
"you",
"are",
"doing",
".",
"Disk",
"cache",
"check",
"is",
"a",
"costly",
"operation",
"the",
"call",
"will",
"block",
"the",
"caller",
"thread",
"until",
"the",
"cache",
"check",
"is",
"completed",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L590-L602
|
14,615
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java
|
ImagePipeline.isInDiskCache
|
public DataSource<Boolean> isInDiskCache(final ImageRequest imageRequest) {
final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
final SimpleDataSource<Boolean> dataSource = SimpleDataSource.create();
mMainBufferedDiskCache.contains(cacheKey)
.continueWithTask(
new Continuation<Boolean, Task<Boolean>>() {
@Override
public Task<Boolean> then(Task<Boolean> task) throws Exception {
if (!task.isCancelled() && !task.isFaulted() && task.getResult()) {
return Task.forResult(true);
}
return mSmallImageBufferedDiskCache.contains(cacheKey);
}
})
.continueWith(
new Continuation<Boolean, Void>() {
@Override
public Void then(Task<Boolean> task) throws Exception {
dataSource.setResult(!task.isCancelled() && !task.isFaulted() && task.getResult());
return null;
}
});
return dataSource;
}
|
java
|
public DataSource<Boolean> isInDiskCache(final ImageRequest imageRequest) {
final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
final SimpleDataSource<Boolean> dataSource = SimpleDataSource.create();
mMainBufferedDiskCache.contains(cacheKey)
.continueWithTask(
new Continuation<Boolean, Task<Boolean>>() {
@Override
public Task<Boolean> then(Task<Boolean> task) throws Exception {
if (!task.isCancelled() && !task.isFaulted() && task.getResult()) {
return Task.forResult(true);
}
return mSmallImageBufferedDiskCache.contains(cacheKey);
}
})
.continueWith(
new Continuation<Boolean, Void>() {
@Override
public Void then(Task<Boolean> task) throws Exception {
dataSource.setResult(!task.isCancelled() && !task.isFaulted() && task.getResult());
return null;
}
});
return dataSource;
}
|
[
"public",
"DataSource",
"<",
"Boolean",
">",
"isInDiskCache",
"(",
"final",
"ImageRequest",
"imageRequest",
")",
"{",
"final",
"CacheKey",
"cacheKey",
"=",
"mCacheKeyFactory",
".",
"getEncodedCacheKey",
"(",
"imageRequest",
",",
"null",
")",
";",
"final",
"SimpleDataSource",
"<",
"Boolean",
">",
"dataSource",
"=",
"SimpleDataSource",
".",
"create",
"(",
")",
";",
"mMainBufferedDiskCache",
".",
"contains",
"(",
"cacheKey",
")",
".",
"continueWithTask",
"(",
"new",
"Continuation",
"<",
"Boolean",
",",
"Task",
"<",
"Boolean",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Task",
"<",
"Boolean",
">",
"then",
"(",
"Task",
"<",
"Boolean",
">",
"task",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"task",
".",
"isCancelled",
"(",
")",
"&&",
"!",
"task",
".",
"isFaulted",
"(",
")",
"&&",
"task",
".",
"getResult",
"(",
")",
")",
"{",
"return",
"Task",
".",
"forResult",
"(",
"true",
")",
";",
"}",
"return",
"mSmallImageBufferedDiskCache",
".",
"contains",
"(",
"cacheKey",
")",
";",
"}",
"}",
")",
".",
"continueWith",
"(",
"new",
"Continuation",
"<",
"Boolean",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"then",
"(",
"Task",
"<",
"Boolean",
">",
"task",
")",
"throws",
"Exception",
"{",
"dataSource",
".",
"setResult",
"(",
"!",
"task",
".",
"isCancelled",
"(",
")",
"&&",
"!",
"task",
".",
"isFaulted",
"(",
")",
"&&",
"task",
".",
"getResult",
"(",
")",
")",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"return",
"dataSource",
";",
"}"
] |
Returns whether the image is stored in the disk cache.
@param imageRequest the imageRequest for the image to be looked up.
@return true if the image was found in the disk cache, false otherwise.
|
[
"Returns",
"whether",
"the",
"image",
"is",
"stored",
"in",
"the",
"disk",
"cache",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipeline.java#L624-L647
|
14,616
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.getParentDrawableAtIndex
|
private DrawableParent getParentDrawableAtIndex(int index) {
DrawableParent parent = mFadeDrawable.getDrawableParentForIndex(index);
if (parent.getDrawable() instanceof MatrixDrawable) {
parent = (MatrixDrawable) parent.getDrawable();
}
if (parent.getDrawable() instanceof ScaleTypeDrawable) {
parent = (ScaleTypeDrawable) parent.getDrawable();
}
return parent;
}
|
java
|
private DrawableParent getParentDrawableAtIndex(int index) {
DrawableParent parent = mFadeDrawable.getDrawableParentForIndex(index);
if (parent.getDrawable() instanceof MatrixDrawable) {
parent = (MatrixDrawable) parent.getDrawable();
}
if (parent.getDrawable() instanceof ScaleTypeDrawable) {
parent = (ScaleTypeDrawable) parent.getDrawable();
}
return parent;
}
|
[
"private",
"DrawableParent",
"getParentDrawableAtIndex",
"(",
"int",
"index",
")",
"{",
"DrawableParent",
"parent",
"=",
"mFadeDrawable",
".",
"getDrawableParentForIndex",
"(",
"index",
")",
";",
"if",
"(",
"parent",
".",
"getDrawable",
"(",
")",
"instanceof",
"MatrixDrawable",
")",
"{",
"parent",
"=",
"(",
"MatrixDrawable",
")",
"parent",
".",
"getDrawable",
"(",
")",
";",
"}",
"if",
"(",
"parent",
".",
"getDrawable",
"(",
")",
"instanceof",
"ScaleTypeDrawable",
")",
"{",
"parent",
"=",
"(",
"ScaleTypeDrawable",
")",
"parent",
".",
"getDrawable",
"(",
")",
";",
"}",
"return",
"parent",
";",
"}"
] |
Gets the lowest parent drawable for the layer at the specified index.
Following drawables are considered as parents: FadeDrawable, MatrixDrawable, ScaleTypeDrawable.
This is because those drawables are added automatically by the hierarchy (if specified),
whereas their children are created externally by the client code. When we need to change the
previously set drawable this is the parent whose child needs to be replaced.
|
[
"Gets",
"the",
"lowest",
"parent",
"drawable",
"for",
"the",
"layer",
"at",
"the",
"specified",
"index",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L326-L335
|
14,617
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.getScaleTypeDrawableAtIndex
|
private ScaleTypeDrawable getScaleTypeDrawableAtIndex(int index) {
DrawableParent parent = getParentDrawableAtIndex(index);
if (parent instanceof ScaleTypeDrawable) {
return (ScaleTypeDrawable) parent;
} else {
return WrappingUtils.wrapChildWithScaleType(parent, ScalingUtils.ScaleType.FIT_XY);
}
}
|
java
|
private ScaleTypeDrawable getScaleTypeDrawableAtIndex(int index) {
DrawableParent parent = getParentDrawableAtIndex(index);
if (parent instanceof ScaleTypeDrawable) {
return (ScaleTypeDrawable) parent;
} else {
return WrappingUtils.wrapChildWithScaleType(parent, ScalingUtils.ScaleType.FIT_XY);
}
}
|
[
"private",
"ScaleTypeDrawable",
"getScaleTypeDrawableAtIndex",
"(",
"int",
"index",
")",
"{",
"DrawableParent",
"parent",
"=",
"getParentDrawableAtIndex",
"(",
"index",
")",
";",
"if",
"(",
"parent",
"instanceof",
"ScaleTypeDrawable",
")",
"{",
"return",
"(",
"ScaleTypeDrawable",
")",
"parent",
";",
"}",
"else",
"{",
"return",
"WrappingUtils",
".",
"wrapChildWithScaleType",
"(",
"parent",
",",
"ScalingUtils",
".",
"ScaleType",
".",
"FIT_XY",
")",
";",
"}",
"}"
] |
Gets the ScaleTypeDrawable at the specified index.
In case there is no child at the specified index, a NullPointerException is thrown.
In case there is a child, but the ScaleTypeDrawable does not exist,
the child will be wrapped with a new ScaleTypeDrawable.
|
[
"Gets",
"the",
"ScaleTypeDrawable",
"at",
"the",
"specified",
"index",
".",
"In",
"case",
"there",
"is",
"no",
"child",
"at",
"the",
"specified",
"index",
"a",
"NullPointerException",
"is",
"thrown",
".",
"In",
"case",
"there",
"is",
"a",
"child",
"but",
"the",
"ScaleTypeDrawable",
"does",
"not",
"exist",
"the",
"child",
"will",
"be",
"wrapped",
"with",
"a",
"new",
"ScaleTypeDrawable",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L356-L363
|
14,618
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.setActualImageFocusPoint
|
public void setActualImageFocusPoint(PointF focusPoint) {
Preconditions.checkNotNull(focusPoint);
getScaleTypeDrawableAtIndex(ACTUAL_IMAGE_INDEX).setFocusPoint(focusPoint);
}
|
java
|
public void setActualImageFocusPoint(PointF focusPoint) {
Preconditions.checkNotNull(focusPoint);
getScaleTypeDrawableAtIndex(ACTUAL_IMAGE_INDEX).setFocusPoint(focusPoint);
}
|
[
"public",
"void",
"setActualImageFocusPoint",
"(",
"PointF",
"focusPoint",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"focusPoint",
")",
";",
"getScaleTypeDrawableAtIndex",
"(",
"ACTUAL_IMAGE_INDEX",
")",
".",
"setFocusPoint",
"(",
"focusPoint",
")",
";",
"}"
] |
Sets the actual image focus point.
|
[
"Sets",
"the",
"actual",
"image",
"focus",
"point",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L386-L389
|
14,619
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.setActualImageScaleType
|
public void setActualImageScaleType(ScalingUtils.ScaleType scaleType) {
Preconditions.checkNotNull(scaleType);
getScaleTypeDrawableAtIndex(ACTUAL_IMAGE_INDEX).setScaleType(scaleType);
}
|
java
|
public void setActualImageScaleType(ScalingUtils.ScaleType scaleType) {
Preconditions.checkNotNull(scaleType);
getScaleTypeDrawableAtIndex(ACTUAL_IMAGE_INDEX).setScaleType(scaleType);
}
|
[
"public",
"void",
"setActualImageScaleType",
"(",
"ScalingUtils",
".",
"ScaleType",
"scaleType",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"scaleType",
")",
";",
"getScaleTypeDrawableAtIndex",
"(",
"ACTUAL_IMAGE_INDEX",
")",
".",
"setScaleType",
"(",
"scaleType",
")",
";",
"}"
] |
Sets the actual image scale type.
|
[
"Sets",
"the",
"actual",
"image",
"scale",
"type",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L392-L395
|
14,620
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.setPlaceholderImageFocusPoint
|
public void setPlaceholderImageFocusPoint(PointF focusPoint) {
Preconditions.checkNotNull(focusPoint);
getScaleTypeDrawableAtIndex(PLACEHOLDER_IMAGE_INDEX).setFocusPoint(focusPoint);
}
|
java
|
public void setPlaceholderImageFocusPoint(PointF focusPoint) {
Preconditions.checkNotNull(focusPoint);
getScaleTypeDrawableAtIndex(PLACEHOLDER_IMAGE_INDEX).setFocusPoint(focusPoint);
}
|
[
"public",
"void",
"setPlaceholderImageFocusPoint",
"(",
"PointF",
"focusPoint",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"focusPoint",
")",
";",
"getScaleTypeDrawableAtIndex",
"(",
"PLACEHOLDER_IMAGE_INDEX",
")",
".",
"setFocusPoint",
"(",
"focusPoint",
")",
";",
"}"
] |
Sets the placeholder image focus point.
|
[
"Sets",
"the",
"placeholder",
"image",
"focus",
"point",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L433-L436
|
14,621
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java
|
BasePool.release
|
@Override
public void release(V value) {
Preconditions.checkNotNull(value);
final int bucketedSize = getBucketedSizeForValue(value);
final int sizeInBytes = getSizeInBytes(bucketedSize);
synchronized (this) {
final Bucket<V> bucket = getBucketIfPresent(bucketedSize);
if (!mInUseValues.remove(value)) {
// This value was not 'known' to the pool (i.e.) allocated via the pool.
// Something is going wrong, so let's free the value and report soft error.
FLog.e(
TAG,
"release (free, value unrecognized) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
free(value);
mPoolStatsTracker.onFree(sizeInBytes);
} else {
// free the value, if
// - pool exceeds maxSize
// - there is no bucket for this value
// - there is a bucket for this value, but it has exceeded its maxLength
// - the value is not reusable
// If no bucket was found for the value, simply free it
// We should free the value if no bucket is found, or if the bucket length cap is exceeded.
// However, if the pool max size softcap is exceeded, it may not always be best to free
// *this* value.
if (bucket == null ||
bucket.isMaxLengthExceeded() ||
isMaxSizeSoftCapExceeded() ||
!isReusable(value)) {
if (bucket != null) {
bucket.decrementInUseCount();
}
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"release (free) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
}
free(value);
mUsed.decrement(sizeInBytes);
mPoolStatsTracker.onFree(sizeInBytes);
} else {
bucket.release(value);
mFree.increment(sizeInBytes);
mUsed.decrement(sizeInBytes);
mPoolStatsTracker.onValueRelease(sizeInBytes);
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"release (reuse) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
}
}
}
logStats();
}
}
|
java
|
@Override
public void release(V value) {
Preconditions.checkNotNull(value);
final int bucketedSize = getBucketedSizeForValue(value);
final int sizeInBytes = getSizeInBytes(bucketedSize);
synchronized (this) {
final Bucket<V> bucket = getBucketIfPresent(bucketedSize);
if (!mInUseValues.remove(value)) {
// This value was not 'known' to the pool (i.e.) allocated via the pool.
// Something is going wrong, so let's free the value and report soft error.
FLog.e(
TAG,
"release (free, value unrecognized) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
free(value);
mPoolStatsTracker.onFree(sizeInBytes);
} else {
// free the value, if
// - pool exceeds maxSize
// - there is no bucket for this value
// - there is a bucket for this value, but it has exceeded its maxLength
// - the value is not reusable
// If no bucket was found for the value, simply free it
// We should free the value if no bucket is found, or if the bucket length cap is exceeded.
// However, if the pool max size softcap is exceeded, it may not always be best to free
// *this* value.
if (bucket == null ||
bucket.isMaxLengthExceeded() ||
isMaxSizeSoftCapExceeded() ||
!isReusable(value)) {
if (bucket != null) {
bucket.decrementInUseCount();
}
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"release (free) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
}
free(value);
mUsed.decrement(sizeInBytes);
mPoolStatsTracker.onFree(sizeInBytes);
} else {
bucket.release(value);
mFree.increment(sizeInBytes);
mUsed.decrement(sizeInBytes);
mPoolStatsTracker.onValueRelease(sizeInBytes);
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"release (reuse) (object, size) = (%x, %s)",
System.identityHashCode(value),
bucketedSize);
}
}
}
logStats();
}
}
|
[
"@",
"Override",
"public",
"void",
"release",
"(",
"V",
"value",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"value",
")",
";",
"final",
"int",
"bucketedSize",
"=",
"getBucketedSizeForValue",
"(",
"value",
")",
";",
"final",
"int",
"sizeInBytes",
"=",
"getSizeInBytes",
"(",
"bucketedSize",
")",
";",
"synchronized",
"(",
"this",
")",
"{",
"final",
"Bucket",
"<",
"V",
">",
"bucket",
"=",
"getBucketIfPresent",
"(",
"bucketedSize",
")",
";",
"if",
"(",
"!",
"mInUseValues",
".",
"remove",
"(",
"value",
")",
")",
"{",
"// This value was not 'known' to the pool (i.e.) allocated via the pool.",
"// Something is going wrong, so let's free the value and report soft error.",
"FLog",
".",
"e",
"(",
"TAG",
",",
"\"release (free, value unrecognized) (object, size) = (%x, %s)\"",
",",
"System",
".",
"identityHashCode",
"(",
"value",
")",
",",
"bucketedSize",
")",
";",
"free",
"(",
"value",
")",
";",
"mPoolStatsTracker",
".",
"onFree",
"(",
"sizeInBytes",
")",
";",
"}",
"else",
"{",
"// free the value, if",
"// - pool exceeds maxSize",
"// - there is no bucket for this value",
"// - there is a bucket for this value, but it has exceeded its maxLength",
"// - the value is not reusable",
"// If no bucket was found for the value, simply free it",
"// We should free the value if no bucket is found, or if the bucket length cap is exceeded.",
"// However, if the pool max size softcap is exceeded, it may not always be best to free",
"// *this* value.",
"if",
"(",
"bucket",
"==",
"null",
"||",
"bucket",
".",
"isMaxLengthExceeded",
"(",
")",
"||",
"isMaxSizeSoftCapExceeded",
"(",
")",
"||",
"!",
"isReusable",
"(",
"value",
")",
")",
"{",
"if",
"(",
"bucket",
"!=",
"null",
")",
"{",
"bucket",
".",
"decrementInUseCount",
"(",
")",
";",
"}",
"if",
"(",
"FLog",
".",
"isLoggable",
"(",
"FLog",
".",
"VERBOSE",
")",
")",
"{",
"FLog",
".",
"v",
"(",
"TAG",
",",
"\"release (free) (object, size) = (%x, %s)\"",
",",
"System",
".",
"identityHashCode",
"(",
"value",
")",
",",
"bucketedSize",
")",
";",
"}",
"free",
"(",
"value",
")",
";",
"mUsed",
".",
"decrement",
"(",
"sizeInBytes",
")",
";",
"mPoolStatsTracker",
".",
"onFree",
"(",
"sizeInBytes",
")",
";",
"}",
"else",
"{",
"bucket",
".",
"release",
"(",
"value",
")",
";",
"mFree",
".",
"increment",
"(",
"sizeInBytes",
")",
";",
"mUsed",
".",
"decrement",
"(",
"sizeInBytes",
")",
";",
"mPoolStatsTracker",
".",
"onValueRelease",
"(",
"sizeInBytes",
")",
";",
"if",
"(",
"FLog",
".",
"isLoggable",
"(",
"FLog",
".",
"VERBOSE",
")",
")",
"{",
"FLog",
".",
"v",
"(",
"TAG",
",",
"\"release (reuse) (object, size) = (%x, %s)\"",
",",
"System",
".",
"identityHashCode",
"(",
"value",
")",
",",
"bucketedSize",
")",
";",
"}",
"}",
"}",
"logStats",
"(",
")",
";",
"}",
"}"
] |
Releases the given value to the pool.
In a few cases, the value is 'freed' instead of being released to the pool. If
- the pool currently exceeds its max size OR
- if the value does not map to a bucket that's currently maintained by the pool, OR
- if the bucket for the value exceeds its maxLength, OR
- if the value is not recognized by the pool
then, the value is 'freed'.
@param value the value to release to the pool
|
[
"Releases",
"the",
"given",
"value",
"to",
"the",
"pool",
".",
"In",
"a",
"few",
"cases",
"the",
"value",
"is",
"freed",
"instead",
"of",
"being",
"released",
"to",
"the",
"pool",
".",
"If",
"-",
"the",
"pool",
"currently",
"exceeds",
"its",
"max",
"size",
"OR",
"-",
"if",
"the",
"value",
"does",
"not",
"map",
"to",
"a",
"bucket",
"that",
"s",
"currently",
"maintained",
"by",
"the",
"pool",
"OR",
"-",
"if",
"the",
"bucket",
"for",
"the",
"value",
"exceeds",
"its",
"maxLength",
"OR",
"-",
"if",
"the",
"value",
"is",
"not",
"recognized",
"by",
"the",
"pool",
"then",
"the",
"value",
"is",
"freed",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java#L313-L375
|
14,622
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java
|
BasePool.getBucket
|
@VisibleForTesting
synchronized Bucket<V> getBucket(int bucketedSize) {
// get an existing bucket
Bucket<V> bucket = mBuckets.get(bucketedSize);
if (bucket != null || !mAllowNewBuckets) {
return bucket;
}
// create a new bucket
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(TAG, "creating new bucket %s", bucketedSize);
}
Bucket<V> newBucket = newBucket(bucketedSize);
mBuckets.put(bucketedSize, newBucket);
return newBucket;
}
|
java
|
@VisibleForTesting
synchronized Bucket<V> getBucket(int bucketedSize) {
// get an existing bucket
Bucket<V> bucket = mBuckets.get(bucketedSize);
if (bucket != null || !mAllowNewBuckets) {
return bucket;
}
// create a new bucket
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(TAG, "creating new bucket %s", bucketedSize);
}
Bucket<V> newBucket = newBucket(bucketedSize);
mBuckets.put(bucketedSize, newBucket);
return newBucket;
}
|
[
"@",
"VisibleForTesting",
"synchronized",
"Bucket",
"<",
"V",
">",
"getBucket",
"(",
"int",
"bucketedSize",
")",
"{",
"// get an existing bucket",
"Bucket",
"<",
"V",
">",
"bucket",
"=",
"mBuckets",
".",
"get",
"(",
"bucketedSize",
")",
";",
"if",
"(",
"bucket",
"!=",
"null",
"||",
"!",
"mAllowNewBuckets",
")",
"{",
"return",
"bucket",
";",
"}",
"// create a new bucket",
"if",
"(",
"FLog",
".",
"isLoggable",
"(",
"FLog",
".",
"VERBOSE",
")",
")",
"{",
"FLog",
".",
"v",
"(",
"TAG",
",",
"\"creating new bucket %s\"",
",",
"bucketedSize",
")",
";",
"}",
"Bucket",
"<",
"V",
">",
"newBucket",
"=",
"newBucket",
"(",
"bucketedSize",
")",
";",
"mBuckets",
".",
"put",
"(",
"bucketedSize",
",",
"newBucket",
")",
";",
"return",
"newBucket",
";",
"}"
] |
Gets the freelist for the specified bucket. Create the freelist if there isn't one
@param bucketedSize the bucket size
@return the freelist for the bucket
|
[
"Gets",
"the",
"freelist",
"for",
"the",
"specified",
"bucket",
".",
"Create",
"the",
"freelist",
"if",
"there",
"isn",
"t",
"one"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java#L686-L701
|
14,623
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java
|
BasePool.canAllocate
|
@VisibleForTesting
synchronized boolean canAllocate(int sizeInBytes) {
int hardCap = mPoolParams.maxSizeHardCap;
// even with our best effort we cannot ensure hard cap limit.
// Return immediately - no point in trimming any space
if (sizeInBytes > hardCap - mUsed.mNumBytes) {
mPoolStatsTracker.onHardCapReached();
return false;
}
// trim if we need to
int softCap = mPoolParams.maxSizeSoftCap;
if (sizeInBytes > softCap - (mUsed.mNumBytes + mFree.mNumBytes)) {
trimToSize(softCap - sizeInBytes);
}
// check again to see if we're below the hard cap
if (sizeInBytes > hardCap - (mUsed.mNumBytes + mFree.mNumBytes)) {
mPoolStatsTracker.onHardCapReached();
return false;
}
return true;
}
|
java
|
@VisibleForTesting
synchronized boolean canAllocate(int sizeInBytes) {
int hardCap = mPoolParams.maxSizeHardCap;
// even with our best effort we cannot ensure hard cap limit.
// Return immediately - no point in trimming any space
if (sizeInBytes > hardCap - mUsed.mNumBytes) {
mPoolStatsTracker.onHardCapReached();
return false;
}
// trim if we need to
int softCap = mPoolParams.maxSizeSoftCap;
if (sizeInBytes > softCap - (mUsed.mNumBytes + mFree.mNumBytes)) {
trimToSize(softCap - sizeInBytes);
}
// check again to see if we're below the hard cap
if (sizeInBytes > hardCap - (mUsed.mNumBytes + mFree.mNumBytes)) {
mPoolStatsTracker.onHardCapReached();
return false;
}
return true;
}
|
[
"@",
"VisibleForTesting",
"synchronized",
"boolean",
"canAllocate",
"(",
"int",
"sizeInBytes",
")",
"{",
"int",
"hardCap",
"=",
"mPoolParams",
".",
"maxSizeHardCap",
";",
"// even with our best effort we cannot ensure hard cap limit.",
"// Return immediately - no point in trimming any space",
"if",
"(",
"sizeInBytes",
">",
"hardCap",
"-",
"mUsed",
".",
"mNumBytes",
")",
"{",
"mPoolStatsTracker",
".",
"onHardCapReached",
"(",
")",
";",
"return",
"false",
";",
"}",
"// trim if we need to",
"int",
"softCap",
"=",
"mPoolParams",
".",
"maxSizeSoftCap",
";",
"if",
"(",
"sizeInBytes",
">",
"softCap",
"-",
"(",
"mUsed",
".",
"mNumBytes",
"+",
"mFree",
".",
"mNumBytes",
")",
")",
"{",
"trimToSize",
"(",
"softCap",
"-",
"sizeInBytes",
")",
";",
"}",
"// check again to see if we're below the hard cap",
"if",
"(",
"sizeInBytes",
">",
"hardCap",
"-",
"(",
"mUsed",
".",
"mNumBytes",
"+",
"mFree",
".",
"mNumBytes",
")",
")",
"{",
"mPoolStatsTracker",
".",
"onHardCapReached",
"(",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Can we allocate a value of size 'sizeInBytes' without exceeding the hard cap on the pool size?
If allocating this value will take the pool over the hard cap, we will first trim the pool down
to its soft cap, and then check again.
If the current used bytes + this new value will take us above the hard cap, then we return
false immediately - there is no point freeing up anything.
@param sizeInBytes the size (in bytes) of the value to allocate
@return true, if we can allocate this; false otherwise
|
[
"Can",
"we",
"allocate",
"a",
"value",
"of",
"size",
"sizeInBytes",
"without",
"exceeding",
"the",
"hard",
"cap",
"on",
"the",
"pool",
"size?",
"If",
"allocating",
"this",
"value",
"will",
"take",
"the",
"pool",
"over",
"the",
"hard",
"cap",
"we",
"will",
"first",
"trim",
"the",
"pool",
"down",
"to",
"its",
"soft",
"cap",
"and",
"then",
"check",
"again",
".",
"If",
"the",
"current",
"used",
"bytes",
"+",
"this",
"new",
"value",
"will",
"take",
"us",
"above",
"the",
"hard",
"cap",
"then",
"we",
"return",
"false",
"immediately",
"-",
"there",
"is",
"no",
"point",
"freeing",
"up",
"anything",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java#L734-L758
|
14,624
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java
|
BasePool.getStats
|
public synchronized Map<String, Integer> getStats() {
Map<String, Integer> stats = new HashMap<String, Integer>();
for (int i = 0; i < mBuckets.size(); ++i) {
final int bucketedSize = mBuckets.keyAt(i);
final Bucket<V> bucket = mBuckets.valueAt(i);
final String BUCKET_USED_KEY =
PoolStatsTracker.BUCKETS_USED_PREFIX + getSizeInBytes(bucketedSize);
stats.put(BUCKET_USED_KEY, bucket.getInUseCount());
}
stats.put(PoolStatsTracker.SOFT_CAP, mPoolParams.maxSizeSoftCap);
stats.put(PoolStatsTracker.HARD_CAP, mPoolParams.maxSizeHardCap);
stats.put(PoolStatsTracker.USED_COUNT, mUsed.mCount);
stats.put(PoolStatsTracker.USED_BYTES, mUsed.mNumBytes);
stats.put(PoolStatsTracker.FREE_COUNT, mFree.mCount);
stats.put(PoolStatsTracker.FREE_BYTES, mFree.mNumBytes);
return stats;
}
|
java
|
public synchronized Map<String, Integer> getStats() {
Map<String, Integer> stats = new HashMap<String, Integer>();
for (int i = 0; i < mBuckets.size(); ++i) {
final int bucketedSize = mBuckets.keyAt(i);
final Bucket<V> bucket = mBuckets.valueAt(i);
final String BUCKET_USED_KEY =
PoolStatsTracker.BUCKETS_USED_PREFIX + getSizeInBytes(bucketedSize);
stats.put(BUCKET_USED_KEY, bucket.getInUseCount());
}
stats.put(PoolStatsTracker.SOFT_CAP, mPoolParams.maxSizeSoftCap);
stats.put(PoolStatsTracker.HARD_CAP, mPoolParams.maxSizeHardCap);
stats.put(PoolStatsTracker.USED_COUNT, mUsed.mCount);
stats.put(PoolStatsTracker.USED_BYTES, mUsed.mNumBytes);
stats.put(PoolStatsTracker.FREE_COUNT, mFree.mCount);
stats.put(PoolStatsTracker.FREE_BYTES, mFree.mNumBytes);
return stats;
}
|
[
"public",
"synchronized",
"Map",
"<",
"String",
",",
"Integer",
">",
"getStats",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Integer",
">",
"stats",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Integer",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mBuckets",
".",
"size",
"(",
")",
";",
"++",
"i",
")",
"{",
"final",
"int",
"bucketedSize",
"=",
"mBuckets",
".",
"keyAt",
"(",
"i",
")",
";",
"final",
"Bucket",
"<",
"V",
">",
"bucket",
"=",
"mBuckets",
".",
"valueAt",
"(",
"i",
")",
";",
"final",
"String",
"BUCKET_USED_KEY",
"=",
"PoolStatsTracker",
".",
"BUCKETS_USED_PREFIX",
"+",
"getSizeInBytes",
"(",
"bucketedSize",
")",
";",
"stats",
".",
"put",
"(",
"BUCKET_USED_KEY",
",",
"bucket",
".",
"getInUseCount",
"(",
")",
")",
";",
"}",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"SOFT_CAP",
",",
"mPoolParams",
".",
"maxSizeSoftCap",
")",
";",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"HARD_CAP",
",",
"mPoolParams",
".",
"maxSizeHardCap",
")",
";",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"USED_COUNT",
",",
"mUsed",
".",
"mCount",
")",
";",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"USED_BYTES",
",",
"mUsed",
".",
"mNumBytes",
")",
";",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"FREE_COUNT",
",",
"mFree",
".",
"mCount",
")",
";",
"stats",
".",
"put",
"(",
"PoolStatsTracker",
".",
"FREE_BYTES",
",",
"mFree",
".",
"mNumBytes",
")",
";",
"return",
"stats",
";",
"}"
] |
Export memory stats regarding buckets used, memory caps, reused values.
|
[
"Export",
"memory",
"stats",
"regarding",
"buckets",
"used",
"memory",
"caps",
"reused",
"values",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BasePool.java#L780-L798
|
14,625
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java
|
DefaultImageDecoder.decode
|
@Override
public CloseableImage decode(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
if (options.customImageDecoder != null) {
return options.customImageDecoder.decode(encodedImage, length, qualityInfo, options);
}
ImageFormat imageFormat = encodedImage.getImageFormat();
if (imageFormat == null || imageFormat == ImageFormat.UNKNOWN) {
imageFormat = ImageFormatChecker.getImageFormat_WrapIOException(
encodedImage.getInputStream());
encodedImage.setImageFormat(imageFormat);
}
if (mCustomDecoders != null) {
ImageDecoder decoder = mCustomDecoders.get(imageFormat);
if (decoder != null) {
return decoder.decode(encodedImage, length, qualityInfo, options);
}
}
return mDefaultDecoder.decode(encodedImage, length, qualityInfo, options);
}
|
java
|
@Override
public CloseableImage decode(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
if (options.customImageDecoder != null) {
return options.customImageDecoder.decode(encodedImage, length, qualityInfo, options);
}
ImageFormat imageFormat = encodedImage.getImageFormat();
if (imageFormat == null || imageFormat == ImageFormat.UNKNOWN) {
imageFormat = ImageFormatChecker.getImageFormat_WrapIOException(
encodedImage.getInputStream());
encodedImage.setImageFormat(imageFormat);
}
if (mCustomDecoders != null) {
ImageDecoder decoder = mCustomDecoders.get(imageFormat);
if (decoder != null) {
return decoder.decode(encodedImage, length, qualityInfo, options);
}
}
return mDefaultDecoder.decode(encodedImage, length, qualityInfo, options);
}
|
[
"@",
"Override",
"public",
"CloseableImage",
"decode",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"final",
"int",
"length",
",",
"final",
"QualityInfo",
"qualityInfo",
",",
"final",
"ImageDecodeOptions",
"options",
")",
"{",
"if",
"(",
"options",
".",
"customImageDecoder",
"!=",
"null",
")",
"{",
"return",
"options",
".",
"customImageDecoder",
".",
"decode",
"(",
"encodedImage",
",",
"length",
",",
"qualityInfo",
",",
"options",
")",
";",
"}",
"ImageFormat",
"imageFormat",
"=",
"encodedImage",
".",
"getImageFormat",
"(",
")",
";",
"if",
"(",
"imageFormat",
"==",
"null",
"||",
"imageFormat",
"==",
"ImageFormat",
".",
"UNKNOWN",
")",
"{",
"imageFormat",
"=",
"ImageFormatChecker",
".",
"getImageFormat_WrapIOException",
"(",
"encodedImage",
".",
"getInputStream",
"(",
")",
")",
";",
"encodedImage",
".",
"setImageFormat",
"(",
"imageFormat",
")",
";",
"}",
"if",
"(",
"mCustomDecoders",
"!=",
"null",
")",
"{",
"ImageDecoder",
"decoder",
"=",
"mCustomDecoders",
".",
"get",
"(",
"imageFormat",
")",
";",
"if",
"(",
"decoder",
"!=",
"null",
")",
"{",
"return",
"decoder",
".",
"decode",
"(",
"encodedImage",
",",
"length",
",",
"qualityInfo",
",",
"options",
")",
";",
"}",
"}",
"return",
"mDefaultDecoder",
".",
"decode",
"(",
"encodedImage",
",",
"length",
",",
"qualityInfo",
",",
"options",
")",
";",
"}"
] |
Decodes image.
@param encodedImage input image (encoded bytes plus meta data)
@param length if image type supports decoding incomplete image then determines where the image
data should be cut for decoding.
@param qualityInfo quality information for the image
@param options options that cange decode behavior
|
[
"Decodes",
"image",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java#L100-L122
|
14,626
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java
|
DefaultImageDecoder.decodeGif
|
public CloseableImage decodeGif(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
if (!options.forceStaticImage && mAnimatedGifDecoder != null) {
return mAnimatedGifDecoder.decode(encodedImage, length, qualityInfo, options);
}
return decodeStaticImage(encodedImage, options);
}
|
java
|
public CloseableImage decodeGif(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
if (!options.forceStaticImage && mAnimatedGifDecoder != null) {
return mAnimatedGifDecoder.decode(encodedImage, length, qualityInfo, options);
}
return decodeStaticImage(encodedImage, options);
}
|
[
"public",
"CloseableImage",
"decodeGif",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"final",
"int",
"length",
",",
"final",
"QualityInfo",
"qualityInfo",
",",
"final",
"ImageDecodeOptions",
"options",
")",
"{",
"if",
"(",
"!",
"options",
".",
"forceStaticImage",
"&&",
"mAnimatedGifDecoder",
"!=",
"null",
")",
"{",
"return",
"mAnimatedGifDecoder",
".",
"decode",
"(",
"encodedImage",
",",
"length",
",",
"qualityInfo",
",",
"options",
")",
";",
"}",
"return",
"decodeStaticImage",
"(",
"encodedImage",
",",
"options",
")",
";",
"}"
] |
Decodes gif into CloseableImage.
@param encodedImage input image (encoded bytes plus meta data)
@return a CloseableImage
|
[
"Decodes",
"gif",
"into",
"CloseableImage",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java#L130-L139
|
14,627
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java
|
DefaultImageDecoder.decodeJpeg
|
public CloseableStaticBitmap decodeJpeg(
final EncodedImage encodedImage,
int length,
QualityInfo qualityInfo,
ImageDecodeOptions options) {
CloseableReference<Bitmap> bitmapReference =
mPlatformDecoder.decodeJPEGFromEncodedImageWithColorSpace(
encodedImage, options.bitmapConfig, null, length, options.colorSpace);
try {
maybeApplyTransformation(options.bitmapTransformation, bitmapReference);
return new CloseableStaticBitmap(
bitmapReference,
qualityInfo,
encodedImage.getRotationAngle(),
encodedImage.getExifOrientation());
} finally {
bitmapReference.close();
}
}
|
java
|
public CloseableStaticBitmap decodeJpeg(
final EncodedImage encodedImage,
int length,
QualityInfo qualityInfo,
ImageDecodeOptions options) {
CloseableReference<Bitmap> bitmapReference =
mPlatformDecoder.decodeJPEGFromEncodedImageWithColorSpace(
encodedImage, options.bitmapConfig, null, length, options.colorSpace);
try {
maybeApplyTransformation(options.bitmapTransformation, bitmapReference);
return new CloseableStaticBitmap(
bitmapReference,
qualityInfo,
encodedImage.getRotationAngle(),
encodedImage.getExifOrientation());
} finally {
bitmapReference.close();
}
}
|
[
"public",
"CloseableStaticBitmap",
"decodeJpeg",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"int",
"length",
",",
"QualityInfo",
"qualityInfo",
",",
"ImageDecodeOptions",
"options",
")",
"{",
"CloseableReference",
"<",
"Bitmap",
">",
"bitmapReference",
"=",
"mPlatformDecoder",
".",
"decodeJPEGFromEncodedImageWithColorSpace",
"(",
"encodedImage",
",",
"options",
".",
"bitmapConfig",
",",
"null",
",",
"length",
",",
"options",
".",
"colorSpace",
")",
";",
"try",
"{",
"maybeApplyTransformation",
"(",
"options",
".",
"bitmapTransformation",
",",
"bitmapReference",
")",
";",
"return",
"new",
"CloseableStaticBitmap",
"(",
"bitmapReference",
",",
"qualityInfo",
",",
"encodedImage",
".",
"getRotationAngle",
"(",
")",
",",
"encodedImage",
".",
"getExifOrientation",
"(",
")",
")",
";",
"}",
"finally",
"{",
"bitmapReference",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Decodes a partial jpeg.
@param encodedImage input image (encoded bytes plus meta data)
@param length amount of currently available data in bytes
@param qualityInfo quality info for the image
@return a CloseableStaticBitmap
|
[
"Decodes",
"a",
"partial",
"jpeg",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java#L171-L189
|
14,628
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java
|
DefaultImageDecoder.decodeAnimatedWebp
|
public CloseableImage decodeAnimatedWebp(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
return mAnimatedWebPDecoder.decode(encodedImage, length, qualityInfo, options);
}
|
java
|
public CloseableImage decodeAnimatedWebp(
final EncodedImage encodedImage,
final int length,
final QualityInfo qualityInfo,
final ImageDecodeOptions options) {
return mAnimatedWebPDecoder.decode(encodedImage, length, qualityInfo, options);
}
|
[
"public",
"CloseableImage",
"decodeAnimatedWebp",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"final",
"int",
"length",
",",
"final",
"QualityInfo",
"qualityInfo",
",",
"final",
"ImageDecodeOptions",
"options",
")",
"{",
"return",
"mAnimatedWebPDecoder",
".",
"decode",
"(",
"encodedImage",
",",
"length",
",",
"qualityInfo",
",",
"options",
")",
";",
"}"
] |
Decode a webp animated image into a CloseableImage.
<p> The image is decoded into a 'pinned' purgeable bitmap.
@param encodedImage input image (encoded bytes plus meta data)
@param options
@return a {@link CloseableImage}
|
[
"Decode",
"a",
"webp",
"animated",
"image",
"into",
"a",
"CloseableImage",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java#L200-L206
|
14,629
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactoryProvider.java
|
PlatformBitmapFactoryProvider.buildPlatformBitmapFactory
|
public static PlatformBitmapFactory buildPlatformBitmapFactory(
PoolFactory poolFactory, PlatformDecoder platformDecoder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new ArtBitmapFactory(poolFactory.getBitmapPool());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return new HoneycombBitmapFactory(
new EmptyJpegGenerator(poolFactory.getPooledByteBufferFactory()), platformDecoder);
} else {
return new GingerbreadBitmapFactory();
}
}
|
java
|
public static PlatformBitmapFactory buildPlatformBitmapFactory(
PoolFactory poolFactory, PlatformDecoder platformDecoder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new ArtBitmapFactory(poolFactory.getBitmapPool());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return new HoneycombBitmapFactory(
new EmptyJpegGenerator(poolFactory.getPooledByteBufferFactory()), platformDecoder);
} else {
return new GingerbreadBitmapFactory();
}
}
|
[
"public",
"static",
"PlatformBitmapFactory",
"buildPlatformBitmapFactory",
"(",
"PoolFactory",
"poolFactory",
",",
"PlatformDecoder",
"platformDecoder",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"{",
"return",
"new",
"ArtBitmapFactory",
"(",
"poolFactory",
".",
"getBitmapPool",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"HONEYCOMB",
")",
"{",
"return",
"new",
"HoneycombBitmapFactory",
"(",
"new",
"EmptyJpegGenerator",
"(",
"poolFactory",
".",
"getPooledByteBufferFactory",
"(",
")",
")",
",",
"platformDecoder",
")",
";",
"}",
"else",
"{",
"return",
"new",
"GingerbreadBitmapFactory",
"(",
")",
";",
"}",
"}"
] |
Provide the implementation of the PlatformBitmapFactory for the current platform using the
provided PoolFactory
@param poolFactory The PoolFactory
@param platformDecoder The PlatformDecoder
@return The PlatformBitmapFactory implementation
|
[
"Provide",
"the",
"implementation",
"of",
"the",
"PlatformBitmapFactory",
"for",
"the",
"current",
"platform",
"using",
"the",
"provided",
"PoolFactory"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactoryProvider.java#L26-L36
|
14,630
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.getResource
|
@Override
public @Nullable BinaryResource getResource(final CacheKey key) {
String resourceId = null;
SettableCacheEvent cacheEvent = SettableCacheEvent.obtain()
.setCacheKey(key);
try {
synchronized (mLock) {
BinaryResource resource = null;
List<String> resourceIds = CacheKeyUtil.getResourceIds(key);
for (int i = 0; i < resourceIds.size(); i++) {
resourceId = resourceIds.get(i);
cacheEvent.setResourceId(resourceId);
resource = mStorage.getResource(resourceId, key);
if (resource != null) {
break;
}
}
if (resource == null) {
mCacheEventListener.onMiss(cacheEvent);
mResourceIndex.remove(resourceId);
} else {
mCacheEventListener.onHit(cacheEvent);
mResourceIndex.add(resourceId);
}
return resource;
}
} catch (IOException ioe) {
mCacheErrorLogger.logError(
CacheErrorLogger.CacheErrorCategory.GENERIC_IO,
TAG,
"getResource",
ioe);
cacheEvent.setException(ioe);
mCacheEventListener.onReadException(cacheEvent);
return null;
} finally {
cacheEvent.recycle();
}
}
|
java
|
@Override
public @Nullable BinaryResource getResource(final CacheKey key) {
String resourceId = null;
SettableCacheEvent cacheEvent = SettableCacheEvent.obtain()
.setCacheKey(key);
try {
synchronized (mLock) {
BinaryResource resource = null;
List<String> resourceIds = CacheKeyUtil.getResourceIds(key);
for (int i = 0; i < resourceIds.size(); i++) {
resourceId = resourceIds.get(i);
cacheEvent.setResourceId(resourceId);
resource = mStorage.getResource(resourceId, key);
if (resource != null) {
break;
}
}
if (resource == null) {
mCacheEventListener.onMiss(cacheEvent);
mResourceIndex.remove(resourceId);
} else {
mCacheEventListener.onHit(cacheEvent);
mResourceIndex.add(resourceId);
}
return resource;
}
} catch (IOException ioe) {
mCacheErrorLogger.logError(
CacheErrorLogger.CacheErrorCategory.GENERIC_IO,
TAG,
"getResource",
ioe);
cacheEvent.setException(ioe);
mCacheEventListener.onReadException(cacheEvent);
return null;
} finally {
cacheEvent.recycle();
}
}
|
[
"@",
"Override",
"public",
"@",
"Nullable",
"BinaryResource",
"getResource",
"(",
"final",
"CacheKey",
"key",
")",
"{",
"String",
"resourceId",
"=",
"null",
";",
"SettableCacheEvent",
"cacheEvent",
"=",
"SettableCacheEvent",
".",
"obtain",
"(",
")",
".",
"setCacheKey",
"(",
"key",
")",
";",
"try",
"{",
"synchronized",
"(",
"mLock",
")",
"{",
"BinaryResource",
"resource",
"=",
"null",
";",
"List",
"<",
"String",
">",
"resourceIds",
"=",
"CacheKeyUtil",
".",
"getResourceIds",
"(",
"key",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"resourceIds",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"resourceId",
"=",
"resourceIds",
".",
"get",
"(",
"i",
")",
";",
"cacheEvent",
".",
"setResourceId",
"(",
"resourceId",
")",
";",
"resource",
"=",
"mStorage",
".",
"getResource",
"(",
"resourceId",
",",
"key",
")",
";",
"if",
"(",
"resource",
"!=",
"null",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"resource",
"==",
"null",
")",
"{",
"mCacheEventListener",
".",
"onMiss",
"(",
"cacheEvent",
")",
";",
"mResourceIndex",
".",
"remove",
"(",
"resourceId",
")",
";",
"}",
"else",
"{",
"mCacheEventListener",
".",
"onHit",
"(",
"cacheEvent",
")",
";",
"mResourceIndex",
".",
"add",
"(",
"resourceId",
")",
";",
"}",
"return",
"resource",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"mCacheErrorLogger",
".",
"logError",
"(",
"CacheErrorLogger",
".",
"CacheErrorCategory",
".",
"GENERIC_IO",
",",
"TAG",
",",
"\"getResource\"",
",",
"ioe",
")",
";",
"cacheEvent",
".",
"setException",
"(",
"ioe",
")",
";",
"mCacheEventListener",
".",
"onReadException",
"(",
"cacheEvent",
")",
";",
"return",
"null",
";",
"}",
"finally",
"{",
"cacheEvent",
".",
"recycle",
"(",
")",
";",
"}",
"}"
] |
Retrieves the file corresponding to the mKey, if it is in the cache. Also touches the item,
thus changing its LRU timestamp. If the file is not present in the file cache, returns null.
<p>This should NOT be called on the UI thread.
@param key the mKey to check
@return The resource if present in cache, otherwise null
|
[
"Retrieves",
"the",
"file",
"corresponding",
"to",
"the",
"mKey",
"if",
"it",
"is",
"in",
"the",
"cache",
".",
"Also",
"touches",
"the",
"item",
"thus",
"changing",
"its",
"LRU",
"timestamp",
".",
"If",
"the",
"file",
"is",
"not",
"present",
"in",
"the",
"file",
"cache",
"returns",
"null",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L245-L283
|
14,631
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.startInsert
|
private DiskStorage.Inserter startInsert(
final String resourceId,
final CacheKey key)
throws IOException {
maybeEvictFilesInCacheDir();
return mStorage.insert(resourceId, key);
}
|
java
|
private DiskStorage.Inserter startInsert(
final String resourceId,
final CacheKey key)
throws IOException {
maybeEvictFilesInCacheDir();
return mStorage.insert(resourceId, key);
}
|
[
"private",
"DiskStorage",
".",
"Inserter",
"startInsert",
"(",
"final",
"String",
"resourceId",
",",
"final",
"CacheKey",
"key",
")",
"throws",
"IOException",
"{",
"maybeEvictFilesInCacheDir",
"(",
")",
";",
"return",
"mStorage",
".",
"insert",
"(",
"resourceId",
",",
"key",
")",
";",
"}"
] |
Creates a temp file for writing outside the session lock
|
[
"Creates",
"a",
"temp",
"file",
"for",
"writing",
"outside",
"the",
"session",
"lock"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L324-L330
|
14,632
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.endInsert
|
private BinaryResource endInsert(
final DiskStorage.Inserter inserter,
final CacheKey key,
String resourceId) throws IOException {
synchronized (mLock) {
BinaryResource resource = inserter.commit(key);
mResourceIndex.add(resourceId);
mCacheStats.increment(resource.size(), 1);
return resource;
}
}
|
java
|
private BinaryResource endInsert(
final DiskStorage.Inserter inserter,
final CacheKey key,
String resourceId) throws IOException {
synchronized (mLock) {
BinaryResource resource = inserter.commit(key);
mResourceIndex.add(resourceId);
mCacheStats.increment(resource.size(), 1);
return resource;
}
}
|
[
"private",
"BinaryResource",
"endInsert",
"(",
"final",
"DiskStorage",
".",
"Inserter",
"inserter",
",",
"final",
"CacheKey",
"key",
",",
"String",
"resourceId",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"mLock",
")",
"{",
"BinaryResource",
"resource",
"=",
"inserter",
".",
"commit",
"(",
"key",
")",
";",
"mResourceIndex",
".",
"add",
"(",
"resourceId",
")",
";",
"mCacheStats",
".",
"increment",
"(",
"resource",
".",
"size",
"(",
")",
",",
"1",
")",
";",
"return",
"resource",
";",
"}",
"}"
] |
Commits the provided temp file to the cache, renaming it to match
the cache's hashing convention.
|
[
"Commits",
"the",
"provided",
"temp",
"file",
"to",
"the",
"cache",
"renaming",
"it",
"to",
"match",
"the",
"cache",
"s",
"hashing",
"convention",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L336-L346
|
14,633
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.clearOldEntries
|
@Override
public long clearOldEntries(long cacheExpirationMs) {
long oldestRemainingEntryAgeMs = 0L;
synchronized (mLock) {
try {
long now = mClock.now();
Collection<DiskStorage.Entry> allEntries = mStorage.getEntries();
final long cacheSizeBeforeClearance = mCacheStats.getSize();
int itemsRemovedCount = 0;
long itemsRemovedSize = 0L;
for (DiskStorage.Entry entry : allEntries) {
// entry age of zero is disallowed.
long entryAgeMs = Math.max(1, Math.abs(now - entry.getTimestamp()));
if (entryAgeMs >= cacheExpirationMs) {
long entryRemovedSize = mStorage.remove(entry);
mResourceIndex.remove(entry.getId());
if (entryRemovedSize > 0) {
itemsRemovedCount++;
itemsRemovedSize += entryRemovedSize;
SettableCacheEvent cacheEvent = SettableCacheEvent.obtain()
.setResourceId(entry.getId())
.setEvictionReason(CacheEventListener.EvictionReason.CONTENT_STALE)
.setItemSize(entryRemovedSize)
.setCacheSize(cacheSizeBeforeClearance - itemsRemovedSize);
mCacheEventListener.onEviction(cacheEvent);
cacheEvent.recycle();
}
} else {
oldestRemainingEntryAgeMs = Math.max(oldestRemainingEntryAgeMs, entryAgeMs);
}
}
mStorage.purgeUnexpectedResources();
if (itemsRemovedCount > 0) {
maybeUpdateFileCacheSize();
mCacheStats.increment(-itemsRemovedSize, -itemsRemovedCount);
}
} catch (IOException ioe) {
mCacheErrorLogger.logError(
CacheErrorLogger.CacheErrorCategory.EVICTION,
TAG,
"clearOldEntries: " + ioe.getMessage(),
ioe);
}
}
return oldestRemainingEntryAgeMs;
}
|
java
|
@Override
public long clearOldEntries(long cacheExpirationMs) {
long oldestRemainingEntryAgeMs = 0L;
synchronized (mLock) {
try {
long now = mClock.now();
Collection<DiskStorage.Entry> allEntries = mStorage.getEntries();
final long cacheSizeBeforeClearance = mCacheStats.getSize();
int itemsRemovedCount = 0;
long itemsRemovedSize = 0L;
for (DiskStorage.Entry entry : allEntries) {
// entry age of zero is disallowed.
long entryAgeMs = Math.max(1, Math.abs(now - entry.getTimestamp()));
if (entryAgeMs >= cacheExpirationMs) {
long entryRemovedSize = mStorage.remove(entry);
mResourceIndex.remove(entry.getId());
if (entryRemovedSize > 0) {
itemsRemovedCount++;
itemsRemovedSize += entryRemovedSize;
SettableCacheEvent cacheEvent = SettableCacheEvent.obtain()
.setResourceId(entry.getId())
.setEvictionReason(CacheEventListener.EvictionReason.CONTENT_STALE)
.setItemSize(entryRemovedSize)
.setCacheSize(cacheSizeBeforeClearance - itemsRemovedSize);
mCacheEventListener.onEviction(cacheEvent);
cacheEvent.recycle();
}
} else {
oldestRemainingEntryAgeMs = Math.max(oldestRemainingEntryAgeMs, entryAgeMs);
}
}
mStorage.purgeUnexpectedResources();
if (itemsRemovedCount > 0) {
maybeUpdateFileCacheSize();
mCacheStats.increment(-itemsRemovedSize, -itemsRemovedCount);
}
} catch (IOException ioe) {
mCacheErrorLogger.logError(
CacheErrorLogger.CacheErrorCategory.EVICTION,
TAG,
"clearOldEntries: " + ioe.getMessage(),
ioe);
}
}
return oldestRemainingEntryAgeMs;
}
|
[
"@",
"Override",
"public",
"long",
"clearOldEntries",
"(",
"long",
"cacheExpirationMs",
")",
"{",
"long",
"oldestRemainingEntryAgeMs",
"=",
"0L",
";",
"synchronized",
"(",
"mLock",
")",
"{",
"try",
"{",
"long",
"now",
"=",
"mClock",
".",
"now",
"(",
")",
";",
"Collection",
"<",
"DiskStorage",
".",
"Entry",
">",
"allEntries",
"=",
"mStorage",
".",
"getEntries",
"(",
")",
";",
"final",
"long",
"cacheSizeBeforeClearance",
"=",
"mCacheStats",
".",
"getSize",
"(",
")",
";",
"int",
"itemsRemovedCount",
"=",
"0",
";",
"long",
"itemsRemovedSize",
"=",
"0L",
";",
"for",
"(",
"DiskStorage",
".",
"Entry",
"entry",
":",
"allEntries",
")",
"{",
"// entry age of zero is disallowed.",
"long",
"entryAgeMs",
"=",
"Math",
".",
"max",
"(",
"1",
",",
"Math",
".",
"abs",
"(",
"now",
"-",
"entry",
".",
"getTimestamp",
"(",
")",
")",
")",
";",
"if",
"(",
"entryAgeMs",
">=",
"cacheExpirationMs",
")",
"{",
"long",
"entryRemovedSize",
"=",
"mStorage",
".",
"remove",
"(",
"entry",
")",
";",
"mResourceIndex",
".",
"remove",
"(",
"entry",
".",
"getId",
"(",
")",
")",
";",
"if",
"(",
"entryRemovedSize",
">",
"0",
")",
"{",
"itemsRemovedCount",
"++",
";",
"itemsRemovedSize",
"+=",
"entryRemovedSize",
";",
"SettableCacheEvent",
"cacheEvent",
"=",
"SettableCacheEvent",
".",
"obtain",
"(",
")",
".",
"setResourceId",
"(",
"entry",
".",
"getId",
"(",
")",
")",
".",
"setEvictionReason",
"(",
"CacheEventListener",
".",
"EvictionReason",
".",
"CONTENT_STALE",
")",
".",
"setItemSize",
"(",
"entryRemovedSize",
")",
".",
"setCacheSize",
"(",
"cacheSizeBeforeClearance",
"-",
"itemsRemovedSize",
")",
";",
"mCacheEventListener",
".",
"onEviction",
"(",
"cacheEvent",
")",
";",
"cacheEvent",
".",
"recycle",
"(",
")",
";",
"}",
"}",
"else",
"{",
"oldestRemainingEntryAgeMs",
"=",
"Math",
".",
"max",
"(",
"oldestRemainingEntryAgeMs",
",",
"entryAgeMs",
")",
";",
"}",
"}",
"mStorage",
".",
"purgeUnexpectedResources",
"(",
")",
";",
"if",
"(",
"itemsRemovedCount",
">",
"0",
")",
"{",
"maybeUpdateFileCacheSize",
"(",
")",
";",
"mCacheStats",
".",
"increment",
"(",
"-",
"itemsRemovedSize",
",",
"-",
"itemsRemovedCount",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"mCacheErrorLogger",
".",
"logError",
"(",
"CacheErrorLogger",
".",
"CacheErrorCategory",
".",
"EVICTION",
",",
"TAG",
",",
"\"clearOldEntries: \"",
"+",
"ioe",
".",
"getMessage",
"(",
")",
",",
"ioe",
")",
";",
"}",
"}",
"return",
"oldestRemainingEntryAgeMs",
";",
"}"
] |
Deletes old cache files.
@param cacheExpirationMs files older than this will be deleted.
@return the age in ms of the oldest file remaining in the cache.
|
[
"Deletes",
"old",
"cache",
"files",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L413-L458
|
14,634
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.maybeEvictFilesInCacheDir
|
private void maybeEvictFilesInCacheDir() throws IOException {
synchronized (mLock) {
boolean calculatedRightNow = maybeUpdateFileCacheSize();
// Update the size limit (mCacheSizeLimit)
updateFileCacheSizeLimit();
long cacheSize = mCacheStats.getSize();
// If we are going to evict force a recalculation of the size
// (except if it was already calculated!)
if (cacheSize > mCacheSizeLimit && !calculatedRightNow) {
mCacheStats.reset();
maybeUpdateFileCacheSize();
}
// If size has exceeded the size limit, evict some files
if (cacheSize > mCacheSizeLimit) {
evictAboveSize(
mCacheSizeLimit * 9 / 10,
CacheEventListener.EvictionReason.CACHE_FULL); // 90%
}
}
}
|
java
|
private void maybeEvictFilesInCacheDir() throws IOException {
synchronized (mLock) {
boolean calculatedRightNow = maybeUpdateFileCacheSize();
// Update the size limit (mCacheSizeLimit)
updateFileCacheSizeLimit();
long cacheSize = mCacheStats.getSize();
// If we are going to evict force a recalculation of the size
// (except if it was already calculated!)
if (cacheSize > mCacheSizeLimit && !calculatedRightNow) {
mCacheStats.reset();
maybeUpdateFileCacheSize();
}
// If size has exceeded the size limit, evict some files
if (cacheSize > mCacheSizeLimit) {
evictAboveSize(
mCacheSizeLimit * 9 / 10,
CacheEventListener.EvictionReason.CACHE_FULL); // 90%
}
}
}
|
[
"private",
"void",
"maybeEvictFilesInCacheDir",
"(",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"mLock",
")",
"{",
"boolean",
"calculatedRightNow",
"=",
"maybeUpdateFileCacheSize",
"(",
")",
";",
"// Update the size limit (mCacheSizeLimit)",
"updateFileCacheSizeLimit",
"(",
")",
";",
"long",
"cacheSize",
"=",
"mCacheStats",
".",
"getSize",
"(",
")",
";",
"// If we are going to evict force a recalculation of the size",
"// (except if it was already calculated!)",
"if",
"(",
"cacheSize",
">",
"mCacheSizeLimit",
"&&",
"!",
"calculatedRightNow",
")",
"{",
"mCacheStats",
".",
"reset",
"(",
")",
";",
"maybeUpdateFileCacheSize",
"(",
")",
";",
"}",
"// If size has exceeded the size limit, evict some files",
"if",
"(",
"cacheSize",
">",
"mCacheSizeLimit",
")",
"{",
"evictAboveSize",
"(",
"mCacheSizeLimit",
"*",
"9",
"/",
"10",
",",
"CacheEventListener",
".",
"EvictionReason",
".",
"CACHE_FULL",
")",
";",
"// 90%",
"}",
"}",
"}"
] |
Test if the cache size has exceeded its limits, and if so, evict some files.
It also calls maybeUpdateFileCacheSize
This method uses mLock for synchronization purposes.
|
[
"Test",
"if",
"the",
"cache",
"size",
"has",
"exceeded",
"its",
"limits",
"and",
"if",
"so",
"evict",
"some",
"files",
".",
"It",
"also",
"calls",
"maybeUpdateFileCacheSize"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L466-L488
|
14,635
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java
|
DiskStorageCache.updateFileCacheSizeLimit
|
@GuardedBy("mLock")
private void updateFileCacheSizeLimit() {
// Test if mCacheSizeLimit can be set to the high limit
boolean isAvailableSpaceLowerThanHighLimit;
StatFsHelper.StorageType storageType =
mStorage.isExternal()
? StatFsHelper.StorageType.EXTERNAL
: StatFsHelper.StorageType.INTERNAL;
isAvailableSpaceLowerThanHighLimit =
mStatFsHelper.testLowDiskSpace(
storageType,
mDefaultCacheSizeLimit - mCacheStats.getSize());
if (isAvailableSpaceLowerThanHighLimit) {
mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit;
} else {
mCacheSizeLimit = mDefaultCacheSizeLimit;
}
}
|
java
|
@GuardedBy("mLock")
private void updateFileCacheSizeLimit() {
// Test if mCacheSizeLimit can be set to the high limit
boolean isAvailableSpaceLowerThanHighLimit;
StatFsHelper.StorageType storageType =
mStorage.isExternal()
? StatFsHelper.StorageType.EXTERNAL
: StatFsHelper.StorageType.INTERNAL;
isAvailableSpaceLowerThanHighLimit =
mStatFsHelper.testLowDiskSpace(
storageType,
mDefaultCacheSizeLimit - mCacheStats.getSize());
if (isAvailableSpaceLowerThanHighLimit) {
mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit;
} else {
mCacheSizeLimit = mDefaultCacheSizeLimit;
}
}
|
[
"@",
"GuardedBy",
"(",
"\"mLock\"",
")",
"private",
"void",
"updateFileCacheSizeLimit",
"(",
")",
"{",
"// Test if mCacheSizeLimit can be set to the high limit",
"boolean",
"isAvailableSpaceLowerThanHighLimit",
";",
"StatFsHelper",
".",
"StorageType",
"storageType",
"=",
"mStorage",
".",
"isExternal",
"(",
")",
"?",
"StatFsHelper",
".",
"StorageType",
".",
"EXTERNAL",
":",
"StatFsHelper",
".",
"StorageType",
".",
"INTERNAL",
";",
"isAvailableSpaceLowerThanHighLimit",
"=",
"mStatFsHelper",
".",
"testLowDiskSpace",
"(",
"storageType",
",",
"mDefaultCacheSizeLimit",
"-",
"mCacheStats",
".",
"getSize",
"(",
")",
")",
";",
"if",
"(",
"isAvailableSpaceLowerThanHighLimit",
")",
"{",
"mCacheSizeLimit",
"=",
"mLowDiskSpaceCacheSizeLimit",
";",
"}",
"else",
"{",
"mCacheSizeLimit",
"=",
"mDefaultCacheSizeLimit",
";",
"}",
"}"
] |
Helper method that sets the cache size limit to be either a high, or a low limit.
If there is not enough free space to satisfy the high limit, it is set to the low limit.
|
[
"Helper",
"method",
"that",
"sets",
"the",
"cache",
"size",
"limit",
"to",
"be",
"either",
"a",
"high",
"or",
"a",
"low",
"limit",
".",
"If",
"there",
"is",
"not",
"enough",
"free",
"space",
"to",
"satisfy",
"the",
"high",
"limit",
"it",
"is",
"set",
"to",
"the",
"low",
"limit",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/DiskStorageCache.java#L561-L578
|
14,636
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/RoundingParams.java
|
RoundingParams.fromCornersRadii
|
public static RoundingParams fromCornersRadii(
float topLeft,
float topRight,
float bottomRight,
float bottomLeft) {
return (new RoundingParams())
.setCornersRadii(topLeft, topRight, bottomRight, bottomLeft);
}
|
java
|
public static RoundingParams fromCornersRadii(
float topLeft,
float topRight,
float bottomRight,
float bottomLeft) {
return (new RoundingParams())
.setCornersRadii(topLeft, topRight, bottomRight, bottomLeft);
}
|
[
"public",
"static",
"RoundingParams",
"fromCornersRadii",
"(",
"float",
"topLeft",
",",
"float",
"topRight",
",",
"float",
"bottomRight",
",",
"float",
"bottomLeft",
")",
"{",
"return",
"(",
"new",
"RoundingParams",
"(",
")",
")",
".",
"setCornersRadii",
"(",
"topLeft",
",",
"topRight",
",",
"bottomRight",
",",
"bottomLeft",
")",
";",
"}"
] |
Factory method that creates new RoundingParams with the specified corners radii.
|
[
"Factory",
"method",
"that",
"creates",
"new",
"RoundingParams",
"with",
"the",
"specified",
"corners",
"radii",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/RoundingParams.java#L179-L186
|
14,637
|
facebook/fresco
|
samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java
|
SizeUtil.calcDesiredSize
|
public static int calcDesiredSize(Context context, int parentWidth, int parentHeight) {
int orientation = context.getResources().getConfiguration().orientation;
int desiredSize = (orientation == Configuration.ORIENTATION_LANDSCAPE) ?
parentWidth : parentHeight;
return Math.min(desiredSize, parentWidth);
}
|
java
|
public static int calcDesiredSize(Context context, int parentWidth, int parentHeight) {
int orientation = context.getResources().getConfiguration().orientation;
int desiredSize = (orientation == Configuration.ORIENTATION_LANDSCAPE) ?
parentWidth : parentHeight;
return Math.min(desiredSize, parentWidth);
}
|
[
"public",
"static",
"int",
"calcDesiredSize",
"(",
"Context",
"context",
",",
"int",
"parentWidth",
",",
"int",
"parentHeight",
")",
"{",
"int",
"orientation",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getConfiguration",
"(",
")",
".",
"orientation",
";",
"int",
"desiredSize",
"=",
"(",
"orientation",
"==",
"Configuration",
".",
"ORIENTATION_LANDSCAPE",
")",
"?",
"parentWidth",
":",
"parentHeight",
";",
"return",
"Math",
".",
"min",
"(",
"desiredSize",
",",
"parentWidth",
")",
";",
"}"
] |
Calculate desired size for the given View based on device orientation
@param context The Context
@param parentWidth The width of the Parent View
@param parentHeight The height of the Parent View
@return The desired size for the View
|
[
"Calculate",
"desired",
"size",
"for",
"the",
"given",
"View",
"based",
"on",
"device",
"orientation"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java#L57-L62
|
14,638
|
facebook/fresco
|
samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java
|
SizeUtil.setConfiguredSize
|
public static void setConfiguredSize(
final View parentView,
final View draweeView,
final Config config) {
if (parentView != null) {
if (config.overrideSize) {
SizeUtil.updateViewLayoutParams(
draweeView,
config.overridenWidth,
config.overridenHeight);
} else {
int size = SizeUtil.calcDesiredSize(
parentView.getContext(),
parentView.getWidth(),
parentView.getHeight());
SizeUtil.updateViewLayoutParams(draweeView, size, (int) (size / Const.RATIO));
}
}
}
|
java
|
public static void setConfiguredSize(
final View parentView,
final View draweeView,
final Config config) {
if (parentView != null) {
if (config.overrideSize) {
SizeUtil.updateViewLayoutParams(
draweeView,
config.overridenWidth,
config.overridenHeight);
} else {
int size = SizeUtil.calcDesiredSize(
parentView.getContext(),
parentView.getWidth(),
parentView.getHeight());
SizeUtil.updateViewLayoutParams(draweeView, size, (int) (size / Const.RATIO));
}
}
}
|
[
"public",
"static",
"void",
"setConfiguredSize",
"(",
"final",
"View",
"parentView",
",",
"final",
"View",
"draweeView",
",",
"final",
"Config",
"config",
")",
"{",
"if",
"(",
"parentView",
"!=",
"null",
")",
"{",
"if",
"(",
"config",
".",
"overrideSize",
")",
"{",
"SizeUtil",
".",
"updateViewLayoutParams",
"(",
"draweeView",
",",
"config",
".",
"overridenWidth",
",",
"config",
".",
"overridenHeight",
")",
";",
"}",
"else",
"{",
"int",
"size",
"=",
"SizeUtil",
".",
"calcDesiredSize",
"(",
"parentView",
".",
"getContext",
"(",
")",
",",
"parentView",
".",
"getWidth",
"(",
")",
",",
"parentView",
".",
"getHeight",
"(",
")",
")",
";",
"SizeUtil",
".",
"updateViewLayoutParams",
"(",
"draweeView",
",",
"size",
",",
"(",
"int",
")",
"(",
"size",
"/",
"Const",
".",
"RATIO",
")",
")",
";",
"}",
"}",
"}"
] |
Utility method which set the size based on the parent and configurations
@param parentView The parent View
@param draweeView The View to resize
@param config The Config object
|
[
"Utility",
"method",
"which",
"set",
"the",
"size",
"based",
"on",
"the",
"parent",
"and",
"configurations"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java#L70-L88
|
14,639
|
facebook/fresco
|
samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java
|
SizeUtil.initSizeData
|
public static void initSizeData(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
DISPLAY_WIDTH = metrics.widthPixels;
DISPLAY_HEIGHT = metrics.heightPixels;
}
|
java
|
public static void initSizeData(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
DISPLAY_WIDTH = metrics.widthPixels;
DISPLAY_HEIGHT = metrics.heightPixels;
}
|
[
"public",
"static",
"void",
"initSizeData",
"(",
"Activity",
"activity",
")",
"{",
"DisplayMetrics",
"metrics",
"=",
"new",
"DisplayMetrics",
"(",
")",
";",
"activity",
".",
"getWindowManager",
"(",
")",
".",
"getDefaultDisplay",
"(",
")",
".",
"getMetrics",
"(",
"metrics",
")",
";",
"DISPLAY_WIDTH",
"=",
"metrics",
".",
"widthPixels",
";",
"DISPLAY_HEIGHT",
"=",
"metrics",
".",
"heightPixels",
";",
"}"
] |
Invoke one into the Activity to get info about the Display size
@param activity The Activity
|
[
"Invoke",
"one",
"into",
"the",
"Activity",
"to",
"get",
"info",
"about",
"the",
"Display",
"size"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/SizeUtil.java#L94-L99
|
14,640
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/drawable/MatrixDrawable.java
|
MatrixDrawable.configureBounds
|
private void configureBounds() {
Drawable underlyingDrawable = getCurrent();
Rect bounds = getBounds();
int underlyingWidth = mUnderlyingWidth = underlyingDrawable.getIntrinsicWidth();
int underlyingHeight = mUnderlyingHeight = underlyingDrawable.getIntrinsicHeight();
// In case underlying drawable doesn't have intrinsic dimensions, we cannot set its bounds to
// -1 so we use our bounds and discard specified matrix. In normal case we use drawable's
// intrinsic dimensions for its bounds and apply specified matrix to it.
if (underlyingWidth <= 0 || underlyingHeight <= 0) {
underlyingDrawable.setBounds(bounds);
mDrawMatrix = null;
} else {
underlyingDrawable.setBounds(0, 0, underlyingWidth, underlyingHeight);
mDrawMatrix = mMatrix;
}
}
|
java
|
private void configureBounds() {
Drawable underlyingDrawable = getCurrent();
Rect bounds = getBounds();
int underlyingWidth = mUnderlyingWidth = underlyingDrawable.getIntrinsicWidth();
int underlyingHeight = mUnderlyingHeight = underlyingDrawable.getIntrinsicHeight();
// In case underlying drawable doesn't have intrinsic dimensions, we cannot set its bounds to
// -1 so we use our bounds and discard specified matrix. In normal case we use drawable's
// intrinsic dimensions for its bounds and apply specified matrix to it.
if (underlyingWidth <= 0 || underlyingHeight <= 0) {
underlyingDrawable.setBounds(bounds);
mDrawMatrix = null;
} else {
underlyingDrawable.setBounds(0, 0, underlyingWidth, underlyingHeight);
mDrawMatrix = mMatrix;
}
}
|
[
"private",
"void",
"configureBounds",
"(",
")",
"{",
"Drawable",
"underlyingDrawable",
"=",
"getCurrent",
"(",
")",
";",
"Rect",
"bounds",
"=",
"getBounds",
"(",
")",
";",
"int",
"underlyingWidth",
"=",
"mUnderlyingWidth",
"=",
"underlyingDrawable",
".",
"getIntrinsicWidth",
"(",
")",
";",
"int",
"underlyingHeight",
"=",
"mUnderlyingHeight",
"=",
"underlyingDrawable",
".",
"getIntrinsicHeight",
"(",
")",
";",
"// In case underlying drawable doesn't have intrinsic dimensions, we cannot set its bounds to",
"// -1 so we use our bounds and discard specified matrix. In normal case we use drawable's",
"// intrinsic dimensions for its bounds and apply specified matrix to it.",
"if",
"(",
"underlyingWidth",
"<=",
"0",
"||",
"underlyingHeight",
"<=",
"0",
")",
"{",
"underlyingDrawable",
".",
"setBounds",
"(",
"bounds",
")",
";",
"mDrawMatrix",
"=",
"null",
";",
"}",
"else",
"{",
"underlyingDrawable",
".",
"setBounds",
"(",
"0",
",",
"0",
",",
"underlyingWidth",
",",
"underlyingHeight",
")",
";",
"mDrawMatrix",
"=",
"mMatrix",
";",
"}",
"}"
] |
Determines bounds for the underlying drawable and a matrix that should be applied on it.
|
[
"Determines",
"bounds",
"for",
"the",
"underlying",
"drawable",
"and",
"a",
"matrix",
"that",
"should",
"be",
"applied",
"on",
"it",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/drawable/MatrixDrawable.java#L100-L116
|
14,641
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java
|
DefaultImageFormatChecker.determineFormat
|
@Nullable
@Override
public final ImageFormat determineFormat(byte[] headerBytes, int headerSize) {
Preconditions.checkNotNull(headerBytes);
if (WebpSupportStatus.isWebpHeader(headerBytes, 0, headerSize)) {
return getWebpFormat(headerBytes, headerSize);
}
if (isJpegHeader(headerBytes, headerSize)) {
return DefaultImageFormats.JPEG;
}
if (isPngHeader(headerBytes, headerSize)) {
return DefaultImageFormats.PNG;
}
if (isGifHeader(headerBytes, headerSize)) {
return DefaultImageFormats.GIF;
}
if (isBmpHeader(headerBytes, headerSize)) {
return DefaultImageFormats.BMP;
}
if (isIcoHeader(headerBytes, headerSize)) {
return DefaultImageFormats.ICO;
}
if (isHeifHeader(headerBytes, headerSize)) {
return DefaultImageFormats.HEIF;
}
return ImageFormat.UNKNOWN;
}
|
java
|
@Nullable
@Override
public final ImageFormat determineFormat(byte[] headerBytes, int headerSize) {
Preconditions.checkNotNull(headerBytes);
if (WebpSupportStatus.isWebpHeader(headerBytes, 0, headerSize)) {
return getWebpFormat(headerBytes, headerSize);
}
if (isJpegHeader(headerBytes, headerSize)) {
return DefaultImageFormats.JPEG;
}
if (isPngHeader(headerBytes, headerSize)) {
return DefaultImageFormats.PNG;
}
if (isGifHeader(headerBytes, headerSize)) {
return DefaultImageFormats.GIF;
}
if (isBmpHeader(headerBytes, headerSize)) {
return DefaultImageFormats.BMP;
}
if (isIcoHeader(headerBytes, headerSize)) {
return DefaultImageFormats.ICO;
}
if (isHeifHeader(headerBytes, headerSize)) {
return DefaultImageFormats.HEIF;
}
return ImageFormat.UNKNOWN;
}
|
[
"@",
"Nullable",
"@",
"Override",
"public",
"final",
"ImageFormat",
"determineFormat",
"(",
"byte",
"[",
"]",
"headerBytes",
",",
"int",
"headerSize",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"headerBytes",
")",
";",
"if",
"(",
"WebpSupportStatus",
".",
"isWebpHeader",
"(",
"headerBytes",
",",
"0",
",",
"headerSize",
")",
")",
"{",
"return",
"getWebpFormat",
"(",
"headerBytes",
",",
"headerSize",
")",
";",
"}",
"if",
"(",
"isJpegHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"JPEG",
";",
"}",
"if",
"(",
"isPngHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"PNG",
";",
"}",
"if",
"(",
"isGifHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"GIF",
";",
"}",
"if",
"(",
"isBmpHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"BMP",
";",
"}",
"if",
"(",
"isIcoHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"ICO",
";",
"}",
"if",
"(",
"isHeifHeader",
"(",
"headerBytes",
",",
"headerSize",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"HEIF",
";",
"}",
"return",
"ImageFormat",
".",
"UNKNOWN",
";",
"}"
] |
Tries to match imageHeaderByte and headerSize against every known image format. If any match
succeeds, corresponding ImageFormat is returned.
@param headerBytes the header bytes to check
@param headerSize the available header size
@return ImageFormat for given imageHeaderBytes or UNKNOWN if no such type could be recognized
|
[
"Tries",
"to",
"match",
"imageHeaderByte",
"and",
"headerSize",
"against",
"every",
"known",
"image",
"format",
".",
"If",
"any",
"match",
"succeeds",
"corresponding",
"ImageFormat",
"is",
"returned",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java#L51-L85
|
14,642
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java
|
DefaultImageFormatChecker.getWebpFormat
|
private static ImageFormat getWebpFormat(final byte[] imageHeaderBytes, final int headerSize) {
Preconditions.checkArgument(WebpSupportStatus.isWebpHeader(imageHeaderBytes, 0, headerSize));
if (WebpSupportStatus.isSimpleWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_SIMPLE;
}
if (WebpSupportStatus.isLosslessWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_LOSSLESS;
}
if (WebpSupportStatus.isExtendedWebpHeader(imageHeaderBytes, 0, headerSize)) {
if (WebpSupportStatus.isAnimatedWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_ANIMATED;
}
if (WebpSupportStatus.isExtendedWebpHeaderWithAlpha(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_EXTENDED_WITH_ALPHA;
}
return DefaultImageFormats.WEBP_EXTENDED;
}
return ImageFormat.UNKNOWN;
}
|
java
|
private static ImageFormat getWebpFormat(final byte[] imageHeaderBytes, final int headerSize) {
Preconditions.checkArgument(WebpSupportStatus.isWebpHeader(imageHeaderBytes, 0, headerSize));
if (WebpSupportStatus.isSimpleWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_SIMPLE;
}
if (WebpSupportStatus.isLosslessWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_LOSSLESS;
}
if (WebpSupportStatus.isExtendedWebpHeader(imageHeaderBytes, 0, headerSize)) {
if (WebpSupportStatus.isAnimatedWebpHeader(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_ANIMATED;
}
if (WebpSupportStatus.isExtendedWebpHeaderWithAlpha(imageHeaderBytes, 0)) {
return DefaultImageFormats.WEBP_EXTENDED_WITH_ALPHA;
}
return DefaultImageFormats.WEBP_EXTENDED;
}
return ImageFormat.UNKNOWN;
}
|
[
"private",
"static",
"ImageFormat",
"getWebpFormat",
"(",
"final",
"byte",
"[",
"]",
"imageHeaderBytes",
",",
"final",
"int",
"headerSize",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"WebpSupportStatus",
".",
"isWebpHeader",
"(",
"imageHeaderBytes",
",",
"0",
",",
"headerSize",
")",
")",
";",
"if",
"(",
"WebpSupportStatus",
".",
"isSimpleWebpHeader",
"(",
"imageHeaderBytes",
",",
"0",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"WEBP_SIMPLE",
";",
"}",
"if",
"(",
"WebpSupportStatus",
".",
"isLosslessWebpHeader",
"(",
"imageHeaderBytes",
",",
"0",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"WEBP_LOSSLESS",
";",
"}",
"if",
"(",
"WebpSupportStatus",
".",
"isExtendedWebpHeader",
"(",
"imageHeaderBytes",
",",
"0",
",",
"headerSize",
")",
")",
"{",
"if",
"(",
"WebpSupportStatus",
".",
"isAnimatedWebpHeader",
"(",
"imageHeaderBytes",
",",
"0",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"WEBP_ANIMATED",
";",
"}",
"if",
"(",
"WebpSupportStatus",
".",
"isExtendedWebpHeaderWithAlpha",
"(",
"imageHeaderBytes",
",",
"0",
")",
")",
"{",
"return",
"DefaultImageFormats",
".",
"WEBP_EXTENDED_WITH_ALPHA",
";",
"}",
"return",
"DefaultImageFormats",
".",
"WEBP_EXTENDED",
";",
"}",
"return",
"ImageFormat",
".",
"UNKNOWN",
";",
"}"
] |
Determines type of WebP image. imageHeaderBytes has to be header of a WebP image
|
[
"Determines",
"type",
"of",
"WebP",
"image",
".",
"imageHeaderBytes",
"has",
"to",
"be",
"header",
"of",
"a",
"WebP",
"image"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java#L104-L125
|
14,643
|
facebook/fresco
|
fbcore/src/main/java/com/facebook/common/activitylistener/ActivityListenerManager.java
|
ActivityListenerManager.register
|
public static void register(ActivityListener activityListener, Context context) {
ListenableActivity activity = getListenableActivity(context);
if (activity != null) {
Listener listener = new Listener(activityListener);
activity.addActivityListener(listener);
}
}
|
java
|
public static void register(ActivityListener activityListener, Context context) {
ListenableActivity activity = getListenableActivity(context);
if (activity != null) {
Listener listener = new Listener(activityListener);
activity.addActivityListener(listener);
}
}
|
[
"public",
"static",
"void",
"register",
"(",
"ActivityListener",
"activityListener",
",",
"Context",
"context",
")",
"{",
"ListenableActivity",
"activity",
"=",
"getListenableActivity",
"(",
"context",
")",
";",
"if",
"(",
"activity",
"!=",
"null",
")",
"{",
"Listener",
"listener",
"=",
"new",
"Listener",
"(",
"activityListener",
")",
";",
"activity",
".",
"addActivityListener",
"(",
"listener",
")",
";",
"}",
"}"
] |
If given context is an instance of ListenableActivity then creates new instance of
WeakReferenceActivityListenerAdapter and adds it to activity's listeners
|
[
"If",
"given",
"context",
"is",
"an",
"instance",
"of",
"ListenableActivity",
"then",
"creates",
"new",
"instance",
"of",
"WeakReferenceActivityListenerAdapter",
"and",
"adds",
"it",
"to",
"activity",
"s",
"listeners"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/activitylistener/ActivityListenerManager.java#L29-L35
|
14,644
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.cloneOrNull
|
public static @Nullable EncodedImage cloneOrNull(EncodedImage encodedImage) {
return encodedImage != null ? encodedImage.cloneOrNull() : null;
}
|
java
|
public static @Nullable EncodedImage cloneOrNull(EncodedImage encodedImage) {
return encodedImage != null ? encodedImage.cloneOrNull() : null;
}
|
[
"public",
"static",
"@",
"Nullable",
"EncodedImage",
"cloneOrNull",
"(",
"EncodedImage",
"encodedImage",
")",
"{",
"return",
"encodedImage",
"!=",
"null",
"?",
"encodedImage",
".",
"cloneOrNull",
"(",
")",
":",
"null",
";",
"}"
] |
Returns the cloned encoded image if the parameter received is not null, null otherwise.
@param encodedImage the EncodedImage to clone
|
[
"Returns",
"the",
"cloned",
"encoded",
"image",
"if",
"the",
"parameter",
"received",
"is",
"not",
"null",
"null",
"otherwise",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L94-L96
|
14,645
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.getInputStream
|
public @Nullable InputStream getInputStream() {
if (mInputStreamSupplier != null) {
return mInputStreamSupplier.get();
}
CloseableReference<PooledByteBuffer> pooledByteBufferRef =
CloseableReference.cloneOrNull(mPooledByteBufferRef);
if (pooledByteBufferRef != null) {
try {
return new PooledByteBufferInputStream(pooledByteBufferRef.get());
} finally {
CloseableReference.closeSafely(pooledByteBufferRef);
}
}
return null;
}
|
java
|
public @Nullable InputStream getInputStream() {
if (mInputStreamSupplier != null) {
return mInputStreamSupplier.get();
}
CloseableReference<PooledByteBuffer> pooledByteBufferRef =
CloseableReference.cloneOrNull(mPooledByteBufferRef);
if (pooledByteBufferRef != null) {
try {
return new PooledByteBufferInputStream(pooledByteBufferRef.get());
} finally {
CloseableReference.closeSafely(pooledByteBufferRef);
}
}
return null;
}
|
[
"public",
"@",
"Nullable",
"InputStream",
"getInputStream",
"(",
")",
"{",
"if",
"(",
"mInputStreamSupplier",
"!=",
"null",
")",
"{",
"return",
"mInputStreamSupplier",
".",
"get",
"(",
")",
";",
"}",
"CloseableReference",
"<",
"PooledByteBuffer",
">",
"pooledByteBufferRef",
"=",
"CloseableReference",
".",
"cloneOrNull",
"(",
"mPooledByteBufferRef",
")",
";",
"if",
"(",
"pooledByteBufferRef",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"new",
"PooledByteBufferInputStream",
"(",
"pooledByteBufferRef",
".",
"get",
"(",
")",
")",
";",
"}",
"finally",
"{",
"CloseableReference",
".",
"closeSafely",
"(",
"pooledByteBufferRef",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Returns an InputStream from the internal InputStream Supplier if it's not null. Otherwise
returns an InputStream for the internal buffer reference if valid and null otherwise.
<p>The caller has to close the InputStream after using it.
|
[
"Returns",
"an",
"InputStream",
"from",
"the",
"internal",
"InputStream",
"Supplier",
"if",
"it",
"s",
"not",
"null",
".",
"Otherwise",
"returns",
"an",
"InputStream",
"for",
"the",
"internal",
"buffer",
"reference",
"if",
"valid",
"and",
"null",
"otherwise",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L149-L163
|
14,646
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.isCompleteAt
|
public boolean isCompleteAt(int length) {
if (mImageFormat != DefaultImageFormats.JPEG) {
return true;
}
// If the image is backed by FileInputStreams return true since they will always be complete.
if (mInputStreamSupplier != null) {
return true;
}
// The image should be backed by a ByteBuffer
Preconditions.checkNotNull(mPooledByteBufferRef);
PooledByteBuffer buf = mPooledByteBufferRef.get();
return (buf.read(length - 2) == (byte) JfifUtil.MARKER_FIRST_BYTE)
&& (buf.read(length - 1) == (byte) JfifUtil.MARKER_EOI);
}
|
java
|
public boolean isCompleteAt(int length) {
if (mImageFormat != DefaultImageFormats.JPEG) {
return true;
}
// If the image is backed by FileInputStreams return true since they will always be complete.
if (mInputStreamSupplier != null) {
return true;
}
// The image should be backed by a ByteBuffer
Preconditions.checkNotNull(mPooledByteBufferRef);
PooledByteBuffer buf = mPooledByteBufferRef.get();
return (buf.read(length - 2) == (byte) JfifUtil.MARKER_FIRST_BYTE)
&& (buf.read(length - 1) == (byte) JfifUtil.MARKER_EOI);
}
|
[
"public",
"boolean",
"isCompleteAt",
"(",
"int",
"length",
")",
"{",
"if",
"(",
"mImageFormat",
"!=",
"DefaultImageFormats",
".",
"JPEG",
")",
"{",
"return",
"true",
";",
"}",
"// If the image is backed by FileInputStreams return true since they will always be complete.",
"if",
"(",
"mInputStreamSupplier",
"!=",
"null",
")",
"{",
"return",
"true",
";",
"}",
"// The image should be backed by a ByteBuffer",
"Preconditions",
".",
"checkNotNull",
"(",
"mPooledByteBufferRef",
")",
";",
"PooledByteBuffer",
"buf",
"=",
"mPooledByteBufferRef",
".",
"get",
"(",
")",
";",
"return",
"(",
"buf",
".",
"read",
"(",
"length",
"-",
"2",
")",
"==",
"(",
"byte",
")",
"JfifUtil",
".",
"MARKER_FIRST_BYTE",
")",
"&&",
"(",
"buf",
".",
"read",
"(",
"length",
"-",
"1",
")",
"==",
"(",
"byte",
")",
"JfifUtil",
".",
"MARKER_EOI",
")",
";",
"}"
] |
Returns true if the image is a JPEG and its data is already complete at the specified length,
false otherwise.
|
[
"Returns",
"true",
"if",
"the",
"image",
"is",
"a",
"JPEG",
"and",
"its",
"data",
"is",
"already",
"complete",
"at",
"the",
"specified",
"length",
"false",
"otherwise",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L281-L294
|
14,647
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.getSize
|
public int getSize() {
if (mPooledByteBufferRef != null && mPooledByteBufferRef.get() != null) {
return mPooledByteBufferRef.get().size();
}
return mStreamSize;
}
|
java
|
public int getSize() {
if (mPooledByteBufferRef != null && mPooledByteBufferRef.get() != null) {
return mPooledByteBufferRef.get().size();
}
return mStreamSize;
}
|
[
"public",
"int",
"getSize",
"(",
")",
"{",
"if",
"(",
"mPooledByteBufferRef",
"!=",
"null",
"&&",
"mPooledByteBufferRef",
".",
"get",
"(",
")",
"!=",
"null",
")",
"{",
"return",
"mPooledByteBufferRef",
".",
"get",
"(",
")",
".",
"size",
"(",
")",
";",
"}",
"return",
"mStreamSize",
";",
"}"
] |
Returns the size of the backing structure.
<p> If it's a PooledByteBuffer returns its size if its not null, -1 otherwise. If it's an
InputStream, return the size if it was set, -1 otherwise.
|
[
"Returns",
"the",
"size",
"of",
"the",
"backing",
"structure",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L302-L307
|
14,648
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.getFirstBytesAsHexString
|
public String getFirstBytesAsHexString(int length) {
CloseableReference<PooledByteBuffer> imageBuffer = getByteBufferRef();
if (imageBuffer == null) {
return "";
}
int imageSize = getSize();
int resultSampleSize = Math.min(imageSize, length);
byte[] bytesBuffer = new byte[resultSampleSize];
try {
PooledByteBuffer pooledByteBuffer = imageBuffer.get();
if (pooledByteBuffer == null) {
return "";
}
pooledByteBuffer.read(0, bytesBuffer, 0, resultSampleSize);
} finally {
imageBuffer.close();
}
StringBuilder stringBuilder = new StringBuilder(bytesBuffer.length * 2);
for (byte b : bytesBuffer) {
stringBuilder.append(String.format("%02X", b));
}
return stringBuilder.toString();
}
|
java
|
public String getFirstBytesAsHexString(int length) {
CloseableReference<PooledByteBuffer> imageBuffer = getByteBufferRef();
if (imageBuffer == null) {
return "";
}
int imageSize = getSize();
int resultSampleSize = Math.min(imageSize, length);
byte[] bytesBuffer = new byte[resultSampleSize];
try {
PooledByteBuffer pooledByteBuffer = imageBuffer.get();
if (pooledByteBuffer == null) {
return "";
}
pooledByteBuffer.read(0, bytesBuffer, 0, resultSampleSize);
} finally {
imageBuffer.close();
}
StringBuilder stringBuilder = new StringBuilder(bytesBuffer.length * 2);
for (byte b : bytesBuffer) {
stringBuilder.append(String.format("%02X", b));
}
return stringBuilder.toString();
}
|
[
"public",
"String",
"getFirstBytesAsHexString",
"(",
"int",
"length",
")",
"{",
"CloseableReference",
"<",
"PooledByteBuffer",
">",
"imageBuffer",
"=",
"getByteBufferRef",
"(",
")",
";",
"if",
"(",
"imageBuffer",
"==",
"null",
")",
"{",
"return",
"\"\"",
";",
"}",
"int",
"imageSize",
"=",
"getSize",
"(",
")",
";",
"int",
"resultSampleSize",
"=",
"Math",
".",
"min",
"(",
"imageSize",
",",
"length",
")",
";",
"byte",
"[",
"]",
"bytesBuffer",
"=",
"new",
"byte",
"[",
"resultSampleSize",
"]",
";",
"try",
"{",
"PooledByteBuffer",
"pooledByteBuffer",
"=",
"imageBuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"pooledByteBuffer",
"==",
"null",
")",
"{",
"return",
"\"\"",
";",
"}",
"pooledByteBuffer",
".",
"read",
"(",
"0",
",",
"bytesBuffer",
",",
"0",
",",
"resultSampleSize",
")",
";",
"}",
"finally",
"{",
"imageBuffer",
".",
"close",
"(",
")",
";",
"}",
"StringBuilder",
"stringBuilder",
"=",
"new",
"StringBuilder",
"(",
"bytesBuffer",
".",
"length",
"*",
"2",
")",
";",
"for",
"(",
"byte",
"b",
":",
"bytesBuffer",
")",
"{",
"stringBuilder",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"%02X\"",
",",
"b",
")",
")",
";",
"}",
"return",
"stringBuilder",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns first n bytes of encoded image as hexbytes
@param length the number of bytes to return
|
[
"Returns",
"first",
"n",
"bytes",
"of",
"encoded",
"image",
"as",
"hexbytes"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L314-L336
|
14,649
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.parseMetaData
|
public void parseMetaData() {
final ImageFormat imageFormat = ImageFormatChecker.getImageFormat_WrapIOException(
getInputStream());
mImageFormat = imageFormat;
// BitmapUtil.decodeDimensions has a bug where it will return 100x100 for some WebPs even though
// those are not its actual dimensions
final Pair<Integer, Integer> dimensions;
if (DefaultImageFormats.isWebpFormat(imageFormat)) {
dimensions = readWebPImageSize();
} else {
dimensions = readImageMetaData().getDimensions();
}
if (imageFormat == DefaultImageFormats.JPEG && mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
// Load the JPEG rotation angle only if we have the dimensions
if (dimensions != null) {
mExifOrientation = JfifUtil.getOrientation(getInputStream());
mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
}
} else if (imageFormat == DefaultImageFormats.HEIF
&& mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
mExifOrientation = HeifExifUtil.getOrientation(getInputStream());
mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
} else {
mRotationAngle = 0;
}
}
|
java
|
public void parseMetaData() {
final ImageFormat imageFormat = ImageFormatChecker.getImageFormat_WrapIOException(
getInputStream());
mImageFormat = imageFormat;
// BitmapUtil.decodeDimensions has a bug where it will return 100x100 for some WebPs even though
// those are not its actual dimensions
final Pair<Integer, Integer> dimensions;
if (DefaultImageFormats.isWebpFormat(imageFormat)) {
dimensions = readWebPImageSize();
} else {
dimensions = readImageMetaData().getDimensions();
}
if (imageFormat == DefaultImageFormats.JPEG && mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
// Load the JPEG rotation angle only if we have the dimensions
if (dimensions != null) {
mExifOrientation = JfifUtil.getOrientation(getInputStream());
mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
}
} else if (imageFormat == DefaultImageFormats.HEIF
&& mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
mExifOrientation = HeifExifUtil.getOrientation(getInputStream());
mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
} else {
mRotationAngle = 0;
}
}
|
[
"public",
"void",
"parseMetaData",
"(",
")",
"{",
"final",
"ImageFormat",
"imageFormat",
"=",
"ImageFormatChecker",
".",
"getImageFormat_WrapIOException",
"(",
"getInputStream",
"(",
")",
")",
";",
"mImageFormat",
"=",
"imageFormat",
";",
"// BitmapUtil.decodeDimensions has a bug where it will return 100x100 for some WebPs even though",
"// those are not its actual dimensions",
"final",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"dimensions",
";",
"if",
"(",
"DefaultImageFormats",
".",
"isWebpFormat",
"(",
"imageFormat",
")",
")",
"{",
"dimensions",
"=",
"readWebPImageSize",
"(",
")",
";",
"}",
"else",
"{",
"dimensions",
"=",
"readImageMetaData",
"(",
")",
".",
"getDimensions",
"(",
")",
";",
"}",
"if",
"(",
"imageFormat",
"==",
"DefaultImageFormats",
".",
"JPEG",
"&&",
"mRotationAngle",
"==",
"UNKNOWN_ROTATION_ANGLE",
")",
"{",
"// Load the JPEG rotation angle only if we have the dimensions",
"if",
"(",
"dimensions",
"!=",
"null",
")",
"{",
"mExifOrientation",
"=",
"JfifUtil",
".",
"getOrientation",
"(",
"getInputStream",
"(",
")",
")",
";",
"mRotationAngle",
"=",
"JfifUtil",
".",
"getAutoRotateAngleFromOrientation",
"(",
"mExifOrientation",
")",
";",
"}",
"}",
"else",
"if",
"(",
"imageFormat",
"==",
"DefaultImageFormats",
".",
"HEIF",
"&&",
"mRotationAngle",
"==",
"UNKNOWN_ROTATION_ANGLE",
")",
"{",
"mExifOrientation",
"=",
"HeifExifUtil",
".",
"getOrientation",
"(",
"getInputStream",
"(",
")",
")",
";",
"mRotationAngle",
"=",
"JfifUtil",
".",
"getAutoRotateAngleFromOrientation",
"(",
"mExifOrientation",
")",
";",
"}",
"else",
"{",
"mRotationAngle",
"=",
"0",
";",
"}",
"}"
] |
Sets the encoded image meta data.
|
[
"Sets",
"the",
"encoded",
"image",
"meta",
"data",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L346-L371
|
14,650
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.readWebPImageSize
|
private Pair<Integer, Integer> readWebPImageSize() {
final Pair<Integer, Integer> dimensions = WebpUtil.getSize(getInputStream());
if (dimensions != null) {
mWidth = dimensions.first;
mHeight = dimensions.second;
}
return dimensions;
}
|
java
|
private Pair<Integer, Integer> readWebPImageSize() {
final Pair<Integer, Integer> dimensions = WebpUtil.getSize(getInputStream());
if (dimensions != null) {
mWidth = dimensions.first;
mHeight = dimensions.second;
}
return dimensions;
}
|
[
"private",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"readWebPImageSize",
"(",
")",
"{",
"final",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"dimensions",
"=",
"WebpUtil",
".",
"getSize",
"(",
"getInputStream",
"(",
")",
")",
";",
"if",
"(",
"dimensions",
"!=",
"null",
")",
"{",
"mWidth",
"=",
"dimensions",
".",
"first",
";",
"mHeight",
"=",
"dimensions",
".",
"second",
";",
"}",
"return",
"dimensions",
";",
"}"
] |
We get the size from a WebP image
|
[
"We",
"get",
"the",
"size",
"from",
"a",
"WebP",
"image"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L376-L383
|
14,651
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.readImageMetaData
|
private ImageMetaData readImageMetaData() {
InputStream inputStream = null;
ImageMetaData metaData = null;
try {
inputStream = getInputStream();
metaData = BitmapUtil.decodeDimensionsAndColorSpace(inputStream);
mColorSpace = metaData.getColorSpace();
Pair<Integer, Integer> dimensions = metaData.getDimensions();
if (dimensions != null) {
mWidth = dimensions.first;
mHeight = dimensions.second;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// Head in the sand
}
}
}
return metaData;
}
|
java
|
private ImageMetaData readImageMetaData() {
InputStream inputStream = null;
ImageMetaData metaData = null;
try {
inputStream = getInputStream();
metaData = BitmapUtil.decodeDimensionsAndColorSpace(inputStream);
mColorSpace = metaData.getColorSpace();
Pair<Integer, Integer> dimensions = metaData.getDimensions();
if (dimensions != null) {
mWidth = dimensions.first;
mHeight = dimensions.second;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// Head in the sand
}
}
}
return metaData;
}
|
[
"private",
"ImageMetaData",
"readImageMetaData",
"(",
")",
"{",
"InputStream",
"inputStream",
"=",
"null",
";",
"ImageMetaData",
"metaData",
"=",
"null",
";",
"try",
"{",
"inputStream",
"=",
"getInputStream",
"(",
")",
";",
"metaData",
"=",
"BitmapUtil",
".",
"decodeDimensionsAndColorSpace",
"(",
"inputStream",
")",
";",
"mColorSpace",
"=",
"metaData",
".",
"getColorSpace",
"(",
")",
";",
"Pair",
"<",
"Integer",
",",
"Integer",
">",
"dimensions",
"=",
"metaData",
".",
"getDimensions",
"(",
")",
";",
"if",
"(",
"dimensions",
"!=",
"null",
")",
"{",
"mWidth",
"=",
"dimensions",
".",
"first",
";",
"mHeight",
"=",
"dimensions",
".",
"second",
";",
"}",
"}",
"finally",
"{",
"if",
"(",
"inputStream",
"!=",
"null",
")",
"{",
"try",
"{",
"inputStream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Head in the sand",
"}",
"}",
"}",
"return",
"metaData",
";",
"}"
] |
We get the size from a generic image
|
[
"We",
"get",
"the",
"size",
"from",
"a",
"generic",
"image"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L386-L408
|
14,652
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java
|
EncodedImage.copyMetaDataFrom
|
public void copyMetaDataFrom(EncodedImage encodedImage) {
mImageFormat = encodedImage.getImageFormat();
mWidth = encodedImage.getWidth();
mHeight = encodedImage.getHeight();
mRotationAngle = encodedImage.getRotationAngle();
mExifOrientation = encodedImage.getExifOrientation();
mSampleSize = encodedImage.getSampleSize();
mStreamSize = encodedImage.getSize();
mBytesRange = encodedImage.getBytesRange();
mColorSpace = encodedImage.getColorSpace();
}
|
java
|
public void copyMetaDataFrom(EncodedImage encodedImage) {
mImageFormat = encodedImage.getImageFormat();
mWidth = encodedImage.getWidth();
mHeight = encodedImage.getHeight();
mRotationAngle = encodedImage.getRotationAngle();
mExifOrientation = encodedImage.getExifOrientation();
mSampleSize = encodedImage.getSampleSize();
mStreamSize = encodedImage.getSize();
mBytesRange = encodedImage.getBytesRange();
mColorSpace = encodedImage.getColorSpace();
}
|
[
"public",
"void",
"copyMetaDataFrom",
"(",
"EncodedImage",
"encodedImage",
")",
"{",
"mImageFormat",
"=",
"encodedImage",
".",
"getImageFormat",
"(",
")",
";",
"mWidth",
"=",
"encodedImage",
".",
"getWidth",
"(",
")",
";",
"mHeight",
"=",
"encodedImage",
".",
"getHeight",
"(",
")",
";",
"mRotationAngle",
"=",
"encodedImage",
".",
"getRotationAngle",
"(",
")",
";",
"mExifOrientation",
"=",
"encodedImage",
".",
"getExifOrientation",
"(",
")",
";",
"mSampleSize",
"=",
"encodedImage",
".",
"getSampleSize",
"(",
")",
";",
"mStreamSize",
"=",
"encodedImage",
".",
"getSize",
"(",
")",
";",
"mBytesRange",
"=",
"encodedImage",
".",
"getBytesRange",
"(",
")",
";",
"mColorSpace",
"=",
"encodedImage",
".",
"getColorSpace",
"(",
")",
";",
"}"
] |
Copy the meta data from another EncodedImage.
@param encodedImage the EncodedImage to copy the meta data from.
|
[
"Copy",
"the",
"meta",
"data",
"from",
"another",
"EncodedImage",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/image/EncodedImage.java#L415-L425
|
14,653
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java
|
AnimatedDrawableUtil.fixFrameDurations
|
public void fixFrameDurations(int[] frameDurationMs) {
// We follow Chrome's behavior which comes from Firefox.
// Comment from Chrome's ImageSource.cpp follows:
// We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
// a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
// for more information.
for (int i = 0; i < frameDurationMs.length; i++) {
if (frameDurationMs[i] < MIN_FRAME_DURATION_MS) {
frameDurationMs[i] = FRAME_DURATION_MS_FOR_MIN;
}
}
}
|
java
|
public void fixFrameDurations(int[] frameDurationMs) {
// We follow Chrome's behavior which comes from Firefox.
// Comment from Chrome's ImageSource.cpp follows:
// We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
// a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
// for more information.
for (int i = 0; i < frameDurationMs.length; i++) {
if (frameDurationMs[i] < MIN_FRAME_DURATION_MS) {
frameDurationMs[i] = FRAME_DURATION_MS_FOR_MIN;
}
}
}
|
[
"public",
"void",
"fixFrameDurations",
"(",
"int",
"[",
"]",
"frameDurationMs",
")",
"{",
"// We follow Chrome's behavior which comes from Firefox.",
"// Comment from Chrome's ImageSource.cpp follows:",
"// We follow Firefox's behavior and use a duration of 100 ms for any frames that specify",
"// a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>",
"// for more information.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"frameDurationMs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"frameDurationMs",
"[",
"i",
"]",
"<",
"MIN_FRAME_DURATION_MS",
")",
"{",
"frameDurationMs",
"[",
"i",
"]",
"=",
"FRAME_DURATION_MS_FOR_MIN",
";",
"}",
"}",
"}"
] |
Adjusts the frame duration array to respect logic for minimum frame duration time.
@param frameDurationMs the frame duration array
|
[
"Adjusts",
"the",
"frame",
"duration",
"array",
"to",
"respect",
"logic",
"for",
"minimum",
"frame",
"duration",
"time",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java#L29-L40
|
14,654
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java
|
AnimatedDrawableUtil.getTotalDurationFromFrameDurations
|
public int getTotalDurationFromFrameDurations(int[] frameDurationMs) {
int totalMs = 0;
for (int i = 0; i < frameDurationMs.length; i++) {
totalMs += frameDurationMs[i];
}
return totalMs;
}
|
java
|
public int getTotalDurationFromFrameDurations(int[] frameDurationMs) {
int totalMs = 0;
for (int i = 0; i < frameDurationMs.length; i++) {
totalMs += frameDurationMs[i];
}
return totalMs;
}
|
[
"public",
"int",
"getTotalDurationFromFrameDurations",
"(",
"int",
"[",
"]",
"frameDurationMs",
")",
"{",
"int",
"totalMs",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"frameDurationMs",
".",
"length",
";",
"i",
"++",
")",
"{",
"totalMs",
"+=",
"frameDurationMs",
"[",
"i",
"]",
";",
"}",
"return",
"totalMs",
";",
"}"
] |
Gets the total duration of an image by summing up the duration of the frames.
@param frameDurationMs the frame duration array
@return the total duration in milliseconds
|
[
"Gets",
"the",
"total",
"duration",
"of",
"an",
"image",
"by",
"summing",
"up",
"the",
"duration",
"of",
"the",
"frames",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java#L48-L54
|
14,655
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java
|
AnimatedDrawableUtil.getFrameTimeStampsFromDurations
|
public int[] getFrameTimeStampsFromDurations(int[] frameDurationsMs) {
int[] frameTimestampsMs = new int[frameDurationsMs.length];
int accumulatedDurationMs = 0;
for (int i = 0; i < frameDurationsMs.length; i++) {
frameTimestampsMs[i] = accumulatedDurationMs;
accumulatedDurationMs += frameDurationsMs[i];
}
return frameTimestampsMs;
}
|
java
|
public int[] getFrameTimeStampsFromDurations(int[] frameDurationsMs) {
int[] frameTimestampsMs = new int[frameDurationsMs.length];
int accumulatedDurationMs = 0;
for (int i = 0; i < frameDurationsMs.length; i++) {
frameTimestampsMs[i] = accumulatedDurationMs;
accumulatedDurationMs += frameDurationsMs[i];
}
return frameTimestampsMs;
}
|
[
"public",
"int",
"[",
"]",
"getFrameTimeStampsFromDurations",
"(",
"int",
"[",
"]",
"frameDurationsMs",
")",
"{",
"int",
"[",
"]",
"frameTimestampsMs",
"=",
"new",
"int",
"[",
"frameDurationsMs",
".",
"length",
"]",
";",
"int",
"accumulatedDurationMs",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"frameDurationsMs",
".",
"length",
";",
"i",
"++",
")",
"{",
"frameTimestampsMs",
"[",
"i",
"]",
"=",
"accumulatedDurationMs",
";",
"accumulatedDurationMs",
"+=",
"frameDurationsMs",
"[",
"i",
"]",
";",
"}",
"return",
"frameTimestampsMs",
";",
"}"
] |
Given an array of frame durations, generate an array of timestamps corresponding to when each
frame beings.
@param frameDurationsMs an array of frame durations
@return an array of timestamps
|
[
"Given",
"an",
"array",
"of",
"frame",
"durations",
"generate",
"an",
"array",
"of",
"timestamps",
"corresponding",
"to",
"when",
"each",
"frame",
"beings",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java#L63-L71
|
14,656
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java
|
AnimatedDrawableUtil.getFrameForTimestampMs
|
public int getFrameForTimestampMs(int frameTimestampsMs[], int timestampMs) {
int index = Arrays.binarySearch(frameTimestampsMs, timestampMs);
if (index < 0) {
return -index - 1 - 1;
} else {
return index;
}
}
|
java
|
public int getFrameForTimestampMs(int frameTimestampsMs[], int timestampMs) {
int index = Arrays.binarySearch(frameTimestampsMs, timestampMs);
if (index < 0) {
return -index - 1 - 1;
} else {
return index;
}
}
|
[
"public",
"int",
"getFrameForTimestampMs",
"(",
"int",
"frameTimestampsMs",
"[",
"]",
",",
"int",
"timestampMs",
")",
"{",
"int",
"index",
"=",
"Arrays",
".",
"binarySearch",
"(",
"frameTimestampsMs",
",",
"timestampMs",
")",
";",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"return",
"-",
"index",
"-",
"1",
"-",
"1",
";",
"}",
"else",
"{",
"return",
"index",
";",
"}",
"}"
] |
Gets the frame index for specified timestamp.
@param frameTimestampsMs an array of timestamps generated by {@link #getFrameForTimestampMs)}
@param timestampMs the timestamp
@return the frame index for the timestamp or the last frame number if the timestamp is outside
the duration of the entire animation
|
[
"Gets",
"the",
"frame",
"index",
"for",
"specified",
"timestamp",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java#L81-L88
|
14,657
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java
|
SimpleDraweeView.setImageRequest
|
public void setImageRequest(ImageRequest request) {
AbstractDraweeControllerBuilder controllerBuilder = mControllerBuilder;
DraweeController controller =
controllerBuilder.setImageRequest(request).setOldController(getController()).build();
setController(controller);
}
|
java
|
public void setImageRequest(ImageRequest request) {
AbstractDraweeControllerBuilder controllerBuilder = mControllerBuilder;
DraweeController controller =
controllerBuilder.setImageRequest(request).setOldController(getController()).build();
setController(controller);
}
|
[
"public",
"void",
"setImageRequest",
"(",
"ImageRequest",
"request",
")",
"{",
"AbstractDraweeControllerBuilder",
"controllerBuilder",
"=",
"mControllerBuilder",
";",
"DraweeController",
"controller",
"=",
"controllerBuilder",
".",
"setImageRequest",
"(",
"request",
")",
".",
"setOldController",
"(",
"getController",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"setController",
"(",
"controller",
")",
";",
"}"
] |
Sets the image request
@param request Image Request
|
[
"Sets",
"the",
"image",
"request"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java#L129-L134
|
14,658
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java
|
ImageRequestBuilder.fromRequest
|
public static ImageRequestBuilder fromRequest(ImageRequest imageRequest) {
return ImageRequestBuilder.newBuilderWithSource(imageRequest.getSourceUri())
.setImageDecodeOptions(imageRequest.getImageDecodeOptions())
.setBytesRange(imageRequest.getBytesRange())
.setCacheChoice(imageRequest.getCacheChoice())
.setLocalThumbnailPreviewsEnabled(imageRequest.getLocalThumbnailPreviewsEnabled())
.setLowestPermittedRequestLevel(imageRequest.getLowestPermittedRequestLevel())
.setPostprocessor(imageRequest.getPostprocessor())
.setProgressiveRenderingEnabled(imageRequest.getProgressiveRenderingEnabled())
.setRequestPriority(imageRequest.getPriority())
.setResizeOptions(imageRequest.getResizeOptions())
.setRequestListener(imageRequest.getRequestListener())
.setRotationOptions(imageRequest.getRotationOptions())
.setShouldDecodePrefetches(imageRequest.shouldDecodePrefetches());
}
|
java
|
public static ImageRequestBuilder fromRequest(ImageRequest imageRequest) {
return ImageRequestBuilder.newBuilderWithSource(imageRequest.getSourceUri())
.setImageDecodeOptions(imageRequest.getImageDecodeOptions())
.setBytesRange(imageRequest.getBytesRange())
.setCacheChoice(imageRequest.getCacheChoice())
.setLocalThumbnailPreviewsEnabled(imageRequest.getLocalThumbnailPreviewsEnabled())
.setLowestPermittedRequestLevel(imageRequest.getLowestPermittedRequestLevel())
.setPostprocessor(imageRequest.getPostprocessor())
.setProgressiveRenderingEnabled(imageRequest.getProgressiveRenderingEnabled())
.setRequestPriority(imageRequest.getPriority())
.setResizeOptions(imageRequest.getResizeOptions())
.setRequestListener(imageRequest.getRequestListener())
.setRotationOptions(imageRequest.getRotationOptions())
.setShouldDecodePrefetches(imageRequest.shouldDecodePrefetches());
}
|
[
"public",
"static",
"ImageRequestBuilder",
"fromRequest",
"(",
"ImageRequest",
"imageRequest",
")",
"{",
"return",
"ImageRequestBuilder",
".",
"newBuilderWithSource",
"(",
"imageRequest",
".",
"getSourceUri",
"(",
")",
")",
".",
"setImageDecodeOptions",
"(",
"imageRequest",
".",
"getImageDecodeOptions",
"(",
")",
")",
".",
"setBytesRange",
"(",
"imageRequest",
".",
"getBytesRange",
"(",
")",
")",
".",
"setCacheChoice",
"(",
"imageRequest",
".",
"getCacheChoice",
"(",
")",
")",
".",
"setLocalThumbnailPreviewsEnabled",
"(",
"imageRequest",
".",
"getLocalThumbnailPreviewsEnabled",
"(",
")",
")",
".",
"setLowestPermittedRequestLevel",
"(",
"imageRequest",
".",
"getLowestPermittedRequestLevel",
"(",
")",
")",
".",
"setPostprocessor",
"(",
"imageRequest",
".",
"getPostprocessor",
"(",
")",
")",
".",
"setProgressiveRenderingEnabled",
"(",
"imageRequest",
".",
"getProgressiveRenderingEnabled",
"(",
")",
")",
".",
"setRequestPriority",
"(",
"imageRequest",
".",
"getPriority",
"(",
")",
")",
".",
"setResizeOptions",
"(",
"imageRequest",
".",
"getResizeOptions",
"(",
")",
")",
".",
"setRequestListener",
"(",
"imageRequest",
".",
"getRequestListener",
"(",
")",
")",
".",
"setRotationOptions",
"(",
"imageRequest",
".",
"getRotationOptions",
"(",
")",
")",
".",
"setShouldDecodePrefetches",
"(",
"imageRequest",
".",
"shouldDecodePrefetches",
"(",
")",
")",
";",
"}"
] |
Creates a new request builder instance with the same parameters as the imageRequest passed in.
@param imageRequest the ImageRequest from where to copy the parameters to the builder.
@return a new request builder instance
|
[
"Creates",
"a",
"new",
"request",
"builder",
"instance",
"with",
"the",
"same",
"parameters",
"as",
"the",
"imageRequest",
"passed",
"in",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java#L84-L98
|
14,659
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java
|
ImageRequestBuilder.setAutoRotateEnabled
|
@Deprecated
public ImageRequestBuilder setAutoRotateEnabled(boolean enabled) {
if (enabled) {
return setRotationOptions(RotationOptions.autoRotate());
} else {
return setRotationOptions(RotationOptions.disableRotation());
}
}
|
java
|
@Deprecated
public ImageRequestBuilder setAutoRotateEnabled(boolean enabled) {
if (enabled) {
return setRotationOptions(RotationOptions.autoRotate());
} else {
return setRotationOptions(RotationOptions.disableRotation());
}
}
|
[
"@",
"Deprecated",
"public",
"ImageRequestBuilder",
"setAutoRotateEnabled",
"(",
"boolean",
"enabled",
")",
"{",
"if",
"(",
"enabled",
")",
"{",
"return",
"setRotationOptions",
"(",
"RotationOptions",
".",
"autoRotate",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"setRotationOptions",
"(",
"RotationOptions",
".",
"disableRotation",
"(",
")",
")",
";",
"}",
"}"
] |
Enables or disables auto-rotate for the image in case image has orientation.
@return the updated builder instance
@param enabled
@deprecated Use #setRotationOptions(RotationOptions)
|
[
"Enables",
"or",
"disables",
"auto",
"-",
"rotate",
"for",
"the",
"image",
"in",
"case",
"image",
"has",
"orientation",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java#L142-L149
|
14,660
|
facebook/fresco
|
imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java
|
ImageRequestBuilder.validate
|
protected void validate() {
// make sure that the source uri is set correctly.
if (mSourceUri == null) {
throw new BuilderException("Source must be set!");
}
// For local resource we require caller to specify statically generated resource id as a path.
if (UriUtil.isLocalResourceUri(mSourceUri)) {
if (!mSourceUri.isAbsolute()) {
throw new BuilderException("Resource URI path must be absolute.");
}
if (mSourceUri.getPath().isEmpty()) {
throw new BuilderException("Resource URI must not be empty");
}
try {
Integer.parseInt(mSourceUri.getPath().substring(1));
} catch (NumberFormatException ignored) {
throw new BuilderException("Resource URI path must be a resource id.");
}
}
// For local asset we require caller to specify absolute path of an asset, which will be
// resolved by AssetManager relative to configured asset folder of an app.
if (UriUtil.isLocalAssetUri(mSourceUri) && !mSourceUri.isAbsolute()) {
throw new BuilderException("Asset URI path must be absolute.");
}
}
|
java
|
protected void validate() {
// make sure that the source uri is set correctly.
if (mSourceUri == null) {
throw new BuilderException("Source must be set!");
}
// For local resource we require caller to specify statically generated resource id as a path.
if (UriUtil.isLocalResourceUri(mSourceUri)) {
if (!mSourceUri.isAbsolute()) {
throw new BuilderException("Resource URI path must be absolute.");
}
if (mSourceUri.getPath().isEmpty()) {
throw new BuilderException("Resource URI must not be empty");
}
try {
Integer.parseInt(mSourceUri.getPath().substring(1));
} catch (NumberFormatException ignored) {
throw new BuilderException("Resource URI path must be a resource id.");
}
}
// For local asset we require caller to specify absolute path of an asset, which will be
// resolved by AssetManager relative to configured asset folder of an app.
if (UriUtil.isLocalAssetUri(mSourceUri) && !mSourceUri.isAbsolute()) {
throw new BuilderException("Asset URI path must be absolute.");
}
}
|
[
"protected",
"void",
"validate",
"(",
")",
"{",
"// make sure that the source uri is set correctly.",
"if",
"(",
"mSourceUri",
"==",
"null",
")",
"{",
"throw",
"new",
"BuilderException",
"(",
"\"Source must be set!\"",
")",
";",
"}",
"// For local resource we require caller to specify statically generated resource id as a path.",
"if",
"(",
"UriUtil",
".",
"isLocalResourceUri",
"(",
"mSourceUri",
")",
")",
"{",
"if",
"(",
"!",
"mSourceUri",
".",
"isAbsolute",
"(",
")",
")",
"{",
"throw",
"new",
"BuilderException",
"(",
"\"Resource URI path must be absolute.\"",
")",
";",
"}",
"if",
"(",
"mSourceUri",
".",
"getPath",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"BuilderException",
"(",
"\"Resource URI must not be empty\"",
")",
";",
"}",
"try",
"{",
"Integer",
".",
"parseInt",
"(",
"mSourceUri",
".",
"getPath",
"(",
")",
".",
"substring",
"(",
"1",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"ignored",
")",
"{",
"throw",
"new",
"BuilderException",
"(",
"\"Resource URI path must be a resource id.\"",
")",
";",
"}",
"}",
"// For local asset we require caller to specify absolute path of an asset, which will be",
"// resolved by AssetManager relative to configured asset folder of an app.",
"if",
"(",
"UriUtil",
".",
"isLocalAssetUri",
"(",
"mSourceUri",
")",
"&&",
"!",
"mSourceUri",
".",
"isAbsolute",
"(",
")",
")",
"{",
"throw",
"new",
"BuilderException",
"(",
"\"Asset URI path must be absolute.\"",
")",
";",
"}",
"}"
] |
Performs validation.
|
[
"Performs",
"validation",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/request/ImageRequestBuilder.java#L369-L395
|
14,661
|
facebook/fresco
|
fbcore/src/main/java/com/facebook/common/webp/WebpSupportStatus.java
|
WebpSupportStatus.isExtendedWebpSupported
|
private static boolean isExtendedWebpSupported() {
// Lossless and extended formats are supported on Android 4.2.1+
// Unfortunately SDK_INT is not enough to distinguish 4.2 and 4.2.1
// (both are API level 17 (JELLY_BEAN_MR1))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return false;
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Let's test if extended webp is supported
// To this end we will try to decode bounds of vp8x webp with alpha channel
byte[] decodedBytes = Base64.decode(VP8X_WEBP_BASE64, Base64.DEFAULT);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, opts);
// If Android managed to find appropriate decoder then opts.outHeight and opts.outWidth
// should be set. We can not assume that outMimeType is set.
// Android guys forgot to update logic for mime types when they introduced support for webp.
// For example, on 4.2.2 this field is not set for webp images.
if (opts.outHeight != 1 || opts.outWidth != 1) {
return false;
}
}
return true;
}
|
java
|
private static boolean isExtendedWebpSupported() {
// Lossless and extended formats are supported on Android 4.2.1+
// Unfortunately SDK_INT is not enough to distinguish 4.2 and 4.2.1
// (both are API level 17 (JELLY_BEAN_MR1))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return false;
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Let's test if extended webp is supported
// To this end we will try to decode bounds of vp8x webp with alpha channel
byte[] decodedBytes = Base64.decode(VP8X_WEBP_BASE64, Base64.DEFAULT);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, opts);
// If Android managed to find appropriate decoder then opts.outHeight and opts.outWidth
// should be set. We can not assume that outMimeType is set.
// Android guys forgot to update logic for mime types when they introduced support for webp.
// For example, on 4.2.2 this field is not set for webp images.
if (opts.outHeight != 1 || opts.outWidth != 1) {
return false;
}
}
return true;
}
|
[
"private",
"static",
"boolean",
"isExtendedWebpSupported",
"(",
")",
"{",
"// Lossless and extended formats are supported on Android 4.2.1+",
"// Unfortunately SDK_INT is not enough to distinguish 4.2 and 4.2.1",
"// (both are API level 17 (JELLY_BEAN_MR1))",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
"<",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN_MR1",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
"==",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN_MR1",
")",
"{",
"// Let's test if extended webp is supported",
"// To this end we will try to decode bounds of vp8x webp with alpha channel",
"byte",
"[",
"]",
"decodedBytes",
"=",
"Base64",
".",
"decode",
"(",
"VP8X_WEBP_BASE64",
",",
"Base64",
".",
"DEFAULT",
")",
";",
"BitmapFactory",
".",
"Options",
"opts",
"=",
"new",
"BitmapFactory",
".",
"Options",
"(",
")",
";",
"opts",
".",
"inJustDecodeBounds",
"=",
"true",
";",
"BitmapFactory",
".",
"decodeByteArray",
"(",
"decodedBytes",
",",
"0",
",",
"decodedBytes",
".",
"length",
",",
"opts",
")",
";",
"// If Android managed to find appropriate decoder then opts.outHeight and opts.outWidth",
"// should be set. We can not assume that outMimeType is set.",
"// Android guys forgot to update logic for mime types when they introduced support for webp.",
"// For example, on 4.2.2 this field is not set for webp images.",
"if",
"(",
"opts",
".",
"outHeight",
"!=",
"1",
"||",
"opts",
".",
"outWidth",
"!=",
"1",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Checks whether underlying platform supports extended WebPs
|
[
"Checks",
"whether",
"underlying",
"platform",
"supports",
"extended",
"WebPs"
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/webp/WebpSupportStatus.java#L94-L120
|
14,662
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
|
TiffUtil.getAutoRotateAngleFromOrientation
|
public static int getAutoRotateAngleFromOrientation(int orientation) {
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
return 0;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
}
return 0;
}
|
java
|
public static int getAutoRotateAngleFromOrientation(int orientation) {
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
return 0;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
}
return 0;
}
|
[
"public",
"static",
"int",
"getAutoRotateAngleFromOrientation",
"(",
"int",
"orientation",
")",
"{",
"switch",
"(",
"orientation",
")",
"{",
"case",
"ExifInterface",
".",
"ORIENTATION_NORMAL",
":",
"case",
"ExifInterface",
".",
"ORIENTATION_UNDEFINED",
":",
"return",
"0",
";",
"case",
"ExifInterface",
".",
"ORIENTATION_ROTATE_180",
":",
"return",
"180",
";",
"case",
"ExifInterface",
".",
"ORIENTATION_ROTATE_90",
":",
"return",
"90",
";",
"case",
"ExifInterface",
".",
"ORIENTATION_ROTATE_270",
":",
"return",
"270",
";",
"}",
"return",
"0",
";",
"}"
] |
Determines auto-rotate angle based on orientation information.
@param orientation orientation information read from APP1 EXIF (TIFF) block.
@return orientation: 1/3/6/8 -> 0/180/90/270. Returns 0 for inverted orientations (2/4/5/7).
|
[
"Determines",
"auto",
"-",
"rotate",
"angle",
"based",
"on",
"orientation",
"information",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L33-L46
|
14,663
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
|
TiffUtil.readOrientationFromTIFF
|
public static int readOrientationFromTIFF(InputStream is, int length) throws IOException {
// read tiff header
TiffHeader tiffHeader = new TiffHeader();
length = readTiffHeader(is, length, tiffHeader);
// move to the first IFD
// offset is relative to the beginning of the TIFF data
// and we already consumed the first 8 bytes of header
int toSkip = tiffHeader.firstIfdOffset - 8;
if (length == 0 || toSkip > length) {
return 0;
}
is.skip(toSkip);
length -= toSkip;
// move to the entry with orientation tag
length = moveToTiffEntryWithTag(is, length, tiffHeader.isLittleEndian, TIFF_TAG_ORIENTATION);
// read orientation
return getOrientationFromTiffEntry(is, length, tiffHeader.isLittleEndian);
}
|
java
|
public static int readOrientationFromTIFF(InputStream is, int length) throws IOException {
// read tiff header
TiffHeader tiffHeader = new TiffHeader();
length = readTiffHeader(is, length, tiffHeader);
// move to the first IFD
// offset is relative to the beginning of the TIFF data
// and we already consumed the first 8 bytes of header
int toSkip = tiffHeader.firstIfdOffset - 8;
if (length == 0 || toSkip > length) {
return 0;
}
is.skip(toSkip);
length -= toSkip;
// move to the entry with orientation tag
length = moveToTiffEntryWithTag(is, length, tiffHeader.isLittleEndian, TIFF_TAG_ORIENTATION);
// read orientation
return getOrientationFromTiffEntry(is, length, tiffHeader.isLittleEndian);
}
|
[
"public",
"static",
"int",
"readOrientationFromTIFF",
"(",
"InputStream",
"is",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"// read tiff header",
"TiffHeader",
"tiffHeader",
"=",
"new",
"TiffHeader",
"(",
")",
";",
"length",
"=",
"readTiffHeader",
"(",
"is",
",",
"length",
",",
"tiffHeader",
")",
";",
"// move to the first IFD",
"// offset is relative to the beginning of the TIFF data",
"// and we already consumed the first 8 bytes of header",
"int",
"toSkip",
"=",
"tiffHeader",
".",
"firstIfdOffset",
"-",
"8",
";",
"if",
"(",
"length",
"==",
"0",
"||",
"toSkip",
">",
"length",
")",
"{",
"return",
"0",
";",
"}",
"is",
".",
"skip",
"(",
"toSkip",
")",
";",
"length",
"-=",
"toSkip",
";",
"// move to the entry with orientation tag",
"length",
"=",
"moveToTiffEntryWithTag",
"(",
"is",
",",
"length",
",",
"tiffHeader",
".",
"isLittleEndian",
",",
"TIFF_TAG_ORIENTATION",
")",
";",
"// read orientation",
"return",
"getOrientationFromTiffEntry",
"(",
"is",
",",
"length",
",",
"tiffHeader",
".",
"isLittleEndian",
")",
";",
"}"
] |
Reads orientation information from TIFF data.
@param is the input stream of TIFF data
@param length length of the TIFF data
@return orientation information (1/3/6/8 on success, 0 if not found)
|
[
"Reads",
"orientation",
"information",
"from",
"TIFF",
"data",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L54-L74
|
14,664
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
|
TiffUtil.readTiffHeader
|
private static int readTiffHeader(InputStream is, int length, TiffHeader tiffHeader)
throws IOException {
if (length <= 8) {
return 0;
}
// read the byte order
tiffHeader.byteOrder = StreamProcessor.readPackedInt(is, 4, false);
length -= 4;
if (tiffHeader.byteOrder != TIFF_BYTE_ORDER_LITTLE_END &&
tiffHeader.byteOrder != TIFF_BYTE_ORDER_BIG_END) {
FLog.e(TAG, "Invalid TIFF header");
return 0;
}
tiffHeader.isLittleEndian = (tiffHeader.byteOrder == TIFF_BYTE_ORDER_LITTLE_END);
// read the offset of the first IFD and check if it is reasonable
tiffHeader.firstIfdOffset = StreamProcessor.readPackedInt(is, 4, tiffHeader.isLittleEndian);
length -= 4;
if (tiffHeader.firstIfdOffset < 8 || tiffHeader.firstIfdOffset - 8 > length) {
FLog.e(TAG, "Invalid offset");
return 0;
}
return length;
}
|
java
|
private static int readTiffHeader(InputStream is, int length, TiffHeader tiffHeader)
throws IOException {
if (length <= 8) {
return 0;
}
// read the byte order
tiffHeader.byteOrder = StreamProcessor.readPackedInt(is, 4, false);
length -= 4;
if (tiffHeader.byteOrder != TIFF_BYTE_ORDER_LITTLE_END &&
tiffHeader.byteOrder != TIFF_BYTE_ORDER_BIG_END) {
FLog.e(TAG, "Invalid TIFF header");
return 0;
}
tiffHeader.isLittleEndian = (tiffHeader.byteOrder == TIFF_BYTE_ORDER_LITTLE_END);
// read the offset of the first IFD and check if it is reasonable
tiffHeader.firstIfdOffset = StreamProcessor.readPackedInt(is, 4, tiffHeader.isLittleEndian);
length -= 4;
if (tiffHeader.firstIfdOffset < 8 || tiffHeader.firstIfdOffset - 8 > length) {
FLog.e(TAG, "Invalid offset");
return 0;
}
return length;
}
|
[
"private",
"static",
"int",
"readTiffHeader",
"(",
"InputStream",
"is",
",",
"int",
"length",
",",
"TiffHeader",
"tiffHeader",
")",
"throws",
"IOException",
"{",
"if",
"(",
"length",
"<=",
"8",
")",
"{",
"return",
"0",
";",
"}",
"// read the byte order",
"tiffHeader",
".",
"byteOrder",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"4",
",",
"false",
")",
";",
"length",
"-=",
"4",
";",
"if",
"(",
"tiffHeader",
".",
"byteOrder",
"!=",
"TIFF_BYTE_ORDER_LITTLE_END",
"&&",
"tiffHeader",
".",
"byteOrder",
"!=",
"TIFF_BYTE_ORDER_BIG_END",
")",
"{",
"FLog",
".",
"e",
"(",
"TAG",
",",
"\"Invalid TIFF header\"",
")",
";",
"return",
"0",
";",
"}",
"tiffHeader",
".",
"isLittleEndian",
"=",
"(",
"tiffHeader",
".",
"byteOrder",
"==",
"TIFF_BYTE_ORDER_LITTLE_END",
")",
";",
"// read the offset of the first IFD and check if it is reasonable",
"tiffHeader",
".",
"firstIfdOffset",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"4",
",",
"tiffHeader",
".",
"isLittleEndian",
")",
";",
"length",
"-=",
"4",
";",
"if",
"(",
"tiffHeader",
".",
"firstIfdOffset",
"<",
"8",
"||",
"tiffHeader",
".",
"firstIfdOffset",
"-",
"8",
">",
"length",
")",
"{",
"FLog",
".",
"e",
"(",
"TAG",
",",
"\"Invalid offset\"",
")",
";",
"return",
"0",
";",
"}",
"return",
"length",
";",
"}"
] |
Reads the TIFF header to the provided structure.
@param is the input stream of TIFF data
@param length length of the TIFF data
@return remaining length of the data on success, 0 on failure
@throws IOException
|
[
"Reads",
"the",
"TIFF",
"header",
"to",
"the",
"provided",
"structure",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L92-L117
|
14,665
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
|
TiffUtil.moveToTiffEntryWithTag
|
private static int moveToTiffEntryWithTag(
InputStream is,
int length,
boolean isLittleEndian,
int tagToFind)
throws IOException {
if (length < 14) {
return 0;
}
// read the number of entries and go through all of them
// each IFD entry has length of 12 bytes and is composed of
// {TAG [2], TYPE [2], COUNT [4], VALUE/OFFSET [4]}
int numEntries = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
length -= 2;
while (numEntries-- > 0 && length >= 12) {
int tag = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
length -= 2;
if (tag == tagToFind) {
return length;
}
is.skip(10);
length -= 10;
}
return 0;
}
|
java
|
private static int moveToTiffEntryWithTag(
InputStream is,
int length,
boolean isLittleEndian,
int tagToFind)
throws IOException {
if (length < 14) {
return 0;
}
// read the number of entries and go through all of them
// each IFD entry has length of 12 bytes and is composed of
// {TAG [2], TYPE [2], COUNT [4], VALUE/OFFSET [4]}
int numEntries = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
length -= 2;
while (numEntries-- > 0 && length >= 12) {
int tag = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
length -= 2;
if (tag == tagToFind) {
return length;
}
is.skip(10);
length -= 10;
}
return 0;
}
|
[
"private",
"static",
"int",
"moveToTiffEntryWithTag",
"(",
"InputStream",
"is",
",",
"int",
"length",
",",
"boolean",
"isLittleEndian",
",",
"int",
"tagToFind",
")",
"throws",
"IOException",
"{",
"if",
"(",
"length",
"<",
"14",
")",
"{",
"return",
"0",
";",
"}",
"// read the number of entries and go through all of them",
"// each IFD entry has length of 12 bytes and is composed of",
"// {TAG [2], TYPE [2], COUNT [4], VALUE/OFFSET [4]}",
"int",
"numEntries",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"2",
",",
"isLittleEndian",
")",
";",
"length",
"-=",
"2",
";",
"while",
"(",
"numEntries",
"--",
">",
"0",
"&&",
"length",
">=",
"12",
")",
"{",
"int",
"tag",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"2",
",",
"isLittleEndian",
")",
";",
"length",
"-=",
"2",
";",
"if",
"(",
"tag",
"==",
"tagToFind",
")",
"{",
"return",
"length",
";",
"}",
"is",
".",
"skip",
"(",
"10",
")",
";",
"length",
"-=",
"10",
";",
"}",
"return",
"0",
";",
"}"
] |
Positions the given input stream to the entry that has a specified tag. Tag will be consumed.
@param is the input stream of TIFF data positioned to the beginning of an IFD.
@param length length of the available data in the given input stream.
@param isLittleEndian whether the TIFF data is stored in little or big endian format
@param tagToFind tag to find
@return remaining length of the data on success, 0 on failure
|
[
"Positions",
"the",
"given",
"input",
"stream",
"to",
"the",
"entry",
"that",
"has",
"a",
"specified",
"tag",
".",
"Tag",
"will",
"be",
"consumed",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L127-L151
|
14,666
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java
|
TiffUtil.getOrientationFromTiffEntry
|
private static int getOrientationFromTiffEntry(InputStream is, int length, boolean isLittleEndian)
throws IOException {
if (length < 10) {
return 0;
}
// orientation entry has type = short
int type = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
if (type != TIFF_TYPE_SHORT) {
return 0;
}
// orientation entry has count = 1
int count = StreamProcessor.readPackedInt(is, 4, isLittleEndian);
if (count != 1) {
return 0;
}
int value = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
int padding = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
return value;
}
|
java
|
private static int getOrientationFromTiffEntry(InputStream is, int length, boolean isLittleEndian)
throws IOException {
if (length < 10) {
return 0;
}
// orientation entry has type = short
int type = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
if (type != TIFF_TYPE_SHORT) {
return 0;
}
// orientation entry has count = 1
int count = StreamProcessor.readPackedInt(is, 4, isLittleEndian);
if (count != 1) {
return 0;
}
int value = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
int padding = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
return value;
}
|
[
"private",
"static",
"int",
"getOrientationFromTiffEntry",
"(",
"InputStream",
"is",
",",
"int",
"length",
",",
"boolean",
"isLittleEndian",
")",
"throws",
"IOException",
"{",
"if",
"(",
"length",
"<",
"10",
")",
"{",
"return",
"0",
";",
"}",
"// orientation entry has type = short",
"int",
"type",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"2",
",",
"isLittleEndian",
")",
";",
"if",
"(",
"type",
"!=",
"TIFF_TYPE_SHORT",
")",
"{",
"return",
"0",
";",
"}",
"// orientation entry has count = 1",
"int",
"count",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"4",
",",
"isLittleEndian",
")",
";",
"if",
"(",
"count",
"!=",
"1",
")",
"{",
"return",
"0",
";",
"}",
"int",
"value",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"2",
",",
"isLittleEndian",
")",
";",
"int",
"padding",
"=",
"StreamProcessor",
".",
"readPackedInt",
"(",
"is",
",",
"2",
",",
"isLittleEndian",
")",
";",
"return",
"value",
";",
"}"
] |
Reads the orientation information from the TIFF entry.
It is assumed that the entry has a TIFF orientation tag and that tag has already been consumed.
@param is the input stream positioned at the TIFF entry with tag already being consumed
@param isLittleEndian whether the TIFF data is stored in little or big endian format
@return Orientation value in TIFF IFD entry.
|
[
"Reads",
"the",
"orientation",
"information",
"from",
"the",
"TIFF",
"entry",
".",
"It",
"is",
"assumed",
"that",
"the",
"entry",
"has",
"a",
"TIFF",
"orientation",
"tag",
"and",
"that",
"tag",
"has",
"already",
"been",
"consumed",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L160-L178
|
14,667
|
facebook/fresco
|
samples/animation2/src/main/java/com/facebook/samples/animation2/color/ExampleColorBackend.java
|
ExampleColorBackend.createSampleColorAnimationBackend
|
public static AnimationBackend createSampleColorAnimationBackend(Resources resources) {
// Get the animation duration in ms for each color frame
int frameDurationMs = resources.getInteger(android.R.integer.config_mediumAnimTime);
// Create and return the backend
return new ExampleColorBackend(SampleData.COLORS, frameDurationMs);
}
|
java
|
public static AnimationBackend createSampleColorAnimationBackend(Resources resources) {
// Get the animation duration in ms for each color frame
int frameDurationMs = resources.getInteger(android.R.integer.config_mediumAnimTime);
// Create and return the backend
return new ExampleColorBackend(SampleData.COLORS, frameDurationMs);
}
|
[
"public",
"static",
"AnimationBackend",
"createSampleColorAnimationBackend",
"(",
"Resources",
"resources",
")",
"{",
"// Get the animation duration in ms for each color frame",
"int",
"frameDurationMs",
"=",
"resources",
".",
"getInteger",
"(",
"android",
".",
"R",
".",
"integer",
".",
"config_mediumAnimTime",
")",
";",
"// Create and return the backend",
"return",
"new",
"ExampleColorBackend",
"(",
"SampleData",
".",
"COLORS",
",",
"frameDurationMs",
")",
";",
"}"
] |
Creates a simple animation backend that cycles through a list of colors.
@return the backend to use
|
[
"Creates",
"a",
"simple",
"animation",
"backend",
"that",
"cycles",
"through",
"a",
"list",
"of",
"colors",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/animation2/src/main/java/com/facebook/samples/animation2/color/ExampleColorBackend.java#L35-L40
|
14,668
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/impl/AnimatedFrameCache.java
|
AnimatedFrameCache.cache
|
@Nullable
public CloseableReference<CloseableImage> cache(
int frameIndex,
CloseableReference<CloseableImage> imageRef) {
return mBackingCache.cache(keyFor(frameIndex), imageRef, mEntryStateObserver);
}
|
java
|
@Nullable
public CloseableReference<CloseableImage> cache(
int frameIndex,
CloseableReference<CloseableImage> imageRef) {
return mBackingCache.cache(keyFor(frameIndex), imageRef, mEntryStateObserver);
}
|
[
"@",
"Nullable",
"public",
"CloseableReference",
"<",
"CloseableImage",
">",
"cache",
"(",
"int",
"frameIndex",
",",
"CloseableReference",
"<",
"CloseableImage",
">",
"imageRef",
")",
"{",
"return",
"mBackingCache",
".",
"cache",
"(",
"keyFor",
"(",
"frameIndex",
")",
",",
"imageRef",
",",
"mEntryStateObserver",
")",
";",
"}"
] |
Caches the image for the given frame index.
<p> Important: the client should use the returned reference instead of the original one.
It is the caller's responsibility to close the returned reference once not needed anymore.
@return the new reference to be used, null if the value cannot be cached
|
[
"Caches",
"the",
"image",
"for",
"the",
"given",
"frame",
"index",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/impl/AnimatedFrameCache.java#L113-L118
|
14,669
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/impl/AnimatedFrameCache.java
|
AnimatedFrameCache.getForReuse
|
@Nullable
public CloseableReference<CloseableImage> getForReuse() {
while (true) {
CacheKey key = popFirstFreeItemKey();
if (key == null) {
return null;
}
CloseableReference<CloseableImage> imageRef = mBackingCache.reuse(key);
if (imageRef != null) {
return imageRef;
}
}
}
|
java
|
@Nullable
public CloseableReference<CloseableImage> getForReuse() {
while (true) {
CacheKey key = popFirstFreeItemKey();
if (key == null) {
return null;
}
CloseableReference<CloseableImage> imageRef = mBackingCache.reuse(key);
if (imageRef != null) {
return imageRef;
}
}
}
|
[
"@",
"Nullable",
"public",
"CloseableReference",
"<",
"CloseableImage",
">",
"getForReuse",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"CacheKey",
"key",
"=",
"popFirstFreeItemKey",
"(",
")",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"CloseableReference",
"<",
"CloseableImage",
">",
"imageRef",
"=",
"mBackingCache",
".",
"reuse",
"(",
"key",
")",
";",
"if",
"(",
"imageRef",
"!=",
"null",
")",
"{",
"return",
"imageRef",
";",
"}",
"}",
"}"
] |
Gets the image to be reused, or null if there is no such image.
<p> The returned image is the least recently used image that has no more clients referencing
it, and it has not yet been evicted from the cache.
<p> The client can freely modify the bitmap of the returned image and can cache it again
without any restrictions.
|
[
"Gets",
"the",
"image",
"to",
"be",
"reused",
"or",
"null",
"if",
"there",
"is",
"no",
"such",
"image",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/impl/AnimatedFrameCache.java#L146-L158
|
14,670
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/transcoder/JpegTranscoderUtils.java
|
JpegTranscoderUtils.getTransformationMatrix
|
@Nullable
public static Matrix getTransformationMatrix(
final EncodedImage encodedImage, final RotationOptions rotationOptions) {
Matrix transformationMatrix = null;
if (JpegTranscoderUtils.INVERTED_EXIF_ORIENTATIONS.contains(
encodedImage.getExifOrientation())) {
// Use exif orientation to rotate since we can't use the rotation angle for inverted exif
// orientations
final int exifOrientation =
getForceRotatedInvertedExifOrientation(rotationOptions, encodedImage);
transformationMatrix = getTransformationMatrixFromInvertedExif(exifOrientation);
} else {
// Use actual rotation angle in degrees to rotate
final int rotationAngle = getRotationAngle(rotationOptions, encodedImage);
if (rotationAngle != 0) {
transformationMatrix = new Matrix();
transformationMatrix.setRotate(rotationAngle);
}
}
return transformationMatrix;
}
|
java
|
@Nullable
public static Matrix getTransformationMatrix(
final EncodedImage encodedImage, final RotationOptions rotationOptions) {
Matrix transformationMatrix = null;
if (JpegTranscoderUtils.INVERTED_EXIF_ORIENTATIONS.contains(
encodedImage.getExifOrientation())) {
// Use exif orientation to rotate since we can't use the rotation angle for inverted exif
// orientations
final int exifOrientation =
getForceRotatedInvertedExifOrientation(rotationOptions, encodedImage);
transformationMatrix = getTransformationMatrixFromInvertedExif(exifOrientation);
} else {
// Use actual rotation angle in degrees to rotate
final int rotationAngle = getRotationAngle(rotationOptions, encodedImage);
if (rotationAngle != 0) {
transformationMatrix = new Matrix();
transformationMatrix.setRotate(rotationAngle);
}
}
return transformationMatrix;
}
|
[
"@",
"Nullable",
"public",
"static",
"Matrix",
"getTransformationMatrix",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"final",
"RotationOptions",
"rotationOptions",
")",
"{",
"Matrix",
"transformationMatrix",
"=",
"null",
";",
"if",
"(",
"JpegTranscoderUtils",
".",
"INVERTED_EXIF_ORIENTATIONS",
".",
"contains",
"(",
"encodedImage",
".",
"getExifOrientation",
"(",
")",
")",
")",
"{",
"// Use exif orientation to rotate since we can't use the rotation angle for inverted exif",
"// orientations",
"final",
"int",
"exifOrientation",
"=",
"getForceRotatedInvertedExifOrientation",
"(",
"rotationOptions",
",",
"encodedImage",
")",
";",
"transformationMatrix",
"=",
"getTransformationMatrixFromInvertedExif",
"(",
"exifOrientation",
")",
";",
"}",
"else",
"{",
"// Use actual rotation angle in degrees to rotate",
"final",
"int",
"rotationAngle",
"=",
"getRotationAngle",
"(",
"rotationOptions",
",",
"encodedImage",
")",
";",
"if",
"(",
"rotationAngle",
"!=",
"0",
")",
"{",
"transformationMatrix",
"=",
"new",
"Matrix",
"(",
")",
";",
"transformationMatrix",
".",
"setRotate",
"(",
"rotationAngle",
")",
";",
"}",
"}",
"return",
"transformationMatrix",
";",
"}"
] |
Compute the transformation matrix needed to rotate the image. If no transformation is needed,
it returns null.
@param encodedImage The {@link EncodedImage} used when computing the matrix.
@param rotationOptions The {@link RotationOptions} used when computing the matrix
@return The transformation matrix, or null if no transformation is required.
|
[
"Compute",
"the",
"transformation",
"matrix",
"needed",
"to",
"rotate",
"the",
"image",
".",
"If",
"no",
"transformation",
"is",
"needed",
"it",
"returns",
"null",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/transcoder/JpegTranscoderUtils.java#L179-L200
|
14,671
|
facebook/fresco
|
animated-base/src/main/java/com/facebook/imagepipeline/animated/factory/AnimatedImageFactoryImpl.java
|
AnimatedImageFactoryImpl.decodeGif
|
public CloseableImage decodeGif(
final EncodedImage encodedImage,
final ImageDecodeOptions options,
final Bitmap.Config bitmapConfig) {
if (sGifAnimatedImageDecoder == null) {
throw new UnsupportedOperationException("To encode animated gif please add the dependency " +
"to the animated-gif module");
}
final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef();
Preconditions.checkNotNull(bytesRef);
try {
final PooledByteBuffer input = bytesRef.get();
AnimatedImage gifImage;
if (input.getByteBuffer() != null) {
gifImage = sGifAnimatedImageDecoder.decode(input.getByteBuffer());
} else {
gifImage = sGifAnimatedImageDecoder.decode(input.getNativePtr(), input.size());
}
return getCloseableImage(options, gifImage, bitmapConfig);
} finally {
CloseableReference.closeSafely(bytesRef);
}
}
|
java
|
public CloseableImage decodeGif(
final EncodedImage encodedImage,
final ImageDecodeOptions options,
final Bitmap.Config bitmapConfig) {
if (sGifAnimatedImageDecoder == null) {
throw new UnsupportedOperationException("To encode animated gif please add the dependency " +
"to the animated-gif module");
}
final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef();
Preconditions.checkNotNull(bytesRef);
try {
final PooledByteBuffer input = bytesRef.get();
AnimatedImage gifImage;
if (input.getByteBuffer() != null) {
gifImage = sGifAnimatedImageDecoder.decode(input.getByteBuffer());
} else {
gifImage = sGifAnimatedImageDecoder.decode(input.getNativePtr(), input.size());
}
return getCloseableImage(options, gifImage, bitmapConfig);
} finally {
CloseableReference.closeSafely(bytesRef);
}
}
|
[
"public",
"CloseableImage",
"decodeGif",
"(",
"final",
"EncodedImage",
"encodedImage",
",",
"final",
"ImageDecodeOptions",
"options",
",",
"final",
"Bitmap",
".",
"Config",
"bitmapConfig",
")",
"{",
"if",
"(",
"sGifAnimatedImageDecoder",
"==",
"null",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"To encode animated gif please add the dependency \"",
"+",
"\"to the animated-gif module\"",
")",
";",
"}",
"final",
"CloseableReference",
"<",
"PooledByteBuffer",
">",
"bytesRef",
"=",
"encodedImage",
".",
"getByteBufferRef",
"(",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"bytesRef",
")",
";",
"try",
"{",
"final",
"PooledByteBuffer",
"input",
"=",
"bytesRef",
".",
"get",
"(",
")",
";",
"AnimatedImage",
"gifImage",
";",
"if",
"(",
"input",
".",
"getByteBuffer",
"(",
")",
"!=",
"null",
")",
"{",
"gifImage",
"=",
"sGifAnimatedImageDecoder",
".",
"decode",
"(",
"input",
".",
"getByteBuffer",
"(",
")",
")",
";",
"}",
"else",
"{",
"gifImage",
"=",
"sGifAnimatedImageDecoder",
".",
"decode",
"(",
"input",
".",
"getNativePtr",
"(",
")",
",",
"input",
".",
"size",
"(",
")",
")",
";",
"}",
"return",
"getCloseableImage",
"(",
"options",
",",
"gifImage",
",",
"bitmapConfig",
")",
";",
"}",
"finally",
"{",
"CloseableReference",
".",
"closeSafely",
"(",
"bytesRef",
")",
";",
"}",
"}"
] |
Decodes a GIF into a CloseableImage.
@param encodedImage encoded image (native byte array holding the encoded bytes and meta data)
@param options the options for the decode
@param bitmapConfig the Bitmap.Config used to generate the output bitmaps
@return a {@link CloseableImage} for the GIF image
|
[
"Decodes",
"a",
"GIF",
"into",
"a",
"CloseableImage",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/factory/AnimatedImageFactoryImpl.java#L72-L94
|
14,672
|
facebook/fresco
|
fbcore/src/main/java/com/facebook/common/memory/PooledByteArrayBufferedInputStream.java
|
PooledByteArrayBufferedInputStream.ensureDataInBuffer
|
private boolean ensureDataInBuffer() throws IOException {
if (mBufferOffset < mBufferedSize) {
return true;
}
final int readData = mInputStream.read(mByteArray);
if (readData <= 0) {
return false;
}
mBufferedSize = readData;
mBufferOffset = 0;
return true;
}
|
java
|
private boolean ensureDataInBuffer() throws IOException {
if (mBufferOffset < mBufferedSize) {
return true;
}
final int readData = mInputStream.read(mByteArray);
if (readData <= 0) {
return false;
}
mBufferedSize = readData;
mBufferOffset = 0;
return true;
}
|
[
"private",
"boolean",
"ensureDataInBuffer",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"mBufferOffset",
"<",
"mBufferedSize",
")",
"{",
"return",
"true",
";",
"}",
"final",
"int",
"readData",
"=",
"mInputStream",
".",
"read",
"(",
"mByteArray",
")",
";",
"if",
"(",
"readData",
"<=",
"0",
")",
"{",
"return",
"false",
";",
"}",
"mBufferedSize",
"=",
"readData",
";",
"mBufferOffset",
"=",
"0",
";",
"return",
"true",
";",
"}"
] |
Checks if there is some data left in the buffer. If not but buffered stream still has some
data to be read, then more data is buffered.
@return false if and only if there is no more data and underlying input stream has no more data
to be read
@throws IOException
|
[
"Checks",
"if",
"there",
"is",
"some",
"data",
"left",
"in",
"the",
"buffer",
".",
"If",
"not",
"but",
"buffered",
"stream",
"still",
"has",
"some",
"data",
"to",
"be",
"read",
"then",
"more",
"data",
"is",
"buffered",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/memory/PooledByteArrayBufferedInputStream.java#L120-L133
|
14,673
|
facebook/fresco
|
drawee-span/src/main/java/com/facebook/drawee/span/SimpleDraweeSpanTextView.java
|
SimpleDraweeSpanTextView.setDraweeSpanStringBuilder
|
public void setDraweeSpanStringBuilder(DraweeSpanStringBuilder draweeSpanStringBuilder) {
// setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder
// if necessary
setText(draweeSpanStringBuilder, BufferType.SPANNABLE);
mDraweeStringBuilder = draweeSpanStringBuilder;
if (mDraweeStringBuilder != null && mIsAttached) {
mDraweeStringBuilder.onAttachToView(this);
}
}
|
java
|
public void setDraweeSpanStringBuilder(DraweeSpanStringBuilder draweeSpanStringBuilder) {
// setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder
// if necessary
setText(draweeSpanStringBuilder, BufferType.SPANNABLE);
mDraweeStringBuilder = draweeSpanStringBuilder;
if (mDraweeStringBuilder != null && mIsAttached) {
mDraweeStringBuilder.onAttachToView(this);
}
}
|
[
"public",
"void",
"setDraweeSpanStringBuilder",
"(",
"DraweeSpanStringBuilder",
"draweeSpanStringBuilder",
")",
"{",
"// setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder",
"// if necessary",
"setText",
"(",
"draweeSpanStringBuilder",
",",
"BufferType",
".",
"SPANNABLE",
")",
";",
"mDraweeStringBuilder",
"=",
"draweeSpanStringBuilder",
";",
"if",
"(",
"mDraweeStringBuilder",
"!=",
"null",
"&&",
"mIsAttached",
")",
"{",
"mDraweeStringBuilder",
".",
"onAttachToView",
"(",
"this",
")",
";",
"}",
"}"
] |
Bind the given string builder to this view.
@param draweeSpanStringBuilder the builder to attach to
|
[
"Bind",
"the",
"given",
"string",
"builder",
"to",
"this",
"view",
"."
] |
0b85879d51c5036d5e46e627a6651afefc0b971a
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee-span/src/main/java/com/facebook/drawee/span/SimpleDraweeSpanTextView.java#L85-L93
|
14,674
|
google/auto
|
factory/src/main/java/com/google/auto/factory/processor/Elements2.java
|
Elements2.getExecutableElementAsMemberOf
|
static ExecutableType getExecutableElementAsMemberOf(
Types types, ExecutableElement executableElement, TypeElement subTypeElement) {
checkNotNull(types);
checkNotNull(executableElement);
checkNotNull(subTypeElement);
TypeMirror subTypeMirror = subTypeElement.asType();
if (!subTypeMirror.getKind().equals(TypeKind.DECLARED)) {
throw new IllegalStateException(
"Expected subTypeElement.asType() to return a class/interface type.");
}
TypeMirror subExecutableTypeMirror = types.asMemberOf(
(DeclaredType) subTypeMirror, executableElement);
if (!subExecutableTypeMirror.getKind().equals(TypeKind.EXECUTABLE)) {
throw new IllegalStateException("Expected subExecutableTypeMirror to be an executable type.");
}
return (ExecutableType) subExecutableTypeMirror;
}
|
java
|
static ExecutableType getExecutableElementAsMemberOf(
Types types, ExecutableElement executableElement, TypeElement subTypeElement) {
checkNotNull(types);
checkNotNull(executableElement);
checkNotNull(subTypeElement);
TypeMirror subTypeMirror = subTypeElement.asType();
if (!subTypeMirror.getKind().equals(TypeKind.DECLARED)) {
throw new IllegalStateException(
"Expected subTypeElement.asType() to return a class/interface type.");
}
TypeMirror subExecutableTypeMirror = types.asMemberOf(
(DeclaredType) subTypeMirror, executableElement);
if (!subExecutableTypeMirror.getKind().equals(TypeKind.EXECUTABLE)) {
throw new IllegalStateException("Expected subExecutableTypeMirror to be an executable type.");
}
return (ExecutableType) subExecutableTypeMirror;
}
|
[
"static",
"ExecutableType",
"getExecutableElementAsMemberOf",
"(",
"Types",
"types",
",",
"ExecutableElement",
"executableElement",
",",
"TypeElement",
"subTypeElement",
")",
"{",
"checkNotNull",
"(",
"types",
")",
";",
"checkNotNull",
"(",
"executableElement",
")",
";",
"checkNotNull",
"(",
"subTypeElement",
")",
";",
"TypeMirror",
"subTypeMirror",
"=",
"subTypeElement",
".",
"asType",
"(",
")",
";",
"if",
"(",
"!",
"subTypeMirror",
".",
"getKind",
"(",
")",
".",
"equals",
"(",
"TypeKind",
".",
"DECLARED",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Expected subTypeElement.asType() to return a class/interface type.\"",
")",
";",
"}",
"TypeMirror",
"subExecutableTypeMirror",
"=",
"types",
".",
"asMemberOf",
"(",
"(",
"DeclaredType",
")",
"subTypeMirror",
",",
"executableElement",
")",
";",
"if",
"(",
"!",
"subExecutableTypeMirror",
".",
"getKind",
"(",
")",
".",
"equals",
"(",
"TypeKind",
".",
"EXECUTABLE",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Expected subExecutableTypeMirror to be an executable type.\"",
")",
";",
"}",
"return",
"(",
"ExecutableType",
")",
"subExecutableTypeMirror",
";",
"}"
] |
Given an executable element in a supertype, returns its ExecutableType when it is viewed as a
member of a subtype.
|
[
"Given",
"an",
"executable",
"element",
"in",
"a",
"supertype",
"returns",
"its",
"ExecutableType",
"when",
"it",
"is",
"viewed",
"as",
"a",
"member",
"of",
"a",
"subtype",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/factory/src/main/java/com/google/auto/factory/processor/Elements2.java#L65-L81
|
14,675
|
google/auto
|
common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java
|
BasicAnnotationProcessor.deferredElements
|
private ImmutableMap<String, Optional<? extends Element>> deferredElements() {
ImmutableMap.Builder<String, Optional<? extends Element>> deferredElements =
ImmutableMap.builder();
for (ElementName elementName : deferredElementNames) {
deferredElements.put(elementName.name(), elementName.getElement(elements));
}
return deferredElements.build();
}
|
java
|
private ImmutableMap<String, Optional<? extends Element>> deferredElements() {
ImmutableMap.Builder<String, Optional<? extends Element>> deferredElements =
ImmutableMap.builder();
for (ElementName elementName : deferredElementNames) {
deferredElements.put(elementName.name(), elementName.getElement(elements));
}
return deferredElements.build();
}
|
[
"private",
"ImmutableMap",
"<",
"String",
",",
"Optional",
"<",
"?",
"extends",
"Element",
">",
">",
"deferredElements",
"(",
")",
"{",
"ImmutableMap",
".",
"Builder",
"<",
"String",
",",
"Optional",
"<",
"?",
"extends",
"Element",
">",
">",
"deferredElements",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"for",
"(",
"ElementName",
"elementName",
":",
"deferredElementNames",
")",
"{",
"deferredElements",
".",
"put",
"(",
"elementName",
".",
"name",
"(",
")",
",",
"elementName",
".",
"getElement",
"(",
"elements",
")",
")",
";",
"}",
"return",
"deferredElements",
".",
"build",
"(",
")",
";",
"}"
] |
Returns the previously deferred elements.
|
[
"Returns",
"the",
"previously",
"deferred",
"elements",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java#L191-L198
|
14,676
|
google/auto
|
common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java
|
BasicAnnotationProcessor.validElements
|
private ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements(
ImmutableMap<String, Optional<? extends Element>> deferredElements,
RoundEnvironment roundEnv) {
ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element>
deferredElementsByAnnotationBuilder = ImmutableSetMultimap.builder();
for (Entry<String, Optional<? extends Element>> deferredTypeElementEntry :
deferredElements.entrySet()) {
Optional<? extends Element> deferredElement = deferredTypeElementEntry.getValue();
if (deferredElement.isPresent()) {
findAnnotatedElements(
deferredElement.get(),
getSupportedAnnotationClasses(),
deferredElementsByAnnotationBuilder);
} else {
deferredElementNames.add(ElementName.forTypeName(deferredTypeElementEntry.getKey()));
}
}
ImmutableSetMultimap<Class<? extends Annotation>, Element> deferredElementsByAnnotation =
deferredElementsByAnnotationBuilder.build();
ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> validElements =
ImmutableSetMultimap.builder();
Set<ElementName> validElementNames = new LinkedHashSet<ElementName>();
// Look at the elements we've found and the new elements from this round and validate them.
for (Class<? extends Annotation> annotationClass : getSupportedAnnotationClasses()) {
// This should just call roundEnv.getElementsAnnotatedWith(Class) directly, but there is a bug
// in some versions of eclipse that cause that method to crash.
TypeElement annotationType = elements.getTypeElement(annotationClass.getCanonicalName());
Set<? extends Element> elementsAnnotatedWith =
(annotationType == null)
? ImmutableSet.<Element>of()
: roundEnv.getElementsAnnotatedWith(annotationType);
for (Element annotatedElement :
Sets.union(elementsAnnotatedWith, deferredElementsByAnnotation.get(annotationClass))) {
if (annotatedElement.getKind().equals(PACKAGE)) {
PackageElement annotatedPackageElement = (PackageElement) annotatedElement;
ElementName annotatedPackageName =
ElementName.forPackageName(annotatedPackageElement.getQualifiedName().toString());
boolean validPackage =
validElementNames.contains(annotatedPackageName)
|| (!deferredElementNames.contains(annotatedPackageName)
&& validateElement(annotatedPackageElement));
if (validPackage) {
validElements.put(annotationClass, annotatedPackageElement);
validElementNames.add(annotatedPackageName);
} else {
deferredElementNames.add(annotatedPackageName);
}
} else {
TypeElement enclosingType = getEnclosingType(annotatedElement);
ElementName enclosingTypeName =
ElementName.forTypeName(enclosingType.getQualifiedName().toString());
boolean validEnclosingType =
validElementNames.contains(enclosingTypeName)
|| (!deferredElementNames.contains(enclosingTypeName)
&& validateElement(enclosingType));
if (validEnclosingType) {
validElements.put(annotationClass, annotatedElement);
validElementNames.add(enclosingTypeName);
} else {
deferredElementNames.add(enclosingTypeName);
}
}
}
}
return validElements.build();
}
|
java
|
private ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements(
ImmutableMap<String, Optional<? extends Element>> deferredElements,
RoundEnvironment roundEnv) {
ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element>
deferredElementsByAnnotationBuilder = ImmutableSetMultimap.builder();
for (Entry<String, Optional<? extends Element>> deferredTypeElementEntry :
deferredElements.entrySet()) {
Optional<? extends Element> deferredElement = deferredTypeElementEntry.getValue();
if (deferredElement.isPresent()) {
findAnnotatedElements(
deferredElement.get(),
getSupportedAnnotationClasses(),
deferredElementsByAnnotationBuilder);
} else {
deferredElementNames.add(ElementName.forTypeName(deferredTypeElementEntry.getKey()));
}
}
ImmutableSetMultimap<Class<? extends Annotation>, Element> deferredElementsByAnnotation =
deferredElementsByAnnotationBuilder.build();
ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> validElements =
ImmutableSetMultimap.builder();
Set<ElementName> validElementNames = new LinkedHashSet<ElementName>();
// Look at the elements we've found and the new elements from this round and validate them.
for (Class<? extends Annotation> annotationClass : getSupportedAnnotationClasses()) {
// This should just call roundEnv.getElementsAnnotatedWith(Class) directly, but there is a bug
// in some versions of eclipse that cause that method to crash.
TypeElement annotationType = elements.getTypeElement(annotationClass.getCanonicalName());
Set<? extends Element> elementsAnnotatedWith =
(annotationType == null)
? ImmutableSet.<Element>of()
: roundEnv.getElementsAnnotatedWith(annotationType);
for (Element annotatedElement :
Sets.union(elementsAnnotatedWith, deferredElementsByAnnotation.get(annotationClass))) {
if (annotatedElement.getKind().equals(PACKAGE)) {
PackageElement annotatedPackageElement = (PackageElement) annotatedElement;
ElementName annotatedPackageName =
ElementName.forPackageName(annotatedPackageElement.getQualifiedName().toString());
boolean validPackage =
validElementNames.contains(annotatedPackageName)
|| (!deferredElementNames.contains(annotatedPackageName)
&& validateElement(annotatedPackageElement));
if (validPackage) {
validElements.put(annotationClass, annotatedPackageElement);
validElementNames.add(annotatedPackageName);
} else {
deferredElementNames.add(annotatedPackageName);
}
} else {
TypeElement enclosingType = getEnclosingType(annotatedElement);
ElementName enclosingTypeName =
ElementName.forTypeName(enclosingType.getQualifiedName().toString());
boolean validEnclosingType =
validElementNames.contains(enclosingTypeName)
|| (!deferredElementNames.contains(enclosingTypeName)
&& validateElement(enclosingType));
if (validEnclosingType) {
validElements.put(annotationClass, annotatedElement);
validElementNames.add(enclosingTypeName);
} else {
deferredElementNames.add(enclosingTypeName);
}
}
}
}
return validElements.build();
}
|
[
"private",
"ImmutableSetMultimap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"validElements",
"(",
"ImmutableMap",
"<",
"String",
",",
"Optional",
"<",
"?",
"extends",
"Element",
">",
">",
"deferredElements",
",",
"RoundEnvironment",
"roundEnv",
")",
"{",
"ImmutableSetMultimap",
".",
"Builder",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"deferredElementsByAnnotationBuilder",
"=",
"ImmutableSetMultimap",
".",
"builder",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"Optional",
"<",
"?",
"extends",
"Element",
">",
">",
"deferredTypeElementEntry",
":",
"deferredElements",
".",
"entrySet",
"(",
")",
")",
"{",
"Optional",
"<",
"?",
"extends",
"Element",
">",
"deferredElement",
"=",
"deferredTypeElementEntry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"deferredElement",
".",
"isPresent",
"(",
")",
")",
"{",
"findAnnotatedElements",
"(",
"deferredElement",
".",
"get",
"(",
")",
",",
"getSupportedAnnotationClasses",
"(",
")",
",",
"deferredElementsByAnnotationBuilder",
")",
";",
"}",
"else",
"{",
"deferredElementNames",
".",
"add",
"(",
"ElementName",
".",
"forTypeName",
"(",
"deferredTypeElementEntry",
".",
"getKey",
"(",
")",
")",
")",
";",
"}",
"}",
"ImmutableSetMultimap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"deferredElementsByAnnotation",
"=",
"deferredElementsByAnnotationBuilder",
".",
"build",
"(",
")",
";",
"ImmutableSetMultimap",
".",
"Builder",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"validElements",
"=",
"ImmutableSetMultimap",
".",
"builder",
"(",
")",
";",
"Set",
"<",
"ElementName",
">",
"validElementNames",
"=",
"new",
"LinkedHashSet",
"<",
"ElementName",
">",
"(",
")",
";",
"// Look at the elements we've found and the new elements from this round and validate them.",
"for",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
":",
"getSupportedAnnotationClasses",
"(",
")",
")",
"{",
"// This should just call roundEnv.getElementsAnnotatedWith(Class) directly, but there is a bug",
"// in some versions of eclipse that cause that method to crash.",
"TypeElement",
"annotationType",
"=",
"elements",
".",
"getTypeElement",
"(",
"annotationClass",
".",
"getCanonicalName",
"(",
")",
")",
";",
"Set",
"<",
"?",
"extends",
"Element",
">",
"elementsAnnotatedWith",
"=",
"(",
"annotationType",
"==",
"null",
")",
"?",
"ImmutableSet",
".",
"<",
"Element",
">",
"of",
"(",
")",
":",
"roundEnv",
".",
"getElementsAnnotatedWith",
"(",
"annotationType",
")",
";",
"for",
"(",
"Element",
"annotatedElement",
":",
"Sets",
".",
"union",
"(",
"elementsAnnotatedWith",
",",
"deferredElementsByAnnotation",
".",
"get",
"(",
"annotationClass",
")",
")",
")",
"{",
"if",
"(",
"annotatedElement",
".",
"getKind",
"(",
")",
".",
"equals",
"(",
"PACKAGE",
")",
")",
"{",
"PackageElement",
"annotatedPackageElement",
"=",
"(",
"PackageElement",
")",
"annotatedElement",
";",
"ElementName",
"annotatedPackageName",
"=",
"ElementName",
".",
"forPackageName",
"(",
"annotatedPackageElement",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"boolean",
"validPackage",
"=",
"validElementNames",
".",
"contains",
"(",
"annotatedPackageName",
")",
"||",
"(",
"!",
"deferredElementNames",
".",
"contains",
"(",
"annotatedPackageName",
")",
"&&",
"validateElement",
"(",
"annotatedPackageElement",
")",
")",
";",
"if",
"(",
"validPackage",
")",
"{",
"validElements",
".",
"put",
"(",
"annotationClass",
",",
"annotatedPackageElement",
")",
";",
"validElementNames",
".",
"add",
"(",
"annotatedPackageName",
")",
";",
"}",
"else",
"{",
"deferredElementNames",
".",
"add",
"(",
"annotatedPackageName",
")",
";",
"}",
"}",
"else",
"{",
"TypeElement",
"enclosingType",
"=",
"getEnclosingType",
"(",
"annotatedElement",
")",
";",
"ElementName",
"enclosingTypeName",
"=",
"ElementName",
".",
"forTypeName",
"(",
"enclosingType",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"boolean",
"validEnclosingType",
"=",
"validElementNames",
".",
"contains",
"(",
"enclosingTypeName",
")",
"||",
"(",
"!",
"deferredElementNames",
".",
"contains",
"(",
"enclosingTypeName",
")",
"&&",
"validateElement",
"(",
"enclosingType",
")",
")",
";",
"if",
"(",
"validEnclosingType",
")",
"{",
"validElements",
".",
"put",
"(",
"annotationClass",
",",
"annotatedElement",
")",
";",
"validElementNames",
".",
"add",
"(",
"enclosingTypeName",
")",
";",
"}",
"else",
"{",
"deferredElementNames",
".",
"add",
"(",
"enclosingTypeName",
")",
";",
"}",
"}",
"}",
"}",
"return",
"validElements",
".",
"build",
"(",
")",
";",
"}"
] |
Returns the valid annotated elements contained in all of the deferred elements. If none are
found for a deferred element, defers it again.
|
[
"Returns",
"the",
"valid",
"annotated",
"elements",
"contained",
"in",
"all",
"of",
"the",
"deferred",
"elements",
".",
"If",
"none",
"are",
"found",
"for",
"a",
"deferred",
"element",
"defers",
"it",
"again",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java#L247-L317
|
14,677
|
google/auto
|
common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java
|
BasicAnnotationProcessor.process
|
private void process(ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements) {
for (ProcessingStep step : steps) {
ImmutableSetMultimap<Class<? extends Annotation>, Element> stepElements =
new ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element>()
.putAll(indexByAnnotation(elementsDeferredBySteps.get(step), step.annotations()))
.putAll(filterKeys(validElements, Predicates.<Object>in(step.annotations())))
.build();
if (stepElements.isEmpty()) {
elementsDeferredBySteps.removeAll(step);
} else {
Set<? extends Element> rejectedElements = step.process(stepElements);
elementsDeferredBySteps.replaceValues(
step,
transform(
rejectedElements,
new Function<Element, ElementName>() {
@Override
public ElementName apply(Element element) {
return ElementName.forAnnotatedElement(element);
}
}));
}
}
}
|
java
|
private void process(ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements) {
for (ProcessingStep step : steps) {
ImmutableSetMultimap<Class<? extends Annotation>, Element> stepElements =
new ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element>()
.putAll(indexByAnnotation(elementsDeferredBySteps.get(step), step.annotations()))
.putAll(filterKeys(validElements, Predicates.<Object>in(step.annotations())))
.build();
if (stepElements.isEmpty()) {
elementsDeferredBySteps.removeAll(step);
} else {
Set<? extends Element> rejectedElements = step.process(stepElements);
elementsDeferredBySteps.replaceValues(
step,
transform(
rejectedElements,
new Function<Element, ElementName>() {
@Override
public ElementName apply(Element element) {
return ElementName.forAnnotatedElement(element);
}
}));
}
}
}
|
[
"private",
"void",
"process",
"(",
"ImmutableSetMultimap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"validElements",
")",
"{",
"for",
"(",
"ProcessingStep",
"step",
":",
"steps",
")",
"{",
"ImmutableSetMultimap",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"stepElements",
"=",
"new",
"ImmutableSetMultimap",
".",
"Builder",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
",",
"Element",
">",
"(",
")",
".",
"putAll",
"(",
"indexByAnnotation",
"(",
"elementsDeferredBySteps",
".",
"get",
"(",
"step",
")",
",",
"step",
".",
"annotations",
"(",
")",
")",
")",
".",
"putAll",
"(",
"filterKeys",
"(",
"validElements",
",",
"Predicates",
".",
"<",
"Object",
">",
"in",
"(",
"step",
".",
"annotations",
"(",
")",
")",
")",
")",
".",
"build",
"(",
")",
";",
"if",
"(",
"stepElements",
".",
"isEmpty",
"(",
")",
")",
"{",
"elementsDeferredBySteps",
".",
"removeAll",
"(",
"step",
")",
";",
"}",
"else",
"{",
"Set",
"<",
"?",
"extends",
"Element",
">",
"rejectedElements",
"=",
"step",
".",
"process",
"(",
"stepElements",
")",
";",
"elementsDeferredBySteps",
".",
"replaceValues",
"(",
"step",
",",
"transform",
"(",
"rejectedElements",
",",
"new",
"Function",
"<",
"Element",
",",
"ElementName",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ElementName",
"apply",
"(",
"Element",
"element",
")",
"{",
"return",
"ElementName",
".",
"forAnnotatedElement",
"(",
"element",
")",
";",
"}",
"}",
")",
")",
";",
"}",
"}",
"}"
] |
Processes the valid elements, including those previously deferred by each step.
|
[
"Processes",
"the",
"valid",
"elements",
"including",
"those",
"previously",
"deferred",
"by",
"each",
"step",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java#L320-L343
|
14,678
|
google/auto
|
value/src/main/java/com/google/auto/value/extension/memoized/processor/MemoizeExtension.java
|
MemoizeExtension.annotatedReturnType
|
private static TypeName annotatedReturnType(ExecutableElement method) {
TypeMirror returnType = method.getReturnType();
List<AnnotationSpec> annotations =
returnType.getAnnotationMirrors().stream()
.map(AnnotationSpec::get)
.collect(toList());
return TypeName.get(returnType).annotated(annotations);
}
|
java
|
private static TypeName annotatedReturnType(ExecutableElement method) {
TypeMirror returnType = method.getReturnType();
List<AnnotationSpec> annotations =
returnType.getAnnotationMirrors().stream()
.map(AnnotationSpec::get)
.collect(toList());
return TypeName.get(returnType).annotated(annotations);
}
|
[
"private",
"static",
"TypeName",
"annotatedReturnType",
"(",
"ExecutableElement",
"method",
")",
"{",
"TypeMirror",
"returnType",
"=",
"method",
".",
"getReturnType",
"(",
")",
";",
"List",
"<",
"AnnotationSpec",
">",
"annotations",
"=",
"returnType",
".",
"getAnnotationMirrors",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"AnnotationSpec",
"::",
"get",
")",
".",
"collect",
"(",
"toList",
"(",
")",
")",
";",
"return",
"TypeName",
".",
"get",
"(",
"returnType",
")",
".",
"annotated",
"(",
"annotations",
")",
";",
"}"
] |
The return type of the given method, including type annotations.
|
[
"The",
"return",
"type",
"of",
"the",
"given",
"method",
"including",
"type",
"annotations",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/extension/memoized/processor/MemoizeExtension.java#L589-L596
|
14,679
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/BuilderSpec.java
|
BuilderSpec.abstractMethods
|
private Set<ExecutableElement> abstractMethods(TypeElement typeElement) {
Set<ExecutableElement> methods =
getLocalAndInheritedMethods(
typeElement, processingEnv.getTypeUtils(), processingEnv.getElementUtils());
ImmutableSet.Builder<ExecutableElement> abstractMethods = ImmutableSet.builder();
for (ExecutableElement method : methods) {
if (method.getModifiers().contains(Modifier.ABSTRACT)) {
abstractMethods.add(method);
}
}
return abstractMethods.build();
}
|
java
|
private Set<ExecutableElement> abstractMethods(TypeElement typeElement) {
Set<ExecutableElement> methods =
getLocalAndInheritedMethods(
typeElement, processingEnv.getTypeUtils(), processingEnv.getElementUtils());
ImmutableSet.Builder<ExecutableElement> abstractMethods = ImmutableSet.builder();
for (ExecutableElement method : methods) {
if (method.getModifiers().contains(Modifier.ABSTRACT)) {
abstractMethods.add(method);
}
}
return abstractMethods.build();
}
|
[
"private",
"Set",
"<",
"ExecutableElement",
">",
"abstractMethods",
"(",
"TypeElement",
"typeElement",
")",
"{",
"Set",
"<",
"ExecutableElement",
">",
"methods",
"=",
"getLocalAndInheritedMethods",
"(",
"typeElement",
",",
"processingEnv",
".",
"getTypeUtils",
"(",
")",
",",
"processingEnv",
".",
"getElementUtils",
"(",
")",
")",
";",
"ImmutableSet",
".",
"Builder",
"<",
"ExecutableElement",
">",
"abstractMethods",
"=",
"ImmutableSet",
".",
"builder",
"(",
")",
";",
"for",
"(",
"ExecutableElement",
"method",
":",
"methods",
")",
"{",
"if",
"(",
"method",
".",
"getModifiers",
"(",
")",
".",
"contains",
"(",
"Modifier",
".",
"ABSTRACT",
")",
")",
"{",
"abstractMethods",
".",
"add",
"(",
"method",
")",
";",
"}",
"}",
"return",
"abstractMethods",
".",
"build",
"(",
")",
";",
"}"
] |
Return a set of all abstract methods in the given TypeElement or inherited from ancestors.
|
[
"Return",
"a",
"set",
"of",
"all",
"abstract",
"methods",
"in",
"the",
"given",
"TypeElement",
"or",
"inherited",
"from",
"ancestors",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/BuilderSpec.java#L448-L459
|
14,680
|
google/auto
|
service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java
|
ServicesFiles.readServiceFile
|
static Set<String> readServiceFile(InputStream input) throws IOException {
HashSet<String> serviceClasses = new HashSet<String>();
Closer closer = Closer.create();
try {
// TODO(gak): use CharStreams
BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
String line;
while ((line = r.readLine()) != null) {
int commentStart = line.indexOf('#');
if (commentStart >= 0) {
line = line.substring(0, commentStart);
}
line = line.trim();
if (!line.isEmpty()) {
serviceClasses.add(line);
}
}
return serviceClasses;
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
|
java
|
static Set<String> readServiceFile(InputStream input) throws IOException {
HashSet<String> serviceClasses = new HashSet<String>();
Closer closer = Closer.create();
try {
// TODO(gak): use CharStreams
BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
String line;
while ((line = r.readLine()) != null) {
int commentStart = line.indexOf('#');
if (commentStart >= 0) {
line = line.substring(0, commentStart);
}
line = line.trim();
if (!line.isEmpty()) {
serviceClasses.add(line);
}
}
return serviceClasses;
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
|
[
"static",
"Set",
"<",
"String",
">",
"readServiceFile",
"(",
"InputStream",
"input",
")",
"throws",
"IOException",
"{",
"HashSet",
"<",
"String",
">",
"serviceClasses",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"Closer",
"closer",
"=",
"Closer",
".",
"create",
"(",
")",
";",
"try",
"{",
"// TODO(gak): use CharStreams",
"BufferedReader",
"r",
"=",
"closer",
".",
"register",
"(",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"input",
",",
"UTF_8",
")",
")",
")",
";",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"r",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"int",
"commentStart",
"=",
"line",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"commentStart",
">=",
"0",
")",
"{",
"line",
"=",
"line",
".",
"substring",
"(",
"0",
",",
"commentStart",
")",
";",
"}",
"line",
"=",
"line",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"line",
".",
"isEmpty",
"(",
")",
")",
"{",
"serviceClasses",
".",
"add",
"(",
"line",
")",
";",
"}",
"}",
"return",
"serviceClasses",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"throw",
"closer",
".",
"rethrow",
"(",
"t",
")",
";",
"}",
"finally",
"{",
"closer",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Reads the set of service classes from a service file.
@param input not {@code null}. Closed after use.
@return a not {@code null Set} of service class names.
@throws IOException
|
[
"Reads",
"the",
"set",
"of",
"service",
"classes",
"from",
"a",
"service",
"file",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java#L58-L81
|
14,681
|
google/auto
|
service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java
|
ServicesFiles.writeServiceFile
|
static void writeServiceFile(Collection<String> services, OutputStream output)
throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8));
for (String service : services) {
writer.write(service);
writer.newLine();
}
writer.flush();
}
|
java
|
static void writeServiceFile(Collection<String> services, OutputStream output)
throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8));
for (String service : services) {
writer.write(service);
writer.newLine();
}
writer.flush();
}
|
[
"static",
"void",
"writeServiceFile",
"(",
"Collection",
"<",
"String",
">",
"services",
",",
"OutputStream",
"output",
")",
"throws",
"IOException",
"{",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"output",
",",
"UTF_8",
")",
")",
";",
"for",
"(",
"String",
"service",
":",
"services",
")",
"{",
"writer",
".",
"write",
"(",
"service",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"}",
"writer",
".",
"flush",
"(",
")",
";",
"}"
] |
Writes the set of service class names to a service file.
@param output not {@code null}. Not closed after use.
@param services a not {@code null Collection} of service class names.
@throws IOException
|
[
"Writes",
"the",
"set",
"of",
"service",
"class",
"names",
"to",
"a",
"service",
"file",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java#L90-L98
|
14,682
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java
|
BuilderMethodClassifier.classify
|
static Optional<BuilderMethodClassifier> classify(
Iterable<ExecutableElement> methods,
ErrorReporter errorReporter,
ProcessingEnvironment processingEnv,
TypeElement autoValueClass,
TypeElement builderType,
ImmutableBiMap<ExecutableElement, String> getterToPropertyName,
ImmutableMap<ExecutableElement, TypeMirror> getterToPropertyType,
boolean autoValueHasToBuilder) {
BuilderMethodClassifier classifier =
new BuilderMethodClassifier(
errorReporter,
processingEnv,
autoValueClass,
builderType,
getterToPropertyName,
getterToPropertyType);
if (classifier.classifyMethods(methods, autoValueHasToBuilder)) {
return Optional.of(classifier);
} else {
return Optional.empty();
}
}
|
java
|
static Optional<BuilderMethodClassifier> classify(
Iterable<ExecutableElement> methods,
ErrorReporter errorReporter,
ProcessingEnvironment processingEnv,
TypeElement autoValueClass,
TypeElement builderType,
ImmutableBiMap<ExecutableElement, String> getterToPropertyName,
ImmutableMap<ExecutableElement, TypeMirror> getterToPropertyType,
boolean autoValueHasToBuilder) {
BuilderMethodClassifier classifier =
new BuilderMethodClassifier(
errorReporter,
processingEnv,
autoValueClass,
builderType,
getterToPropertyName,
getterToPropertyType);
if (classifier.classifyMethods(methods, autoValueHasToBuilder)) {
return Optional.of(classifier);
} else {
return Optional.empty();
}
}
|
[
"static",
"Optional",
"<",
"BuilderMethodClassifier",
">",
"classify",
"(",
"Iterable",
"<",
"ExecutableElement",
">",
"methods",
",",
"ErrorReporter",
"errorReporter",
",",
"ProcessingEnvironment",
"processingEnv",
",",
"TypeElement",
"autoValueClass",
",",
"TypeElement",
"builderType",
",",
"ImmutableBiMap",
"<",
"ExecutableElement",
",",
"String",
">",
"getterToPropertyName",
",",
"ImmutableMap",
"<",
"ExecutableElement",
",",
"TypeMirror",
">",
"getterToPropertyType",
",",
"boolean",
"autoValueHasToBuilder",
")",
"{",
"BuilderMethodClassifier",
"classifier",
"=",
"new",
"BuilderMethodClassifier",
"(",
"errorReporter",
",",
"processingEnv",
",",
"autoValueClass",
",",
"builderType",
",",
"getterToPropertyName",
",",
"getterToPropertyType",
")",
";",
"if",
"(",
"classifier",
".",
"classifyMethods",
"(",
"methods",
",",
"autoValueHasToBuilder",
")",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"classifier",
")",
";",
"}",
"else",
"{",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"}"
] |
Classifies the given methods from a builder type and its ancestors.
@param methods the methods in {@code builderType} and its ancestors.
@param errorReporter where to report errors.
@param processingEnv the ProcessingEnvironment for annotation processing.
@param autoValueClass the {@code AutoValue} class containing the builder.
@param builderType the builder class or interface within {@code autoValueClass}.
@param getterToPropertyName a map from getter methods to the properties they get.
@param getterToPropertyType a map from getter methods to their return types. The return types
here use type parameters from the builder class (if any) rather than from the {@code
AutoValue} class, even though the getter methods are in the latter.
@param autoValueHasToBuilder true if the containing {@code @AutoValue} class has a {@code
toBuilder()} method.
@return an {@code Optional} that contains the results of the classification if it was
successful or nothing if it was not.
|
[
"Classifies",
"the",
"given",
"methods",
"from",
"a",
"builder",
"type",
"and",
"its",
"ancestors",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java#L116-L138
|
14,683
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java
|
BuilderMethodClassifier.classifyMethods
|
private boolean classifyMethods(
Iterable<ExecutableElement> methods, boolean autoValueHasToBuilder) {
int startErrorCount = errorReporter.errorCount();
for (ExecutableElement method : methods) {
classifyMethod(method);
}
if (errorReporter.errorCount() > startErrorCount) {
return false;
}
Multimap<String, ExecutableElement> propertyNameToSetter;
if (propertyNameToPrefixedSetters.isEmpty()) {
propertyNameToSetter = propertyNameToUnprefixedSetters;
this.settersPrefixed = false;
} else if (propertyNameToUnprefixedSetters.isEmpty()) {
propertyNameToSetter = propertyNameToPrefixedSetters;
this.settersPrefixed = true;
} else {
errorReporter.reportError(
"If any setter methods use the setFoo convention then all must",
propertyNameToUnprefixedSetters.values().iterator().next());
return false;
}
getterToPropertyName.forEach(
(getter, property) -> {
TypeMirror propertyType = getterToPropertyType.get(getter);
boolean hasSetter = propertyNameToSetter.containsKey(property);
PropertyBuilder propertyBuilder = propertyNameToPropertyBuilder.get(property);
boolean hasBuilder = propertyBuilder != null;
if (hasBuilder) {
// If property bar of type Bar has a barBuilder() that returns BarBuilder, then it must
// be possible to make a BarBuilder from a Bar if either (1) the @AutoValue class has a
// toBuilder() or (2) there is also a setBar(Bar). Making BarBuilder from Bar is
// possible if Bar either has a toBuilder() method or is a Guava immutable collection
// (in which case we can use addAll or putAll).
boolean canMakeBarBuilder =
(propertyBuilder.getBuiltToBuilder() != null
|| propertyBuilder.getCopyAll() != null);
boolean needToMakeBarBuilder = (autoValueHasToBuilder || hasSetter);
if (needToMakeBarBuilder && !canMakeBarBuilder) {
String error =
String.format(
"Property builder method returns %1$s but there is no way to make that type"
+ " from %2$s: %2$s does not have a non-static toBuilder() method that"
+ " returns %1$s",
propertyBuilder.getBuilderTypeMirror(), propertyType);
errorReporter.reportError(error, propertyBuilder.getPropertyBuilderMethod());
}
} else if (!hasSetter) {
// We have neither barBuilder() nor setBar(Bar), so we should complain.
String setterName = settersPrefixed ? prefixWithSet(property) : property;
String error =
String.format(
"Expected a method with this signature: %s%s %s(%s), or a %sBuilder() method",
builderType, typeParamsString(), setterName, propertyType, property);
errorReporter.reportError(error, builderType);
}
});
return errorReporter.errorCount() == startErrorCount;
}
|
java
|
private boolean classifyMethods(
Iterable<ExecutableElement> methods, boolean autoValueHasToBuilder) {
int startErrorCount = errorReporter.errorCount();
for (ExecutableElement method : methods) {
classifyMethod(method);
}
if (errorReporter.errorCount() > startErrorCount) {
return false;
}
Multimap<String, ExecutableElement> propertyNameToSetter;
if (propertyNameToPrefixedSetters.isEmpty()) {
propertyNameToSetter = propertyNameToUnprefixedSetters;
this.settersPrefixed = false;
} else if (propertyNameToUnprefixedSetters.isEmpty()) {
propertyNameToSetter = propertyNameToPrefixedSetters;
this.settersPrefixed = true;
} else {
errorReporter.reportError(
"If any setter methods use the setFoo convention then all must",
propertyNameToUnprefixedSetters.values().iterator().next());
return false;
}
getterToPropertyName.forEach(
(getter, property) -> {
TypeMirror propertyType = getterToPropertyType.get(getter);
boolean hasSetter = propertyNameToSetter.containsKey(property);
PropertyBuilder propertyBuilder = propertyNameToPropertyBuilder.get(property);
boolean hasBuilder = propertyBuilder != null;
if (hasBuilder) {
// If property bar of type Bar has a barBuilder() that returns BarBuilder, then it must
// be possible to make a BarBuilder from a Bar if either (1) the @AutoValue class has a
// toBuilder() or (2) there is also a setBar(Bar). Making BarBuilder from Bar is
// possible if Bar either has a toBuilder() method or is a Guava immutable collection
// (in which case we can use addAll or putAll).
boolean canMakeBarBuilder =
(propertyBuilder.getBuiltToBuilder() != null
|| propertyBuilder.getCopyAll() != null);
boolean needToMakeBarBuilder = (autoValueHasToBuilder || hasSetter);
if (needToMakeBarBuilder && !canMakeBarBuilder) {
String error =
String.format(
"Property builder method returns %1$s but there is no way to make that type"
+ " from %2$s: %2$s does not have a non-static toBuilder() method that"
+ " returns %1$s",
propertyBuilder.getBuilderTypeMirror(), propertyType);
errorReporter.reportError(error, propertyBuilder.getPropertyBuilderMethod());
}
} else if (!hasSetter) {
// We have neither barBuilder() nor setBar(Bar), so we should complain.
String setterName = settersPrefixed ? prefixWithSet(property) : property;
String error =
String.format(
"Expected a method with this signature: %s%s %s(%s), or a %sBuilder() method",
builderType, typeParamsString(), setterName, propertyType, property);
errorReporter.reportError(error, builderType);
}
});
return errorReporter.errorCount() == startErrorCount;
}
|
[
"private",
"boolean",
"classifyMethods",
"(",
"Iterable",
"<",
"ExecutableElement",
">",
"methods",
",",
"boolean",
"autoValueHasToBuilder",
")",
"{",
"int",
"startErrorCount",
"=",
"errorReporter",
".",
"errorCount",
"(",
")",
";",
"for",
"(",
"ExecutableElement",
"method",
":",
"methods",
")",
"{",
"classifyMethod",
"(",
"method",
")",
";",
"}",
"if",
"(",
"errorReporter",
".",
"errorCount",
"(",
")",
">",
"startErrorCount",
")",
"{",
"return",
"false",
";",
"}",
"Multimap",
"<",
"String",
",",
"ExecutableElement",
">",
"propertyNameToSetter",
";",
"if",
"(",
"propertyNameToPrefixedSetters",
".",
"isEmpty",
"(",
")",
")",
"{",
"propertyNameToSetter",
"=",
"propertyNameToUnprefixedSetters",
";",
"this",
".",
"settersPrefixed",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"propertyNameToUnprefixedSetters",
".",
"isEmpty",
"(",
")",
")",
"{",
"propertyNameToSetter",
"=",
"propertyNameToPrefixedSetters",
";",
"this",
".",
"settersPrefixed",
"=",
"true",
";",
"}",
"else",
"{",
"errorReporter",
".",
"reportError",
"(",
"\"If any setter methods use the setFoo convention then all must\"",
",",
"propertyNameToUnprefixedSetters",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"getterToPropertyName",
".",
"forEach",
"(",
"(",
"getter",
",",
"property",
")",
"->",
"{",
"TypeMirror",
"propertyType",
"=",
"getterToPropertyType",
".",
"get",
"(",
"getter",
")",
";",
"boolean",
"hasSetter",
"=",
"propertyNameToSetter",
".",
"containsKey",
"(",
"property",
")",
";",
"PropertyBuilder",
"propertyBuilder",
"=",
"propertyNameToPropertyBuilder",
".",
"get",
"(",
"property",
")",
";",
"boolean",
"hasBuilder",
"=",
"propertyBuilder",
"!=",
"null",
";",
"if",
"(",
"hasBuilder",
")",
"{",
"// If property bar of type Bar has a barBuilder() that returns BarBuilder, then it must",
"// be possible to make a BarBuilder from a Bar if either (1) the @AutoValue class has a",
"// toBuilder() or (2) there is also a setBar(Bar). Making BarBuilder from Bar is",
"// possible if Bar either has a toBuilder() method or is a Guava immutable collection",
"// (in which case we can use addAll or putAll).",
"boolean",
"canMakeBarBuilder",
"=",
"(",
"propertyBuilder",
".",
"getBuiltToBuilder",
"(",
")",
"!=",
"null",
"||",
"propertyBuilder",
".",
"getCopyAll",
"(",
")",
"!=",
"null",
")",
";",
"boolean",
"needToMakeBarBuilder",
"=",
"(",
"autoValueHasToBuilder",
"||",
"hasSetter",
")",
";",
"if",
"(",
"needToMakeBarBuilder",
"&&",
"!",
"canMakeBarBuilder",
")",
"{",
"String",
"error",
"=",
"String",
".",
"format",
"(",
"\"Property builder method returns %1$s but there is no way to make that type\"",
"+",
"\" from %2$s: %2$s does not have a non-static toBuilder() method that\"",
"+",
"\" returns %1$s\"",
",",
"propertyBuilder",
".",
"getBuilderTypeMirror",
"(",
")",
",",
"propertyType",
")",
";",
"errorReporter",
".",
"reportError",
"(",
"error",
",",
"propertyBuilder",
".",
"getPropertyBuilderMethod",
"(",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"hasSetter",
")",
"{",
"// We have neither barBuilder() nor setBar(Bar), so we should complain.",
"String",
"setterName",
"=",
"settersPrefixed",
"?",
"prefixWithSet",
"(",
"property",
")",
":",
"property",
";",
"String",
"error",
"=",
"String",
".",
"format",
"(",
"\"Expected a method with this signature: %s%s %s(%s), or a %sBuilder() method\"",
",",
"builderType",
",",
"typeParamsString",
"(",
")",
",",
"setterName",
",",
"propertyType",
",",
"property",
")",
";",
"errorReporter",
".",
"reportError",
"(",
"error",
",",
"builderType",
")",
";",
"}",
"}",
")",
";",
"return",
"errorReporter",
".",
"errorCount",
"(",
")",
"==",
"startErrorCount",
";",
"}"
] |
Classifies the given methods and sets the state of this object based on what is found.
|
[
"Classifies",
"the",
"given",
"methods",
"and",
"sets",
"the",
"state",
"of",
"this",
"object",
"based",
"on",
"what",
"is",
"found",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java#L176-L234
|
14,684
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java
|
BuilderMethodClassifier.classifyMethod
|
private void classifyMethod(ExecutableElement method) {
switch (method.getParameters().size()) {
case 0:
classifyMethodNoArgs(method);
break;
case 1:
classifyMethodOneArg(method);
break;
default:
errorReporter.reportError("Builder methods must have 0 or 1 parameters", method);
}
}
|
java
|
private void classifyMethod(ExecutableElement method) {
switch (method.getParameters().size()) {
case 0:
classifyMethodNoArgs(method);
break;
case 1:
classifyMethodOneArg(method);
break;
default:
errorReporter.reportError("Builder methods must have 0 or 1 parameters", method);
}
}
|
[
"private",
"void",
"classifyMethod",
"(",
"ExecutableElement",
"method",
")",
"{",
"switch",
"(",
"method",
".",
"getParameters",
"(",
")",
".",
"size",
"(",
")",
")",
"{",
"case",
"0",
":",
"classifyMethodNoArgs",
"(",
"method",
")",
";",
"break",
";",
"case",
"1",
":",
"classifyMethodOneArg",
"(",
"method",
")",
";",
"break",
";",
"default",
":",
"errorReporter",
".",
"reportError",
"(",
"\"Builder methods must have 0 or 1 parameters\"",
",",
"method",
")",
";",
"}",
"}"
] |
Classifies a method and update the state of this object based on what is found.
|
[
"Classifies",
"a",
"method",
"and",
"update",
"the",
"state",
"of",
"this",
"object",
"based",
"on",
"what",
"is",
"found",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java#L237-L248
|
14,685
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java
|
BuilderMethodClassifier.checkForFailedJavaBean
|
private void checkForFailedJavaBean(ExecutableElement rejectedSetter) {
ImmutableSet<ExecutableElement> allGetters = getterToPropertyName.keySet();
ImmutableSet<ExecutableElement> prefixedGetters =
AutoValueProcessor.prefixedGettersIn(allGetters);
if (prefixedGetters.size() < allGetters.size()
&& prefixedGetters.size() >= allGetters.size() / 2) {
String note =
"This might be because you are using the getFoo() convention"
+ " for some but not all methods. These methods don't follow the convention: "
+ difference(allGetters, prefixedGetters);
errorReporter.reportNote(note, rejectedSetter);
}
}
|
java
|
private void checkForFailedJavaBean(ExecutableElement rejectedSetter) {
ImmutableSet<ExecutableElement> allGetters = getterToPropertyName.keySet();
ImmutableSet<ExecutableElement> prefixedGetters =
AutoValueProcessor.prefixedGettersIn(allGetters);
if (prefixedGetters.size() < allGetters.size()
&& prefixedGetters.size() >= allGetters.size() / 2) {
String note =
"This might be because you are using the getFoo() convention"
+ " for some but not all methods. These methods don't follow the convention: "
+ difference(allGetters, prefixedGetters);
errorReporter.reportNote(note, rejectedSetter);
}
}
|
[
"private",
"void",
"checkForFailedJavaBean",
"(",
"ExecutableElement",
"rejectedSetter",
")",
"{",
"ImmutableSet",
"<",
"ExecutableElement",
">",
"allGetters",
"=",
"getterToPropertyName",
".",
"keySet",
"(",
")",
";",
"ImmutableSet",
"<",
"ExecutableElement",
">",
"prefixedGetters",
"=",
"AutoValueProcessor",
".",
"prefixedGettersIn",
"(",
"allGetters",
")",
";",
"if",
"(",
"prefixedGetters",
".",
"size",
"(",
")",
"<",
"allGetters",
".",
"size",
"(",
")",
"&&",
"prefixedGetters",
".",
"size",
"(",
")",
">=",
"allGetters",
".",
"size",
"(",
")",
"/",
"2",
")",
"{",
"String",
"note",
"=",
"\"This might be because you are using the getFoo() convention\"",
"+",
"\" for some but not all methods. These methods don't follow the convention: \"",
"+",
"difference",
"(",
"allGetters",
",",
"prefixedGetters",
")",
";",
"errorReporter",
".",
"reportNote",
"(",
"note",
",",
"rejectedSetter",
")",
";",
"}",
"}"
] |
setGetFoo).
|
[
"setGetFoo",
")",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/BuilderMethodClassifier.java#L396-L408
|
14,686
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java
|
TypeSimplifier.typesToImport
|
ImmutableSortedSet<String> typesToImport() {
ImmutableSortedSet.Builder<String> typesToImport = ImmutableSortedSet.naturalOrder();
for (Map.Entry<String, Spelling> entry : imports.entrySet()) {
if (entry.getValue().importIt) {
typesToImport.add(entry.getKey());
}
}
return typesToImport.build();
}
|
java
|
ImmutableSortedSet<String> typesToImport() {
ImmutableSortedSet.Builder<String> typesToImport = ImmutableSortedSet.naturalOrder();
for (Map.Entry<String, Spelling> entry : imports.entrySet()) {
if (entry.getValue().importIt) {
typesToImport.add(entry.getKey());
}
}
return typesToImport.build();
}
|
[
"ImmutableSortedSet",
"<",
"String",
">",
"typesToImport",
"(",
")",
"{",
"ImmutableSortedSet",
".",
"Builder",
"<",
"String",
">",
"typesToImport",
"=",
"ImmutableSortedSet",
".",
"naturalOrder",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Spelling",
">",
"entry",
":",
"imports",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"importIt",
")",
"{",
"typesToImport",
".",
"add",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"}",
"}",
"return",
"typesToImport",
".",
"build",
"(",
")",
";",
"}"
] |
Returns the set of types to import. We import every type that is neither in java.lang nor in
the package containing the AutoValue class, provided that the result refers to the type
unambiguously. For example, if there is a property of type java.util.Map.Entry then we will
import java.util.Map.Entry and refer to the property as Entry. We could also import just
java.util.Map in this case and refer to Map.Entry, but currently we never do that.
|
[
"Returns",
"the",
"set",
"of",
"types",
"to",
"import",
".",
"We",
"import",
"every",
"type",
"that",
"is",
"neither",
"in",
"java",
".",
"lang",
"nor",
"in",
"the",
"package",
"containing",
"the",
"AutoValue",
"class",
"provided",
"that",
"the",
"result",
"refers",
"to",
"the",
"type",
"unambiguously",
".",
"For",
"example",
"if",
"there",
"is",
"a",
"property",
"of",
"type",
"java",
".",
"util",
".",
"Map",
".",
"Entry",
"then",
"we",
"will",
"import",
"java",
".",
"util",
".",
"Map",
".",
"Entry",
"and",
"refer",
"to",
"the",
"property",
"as",
"Entry",
".",
"We",
"could",
"also",
"import",
"just",
"java",
".",
"util",
".",
"Map",
"in",
"this",
"case",
"and",
"refer",
"to",
"Map",
".",
"Entry",
"but",
"currently",
"we",
"never",
"do",
"that",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java#L106-L114
|
14,687
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java
|
TypeSimplifier.classNameOf
|
static String classNameOf(TypeElement type) {
String name = type.getQualifiedName().toString();
String pkgName = packageNameOf(type);
return pkgName.isEmpty() ? name : name.substring(pkgName.length() + 1);
}
|
java
|
static String classNameOf(TypeElement type) {
String name = type.getQualifiedName().toString();
String pkgName = packageNameOf(type);
return pkgName.isEmpty() ? name : name.substring(pkgName.length() + 1);
}
|
[
"static",
"String",
"classNameOf",
"(",
"TypeElement",
"type",
")",
"{",
"String",
"name",
"=",
"type",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"pkgName",
"=",
"packageNameOf",
"(",
"type",
")",
";",
"return",
"pkgName",
".",
"isEmpty",
"(",
")",
"?",
"name",
":",
"name",
".",
"substring",
"(",
"pkgName",
".",
"length",
"(",
")",
"+",
"1",
")",
";",
"}"
] |
Returns the name of the given type, including any enclosing types but not the package.
|
[
"Returns",
"the",
"name",
"of",
"the",
"given",
"type",
"including",
"any",
"enclosing",
"types",
"but",
"not",
"the",
"package",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java#L148-L152
|
14,688
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java
|
TypeSimplifier.findImports
|
private static Map<String, Spelling> findImports(
Elements elementUtils,
Types typeUtils,
String codePackageName,
Set<TypeMirror> referenced,
Set<TypeMirror> defined) {
Map<String, Spelling> imports = new HashMap<>();
Set<TypeMirror> typesInScope = new TypeMirrorSet();
typesInScope.addAll(referenced);
typesInScope.addAll(defined);
Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
for (TypeMirror type : referenced) {
TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
String fullName = typeElement.getQualifiedName().toString();
String simpleName = typeElement.getSimpleName().toString();
String pkg = packageNameOf(typeElement);
boolean importIt;
String spelling;
if (ambiguous.contains(simpleName)) {
importIt = false;
spelling = fullName;
} else if (pkg.equals("java.lang")) {
importIt = false;
spelling = javaLangSpelling(elementUtils, codePackageName, typeElement);
} else if (pkg.equals(codePackageName)) {
importIt = false;
spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
} else {
importIt = true;
spelling = simpleName;
}
imports.put(fullName, new Spelling(spelling, importIt));
}
return imports;
}
|
java
|
private static Map<String, Spelling> findImports(
Elements elementUtils,
Types typeUtils,
String codePackageName,
Set<TypeMirror> referenced,
Set<TypeMirror> defined) {
Map<String, Spelling> imports = new HashMap<>();
Set<TypeMirror> typesInScope = new TypeMirrorSet();
typesInScope.addAll(referenced);
typesInScope.addAll(defined);
Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
for (TypeMirror type : referenced) {
TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
String fullName = typeElement.getQualifiedName().toString();
String simpleName = typeElement.getSimpleName().toString();
String pkg = packageNameOf(typeElement);
boolean importIt;
String spelling;
if (ambiguous.contains(simpleName)) {
importIt = false;
spelling = fullName;
} else if (pkg.equals("java.lang")) {
importIt = false;
spelling = javaLangSpelling(elementUtils, codePackageName, typeElement);
} else if (pkg.equals(codePackageName)) {
importIt = false;
spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
} else {
importIt = true;
spelling = simpleName;
}
imports.put(fullName, new Spelling(spelling, importIt));
}
return imports;
}
|
[
"private",
"static",
"Map",
"<",
"String",
",",
"Spelling",
">",
"findImports",
"(",
"Elements",
"elementUtils",
",",
"Types",
"typeUtils",
",",
"String",
"codePackageName",
",",
"Set",
"<",
"TypeMirror",
">",
"referenced",
",",
"Set",
"<",
"TypeMirror",
">",
"defined",
")",
"{",
"Map",
"<",
"String",
",",
"Spelling",
">",
"imports",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"Set",
"<",
"TypeMirror",
">",
"typesInScope",
"=",
"new",
"TypeMirrorSet",
"(",
")",
";",
"typesInScope",
".",
"addAll",
"(",
"referenced",
")",
";",
"typesInScope",
".",
"addAll",
"(",
"defined",
")",
";",
"Set",
"<",
"String",
">",
"ambiguous",
"=",
"ambiguousNames",
"(",
"typeUtils",
",",
"typesInScope",
")",
";",
"for",
"(",
"TypeMirror",
"type",
":",
"referenced",
")",
"{",
"TypeElement",
"typeElement",
"=",
"(",
"TypeElement",
")",
"typeUtils",
".",
"asElement",
"(",
"type",
")",
";",
"String",
"fullName",
"=",
"typeElement",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"simpleName",
"=",
"typeElement",
".",
"getSimpleName",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"pkg",
"=",
"packageNameOf",
"(",
"typeElement",
")",
";",
"boolean",
"importIt",
";",
"String",
"spelling",
";",
"if",
"(",
"ambiguous",
".",
"contains",
"(",
"simpleName",
")",
")",
"{",
"importIt",
"=",
"false",
";",
"spelling",
"=",
"fullName",
";",
"}",
"else",
"if",
"(",
"pkg",
".",
"equals",
"(",
"\"java.lang\"",
")",
")",
"{",
"importIt",
"=",
"false",
";",
"spelling",
"=",
"javaLangSpelling",
"(",
"elementUtils",
",",
"codePackageName",
",",
"typeElement",
")",
";",
"}",
"else",
"if",
"(",
"pkg",
".",
"equals",
"(",
"codePackageName",
")",
")",
"{",
"importIt",
"=",
"false",
";",
"spelling",
"=",
"fullName",
".",
"substring",
"(",
"pkg",
".",
"isEmpty",
"(",
")",
"?",
"0",
":",
"pkg",
".",
"length",
"(",
")",
"+",
"1",
")",
";",
"}",
"else",
"{",
"importIt",
"=",
"true",
";",
"spelling",
"=",
"simpleName",
";",
"}",
"imports",
".",
"put",
"(",
"fullName",
",",
"new",
"Spelling",
"(",
"spelling",
",",
"importIt",
")",
")",
";",
"}",
"return",
"imports",
";",
"}"
] |
Given a set of referenced types, works out which of them should be imported and what the
resulting spelling of each one is.
<p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>}
because it is not strictly possible to determine what part of a fully-qualified type name is
the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is a
class called {@code Map.Entry} in a package called {@code java.util} assuming Java conventions
are being followed, but it could theoretically also be a class called {@code Entry} in a
package called {@code java.util.Map}. Since we are operating as part of the compiler, our goal
should be complete correctness, and the only way to achieve that is to operate on the real
representations of types.
@param codePackageName The name of the package where the class containing these references is
defined. Other classes within the same package do not need to be imported.
@param referenced The complete set of declared types (classes and interfaces) that will be
referenced in the generated code.
@param defined The complete set of declared types (classes and interfaces) that are defined
within the scope of the generated class (i.e. nested somewhere in its superclass chain, or
in its interface set)
@return a map where the keys are fully-qualified types and the corresponding values indicate
whether the type should be imported, and how the type should be spelled in the source code.
|
[
"Given",
"a",
"set",
"of",
"referenced",
"types",
"works",
"out",
"which",
"of",
"them",
"should",
"be",
"imported",
"and",
"what",
"the",
"resulting",
"spelling",
"of",
"each",
"one",
"is",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TypeSimplifier.java#L200-L234
|
14,689
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
|
AutoValueOrOneOfProcessor.defineSharedVarsForType
|
final void defineSharedVarsForType(
TypeElement type,
ImmutableSet<ExecutableElement> methods,
AutoValueOrOneOfTemplateVars vars) {
vars.pkg = TypeSimplifier.packageNameOf(type);
vars.origClass = TypeSimplifier.classNameOf(type);
vars.simpleClassName = TypeSimplifier.simpleNameOf(vars.origClass);
vars.generated =
generatedAnnotation(elementUtils(), processingEnv.getSourceVersion())
.map(annotation -> TypeEncoder.encode(annotation.asType()))
.orElse("");
vars.formalTypes = TypeEncoder.formalTypeParametersString(type);
vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
vars.wildcardTypes = wildcardTypeParametersString(type);
vars.annotations = copiedClassAnnotations(type);
Map<ObjectMethod, ExecutableElement> methodsToGenerate =
determineObjectMethodsToGenerate(methods);
vars.toString = methodsToGenerate.containsKey(ObjectMethod.TO_STRING);
vars.equals = methodsToGenerate.containsKey(ObjectMethod.EQUALS);
vars.hashCode = methodsToGenerate.containsKey(ObjectMethod.HASH_CODE);
vars.equalsParameterType = equalsParameterType(methodsToGenerate);
}
|
java
|
final void defineSharedVarsForType(
TypeElement type,
ImmutableSet<ExecutableElement> methods,
AutoValueOrOneOfTemplateVars vars) {
vars.pkg = TypeSimplifier.packageNameOf(type);
vars.origClass = TypeSimplifier.classNameOf(type);
vars.simpleClassName = TypeSimplifier.simpleNameOf(vars.origClass);
vars.generated =
generatedAnnotation(elementUtils(), processingEnv.getSourceVersion())
.map(annotation -> TypeEncoder.encode(annotation.asType()))
.orElse("");
vars.formalTypes = TypeEncoder.formalTypeParametersString(type);
vars.actualTypes = TypeSimplifier.actualTypeParametersString(type);
vars.wildcardTypes = wildcardTypeParametersString(type);
vars.annotations = copiedClassAnnotations(type);
Map<ObjectMethod, ExecutableElement> methodsToGenerate =
determineObjectMethodsToGenerate(methods);
vars.toString = methodsToGenerate.containsKey(ObjectMethod.TO_STRING);
vars.equals = methodsToGenerate.containsKey(ObjectMethod.EQUALS);
vars.hashCode = methodsToGenerate.containsKey(ObjectMethod.HASH_CODE);
vars.equalsParameterType = equalsParameterType(methodsToGenerate);
}
|
[
"final",
"void",
"defineSharedVarsForType",
"(",
"TypeElement",
"type",
",",
"ImmutableSet",
"<",
"ExecutableElement",
">",
"methods",
",",
"AutoValueOrOneOfTemplateVars",
"vars",
")",
"{",
"vars",
".",
"pkg",
"=",
"TypeSimplifier",
".",
"packageNameOf",
"(",
"type",
")",
";",
"vars",
".",
"origClass",
"=",
"TypeSimplifier",
".",
"classNameOf",
"(",
"type",
")",
";",
"vars",
".",
"simpleClassName",
"=",
"TypeSimplifier",
".",
"simpleNameOf",
"(",
"vars",
".",
"origClass",
")",
";",
"vars",
".",
"generated",
"=",
"generatedAnnotation",
"(",
"elementUtils",
"(",
")",
",",
"processingEnv",
".",
"getSourceVersion",
"(",
")",
")",
".",
"map",
"(",
"annotation",
"->",
"TypeEncoder",
".",
"encode",
"(",
"annotation",
".",
"asType",
"(",
")",
")",
")",
".",
"orElse",
"(",
"\"\"",
")",
";",
"vars",
".",
"formalTypes",
"=",
"TypeEncoder",
".",
"formalTypeParametersString",
"(",
"type",
")",
";",
"vars",
".",
"actualTypes",
"=",
"TypeSimplifier",
".",
"actualTypeParametersString",
"(",
"type",
")",
";",
"vars",
".",
"wildcardTypes",
"=",
"wildcardTypeParametersString",
"(",
"type",
")",
";",
"vars",
".",
"annotations",
"=",
"copiedClassAnnotations",
"(",
"type",
")",
";",
"Map",
"<",
"ObjectMethod",
",",
"ExecutableElement",
">",
"methodsToGenerate",
"=",
"determineObjectMethodsToGenerate",
"(",
"methods",
")",
";",
"vars",
".",
"toString",
"=",
"methodsToGenerate",
".",
"containsKey",
"(",
"ObjectMethod",
".",
"TO_STRING",
")",
";",
"vars",
".",
"equals",
"=",
"methodsToGenerate",
".",
"containsKey",
"(",
"ObjectMethod",
".",
"EQUALS",
")",
";",
"vars",
".",
"hashCode",
"=",
"methodsToGenerate",
".",
"containsKey",
"(",
"ObjectMethod",
".",
"HASH_CODE",
")",
";",
"vars",
".",
"equalsParameterType",
"=",
"equalsParameterType",
"(",
"methodsToGenerate",
")",
";",
"}"
] |
Defines the template variables that are shared by AutoValue and AutoOneOf.
|
[
"Defines",
"the",
"template",
"variables",
"that",
"are",
"shared",
"by",
"AutoValue",
"and",
"AutoOneOf",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L406-L427
|
14,690
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
|
AutoValueOrOneOfProcessor.annotationStrings
|
static ImmutableList<String> annotationStrings(List<? extends AnnotationMirror> annotations) {
// TODO(b/68008628): use ImmutableList.toImmutableList() when that works.
return ImmutableList.copyOf(
annotations.stream().map(AnnotationOutput::sourceFormForAnnotation).collect(toList()));
}
|
java
|
static ImmutableList<String> annotationStrings(List<? extends AnnotationMirror> annotations) {
// TODO(b/68008628): use ImmutableList.toImmutableList() when that works.
return ImmutableList.copyOf(
annotations.stream().map(AnnotationOutput::sourceFormForAnnotation).collect(toList()));
}
|
[
"static",
"ImmutableList",
"<",
"String",
">",
"annotationStrings",
"(",
"List",
"<",
"?",
"extends",
"AnnotationMirror",
">",
"annotations",
")",
"{",
"// TODO(b/68008628): use ImmutableList.toImmutableList() when that works.",
"return",
"ImmutableList",
".",
"copyOf",
"(",
"annotations",
".",
"stream",
"(",
")",
".",
"map",
"(",
"AnnotationOutput",
"::",
"sourceFormForAnnotation",
")",
".",
"collect",
"(",
"toList",
"(",
")",
")",
")",
";",
"}"
] |
Returns the spelling to be used in the generated code for the given list of annotations.
|
[
"Returns",
"the",
"spelling",
"to",
"be",
"used",
"in",
"the",
"generated",
"code",
"for",
"the",
"given",
"list",
"of",
"annotations",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L430-L434
|
14,691
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
|
AutoValueOrOneOfProcessor.propertyNameToMethodMap
|
final ImmutableBiMap<String, ExecutableElement> propertyNameToMethodMap(
Set<ExecutableElement> propertyMethods) {
Map<String, ExecutableElement> map = new LinkedHashMap<>();
Set<String> reportedDups = new HashSet<>();
boolean allPrefixed = gettersAllPrefixed(propertyMethods);
for (ExecutableElement method : propertyMethods) {
String methodName = method.getSimpleName().toString();
String name = allPrefixed ? nameWithoutPrefix(methodName) : methodName;
ExecutableElement old = map.put(name, method);
if (old != null) {
String message = "More than one @" + simpleAnnotationName + " property called " + name;
errorReporter.reportError(message, method);
if (reportedDups.add(name)) {
errorReporter.reportError(message, old);
}
}
}
return ImmutableBiMap.copyOf(map);
}
|
java
|
final ImmutableBiMap<String, ExecutableElement> propertyNameToMethodMap(
Set<ExecutableElement> propertyMethods) {
Map<String, ExecutableElement> map = new LinkedHashMap<>();
Set<String> reportedDups = new HashSet<>();
boolean allPrefixed = gettersAllPrefixed(propertyMethods);
for (ExecutableElement method : propertyMethods) {
String methodName = method.getSimpleName().toString();
String name = allPrefixed ? nameWithoutPrefix(methodName) : methodName;
ExecutableElement old = map.put(name, method);
if (old != null) {
String message = "More than one @" + simpleAnnotationName + " property called " + name;
errorReporter.reportError(message, method);
if (reportedDups.add(name)) {
errorReporter.reportError(message, old);
}
}
}
return ImmutableBiMap.copyOf(map);
}
|
[
"final",
"ImmutableBiMap",
"<",
"String",
",",
"ExecutableElement",
">",
"propertyNameToMethodMap",
"(",
"Set",
"<",
"ExecutableElement",
">",
"propertyMethods",
")",
"{",
"Map",
"<",
"String",
",",
"ExecutableElement",
">",
"map",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"Set",
"<",
"String",
">",
"reportedDups",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"boolean",
"allPrefixed",
"=",
"gettersAllPrefixed",
"(",
"propertyMethods",
")",
";",
"for",
"(",
"ExecutableElement",
"method",
":",
"propertyMethods",
")",
"{",
"String",
"methodName",
"=",
"method",
".",
"getSimpleName",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"name",
"=",
"allPrefixed",
"?",
"nameWithoutPrefix",
"(",
"methodName",
")",
":",
"methodName",
";",
"ExecutableElement",
"old",
"=",
"map",
".",
"put",
"(",
"name",
",",
"method",
")",
";",
"if",
"(",
"old",
"!=",
"null",
")",
"{",
"String",
"message",
"=",
"\"More than one @\"",
"+",
"simpleAnnotationName",
"+",
"\" property called \"",
"+",
"name",
";",
"errorReporter",
".",
"reportError",
"(",
"message",
",",
"method",
")",
";",
"if",
"(",
"reportedDups",
".",
"add",
"(",
"name",
")",
")",
"{",
"errorReporter",
".",
"reportError",
"(",
"message",
",",
"old",
")",
";",
"}",
"}",
"}",
"return",
"ImmutableBiMap",
".",
"copyOf",
"(",
"map",
")",
";",
"}"
] |
Returns a bi-map between property names and the corresponding abstract property methods.
|
[
"Returns",
"a",
"bi",
"-",
"map",
"between",
"property",
"names",
"and",
"the",
"corresponding",
"abstract",
"property",
"methods",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L499-L517
|
14,692
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
|
AutoValueOrOneOfProcessor.abstractMethodsIn
|
static ImmutableSet<ExecutableElement> abstractMethodsIn(
ImmutableSet<ExecutableElement> methods) {
Set<Name> noArgMethods = new HashSet<>();
ImmutableSet.Builder<ExecutableElement> abstracts = ImmutableSet.builder();
for (ExecutableElement method : methods) {
if (method.getModifiers().contains(Modifier.ABSTRACT)) {
boolean hasArgs = !method.getParameters().isEmpty();
if (hasArgs || noArgMethods.add(method.getSimpleName())) {
// If an abstract method with the same signature is inherited on more than one path,
// we only add it once. At the moment we only do this check for no-arg methods. All
// methods that AutoValue will implement are either no-arg methods or equals(Object).
// The former is covered by this check and the latter will lead to vars.equals being
// set to true, regardless of how many times it appears. So the only case that is
// covered imperfectly here is that of a method that is inherited on more than one path
// and that will be consumed by an extension. We could check parameters as well, but that
// can be a bit tricky if any of the parameters are generic.
abstracts.add(method);
}
}
}
return abstracts.build();
}
|
java
|
static ImmutableSet<ExecutableElement> abstractMethodsIn(
ImmutableSet<ExecutableElement> methods) {
Set<Name> noArgMethods = new HashSet<>();
ImmutableSet.Builder<ExecutableElement> abstracts = ImmutableSet.builder();
for (ExecutableElement method : methods) {
if (method.getModifiers().contains(Modifier.ABSTRACT)) {
boolean hasArgs = !method.getParameters().isEmpty();
if (hasArgs || noArgMethods.add(method.getSimpleName())) {
// If an abstract method with the same signature is inherited on more than one path,
// we only add it once. At the moment we only do this check for no-arg methods. All
// methods that AutoValue will implement are either no-arg methods or equals(Object).
// The former is covered by this check and the latter will lead to vars.equals being
// set to true, regardless of how many times it appears. So the only case that is
// covered imperfectly here is that of a method that is inherited on more than one path
// and that will be consumed by an extension. We could check parameters as well, but that
// can be a bit tricky if any of the parameters are generic.
abstracts.add(method);
}
}
}
return abstracts.build();
}
|
[
"static",
"ImmutableSet",
"<",
"ExecutableElement",
">",
"abstractMethodsIn",
"(",
"ImmutableSet",
"<",
"ExecutableElement",
">",
"methods",
")",
"{",
"Set",
"<",
"Name",
">",
"noArgMethods",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"ImmutableSet",
".",
"Builder",
"<",
"ExecutableElement",
">",
"abstracts",
"=",
"ImmutableSet",
".",
"builder",
"(",
")",
";",
"for",
"(",
"ExecutableElement",
"method",
":",
"methods",
")",
"{",
"if",
"(",
"method",
".",
"getModifiers",
"(",
")",
".",
"contains",
"(",
"Modifier",
".",
"ABSTRACT",
")",
")",
"{",
"boolean",
"hasArgs",
"=",
"!",
"method",
".",
"getParameters",
"(",
")",
".",
"isEmpty",
"(",
")",
";",
"if",
"(",
"hasArgs",
"||",
"noArgMethods",
".",
"add",
"(",
"method",
".",
"getSimpleName",
"(",
")",
")",
")",
"{",
"// If an abstract method with the same signature is inherited on more than one path,",
"// we only add it once. At the moment we only do this check for no-arg methods. All",
"// methods that AutoValue will implement are either no-arg methods or equals(Object).",
"// The former is covered by this check and the latter will lead to vars.equals being",
"// set to true, regardless of how many times it appears. So the only case that is",
"// covered imperfectly here is that of a method that is inherited on more than one path",
"// and that will be consumed by an extension. We could check parameters as well, but that",
"// can be a bit tricky if any of the parameters are generic.",
"abstracts",
".",
"add",
"(",
"method",
")",
";",
"}",
"}",
"}",
"return",
"abstracts",
".",
"build",
"(",
")",
";",
"}"
] |
Returns the subset of all abstract methods in the given set of methods. A given method
signature is only mentioned once, even if it is inherited on more than one path.
|
[
"Returns",
"the",
"subset",
"of",
"all",
"abstract",
"methods",
"in",
"the",
"given",
"set",
"of",
"methods",
".",
"A",
"given",
"method",
"signature",
"is",
"only",
"mentioned",
"once",
"even",
"if",
"it",
"is",
"inherited",
"on",
"more",
"than",
"one",
"path",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L695-L716
|
14,693
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java
|
AutoValueOrOneOfProcessor.checkReturnType
|
final void checkReturnType(TypeElement autoValueClass, ExecutableElement getter) {
TypeMirror type = getter.getReturnType();
if (type.getKind() == TypeKind.ARRAY) {
TypeMirror componentType = ((ArrayType) type).getComponentType();
if (componentType.getKind().isPrimitive()) {
warnAboutPrimitiveArrays(autoValueClass, getter);
} else {
errorReporter.reportError(
"An @"
+ simpleAnnotationName
+ " class cannot define an array-valued property unless it is a primitive array",
getter);
}
}
}
|
java
|
final void checkReturnType(TypeElement autoValueClass, ExecutableElement getter) {
TypeMirror type = getter.getReturnType();
if (type.getKind() == TypeKind.ARRAY) {
TypeMirror componentType = ((ArrayType) type).getComponentType();
if (componentType.getKind().isPrimitive()) {
warnAboutPrimitiveArrays(autoValueClass, getter);
} else {
errorReporter.reportError(
"An @"
+ simpleAnnotationName
+ " class cannot define an array-valued property unless it is a primitive array",
getter);
}
}
}
|
[
"final",
"void",
"checkReturnType",
"(",
"TypeElement",
"autoValueClass",
",",
"ExecutableElement",
"getter",
")",
"{",
"TypeMirror",
"type",
"=",
"getter",
".",
"getReturnType",
"(",
")",
";",
"if",
"(",
"type",
".",
"getKind",
"(",
")",
"==",
"TypeKind",
".",
"ARRAY",
")",
"{",
"TypeMirror",
"componentType",
"=",
"(",
"(",
"ArrayType",
")",
"type",
")",
".",
"getComponentType",
"(",
")",
";",
"if",
"(",
"componentType",
".",
"getKind",
"(",
")",
".",
"isPrimitive",
"(",
")",
")",
"{",
"warnAboutPrimitiveArrays",
"(",
"autoValueClass",
",",
"getter",
")",
";",
"}",
"else",
"{",
"errorReporter",
".",
"reportError",
"(",
"\"An @\"",
"+",
"simpleAnnotationName",
"+",
"\" class cannot define an array-valued property unless it is a primitive array\"",
",",
"getter",
")",
";",
"}",
"}",
"}"
] |
Checks that the return type of the given property method is allowed. Currently, this means that
it cannot be an array, unless it is a primitive array.
|
[
"Checks",
"that",
"the",
"return",
"type",
"of",
"the",
"given",
"property",
"method",
"is",
"allowed",
".",
"Currently",
"this",
"means",
"that",
"it",
"cannot",
"be",
"an",
"array",
"unless",
"it",
"is",
"a",
"primitive",
"array",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoValueOrOneOfProcessor.java#L738-L752
|
14,694
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/Optionalish.java
|
Optionalish.createIfOptional
|
static Optionalish createIfOptional(TypeMirror type) {
if (isOptional(type)) {
return new Optionalish(MoreTypes.asDeclared(type));
} else {
return null;
}
}
|
java
|
static Optionalish createIfOptional(TypeMirror type) {
if (isOptional(type)) {
return new Optionalish(MoreTypes.asDeclared(type));
} else {
return null;
}
}
|
[
"static",
"Optionalish",
"createIfOptional",
"(",
"TypeMirror",
"type",
")",
"{",
"if",
"(",
"isOptional",
"(",
"type",
")",
")",
"{",
"return",
"new",
"Optionalish",
"(",
"MoreTypes",
".",
"asDeclared",
"(",
"type",
")",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
Returns an instance wrapping the given TypeMirror, or null if it is not any kind of Optional.
@param type the TypeMirror for the original optional type, for example {@code
Optional<String>}.
|
[
"Returns",
"an",
"instance",
"wrapping",
"the",
"given",
"TypeMirror",
"or",
"null",
"if",
"it",
"is",
"not",
"any",
"kind",
"of",
"Optional",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/Optionalish.java#L59-L65
|
14,695
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/ErrorReporter.java
|
ErrorReporter.reportNote
|
void reportNote(String msg, Element e) {
messager.printMessage(Diagnostic.Kind.NOTE, msg, e);
}
|
java
|
void reportNote(String msg, Element e) {
messager.printMessage(Diagnostic.Kind.NOTE, msg, e);
}
|
[
"void",
"reportNote",
"(",
"String",
"msg",
",",
"Element",
"e",
")",
"{",
"messager",
".",
"printMessage",
"(",
"Diagnostic",
".",
"Kind",
".",
"NOTE",
",",
"msg",
",",
"e",
")",
";",
"}"
] |
Issue a compilation note.
@param msg the text of the note
@param e the element to which it pertains
|
[
"Issue",
"a",
"compilation",
"note",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/ErrorReporter.java#L42-L44
|
14,696
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/ErrorReporter.java
|
ErrorReporter.reportWarning
|
void reportWarning(String msg, Element e) {
messager.printMessage(Diagnostic.Kind.WARNING, msg, e);
}
|
java
|
void reportWarning(String msg, Element e) {
messager.printMessage(Diagnostic.Kind.WARNING, msg, e);
}
|
[
"void",
"reportWarning",
"(",
"String",
"msg",
",",
"Element",
"e",
")",
"{",
"messager",
".",
"printMessage",
"(",
"Diagnostic",
".",
"Kind",
".",
"WARNING",
",",
"msg",
",",
"e",
")",
";",
"}"
] |
Issue a compilation warning.
@param msg the text of the warning
@param e the element to which it pertains
|
[
"Issue",
"a",
"compilation",
"warning",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/ErrorReporter.java#L52-L54
|
14,697
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AnnotationOutput.java
|
AnnotationOutput.sourceFormForInitializer
|
static String sourceFormForInitializer(
AnnotationValue annotationValue,
ProcessingEnvironment processingEnv,
String memberName,
Element context) {
SourceFormVisitor visitor =
new InitializerSourceFormVisitor(processingEnv, memberName, context);
StringBuilder sb = new StringBuilder();
visitor.visit(annotationValue, sb);
return sb.toString();
}
|
java
|
static String sourceFormForInitializer(
AnnotationValue annotationValue,
ProcessingEnvironment processingEnv,
String memberName,
Element context) {
SourceFormVisitor visitor =
new InitializerSourceFormVisitor(processingEnv, memberName, context);
StringBuilder sb = new StringBuilder();
visitor.visit(annotationValue, sb);
return sb.toString();
}
|
[
"static",
"String",
"sourceFormForInitializer",
"(",
"AnnotationValue",
"annotationValue",
",",
"ProcessingEnvironment",
"processingEnv",
",",
"String",
"memberName",
",",
"Element",
"context",
")",
"{",
"SourceFormVisitor",
"visitor",
"=",
"new",
"InitializerSourceFormVisitor",
"(",
"processingEnv",
",",
"memberName",
",",
"context",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"visitor",
".",
"visit",
"(",
"annotationValue",
",",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns a string representation of the given annotation value, suitable for inclusion in a Java
source file as the initializer of a variable of the appropriate type.
|
[
"Returns",
"a",
"string",
"representation",
"of",
"the",
"given",
"annotation",
"value",
"suitable",
"for",
"inclusion",
"in",
"a",
"Java",
"source",
"file",
"as",
"the",
"initializer",
"of",
"a",
"variable",
"of",
"the",
"appropriate",
"type",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AnnotationOutput.java#L179-L189
|
14,698
|
google/auto
|
value/src/main/java/com/google/auto/value/processor/AnnotationOutput.java
|
AnnotationOutput.sourceFormForAnnotation
|
static String sourceFormForAnnotation(AnnotationMirror annotationMirror) {
StringBuilder sb = new StringBuilder();
new AnnotationSourceFormVisitor().visitAnnotation(annotationMirror, sb);
return sb.toString();
}
|
java
|
static String sourceFormForAnnotation(AnnotationMirror annotationMirror) {
StringBuilder sb = new StringBuilder();
new AnnotationSourceFormVisitor().visitAnnotation(annotationMirror, sb);
return sb.toString();
}
|
[
"static",
"String",
"sourceFormForAnnotation",
"(",
"AnnotationMirror",
"annotationMirror",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"new",
"AnnotationSourceFormVisitor",
"(",
")",
".",
"visitAnnotation",
"(",
"annotationMirror",
",",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns a string representation of the given annotation mirror, suitable for inclusion in a
Java source file to reproduce the annotation in source form.
|
[
"Returns",
"a",
"string",
"representation",
"of",
"the",
"given",
"annotation",
"mirror",
"suitable",
"for",
"inclusion",
"in",
"a",
"Java",
"source",
"file",
"to",
"reproduce",
"the",
"annotation",
"in",
"source",
"form",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AnnotationOutput.java#L195-L199
|
14,699
|
google/auto
|
common/src/main/java/com/google/auto/common/MoreTypes.java
|
MoreTypes.nonObjectSuperclass
|
public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements,
DeclaredType type) {
checkNotNull(types);
checkNotNull(elements);
checkNotNull(type);
final TypeMirror objectType =
elements.getTypeElement(Object.class.getCanonicalName()).asType();
// It's guaranteed there's only a single CLASS superclass because java doesn't have multiple
// class inheritance.
TypeMirror superclass =
getOnlyElement(
FluentIterable.from(types.directSupertypes(type))
.filter(
new Predicate<TypeMirror>() {
@Override
public boolean apply(TypeMirror input) {
return input.getKind().equals(TypeKind.DECLARED)
&& (MoreElements.asType(MoreTypes.asDeclared(input).asElement()))
.getKind()
.equals(ElementKind.CLASS)
&& !types.isSameType(objectType, input);
}
}),
null);
return superclass != null
? Optional.of(MoreTypes.asDeclared(superclass))
: Optional.<DeclaredType>absent();
}
|
java
|
public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements,
DeclaredType type) {
checkNotNull(types);
checkNotNull(elements);
checkNotNull(type);
final TypeMirror objectType =
elements.getTypeElement(Object.class.getCanonicalName()).asType();
// It's guaranteed there's only a single CLASS superclass because java doesn't have multiple
// class inheritance.
TypeMirror superclass =
getOnlyElement(
FluentIterable.from(types.directSupertypes(type))
.filter(
new Predicate<TypeMirror>() {
@Override
public boolean apply(TypeMirror input) {
return input.getKind().equals(TypeKind.DECLARED)
&& (MoreElements.asType(MoreTypes.asDeclared(input).asElement()))
.getKind()
.equals(ElementKind.CLASS)
&& !types.isSameType(objectType, input);
}
}),
null);
return superclass != null
? Optional.of(MoreTypes.asDeclared(superclass))
: Optional.<DeclaredType>absent();
}
|
[
"public",
"static",
"Optional",
"<",
"DeclaredType",
">",
"nonObjectSuperclass",
"(",
"final",
"Types",
"types",
",",
"Elements",
"elements",
",",
"DeclaredType",
"type",
")",
"{",
"checkNotNull",
"(",
"types",
")",
";",
"checkNotNull",
"(",
"elements",
")",
";",
"checkNotNull",
"(",
"type",
")",
";",
"final",
"TypeMirror",
"objectType",
"=",
"elements",
".",
"getTypeElement",
"(",
"Object",
".",
"class",
".",
"getCanonicalName",
"(",
")",
")",
".",
"asType",
"(",
")",
";",
"// It's guaranteed there's only a single CLASS superclass because java doesn't have multiple",
"// class inheritance.",
"TypeMirror",
"superclass",
"=",
"getOnlyElement",
"(",
"FluentIterable",
".",
"from",
"(",
"types",
".",
"directSupertypes",
"(",
"type",
")",
")",
".",
"filter",
"(",
"new",
"Predicate",
"<",
"TypeMirror",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"TypeMirror",
"input",
")",
"{",
"return",
"input",
".",
"getKind",
"(",
")",
".",
"equals",
"(",
"TypeKind",
".",
"DECLARED",
")",
"&&",
"(",
"MoreElements",
".",
"asType",
"(",
"MoreTypes",
".",
"asDeclared",
"(",
"input",
")",
".",
"asElement",
"(",
")",
")",
")",
".",
"getKind",
"(",
")",
".",
"equals",
"(",
"ElementKind",
".",
"CLASS",
")",
"&&",
"!",
"types",
".",
"isSameType",
"(",
"objectType",
",",
"input",
")",
";",
"}",
"}",
")",
",",
"null",
")",
";",
"return",
"superclass",
"!=",
"null",
"?",
"Optional",
".",
"of",
"(",
"MoreTypes",
".",
"asDeclared",
"(",
"superclass",
")",
")",
":",
"Optional",
".",
"<",
"DeclaredType",
">",
"absent",
"(",
")",
";",
"}"
] |
Returns the non-object superclass of the type with the proper type parameters.
An absent Optional is returned if there is no non-Object superclass.
|
[
"Returns",
"the",
"non",
"-",
"object",
"superclass",
"of",
"the",
"type",
"with",
"the",
"proper",
"type",
"parameters",
".",
"An",
"absent",
"Optional",
"is",
"returned",
"if",
"there",
"is",
"no",
"non",
"-",
"Object",
"superclass",
"."
] |
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/MoreTypes.java#L881-L909
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.