-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ShadowBitmapFactory.java
413 lines (368 loc) · 14.3 KB
/
ShadowBitmapFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package org.robolectric.shadows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.robolectric.shadows.ImageUtil.getImageFromStream;
import static org.robolectric.util.reflector.Reflector.reflector;
import android.content.res.AssetManager.AssetInputStream;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.util.TypedValue;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ImageUtil.RobolectricBufferedImage;
import org.robolectric.util.Join;
import org.robolectric.util.Logger;
import org.robolectric.util.NamedStream;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Static;
@SuppressWarnings({"UnusedDeclaration"})
@Implements(BitmapFactory.class)
public class ShadowBitmapFactory {
private static Map<String, Point> widthAndHeightMap = new HashMap<>();
// Determines whether BitmapFactory.decode methods should allow invalid bitmap data and always
// return a Bitmap object. Currently defaults to true to preserve legacy behavior. A
// forthcoming release will switch the default to false, which is consistent with real Android.
private static boolean allowInvalidImageData = true;
@Implementation
protected static Bitmap decodeResourceStream(
Resources res, TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts) {
Bitmap bitmap =
reflector(BitmapFactoryReflector.class).decodeResourceStream(res, value, is, pad, opts);
if (value != null && value.string != null && value.string.toString().contains(".9.")) {
// todo: better support for nine-patches
ReflectionHelpers.callInstanceMethod(
bitmap, "setNinePatchChunk", ClassParameter.from(byte[].class, new byte[0]));
}
return bitmap;
}
@Implementation
protected static Bitmap decodeResource(Resources res, int id, BitmapFactory.Options options) {
if (id == 0) {
return null;
}
final TypedValue value = new TypedValue();
InputStream is = res.openRawResource(id, value);
String resourceName = res.getResourceName(id);
RobolectricBufferedImage image = getImageFromStream(resourceName, is);
if (!allowInvalidImageData && image == null) {
if (options != null) {
options.outWidth = -1;
options.outHeight = -1;
}
return null;
}
Bitmap bitmap = create("resource:" + resourceName, options, image);
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.createdFromResId = id;
return bitmap;
}
@Implementation
protected static Bitmap decodeFile(String pathName) {
return decodeFile(pathName, null);
}
@SuppressWarnings("Var")
@Implementation
protected static Bitmap decodeFile(String pathName, BitmapFactory.Options options) {
// If a real file is used, attempt to get the image size from that file.
RobolectricBufferedImage image = null;
if (pathName != null && new File(pathName).exists()) {
try (FileInputStream fileInputStream = new FileInputStream(pathName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {
image = getImageFromStream(pathName, bufferedInputStream);
} catch (IOException e) {
Logger.warn("Error getting size of bitmap file", e);
}
}
if (!allowInvalidImageData && image == null) {
if (options != null) {
options.outWidth = -1;
options.outHeight = -1;
}
return null;
}
Bitmap bitmap = create("file:" + pathName, options, image);
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.createdFromPath = pathName;
return bitmap;
}
@SuppressWarnings({"ObjectToString", "Var"})
@Implementation
protected static Bitmap decodeFileDescriptor(
FileDescriptor fd, Rect outPadding, BitmapFactory.Options opts) {
RobolectricBufferedImage image = null;
// If a real FileDescriptor is used, attempt to get the image size.
if (fd != null && fd.valid()) {
try (FileInputStream fileInputStream = new FileInputStream(fd);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); ) {
image = getImageFromStream(bufferedInputStream);
} catch (IOException e) {
Logger.warn("Error getting size of bitmap file", e);
}
}
if (!allowInvalidImageData && image == null) {
if (opts != null) {
opts.outWidth = -1;
opts.outHeight = -1;
}
return null;
}
Bitmap bitmap = create("fd:" + fd, outPadding, opts, null, image);
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.createdFromFileDescriptor = fd;
return bitmap;
}
@Implementation
protected static Bitmap decodeStream(InputStream is) {
return decodeStream(is, null, null);
}
@Implementation
protected static Bitmap decodeStream(
InputStream is, Rect outPadding, BitmapFactory.Options opts) {
byte[] ninePatchChunk = null;
if (is instanceof AssetInputStream) {
ShadowAssetInputStream sais = Shadow.extract(is);
if (sais.isNinePatch()) {
ninePatchChunk = new byte[0];
}
if (sais.getDelegate() != null) {
is = sais.getDelegate();
}
}
try {
if (is != null) {
is.reset();
}
} catch (IOException e) {
// ignore
}
boolean isNamedStream = is instanceof NamedStream;
String name = isNamedStream ? is.toString().replace("stream for ", "") : null;
RobolectricBufferedImage image = isNamedStream ? null : getImageFromStream(is);
if (!allowInvalidImageData && image == null) {
if (opts != null) {
opts.outWidth = -1;
opts.outHeight = -1;
}
return null;
}
Bitmap bitmap = create(name, outPadding, opts, null, image);
ReflectionHelpers.callInstanceMethod(
bitmap, "setNinePatchChunk", ClassParameter.from(byte[].class, ninePatchChunk));
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.createdFromStream = is;
if (image != null && opts != null) {
opts.outMimeType = image.getMimeType();
}
return bitmap;
}
@Implementation
protected static Bitmap decodeByteArray(byte[] data, int offset, int length) {
Bitmap bitmap = decodeByteArray(data, offset, length, new BitmapFactory.Options());
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.createdFromBytes = data;
return bitmap;
}
@Implementation
protected static Bitmap decodeByteArray(
byte[] data, int offset, int length, BitmapFactory.Options opts) {
String desc = new String(data, UTF_8);
if (offset != 0 || length != data.length) {
desc += " bytes " + offset + ".." + length;
}
ByteArrayInputStream is = new ByteArrayInputStream(data, offset, length);
RobolectricBufferedImage image = getImageFromStream(is);
if (!allowInvalidImageData && image == null) {
if (opts != null) {
opts.outWidth = -1;
opts.outHeight = -1;
}
return null;
}
Bitmap bitmap = create(desc, opts, image);
return bitmap;
}
static Bitmap create(String name) {
return create(name, null);
}
/**
* @deprecated Use {@link Bitmap#createBitmap(int, int, Config)} to create a simple Bitmap or any
* of the BitmapFactory.decode methods with real image data.
*/
@Deprecated
public static Bitmap create(String name, BitmapFactory.Options options) {
return create(name, options, (Point) null);
}
/**
* @deprecated Use {@link Bitmap#createBitmap(int, int, Config)} to create a simple Bitmap or any
* of the BitmapFactory.decode methods with real image data.
*/
@Deprecated
public static Bitmap create(
final String name, final BitmapFactory.Options options, final Point widthAndHeight) {
return create(name, null, options, widthAndHeight, null);
}
private static Bitmap create(
final String name,
final BitmapFactory.Options options,
final RobolectricBufferedImage image) {
return create(name, null, options, null, image);
}
private static Bitmap create(
final String name,
final Rect outPadding,
final BitmapFactory.Options options,
final Point widthAndHeightOverride,
final RobolectricBufferedImage image) {
Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class);
ShadowBitmap shadowBitmap = Shadow.extract(bitmap);
shadowBitmap.appendDescription(name == null ? "Bitmap" : "Bitmap for " + name);
Bitmap.Config config;
if (options != null && options.inPreferredConfig != null) {
config = options.inPreferredConfig;
} else {
config = Bitmap.Config.ARGB_8888;
}
shadowBitmap.setConfig(config);
String optionsString = stringify(options);
if (!optionsString.isEmpty()) {
shadowBitmap.appendDescription(" with options ");
shadowBitmap.appendDescription(optionsString);
}
Point p = new Point(selectWidthAndHeight(name, widthAndHeightOverride, image));
if (options != null && options.inSampleSize > 1) {
p.x = p.x / options.inSampleSize;
p.y = p.y / options.inSampleSize;
p.x = p.x == 0 ? 1 : p.x;
p.y = p.y == 0 ? 1 : p.y;
}
shadowBitmap.setWidth(p.x);
shadowBitmap.setHeight(p.y);
if (image != null) {
BufferedImage bufferedImage = new BufferedImage(p.x, p.y, BufferedImage.TYPE_INT_ARGB);
// Copy the image as TYPE_INT_ARGB for fast comparison (sameAs).
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image.getBufferedImage(), 0, 0, null);
g.dispose();
shadowBitmap.setBufferedImage(bufferedImage);
} else {
shadowBitmap.setPixelsInternal(new int[p.x * p.y], 0, 0, 0, 0, p.x, p.y);
}
if (options != null) {
options.outWidth = p.x;
options.outHeight = p.y;
shadowBitmap.setMutable(options.inMutable);
}
if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.KITKAT) {
ReflectionHelpers.callStaticMethod(
BitmapFactory.class,
"setDensityFromOptions",
ClassParameter.from(Bitmap.class, bitmap),
ClassParameter.from(BitmapFactory.Options.class, options));
} else {
bitmap =
ReflectionHelpers.callStaticMethod(
BitmapFactory.class,
"finishDecode",
ClassParameter.from(Bitmap.class, bitmap),
ClassParameter.from(Rect.class, outPadding),
ClassParameter.from(BitmapFactory.Options.class, options));
}
return bitmap;
}
/** @deprecated Use any of the BitmapFactory.decode methods with real image data. */
@Deprecated
public static void provideWidthAndHeightHints(Uri uri, int width, int height) {
widthAndHeightMap.put(uri.toString(), new Point(width, height));
}
/** @deprecated Use any of the BitmapFactory.decode methods with real image data. */
@Deprecated
public static void provideWidthAndHeightHints(int resourceId, int width, int height) {
widthAndHeightMap.put(
"resource:"
+ RuntimeEnvironment.getApplication().getResources().getResourceName(resourceId),
new Point(width, height));
}
/** @deprecated Use any of the BitmapFactory.decode methods with real image data. */
@Deprecated
public static void provideWidthAndHeightHints(String file, int width, int height) {
widthAndHeightMap.put("file:" + file, new Point(width, height));
}
/** @deprecated Use any of the BitmapFactory.decode methods with real image data. */
@Deprecated
@SuppressWarnings("ObjectToString")
public static void provideWidthAndHeightHints(FileDescriptor fd, int width, int height) {
widthAndHeightMap.put("fd:" + fd, new Point(width, height));
}
private static String stringify(BitmapFactory.Options options) {
if (options == null) return "";
List<String> opts = new ArrayList<>();
if (options.inJustDecodeBounds) opts.add("inJustDecodeBounds");
if (options.inSampleSize > 1) opts.add("inSampleSize=" + options.inSampleSize);
return Join.join(", ", opts);
}
@Resetter
public static void reset() {
widthAndHeightMap.clear();
allowInvalidImageData = true;
}
private static Point selectWidthAndHeight(
final String name,
final Point widthAndHeightOverride,
final RobolectricBufferedImage robolectricBufferedImage) {
final Point widthAndHeightFromMap = widthAndHeightMap.get(name);
if (widthAndHeightFromMap != null) {
return widthAndHeightFromMap;
}
if (robolectricBufferedImage != null) {
return robolectricBufferedImage.getWidthAndHeight();
}
if (widthAndHeightOverride != null) {
return widthAndHeightOverride;
}
return new Point(100, 100);
}
/**
* Whether the BitmapFactory.decode methods, such as {@link
* BitmapFactory#decodeStream(InputStream, Rect, Options)} should allow invalid image data and
* always return Bitmap objects. If set to false, BitmapFactory.decode methods will be consistent
* with real Android, and return null Bitmap values and set {@link BitmapFactory.Options#outWidth}
* and {@link BitmapFactory.Options#outHeight} to -1.
*
* @param allowInvalidImageData whether invalid bitmap data is allowed and BitmapFactory should
* always return Bitmap objects.
*/
public static void setAllowInvalidImageData(boolean allowInvalidImageData) {
ShadowBitmapFactory.allowInvalidImageData = allowInvalidImageData;
}
@ForType(BitmapFactory.class)
interface BitmapFactoryReflector {
@Static
@Direct
Bitmap decodeResourceStream(
Resources res, TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts);
}
}