1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "ui/gl/android/scoped_java_surface.h"
6
7#include "base/logging.h"
8#include "jni/Surface_jni.h"
9#include "ui/gl/android/surface_texture.h"
10
11namespace {
12
13bool g_jni_initialized = false;
14
15void RegisterNativesIfNeeded(JNIEnv* env) {
16  if (!g_jni_initialized) {
17    JNI_Surface::RegisterNativesImpl(env);
18    g_jni_initialized = true;
19  }
20}
21
22}  // anonymous namespace
23
24namespace gfx {
25
26ScopedJavaSurface::ScopedJavaSurface() {
27}
28
29ScopedJavaSurface::ScopedJavaSurface(
30    const base::android::JavaRef<jobject>& surface)
31    : auto_release_(true),
32      is_protected_(false) {
33  JNIEnv* env = base::android::AttachCurrentThread();
34  RegisterNativesIfNeeded(env);
35  DCHECK(env->IsInstanceOf(surface.obj(), Surface_clazz(env)));
36  j_surface_.Reset(surface);
37}
38
39ScopedJavaSurface::ScopedJavaSurface(
40    const SurfaceTexture* surface_texture)
41    : auto_release_(true),
42      is_protected_(false) {
43  JNIEnv* env = base::android::AttachCurrentThread();
44  RegisterNativesIfNeeded(env);
45  ScopedJavaLocalRef<jobject> tmp(JNI_Surface::Java_Surface_Constructor(
46      env, surface_texture->j_surface_texture().obj()));
47  DCHECK(!tmp.is_null());
48  j_surface_.Reset(tmp);
49}
50
51ScopedJavaSurface::ScopedJavaSurface(RValue rvalue) {
52  MoveFrom(*rvalue.object);
53}
54
55ScopedJavaSurface& ScopedJavaSurface::operator=(RValue rhs) {
56  MoveFrom(*rhs.object);
57  return *this;
58}
59
60ScopedJavaSurface::~ScopedJavaSurface() {
61  if (auto_release_ && !j_surface_.is_null()) {
62    JNIEnv* env = base::android::AttachCurrentThread();
63    JNI_Surface::Java_Surface_release(env, j_surface_.obj());
64  }
65}
66
67void ScopedJavaSurface::MoveFrom(ScopedJavaSurface& other) {
68  JNIEnv* env = base::android::AttachCurrentThread();
69  j_surface_.Reset(env, other.j_surface_.Release());
70  auto_release_ = other.auto_release_;
71  is_protected_ = other.is_protected_;
72}
73
74bool ScopedJavaSurface::IsEmpty() const {
75  return j_surface_.is_null();
76}
77
78// static
79ScopedJavaSurface ScopedJavaSurface::AcquireExternalSurface(jobject surface) {
80  JNIEnv* env = base::android::AttachCurrentThread();
81  ScopedJavaLocalRef<jobject> surface_ref;
82  surface_ref.Reset(env, surface);
83  gfx::ScopedJavaSurface scoped_surface(surface_ref);
84  scoped_surface.auto_release_ = false;
85  scoped_surface.is_protected_ = true;
86  return scoped_surface;
87}
88
89}  // namespace gfx
90