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 17 package android.webkit; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.annotation.SuppressLint; 22 import android.annotation.SystemApi; 23 import android.content.Intent; 24 import android.content.res.Configuration; 25 import android.graphics.Bitmap; 26 import android.graphics.Canvas; 27 import android.graphics.Paint; 28 import android.graphics.Picture; 29 import android.graphics.Rect; 30 import android.graphics.drawable.Drawable; 31 import android.net.Uri; 32 import android.net.http.SslCertificate; 33 import android.os.Bundle; 34 import android.os.Handler; 35 import android.os.Message; 36 import android.print.PrintDocumentAdapter; 37 import android.util.LongSparseArray; 38 import android.util.SparseArray; 39 import android.view.DragEvent; 40 import android.view.KeyEvent; 41 import android.view.MotionEvent; 42 import android.view.PointerIcon; 43 import android.view.View; 44 import android.view.ViewGroup.LayoutParams; 45 import android.view.WindowInsets; 46 import android.view.accessibility.AccessibilityEvent; 47 import android.view.accessibility.AccessibilityNodeInfo; 48 import android.view.accessibility.AccessibilityNodeProvider; 49 import android.view.autofill.AutofillId; 50 import android.view.autofill.AutofillValue; 51 import android.view.inputmethod.EditorInfo; 52 import android.view.inputmethod.InputConnection; 53 import android.view.textclassifier.TextClassifier; 54 import android.view.translation.TranslationCapability; 55 import android.view.translation.TranslationSpec.DataFormat; 56 import android.view.translation.ViewTranslationRequest; 57 import android.view.translation.ViewTranslationResponse; 58 import android.webkit.WebView.HitTestResult; 59 import android.webkit.WebView.PictureListener; 60 import android.webkit.WebView.VisualStateCallback; 61 62 63 import java.io.BufferedWriter; 64 import java.io.File; 65 import java.util.List; 66 import java.util.Map; 67 import java.util.concurrent.Executor; 68 import java.util.function.Consumer; 69 70 /** 71 * WebView backend provider interface: this interface is the abstract backend to a WebView 72 * instance; each WebView object is bound to exactly one WebViewProvider object which implements 73 * the runtime behavior of that WebView. 74 * 75 * All methods must behave as per their namesake in {@link WebView}, unless otherwise noted. 76 * 77 * @hide Not part of the public API; only required by system implementors. 78 */ 79 @SystemApi 80 public interface WebViewProvider { 81 //------------------------------------------------------------------------- 82 // Main interface for backend provider of the WebView class. 83 //------------------------------------------------------------------------- 84 /** 85 * Initialize this WebViewProvider instance. Called after the WebView has fully constructed. 86 * @param javaScriptInterfaces is a Map of interface names, as keys, and 87 * object implementing those interfaces, as values. 88 * @param privateBrowsing If {@code true} the web view will be initialized in private / 89 * incognito mode. 90 */ init(Map<String, Object> javaScriptInterfaces, boolean privateBrowsing)91 public void init(Map<String, Object> javaScriptInterfaces, 92 boolean privateBrowsing); 93 94 // Deprecated - should never be called setHorizontalScrollbarOverlay(boolean overlay)95 public void setHorizontalScrollbarOverlay(boolean overlay); 96 97 // Deprecated - should never be called setVerticalScrollbarOverlay(boolean overlay)98 public void setVerticalScrollbarOverlay(boolean overlay); 99 100 // Deprecated - should never be called overlayHorizontalScrollbar()101 public boolean overlayHorizontalScrollbar(); 102 103 // Deprecated - should never be called overlayVerticalScrollbar()104 public boolean overlayVerticalScrollbar(); 105 getVisibleTitleHeight()106 public int getVisibleTitleHeight(); 107 getCertificate()108 public SslCertificate getCertificate(); 109 setCertificate(SslCertificate certificate)110 public void setCertificate(SslCertificate certificate); 111 savePassword(String host, String username, String password)112 public void savePassword(String host, String username, String password); 113 setHttpAuthUsernamePassword(String host, String realm, String username, String password)114 public void setHttpAuthUsernamePassword(String host, String realm, 115 String username, String password); 116 getHttpAuthUsernamePassword(String host, String realm)117 public String[] getHttpAuthUsernamePassword(String host, String realm); 118 119 /** 120 * See {@link WebView#destroy()}. 121 * As well as releasing the internal state and resources held by the implementation, 122 * the provider should null all references it holds on the WebView proxy class, and ensure 123 * no further method calls are made to it. 124 */ destroy()125 public void destroy(); 126 setNetworkAvailable(boolean networkUp)127 public void setNetworkAvailable(boolean networkUp); 128 saveState(Bundle outState)129 public WebBackForwardList saveState(Bundle outState); 130 savePicture(Bundle b, final File dest)131 public boolean savePicture(Bundle b, final File dest); 132 restorePicture(Bundle b, File src)133 public boolean restorePicture(Bundle b, File src); 134 restoreState(Bundle inState)135 public WebBackForwardList restoreState(Bundle inState); 136 loadUrl(String url, Map<String, String> additionalHttpHeaders)137 public void loadUrl(String url, Map<String, String> additionalHttpHeaders); 138 loadUrl(String url)139 public void loadUrl(String url); 140 postUrl(String url, byte[] postData)141 public void postUrl(String url, byte[] postData); 142 loadData(String data, String mimeType, String encoding)143 public void loadData(String data, String mimeType, String encoding); 144 loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)145 public void loadDataWithBaseURL(String baseUrl, String data, 146 String mimeType, String encoding, String historyUrl); 147 evaluateJavaScript(String script, ValueCallback<String> resultCallback)148 public void evaluateJavaScript(String script, ValueCallback<String> resultCallback); 149 saveWebArchive(String filename)150 public void saveWebArchive(String filename); 151 saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback)152 public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback); 153 stopLoading()154 public void stopLoading(); 155 reload()156 public void reload(); 157 canGoBack()158 public boolean canGoBack(); 159 goBack()160 public void goBack(); 161 canGoForward()162 public boolean canGoForward(); 163 goForward()164 public void goForward(); 165 canGoBackOrForward(int steps)166 public boolean canGoBackOrForward(int steps); 167 goBackOrForward(int steps)168 public void goBackOrForward(int steps); 169 isPrivateBrowsingEnabled()170 public boolean isPrivateBrowsingEnabled(); 171 pageUp(boolean top)172 public boolean pageUp(boolean top); 173 pageDown(boolean bottom)174 public boolean pageDown(boolean bottom); 175 insertVisualStateCallback(long requestId, VisualStateCallback callback)176 public void insertVisualStateCallback(long requestId, VisualStateCallback callback); 177 clearView()178 public void clearView(); 179 capturePicture()180 public Picture capturePicture(); 181 createPrintDocumentAdapter(String documentName)182 public PrintDocumentAdapter createPrintDocumentAdapter(String documentName); 183 getScale()184 public float getScale(); 185 setInitialScale(int scaleInPercent)186 public void setInitialScale(int scaleInPercent); 187 invokeZoomPicker()188 public void invokeZoomPicker(); 189 getHitTestResult()190 public HitTestResult getHitTestResult(); 191 requestFocusNodeHref(Message hrefMsg)192 public void requestFocusNodeHref(Message hrefMsg); 193 requestImageRef(Message msg)194 public void requestImageRef(Message msg); 195 getUrl()196 public String getUrl(); 197 getOriginalUrl()198 public String getOriginalUrl(); 199 getTitle()200 public String getTitle(); 201 getFavicon()202 public Bitmap getFavicon(); 203 getTouchIconUrl()204 public String getTouchIconUrl(); 205 getProgress()206 public int getProgress(); 207 getContentHeight()208 public int getContentHeight(); 209 getContentWidth()210 public int getContentWidth(); 211 pauseTimers()212 public void pauseTimers(); 213 resumeTimers()214 public void resumeTimers(); 215 onPause()216 public void onPause(); 217 onResume()218 public void onResume(); 219 isPaused()220 public boolean isPaused(); 221 freeMemory()222 public void freeMemory(); 223 clearCache(boolean includeDiskFiles)224 public void clearCache(boolean includeDiskFiles); 225 clearFormData()226 public void clearFormData(); 227 clearHistory()228 public void clearHistory(); 229 clearSslPreferences()230 public void clearSslPreferences(); 231 copyBackForwardList()232 public WebBackForwardList copyBackForwardList(); 233 setFindListener(WebView.FindListener listener)234 public void setFindListener(WebView.FindListener listener); 235 findNext(boolean forward)236 public void findNext(boolean forward); 237 findAll(String find)238 public int findAll(String find); 239 findAllAsync(String find)240 public void findAllAsync(String find); 241 showFindDialog(String text, boolean showIme)242 public boolean showFindDialog(String text, boolean showIme); 243 clearMatches()244 public void clearMatches(); 245 documentHasImages(Message response)246 public void documentHasImages(Message response); 247 setWebViewClient(WebViewClient client)248 public void setWebViewClient(WebViewClient client); 249 getWebViewClient()250 public WebViewClient getWebViewClient(); 251 252 @Nullable getWebViewRenderProcess()253 public WebViewRenderProcess getWebViewRenderProcess(); 254 setWebViewRenderProcessClient( @ullable Executor executor, @Nullable WebViewRenderProcessClient client)255 public void setWebViewRenderProcessClient( 256 @Nullable Executor executor, 257 @Nullable WebViewRenderProcessClient client); 258 259 @Nullable getWebViewRenderProcessClient()260 public WebViewRenderProcessClient getWebViewRenderProcessClient(); 261 setDownloadListener(DownloadListener listener)262 public void setDownloadListener(DownloadListener listener); 263 setWebChromeClient(WebChromeClient client)264 public void setWebChromeClient(WebChromeClient client); 265 getWebChromeClient()266 public WebChromeClient getWebChromeClient(); 267 setPictureListener(PictureListener listener)268 public void setPictureListener(PictureListener listener); 269 addJavascriptInterface(Object obj, String interfaceName)270 public void addJavascriptInterface(Object obj, String interfaceName); 271 removeJavascriptInterface(String interfaceName)272 public void removeJavascriptInterface(String interfaceName); 273 createWebMessageChannel()274 public WebMessagePort[] createWebMessageChannel(); 275 postMessageToMainFrame(WebMessage message, Uri targetOrigin)276 public void postMessageToMainFrame(WebMessage message, Uri targetOrigin); 277 getSettings()278 public WebSettings getSettings(); 279 setMapTrackballToArrowKeys(boolean setMap)280 public void setMapTrackballToArrowKeys(boolean setMap); 281 flingScroll(int vx, int vy)282 public void flingScroll(int vx, int vy); 283 getZoomControls()284 public View getZoomControls(); 285 canZoomIn()286 public boolean canZoomIn(); 287 canZoomOut()288 public boolean canZoomOut(); 289 zoomBy(float zoomFactor)290 public boolean zoomBy(float zoomFactor); 291 zoomIn()292 public boolean zoomIn(); 293 zoomOut()294 public boolean zoomOut(); 295 dumpViewHierarchyWithProperties(BufferedWriter out, int level)296 public void dumpViewHierarchyWithProperties(BufferedWriter out, int level); 297 findHierarchyView(String className, int hashCode)298 public View findHierarchyView(String className, int hashCode); 299 setRendererPriorityPolicy(int rendererRequestedPriority, boolean waivedWhenNotVisible)300 public void setRendererPriorityPolicy(int rendererRequestedPriority, boolean waivedWhenNotVisible); 301 getRendererRequestedPriority()302 public int getRendererRequestedPriority(); 303 getRendererPriorityWaivedWhenNotVisible()304 public boolean getRendererPriorityWaivedWhenNotVisible(); 305 306 @SuppressWarnings("unused") setTextClassifier(@ullable TextClassifier textClassifier)307 public default void setTextClassifier(@Nullable TextClassifier textClassifier) {} 308 309 @NonNull getTextClassifier()310 public default TextClassifier getTextClassifier() { return TextClassifier.NO_OP; } 311 312 //------------------------------------------------------------------------- 313 // Provider internal methods 314 //------------------------------------------------------------------------- 315 316 /** 317 * @return the ViewDelegate implementation. This provides the functionality to back all of 318 * the name-sake functions from the View and ViewGroup base classes of WebView. 319 */ getViewDelegate()320 /* package */ ViewDelegate getViewDelegate(); 321 322 /** 323 * @return a ScrollDelegate implementation. Normally this would be same object as is 324 * returned by getViewDelegate(). 325 */ getScrollDelegate()326 /* package */ ScrollDelegate getScrollDelegate(); 327 328 /** 329 * Only used by FindActionModeCallback to inform providers that the find dialog has 330 * been dismissed. 331 */ notifyFindDialogDismissed()332 public void notifyFindDialogDismissed(); 333 334 //------------------------------------------------------------------------- 335 // View / ViewGroup delegation methods 336 //------------------------------------------------------------------------- 337 338 /** 339 * Provides mechanism for the name-sake methods declared in View and ViewGroup to be delegated 340 * into the WebViewProvider instance. 341 * NOTE: For many of these methods, the WebView will provide a super.Foo() call before or after 342 * making the call into the provider instance. This is done for convenience in the common case 343 * of maintaining backward compatibility. For remaining super class calls (e.g. where the 344 * provider may need to only conditionally make the call based on some internal state) see the 345 * {@link WebView.PrivateAccess} callback class. 346 */ 347 // TODO: See if the pattern of the super-class calls can be rationalized at all, and document 348 // the remainder on the methods below. 349 interface ViewDelegate { shouldDelayChildPressedState()350 public boolean shouldDelayChildPressedState(); 351 onProvideVirtualStructure(android.view.ViewStructure structure)352 public void onProvideVirtualStructure(android.view.ViewStructure structure); 353 onProvideAutofillVirtualStructure( @uppressWarnings"unused") android.view.ViewStructure structure, @SuppressWarnings("unused") int flags)354 default void onProvideAutofillVirtualStructure( 355 @SuppressWarnings("unused") android.view.ViewStructure structure, 356 @SuppressWarnings("unused") int flags) { 357 } 358 autofill(@uppressWarnings"unused") SparseArray<AutofillValue> values)359 default void autofill(@SuppressWarnings("unused") SparseArray<AutofillValue> values) { 360 } 361 isVisibleToUserForAutofill(@uppressWarnings"unused") int virtualId)362 default boolean isVisibleToUserForAutofill(@SuppressWarnings("unused") int virtualId) { 363 return true; // true is the default value returned by View.isVisibleToUserForAutofill() 364 } 365 onProvideContentCaptureStructure( @onNull @uppressWarnings"unused") android.view.ViewStructure structure, @SuppressWarnings("unused") int flags)366 default void onProvideContentCaptureStructure( 367 @NonNull @SuppressWarnings("unused") android.view.ViewStructure structure, 368 @SuppressWarnings("unused") int flags) { 369 } 370 371 @SuppressLint("NullableCollection") onCreateVirtualViewTranslationRequests( @onNull @uppressWarnings"unused") long[] virtualIds, @NonNull @SuppressWarnings("unused") @DataFormat int[] supportedFormats, @NonNull @SuppressWarnings("unused") Consumer<ViewTranslationRequest> requestsCollector)372 default void onCreateVirtualViewTranslationRequests( 373 @NonNull @SuppressWarnings("unused") long[] virtualIds, 374 @NonNull @SuppressWarnings("unused") @DataFormat int[] supportedFormats, 375 @NonNull @SuppressWarnings("unused") 376 Consumer<ViewTranslationRequest> requestsCollector) { 377 } 378 onVirtualViewTranslationResponses( @onNull @uppressWarnings"unused") LongSparseArray<ViewTranslationResponse> response)379 default void onVirtualViewTranslationResponses( 380 @NonNull @SuppressWarnings("unused") 381 LongSparseArray<ViewTranslationResponse> response) { 382 } 383 dispatchCreateViewTranslationRequest( @onNull @uppressWarnings"unused") Map<AutofillId, long[]> viewIds, @NonNull @SuppressWarnings("unused") @DataFormat int[] supportedFormats, @Nullable @SuppressWarnings("unused") TranslationCapability capability, @NonNull @SuppressWarnings("unused") List<ViewTranslationRequest> requests)384 default void dispatchCreateViewTranslationRequest( 385 @NonNull @SuppressWarnings("unused") Map<AutofillId, long[]> viewIds, 386 @NonNull @SuppressWarnings("unused") @DataFormat int[] supportedFormats, 387 @Nullable @SuppressWarnings("unused") TranslationCapability capability, 388 @NonNull @SuppressWarnings("unused") List<ViewTranslationRequest> requests) { 389 390 } 391 getAccessibilityNodeProvider()392 public AccessibilityNodeProvider getAccessibilityNodeProvider(); 393 onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)394 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info); 395 onInitializeAccessibilityEvent(AccessibilityEvent event)396 public void onInitializeAccessibilityEvent(AccessibilityEvent event); 397 performAccessibilityAction(int action, Bundle arguments)398 public boolean performAccessibilityAction(int action, Bundle arguments); 399 setOverScrollMode(int mode)400 public void setOverScrollMode(int mode); 401 setScrollBarStyle(int style)402 public void setScrollBarStyle(int style); 403 onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, int l, int t, int r, int b)404 public void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, int l, int t, 405 int r, int b); 406 onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)407 public void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY); 408 onWindowVisibilityChanged(int visibility)409 public void onWindowVisibilityChanged(int visibility); 410 onDraw(Canvas canvas)411 public void onDraw(Canvas canvas); 412 setLayoutParams(LayoutParams layoutParams)413 public void setLayoutParams(LayoutParams layoutParams); 414 performLongClick()415 public boolean performLongClick(); 416 onConfigurationChanged(Configuration newConfig)417 public void onConfigurationChanged(Configuration newConfig); 418 onCreateInputConnection(EditorInfo outAttrs)419 public InputConnection onCreateInputConnection(EditorInfo outAttrs); 420 onDragEvent(DragEvent event)421 public boolean onDragEvent(DragEvent event); 422 onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)423 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event); 424 onKeyDown(int keyCode, KeyEvent event)425 public boolean onKeyDown(int keyCode, KeyEvent event); 426 onKeyUp(int keyCode, KeyEvent event)427 public boolean onKeyUp(int keyCode, KeyEvent event); 428 onAttachedToWindow()429 public void onAttachedToWindow(); 430 onDetachedFromWindow()431 public void onDetachedFromWindow(); 432 onMovedToDisplay(int displayId, Configuration config)433 public default void onMovedToDisplay(int displayId, Configuration config) {} 434 onVisibilityChanged(View changedView, int visibility)435 public void onVisibilityChanged(View changedView, int visibility); 436 onWindowFocusChanged(boolean hasWindowFocus)437 public void onWindowFocusChanged(boolean hasWindowFocus); 438 onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)439 public void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect); 440 setFrame(int left, int top, int right, int bottom)441 public boolean setFrame(int left, int top, int right, int bottom); 442 onSizeChanged(int w, int h, int ow, int oh)443 public void onSizeChanged(int w, int h, int ow, int oh); 444 onScrollChanged(int l, int t, int oldl, int oldt)445 public void onScrollChanged(int l, int t, int oldl, int oldt); 446 dispatchKeyEvent(KeyEvent event)447 public boolean dispatchKeyEvent(KeyEvent event); 448 onTouchEvent(MotionEvent ev)449 public boolean onTouchEvent(MotionEvent ev); 450 onHoverEvent(MotionEvent event)451 public boolean onHoverEvent(MotionEvent event); 452 onGenericMotionEvent(MotionEvent event)453 public boolean onGenericMotionEvent(MotionEvent event); 454 onTrackballEvent(MotionEvent ev)455 public boolean onTrackballEvent(MotionEvent ev); 456 requestFocus(int direction, Rect previouslyFocusedRect)457 public boolean requestFocus(int direction, Rect previouslyFocusedRect); 458 onMeasure(int widthMeasureSpec, int heightMeasureSpec)459 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec); 460 requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)461 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate); 462 setBackgroundColor(int color)463 public void setBackgroundColor(int color); 464 setLayerType(int layerType, Paint paint)465 public void setLayerType(int layerType, Paint paint); 466 preDispatchDraw(Canvas canvas)467 public void preDispatchDraw(Canvas canvas); 468 onStartTemporaryDetach()469 public void onStartTemporaryDetach(); 470 onFinishTemporaryDetach()471 public void onFinishTemporaryDetach(); 472 onActivityResult(int requestCode, int resultCode, Intent data)473 public void onActivityResult(int requestCode, int resultCode, Intent data); 474 getHandler(Handler originalHandler)475 public Handler getHandler(Handler originalHandler); 476 findFocus(View originalFocusedView)477 public View findFocus(View originalFocusedView); 478 479 @SuppressWarnings("unused") onCheckIsTextEditor()480 default boolean onCheckIsTextEditor() { 481 return false; 482 } 483 484 /** 485 * @see View#onApplyWindowInsets(WindowInsets). 486 * 487 * <p>This is the entry point for the WebView implementation to override. It returns 488 * {@code null} when the WebView implementation hasn't implemented the WindowInsets support 489 * on S yet. In this case, the {@link View#onApplyWindowInsets()} super method will be 490 * called instead. 491 * 492 * @param insets Insets to apply 493 * @return The supplied insets with any applied insets consumed. 494 */ 495 @SuppressWarnings("unused") 496 @Nullable onApplyWindowInsets(@ullable WindowInsets insets)497 default WindowInsets onApplyWindowInsets(@Nullable WindowInsets insets) { 498 return null; 499 } 500 501 /** 502 * @hide Only used by WebView. 503 */ 504 @SuppressWarnings("unused") 505 @Nullable onResolvePointerIcon(@onNull MotionEvent event, int pointerIndex)506 default PointerIcon onResolvePointerIcon(@NonNull MotionEvent event, int pointerIndex) { 507 return null; 508 } 509 } 510 511 interface ScrollDelegate { 512 // These methods are declared protected in the ViewGroup base class. This interface 513 // exists to promote them to public so they may be called by the WebView proxy class. 514 // TODO: Combine into ViewDelegate? 515 /** 516 * See {@link android.webkit.WebView#computeHorizontalScrollRange} 517 */ computeHorizontalScrollRange()518 public int computeHorizontalScrollRange(); 519 520 /** 521 * See {@link android.webkit.WebView#computeHorizontalScrollOffset} 522 */ computeHorizontalScrollOffset()523 public int computeHorizontalScrollOffset(); 524 525 /** 526 * See {@link android.webkit.WebView#computeVerticalScrollRange} 527 */ computeVerticalScrollRange()528 public int computeVerticalScrollRange(); 529 530 /** 531 * See {@link android.webkit.WebView#computeVerticalScrollOffset} 532 */ computeVerticalScrollOffset()533 public int computeVerticalScrollOffset(); 534 535 /** 536 * See {@link android.webkit.WebView#computeVerticalScrollExtent} 537 */ computeVerticalScrollExtent()538 public int computeVerticalScrollExtent(); 539 540 /** 541 * See {@link android.webkit.WebView#computeScroll} 542 */ computeScroll()543 public void computeScroll(); 544 } 545 } 546