This repository has been archived by the owner on Jan 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 711
/
SystemWebView.kt
325 lines (265 loc) · 11.7 KB
/
SystemWebView.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.webview
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import androidx.annotation.VisibleForTesting
import android.util.AttributeSet
import android.util.Log
import android.util.SparseArray
import android.view.View
import android.view.autofill.AutofillValue
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.webkit.CookieManager
import android.webkit.DownloadListener
import android.webkit.WebChromeClient
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewDatabase
import androidx.preference.PreferenceManager
import mozilla.components.browser.session.Session
import mozilla.components.support.utils.ThreadUtils
import org.mozilla.focus.BuildConfig
import org.mozilla.focus.ext.savedWebViewState
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.AppConstants
import org.mozilla.focus.utils.FileUtils
import org.mozilla.focus.utils.UrlUtils
import org.mozilla.focus.utils.ViewUtils
import org.mozilla.focus.web.Download
import org.mozilla.focus.web.IFindListener
import org.mozilla.focus.web.IWebView
import org.mozilla.focus.web.WebViewProvider
import java.util.HashMap
@Suppress("TooManyFunctions")
class SystemWebView(context: Context, attrs: AttributeSet) : NestedWebView(context, attrs), IWebView,
SharedPreferences.OnSharedPreferenceChangeListener {
private var callback: IWebView.Callback? = null
private val client: FocusWebViewClient = FocusWebViewClient(getContext().applicationContext)
private val linkHandler: LinkHandler
init {
webViewClient = client
webChromeClient = createWebChromeClient()
setDownloadListener(createDownloadListener())
if (BuildConfig.DEBUG) {
WebView.setWebContentsDebuggingEnabled(true)
}
isLongClickable = true
linkHandler = LinkHandler(this)
setOnLongClickListener(linkHandler)
}
@VisibleForTesting
fun getCallback(): IWebView.Callback? {
return callback
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TelemetryAutofillCallback.register(context)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TelemetryAutofillCallback.unregister(context)
}
}
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
val connection: InputConnection? = super.onCreateInputConnection(outAttrs)
outAttrs.imeOptions = outAttrs.imeOptions or ViewUtils.IME_FLAG_NO_PERSONALIZED_LEARNING
return connection
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
WebViewProvider.applyAppSettings(context, settings, this)
reload()
}
override fun onPause() {
super.onPause()
pauseTimers()
}
override fun onResume() {
super.onResume()
resumeTimers()
}
override fun restoreWebViewState(session: Session) {
val stateData = session.savedWebViewState
val backForwardList = if (stateData != null)
super.restoreState(stateData)
else
null
val desiredURL = session.url
client.restoreState(stateData)
client.notifyCurrentURL(desiredURL)
// Pages are only added to the back/forward list when loading finishes. If a new page is
// loading when the Activity is paused/killed, then that page won't be in the list,
// and needs to be restored separately to the history list. We detect this by checking
// whether the last fully loaded page (getCurrentItem()) matches the last page that the
// WebView was actively loading (which was retrieved during onSaveInstanceState():
// WebView.getUrl() always returns the currently loading or loaded page).
// If the app is paused/killed before the initial page finished loading, then the entire
// list will be null - so we need to additionally check whether the list even exists.
if (backForwardList != null && backForwardList.currentItem!!.url == desiredURL) {
// restoreState doesn't actually load the current page, it just restores navigation history,
// so we also need to explicitly reload in this case:
reload()
} else {
loadUrl(desiredURL)
}
}
override fun saveWebViewState(session: Session) {
// We store the actual state into another bundle that we will keep in memory as long as this
// browsing session is active. The data that WebView stores in this bundle is too large for
// Android to save and restore as part of the state bundle.
val stateData = Bundle()
super.saveState(stateData)
client.saveState(this, stateData)
session.savedWebViewState = stateData
}
override fun setBlockingEnabled(enabled: Boolean) {
client.isBlockingEnabled = enabled
if (enabled) {
WebViewProvider.applyAppSettings(context, settings, this)
} else {
WebViewProvider.disableBlocking(settings, this)
}
if (callback != null) {
callback!!.onBlockingStateChanged(enabled)
}
}
override fun setRequestDesktop(shouldRequestDesktop: Boolean) {
if (shouldRequestDesktop) {
WebViewProvider.requestDesktopSite(settings)
} else {
WebViewProvider.requestMobileSite(context, settings)
}
if (callback != null) {
callback!!.onRequestDesktopStateChanged(shouldRequestDesktop)
}
}
override fun setCallback(callback: IWebView.Callback?) {
this.callback = callback
client.setCallback(callback)
linkHandler.setCallback(callback)
}
override fun setFindListener(findListener: IFindListener) {
this.setFindListener(findListener as WebView.FindListener)
}
override fun loadUrl(url: String?) {
// We need to check external URL handling here - shouldOverrideUrlLoading() is only
// called by webview when clicking on a link, and not when opening a new page for the
// first time using loadUrl().
@Suppress("DEPRECATION")
if (!client.shouldOverrideUrlLoading(this, url)) {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["X-Requested-With"] = ""
super.loadUrl(url, additionalHeaders)
}
client.notifyCurrentURL(url)
}
override fun exitFullscreen() {}
override fun loadData(baseURL: String, data: String, mimeType: String, encoding: String, historyURL: String) {
loadDataWithBaseURL(baseURL, data, mimeType, encoding, historyURL)
}
override fun destroy() {
super.destroy()
// WebView might save data to disk once it gets destroyed. In this case our cleanup call
// might not have been able to see this data. Let's do it again.
deleteContentFromKnownLocations(context)
}
override fun cleanup() {
clearFormData()
clearHistory()
clearMatches()
clearSslPreferences()
clearCache(true)
// We don't care about the callback - we just want to make sure cookies are gone
CookieManager.getInstance().removeAllCookies(null)
WebStorage.getInstance().deleteAllData()
val webViewDatabase = WebViewDatabase.getInstance(context)
// It isn't entirely clear how this differs from WebView.clearFormData()
@Suppress("DEPRECATION")
webViewDatabase.clearFormData()
webViewDatabase.clearHttpAuthUsernamePassword()
deleteContentFromKnownLocations(context)
}
override fun autofill(values: SparseArray<AutofillValue>) {
super.autofill(values)
TelemetryWrapper.autofillPerformedEvent()
}
private fun createWebChromeClient(): WebChromeClient {
return object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
if (callback != null) {
// This is the earliest point where we might be able to confirm a redirected
// URL: we don't necessarily get a shouldInterceptRequest() after a redirect,
// so we can only check the updated url in onProgressChanges(), or in onPageFinished()
// (which is even later).
val viewURL = view.url
if (!UrlUtils.isInternalErrorURL(viewURL) && viewURL != null) {
callback!!.onURLChanged(viewURL)
callback!!.onTitleChanged(title)
}
callback!!.onProgress(newProgress)
}
}
override fun onShowCustomView(view: View, webviewCallback: WebChromeClient.CustomViewCallback) {
val fullscreenCallback = IWebView.FullscreenCallback { webviewCallback.onCustomViewHidden() }
callback?.onEnterFullScreen(fullscreenCallback, view)
}
override fun onHideCustomView() {
callback?.onExitFullScreen()
}
}
}
override fun releaseGeckoSession() {
// Do nothing, only for GV
}
private fun createDownloadListener(): DownloadListener {
return DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
if (!AppConstants.supportsDownloadingFiles()) {
return@DownloadListener
}
val scheme = Uri.parse(url).scheme
if (scheme == null || scheme != "http" && scheme != "https") {
// We are ignoring everything that is not http or https. This is a limitation of
// Android's download manager. There's no reason to show a download dialog for
// something we can't download anyways.
Log.w(TAG, "Ignoring download from non http(s) URL: $url")
return@DownloadListener
}
if (callback != null) {
val download = Download(
url,
userAgent,
contentDisposition,
mimetype,
contentLength,
Environment.DIRECTORY_DOWNLOADS,
null
)
callback!!.onDownloadStart(download)
}
}
}
companion object {
private const val TAG = "WebkitView"
fun deleteContentFromKnownLocations(context: Context) {
ThreadUtils.postToBackgroundThread(Runnable {
// We call all methods on WebView to delete data. But some traces still remain
// on disk. This will wipe the whole webview directory.
FileUtils.deleteWebViewDirectory(context)
// WebView stores some files in the cache directory. We do not use it ourselves
// so let's truncate it.
FileUtils.truncateCacheDirectory(context)
})
}
}
}