1 /*
2  * Copyright (C) 2014 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.app.ActivityThread;
23 import android.app.Application;
24 import android.app.ResourcesManager;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.content.Context;
27 import android.content.pm.ApplicationInfo;
28 import android.content.res.Resources;
29 import android.graphics.Canvas;
30 import android.graphics.RecordingCanvas;
31 import android.os.RemoteException;
32 import android.os.SystemProperties;
33 import android.os.Trace;
34 import android.util.SparseArray;
35 import android.view.View;
36 import android.view.ViewRootImpl;
37 
38 import com.android.internal.util.ArrayUtils;
39 
40 /**
41  * Delegate used by the WebView provider implementation to access
42  * the required framework functionality needed to implement a {@link WebView}.
43  *
44  * @hide
45  */
46 @SystemApi
47 public final class WebViewDelegate {
48 
49     @UnsupportedAppUsage
WebViewDelegate()50     /* package */ WebViewDelegate() { }
51 
52     /**
53      * Listener that gets notified whenever tracing has been enabled/disabled.
54      */
55     public interface OnTraceEnabledChangeListener {
onTraceEnabledChange(boolean enabled)56         void onTraceEnabledChange(boolean enabled);
57     }
58 
59     /**
60      * Register a callback to be invoked when tracing for the WebView component has been
61      * enabled/disabled.
62      */
setOnTraceEnabledChangeListener(final OnTraceEnabledChangeListener listener)63     public void setOnTraceEnabledChangeListener(final OnTraceEnabledChangeListener listener) {
64         SystemProperties.addChangeCallback(new Runnable() {
65             @Override
66             public void run() {
67                 listener.onTraceEnabledChange(isTraceTagEnabled());
68             }
69         });
70     }
71 
72     /**
73      * Returns {@code true} if the WebView trace tag is enabled and {@code false} otherwise.
74      */
isTraceTagEnabled()75     public boolean isTraceTagEnabled() {
76         return Trace.isTagEnabled(Trace.TRACE_TAG_WEBVIEW);
77     }
78 
79     /**
80      * Returns {@code true} if the draw GL functor can be invoked (see {@link #invokeDrawGlFunctor})
81      * and {@code false} otherwise.
82      *
83      * @deprecated Use {@link #drawWebViewFunctor(Canvas, int)}
84      */
85     @Deprecated
canInvokeDrawGlFunctor(View containerView)86     public boolean canInvokeDrawGlFunctor(View containerView) {
87         return true;
88     }
89 
90     /**
91      * Invokes the draw GL functor. If waitForCompletion is {@code false} the functor
92      * may be invoked asynchronously.
93      *
94      * @param nativeDrawGLFunctor the pointer to the native functor that implements
95      *        system/core/include/utils/Functor.h
96      * @deprecated Use {@link #drawWebViewFunctor(Canvas, int)}
97      */
98     @Deprecated
invokeDrawGlFunctor(View containerView, long nativeDrawGLFunctor, boolean waitForCompletion)99     public void invokeDrawGlFunctor(View containerView, long nativeDrawGLFunctor,
100             boolean waitForCompletion) {
101         ViewRootImpl.invokeFunctor(nativeDrawGLFunctor, waitForCompletion);
102     }
103 
104     /**
105      * Calls the function specified with the nativeDrawGLFunctor functor pointer. This
106      * functionality is used by the WebView for calling into their renderer from the
107      * framework display lists.
108      *
109      * @param canvas a hardware accelerated canvas (see {@link Canvas#isHardwareAccelerated()})
110      * @param nativeDrawGLFunctor the pointer to the native functor that implements
111      *        system/core/include/utils/Functor.h
112      * @throws IllegalArgumentException if the canvas is not hardware accelerated
113      * @deprecated Use {@link #drawWebViewFunctor(Canvas, int)}
114      */
115     @Deprecated
callDrawGlFunction(Canvas canvas, long nativeDrawGLFunctor)116     public void callDrawGlFunction(Canvas canvas, long nativeDrawGLFunctor) {
117         if (!(canvas instanceof RecordingCanvas)) {
118             // Canvas#isHardwareAccelerated() is only true for subclasses of HardwareCanvas.
119             throw new IllegalArgumentException(canvas.getClass().getName()
120                     + " is not a DisplayList canvas");
121         }
122         ((RecordingCanvas) canvas).drawGLFunctor2(nativeDrawGLFunctor, null);
123     }
124 
125     /**
126      * Calls the function specified with the nativeDrawGLFunctor functor pointer. This
127      * functionality is used by the WebView for calling into their renderer from the
128      * framework display lists.
129      *
130      * @param canvas a hardware accelerated canvas (see {@link Canvas#isHardwareAccelerated()})
131      * @param nativeDrawGLFunctor the pointer to the native functor that implements
132      *        system/core/include/utils/Functor.h
133      * @param releasedRunnable Called when this nativeDrawGLFunctor is no longer referenced by this
134      *        canvas, so is safe to be destroyed.
135      * @throws IllegalArgumentException if the canvas is not hardware accelerated
136      * @deprecated Use {@link #drawWebViewFunctor(Canvas, int)}
137      */
138     @Deprecated
callDrawGlFunction(@onNull Canvas canvas, long nativeDrawGLFunctor, @Nullable Runnable releasedRunnable)139     public void callDrawGlFunction(@NonNull Canvas canvas, long nativeDrawGLFunctor,
140             @Nullable Runnable releasedRunnable) {
141         if (!(canvas instanceof RecordingCanvas)) {
142             // Canvas#isHardwareAccelerated() is only true for subclasses of HardwareCanvas.
143             throw new IllegalArgumentException(canvas.getClass().getName()
144                     + " is not a DisplayList canvas");
145         }
146         ((RecordingCanvas) canvas).drawGLFunctor2(nativeDrawGLFunctor, releasedRunnable);
147     }
148 
149     /**
150      * Call webview draw functor. See API in draw_fn.h.
151      * @param canvas a {@link RecordingCanvas}.
152      * @param functor created by AwDrawFn_CreateFunctor in draw_fn.h.
153      */
drawWebViewFunctor(@onNull Canvas canvas, int functor)154     public void drawWebViewFunctor(@NonNull Canvas canvas, int functor) {
155         if (!(canvas instanceof RecordingCanvas)) {
156             // Canvas#isHardwareAccelerated() is only true for subclasses of RecordingCanvas.
157             throw new IllegalArgumentException(canvas.getClass().getName()
158                     + " is not a RecordingCanvas canvas");
159         }
160         ((RecordingCanvas) canvas).drawWebViewFunctor(functor);
161     }
162 
163     /**
164      * Detaches the draw GL functor.
165      *
166      * @param nativeDrawGLFunctor the pointer to the native functor that implements
167      *        system/core/include/utils/Functor.h
168      * @deprecated Use {@link #drawWebViewFunctor(Canvas, int)}
169      */
170     @Deprecated
detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor)171     public void detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor) {
172         ViewRootImpl viewRootImpl = containerView.getViewRootImpl();
173         if (nativeDrawGLFunctor != 0 && viewRootImpl != null) {
174             viewRootImpl.detachFunctor(nativeDrawGLFunctor);
175         }
176     }
177 
178     /**
179      * Returns the package id of the given {@code packageName}.
180      */
getPackageId(Resources resources, String packageName)181     public int getPackageId(Resources resources, String packageName) {
182         SparseArray<String> packageIdentifiers =
183                 resources.getAssets().getAssignedPackageIdentifiers();
184         for (int i = 0; i < packageIdentifiers.size(); i++) {
185             final String name = packageIdentifiers.valueAt(i);
186 
187             if (packageName.equals(name)) {
188                 return packageIdentifiers.keyAt(i);
189             }
190         }
191         throw new RuntimeException("Package not found: " + packageName);
192     }
193 
194     /**
195      * Returns the application which is embedding the WebView.
196      */
getApplication()197     public Application getApplication() {
198         return ActivityThread.currentApplication();
199     }
200 
201     /**
202      * Returns the error string for the given {@code errorCode}.
203      */
getErrorString(Context context, int errorCode)204     public String getErrorString(Context context, int errorCode) {
205         return LegacyErrorStrings.getString(errorCode, context);
206     }
207 
208     /**
209      * Adds the WebView asset path to {@link android.content.res.AssetManager}.
210      */
addWebViewAssetPath(Context context)211     public void addWebViewAssetPath(Context context) {
212         final String[] newAssetPaths =
213                 WebViewFactory.getLoadedPackageInfo().applicationInfo.getAllApkPaths();
214         final ApplicationInfo appInfo = context.getApplicationInfo();
215 
216         // Build the new library asset path list.
217         String[] newLibAssets = appInfo.sharedLibraryFiles;
218         for (String newAssetPath : newAssetPaths) {
219             newLibAssets = ArrayUtils.appendElement(String.class, newLibAssets, newAssetPath);
220         }
221 
222         if (newLibAssets != appInfo.sharedLibraryFiles) {
223             // Update the ApplicationInfo object with the new list.
224             // We know this will persist and future Resources created via ResourcesManager
225             // will include the shared library because this ApplicationInfo comes from the
226             // underlying LoadedApk in ContextImpl, which does not change during the life of the
227             // application.
228             appInfo.sharedLibraryFiles = newLibAssets;
229 
230             // Update existing Resources with the WebView library.
231             ResourcesManager.getInstance().appendLibAssetsForMainAssetPath(
232                     appInfo.getBaseResourcePath(), newAssetPaths);
233         }
234     }
235 
236     /**
237      * Returns whether WebView should run in multiprocess mode.
238      */
isMultiProcessEnabled()239     public boolean isMultiProcessEnabled() {
240         try {
241             return WebViewFactory.getUpdateService().isMultiProcessEnabled();
242         } catch (RemoteException e) {
243             throw e.rethrowFromSystemServer();
244         }
245     }
246 
247     /**
248      * Returns the data directory suffix to use, or null for none.
249      */
getDataDirectorySuffix()250     public String getDataDirectorySuffix() {
251         return WebViewFactory.getDataDirectorySuffix();
252     }
253 }
254