WebViewContentsClientAdapter.java revision d7fde5118cb6e238163c9755ab581b82eea47dba
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 // The Context that was passed to the WebView by the external client app. 139 private final Context mContext; 140 141 NullWebViewClient(Context context) { 142 mContext = context; 143 } 144 145 @Override 146 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { 147 // TODO: Investigate more and add a test case. 148 // This is a copy of what Clank does. The WebViewCore key handling code and Clank key 149 // handling code differ enough that it's not trivial to figure out how keycodes are 150 // being filtered. 151 int keyCode = event.getKeyCode(); 152 if (keyCode == KeyEvent.KEYCODE_MENU || 153 keyCode == KeyEvent.KEYCODE_HOME || 154 keyCode == KeyEvent.KEYCODE_BACK || 155 keyCode == KeyEvent.KEYCODE_CALL || 156 keyCode == KeyEvent.KEYCODE_ENDCALL || 157 keyCode == KeyEvent.KEYCODE_POWER || 158 keyCode == KeyEvent.KEYCODE_HEADSETHOOK || 159 keyCode == KeyEvent.KEYCODE_CAMERA || 160 keyCode == KeyEvent.KEYCODE_FOCUS || 161 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || 162 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE || 163 keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 164 return true; 165 } 166 return false; 167 } 168 169 @Override 170 public boolean shouldOverrideUrlLoading(WebView view, String url) { 171 Intent intent; 172 // Perform generic parsing of the URI to turn it into an Intent. 173 try { 174 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); 175 } catch (URISyntaxException ex) { 176 Log.w(TAG, "Bad URI " + url + ": " + ex.getMessage()); 177 return false; 178 } 179 // Sanitize the Intent, ensuring web pages can not bypass browser 180 // security (only access to BROWSABLE activities). 181 intent.addCategory(Intent.CATEGORY_BROWSABLE); 182 intent.setComponent(null); 183 // Pass the package name as application ID so that the intent from the 184 // same application can be opened in the same tab. 185 intent.putExtra(Browser.EXTRA_APPLICATION_ID, mContext.getPackageName()); 186 try { 187 mContext.startActivity(intent); 188 } catch (ActivityNotFoundException ex) { 189 Log.w(TAG, "No application can handle " + url); 190 return false; 191 } 192 return true; 193 } 194 } 195 196 void setWebViewClient(WebViewClient client) { 197 if (client != null) { 198 mWebViewClient = client; 199 } else { 200 mWebViewClient = new NullWebViewClient(mWebView.getContext()); 201 } 202 } 203 204 void setWebChromeClient(WebChromeClient client) { 205 if (client != null) { 206 mWebChromeClient = client; 207 } else { 208 // WebViewClassic doesn't implement any special behavior for a null WebChromeClient. 209 mWebChromeClient = new WebChromeClient(); 210 } 211 } 212 213 void setDownloadListener(DownloadListener listener) { 214 mDownloadListener = listener; 215 } 216 217 void setFindListener(WebView.FindListener listener) { 218 mFindListener = listener; 219 } 220 221 void setPictureListener(WebView.PictureListener listener) { 222 mPictureListener = listener; 223 } 224 225 //-------------------------------------------------------------------------------------------- 226 // Adapter for WebContentsDelegate methods. 227 //-------------------------------------------------------------------------------------------- 228 229 /** 230 * @see AwContentsClient#onProgressChanged(int) 231 */ 232 @Override 233 public void onProgressChanged(int progress) { 234 mWebChromeClient.onProgressChanged(mWebView, progress); 235 } 236 237 /** 238 * @see AwContentsClient#shouldInterceptRequest(java.lang.String) 239 */ 240 @Override 241 public InterceptedRequestData shouldInterceptRequest(String url) { 242 WebResourceResponse response = mWebViewClient.shouldInterceptRequest(mWebView, url); 243 if (response == null) return null; 244 return new InterceptedRequestData( 245 response.getMimeType(), 246 response.getEncoding(), 247 response.getData()); 248 } 249 250 /** 251 * @see AwContentsClient#shouldIgnoreNavigation(java.lang.String) 252 */ 253 @Override 254 public boolean shouldIgnoreNavigation(String url) { 255 return mWebViewClient.shouldOverrideUrlLoading(mWebView, url); 256 } 257 258 /** 259 * @see AwContentsClient#onUnhandledKeyEvent(android.view.KeyEvent) 260 */ 261 @Override 262 public void onUnhandledKeyEvent(KeyEvent event) { 263 mWebViewClient.onUnhandledKeyEvent(mWebView, event); 264 } 265 266 /** 267 * @see AwContentsClient#onConsoleMessage(android.webkit.ConsoleMessage) 268 */ 269 @Override 270 public boolean onConsoleMessage(ConsoleMessage consoleMessage) { 271 return mWebChromeClient.onConsoleMessage(consoleMessage); 272 } 273 274 /** 275 * @see AwContentsClient#onFindResultReceived(int,int,boolean) 276 */ 277 @Override 278 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 279 boolean isDoneCounting) { 280 if (mFindListener == null) return; 281 mFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, isDoneCounting); 282 } 283 284 @Override 285 public void onLoadResource(String url) { 286 mWebViewClient.onLoadResource(mWebView, url); 287 } 288 289 @Override 290 public boolean onCreateWindow(boolean isDialog, boolean isUserGesture) { 291 Message m = mUiThreadHandler.obtainMessage( 292 NEW_WEBVIEW_CREATED, mWebView.new WebViewTransport()); 293 return mWebChromeClient.onCreateWindow(mWebView, isDialog, isUserGesture, m); 294 } 295 296 /** 297 * @see AwContentsClient#onCloseWindow() 298 */ 299 /* @Override */ 300 public void onCloseWindow() { 301 mWebChromeClient.onCloseWindow(mWebView); 302 } 303 304 /** 305 * @see AwContentsClient#onRequestFocus() 306 */ 307 /* @Override */ 308 public void onRequestFocus() { 309 mWebChromeClient.onRequestFocus(mWebView); 310 } 311 312 //-------------------------------------------------------------------------------------------- 313 // Trivial Chrome -> WebViewClient mappings. 314 //-------------------------------------------------------------------------------------------- 315 316 /** 317 * @see ContentViewClient#onPageStarted(String) 318 */ 319 @Override 320 public void onPageStarted(String url) { 321 //TODO: Can't get the favicon till b/6094807 is fixed. 322 mWebViewClient.onPageStarted(mWebView, url, null); 323 } 324 325 /** 326 * @see ContentViewClient#onPageFinished(String) 327 */ 328 @Override 329 public void onPageFinished(String url) { 330 mWebViewClient.onPageFinished(mWebView, url); 331 332 // HACK: Fake a picture listener update, to allow CTS tests to progress. 333 // TODO: Remove when we have real picture listener updates implemented. 334 if (mPictureListener != null) { 335 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { 336 @Override 337 public void run() { 338 UnimplementedWebViewApi.invoke(); 339 if (mPictureListener != null) { 340 mPictureListener.onNewPicture(mWebView, new Picture()); 341 } 342 } 343 }, 100); 344 } 345 } 346 347 /** 348 * @see ContentViewClient#onReceivedError(int,String,String) 349 */ 350 @Override 351 public void onReceivedError(int errorCode, String description, String failingUrl) { 352 mWebViewClient.onReceivedError(mWebView, errorCode, description, failingUrl); 353 } 354 355 /** 356 * @see ContentViewClient#onUpdateTitle(String) 357 */ 358 @Override 359 public void onUpdateTitle(String title) { 360 mWebChromeClient.onReceivedTitle(mWebView, title); 361 } 362 363 364 /** 365 * @see ContentViewClient#shouldOverrideKeyEvent(KeyEvent) 366 */ 367 @Override 368 public boolean shouldOverrideKeyEvent(KeyEvent event) { 369 return mWebViewClient.shouldOverrideKeyEvent(mWebView, event); 370 } 371 372 373 //-------------------------------------------------------------------------------------------- 374 // More complicated mappings (including behavior choices) 375 //-------------------------------------------------------------------------------------------- 376 377 /** 378 * @see ContentViewClient#onTabCrash() 379 */ 380 @Override 381 public void onTabCrash() { 382 // The WebViewClassic implementation used a single process, so any crash would 383 // cause the application to terminate. WebViewChromium should have the same 384 // behavior as long as we run the renderer in-process. This needs to be revisited 385 // if we change that decision. 386 Log.e(TAG, "Renderer crash reported."); 387 mWebChromeClient.onCloseWindow(mWebView); 388 } 389 390 //-------------------------------------------------------------------------------------------- 391 // The TODO section 392 //-------------------------------------------------------------------------------------------- 393 394 395 /** 396 * @see ContentViewClient#onImeEvent() 397 */ 398 @Override 399 public void onImeEvent() { 400 } 401 402 /** 403 * @see ContentViewClient#onEvaluateJavaScriptResult(int,String) 404 */ 405 @Override 406 public void onEvaluateJavaScriptResult(int id, String jsonResult) { 407 } 408 409 /** 410 * @see ContentViewClient#onStartContentIntent(Context, String) 411 */ 412 @Override 413 public void onStartContentIntent(Context context, String contentUrl) { 414 } 415 416 private static class SimpleJsResultReceiver implements JsResult.ResultReceiver { 417 private JsResultReceiver mChromeResultReceiver; 418 419 public SimpleJsResultReceiver(JsResultReceiver receiver) { 420 mChromeResultReceiver = receiver; 421 } 422 423 @Override 424 public void onJsResultComplete(JsResult result) { 425 if (result.getResult()) { 426 mChromeResultReceiver.confirm(); 427 } else { 428 mChromeResultReceiver.cancel(); 429 } 430 } 431 } 432 433 private static class JsPromptResultReceiverAdapter implements JsResult.ResultReceiver { 434 private JsPromptResultReceiver mChromeResultReceiver; 435 private JsPromptResult mPromptResult; 436 437 public JsPromptResultReceiverAdapter(JsPromptResultReceiver receiver) { 438 mChromeResultReceiver = receiver; 439 // We hold onto the JsPromptResult here, just to avoid the need to downcast 440 // in onJsResultComplete. 441 mPromptResult = new JsPromptResult(this); 442 } 443 444 public JsPromptResult getPromptResult() { 445 return mPromptResult; 446 } 447 448 @Override 449 public void onJsResultComplete(JsResult result) { 450 if (result != mPromptResult) throw new RuntimeException("incorrect JsResult instance"); 451 if (mPromptResult.getResult()) { 452 mChromeResultReceiver.confirm(mPromptResult.getStringResult()); 453 } else { 454 mChromeResultReceiver.cancel(); 455 } 456 } 457 } 458 459 @Override 460 public void handleJsAlert(String url, String message, JsResultReceiver receiver) { 461 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 462 mWebChromeClient.onJsAlert(mWebView, url, message, res); 463 // TODO: Handle the case of the client returning false; 464 } 465 466 @Override 467 public void handleJsBeforeUnload(String url, String message, JsResultReceiver receiver) { 468 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 469 mWebChromeClient.onJsBeforeUnload(mWebView, url, message, res); 470 // TODO: Handle the case of the client returning false; 471 } 472 473 @Override 474 public void handleJsConfirm(String url, String message, JsResultReceiver receiver) { 475 JsResult res = new JsResult(new SimpleJsResultReceiver(receiver)); 476 mWebChromeClient.onJsConfirm(mWebView, url, message, res); 477 // TODO: Handle the case of the client returning false; 478 } 479 480 @Override 481 public void handleJsPrompt(String url, String message, String defaultValue, 482 JsPromptResultReceiver receiver) { 483 JsPromptResult res = new JsPromptResultReceiverAdapter(receiver).getPromptResult(); 484 mWebChromeClient.onJsPrompt(mWebView, url, message, defaultValue, res); 485 // TODO: Handle the case of the client returning false; 486 } 487 488 @Override 489 public void onReceivedHttpAuthRequest(AwHttpAuthHandler handler, String host, String realm) { 490 mWebViewClient.onReceivedHttpAuthRequest(mWebView, 491 new AwHttpAuthHandlerAdapter(handler), host, realm); 492 } 493 494 @Override 495 public void onFormResubmission(Message dontResend, Message resend) { 496 mWebViewClient.onFormResubmission(mWebView, dontResend, resend); 497 } 498 499 @Override 500 public void onDownloadStart(String url, 501 String userAgent, 502 String contentDisposition, 503 String mimeType, 504 long contentLength) { 505 if (mDownloadListener != null) { 506 mDownloadListener.onDownloadStart(url, 507 userAgent, 508 contentDisposition, 509 mimeType, 510 contentLength); 511 } 512 } 513 514 515 private static class AwHttpAuthHandlerAdapter extends android.webkit.HttpAuthHandler { 516 private AwHttpAuthHandler mAwHandler; 517 518 public AwHttpAuthHandlerAdapter(AwHttpAuthHandler awHandler) { 519 mAwHandler = awHandler; 520 } 521 522 @Override 523 public void proceed(String username, String password) { 524 if (username == null) { 525 username = ""; 526 } 527 528 if (password == null) { 529 password = ""; 530 } 531 mAwHandler.proceed(username, password); 532 } 533 534 @Override 535 public void cancel() { 536 mAwHandler.cancel(); 537 } 538 539 @Override 540 public boolean useHttpAuthUsernamePassword() { 541 // The documentation for this method says: 542 // Gets whether the credentials stored for the current host (i.e. the host 543 // for which {@link WebViewClient#onReceivedHttpAuthRequest} was called) 544 // are suitable for use. Credentials are not suitable if they have 545 // previously been rejected by the server for the current request. 546 // @return whether the credentials are suitable for use 547 // 548 // The CTS tests point out that it always returns true (at odds with 549 // the documentation). 550 // TODO: Decide whether to follow the docs or follow the classic 551 // implementation and update the docs. For now the latter, as it's 552 // easiest. (though not updating docs until this is resolved). 553 // See b/6204427. 554 return true; 555 } 556 } 557} 558