WebViewContentsClientAdapter.java revision fe742c86d6f6e12bd339c9c2efd947d55c910e2d
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 */ 398 @Override 399 public void onStartContentIntent(Context context, String contentUrl) { 400 } 401 402 private static class SimpleJsResultReceiver implements JsResult.ResultReceiver { 403 private JsResultReceiver mChromeResultReceiver; 404 405 public SimpleJsResultReceiver(JsResultReceiver receiver) { 406 mChromeResultReceiver = receiver; 407 } 408 409 @Override 410 public void onJsResultComplete(JsResult result) { 411 if (result.getResult()) { 412 mChromeResultReceiver.confirm(); 413 } else { 414 mChromeResultReceiver.cancel(); 415 } 416 } 417 } 418 419 private static class JsPromptResultReceiverAdapter implements JsResult.ResultReceiver { 420 private JsPromptResultReceiver mChromeResultReceiver; 421 private JsPromptResult mPromptResult; 422 423 public JsPromptResultReceiverAdapter(JsPromptResultReceiver receiver) { 424 mChromeResultReceiver = receiver; 425 // We hold onto the JsPromptResult here, just to avoid the need to downcast 426 // in onJsResultComplete. 427 mPromptResult = new JsPromptResult(this); 428 } 429 430 public JsPromptResult getPromptResult() { 431 return mPromptResult; 432 } 433 434 @Override 435 public void onJsResultComplete(JsResult result) { 436 if (result != mPromptResult) throw new RuntimeException("incorrect JsResult instance"); 437 if (mPromptResult.getResult()) { 438 mChromeResultReceiver.confirm(mPromptResult.getStringResult()); 439 } else { 440 mChromeResultReceiver.cancel(); 441 } 442 } 443 } 444 445 @Override 446 public void handleJsAlert(String url, String message, JsResultReceiver receiver) { 447 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 448 mWebChromeClient.onJsAlert(mWebView, url, message, res); 449 // TODO: Handle the case of the client returning false; 450 } 451 452 @Override 453 public void handleJsBeforeUnload(String url, String message, JsResultReceiver receiver) { 454 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 455 mWebChromeClient.onJsBeforeUnload(mWebView, url, message, res); 456 // TODO: Handle the case of the client returning false; 457 } 458 459 @Override 460 public void handleJsConfirm(String url, String message, JsResultReceiver receiver) { 461 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 462 mWebChromeClient.onJsConfirm(mWebView, url, message, res); 463 // TODO: Handle the case of the client returning false; 464 } 465 466 @Override 467 public void handleJsPrompt(String url, String message, String defaultValue, 468 JsPromptResultReceiver receiver) { 469 JsPromptResult res = new JsPromptResultReceiverAdapter(receiver).getPromptResult(); 470 mWebChromeClient.onJsPrompt(mWebView, url, message, defaultValue, res); 471 // TODO: Handle the case of the client returning false; 472 } 473 474 @Override 475 public void onReceivedHttpAuthRequest(AwHttpAuthHandler handler, String host, String realm) { 476 mWebViewClient.onReceivedHttpAuthRequest(mWebView, 477 new AwHttpAuthHandlerAdapter(handler), host, realm); 478 } 479 480 @Override 481 public void onFormResubmission(Message dontResend, Message resend) { 482 mWebViewClient.onFormResubmission(mWebView, dontResend, resend); 483 } 484 485 @Override 486 public void onDownloadStart(String url, 487 String userAgent, 488 String contentDisposition, 489 String mimeType, 490 long contentLength) { 491 if (mDownloadListener != null) { 492 mDownloadListener.onDownloadStart(url, 493 userAgent, 494 contentDisposition, 495 mimeType, 496 contentLength); 497 } 498 } 499 500 501 private static class AwHttpAuthHandlerAdapter extends android.webkit.HttpAuthHandler { 502 private AwHttpAuthHandler mAwHandler; 503 504 public AwHttpAuthHandlerAdapter(AwHttpAuthHandler awHandler) { 505 mAwHandler = awHandler; 506 } 507 508 @Override 509 public void proceed(String username, String password) { 510 if (username == null) { 511 username = ""; 512 } 513 514 if (password == null) { 515 password = ""; 516 } 517 mAwHandler.proceed(username, password); 518 } 519 520 @Override 521 public void cancel() { 522 mAwHandler.cancel(); 523 } 524 525 @Override 526 public boolean useHttpAuthUsernamePassword() { 527 // The documentation for this method says: 528 // Gets whether the credentials stored for the current host (i.e. the host 529 // for which {@link WebViewClient#onReceivedHttpAuthRequest} was called) 530 // are suitable for use. Credentials are not suitable if they have 531 // previously been rejected by the server for the current request. 532 // @return whether the credentials are suitable for use 533 // 534 // The CTS tests point out that it always returns true (at odds with 535 // the documentation). 536 // TODO: Decide whether to follow the docs or follow the classic 537 // implementation and update the docs. For now the latter, as it's 538 // easiest. (though not updating docs until this is resolved). 539 // See b/6204427. 540 return true; 541 } 542 } 543} 544