android_view_Surface.cpp revision f9136fd9692158574d187af8d4031fa4b1e2b6e6
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Surface"
18
19#include <stdio.h>
20
21#include "android_os_Parcel.h"
22#include "android_util_Binder.h"
23#include "android/graphics/GraphicsJNI.h"
24#include "android/graphics/Region.h"
25
26#include <binder/IMemory.h>
27
28#include <gui/ISurfaceComposer.h>
29#include <gui/Surface.h>
30#include <gui/SurfaceComposerClient.h>
31#include <gui/GLConsumer.h>
32
33#include <ui/DisplayInfo.h>
34#include <ui/Rect.h>
35#include <ui/Region.h>
36
37#include <EGL/egl.h>
38
39#include <SkCanvas.h>
40#include <SkBitmap.h>
41#include <SkRegion.h>
42#include <SkPixelRef.h>
43
44#include "jni.h"
45#include "JNIHelp.h"
46#include <android_runtime/AndroidRuntime.h>
47#include <android_runtime/android_view_Surface.h>
48#include <android_runtime/android_view_SurfaceSession.h>
49#include <android_runtime/android_graphics_SurfaceTexture.h>
50#include <utils/misc.h>
51#include <utils/Log.h>
52
53#include <ScopedUtfChars.h>
54
55
56// ----------------------------------------------------------------------------
57
58namespace android {
59
60static const char* const OutOfResourcesException =
61    "android/view/Surface$OutOfResourcesException";
62
63static struct {
64    jclass clazz;
65    jfieldID mNativeSurface;
66    jfieldID mNativeSurfaceControl;
67    jfieldID mGenerationId;
68    jfieldID mCanvas;
69    jfieldID mCanvasSaveCount;
70    jmethodID ctor;
71} gSurfaceClassInfo;
72
73static struct {
74    jfieldID left;
75    jfieldID top;
76    jfieldID right;
77    jfieldID bottom;
78} gRectClassInfo;
79
80static struct {
81    jfieldID mNativeCanvas;
82    jfieldID mSurfaceFormat;
83} gCanvasClassInfo;
84
85static struct {
86    jfieldID width;
87    jfieldID height;
88    jfieldID refreshRate;
89    jfieldID density;
90    jfieldID xDpi;
91    jfieldID yDpi;
92    jfieldID secure;
93} gPhysicalDisplayInfoClassInfo;
94
95
96class ScreenshotPixelRef : public SkPixelRef {
97public:
98    ScreenshotPixelRef(SkColorTable* ctable) {
99        fCTable = ctable;
100        SkSafeRef(ctable);
101        setImmutable();
102    }
103
104    virtual ~ScreenshotPixelRef() {
105        SkSafeUnref(fCTable);
106    }
107
108    status_t update(const sp<IBinder>& display, int width, int height,
109            int minLayer, int maxLayer, bool allLayers) {
110        status_t res = (width > 0 && height > 0)
111                ? (allLayers
112                        ? mScreenshot.update(display, width, height)
113                        : mScreenshot.update(display, width, height, minLayer, maxLayer))
114                : mScreenshot.update(display);
115        if (res != NO_ERROR) {
116            return res;
117        }
118
119        return NO_ERROR;
120    }
121
122    uint32_t getWidth() const {
123        return mScreenshot.getWidth();
124    }
125
126    uint32_t getHeight() const {
127        return mScreenshot.getHeight();
128    }
129
130    uint32_t getStride() const {
131        return mScreenshot.getStride();
132    }
133
134    uint32_t getFormat() const {
135        return mScreenshot.getFormat();
136    }
137
138protected:
139    // overrides from SkPixelRef
140    virtual void* onLockPixels(SkColorTable** ct) {
141        *ct = fCTable;
142        return (void*)mScreenshot.getPixels();
143    }
144
145    virtual void onUnlockPixels() {
146    }
147
148private:
149    ScreenshotClient mScreenshot;
150    SkColorTable*    fCTable;
151
152    typedef SkPixelRef INHERITED;
153};
154
155
156// ----------------------------------------------------------------------------
157
158static sp<SurfaceControl> getSurfaceControl(JNIEnv* env, jobject surfaceObj) {
159    return reinterpret_cast<SurfaceControl*>(
160            env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurfaceControl));
161}
162
163static void setSurfaceControl(JNIEnv* env, jobject surfaceObj,
164        const sp<SurfaceControl>& surface) {
165    SurfaceControl* const p = reinterpret_cast<SurfaceControl*>(
166            env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurfaceControl));
167    if (surface.get()) {
168        surface->incStrong(surfaceObj);
169    }
170    if (p) {
171        p->decStrong(surfaceObj);
172    }
173    env->SetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurfaceControl,
174            reinterpret_cast<jint>(surface.get()));
175}
176
177static sp<Surface> getSurface(JNIEnv* env, jobject surfaceObj) {
178    sp<Surface> result(android_view_Surface_getSurface(env, surfaceObj));
179    if (result == NULL) {
180        /*
181         * if this method is called from the WindowManager's process, it means
182         * the client is is not remote, and therefore is allowed to have
183         * a Surface (data), so we create it here.
184         * If we don't have a SurfaceControl, it means we're in a different
185         * process.
186         */
187
188        SurfaceControl* const control = reinterpret_cast<SurfaceControl*>(
189                env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurfaceControl));
190        if (control) {
191            result = control->getSurface();
192            if (result != NULL) {
193                result->incStrong(surfaceObj);
194                env->SetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurface,
195                        reinterpret_cast<jint>(result.get()));
196            }
197        }
198    }
199    return result;
200}
201
202sp<ANativeWindow> android_view_Surface_getNativeWindow(JNIEnv* env, jobject surfaceObj) {
203    return getSurface(env, surfaceObj);
204}
205
206bool android_view_Surface_isInstanceOf(JNIEnv* env, jobject obj) {
207    return env->IsInstanceOf(obj, gSurfaceClassInfo.clazz);
208}
209
210sp<Surface> android_view_Surface_getSurface(JNIEnv* env, jobject surfaceObj) {
211    return reinterpret_cast<Surface*>(
212            env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurface));
213}
214
215static void setSurface(JNIEnv* env, jobject surfaceObj, const sp<Surface>& surface) {
216    Surface* const p = reinterpret_cast<Surface*>(
217            env->GetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurface));
218    if (surface.get()) {
219        surface->incStrong(surfaceObj);
220    }
221    if (p) {
222        p->decStrong(surfaceObj);
223    }
224    env->SetIntField(surfaceObj, gSurfaceClassInfo.mNativeSurface,
225            reinterpret_cast<jint>(surface.get()));
226
227    // This test is conservative and it would be better to compare the ISurfaces
228    if (p && p != surface.get()) {
229        jint generationId = env->GetIntField(surfaceObj,
230                gSurfaceClassInfo.mGenerationId);
231        generationId++;
232        env->SetIntField(surfaceObj,
233                gSurfaceClassInfo.mGenerationId, generationId);
234    }
235}
236
237static sp<IGraphicBufferProducer> getISurfaceTexture(JNIEnv* env, jobject surfaceObj) {
238    if (surfaceObj) {
239        sp<Surface> surface(getSurface(env, surfaceObj));
240        if (surface != NULL) {
241            return surface->getSurfaceTexture();
242        }
243    }
244    return NULL;
245}
246
247jobject android_view_Surface_createFromISurfaceTexture(JNIEnv* env,
248        const sp<IGraphicBufferProducer>& bufferProducer) {
249    if (bufferProducer == NULL) {
250        return NULL;
251    }
252
253    sp<Surface> surface(new Surface(bufferProducer));
254    if (surface == NULL) {
255        return NULL;
256    }
257
258    jobject surfaceObj = env->NewObject(gSurfaceClassInfo.clazz, gSurfaceClassInfo.ctor);
259    if (surfaceObj == NULL) {
260        if (env->ExceptionCheck()) {
261            ALOGE("Could not create instance of Surface from IGraphicBufferProducer.");
262            LOGE_EX(env);
263            env->ExceptionClear();
264        }
265        return NULL;
266    }
267
268    setSurface(env, surfaceObj, surface);
269    return surfaceObj;
270}
271
272
273// ----------------------------------------------------------------------------
274
275static void nativeCreate(JNIEnv* env, jobject surfaceObj, jobject sessionObj,
276        jstring nameStr, jint w, jint h, jint format, jint flags) {
277    ScopedUtfChars name(env, nameStr);
278    sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));
279
280    sp<SurfaceControl> surface = client->createSurface(
281            String8(name.c_str()), w, h, format, flags);
282    if (surface == NULL) {
283        jniThrowException(env, OutOfResourcesException, NULL);
284        return;
285    }
286
287    setSurfaceControl(env, surfaceObj, surface);
288}
289
290static void nativeCreateFromSurfaceTexture(JNIEnv* env, jobject surfaceObj,
291        jobject surfaceTextureObj) {
292    sp<GLConsumer> st(SurfaceTexture_getSurfaceTexture(env, surfaceTextureObj));
293    if (st == NULL) {
294        jniThrowException(env, "java/lang/IllegalArgumentException",
295                "SurfaceTexture has already been released");
296        return;
297    }
298
299    sp<IGraphicBufferProducer> bq = st->getBufferQueue();
300
301    sp<Surface> surface(new Surface(bq));
302    if (surface == NULL) {
303        jniThrowException(env, OutOfResourcesException, NULL);
304        return;
305    }
306
307    setSurface(env, surfaceObj, surface);
308}
309
310static void nativeRelease(JNIEnv* env, jobject surfaceObj) {
311    setSurfaceControl(env, surfaceObj, NULL);
312    setSurface(env, surfaceObj, NULL);
313}
314
315static void nativeDestroy(JNIEnv* env, jobject surfaceObj) {
316    sp<SurfaceControl> surfaceControl(getSurfaceControl(env, surfaceObj));
317    if (SurfaceControl::isValid(surfaceControl)) {
318        surfaceControl->clear();
319    }
320    setSurfaceControl(env, surfaceObj, NULL);
321    setSurface(env, surfaceObj, NULL);
322}
323
324static jboolean nativeIsValid(JNIEnv* env, jobject surfaceObj) {
325    sp<SurfaceControl> surfaceControl(getSurfaceControl(env, surfaceObj));
326    if (surfaceControl != NULL) {
327        return SurfaceControl::isValid(surfaceControl) ? JNI_TRUE : JNI_FALSE;
328    }
329
330    sp<Surface> surface(getSurface(env, surfaceObj));
331    return Surface::isValid(surface) ? JNI_TRUE : JNI_FALSE;
332}
333
334static jboolean nativeIsConsumerRunningBehind(JNIEnv* env, jobject surfaceObj) {
335    sp<Surface> surface(getSurface(env, surfaceObj));
336    if (!Surface::isValid(surface)) {
337        doThrowIAE(env);
338        return JNI_FALSE;
339    }
340
341    int value = 0;
342    ANativeWindow* anw = static_cast<ANativeWindow*>(surface.get());
343    anw->query(anw, NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &value);
344    return value;
345}
346
347static inline SkBitmap::Config convertPixelFormat(PixelFormat format) {
348    /* note: if PIXEL_FORMAT_RGBX_8888 means that all alpha bytes are 0xFF, then
349        we can map to SkBitmap::kARGB_8888_Config, and optionally call
350        bitmap.setIsOpaque(true) on the resulting SkBitmap (as an accelerator)
351    */
352    switch (format) {
353    case PIXEL_FORMAT_RGBX_8888:    return SkBitmap::kARGB_8888_Config;
354    case PIXEL_FORMAT_RGBA_8888:    return SkBitmap::kARGB_8888_Config;
355    case PIXEL_FORMAT_RGBA_4444:    return SkBitmap::kARGB_4444_Config;
356    case PIXEL_FORMAT_RGB_565:      return SkBitmap::kRGB_565_Config;
357    case PIXEL_FORMAT_A_8:          return SkBitmap::kA8_Config;
358    default:                        return SkBitmap::kNo_Config;
359    }
360}
361
362static jobject nativeLockCanvas(JNIEnv* env, jobject surfaceObj, jobject dirtyRectObj) {
363    sp<Surface> surface(getSurface(env, surfaceObj));
364    if (!Surface::isValid(surface)) {
365        doThrowIAE(env);
366        return NULL;
367    }
368
369    // get dirty region
370    Region dirtyRegion;
371    if (dirtyRectObj) {
372        Rect dirty;
373        dirty.left = env->GetIntField(dirtyRectObj, gRectClassInfo.left);
374        dirty.top = env->GetIntField(dirtyRectObj, gRectClassInfo.top);
375        dirty.right = env->GetIntField(dirtyRectObj, gRectClassInfo.right);
376        dirty.bottom = env->GetIntField(dirtyRectObj, gRectClassInfo.bottom);
377        if (!dirty.isEmpty()) {
378            dirtyRegion.set(dirty);
379        }
380    } else {
381        dirtyRegion.set(Rect(0x3FFF, 0x3FFF));
382    }
383
384    Surface::SurfaceInfo info;
385    status_t err = surface->lock(&info, &dirtyRegion);
386    if (err < 0) {
387        const char* const exception = (err == NO_MEMORY) ?
388                OutOfResourcesException :
389                "java/lang/IllegalArgumentException";
390        jniThrowException(env, exception, NULL);
391        return NULL;
392    }
393
394    // Associate a SkCanvas object to this surface
395    jobject canvasObj = env->GetObjectField(surfaceObj, gSurfaceClassInfo.mCanvas);
396    env->SetIntField(canvasObj, gCanvasClassInfo.mSurfaceFormat, info.format);
397
398    SkCanvas* nativeCanvas = reinterpret_cast<SkCanvas*>(
399            env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
400    SkBitmap bitmap;
401    ssize_t bpr = info.s * bytesPerPixel(info.format);
402    bitmap.setConfig(convertPixelFormat(info.format), info.w, info.h, bpr);
403    if (info.format == PIXEL_FORMAT_RGBX_8888) {
404        bitmap.setIsOpaque(true);
405    }
406    if (info.w > 0 && info.h > 0) {
407        bitmap.setPixels(info.bits);
408    } else {
409        // be safe with an empty bitmap.
410        bitmap.setPixels(NULL);
411    }
412    nativeCanvas->setBitmapDevice(bitmap);
413
414    SkRegion clipReg;
415    if (dirtyRegion.isRect()) { // very common case
416        const Rect b(dirtyRegion.getBounds());
417        clipReg.setRect(b.left, b.top, b.right, b.bottom);
418    } else {
419        size_t count;
420        Rect const* r = dirtyRegion.getArray(&count);
421        while (count) {
422            clipReg.op(r->left, r->top, r->right, r->bottom, SkRegion::kUnion_Op);
423            r++, count--;
424        }
425    }
426
427    nativeCanvas->clipRegion(clipReg);
428
429    int saveCount = nativeCanvas->save();
430    env->SetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount, saveCount);
431
432    if (dirtyRectObj) {
433        const Rect& bounds(dirtyRegion.getBounds());
434        env->SetIntField(dirtyRectObj, gRectClassInfo.left, bounds.left);
435        env->SetIntField(dirtyRectObj, gRectClassInfo.top, bounds.top);
436        env->SetIntField(dirtyRectObj, gRectClassInfo.right, bounds.right);
437        env->SetIntField(dirtyRectObj, gRectClassInfo.bottom, bounds.bottom);
438    }
439
440    return canvasObj;
441}
442
443static void nativeUnlockCanvasAndPost(JNIEnv* env, jobject surfaceObj, jobject canvasObj) {
444    jobject ownCanvasObj = env->GetObjectField(surfaceObj, gSurfaceClassInfo.mCanvas);
445    if (!env->IsSameObject(ownCanvasObj, canvasObj)) {
446        doThrowIAE(env);
447        return;
448    }
449
450    sp<Surface> surface(getSurface(env, surfaceObj));
451    if (!Surface::isValid(surface)) {
452        return;
453    }
454
455    // detach the canvas from the surface
456    SkCanvas* nativeCanvas = reinterpret_cast<SkCanvas*>(
457            env->GetIntField(canvasObj, gCanvasClassInfo.mNativeCanvas));
458    int saveCount = env->GetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount);
459    nativeCanvas->restoreToCount(saveCount);
460    nativeCanvas->setBitmapDevice(SkBitmap());
461    env->SetIntField(surfaceObj, gSurfaceClassInfo.mCanvasSaveCount, 0);
462
463    // unlock surface
464    status_t err = surface->unlockAndPost();
465    if (err < 0) {
466        doThrowIAE(env);
467    }
468}
469
470static jobject nativeScreenshot(JNIEnv* env, jclass clazz, jobject displayTokenObj,
471        jint width, jint height, jint minLayer, jint maxLayer, bool allLayers) {
472    sp<IBinder> displayToken = ibinderForJavaObject(env, displayTokenObj);
473    if (displayToken == NULL) {
474        return NULL;
475    }
476
477    ScreenshotPixelRef* pixels = new ScreenshotPixelRef(NULL);
478    if (pixels->update(displayToken, width, height,
479            minLayer, maxLayer, allLayers) != NO_ERROR) {
480        delete pixels;
481        return NULL;
482    }
483
484    uint32_t w = pixels->getWidth();
485    uint32_t h = pixels->getHeight();
486    uint32_t s = pixels->getStride();
487    uint32_t f = pixels->getFormat();
488    ssize_t bpr = s * android::bytesPerPixel(f);
489
490    SkBitmap* bitmap = new SkBitmap();
491    bitmap->setConfig(convertPixelFormat(f), w, h, bpr);
492    if (f == PIXEL_FORMAT_RGBX_8888) {
493        bitmap->setIsOpaque(true);
494    }
495
496    if (w > 0 && h > 0) {
497        bitmap->setPixelRef(pixels)->unref();
498        bitmap->lockPixels();
499    } else {
500        // be safe with an empty bitmap.
501        delete pixels;
502        bitmap->setPixels(NULL);
503    }
504
505    return GraphicsJNI::createBitmap(env, bitmap, false, NULL);
506}
507
508static void nativeOpenTransaction(JNIEnv* env, jclass clazz) {
509    SurfaceComposerClient::openGlobalTransaction();
510}
511
512static void nativeCloseTransaction(JNIEnv* env, jclass clazz) {
513    SurfaceComposerClient::closeGlobalTransaction();
514}
515
516static void nativeSetAnimationTransaction(JNIEnv* env, jclass clazz) {
517    SurfaceComposerClient::setAnimationTransaction();
518}
519
520static void nativeSetLayer(JNIEnv* env, jobject surfaceObj, jint zorder) {
521    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
522    if (surface == NULL) return;
523
524    status_t err = surface->setLayer(zorder);
525    if (err < 0 && err != NO_INIT) {
526        doThrowIAE(env);
527    }
528}
529
530static void nativeSetPosition(JNIEnv* env, jobject surfaceObj, jfloat x, jfloat y) {
531    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
532    if (surface == NULL) return;
533
534    status_t err = surface->setPosition(x, y);
535    if (err < 0 && err != NO_INIT) {
536        doThrowIAE(env);
537    }
538}
539
540static void nativeSetSize(JNIEnv* env, jobject surfaceObj, jint w, jint h) {
541    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
542    if (surface == NULL) return;
543
544    status_t err = surface->setSize(w, h);
545    if (err < 0 && err != NO_INIT) {
546        doThrowIAE(env);
547    }
548}
549
550static void nativeSetFlags(JNIEnv* env, jobject surfaceObj, jint flags, jint mask) {
551    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
552    if (surface == NULL) return;
553
554    status_t err = surface->setFlags(flags, mask);
555    if (err < 0 && err != NO_INIT) {
556        doThrowIAE(env);
557    }
558}
559
560static void nativeSetTransparentRegionHint(JNIEnv* env, jobject surfaceObj, jobject regionObj) {
561    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
562    if (surface == NULL) return;
563
564    SkRegion* region = android_graphics_Region_getSkRegion(env, regionObj);
565    if (!region) {
566        doThrowIAE(env);
567        return;
568    }
569
570    const SkIRect& b(region->getBounds());
571    Region reg(Rect(b.fLeft, b.fTop, b.fRight, b.fBottom));
572    if (region->isComplex()) {
573        SkRegion::Iterator it(*region);
574        while (!it.done()) {
575            const SkIRect& r(it.rect());
576            reg.addRectUnchecked(r.fLeft, r.fTop, r.fRight, r.fBottom);
577            it.next();
578        }
579    }
580
581    status_t err = surface->setTransparentRegionHint(reg);
582    if (err < 0 && err != NO_INIT) {
583        doThrowIAE(env);
584    }
585}
586
587static void nativeSetAlpha(JNIEnv* env, jobject surfaceObj, jfloat alpha) {
588    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
589    if (surface == NULL) return;
590
591    status_t err = surface->setAlpha(alpha);
592    if (err < 0 && err != NO_INIT) {
593        doThrowIAE(env);
594    }
595}
596
597static void nativeSetMatrix(JNIEnv* env, jobject surfaceObj,
598        jfloat dsdx, jfloat dtdx, jfloat dsdy, jfloat dtdy) {
599    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
600    if (surface == NULL) return;
601
602    status_t err = surface->setMatrix(dsdx, dtdx, dsdy, dtdy);
603    if (err < 0 && err != NO_INIT) {
604        doThrowIAE(env);
605    }
606}
607
608static void nativeSetWindowCrop(JNIEnv* env, jobject surfaceObj, jobject cropObj) {
609    const sp<SurfaceControl>& surface(getSurfaceControl(env, surfaceObj));
610    if (surface == NULL) return;
611
612    Rect crop;
613    if (cropObj) {
614        crop.left = env->GetIntField(cropObj, gRectClassInfo.left);
615        crop.top = env->GetIntField(cropObj, gRectClassInfo.top);
616        crop.right = env->GetIntField(cropObj, gRectClassInfo.right);
617        crop.bottom = env->GetIntField(cropObj, gRectClassInfo.bottom);
618    } else {
619        crop.left = crop.top = crop.right = crop.bottom = 0;
620    }
621
622    status_t err = surface->setCrop(crop);
623    if (err < 0 && err != NO_INIT) {
624        doThrowIAE(env);
625    }
626}
627
628static void nativeSetLayerStack(JNIEnv* env, jobject surfaceObj, jint layerStack) {
629    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
630    if (surface == NULL) return;
631
632    status_t err = surface->setLayerStack(layerStack);
633    if (err < 0 && err != NO_INIT) {
634        doThrowIAE(env);
635    }
636}
637
638static jobject nativeGetBuiltInDisplay(JNIEnv* env, jclass clazz, jint id) {
639    sp<IBinder> token(SurfaceComposerClient::getBuiltInDisplay(id));
640    return javaObjectForIBinder(env, token);
641}
642
643static jobject nativeCreateDisplay(JNIEnv* env, jclass clazz, jstring nameObj,
644        jboolean secure) {
645    ScopedUtfChars name(env, nameObj);
646    sp<IBinder> token(SurfaceComposerClient::createDisplay(
647            String8(name.c_str()), bool(secure)));
648    return javaObjectForIBinder(env, token);
649}
650
651static void nativeSetDisplaySurface(JNIEnv* env, jclass clazz,
652        jobject tokenObj, jobject surfaceObj) {
653    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
654    if (token == NULL) return;
655
656    sp<IGraphicBufferProducer> bufferProducer(getISurfaceTexture(env, surfaceObj));
657    SurfaceComposerClient::setDisplaySurface(token, bufferProducer);
658}
659
660static void nativeSetDisplayLayerStack(JNIEnv* env, jclass clazz,
661        jobject tokenObj, jint layerStack) {
662    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
663    if (token == NULL) return;
664
665    SurfaceComposerClient::setDisplayLayerStack(token, layerStack);
666}
667
668static void nativeSetDisplayProjection(JNIEnv* env, jclass clazz,
669        jobject tokenObj, jint orientation, jobject layerStackRectObj, jobject displayRectObj) {
670    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
671    if (token == NULL) return;
672
673    Rect layerStackRect;
674    layerStackRect.left = env->GetIntField(layerStackRectObj, gRectClassInfo.left);
675    layerStackRect.top = env->GetIntField(layerStackRectObj, gRectClassInfo.top);
676    layerStackRect.right = env->GetIntField(layerStackRectObj, gRectClassInfo.right);
677    layerStackRect.bottom = env->GetIntField(layerStackRectObj, gRectClassInfo.bottom);
678
679    Rect displayRect;
680    displayRect.left = env->GetIntField(displayRectObj, gRectClassInfo.left);
681    displayRect.top = env->GetIntField(displayRectObj, gRectClassInfo.top);
682    displayRect.right = env->GetIntField(displayRectObj, gRectClassInfo.right);
683    displayRect.bottom = env->GetIntField(displayRectObj, gRectClassInfo.bottom);
684
685    SurfaceComposerClient::setDisplayProjection(token, orientation, layerStackRect, displayRect);
686}
687
688static jboolean nativeGetDisplayInfo(JNIEnv* env, jclass clazz,
689        jobject tokenObj, jobject infoObj) {
690    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
691    if (token == NULL) return JNI_FALSE;
692
693    DisplayInfo info;
694    if (SurfaceComposerClient::getDisplayInfo(token, &info)) {
695        return JNI_FALSE;
696    }
697
698    env->SetIntField(infoObj, gPhysicalDisplayInfoClassInfo.width, info.w);
699    env->SetIntField(infoObj, gPhysicalDisplayInfoClassInfo.height, info.h);
700    env->SetFloatField(infoObj, gPhysicalDisplayInfoClassInfo.refreshRate, info.fps);
701    env->SetFloatField(infoObj, gPhysicalDisplayInfoClassInfo.density, info.density);
702    env->SetFloatField(infoObj, gPhysicalDisplayInfoClassInfo.xDpi, info.xdpi);
703    env->SetFloatField(infoObj, gPhysicalDisplayInfoClassInfo.yDpi, info.ydpi);
704    env->SetBooleanField(infoObj, gPhysicalDisplayInfoClassInfo.secure, info.secure);
705    return JNI_TRUE;
706}
707
708static void nativeBlankDisplay(JNIEnv* env, jclass clazz, jobject tokenObj) {
709    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
710    if (token == NULL) return;
711
712    ALOGD_IF_SLOW(100, "Excessive delay in blankDisplay() while turning screen off");
713    SurfaceComposerClient::blankDisplay(token);
714}
715
716static void nativeUnblankDisplay(JNIEnv* env, jclass clazz, jobject tokenObj) {
717    sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
718    if (token == NULL) return;
719
720    ALOGD_IF_SLOW(100, "Excessive delay in unblankDisplay() while turning screen on");
721    SurfaceComposerClient::unblankDisplay(token);
722}
723
724// ----------------------------------------------------------------------------
725
726static void nativeCopyFrom(JNIEnv* env, jobject surfaceObj, jobject otherObj) {
727    /*
728     * This is used by the WindowManagerService just after constructing
729     * a Surface and is necessary for returning the Surface reference to
730     * the caller. At this point, we should only have a SurfaceControl.
731     */
732
733    sp<SurfaceControl> surface(getSurfaceControl(env, surfaceObj));
734    sp<SurfaceControl> other(getSurfaceControl(env, otherObj));
735    if (!SurfaceControl::isSameSurface(surface, other)) {
736        // we reassign the surface only if it's a different one
737        // otherwise we would loose our client-side state.
738        setSurfaceControl(env, surfaceObj, other);
739    }
740}
741
742static void nativeTransferFrom(JNIEnv* env, jobject surfaceObj, jobject otherObj) {
743    sp<SurfaceControl> control(getSurfaceControl(env, otherObj));
744    sp<Surface> surface(android_view_Surface_getSurface(env, otherObj));
745    setSurfaceControl(env, surfaceObj, control);
746    setSurface(env, surfaceObj, surface);
747    setSurfaceControl(env, otherObj, NULL);
748    setSurface(env, otherObj, NULL);
749}
750
751static void nativeReadFromParcel(JNIEnv* env, jobject surfaceObj, jobject parcelObj) {
752    Parcel* parcel = parcelForJavaObject(env, parcelObj);
753    if (parcel == NULL) {
754        doThrowNPE(env);
755        return;
756    }
757
758    sp<Surface> surface(Surface::readFromParcel(*parcel));
759    setSurfaceControl(env, surfaceObj, NULL);
760    setSurface(env, surfaceObj, surface);
761}
762
763static void nativeWriteToParcel(JNIEnv* env, jobject surfaceObj, jobject parcelObj) {
764    Parcel* parcel = parcelForJavaObject(env, parcelObj);
765    if (parcel == NULL) {
766        doThrowNPE(env);
767        return;
768    }
769
770    // The Java instance may have a SurfaceControl (in the case of the
771    // WindowManager or a system app). In that case, we defer to the
772    // SurfaceControl to send its ISurface. Otherwise, if the Surface is
773    // available we let it parcel itself. Finally, if the Surface is also
774    // NULL we fall back to using the SurfaceControl path which sends an
775    // empty surface; this matches legacy behavior.
776    sp<SurfaceControl> control(getSurfaceControl(env, surfaceObj));
777    if (control != NULL) {
778        SurfaceControl::writeSurfaceToParcel(control, parcel);
779    } else {
780        sp<Surface> surface(android_view_Surface_getSurface(env, surfaceObj));
781        if (surface != NULL) {
782            Surface::writeToParcel(surface, parcel);
783        } else {
784            SurfaceControl::writeSurfaceToParcel(NULL, parcel);
785        }
786    }
787}
788
789// ----------------------------------------------------------------------------
790
791static JNINativeMethod gSurfaceMethods[] = {
792    {"nativeCreate", "(Landroid/view/SurfaceSession;Ljava/lang/String;IIII)V",
793            (void*)nativeCreate },
794    {"nativeCreateFromSurfaceTexture", "(Landroid/graphics/SurfaceTexture;)V",
795            (void*)nativeCreateFromSurfaceTexture },
796    {"nativeRelease", "()V",
797            (void*)nativeRelease },
798    {"nativeDestroy", "()V",
799            (void*)nativeDestroy },
800    {"nativeIsValid", "()Z",
801            (void*)nativeIsValid },
802    {"nativeIsConsumerRunningBehind", "()Z",
803            (void*)nativeIsConsumerRunningBehind },
804    {"nativeLockCanvas", "(Landroid/graphics/Rect;)Landroid/graphics/Canvas;",
805            (void*)nativeLockCanvas },
806    {"nativeUnlockCanvasAndPost", "(Landroid/graphics/Canvas;)V",
807            (void*)nativeUnlockCanvasAndPost },
808    {"nativeScreenshot", "(Landroid/os/IBinder;IIIIZ)Landroid/graphics/Bitmap;",
809            (void*)nativeScreenshot },
810    {"nativeOpenTransaction", "()V",
811            (void*)nativeOpenTransaction },
812    {"nativeCloseTransaction", "()V",
813            (void*)nativeCloseTransaction },
814    {"nativeSetAnimationTransaction", "()V",
815            (void*)nativeSetAnimationTransaction },
816    {"nativeSetLayer", "(I)V",
817            (void*)nativeSetLayer },
818    {"nativeSetPosition", "(FF)V",
819            (void*)nativeSetPosition },
820    {"nativeSetSize", "(II)V",
821            (void*)nativeSetSize },
822    {"nativeSetTransparentRegionHint", "(Landroid/graphics/Region;)V",
823            (void*)nativeSetTransparentRegionHint },
824    {"nativeSetAlpha", "(F)V",
825            (void*)nativeSetAlpha },
826    {"nativeSetMatrix", "(FFFF)V",
827            (void*)nativeSetMatrix },
828    {"nativeSetFlags", "(II)V",
829            (void*)nativeSetFlags },
830    {"nativeSetWindowCrop", "(Landroid/graphics/Rect;)V",
831            (void*)nativeSetWindowCrop },
832    {"nativeSetLayerStack", "(I)V",
833            (void*)nativeSetLayerStack },
834    {"nativeGetBuiltInDisplay", "(I)Landroid/os/IBinder;",
835            (void*)nativeGetBuiltInDisplay },
836    {"nativeCreateDisplay", "(Ljava/lang/String;Z)Landroid/os/IBinder;",
837            (void*)nativeCreateDisplay },
838    {"nativeSetDisplaySurface", "(Landroid/os/IBinder;Landroid/view/Surface;)V",
839            (void*)nativeSetDisplaySurface },
840    {"nativeSetDisplayLayerStack", "(Landroid/os/IBinder;I)V",
841            (void*)nativeSetDisplayLayerStack },
842    {"nativeSetDisplayProjection", "(Landroid/os/IBinder;ILandroid/graphics/Rect;Landroid/graphics/Rect;)V",
843            (void*)nativeSetDisplayProjection },
844    {"nativeGetDisplayInfo", "(Landroid/os/IBinder;Landroid/view/Surface$PhysicalDisplayInfo;)Z",
845            (void*)nativeGetDisplayInfo },
846    {"nativeBlankDisplay", "(Landroid/os/IBinder;)V",
847            (void*)nativeBlankDisplay },
848    {"nativeUnblankDisplay", "(Landroid/os/IBinder;)V",
849            (void*)nativeUnblankDisplay },
850    {"nativeCopyFrom", "(Landroid/view/Surface;)V",
851            (void*)nativeCopyFrom },
852    {"nativeTransferFrom", "(Landroid/view/Surface;)V",
853            (void*)nativeTransferFrom },
854    {"nativeReadFromParcel", "(Landroid/os/Parcel;)V",
855            (void*)nativeReadFromParcel },
856    {"nativeWriteToParcel", "(Landroid/os/Parcel;)V",
857            (void*)nativeWriteToParcel },
858};
859
860int register_android_view_Surface(JNIEnv* env)
861{
862    int err = AndroidRuntime::registerNativeMethods(env, "android/view/Surface",
863            gSurfaceMethods, NELEM(gSurfaceMethods));
864
865    jclass clazz = env->FindClass("android/view/Surface");
866    gSurfaceClassInfo.clazz = jclass(env->NewGlobalRef(clazz));
867    gSurfaceClassInfo.mNativeSurface =
868            env->GetFieldID(gSurfaceClassInfo.clazz, ANDROID_VIEW_SURFACE_JNI_ID, "I");
869    gSurfaceClassInfo.mNativeSurfaceControl =
870            env->GetFieldID(gSurfaceClassInfo.clazz, "mNativeSurfaceControl", "I");
871    gSurfaceClassInfo.mGenerationId =
872            env->GetFieldID(gSurfaceClassInfo.clazz, "mGenerationId", "I");
873    gSurfaceClassInfo.mCanvas =
874            env->GetFieldID(gSurfaceClassInfo.clazz, "mCanvas", "Landroid/graphics/Canvas;");
875    gSurfaceClassInfo.mCanvasSaveCount =
876            env->GetFieldID(gSurfaceClassInfo.clazz, "mCanvasSaveCount", "I");
877    gSurfaceClassInfo.ctor = env->GetMethodID(gSurfaceClassInfo.clazz, "<init>", "()V");
878
879    clazz = env->FindClass("android/graphics/Canvas");
880    gCanvasClassInfo.mNativeCanvas = env->GetFieldID(clazz, "mNativeCanvas", "I");
881    gCanvasClassInfo.mSurfaceFormat = env->GetFieldID(clazz, "mSurfaceFormat", "I");
882
883    clazz = env->FindClass("android/graphics/Rect");
884    gRectClassInfo.left = env->GetFieldID(clazz, "left", "I");
885    gRectClassInfo.top = env->GetFieldID(clazz, "top", "I");
886    gRectClassInfo.right = env->GetFieldID(clazz, "right", "I");
887    gRectClassInfo.bottom = env->GetFieldID(clazz, "bottom", "I");
888
889    clazz = env->FindClass("android/view/Surface$PhysicalDisplayInfo");
890    gPhysicalDisplayInfoClassInfo.width = env->GetFieldID(clazz, "width", "I");
891    gPhysicalDisplayInfoClassInfo.height = env->GetFieldID(clazz, "height", "I");
892    gPhysicalDisplayInfoClassInfo.refreshRate = env->GetFieldID(clazz, "refreshRate", "F");
893    gPhysicalDisplayInfoClassInfo.density = env->GetFieldID(clazz, "density", "F");
894    gPhysicalDisplayInfoClassInfo.xDpi = env->GetFieldID(clazz, "xDpi", "F");
895    gPhysicalDisplayInfoClassInfo.yDpi = env->GetFieldID(clazz, "yDpi", "F");
896    gPhysicalDisplayInfoClassInfo.secure = env->GetFieldID(clazz, "secure", "Z");
897    return err;
898}
899
900};
901