- add sources.
[platform/framework/web/crosswalk.git] / src / remoting / client / jni / chromoting_jni_runtime.cc
1 // Copyright 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 "remoting/client/jni/chromoting_jni_runtime.h"
6
7 #include "base/android/jni_android.h"
8 #include "base/android/jni_array.h"
9 #include "base/android/jni_string.h"
10 #include "base/android/scoped_java_ref.h"
11 #include "base/basictypes.h"
12 #include "base/command_line.h"
13 #include "base/memory/singleton.h"
14 #include "base/stl_util.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "google_apis/google_api_keys.h"
17 #include "jni/JniInterface_jni.h"
18 #include "media/base/yuv_convert.h"
19 #include "remoting/base/url_request_context.h"
20 #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
21
22 using base::android::ConvertJavaStringToUTF8;
23 using base::android::ConvertUTF8ToJavaString;
24 using base::android::ToJavaByteArray;
25
26 namespace {
27
28 const int kBytesPerPixel = 4;
29
30 }  // namespace
31
32 namespace remoting {
33
34 bool RegisterJni(JNIEnv* env) {
35   return remoting::RegisterNativesImpl(env);
36 }
37
38 // Implementation of stubs defined in JniInterface_jni.h. These are the entry
39 // points for JNI calls from Java into C++.
40
41 static void LoadNative(JNIEnv* env, jclass clazz, jobject context) {
42   base::android::ScopedJavaLocalRef<jobject> context_activity(env, context);
43   base::android::InitApplicationContext(context_activity);
44
45   // The google_apis functions check the command-line arguments to make sure no
46   // runtime API keys have been specified by the environment. Unfortunately, we
47   // neither launch Chromium nor have a command line, so we need to prevent
48   // them from DCHECKing out when they go looking.
49   CommandLine::Init(0, NULL);
50
51   // Create the singleton now so that the Chromoting threads will be set up.
52   remoting::ChromotingJniRuntime::GetInstance();
53 }
54
55 static jstring GetApiKey(JNIEnv* env, jclass clazz) {
56   return env->NewStringUTF(google_apis::GetAPIKey().c_str());
57 }
58
59 static jstring GetClientId(JNIEnv* env, jclass clazz) {
60   return env->NewStringUTF(
61       google_apis::GetOAuth2ClientID(google_apis::CLIENT_REMOTING).c_str());
62 }
63
64 static jstring GetClientSecret(JNIEnv* env, jclass clazz) {
65   return env->NewStringUTF(
66       google_apis::GetOAuth2ClientSecret(google_apis::CLIENT_REMOTING).c_str());
67 }
68
69 static void Connect(JNIEnv* env,
70                     jclass clazz,
71                     jstring username,
72                     jstring authToken,
73                     jstring hostJid,
74                     jstring hostId,
75                     jstring hostPubkey,
76                     jstring pairId,
77                     jstring pairSecret) {
78   remoting::ChromotingJniRuntime::GetInstance()->ConnectToHost(
79       ConvertJavaStringToUTF8(env, username).c_str(),
80       ConvertJavaStringToUTF8(env, authToken).c_str(),
81       ConvertJavaStringToUTF8(env, hostJid).c_str(),
82       ConvertJavaStringToUTF8(env, hostId).c_str(),
83       ConvertJavaStringToUTF8(env, hostPubkey).c_str(),
84       ConvertJavaStringToUTF8(env, pairId).c_str(),
85       ConvertJavaStringToUTF8(env, pairSecret).c_str());
86 }
87
88 static void Disconnect(JNIEnv* env, jclass clazz) {
89   remoting::ChromotingJniRuntime::GetInstance()->DisconnectFromHost();
90 }
91
92 static void AuthenticationResponse(JNIEnv* env,
93                                    jclass clazz,
94                                    jstring pin,
95                                    jboolean createPair) {
96   remoting::ChromotingJniRuntime::GetInstance()->session()->ProvideSecret(
97       ConvertJavaStringToUTF8(env, pin).c_str(), createPair);
98 }
99
100 static void ScheduleRedraw(JNIEnv* env, jclass clazz) {
101   remoting::ChromotingJniRuntime::GetInstance()->session()->RedrawDesktop();
102 }
103
104 static void MouseAction(JNIEnv* env,
105                         jclass clazz,
106                         jint x,
107                         jint y,
108                         jint whichButton,
109                         jboolean buttonDown) {
110   // Button must be within the bounds of the MouseEvent_MouseButton enum.
111   DCHECK(whichButton >= 0 && whichButton < 5);
112
113   remoting::ChromotingJniRuntime::GetInstance()->session()->PerformMouseAction(
114       x,
115       y,
116       static_cast<remoting::protocol::MouseEvent_MouseButton>(whichButton),
117       buttonDown);
118 }
119
120 static void KeyboardAction(JNIEnv* env,
121                            jclass clazz,
122                            jint keyCode,
123                            jboolean keyDown) {
124   remoting::ChromotingJniRuntime::GetInstance()
125       ->session()
126       ->PerformKeyboardAction(keyCode, keyDown);
127 }
128
129 // ChromotingJniRuntime implementation.
130
131 // static
132 ChromotingJniRuntime* ChromotingJniRuntime::GetInstance() {
133   return Singleton<ChromotingJniRuntime>::get();
134 }
135
136 ChromotingJniRuntime::ChromotingJniRuntime() {
137   at_exit_manager_.reset(new base::AtExitManager());
138
139   // On Android, the UI thread is managed by Java, so we need to attach and
140   // start a special type of message loop to allow Chromium code to run tasks.
141   LOG(INFO) << "Starting main message loop";
142   ui_loop_.reset(new base::MessageLoopForUI());
143   ui_loop_->Start();
144
145   LOG(INFO) << "Spawning additional threads";
146   // TODO(solb) Stop pretending to control the managed UI thread's lifetime.
147   ui_task_runner_ = new AutoThreadTaskRunner(ui_loop_->message_loop_proxy(),
148                                              base::MessageLoop::QuitClosure());
149   network_task_runner_ = AutoThread::CreateWithType("native_net",
150                                                     ui_task_runner_,
151                                                     base::MessageLoop::TYPE_IO);
152   display_task_runner_ = AutoThread::Create("native_disp",
153                                             ui_task_runner_);
154
155   url_requester_ = new URLRequestContextGetter(network_task_runner_);
156
157   // Allows later decoding of video frames.
158   media::InitializeCPUSpecificYUVConversions();
159 }
160
161 ChromotingJniRuntime::~ChromotingJniRuntime() {
162   // The singleton should only ever be destroyed on the main thread.
163   DCHECK(ui_task_runner_->BelongsToCurrentThread());
164
165   // The session must be shut down first, since it depends on our other
166   // components' still being alive.
167   DisconnectFromHost();
168
169   base::WaitableEvent done_event(false, false);
170   network_task_runner_->PostTask(FROM_HERE, base::Bind(
171       &ChromotingJniRuntime::DetachFromVmAndSignal,
172       base::Unretained(this),
173       &done_event));
174   done_event.Wait();
175   display_task_runner_->PostTask(FROM_HERE, base::Bind(
176       &ChromotingJniRuntime::DetachFromVmAndSignal,
177       base::Unretained(this),
178       &done_event));
179   done_event.Wait();
180   base::android::DetachFromVM();
181 }
182
183 void ChromotingJniRuntime::ConnectToHost(const char* username,
184                                   const char* auth_token,
185                                   const char* host_jid,
186                                   const char* host_id,
187                                   const char* host_pubkey,
188                                   const char* pairing_id,
189                                   const char* pairing_secret) {
190   DCHECK(ui_task_runner_->BelongsToCurrentThread());
191   DCHECK(!session_);
192   session_ = new ChromotingJniInstance(this,
193                                        username,
194                                        auth_token,
195                                        host_jid,
196                                        host_id,
197                                        host_pubkey,
198                                        pairing_id,
199                                        pairing_secret);
200 }
201
202 void ChromotingJniRuntime::DisconnectFromHost() {
203   DCHECK(ui_task_runner_->BelongsToCurrentThread());
204   if (session_) {
205     session_->Cleanup();
206     session_ = NULL;
207   }
208 }
209
210 void ChromotingJniRuntime::ReportConnectionStatus(
211     protocol::ConnectionToHost::State state,
212     protocol::ErrorCode error) {
213   DCHECK(ui_task_runner_->BelongsToCurrentThread());
214
215   JNIEnv* env = base::android::AttachCurrentThread();
216   Java_JniInterface_reportConnectionStatus(env, state, error);
217 }
218
219 void ChromotingJniRuntime::DisplayAuthenticationPrompt(bool pairing_supported) {
220   DCHECK(ui_task_runner_->BelongsToCurrentThread());
221
222   JNIEnv* env = base::android::AttachCurrentThread();
223   Java_JniInterface_displayAuthenticationPrompt(env, pairing_supported);
224 }
225
226 void ChromotingJniRuntime::CommitPairingCredentials(const std::string& host,
227                                                     const std::string& id,
228                                                     const std::string& secret) {
229   DCHECK(ui_task_runner_->BelongsToCurrentThread());
230
231   JNIEnv* env = base::android::AttachCurrentThread();
232   ScopedJavaLocalRef<jstring> j_host = ConvertUTF8ToJavaString(env, host);
233   ScopedJavaLocalRef<jbyteArray> j_id = ToJavaByteArray(
234       env, reinterpret_cast<const uint8*>(id.data()), id.size());
235   ScopedJavaLocalRef<jbyteArray> j_secret = ToJavaByteArray(
236       env, reinterpret_cast<const uint8*>(secret.data()), secret.size());
237
238   Java_JniInterface_commitPairingCredentials(
239       env, j_host.obj(), j_id.obj(), j_secret.obj());
240 }
241
242 base::android::ScopedJavaLocalRef<jobject> ChromotingJniRuntime::NewBitmap(
243     webrtc::DesktopSize size) {
244   JNIEnv* env = base::android::AttachCurrentThread();
245   return Java_JniInterface_newBitmap(env, size.width(), size.height());
246 }
247
248 void ChromotingJniRuntime::UpdateFrameBitmap(jobject bitmap) {
249   DCHECK(display_task_runner_->BelongsToCurrentThread());
250
251   JNIEnv* env = base::android::AttachCurrentThread();
252   Java_JniInterface_setVideoFrame(env, bitmap);
253 }
254
255 void ChromotingJniRuntime::UpdateCursorShape(
256     const protocol::CursorShapeInfo& cursor_shape) {
257   DCHECK(display_task_runner_->BelongsToCurrentThread());
258
259   // const_cast<> is safe as long as the Java updateCursorShape() method copies
260   // the data out of the buffer without mutating it, and doesn't keep any
261   // reference to the buffer afterwards. Unfortunately, there seems to be no way
262   // to create a read-only ByteBuffer from a pointer-to-const.
263   char* data = string_as_array(const_cast<std::string*>(&cursor_shape.data()));
264   int cursor_total_bytes =
265       cursor_shape.width() * cursor_shape.height() * kBytesPerPixel;
266
267   JNIEnv* env = base::android::AttachCurrentThread();
268   base::android::ScopedJavaLocalRef<jobject> buffer(env,
269       env->NewDirectByteBuffer(data, cursor_total_bytes));
270   Java_JniInterface_updateCursorShape(env,
271                                       cursor_shape.width(),
272                                       cursor_shape.height(),
273                                       cursor_shape.hotspot_x(),
274                                       cursor_shape.hotspot_y(),
275                                       buffer.obj());
276 }
277
278 void ChromotingJniRuntime::RedrawCanvas() {
279   DCHECK(display_task_runner_->BelongsToCurrentThread());
280
281   JNIEnv* env = base::android::AttachCurrentThread();
282   Java_JniInterface_redrawGraphicsInternal(env);
283 }
284
285 void ChromotingJniRuntime::DetachFromVmAndSignal(base::WaitableEvent* waiter) {
286   base::android::DetachFromVM();
287   waiter->Signal();
288 }
289
290 }  // namespace remoting