WebViewContentsClientAdapter.java revision 7bc1fd3e42c1a731a7891043f0f8ee96be1b598c
1/* 2 * Copyright (C) 2012 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 17package com.android.webview.chromium; 18 19import android.content.ActivityNotFoundException; 20import android.content.Context; 21import android.content.Intent; 22import android.graphics.Picture; 23import android.os.Handler; 24import android.os.Looper; 25import android.os.Message; 26import android.provider.Browser; 27import android.util.Log; 28import android.view.KeyEvent; 29import android.webkit.ConsoleMessage; 30import android.webkit.DownloadListener; 31import android.webkit.JsPromptResult; 32import android.webkit.JsResult; 33import android.webkit.WebChromeClient; 34import android.webkit.WebResourceResponse; 35import android.webkit.WebView; 36import android.webkit.WebViewClient; 37 38import org.chromium.android_webview.AwContentsClient; 39import org.chromium.android_webview.AwHttpAuthHandler; 40import org.chromium.android_webview.InterceptedRequestData; 41import org.chromium.android_webview.JsPromptResultReceiver; 42import org.chromium.android_webview.JsResultReceiver; 43import org.chromium.content.browser.ContentView; 44import org.chromium.content.browser.ContentViewClient; 45 46import java.net.URISyntaxException; 47 48/** 49 * An adapter class that forwards the callbacks from {@link ContentViewClient} 50 * to the appropriate {@link WebViewClient} or {@link WebChromeClient}. 51 * 52 * An instance of this class is associated with one {@link WebViewChromium} 53 * instance. A WebViewChromium is a WebView implementation provider (that is 54 * android.webkit.WebView delegates all functionality to it) and has exactly 55 * one corresponding {@link ContentView} instance. 56 * 57 * A {@link ContentViewClient} may be shared between multiple {@link ContentView}s, 58 * and hence multiple WebViews. Many WebViewClient methods pass the source 59 * WebView as an argument. This means that we either need to pass the 60 * corresponding ContentView to the corresponding ContentViewClient methods, 61 * or use an instance of ContentViewClientAdapter per WebViewChromium, to 62 * allow the source WebView to be injected by ContentViewClientAdapter. We 63 * choose the latter, because it makes for a cleaner design. 64 */ 65public class WebViewContentsClientAdapter extends AwContentsClient { 66 private static final String TAG = "ContentViewClientAdapter"; 67 // The WebView instance that this adapter is serving. 68 private final WebView mWebView; 69 // The WebViewClient instance that was passed to WebView.setWebViewClient(). 70 private WebViewClient mWebViewClient; 71 // The WebViewClient instance that was passed to WebView.setContentViewClient(). 72 private WebChromeClient mWebChromeClient; 73 // The listener receiving find-in-page API results. 74 private WebView.FindListener mFindListener; 75 // The listener receiving notifications of screen updates. 76 private WebView.PictureListener mPictureListener; 77 78 private DownloadListener mDownloadListener; 79 80 private Handler mUiThreadHandler; 81 82 private static final int NEW_WEBVIEW_CREATED = 100; 83 84 /** 85 * Adapter constructor. 86 * 87 * @param webView the {@link WebView} instance that this adapter is serving. 88 */ 89 WebViewContentsClientAdapter(WebView webView) { 90 if (webView == null) { 91 throw new IllegalArgumentException("webView can't be null"); 92 } 93 94 mWebView = webView; 95 setWebViewClient(null); 96 setWebChromeClient(null); 97 98 mUiThreadHandler = new Handler() { 99 100 @Override 101 public void handleMessage(Message msg) { 102 switch(msg.what) { 103 case NEW_WEBVIEW_CREATED: 104 WebView.WebViewTransport t = (WebView.WebViewTransport) msg.obj; 105 WebView newWebView = t.getWebView(); 106 if (newWebView == null) { 107 throw new IllegalArgumentException( 108 "Must provide a new WebView for the new window."); 109 } 110 if (newWebView == mWebView) { 111 throw new IllegalArgumentException( 112 "Parent WebView cannot host it's own popup window. Please " + 113 "use WebSettings.setSupportMultipleWindows(false)"); 114 } 115 116 if (newWebView.copyBackForwardList().getSize() != 0) { 117 throw new IllegalArgumentException( 118 "New WebView for popup window must not have been previously " + 119 "navigated."); 120 } 121 122 WebViewChromium.completeWindowCreation(mWebView, newWebView); 123 break; 124 default: 125 throw new IllegalStateException(); 126 } 127 } 128 }; 129 130 } 131 132 // WebViewClassic is coded in such a way that even if a null WebViewClient is set, 133 // certain actions take place. 134 // We choose to replicate this behavior by using a NullWebViewClient implementation (also known 135 // as the Null Object pattern) rather than duplicating the WebViewClassic approach in 136 // ContentView. 137 static class NullWebViewClient extends WebViewClient { 138 @Override 139 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { 140 // TODO: Investigate more and add a test case. 141 // This is a copy of what Clank does. The WebViewCore key handling code and Clank key 142 // handling code differ enough that it's not trivial to figure out how keycodes are 143 // being filtered. 144 int keyCode = event.getKeyCode(); 145 if (keyCode == KeyEvent.KEYCODE_MENU || 146 keyCode == KeyEvent.KEYCODE_HOME || 147 keyCode == KeyEvent.KEYCODE_BACK || 148 keyCode == KeyEvent.KEYCODE_CALL || 149 keyCode == KeyEvent.KEYCODE_ENDCALL || 150 keyCode == KeyEvent.KEYCODE_POWER || 151 keyCode == KeyEvent.KEYCODE_HEADSETHOOK || 152 keyCode == KeyEvent.KEYCODE_CAMERA || 153 keyCode == KeyEvent.KEYCODE_FOCUS || 154 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || 155 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE || 156 keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 157 return true; 158 } 159 return false; 160 } 161 162 @Override 163 public boolean shouldOverrideUrlLoading(WebView view, String url) { 164 Intent intent; 165 // Perform generic parsing of the URI to turn it into an Intent. 166 try { 167 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); 168 } catch (URISyntaxException ex) { 169 Log.w(TAG, "Bad URI " + url + ": " + ex.getMessage()); 170 return false; 171 } 172 // Sanitize the Intent, ensuring web pages can not bypass browser 173 // security (only access to BROWSABLE activities). 174 intent.addCategory(Intent.CATEGORY_BROWSABLE); 175 intent.setComponent(null); 176 // Pass the package name as application ID so that the intent from the 177 // same application can be opened in the same tab. 178 intent.putExtra(Browser.EXTRA_APPLICATION_ID, 179 view.getContext().getPackageName()); 180 try { 181 view.getContext().startActivity(intent); 182 } catch (ActivityNotFoundException ex) { 183 Log.w(TAG, "No application can handle " + url); 184 return false; 185 } 186 return true; 187 } 188 } 189 190 void setWebViewClient(WebViewClient client) { 191 if (client != null) { 192 mWebViewClient = client; 193 } else { 194 mWebViewClient = new NullWebViewClient(); 195 } 196 } 197 198 void setWebChromeClient(WebChromeClient client) { 199 if (client != null) { 200 mWebChromeClient = client; 201 } else { 202 // WebViewClassic doesn't implement any special behavior for a null WebChromeClient. 203 mWebChromeClient = new WebChromeClient(); 204 } 205 } 206 207 void setDownloadListener(DownloadListener listener) { 208 mDownloadListener = listener; 209 } 210 211 void setFindListener(WebView.FindListener listener) { 212 mFindListener = listener; 213 } 214 215 void setPictureListener(WebView.PictureListener listener) { 216 mPictureListener = listener; 217 } 218 219 //-------------------------------------------------------------------------------------------- 220 // Adapter for WebContentsDelegate methods. 221 //-------------------------------------------------------------------------------------------- 222 223 /** 224 * @see AwContentsClient#onProgressChanged(int) 225 */ 226 @Override 227 public void onProgressChanged(int progress) { 228 mWebChromeClient.onProgressChanged(mWebView, progress); 229 } 230 231 /** 232 * @see AwContentsClient#shouldInterceptRequest(java.lang.String) 233 */ 234 @Override 235 public InterceptedRequestData shouldInterceptRequest(String url) { 236 WebResourceResponse response = mWebViewClient.shouldInterceptRequest(mWebView, url); 237 if (response == null) return null; 238 return new InterceptedRequestData( 239 response.getMimeType(), 240 response.getEncoding(), 241 response.getData()); 242 } 243 244 /** 245 * @see AwContentsClient#shouldIgnoreNavigation(java.lang.String) 246 */ 247 @Override 248 public boolean shouldIgnoreNavigation(String url) { 249 return mWebViewClient.shouldOverrideUrlLoading(mWebView, url); 250 } 251 252 /** 253 * @see AwContentsClient#onUnhandledKeyEvent(android.view.KeyEvent) 254 */ 255 @Override 256 public void onUnhandledKeyEvent(KeyEvent event) { 257 mWebViewClient.onUnhandledKeyEvent(mWebView, event); 258 } 259 260 /** 261 * @see AwContentsClient#onConsoleMessage(android.webkit.ConsoleMessage) 262 */ 263 @Override 264 public boolean onConsoleMessage(ConsoleMessage consoleMessage) { 265 return mWebChromeClient.onConsoleMessage(consoleMessage); 266 } 267 268 /** 269 * @see AwContentsClient#onFindResultReceived(int,int,boolean) 270 */ 271 @Override 272 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 273 boolean isDoneCounting) { 274 if (mFindListener == null) return; 275 mFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, isDoneCounting); 276 } 277 278 @Override 279 public void onLoadResource(String url) { 280 mWebViewClient.onLoadResource(mWebView, url); 281 } 282 283 @Override 284 public boolean onCreateWindow(boolean isDialog, boolean isUserGesture) { 285 Message m = mUiThreadHandler.obtainMessage( 286 NEW_WEBVIEW_CREATED, mWebView.new WebViewTransport()); 287 return mWebChromeClient.onCreateWindow(mWebView, isDialog, isUserGesture, m); 288 } 289 290 /** 291 * @see AwContentsClient#onCloseWindow() 292 */ 293 /* @Override */ 294 public void onCloseWindow() { 295 mWebChromeClient.onCloseWindow(mWebView); 296 } 297 298 //-------------------------------------------------------------------------------------------- 299 // Trivial Chrome -> WebViewClient mappings. 300 //-------------------------------------------------------------------------------------------- 301 302 /** 303 * @see ContentViewClient#onPageStarted(String) 304 */ 305 @Override 306 public void onPageStarted(String url) { 307 //TODO: Can't get the favicon till b/6094807 is fixed. 308 mWebViewClient.onPageStarted(mWebView, url, null); 309 } 310 311 /** 312 * @see ContentViewClient#onPageFinished(String) 313 */ 314 @Override 315 public void onPageFinished(String url) { 316 mWebViewClient.onPageFinished(mWebView, url); 317 318 // HACK: Fake a picture listener update, to allow CTS tests to progress. 319 // TODO: Remove when we have real picture listener updates implemented. 320 if (mPictureListener != null) { 321 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { 322 @Override 323 public void run() { 324 UnimplementedWebViewApi.invoke(); 325 if (mPictureListener != null) { 326 mPictureListener.onNewPicture(mWebView, new Picture()); 327 } 328 } 329 }, 100); 330 } 331 } 332 333 /** 334 * @see ContentViewClient#onReceivedError(int,String,String) 335 */ 336 @Override 337 public void onReceivedError(int errorCode, String description, String failingUrl) { 338 mWebViewClient.onReceivedError(mWebView, errorCode, description, failingUrl); 339 } 340 341 /** 342 * @see ContentViewClient#onUpdateTitle(String) 343 */ 344 @Override 345 public void onUpdateTitle(String title) { 346 mWebChromeClient.onReceivedTitle(mWebView, title); 347 } 348 349 350 /** 351 * @see ContentViewClient#shouldOverrideKeyEvent(KeyEvent) 352 */ 353 @Override 354 public boolean shouldOverrideKeyEvent(KeyEvent event) { 355 return mWebViewClient.shouldOverrideKeyEvent(mWebView, event); 356 } 357 358 359 //-------------------------------------------------------------------------------------------- 360 // More complicated mappings (including behavior choices) 361 //-------------------------------------------------------------------------------------------- 362 363 /** 364 * @see ContentViewClient#onTabCrash() 365 */ 366 @Override 367 public void onTabCrash() { 368 // The WebViewClassic implementation used a single process, so any crash would 369 // cause the application to terminate. WebViewChromium should have the same 370 // behavior as long as we run the renderer in-process. This needs to be revisited 371 // if we change that decision. 372 Log.e(TAG, "Renderer crash reported."); 373 mWebChromeClient.onCloseWindow(mWebView); 374 } 375 376 //-------------------------------------------------------------------------------------------- 377 // The TODO section 378 //-------------------------------------------------------------------------------------------- 379 380 381 /** 382 * @see ContentViewClient#onImeEvent() 383 */ 384 @Override 385 public void onImeEvent() { 386 } 387 388 /** 389 * @see ContentViewClient#onEvaluateJavaScriptResult(int,String) 390 */ 391 @Override 392 public void onEvaluateJavaScriptResult(int id, String jsonResult) { 393 } 394 395 /** 396 * @see ContentViewClient#onStartContentIntent(Context, String) 397 * Callback when detecting a click on a content link. 398 */ 399 @Override 400 public void onStartContentIntent(Context context, String contentUrl) { 401 mWebViewClient.shouldOverrideUrlLoading(mWebView, contentUrl); 402 } 403 404 private static class SimpleJsResultReceiver implements JsResult.ResultReceiver { 405 private JsResultReceiver mChromeResultReceiver; 406 407 public SimpleJsResultReceiver(JsResultReceiver receiver) { 408 mChromeResultReceiver = receiver; 409 } 410 411 @Override 412 public void onJsResultComplete(JsResult result) { 413 if (result.getResult()) { 414 mChromeResultReceiver.confirm(); 415 } else { 416 mChromeResultReceiver.cancel(); 417 } 418 } 419 } 420 421 private static class JsPromptResultReceiverAdapter implements JsResult.ResultReceiver { 422 private JsPromptResultReceiver mChromeResultReceiver; 423 private JsPromptResult mPromptResult; 424 425 public JsPromptResultReceiverAdapter(JsPromptResultReceiver receiver) { 426 mChromeResultReceiver = receiver; 427 // We hold onto the JsPromptResult here, just to avoid the need to downcast 428 // in onJsResultComplete. 429 mPromptResult = new JsPromptResult(this); 430 } 431 432 public JsPromptResult getPromptResult() { 433 return mPromptResult; 434 } 435 436 @Override 437 public void onJsResultComplete(JsResult result) { 438 if (result != mPromptResult) throw new RuntimeException("incorrect JsResult instance"); 439 if (mPromptResult.getResult()) { 440 mChromeResultReceiver.confirm(mPromptResult.getStringResult()); 441 } else { 442 mChromeResultReceiver.cancel(); 443 } 444 } 445 } 446 447 @Override 448 public void handleJsAlert(String url, String message, JsResultReceiver receiver) { 449 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 450 mWebChromeClient.onJsAlert(mWebView, url, message, res); 451 // TODO: Handle the case of the client returning false; 452 } 453 454 @Override 455 public void handleJsBeforeUnload(String url, String message, JsResultReceiver receiver) { 456 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 457 mWebChromeClient.onJsBeforeUnload(mWebView, url, message, res); 458 // TODO: Handle the case of the client returning false; 459 } 460 461 @Override 462 public void handleJsConfirm(String url, String message, JsResultReceiver receiver) { 463 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 464 mWebChromeClient.onJsConfirm(mWebView, url, message, res); 465 // TODO: Handle the case of the client returning false; 466 } 467 468 @Override 469 public void handleJsPrompt(String url, String message, String defaultValue, 470 JsPromptResultReceiver receiver) { 471 JsPromptResult res = new JsPromptResultReceiverAdapter(receiver).getPromptResult(); 472 mWebChromeClient.onJsPrompt(mWebView, url, message, defaultValue, res); 473 // TODO: Handle the case of the client returning false; 474 } 475 476 @Override 477 public void onReceivedHttpAuthRequest(AwHttpAuthHandler handler, String host, String realm) { 478 mWebViewClient.onReceivedHttpAuthRequest(mWebView, 479 new AwHttpAuthHandlerAdapter(handler), host, realm); 480 } 481 482 @Override 483 public void onFormResubmission(Message dontResend, Message resend) { 484 mWebViewClient.onFormResubmission(mWebView, dontResend, resend); 485 } 486 487 @Override 488 public void onDownloadStart(String url, 489 String userAgent, 490 String contentDisposition, 491 String mimeType, 492 long contentLength) { 493 if (mDownloadListener != null) { 494 mDownloadListener.onDownloadStart(url, 495 userAgent, 496 contentDisposition, 497 mimeType, 498 contentLength); 499 } 500 } 501 502 503 private static class AwHttpAuthHandlerAdapter extends android.webkit.HttpAuthHandler { 504 private AwHttpAuthHandler mAwHandler; 505 506 public AwHttpAuthHandlerAdapter(AwHttpAuthHandler awHandler) { 507 mAwHandler = awHandler; 508 } 509 510 @Override 511 public void proceed(String username, String password) { 512 if (username == null) { 513 username = ""; 514 } 515 516 if (password == null) { 517 password = ""; 518 } 519 mAwHandler.proceed(username, password); 520 } 521 522 @Override 523 public void cancel() { 524 mAwHandler.cancel(); 525 } 526 527 @Override 528 public boolean useHttpAuthUsernamePassword() { 529 // The documentation for this method says: 530 // Gets whether the credentials stored for the current host (i.e. the host 531 // for which {@link WebViewClient#onReceivedHttpAuthRequest} was called) 532 // are suitable for use. Credentials are not suitable if they have 533 // previously been rejected by the server for the current request. 534 // @return whether the credentials are suitable for use 535 // 536 // The CTS tests point out that it always returns true (at odds with 537 // the documentation). 538 // TODO: Decide whether to follow the docs or follow the classic 539 // implementation and update the docs. For now the latter, as it's 540 // easiest. (though not updating docs until this is resolved). 541 // See b/6204427. 542 return true; 543 } 544 } 545} 546