1#define LOG_TAG "GraphicsJNI"
2
3#include <unistd.h>
4#include <sys/mman.h>
5
6#include "jni.h"
7#include "JNIHelp.h"
8#include "GraphicsJNI.h"
9
10#include "SkCanvas.h"
11#include "SkDevice.h"
12#include "SkMath.h"
13#include "SkRegion.h"
14#include <android_runtime/AndroidRuntime.h>
15#include <cutils/ashmem.h>
16#include <hwui/Canvas.h>
17
18#include <Caches.h>
19#include <TextureCache.h>
20
21void doThrowNPE(JNIEnv* env) {
22    jniThrowNullPointerException(env, NULL);
23}
24
25void doThrowAIOOBE(JNIEnv* env) {
26    jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
27}
28
29void doThrowRE(JNIEnv* env, const char* msg) {
30    jniThrowRuntimeException(env, msg);
31}
32
33void doThrowIAE(JNIEnv* env, const char* msg) {
34    jniThrowException(env, "java/lang/IllegalArgumentException", msg);
35}
36
37void doThrowISE(JNIEnv* env, const char* msg) {
38    jniThrowException(env, "java/lang/IllegalStateException", msg);
39}
40
41void doThrowOOME(JNIEnv* env, const char* msg) {
42    jniThrowException(env, "java/lang/OutOfMemoryError", msg);
43}
44
45void doThrowIOE(JNIEnv* env, const char* msg) {
46    jniThrowException(env, "java/io/IOException", msg);
47}
48
49bool GraphicsJNI::hasException(JNIEnv *env) {
50    if (env->ExceptionCheck() != 0) {
51        ALOGE("*** Uncaught exception returned from Java call!\n");
52        env->ExceptionDescribe();
53        return true;
54    }
55    return false;
56}
57
58///////////////////////////////////////////////////////////////////////////////
59
60AutoJavaFloatArray::AutoJavaFloatArray(JNIEnv* env, jfloatArray array,
61                                       int minLength, JNIAccess access)
62: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
63    SkASSERT(env);
64    if (array) {
65        fLen = env->GetArrayLength(array);
66        if (fLen < minLength) {
67            sk_throw();
68        }
69        fPtr = env->GetFloatArrayElements(array, NULL);
70    }
71    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
72}
73
74AutoJavaFloatArray::~AutoJavaFloatArray() {
75    if (fPtr) {
76        fEnv->ReleaseFloatArrayElements(fArray, fPtr, fReleaseMode);
77    }
78}
79
80AutoJavaIntArray::AutoJavaIntArray(JNIEnv* env, jintArray array,
81                                       int minLength)
82: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
83    SkASSERT(env);
84    if (array) {
85        fLen = env->GetArrayLength(array);
86        if (fLen < minLength) {
87            sk_throw();
88        }
89        fPtr = env->GetIntArrayElements(array, NULL);
90    }
91}
92
93AutoJavaIntArray::~AutoJavaIntArray() {
94    if (fPtr) {
95        fEnv->ReleaseIntArrayElements(fArray, fPtr, 0);
96    }
97}
98
99AutoJavaShortArray::AutoJavaShortArray(JNIEnv* env, jshortArray array,
100                                       int minLength, JNIAccess access)
101: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
102    SkASSERT(env);
103    if (array) {
104        fLen = env->GetArrayLength(array);
105        if (fLen < minLength) {
106            sk_throw();
107        }
108        fPtr = env->GetShortArrayElements(array, NULL);
109    }
110    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
111}
112
113AutoJavaShortArray::~AutoJavaShortArray() {
114    if (fPtr) {
115        fEnv->ReleaseShortArrayElements(fArray, fPtr, fReleaseMode);
116    }
117}
118
119AutoJavaByteArray::AutoJavaByteArray(JNIEnv* env, jbyteArray array,
120                                       int minLength)
121: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
122    SkASSERT(env);
123    if (array) {
124        fLen = env->GetArrayLength(array);
125        if (fLen < minLength) {
126            sk_throw();
127        }
128        fPtr = env->GetByteArrayElements(array, NULL);
129    }
130}
131
132AutoJavaByteArray::~AutoJavaByteArray() {
133    if (fPtr) {
134        fEnv->ReleaseByteArrayElements(fArray, fPtr, 0);
135    }
136}
137
138///////////////////////////////////////////////////////////////////////////////
139
140static jclass   gRect_class;
141static jfieldID gRect_leftFieldID;
142static jfieldID gRect_topFieldID;
143static jfieldID gRect_rightFieldID;
144static jfieldID gRect_bottomFieldID;
145
146static jclass   gRectF_class;
147static jfieldID gRectF_leftFieldID;
148static jfieldID gRectF_topFieldID;
149static jfieldID gRectF_rightFieldID;
150static jfieldID gRectF_bottomFieldID;
151
152static jclass   gPoint_class;
153static jfieldID gPoint_xFieldID;
154static jfieldID gPoint_yFieldID;
155
156static jclass   gPointF_class;
157static jfieldID gPointF_xFieldID;
158static jfieldID gPointF_yFieldID;
159
160static jclass   gBitmap_class;
161static jfieldID gBitmap_nativePtr;
162static jmethodID gBitmap_constructorMethodID;
163static jmethodID gBitmap_reinitMethodID;
164static jmethodID gBitmap_getAllocationByteCountMethodID;
165
166static jclass   gBitmapConfig_class;
167static jfieldID gBitmapConfig_nativeInstanceID;
168
169static jclass   gBitmapRegionDecoder_class;
170static jmethodID gBitmapRegionDecoder_constructorMethodID;
171
172static jclass   gCanvas_class;
173static jfieldID gCanvas_nativeInstanceID;
174
175static jclass   gPicture_class;
176static jfieldID gPicture_nativeInstanceID;
177
178static jclass   gRegion_class;
179static jfieldID gRegion_nativeInstanceID;
180static jmethodID gRegion_constructorMethodID;
181
182static jclass    gByte_class;
183static jobject   gVMRuntime;
184static jclass    gVMRuntime_class;
185static jmethodID gVMRuntime_newNonMovableArray;
186static jmethodID gVMRuntime_addressOf;
187
188///////////////////////////////////////////////////////////////////////////////
189
190void GraphicsJNI::get_jrect(JNIEnv* env, jobject obj, int* L, int* T, int* R, int* B)
191{
192    SkASSERT(env->IsInstanceOf(obj, gRect_class));
193
194    *L = env->GetIntField(obj, gRect_leftFieldID);
195    *T = env->GetIntField(obj, gRect_topFieldID);
196    *R = env->GetIntField(obj, gRect_rightFieldID);
197    *B = env->GetIntField(obj, gRect_bottomFieldID);
198}
199
200void GraphicsJNI::set_jrect(JNIEnv* env, jobject obj, int L, int T, int R, int B)
201{
202    SkASSERT(env->IsInstanceOf(obj, gRect_class));
203
204    env->SetIntField(obj, gRect_leftFieldID, L);
205    env->SetIntField(obj, gRect_topFieldID, T);
206    env->SetIntField(obj, gRect_rightFieldID, R);
207    env->SetIntField(obj, gRect_bottomFieldID, B);
208}
209
210SkIRect* GraphicsJNI::jrect_to_irect(JNIEnv* env, jobject obj, SkIRect* ir)
211{
212    SkASSERT(env->IsInstanceOf(obj, gRect_class));
213
214    ir->set(env->GetIntField(obj, gRect_leftFieldID),
215            env->GetIntField(obj, gRect_topFieldID),
216            env->GetIntField(obj, gRect_rightFieldID),
217            env->GetIntField(obj, gRect_bottomFieldID));
218    return ir;
219}
220
221void GraphicsJNI::irect_to_jrect(const SkIRect& ir, JNIEnv* env, jobject obj)
222{
223    SkASSERT(env->IsInstanceOf(obj, gRect_class));
224
225    env->SetIntField(obj, gRect_leftFieldID, ir.fLeft);
226    env->SetIntField(obj, gRect_topFieldID, ir.fTop);
227    env->SetIntField(obj, gRect_rightFieldID, ir.fRight);
228    env->SetIntField(obj, gRect_bottomFieldID, ir.fBottom);
229}
230
231SkRect* GraphicsJNI::jrectf_to_rect(JNIEnv* env, jobject obj, SkRect* r)
232{
233    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
234
235    r->set(env->GetFloatField(obj, gRectF_leftFieldID),
236           env->GetFloatField(obj, gRectF_topFieldID),
237           env->GetFloatField(obj, gRectF_rightFieldID),
238           env->GetFloatField(obj, gRectF_bottomFieldID));
239    return r;
240}
241
242SkRect* GraphicsJNI::jrect_to_rect(JNIEnv* env, jobject obj, SkRect* r)
243{
244    SkASSERT(env->IsInstanceOf(obj, gRect_class));
245
246    r->set(SkIntToScalar(env->GetIntField(obj, gRect_leftFieldID)),
247           SkIntToScalar(env->GetIntField(obj, gRect_topFieldID)),
248           SkIntToScalar(env->GetIntField(obj, gRect_rightFieldID)),
249           SkIntToScalar(env->GetIntField(obj, gRect_bottomFieldID)));
250    return r;
251}
252
253void GraphicsJNI::rect_to_jrectf(const SkRect& r, JNIEnv* env, jobject obj)
254{
255    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
256
257    env->SetFloatField(obj, gRectF_leftFieldID, SkScalarToFloat(r.fLeft));
258    env->SetFloatField(obj, gRectF_topFieldID, SkScalarToFloat(r.fTop));
259    env->SetFloatField(obj, gRectF_rightFieldID, SkScalarToFloat(r.fRight));
260    env->SetFloatField(obj, gRectF_bottomFieldID, SkScalarToFloat(r.fBottom));
261}
262
263SkIPoint* GraphicsJNI::jpoint_to_ipoint(JNIEnv* env, jobject obj, SkIPoint* point)
264{
265    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
266
267    point->set(env->GetIntField(obj, gPoint_xFieldID),
268               env->GetIntField(obj, gPoint_yFieldID));
269    return point;
270}
271
272void GraphicsJNI::ipoint_to_jpoint(const SkIPoint& ir, JNIEnv* env, jobject obj)
273{
274    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
275
276    env->SetIntField(obj, gPoint_xFieldID, ir.fX);
277    env->SetIntField(obj, gPoint_yFieldID, ir.fY);
278}
279
280SkPoint* GraphicsJNI::jpointf_to_point(JNIEnv* env, jobject obj, SkPoint* point)
281{
282    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
283
284    point->set(env->GetIntField(obj, gPointF_xFieldID),
285               env->GetIntField(obj, gPointF_yFieldID));
286    return point;
287}
288
289void GraphicsJNI::point_to_jpointf(const SkPoint& r, JNIEnv* env, jobject obj)
290{
291    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
292
293    env->SetFloatField(obj, gPointF_xFieldID, SkScalarToFloat(r.fX));
294    env->SetFloatField(obj, gPointF_yFieldID, SkScalarToFloat(r.fY));
295}
296
297// This enum must keep these int values, to match the int values
298// in the java Bitmap.Config enum.
299enum LegacyBitmapConfig {
300    kNo_LegacyBitmapConfig          = 0,
301    kA8_LegacyBitmapConfig          = 1,
302    kIndex8_LegacyBitmapConfig      = 2,
303    kRGB_565_LegacyBitmapConfig     = 3,
304    kARGB_4444_LegacyBitmapConfig   = 4,
305    kARGB_8888_LegacyBitmapConfig   = 5,
306
307    kLastEnum_LegacyBitmapConfig = kARGB_8888_LegacyBitmapConfig
308};
309
310jint GraphicsJNI::colorTypeToLegacyBitmapConfig(SkColorType colorType) {
311    switch (colorType) {
312        case kN32_SkColorType:
313            return kARGB_8888_LegacyBitmapConfig;
314        case kARGB_4444_SkColorType:
315            return kARGB_4444_LegacyBitmapConfig;
316        case kRGB_565_SkColorType:
317            return kRGB_565_LegacyBitmapConfig;
318        case kIndex_8_SkColorType:
319            return kIndex8_LegacyBitmapConfig;
320        case kAlpha_8_SkColorType:
321            return kA8_LegacyBitmapConfig;
322        case kUnknown_SkColorType:
323        default:
324            break;
325    }
326    return kNo_LegacyBitmapConfig;
327}
328
329SkColorType GraphicsJNI::legacyBitmapConfigToColorType(jint legacyConfig) {
330    const uint8_t gConfig2ColorType[] = {
331        kUnknown_SkColorType,
332        kAlpha_8_SkColorType,
333        kIndex_8_SkColorType,
334        kRGB_565_SkColorType,
335        kARGB_4444_SkColorType,
336        kN32_SkColorType
337    };
338
339    if (legacyConfig < 0 || legacyConfig > kLastEnum_LegacyBitmapConfig) {
340        legacyConfig = kNo_LegacyBitmapConfig;
341    }
342    return static_cast<SkColorType>(gConfig2ColorType[legacyConfig]);
343}
344
345android::Bitmap* GraphicsJNI::getBitmap(JNIEnv* env, jobject bitmap) {
346    SkASSERT(env);
347    SkASSERT(bitmap);
348    SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
349    jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativePtr);
350    android::Bitmap* b = reinterpret_cast<android::Bitmap*>(bitmapHandle);
351    SkASSERT(b);
352    return b;
353}
354
355void GraphicsJNI::getSkBitmap(JNIEnv* env, jobject bitmap, SkBitmap* outBitmap) {
356    getBitmap(env, bitmap)->getSkBitmap(outBitmap);
357}
358
359SkPixelRef* GraphicsJNI::refSkPixelRef(JNIEnv* env, jobject bitmap) {
360    return getBitmap(env, bitmap)->refPixelRef();
361}
362
363SkColorType GraphicsJNI::getNativeBitmapColorType(JNIEnv* env, jobject jconfig) {
364    SkASSERT(env);
365    if (NULL == jconfig) {
366        return kUnknown_SkColorType;
367    }
368    SkASSERT(env->IsInstanceOf(jconfig, gBitmapConfig_class));
369    int c = env->GetIntField(jconfig, gBitmapConfig_nativeInstanceID);
370    return legacyBitmapConfigToColorType(c);
371}
372
373android::Canvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) {
374    SkASSERT(env);
375    SkASSERT(canvas);
376    SkASSERT(env->IsInstanceOf(canvas, gCanvas_class));
377    jlong canvasHandle = env->GetLongField(canvas, gCanvas_nativeInstanceID);
378    if (!canvasHandle) {
379        return NULL;
380    }
381    return reinterpret_cast<android::Canvas*>(canvasHandle);
382}
383
384SkRegion* GraphicsJNI::getNativeRegion(JNIEnv* env, jobject region)
385{
386    SkASSERT(env);
387    SkASSERT(region);
388    SkASSERT(env->IsInstanceOf(region, gRegion_class));
389    jlong regionHandle = env->GetLongField(region, gRegion_nativeInstanceID);
390    SkRegion* r = reinterpret_cast<SkRegion*>(regionHandle);
391    SkASSERT(r);
392    return r;
393}
394
395///////////////////////////////////////////////////////////////////////////////////////////
396
397// Assert that bitmap's SkAlphaType is consistent with isPremultiplied.
398static void assert_premultiplied(const SkImageInfo& info, bool isPremultiplied) {
399    // kOpaque_SkAlphaType and kIgnore_SkAlphaType mean that isPremultiplied is
400    // irrelevant. This just tests to ensure that the SkAlphaType is not
401    // opposite of isPremultiplied.
402    if (isPremultiplied) {
403        SkASSERT(info.alphaType() != kUnpremul_SkAlphaType);
404    } else {
405        SkASSERT(info.alphaType() != kPremul_SkAlphaType);
406    }
407}
408
409jobject GraphicsJNI::createBitmap(JNIEnv* env, android::Bitmap* bitmap,
410        int bitmapCreateFlags, jbyteArray ninePatchChunk, jobject ninePatchInsets,
411        int density) {
412    bool isMutable = bitmapCreateFlags & kBitmapCreateFlag_Mutable;
413    bool isPremultiplied = bitmapCreateFlags & kBitmapCreateFlag_Premultiplied;
414    // The caller needs to have already set the alpha type properly, so the
415    // native SkBitmap stays in sync with the Java Bitmap.
416    assert_premultiplied(bitmap->info(), isPremultiplied);
417
418    jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
419            reinterpret_cast<jlong>(bitmap), bitmap->javaByteArray(),
420            bitmap->width(), bitmap->height(), density, isMutable, isPremultiplied,
421            ninePatchChunk, ninePatchInsets);
422    hasException(env); // For the side effect of logging.
423    return obj;
424}
425
426void GraphicsJNI::reinitBitmap(JNIEnv* env, jobject javaBitmap, const SkImageInfo& info,
427        bool isPremultiplied)
428{
429    // The caller needs to have already set the alpha type properly, so the
430    // native SkBitmap stays in sync with the Java Bitmap.
431    assert_premultiplied(info, isPremultiplied);
432
433    env->CallVoidMethod(javaBitmap, gBitmap_reinitMethodID,
434            info.width(), info.height(), isPremultiplied);
435}
436
437int GraphicsJNI::getBitmapAllocationByteCount(JNIEnv* env, jobject javaBitmap)
438{
439    return env->CallIntMethod(javaBitmap, gBitmap_getAllocationByteCountMethodID);
440}
441
442jobject GraphicsJNI::createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap)
443{
444    SkASSERT(bitmap != NULL);
445
446    jobject obj = env->NewObject(gBitmapRegionDecoder_class,
447            gBitmapRegionDecoder_constructorMethodID,
448            reinterpret_cast<jlong>(bitmap));
449    hasException(env); // For the side effect of logging.
450    return obj;
451}
452
453jobject GraphicsJNI::createRegion(JNIEnv* env, SkRegion* region)
454{
455    SkASSERT(region != NULL);
456    jobject obj = env->NewObject(gRegion_class, gRegion_constructorMethodID,
457                                 reinterpret_cast<jlong>(region), 0);
458    hasException(env); // For the side effect of logging.
459    return obj;
460}
461
462static JNIEnv* vm2env(JavaVM* vm)
463{
464    JNIEnv* env = NULL;
465    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || NULL == env)
466    {
467        SkDebugf("------- [%p] vm->GetEnv() failed\n", vm);
468        sk_throw();
469    }
470    return env;
471}
472
473///////////////////////////////////////////////////////////////////////////////
474
475static bool computeAllocationSize(const SkBitmap& bitmap, size_t* size) {
476    int32_t rowBytes32 = SkToS32(bitmap.rowBytes());
477    int64_t bigSize = (int64_t)bitmap.height() * rowBytes32;
478    if (rowBytes32 < 0 || !sk_64_isS32(bigSize)) {
479        return false; // allocation will be too large
480    }
481
482    *size = sk_64_asS32(bigSize);
483    return true;
484}
485
486android::Bitmap* GraphicsJNI::allocateJavaPixelRef(JNIEnv* env, SkBitmap* bitmap,
487                                             SkColorTable* ctable) {
488    const SkImageInfo& info = bitmap->info();
489    if (info.colorType() == kUnknown_SkColorType) {
490        doThrowIAE(env, "unknown bitmap configuration");
491        return NULL;
492    }
493
494    size_t size;
495    if (!computeAllocationSize(*bitmap, &size)) {
496        return NULL;
497    }
498
499    // we must respect the rowBytes value already set on the bitmap instead of
500    // attempting to compute our own.
501    const size_t rowBytes = bitmap->rowBytes();
502
503    jbyteArray arrayObj = (jbyteArray) env->CallObjectMethod(gVMRuntime,
504                                                             gVMRuntime_newNonMovableArray,
505                                                             gByte_class, size);
506    if (env->ExceptionCheck() != 0) {
507        return NULL;
508    }
509    SkASSERT(arrayObj);
510    jbyte* addr = (jbyte*) env->CallLongMethod(gVMRuntime, gVMRuntime_addressOf, arrayObj);
511    if (env->ExceptionCheck() != 0) {
512        return NULL;
513    }
514    SkASSERT(addr);
515    android::Bitmap* wrapper = new android::Bitmap(env, arrayObj, (void*) addr,
516            info, rowBytes, ctable);
517    wrapper->getSkBitmap(bitmap);
518    // since we're already allocated, we lockPixels right away
519    // HeapAllocator behaves this way too
520    bitmap->lockPixels();
521
522    return wrapper;
523}
524
525struct AndroidPixelRefContext {
526    int32_t stableID;
527};
528
529static void allocatePixelsReleaseProc(void* ptr, void* ctx) {
530    AndroidPixelRefContext* context = (AndroidPixelRefContext*)ctx;
531    if (android::uirenderer::Caches::hasInstance()) {
532         android::uirenderer::Caches::getInstance().textureCache.releaseTexture(context->stableID);
533    }
534
535    sk_free(ptr);
536    delete context;
537}
538
539bool GraphicsJNI::allocatePixels(JNIEnv* env, SkBitmap* bitmap, SkColorTable* ctable) {
540    const SkImageInfo& info = bitmap->info();
541    if (info.colorType() == kUnknown_SkColorType) {
542        doThrowIAE(env, "unknown bitmap configuration");
543        return NULL;
544    }
545
546    size_t size;
547    if (!computeAllocationSize(*bitmap, &size)) {
548        return false;
549    }
550
551    // we must respect the rowBytes value already set on the bitmap instead of
552    // attempting to compute our own.
553    const size_t rowBytes = bitmap->rowBytes();
554
555    void* addr = sk_malloc_flags(size, 0);
556    if (NULL == addr) {
557        return false;
558    }
559
560    AndroidPixelRefContext* context = new AndroidPixelRefContext;
561    SkMallocPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rowBytes, ctable, addr,
562                                                         &allocatePixelsReleaseProc, context);
563    if (!pr) {
564        delete context;
565        return false;
566    }
567
568    // set the stableID in the context so that it can be used later in
569    // allocatePixelsReleaseProc to remove the texture from the cache.
570    context->stableID = pr->getStableID();
571
572    bitmap->setPixelRef(pr)->unref();
573    // since we're already allocated, we can lockPixels right away
574    bitmap->lockPixels();
575
576    return true;
577}
578
579android::Bitmap* GraphicsJNI::allocateAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
580                                                     SkColorTable* ctable) {
581    int fd;
582
583    const SkImageInfo& info = bitmap->info();
584    if (info.colorType() == kUnknown_SkColorType) {
585        doThrowIAE(env, "unknown bitmap configuration");
586        return nullptr;
587    }
588
589    size_t size;
590    if (!computeAllocationSize(*bitmap, &size)) {
591        return nullptr;
592    }
593
594    // we must respect the rowBytes value already set on the bitmap instead of
595    // attempting to compute our own.
596    const size_t rowBytes = bitmap->rowBytes();
597
598    // Create new ashmem region with read/write priv
599    fd = ashmem_create_region("bitmap", size);
600    if (fd < 0) {
601        return nullptr;
602    }
603
604    void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
605    if (addr == MAP_FAILED) {
606        close(fd);
607        return nullptr;
608    }
609
610    if (ashmem_set_prot_region(fd, PROT_READ) < 0) {
611        munmap(addr, size);
612        close(fd);
613        return nullptr;
614    }
615
616    android::Bitmap* wrapper = new android::Bitmap(addr, fd, size, info, rowBytes, ctable);
617    wrapper->getSkBitmap(bitmap);
618    // since we're already allocated, we lockPixels right away
619    // HeapAllocator behaves this way too
620    bitmap->lockPixels();
621
622    return wrapper;
623}
624
625android::Bitmap* GraphicsJNI::mapAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
626        SkColorTable* ctable, int fd, void* addr, size_t size, bool readOnly) {
627    const SkImageInfo& info = bitmap->info();
628    if (info.colorType() == kUnknown_SkColorType) {
629        doThrowIAE(env, "unknown bitmap configuration");
630        return nullptr;
631    }
632
633    if (!addr) {
634        // Map existing ashmem region if not already mapped.
635        int flags = readOnly ? (PROT_READ) : (PROT_READ | PROT_WRITE);
636        size = ashmem_get_size_region(fd);
637        addr = mmap(NULL, size, flags, MAP_SHARED, fd, 0);
638        if (addr == MAP_FAILED) {
639            return nullptr;
640        }
641    }
642
643    // we must respect the rowBytes value already set on the bitmap instead of
644    // attempting to compute our own.
645    const size_t rowBytes = bitmap->rowBytes();
646
647    android::Bitmap* wrapper = new android::Bitmap(addr, fd, size, info, rowBytes, ctable);
648    wrapper->getSkBitmap(bitmap);
649    if (readOnly) {
650        bitmap->pixelRef()->setImmutable();
651    }
652    // since we're already allocated, we lockPixels right away
653    // HeapAllocator behaves this way too
654    bitmap->lockPixels();
655
656    return wrapper;
657}
658
659///////////////////////////////////////////////////////////////////////////////
660
661JavaPixelAllocator::JavaPixelAllocator(JNIEnv* env) {
662    LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
663            "env->GetJavaVM failed");
664}
665
666JavaPixelAllocator::~JavaPixelAllocator() {
667    if (mStorage) {
668        mStorage->detachFromJava();
669    }
670}
671
672bool JavaPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
673    JNIEnv* env = vm2env(mJavaVM);
674
675    mStorage = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
676    return mStorage != nullptr;
677}
678
679////////////////////////////////////////////////////////////////////////////////
680
681RecyclingClippingPixelAllocator::RecyclingClippingPixelAllocator(
682        android::Bitmap* recycledBitmap, size_t recycledBytes)
683    : mRecycledBitmap(recycledBitmap)
684    , mRecycledBytes(recycledBytes)
685    , mSkiaBitmap(nullptr)
686    , mNeedsCopy(false)
687{}
688
689RecyclingClippingPixelAllocator::~RecyclingClippingPixelAllocator() {}
690
691bool RecyclingClippingPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
692    // Ensure that the caller did not pass in a NULL bitmap to the constructor or this
693    // function.
694    LOG_ALWAYS_FATAL_IF(!mRecycledBitmap);
695    LOG_ALWAYS_FATAL_IF(!bitmap);
696    mSkiaBitmap = bitmap;
697
698    // This behaves differently than the RecyclingPixelAllocator.  For backwards
699    // compatibility, the original color type of the recycled bitmap must be maintained.
700    if (mRecycledBitmap->info().colorType() != bitmap->colorType()) {
701        return false;
702    }
703
704    // The Skia bitmap specifies the width and height needed by the decoder.
705    // mRecycledBitmap specifies the width and height of the bitmap that we
706    // want to reuse.  Neither can be changed.  We will try to find a way
707    // to reuse the memory.
708    const int maxWidth = SkTMax(bitmap->width(), mRecycledBitmap->info().width());
709    const int maxHeight = SkTMax(bitmap->height(), mRecycledBitmap->info().height());
710    const SkImageInfo maxInfo = bitmap->info().makeWH(maxWidth, maxHeight);
711    const size_t rowBytes = maxInfo.minRowBytes();
712    const size_t bytesNeeded = maxInfo.getSafeSize(rowBytes);
713    if (bytesNeeded <= mRecycledBytes) {
714        // Here we take advantage of reconfigure() to reset the rowBytes and ctable
715        // of mRecycledBitmap.  It is very important that we pass in
716        // mRecycledBitmap->info() for the SkImageInfo.  According to the
717        // specification for BitmapRegionDecoder, we are not allowed to change
718        // the SkImageInfo.
719        mRecycledBitmap->reconfigure(mRecycledBitmap->info(), rowBytes, ctable);
720
721        // This call will give the bitmap the same pixelRef as mRecycledBitmap.
722        bitmap->setPixelRef(mRecycledBitmap->refPixelRef())->unref();
723
724        // Make sure that the recycled bitmap has the correct alpha type.
725        mRecycledBitmap->setAlphaType(bitmap->alphaType());
726
727        bitmap->notifyPixelsChanged();
728        bitmap->lockPixels();
729        mNeedsCopy = false;
730
731        // TODO: If the dimensions of the SkBitmap are smaller than those of
732        // mRecycledBitmap, should we zero the memory in mRecycledBitmap?
733        return true;
734    }
735
736    // In the event that mRecycledBitmap is not large enough, allocate new memory
737    // on the heap.
738    SkBitmap::HeapAllocator heapAllocator;
739
740    // We will need to copy from heap memory to mRecycledBitmap's memory after the
741    // decode is complete.
742    mNeedsCopy = true;
743
744    return heapAllocator.allocPixelRef(bitmap, ctable);
745}
746
747void RecyclingClippingPixelAllocator::copyIfNecessary() {
748    if (mNeedsCopy) {
749        SkPixelRef* recycledPixels = mRecycledBitmap->refPixelRef();
750        void* dst = recycledPixels->pixels();
751        const size_t dstRowBytes = mRecycledBitmap->rowBytes();
752        const size_t bytesToCopy = std::min(mRecycledBitmap->info().minRowBytes(),
753                mSkiaBitmap->info().minRowBytes());
754        const int rowsToCopy = std::min(mRecycledBitmap->info().height(),
755                mSkiaBitmap->info().height());
756        for (int y = 0; y < rowsToCopy; y++) {
757            memcpy(dst, mSkiaBitmap->getAddr(0, y), bytesToCopy);
758            dst = SkTAddOffset<void>(dst, dstRowBytes);
759        }
760        recycledPixels->notifyPixelsChanged();
761        recycledPixels->unref();
762    }
763    mRecycledBitmap = nullptr;
764    mSkiaBitmap = nullptr;
765}
766
767////////////////////////////////////////////////////////////////////////////////
768
769AshmemPixelAllocator::AshmemPixelAllocator(JNIEnv *env) {
770    LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
771            "env->GetJavaVM failed");
772}
773
774AshmemPixelAllocator::~AshmemPixelAllocator() {
775    if (mStorage) {
776        mStorage->detachFromJava();
777    }
778}
779
780bool AshmemPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
781    JNIEnv* env = vm2env(mJavaVM);
782    mStorage = GraphicsJNI::allocateAshmemPixelRef(env, bitmap, ctable);
783    return mStorage != nullptr;
784}
785
786////////////////////////////////////////////////////////////////////////////////
787
788static jclass make_globalref(JNIEnv* env, const char classname[])
789{
790    jclass c = env->FindClass(classname);
791    SkASSERT(c);
792    return (jclass) env->NewGlobalRef(c);
793}
794
795static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
796                                const char fieldname[], const char type[])
797{
798    jfieldID id = env->GetFieldID(clazz, fieldname, type);
799    SkASSERT(id);
800    return id;
801}
802
803int register_android_graphics_Graphics(JNIEnv* env)
804{
805    jmethodID m;
806    jclass c;
807
808    gRect_class = make_globalref(env, "android/graphics/Rect");
809    gRect_leftFieldID = getFieldIDCheck(env, gRect_class, "left", "I");
810    gRect_topFieldID = getFieldIDCheck(env, gRect_class, "top", "I");
811    gRect_rightFieldID = getFieldIDCheck(env, gRect_class, "right", "I");
812    gRect_bottomFieldID = getFieldIDCheck(env, gRect_class, "bottom", "I");
813
814    gRectF_class = make_globalref(env, "android/graphics/RectF");
815    gRectF_leftFieldID = getFieldIDCheck(env, gRectF_class, "left", "F");
816    gRectF_topFieldID = getFieldIDCheck(env, gRectF_class, "top", "F");
817    gRectF_rightFieldID = getFieldIDCheck(env, gRectF_class, "right", "F");
818    gRectF_bottomFieldID = getFieldIDCheck(env, gRectF_class, "bottom", "F");
819
820    gPoint_class = make_globalref(env, "android/graphics/Point");
821    gPoint_xFieldID = getFieldIDCheck(env, gPoint_class, "x", "I");
822    gPoint_yFieldID = getFieldIDCheck(env, gPoint_class, "y", "I");
823
824    gPointF_class = make_globalref(env, "android/graphics/PointF");
825    gPointF_xFieldID = getFieldIDCheck(env, gPointF_class, "x", "F");
826    gPointF_yFieldID = getFieldIDCheck(env, gPointF_class, "y", "F");
827
828    gBitmap_class = make_globalref(env, "android/graphics/Bitmap");
829    gBitmap_nativePtr = getFieldIDCheck(env, gBitmap_class, "mNativePtr", "J");
830    gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "<init>", "(J[BIIIZZ[BLandroid/graphics/NinePatch$InsetStruct;)V");
831    gBitmap_reinitMethodID = env->GetMethodID(gBitmap_class, "reinit", "(IIZ)V");
832    gBitmap_getAllocationByteCountMethodID = env->GetMethodID(gBitmap_class, "getAllocationByteCount", "()I");
833    gBitmapRegionDecoder_class = make_globalref(env, "android/graphics/BitmapRegionDecoder");
834    gBitmapRegionDecoder_constructorMethodID = env->GetMethodID(gBitmapRegionDecoder_class, "<init>", "(J)V");
835
836    gBitmapConfig_class = make_globalref(env, "android/graphics/Bitmap$Config");
837    gBitmapConfig_nativeInstanceID = getFieldIDCheck(env, gBitmapConfig_class,
838                                                     "nativeInt", "I");
839
840    gCanvas_class = make_globalref(env, "android/graphics/Canvas");
841    gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvasWrapper", "J");
842
843    gPicture_class = make_globalref(env, "android/graphics/Picture");
844    gPicture_nativeInstanceID = getFieldIDCheck(env, gPicture_class, "mNativePicture", "J");
845
846    gRegion_class = make_globalref(env, "android/graphics/Region");
847    gRegion_nativeInstanceID = getFieldIDCheck(env, gRegion_class, "mNativeRegion", "J");
848    gRegion_constructorMethodID = env->GetMethodID(gRegion_class, "<init>",
849        "(JI)V");
850
851    c = env->FindClass("java/lang/Byte");
852    gByte_class = (jclass) env->NewGlobalRef(
853        env->GetStaticObjectField(c, env->GetStaticFieldID(c, "TYPE", "Ljava/lang/Class;")));
854
855    gVMRuntime_class = make_globalref(env, "dalvik/system/VMRuntime");
856    m = env->GetStaticMethodID(gVMRuntime_class, "getRuntime", "()Ldalvik/system/VMRuntime;");
857    gVMRuntime = env->NewGlobalRef(env->CallStaticObjectMethod(gVMRuntime_class, m));
858    gVMRuntime_newNonMovableArray = env->GetMethodID(gVMRuntime_class, "newNonMovableArray",
859                                                     "(Ljava/lang/Class;I)Ljava/lang/Object;");
860    gVMRuntime_addressOf = env->GetMethodID(gVMRuntime_class, "addressOf", "(Ljava/lang/Object;)J");
861
862    return 0;
863}
864