Graphics.cpp revision 1103b3255945d2eb2fa9c191e84e2270b343cca9
1#define LOG_TAG "GraphicsJNI"
2
3#include "jni.h"
4#include "JNIHelp.h"
5#include "GraphicsJNI.h"
6
7#include "SkCanvas.h"
8#include "SkDevice.h"
9#include "SkMath.h"
10#include "SkPicture.h"
11#include "SkRegion.h"
12#include <android_runtime/AndroidRuntime.h>
13
14void doThrowNPE(JNIEnv* env) {
15    jniThrowNullPointerException(env, NULL);
16}
17
18void doThrowAIOOBE(JNIEnv* env) {
19    jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
20}
21
22void doThrowRE(JNIEnv* env, const char* msg) {
23    jniThrowRuntimeException(env, msg);
24}
25
26void doThrowIAE(JNIEnv* env, const char* msg) {
27    jniThrowException(env, "java/lang/IllegalArgumentException", msg);
28}
29
30void doThrowISE(JNIEnv* env, const char* msg) {
31    jniThrowException(env, "java/lang/IllegalStateException", msg);
32}
33
34void doThrowOOME(JNIEnv* env, const char* msg) {
35    jniThrowException(env, "java/lang/OutOfMemoryError", msg);
36}
37
38void doThrowIOE(JNIEnv* env, const char* msg) {
39    jniThrowException(env, "java/io/IOException", msg);
40}
41
42bool GraphicsJNI::hasException(JNIEnv *env) {
43    if (env->ExceptionCheck() != 0) {
44        ALOGE("*** Uncaught exception returned from Java call!\n");
45        env->ExceptionDescribe();
46        return true;
47    }
48    return false;
49}
50
51///////////////////////////////////////////////////////////////////////////////
52
53AutoJavaFloatArray::AutoJavaFloatArray(JNIEnv* env, jfloatArray array,
54                                       int minLength, JNIAccess access)
55: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
56    SkASSERT(env);
57    if (array) {
58        fLen = env->GetArrayLength(array);
59        if (fLen < minLength) {
60            sk_throw();
61        }
62        fPtr = env->GetFloatArrayElements(array, NULL);
63    }
64    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
65}
66
67AutoJavaFloatArray::~AutoJavaFloatArray() {
68    if (fPtr) {
69        fEnv->ReleaseFloatArrayElements(fArray, fPtr, fReleaseMode);
70    }
71}
72
73AutoJavaIntArray::AutoJavaIntArray(JNIEnv* env, jintArray array,
74                                       int minLength)
75: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
76    SkASSERT(env);
77    if (array) {
78        fLen = env->GetArrayLength(array);
79        if (fLen < minLength) {
80            sk_throw();
81        }
82        fPtr = env->GetIntArrayElements(array, NULL);
83    }
84}
85
86AutoJavaIntArray::~AutoJavaIntArray() {
87    if (fPtr) {
88        fEnv->ReleaseIntArrayElements(fArray, fPtr, 0);
89    }
90}
91
92AutoJavaShortArray::AutoJavaShortArray(JNIEnv* env, jshortArray array,
93                                       int minLength, JNIAccess access)
94: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
95    SkASSERT(env);
96    if (array) {
97        fLen = env->GetArrayLength(array);
98        if (fLen < minLength) {
99            sk_throw();
100        }
101        fPtr = env->GetShortArrayElements(array, NULL);
102    }
103    fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
104}
105
106AutoJavaShortArray::~AutoJavaShortArray() {
107    if (fPtr) {
108        fEnv->ReleaseShortArrayElements(fArray, fPtr, fReleaseMode);
109    }
110}
111
112AutoJavaByteArray::AutoJavaByteArray(JNIEnv* env, jbyteArray array,
113                                       int minLength)
114: fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
115    SkASSERT(env);
116    if (array) {
117        fLen = env->GetArrayLength(array);
118        if (fLen < minLength) {
119            sk_throw();
120        }
121        fPtr = env->GetByteArrayElements(array, NULL);
122    }
123}
124
125AutoJavaByteArray::~AutoJavaByteArray() {
126    if (fPtr) {
127        fEnv->ReleaseByteArrayElements(fArray, fPtr, 0);
128    }
129}
130
131///////////////////////////////////////////////////////////////////////////////
132
133static jclass   gRect_class;
134static jfieldID gRect_leftFieldID;
135static jfieldID gRect_topFieldID;
136static jfieldID gRect_rightFieldID;
137static jfieldID gRect_bottomFieldID;
138
139static jclass   gRectF_class;
140static jfieldID gRectF_leftFieldID;
141static jfieldID gRectF_topFieldID;
142static jfieldID gRectF_rightFieldID;
143static jfieldID gRectF_bottomFieldID;
144
145static jclass   gPoint_class;
146static jfieldID gPoint_xFieldID;
147static jfieldID gPoint_yFieldID;
148
149static jclass   gPointF_class;
150static jfieldID gPointF_xFieldID;
151static jfieldID gPointF_yFieldID;
152
153static jclass   gBitmap_class;
154static jfieldID gBitmap_nativeInstanceID;
155static jmethodID gBitmap_constructorMethodID;
156static jmethodID gBitmap_reinitMethodID;
157static jmethodID gBitmap_getAllocationByteCountMethodID;
158
159static jclass   gBitmapConfig_class;
160static jfieldID gBitmapConfig_nativeInstanceID;
161
162static jclass   gBitmapRegionDecoder_class;
163static jmethodID gBitmapRegionDecoder_constructorMethodID;
164
165static jclass   gCanvas_class;
166static jfieldID gCanvas_nativeInstanceID;
167
168static jclass   gPaint_class;
169static jfieldID gPaint_nativeInstanceID;
170static jfieldID gPaint_nativeTypefaceID;
171
172static jclass   gPicture_class;
173static jfieldID gPicture_nativeInstanceID;
174
175static jclass   gRegion_class;
176static jfieldID gRegion_nativeInstanceID;
177static jmethodID gRegion_constructorMethodID;
178
179static jclass    gByte_class;
180static jobject   gVMRuntime;
181static jclass    gVMRuntime_class;
182static jmethodID gVMRuntime_newNonMovableArray;
183static jmethodID gVMRuntime_addressOf;
184
185///////////////////////////////////////////////////////////////////////////////
186
187void GraphicsJNI::get_jrect(JNIEnv* env, jobject obj, int* L, int* T, int* R, int* B)
188{
189    SkASSERT(env->IsInstanceOf(obj, gRect_class));
190
191    *L = env->GetIntField(obj, gRect_leftFieldID);
192    *T = env->GetIntField(obj, gRect_topFieldID);
193    *R = env->GetIntField(obj, gRect_rightFieldID);
194    *B = env->GetIntField(obj, gRect_bottomFieldID);
195}
196
197void GraphicsJNI::set_jrect(JNIEnv* env, jobject obj, int L, int T, int R, int B)
198{
199    SkASSERT(env->IsInstanceOf(obj, gRect_class));
200
201    env->SetIntField(obj, gRect_leftFieldID, L);
202    env->SetIntField(obj, gRect_topFieldID, T);
203    env->SetIntField(obj, gRect_rightFieldID, R);
204    env->SetIntField(obj, gRect_bottomFieldID, B);
205}
206
207SkIRect* GraphicsJNI::jrect_to_irect(JNIEnv* env, jobject obj, SkIRect* ir)
208{
209    SkASSERT(env->IsInstanceOf(obj, gRect_class));
210
211    ir->set(env->GetIntField(obj, gRect_leftFieldID),
212            env->GetIntField(obj, gRect_topFieldID),
213            env->GetIntField(obj, gRect_rightFieldID),
214            env->GetIntField(obj, gRect_bottomFieldID));
215    return ir;
216}
217
218void GraphicsJNI::irect_to_jrect(const SkIRect& ir, JNIEnv* env, jobject obj)
219{
220    SkASSERT(env->IsInstanceOf(obj, gRect_class));
221
222    env->SetIntField(obj, gRect_leftFieldID, ir.fLeft);
223    env->SetIntField(obj, gRect_topFieldID, ir.fTop);
224    env->SetIntField(obj, gRect_rightFieldID, ir.fRight);
225    env->SetIntField(obj, gRect_bottomFieldID, ir.fBottom);
226}
227
228SkRect* GraphicsJNI::jrectf_to_rect(JNIEnv* env, jobject obj, SkRect* r)
229{
230    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
231
232    r->set(env->GetFloatField(obj, gRectF_leftFieldID),
233           env->GetFloatField(obj, gRectF_topFieldID),
234           env->GetFloatField(obj, gRectF_rightFieldID),
235           env->GetFloatField(obj, gRectF_bottomFieldID));
236    return r;
237}
238
239SkRect* GraphicsJNI::jrect_to_rect(JNIEnv* env, jobject obj, SkRect* r)
240{
241    SkASSERT(env->IsInstanceOf(obj, gRect_class));
242
243    r->set(SkIntToScalar(env->GetIntField(obj, gRect_leftFieldID)),
244           SkIntToScalar(env->GetIntField(obj, gRect_topFieldID)),
245           SkIntToScalar(env->GetIntField(obj, gRect_rightFieldID)),
246           SkIntToScalar(env->GetIntField(obj, gRect_bottomFieldID)));
247    return r;
248}
249
250void GraphicsJNI::rect_to_jrectf(const SkRect& r, JNIEnv* env, jobject obj)
251{
252    SkASSERT(env->IsInstanceOf(obj, gRectF_class));
253
254    env->SetFloatField(obj, gRectF_leftFieldID, SkScalarToFloat(r.fLeft));
255    env->SetFloatField(obj, gRectF_topFieldID, SkScalarToFloat(r.fTop));
256    env->SetFloatField(obj, gRectF_rightFieldID, SkScalarToFloat(r.fRight));
257    env->SetFloatField(obj, gRectF_bottomFieldID, SkScalarToFloat(r.fBottom));
258}
259
260SkIPoint* GraphicsJNI::jpoint_to_ipoint(JNIEnv* env, jobject obj, SkIPoint* point)
261{
262    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
263
264    point->set(env->GetIntField(obj, gPoint_xFieldID),
265               env->GetIntField(obj, gPoint_yFieldID));
266    return point;
267}
268
269void GraphicsJNI::ipoint_to_jpoint(const SkIPoint& ir, JNIEnv* env, jobject obj)
270{
271    SkASSERT(env->IsInstanceOf(obj, gPoint_class));
272
273    env->SetIntField(obj, gPoint_xFieldID, ir.fX);
274    env->SetIntField(obj, gPoint_yFieldID, ir.fY);
275}
276
277SkPoint* GraphicsJNI::jpointf_to_point(JNIEnv* env, jobject obj, SkPoint* point)
278{
279    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
280
281    point->set(env->GetIntField(obj, gPointF_xFieldID),
282               env->GetIntField(obj, gPointF_yFieldID));
283    return point;
284}
285
286void GraphicsJNI::point_to_jpointf(const SkPoint& r, JNIEnv* env, jobject obj)
287{
288    SkASSERT(env->IsInstanceOf(obj, gPointF_class));
289
290    env->SetFloatField(obj, gPointF_xFieldID, SkScalarToFloat(r.fX));
291    env->SetFloatField(obj, gPointF_yFieldID, SkScalarToFloat(r.fY));
292}
293
294// This enum must keep these int values, to match the int values
295// in the java Bitmap.Config enum.
296enum LegacyBitmapConfig {
297    kNo_LegacyBitmapConfig          = 0,
298    kA8_LegacyBitmapConfig          = 1,
299    kIndex8_LegacyBitmapConfig      = 2,
300    kRGB_565_LegacyBitmapConfig     = 3,
301    kARGB_4444_LegacyBitmapConfig   = 4,
302    kARGB_8888_LegacyBitmapConfig   = 5,
303
304    kLastEnum_LegacyBitmapConfig = kARGB_8888_LegacyBitmapConfig
305};
306
307jint GraphicsJNI::colorTypeToLegacyBitmapConfig(SkColorType colorType) {
308    switch (colorType) {
309        case kN32_SkColorType:
310            return kARGB_8888_LegacyBitmapConfig;
311        case kARGB_4444_SkColorType:
312            return kARGB_4444_LegacyBitmapConfig;
313        case kRGB_565_SkColorType:
314            return kRGB_565_LegacyBitmapConfig;
315        case kIndex_8_SkColorType:
316            return kIndex8_LegacyBitmapConfig;
317        case kAlpha_8_SkColorType:
318            return kA8_LegacyBitmapConfig;
319        case kUnknown_SkColorType:
320        default:
321            break;
322    }
323    return kNo_LegacyBitmapConfig;
324}
325
326SkColorType GraphicsJNI::legacyBitmapConfigToColorType(jint legacyConfig) {
327    const uint8_t gConfig2ColorType[] = {
328        kUnknown_SkColorType,
329        kAlpha_8_SkColorType,
330        kIndex_8_SkColorType,
331        kRGB_565_SkColorType,
332        kARGB_4444_SkColorType,
333        kN32_SkColorType
334    };
335
336    if (legacyConfig < 0 || legacyConfig > kLastEnum_LegacyBitmapConfig) {
337        legacyConfig = kNo_LegacyBitmapConfig;
338    }
339    return static_cast<SkColorType>(gConfig2ColorType[legacyConfig]);
340}
341
342SkBitmap* GraphicsJNI::getNativeBitmap(JNIEnv* env, jobject bitmap) {
343    SkASSERT(env);
344    SkASSERT(bitmap);
345    SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
346    jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativeInstanceID);
347    SkBitmap* b = reinterpret_cast<SkBitmap*>(bitmapHandle);
348    SkASSERT(b);
349    return b;
350}
351
352SkColorType GraphicsJNI::getNativeBitmapColorType(JNIEnv* env, jobject jconfig) {
353    SkASSERT(env);
354    if (NULL == jconfig) {
355        return kUnknown_SkColorType;
356    }
357    SkASSERT(env->IsInstanceOf(jconfig, gBitmapConfig_class));
358    int c = env->GetIntField(jconfig, gBitmapConfig_nativeInstanceID);
359    return legacyBitmapConfigToColorType(c);
360}
361
362SkCanvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) {
363    SkASSERT(env);
364    SkASSERT(canvas);
365    SkASSERT(env->IsInstanceOf(canvas, gCanvas_class));
366    jlong canvasHandle = env->GetLongField(canvas, gCanvas_nativeInstanceID);
367    SkCanvas* c = getNativeCanvas(canvasHandle);
368    SkASSERT(c);
369    return c;
370}
371
372SkPaint* GraphicsJNI::getNativePaint(JNIEnv* env, jobject paint) {
373    SkASSERT(env);
374    SkASSERT(paint);
375    SkASSERT(env->IsInstanceOf(paint, gPaint_class));
376    jlong paintHandle = env->GetLongField(paint, gPaint_nativeInstanceID);
377    SkPaint* p = reinterpret_cast<SkPaint*>(paintHandle);
378    SkASSERT(p);
379    return p;
380}
381
382android::TypefaceImpl* GraphicsJNI::getNativeTypeface(JNIEnv* env, jobject paint) {
383    SkASSERT(env);
384    SkASSERT(paint);
385    SkASSERT(env->IsInstanceOf(paint, gPaint_class));
386    jlong typefaceHandle = env->GetLongField(paint, gPaint_nativeTypefaceID);
387    android::TypefaceImpl* p = reinterpret_cast<android::TypefaceImpl*>(typefaceHandle);
388    SkASSERT(p);
389    return p;
390}
391
392SkRegion* GraphicsJNI::getNativeRegion(JNIEnv* env, jobject region)
393{
394    SkASSERT(env);
395    SkASSERT(region);
396    SkASSERT(env->IsInstanceOf(region, gRegion_class));
397    jlong regionHandle = env->GetLongField(region, gRegion_nativeInstanceID);
398    SkRegion* r = reinterpret_cast<SkRegion*>(regionHandle);
399    SkASSERT(r);
400    return r;
401}
402
403///////////////////////////////////////////////////////////////////////////////////////////
404
405// Assert that bitmap's SkAlphaType is consistent with isPremultiplied.
406static void assert_premultiplied(const SkBitmap& bitmap, bool isPremultiplied) {
407    // kOpaque_SkAlphaType and kIgnore_SkAlphaType mean that isPremultiplied is
408    // irrelevant. This just tests to ensure that the SkAlphaType is not
409    // opposite of isPremultiplied.
410    if (isPremultiplied) {
411        SkASSERT(bitmap.alphaType() != kUnpremul_SkAlphaType);
412    } else {
413        SkASSERT(bitmap.alphaType() != kPremul_SkAlphaType);
414    }
415}
416
417jobject GraphicsJNI::createBitmap(JNIEnv* env, SkBitmap* bitmap, jbyteArray buffer,
418        int bitmapCreateFlags, jbyteArray ninepatch, jintArray layoutbounds, int density)
419{
420    SkASSERT(bitmap);
421    SkASSERT(bitmap->pixelRef());
422    bool isMutable = bitmapCreateFlags & kBitmapCreateFlag_Mutable;
423    bool isPremultiplied = bitmapCreateFlags & kBitmapCreateFlag_Premultiplied;
424
425    // The caller needs to have already set the alpha type properly, so the
426    // native SkBitmap stays in sync with the Java Bitmap.
427    assert_premultiplied(*bitmap, isPremultiplied);
428
429    jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
430            reinterpret_cast<jlong>(bitmap), buffer,
431            bitmap->width(), bitmap->height(), density, isMutable, isPremultiplied,
432            ninepatch, layoutbounds);
433    hasException(env); // For the side effect of logging.
434    return obj;
435}
436
437jobject GraphicsJNI::createBitmap(JNIEnv* env, SkBitmap* bitmap, int bitmapCreateFlags,
438        jbyteArray ninepatch, int density)
439{
440    return createBitmap(env, bitmap, NULL, bitmapCreateFlags, ninepatch, NULL, density);
441}
442
443void GraphicsJNI::reinitBitmap(JNIEnv* env, jobject javaBitmap, SkBitmap* bitmap,
444        bool isPremultiplied)
445{
446    // The caller needs to have already set the alpha type properly, so the
447    // native SkBitmap stays in sync with the Java Bitmap.
448    assert_premultiplied(*bitmap, isPremultiplied);
449
450    env->CallVoidMethod(javaBitmap, gBitmap_reinitMethodID,
451            bitmap->width(), bitmap->height(), isPremultiplied);
452}
453
454int GraphicsJNI::getBitmapAllocationByteCount(JNIEnv* env, jobject javaBitmap)
455{
456    return env->CallIntMethod(javaBitmap, gBitmap_getAllocationByteCountMethodID);
457}
458
459jobject GraphicsJNI::createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap)
460{
461    SkASSERT(bitmap != NULL);
462
463    jobject obj = env->NewObject(gBitmapRegionDecoder_class,
464            gBitmapRegionDecoder_constructorMethodID,
465            reinterpret_cast<jlong>(bitmap));
466    hasException(env); // For the side effect of logging.
467    return obj;
468}
469
470jobject GraphicsJNI::createRegion(JNIEnv* env, SkRegion* region)
471{
472    SkASSERT(region != NULL);
473    jobject obj = env->NewObject(gRegion_class, gRegion_constructorMethodID,
474                                 reinterpret_cast<jlong>(region), 0);
475    hasException(env); // For the side effect of logging.
476    return obj;
477}
478
479static JNIEnv* vm2env(JavaVM* vm)
480{
481    JNIEnv* env = NULL;
482    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || NULL == env)
483    {
484        SkDebugf("------- [%p] vm->GetEnv() failed\n", vm);
485        sk_throw();
486    }
487    return env;
488}
489
490///////////////////////////////////////////////////////////////////////////////
491
492AndroidPixelRef::AndroidPixelRef(JNIEnv* env, const SkImageInfo& info, void* storage,
493        size_t rowBytes, jbyteArray storageObj, SkColorTable* ctable) :
494        SkMallocPixelRef(info, storage, rowBytes, ctable, (storageObj == NULL)),
495        fWrappedPixelRef(NULL) {
496    SkASSERT(storage);
497    SkASSERT(env);
498
499    if (env->GetJavaVM(&fVM) != JNI_OK) {
500        SkDebugf("------ [%p] env->GetJavaVM failed\n", env);
501        sk_throw();
502    }
503    fStorageObj = storageObj;
504    fHasGlobalRef = false;
505    fGlobalRefCnt = 0;
506
507    // If storageObj is NULL, the memory was NOT allocated on the Java heap
508    fOnJavaHeap = (storageObj != NULL);
509
510}
511
512AndroidPixelRef::AndroidPixelRef(AndroidPixelRef& wrappedPixelRef, const SkImageInfo& info,
513        size_t rowBytes, SkColorTable* ctable) :
514        SkMallocPixelRef(info, wrappedPixelRef.getAddr(), rowBytes, ctable, false),
515        fWrappedPixelRef(wrappedPixelRef.fWrappedPixelRef ?
516                wrappedPixelRef.fWrappedPixelRef : &wrappedPixelRef)
517{
518    SkASSERT(fWrappedPixelRef);
519    SkSafeRef(fWrappedPixelRef);
520
521    // don't need to initialize these, as all the relevant logic delegates to the wrapped ref
522    fStorageObj = NULL;
523    fHasGlobalRef = false;
524    fGlobalRefCnt = 0;
525    fOnJavaHeap = false;
526}
527
528AndroidPixelRef::~AndroidPixelRef() {
529    if (fWrappedPixelRef) {
530        SkSafeUnref(fWrappedPixelRef);
531    } else if (fOnJavaHeap) {
532        JNIEnv* env = vm2env(fVM);
533
534        if (fStorageObj && fHasGlobalRef) {
535            env->DeleteGlobalRef(fStorageObj);
536        }
537        fStorageObj = NULL;
538    }
539}
540jbyteArray AndroidPixelRef::getStorageObj() {
541    if (fWrappedPixelRef) {
542        return fWrappedPixelRef->fStorageObj;
543    }
544    return fStorageObj;
545}
546
547void AndroidPixelRef::setLocalJNIRef(jbyteArray arr) {
548    if (fWrappedPixelRef) {
549        // delegate java obj management to the wrapped ref
550        fWrappedPixelRef->setLocalJNIRef(arr);
551    } else if (!fHasGlobalRef) {
552        fStorageObj = arr;
553    }
554}
555
556void AndroidPixelRef::globalRef(void* localref) {
557    if (fWrappedPixelRef) {
558        // delegate java obj management to the wrapped ref
559        fWrappedPixelRef->globalRef(localref);
560
561        // Note: we only ref and unref the wrapped AndroidPixelRef so that
562        // bitmap->pixelRef()->globalRef() and globalUnref() can be used in a pair, even if
563        // the bitmap has its underlying AndroidPixelRef swapped out/wrapped
564        return;
565    }
566    if (fOnJavaHeap && sk_atomic_inc(&fGlobalRefCnt) == 0) {
567        JNIEnv *env = vm2env(fVM);
568
569        // If JNI ref was passed, it is always used
570        if (localref) fStorageObj = (jbyteArray) localref;
571
572        if (fStorageObj == NULL) {
573            SkDebugf("No valid local ref to create a JNI global ref\n");
574            sk_throw();
575        }
576        if (fHasGlobalRef) {
577            // This should never happen
578            SkDebugf("Already holding a JNI global ref");
579            sk_throw();
580        }
581
582        fStorageObj = (jbyteArray) env->NewGlobalRef(fStorageObj);
583        // TODO: Check for failure here
584        fHasGlobalRef = true;
585    }
586    ref();
587}
588
589void AndroidPixelRef::globalUnref() {
590    if (fWrappedPixelRef) {
591        // delegate java obj management to the wrapped ref
592        fWrappedPixelRef->globalUnref();
593        return;
594    }
595    if (fOnJavaHeap && sk_atomic_dec(&fGlobalRefCnt) == 1) {
596        JNIEnv *env = vm2env(fVM);
597        if (!fHasGlobalRef) {
598            SkDebugf("We don't have a global ref!");
599            sk_throw();
600        }
601        env->DeleteGlobalRef(fStorageObj);
602        fStorageObj = NULL;
603        fHasGlobalRef = false;
604    }
605    unref();
606}
607
608///////////////////////////////////////////////////////////////////////////////
609
610jbyteArray GraphicsJNI::allocateJavaPixelRef(JNIEnv* env, SkBitmap* bitmap,
611                                             SkColorTable* ctable) {
612    const SkImageInfo& info = bitmap->info();
613    if (info.fColorType == kUnknown_SkColorType) {
614        doThrowIAE(env, "unknown bitmap configuration");
615        return NULL;
616    }
617
618    const size_t size = bitmap->getSize();
619    jbyteArray arrayObj = (jbyteArray) env->CallObjectMethod(gVMRuntime,
620                                                             gVMRuntime_newNonMovableArray,
621                                                             gByte_class, size);
622    if (env->ExceptionCheck() != 0) {
623        return NULL;
624    }
625    SkASSERT(arrayObj);
626    jbyte* addr = (jbyte*) env->CallLongMethod(gVMRuntime, gVMRuntime_addressOf, arrayObj);
627    if (env->ExceptionCheck() != 0) {
628        return NULL;
629    }
630    SkASSERT(addr);
631    SkPixelRef* pr = new AndroidPixelRef(env, info, (void*) addr,
632            bitmap->rowBytes(), arrayObj, ctable);
633    bitmap->setPixelRef(pr)->unref();
634    // since we're already allocated, we lockPixels right away
635    // HeapAllocator behaves this way too
636    bitmap->lockPixels();
637
638    return arrayObj;
639}
640
641///////////////////////////////////////////////////////////////////////////////
642
643JavaPixelAllocator::JavaPixelAllocator(JNIEnv* env)
644    : fStorageObj(NULL),
645      fAllocCount(0) {
646    if (env->GetJavaVM(&fVM) != JNI_OK) {
647        SkDebugf("------ [%p] env->GetJavaVM failed\n", env);
648        sk_throw();
649    }
650}
651
652bool JavaPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
653    JNIEnv* env = vm2env(fVM);
654
655    fStorageObj = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
656    fAllocCount += 1;
657    return fStorageObj != NULL;
658}
659
660////////////////////////////////////////////////////////////////////////////////
661
662JavaHeapBitmapRef::JavaHeapBitmapRef(JNIEnv* env, SkBitmap* nativeBitmap, jbyteArray buffer) {
663    fEnv = env;
664    fNativeBitmap = nativeBitmap;
665    fBuffer = buffer;
666
667    // If the buffer is NULL, the backing memory wasn't allocated on the Java heap
668    if (fBuffer) {
669        ((AndroidPixelRef*) fNativeBitmap->pixelRef())->setLocalJNIRef(fBuffer);
670    }
671}
672
673JavaHeapBitmapRef::~JavaHeapBitmapRef() {
674    if (fBuffer) {
675        ((AndroidPixelRef*) fNativeBitmap->pixelRef())->setLocalJNIRef(NULL);
676    }
677}
678
679////////////////////////////////////////////////////////////////////////////////
680
681static jclass make_globalref(JNIEnv* env, const char classname[])
682{
683    jclass c = env->FindClass(classname);
684    SkASSERT(c);
685    return (jclass) env->NewGlobalRef(c);
686}
687
688static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
689                                const char fieldname[], const char type[])
690{
691    jfieldID id = env->GetFieldID(clazz, fieldname, type);
692    SkASSERT(id);
693    return id;
694}
695
696int register_android_graphics_Graphics(JNIEnv* env)
697{
698    jmethodID m;
699    jclass c;
700
701    gRect_class = make_globalref(env, "android/graphics/Rect");
702    gRect_leftFieldID = getFieldIDCheck(env, gRect_class, "left", "I");
703    gRect_topFieldID = getFieldIDCheck(env, gRect_class, "top", "I");
704    gRect_rightFieldID = getFieldIDCheck(env, gRect_class, "right", "I");
705    gRect_bottomFieldID = getFieldIDCheck(env, gRect_class, "bottom", "I");
706
707    gRectF_class = make_globalref(env, "android/graphics/RectF");
708    gRectF_leftFieldID = getFieldIDCheck(env, gRectF_class, "left", "F");
709    gRectF_topFieldID = getFieldIDCheck(env, gRectF_class, "top", "F");
710    gRectF_rightFieldID = getFieldIDCheck(env, gRectF_class, "right", "F");
711    gRectF_bottomFieldID = getFieldIDCheck(env, gRectF_class, "bottom", "F");
712
713    gPoint_class = make_globalref(env, "android/graphics/Point");
714    gPoint_xFieldID = getFieldIDCheck(env, gPoint_class, "x", "I");
715    gPoint_yFieldID = getFieldIDCheck(env, gPoint_class, "y", "I");
716
717    gPointF_class = make_globalref(env, "android/graphics/PointF");
718    gPointF_xFieldID = getFieldIDCheck(env, gPointF_class, "x", "F");
719    gPointF_yFieldID = getFieldIDCheck(env, gPointF_class, "y", "F");
720
721    gBitmap_class = make_globalref(env, "android/graphics/Bitmap");
722    gBitmap_nativeInstanceID = getFieldIDCheck(env, gBitmap_class, "mNativeBitmap", "J");
723    gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "<init>", "(J[BIIIZZ[B[I)V");
724    gBitmap_reinitMethodID = env->GetMethodID(gBitmap_class, "reinit", "(IIZ)V");
725    gBitmap_getAllocationByteCountMethodID = env->GetMethodID(gBitmap_class, "getAllocationByteCount", "()I");
726    gBitmapRegionDecoder_class = make_globalref(env, "android/graphics/BitmapRegionDecoder");
727    gBitmapRegionDecoder_constructorMethodID = env->GetMethodID(gBitmapRegionDecoder_class, "<init>", "(J)V");
728
729    gBitmapConfig_class = make_globalref(env, "android/graphics/Bitmap$Config");
730    gBitmapConfig_nativeInstanceID = getFieldIDCheck(env, gBitmapConfig_class,
731                                                     "nativeInt", "I");
732
733    gCanvas_class = make_globalref(env, "android/graphics/Canvas");
734    gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvasWrapper", "J");
735
736    gPaint_class = make_globalref(env, "android/graphics/Paint");
737    gPaint_nativeInstanceID = getFieldIDCheck(env, gPaint_class, "mNativePaint", "J");
738    gPaint_nativeTypefaceID = getFieldIDCheck(env, gPaint_class, "mNativeTypeface", "J");
739
740    gPicture_class = make_globalref(env, "android/graphics/Picture");
741    gPicture_nativeInstanceID = getFieldIDCheck(env, gPicture_class, "mNativePicture", "J");
742
743    gRegion_class = make_globalref(env, "android/graphics/Region");
744    gRegion_nativeInstanceID = getFieldIDCheck(env, gRegion_class, "mNativeRegion", "J");
745    gRegion_constructorMethodID = env->GetMethodID(gRegion_class, "<init>",
746        "(JI)V");
747
748    c = env->FindClass("java/lang/Byte");
749    gByte_class = (jclass) env->NewGlobalRef(
750        env->GetStaticObjectField(c, env->GetStaticFieldID(c, "TYPE", "Ljava/lang/Class;")));
751
752    gVMRuntime_class = make_globalref(env, "dalvik/system/VMRuntime");
753    m = env->GetStaticMethodID(gVMRuntime_class, "getRuntime", "()Ldalvik/system/VMRuntime;");
754    gVMRuntime = env->NewGlobalRef(env->CallStaticObjectMethod(gVMRuntime_class, m));
755    gVMRuntime_newNonMovableArray = env->GetMethodID(gVMRuntime_class, "newNonMovableArray",
756                                                     "(Ljava/lang/Class;I)Ljava/lang/Object;");
757    gVMRuntime_addressOf = env->GetMethodID(gVMRuntime_class, "addressOf", "(Ljava/lang/Object;)J");
758
759    return 0;
760}
761