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