react-native-minimal-webview 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +487 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +197 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +303 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +259 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +96 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +453 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +137 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +33 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +105 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +59 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +15 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +22 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +701 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +201 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +16 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +24 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +32 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +115 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1173 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +158 -0
  80. package/ios/DocumentEnd.swift +22 -0
  81. package/ios/DownloadName.swift +10 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +310 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +38 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +96 -0
  90. package/ios/MinimalWebView+Navigation.swift +243 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +513 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +36 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +252 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +99 -4
  104. package/src/WebView.tsx +626 -0
  105. package/src/bridge/createBridge.ts +178 -0
  106. package/src/bridge/endpoint.ts +123 -0
  107. package/src/bridge/origins.ts +61 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +67 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +24 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +693 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +26 -0
  116. package/src/refStore.ts +165 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1240 -0
@@ -0,0 +1,507 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.app.Activity
5
+ import android.content.Context
6
+ import android.content.pm.ApplicationInfo
7
+ import android.os.Bundle
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.util.Log
11
+ import android.view.MotionEvent
12
+ import android.view.View
13
+ import android.webkit.CookieManager
14
+ import android.webkit.WebChromeClient
15
+ import android.webkit.WebSettings
16
+ import android.webkit.WebView
17
+ import android.webkit.WebViewClient
18
+ import androidx.webkit.Profile
19
+ import androidx.webkit.WebSettingsCompat
20
+ import androidx.webkit.WebViewCompat
21
+ import androidx.webkit.WebViewFeature
22
+ import expo.modules.kotlin.AppContext
23
+ import expo.modules.kotlin.viewevent.EventDispatcher
24
+ import expo.modules.kotlin.views.ExpoView
25
+ import expo.modules.minimalwebview.requests.DownloadInfo
26
+ import expo.modules.minimalwebview.requests.Downloads
27
+ import expo.modules.minimalwebview.requests.FileUpload
28
+ import expo.modules.minimalwebview.requests.FullscreenVideo
29
+ import expo.modules.minimalwebview.requests.Permissions
30
+
31
+ @Suppress("TooManyFunctions") // because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
32
+ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
33
+ private val onNavigationState by EventDispatcher<Map<String, Any?>>()
34
+ private val onBridge by EventDispatcher<Map<String, Any?>>()
35
+ private val onHookEvent by EventDispatcher<Map<String, Any?>>()
36
+ private val onError by EventDispatcher<Map<String, Any?>>()
37
+ private val onProcessGone by EventDispatcher<Map<String, Any?>>()
38
+ private val onNavigation by EventDispatcher<Map<String, Any?>>()
39
+
40
+ internal val hasNavigationListener = WebViewFeature.isFeatureSupported(WebViewFeature.NAVIGATION_LISTENER)
41
+ private val navigation = MinimalWebViewNavigation(this) { onNavigation(it) }
42
+ private val scripts = MinimalWebViewScripts(this) { onBridge(it) }
43
+
44
+ /** Set by the first prop batch and replaced after a renderer crash; see [recovering]. */
45
+ internal lateinit var webView: WebView
46
+ private set
47
+ private val hasWebView get() = ::webView.isInitialized
48
+
49
+ // Props, applied together in applyProps()
50
+ internal var source: WebViewSource? = null
51
+ internal var navigationRules: List<Map<String, Any?>>? = null
52
+ internal var bridgeScript: String? = null
53
+ internal var bridgeOrigins: List<String>? = null
54
+ /** The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions). */
55
+ internal var hookOptions: Map<String, Any?> = emptyMap()
56
+ set(value) {
57
+ val old = field
58
+ field = value
59
+ if (hasWebView) optionsChanged(old)
60
+ }
61
+ internal var injectedScripts: List<InjectedScript>? = null
62
+ /** The `android` prop: WebSettings and WebView setters by name, applied by [PlatformSettings]. */
63
+ internal var settings: Map<String, Any?>? = null
64
+ internal val platformSettings = PlatformSettings { PlatformSettings.targets(webView, it) }
65
+ internal var pullToRefresh = false
66
+ private val refresher = PullToRefresh(this)
67
+ /**
68
+ * The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`, read when a
69
+ * request comes or a decision is reported.
70
+ */
71
+ internal var requestHandlers: Set<String> = emptySet()
72
+ private var loadedSource: WebViewSource? = null
73
+
74
+ // The hooks' lists: each context owns its own, and the core routes those of the hooks that are on, in attach order.
75
+ val clients: List<WebViewClient> get() = routed(hookContexts) { it.clients }
76
+ val chromeClients: List<WebChromeClient> get() = routed(hookContexts) { it.chromeClients }
77
+ val activity: Activity? get() = appContext.currentActivity
78
+ internal val fileUpload = FileUpload(this)
79
+ internal val fullscreen = FullscreenVideo(this)
80
+ internal val permissions = Permissions(this)
81
+ private val downloads = Downloads(this)
82
+ /** Keys of the extensions that are on in `hookOptions` when the first WebView is made, plus those attached later. They pick the hooks again for the WebView built after a crash. */
83
+ private var hookKeys: Set<String> = emptySet()
84
+ /** The hooks' contexts for the current WebView, in attach order. Chromium's IO thread reads it (shouldInterceptRequest). */
85
+ @Volatile private var hookContexts: List<HookContext> = emptyList()
86
+
87
+ internal val asks = Asks { onHookEvent(it) }
88
+ internal val deciders = Deciders { message -> mainHandler.post { warn(message) } }
89
+
90
+ // Navigation state: native owns it and tells JS. The clients (MinimalWebViewClients.kt) write it.
91
+ internal var url = ""
92
+ internal var pendingUrl: String? = null
93
+ internal var title = ""
94
+ internal var loading = false
95
+ internal var progress = 0.0
96
+ /** How the current load ends so far, "finished", "failed" or "cancelled"; JS sees it only once `loading` is false. */
97
+ internal var outcome: String? = null
98
+ private var lastEmitted: Map<String, Any?>? = null
99
+ private var emitScheduled = false
100
+
101
+ /** From a renderer death until [recover] builds the new WebView: whether it loads, and the dead one's history. */
102
+ private var pendingRecovery: Recovery? = null
103
+ private class Recovery(val reload: Boolean, val history: Bundle?)
104
+ private var destroyed = false
105
+
106
+ // The core's deferred work. Not View.post: a detached view (unmounted, or a covered screen) holds that until it is
107
+ // attached again.
108
+ internal val mainHandler = Handler(Looper.getMainLooper())
109
+
110
+ init {
111
+ // The WebView goes into the layout in setUp(); the prop only turns the pull on and off.
112
+ addView(refresher.layout, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
113
+ }
114
+
115
+ private fun createWebView(): WebView {
116
+ // recover() calls this while the dead WebView is still set: the keys and the one-time warnings carry over.
117
+ val first = !hasWebView
118
+ if (first) hookKeys = hookOptions.keys
119
+ val (attaching, unregistered) = selectHooks(MinimalWebViewHooks.hooks, hookKeys)
120
+ val (maker, unused) = pickFactory(attaching)
121
+ val view = maker?.webViewFactory?.invoke(context) ?: WebView(context)
122
+ hookContexts = attaching.map { HookContext(it, this) }
123
+ // A typo, or a hook's module not linked or not rebuilt. Once: the WebView after a crash has the same keys.
124
+ if (first) unregistered.forEach { warn("extension $it: no hook is registered under this key") }
125
+ if (first) unused.forEach { warn("extension $it: its webViewFactory is not used, ${maker?.key}'s is") }
126
+ // Before the package touches the WebView: some calls (WebViewCompat.setProfile) must come first.
127
+ hookContexts.forEach { it.hook.configure?.invoke(view, it) }
128
+ webViewCreated = true
129
+ val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
130
+ WebView.setWebContentsDebuggingEnabled(webContentsDebugging ?: debuggable)
131
+ configure(view.settings)
132
+ view.webViewClient = Client(this, navigation)
133
+ view.webChromeClient = ChromeClient(this, navigation)
134
+ view.setDownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->
135
+ val download = DownloadInfo(url, userAgent, contentDisposition.orEmpty(), mimeType.orEmpty())
136
+ val taken = hookContexts.any {
137
+ it.downloadStarted(url, userAgent, download.contentDisposition, download.mimeType, contentLength)
138
+ }
139
+ if (!taken && !downloads.onDownloadStart(download)) navigation.openDownload(url)
140
+ }
141
+ // View's slots hold one listener each: the hooks share them through their lists.
142
+ view.setOnTouchListener(::touched)
143
+ view.setOnScrollChangeListener(::scrolled)
144
+ if (hasNavigationListener) WebViewCompat.addNavigationListener(view, context.mainExecutor, Listener(this))
145
+ return view
146
+ }
147
+
148
+ // The on hooks' own lists, not copies: this runs for every touch event and scroll change.
149
+ private fun touched(view: View, event: MotionEvent) =
150
+ hookContexts.any { c -> c.routed && c.touchListeners.any { it.onTouch(view, event) } }
151
+
152
+ private fun scrolled(view: View, x: Int, y: Int, oldX: Int, oldY: Int) {
153
+ for (c in hookContexts) {
154
+ if (c.routed) c.scrollListeners.forEach { it.onScrollChange(view, x, y, oldX, oldY) }
155
+ }
156
+ }
157
+
158
+ @SuppressLint("SetJavaScriptEnabled") // because a browser-tab WebView needs JS; no addJavascriptInterface is used
159
+ private fun configure(settings: WebSettings) {
160
+ settings.javaScriptEnabled = true
161
+ // A tap's window.open and target=_blank reach onCreateWindow; the navigation rules decide (newWindow: true).
162
+ // Without a gesture only when the app opts in (javaScriptCanOpenWindowsAutomatically, in applySettings).
163
+ settings.setSupportMultipleWindows(true)
164
+ settings.domStorageEnabled = true
165
+ settings.allowFileAccess = false
166
+ settings.allowContentAccess = false
167
+ settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
168
+ // Pinch-zoom (an accessibility basic; pages opt out with a viewport meta), without the legacy +/- buttons.
169
+ settings.builtInZoomControls = true
170
+ settings.displayZoomControls = false
171
+ // Back and forward restore the page instead of reloading it, as WebKit does. `android.settings` applies after this.
172
+ // Not without NavigationListener: WebView 133 sends onPageStarted for a restored page but no onPageFinished.
173
+ if (hasNavigationListener && WebViewFeature.isFeatureSupported(WebViewFeature.BACK_FORWARD_CACHE)) {
174
+ WebSettingsCompat.setBackForwardCacheEnabled(settings, true)
175
+ }
176
+ // No favicon requests: nothing shows them.
177
+ if (WebViewFeature.isFeatureSupported(WebViewFeature.DOWNLOAD_FAVICONS_ENABLED)) {
178
+ WebSettingsCompat.setDownloadFaviconsEnabled(settings, false)
179
+ }
180
+ }
181
+
182
+ /** Called once per prop batch. `source` loads last so everything else is ready first. */
183
+ internal fun applyProps() {
184
+ // The dead WebView after a crash takes nothing: recover() applies the props to the new one.
185
+ if (recovering) return
186
+ // The first prop batch sets up the first WebView: the hooks get their options with it.
187
+ if (hasWebView) {
188
+ applySettings()
189
+ scripts.update()
190
+ } else {
191
+ webView = createWebView()
192
+ setUp()
193
+ }
194
+ refresher.layout.isEnabled = pullToRefresh
195
+ loadNewSource()
196
+ }
197
+
198
+ /** Loads `source` if it isn't the one loaded yet; returns whether it did. */
199
+ private fun loadNewSource(): Boolean {
200
+ val next = source ?: return false
201
+ if (next == loadedSource) return false
202
+ loadedSource = next
203
+ load(next)
204
+ return true
205
+ }
206
+
207
+ /** Readies a new WebView, the first or the one after a crash, in one order: settings, layout, hooks, scripts. */
208
+ private fun setUp() {
209
+ applySettings(force = true)
210
+ // addView(view) alone would give the view WRAP_CONTENT, and Chromium then resolves CSS vh to 0.
211
+ refresher.content.addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
212
+ // React Native ignores requestLayout: a WebView added after it laid this view out (a crash) needs its own pass.
213
+ if (isLaidOut) measureAndLayout()
214
+ hookContexts.forEach { it.hook.attach(webView, it) }
215
+ scripts.install()
216
+ }
217
+
218
+ private fun load(source: WebViewSource) {
219
+ if (source.uri == null) {
220
+ webView.loadDataWithBaseURL(source.baseUrl, source.html ?: "", "text/html", "utf-8", null)
221
+ } else if (source.body != null) {
222
+ webView.postUrl(source.uri, source.body.toByteArray()) // form-urlencoded; postUrl takes no headers
223
+ } else {
224
+ webView.loadUrl(source.uri, source.headers.orEmpty())
225
+ }
226
+ }
227
+
228
+ /** Loads the page on screen again: the `source` when that is the page (its headers, html or POST), else its URL. */
229
+ private fun loadAgain() {
230
+ if (showsSource(source, url)) source?.let(::load) else if (url.isNotEmpty()) webView.loadUrl(url)
231
+ }
232
+
233
+ /**
234
+ * The ref's reload: the app's retry starts the crash-loop guard over. Only this clears it: the guard counts the
235
+ * process's renderer deaths, so another view's new source or pull-to-refresh mustn't end a crash loop's count.
236
+ */
237
+ internal fun retry() {
238
+ crashTimes.clear()
239
+ reload()
240
+ }
241
+
242
+ internal fun reload() {
243
+ when {
244
+ // The renderer died and the new WebView isn't built yet: build it now, and load.
245
+ recovering -> recover(reload = true)
246
+ // Nothing loaded: the crash-loop guard gave up (processGone), and this is the app's retry.
247
+ webView.url == null -> loadAgain()
248
+ // WebView's reload declines a POST's form resubmission: send the source again.
249
+ source?.body != null && showsSource(source, url) -> source?.let(::load)
250
+ else -> webView.reload()
251
+ }
252
+ }
253
+
254
+ /**
255
+ * The `android` settings, applied from each prop batch (only the keys that changed) and all again to a new WebView
256
+ * after a crash. A key that can't be applied is reported to JS, which warns.
257
+ */
258
+ private fun applySettings(force: Boolean = false) {
259
+ platformSettings.apply(settings, force).forEach { warn("android.${it["key"]}: ${it["reason"]}") }
260
+ }
261
+
262
+ /** A warning for the app's developer, which JS logs with console.warn. */
263
+ internal fun warn(message: String) = emit("core", "warning", mapOf("message" to message))
264
+
265
+ /** Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewFactory` whose key turns on. */
266
+ private fun optionsChanged(old: Map<String, Any?>) {
267
+ for (key in inRegistrationOrder(old.keys + hookOptions.keys, MinimalWebViewHooks.hooks.map { it.key })) {
268
+ val value = hookOptions[key]
269
+ if (old[key] == value) continue
270
+ val context = hookContexts.find { it.key == key }
271
+ if (context != null) {
272
+ context.optionsChanged(value)
273
+ } else if (key !in hookKeys && old[key] == null) {
274
+ attachLate(key)
275
+ }
276
+ }
277
+ }
278
+
279
+ private fun attachLate(key: String) {
280
+ val hook = MinimalWebViewHooks.hooks.find { it.key == key }
281
+ ?: return warn("extension $key: no hook is registered under this key")
282
+ // configure runs before the package sets the WebView up, and a factory makes it: too late for one that exists.
283
+ if (hook.configure != null || hook.webViewFactory != null) {
284
+ val why = if (hook.configure != null) "configure" else "a webViewFactory"
285
+ return warn("extension $key: its hook has $why, so it attaches only when the WebView is created")
286
+ }
287
+ hookKeys = hookKeys + key
288
+ // The WebView the recovery builds attaches it with the others.
289
+ if (recovering) return
290
+ val context = HookContext(hook, this)
291
+ hookContexts = hookContexts + context
292
+ hook.attach(webView, context)
293
+ }
294
+
295
+ /** The handler a hook registered with `context.handle` for [method], if it is attached and on. */
296
+ internal fun hookHandler(key: String, method: String) = hookContexts.find { it.key == key && it.routed }?.handlers?.get(method)
297
+
298
+ fun emit(key: String, name: String, payload: Map<String, Any?>) =
299
+ onHookEvent(mapOf("key" to key, "name" to name, "payload" to payload))
300
+
301
+ private var documentOpen = false
302
+
303
+ internal fun endDocument(reason: DocumentEnd) {
304
+ // The first commit after mount or a crash opens a Document and ends none: the asks and hooks don't hear it.
305
+ val opening = reason == DocumentEnd.COMMITTED && !documentOpen
306
+ documentOpen = reason == DocumentEnd.COMMITTED
307
+ fileUpload.cancel()
308
+ navigation.documentEnded()
309
+ scripts.documentEnded(reason)
310
+ fullscreen.documentEnded(reason)
311
+ if (opening) return
312
+ // The asks and hooks last, so a throw in hook or Chromium code can't skip the core's resets.
313
+ asks.documentEnded(reason)
314
+ hookContexts.forEach { it.documentEnded(reason) }
315
+ }
316
+
317
+ internal fun loadStarted() {
318
+ loading = true
319
+ outcome = null
320
+ stateChanged()
321
+ }
322
+
323
+ /** A load ended (callers set outcome first): loading stops, and the spinner with it. */
324
+ internal fun loadEnded() {
325
+ loading = false
326
+ refresher.pageFinished()
327
+ stateChanged()
328
+ }
329
+
330
+ internal fun bridgePost(message: String) = scripts.post(message)
331
+
332
+ internal fun evaluate(script: String, onResult: (Result<String>) -> Unit) =
333
+ if (recovering) onResult(Result.failure(EvaluateError("unavailable", RECOVERING))) else scripts.evaluate(script, onResult)
334
+
335
+ /**
336
+ * The renderer died. The WebView can't be reused: it goes now, after saving its history. The new one is built
337
+ * at once if the view can be seen, else once it can (Android's guidance: not in the background).
338
+ */
339
+ internal fun processGone(cause: String, at: Long) {
340
+ if (destroyed) return
341
+ val reload = crashAllowsReload(crashTimes, at) && !(source?.body != null && showsSource(source, url))
342
+ // The source page reloads as the source: a restored entry carries neither source.headers nor an html source.
343
+ val restorable = !showsSource(source, url)
344
+ val history = Bundle().takeIf { reload && restorable && webView.saveState(it) != null }
345
+ tearDown(DocumentEnd.CRASHED)
346
+ pendingRecovery = Recovery(reload, history)
347
+ // Nothing will end the load the crash cut off. `url` stays: loadAgain() loads it.
348
+ if (loading) outcome = "failed"
349
+ loading = false
350
+ pendingUrl = null
351
+ progress = 0.0
352
+ refresher.pageFinished()
353
+ onProcessGone(mapOf("cause" to cause, "recovered" to reload))
354
+ // A detached view's window reports GONE: onWindowVisibilityChanged recovers once it is shown.
355
+ if (windowVisibility == View.VISIBLE) recover()
356
+ stateChanged() // after onProcessGone: the cut-off load ends as failed
357
+ }
358
+
359
+ /** The renderer died and the new WebView isn't built yet: the one in [webView] is destroyed. */
360
+ internal val recovering get() = pendingRecovery != null
361
+
362
+ // Also on attach: dispatchAttachedToWindow calls this unless the window is GONE.
363
+ override fun onWindowVisibilityChanged(visibility: Int) {
364
+ super.onWindowVisibilityChanged(visibility)
365
+ if (visibility == View.VISIBLE) recover()
366
+ }
367
+
368
+ /**
369
+ * Builds the WebView that replaces the dead one and brings its history back, or else loads its page again. With
370
+ * [reload] (the app's retry) it loads also when the crash-loop guard or a POST source held the reload back.
371
+ */
372
+ private fun recover(reload: Boolean = false) {
373
+ val recovery = pendingRecovery ?: return
374
+ pendingRecovery = null
375
+ webView = createWebView()
376
+ setUp()
377
+ refresher.layout.isEnabled = pullToRefresh
378
+ // A source the app set while this waited loads instead of the old page.
379
+ if (!loadNewSource()) {
380
+ val restored = recovery.history?.let { webView.restoreState(it) } != null
381
+ if (!restored && (recovery.reload || reload)) loadAgain()
382
+ }
383
+ stateChanged()
384
+ }
385
+
386
+ internal fun destroy() {
387
+ destroyed = true
388
+ downloads.detach()
389
+ // A crash tore the WebView down already, and detached the hooks; with none, there is nothing to tear down.
390
+ if (!hasWebView || recovering) {
391
+ pendingRecovery = null
392
+ return endDocument(DocumentEnd.CLOSING)
393
+ }
394
+ webView.stopLoading()
395
+ tearDown(DocumentEnd.CLOSING)
396
+ }
397
+
398
+ /** Ends the Document with [reason] and destroys the WebView. The detached hooks' onDestroyed handlers run after it is destroyed. */
399
+ private fun tearDown(reason: DocumentEnd) {
400
+ endDocument(reason)
401
+ val detached = hookContexts
402
+ detached.forEach { it.detach() }
403
+ hookContexts = emptyList()
404
+ refresher.content.removeView(webView)
405
+ webView.destroy()
406
+ detached.forEach { it.destroyed(reason) }
407
+ }
408
+
409
+ internal fun reportError(kind: String, url: String, code: Int, description: String) {
410
+ // A network or SSL error fails the load in progress; one with no load JS saw start (an SSL error before 146) doesn't.
411
+ if (loading) outcome = "failed"
412
+ onError(mapOf("kind" to kind, "url" to url, "code" to code, "description" to description))
413
+ }
414
+
415
+ internal fun reportHttpError(url: String, statusCode: Int) =
416
+ onError(mapOf("kind" to "http", "url" to url, "statusCode" to statusCode))
417
+
418
+ // Changes within one frame are combined into one event, except `loading` flips: a load that starts and fails
419
+ // within one frame must still reach JS as loading true -> false (onLoadStart / onLoadEnd).
420
+ internal fun stateChanged() {
421
+ if (loading != lastEmitted?.get("loading")) return emitState()
422
+ if (emitScheduled) return
423
+ emitScheduled = true
424
+ mainHandler.postDelayed({
425
+ emitScheduled = false
426
+ emitState()
427
+ }, FRAME_MS)
428
+ }
429
+
430
+ private fun emitState() {
431
+ if (destroyed) return
432
+ // While a recovery waits, `webView` is the destroyed one: the history stays as JS saw it last.
433
+ val (back, forward) = if (recovering) {
434
+ (lastEmitted?.get("canGoBack") ?: false) to (lastEmitted?.get("canGoForward") ?: false)
435
+ } else {
436
+ webView.canGoBack() to webView.canGoForward()
437
+ }
438
+ val state = mapOf(
439
+ "url" to url,
440
+ "pendingUrl" to pendingUrl,
441
+ "title" to title,
442
+ "loading" to loading,
443
+ "progress" to progress,
444
+ "canGoBack" to back,
445
+ "canGoForward" to forward,
446
+ "outcome" to if (loading) null else outcome
447
+ )
448
+ if (state == lastEmitted) return
449
+ lastEmitted = state
450
+ onNavigationState(state)
451
+ }
452
+
453
+ internal companion object {
454
+ // The app's WebViews share one renderer, so the crash-loop guard counts its deaths for the whole process.
455
+ private val crashTimes = ArrayDeque<Long>()
456
+ }
457
+ }
458
+
459
+ internal const val TAG = "MinimalWebView"
460
+ internal const val RECOVERING = "the WebView is being rebuilt after its renderer died"
461
+
462
+ /** Whether this process has made a WebView; until then WebView isn't started. */
463
+ @Volatile internal var webViewCreated = false
464
+
465
+ /** What `setWebContentsDebuggingEnabled` set; null until it is called. */
466
+ @Volatile internal var webContentsDebugging: Boolean? = null
467
+
468
+ internal fun failed(message: String, error: Exception): Boolean {
469
+ Log.w(TAG, message, error)
470
+ return false
471
+ }
472
+
473
+ /**
474
+ * [webView]'s profile (`android.webView.profile`), or null when WebView has only the default one: then the process-wide
475
+ * [CookieManager] and [WebStorage][android.webkit.WebStorage] are its. Only once the WebView is set up, so that it is
476
+ * the profile the WebView ends on.
477
+ */
478
+ internal fun profileOf(webView: WebView): Profile? =
479
+ if (WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) WebViewCompat.getProfile(webView) else null
480
+
481
+ /**
482
+ * Whether the committed [url] is the [source]'s page (or nothing has committed yet). An html source's page is its
483
+ * baseUrl or about:blank. Chromium canonicalizes (`https://example.com` commits as `https://example.com/`).
484
+ */
485
+ internal fun showsSource(source: WebViewSource?, url: String): Boolean {
486
+ if (source == null) return false
487
+ if (url.isEmpty()) return true
488
+ val page = source.uri ?: source.baseUrl ?: "about:blank"
489
+ return page.trimEnd('/') == url.trimEnd('/')
490
+ }
491
+
492
+ /**
493
+ * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
494
+ * [MAX_CRASHES_PER_WINDOW] in [CRASH_WINDOW_MS]. Every WebView on the renderer hears of its death, so one within
495
+ * [SAME_CRASH_MS] of the last is that same death.
496
+ */
497
+ internal fun crashAllowsReload(times: ArrayDeque<Long>, now: Long): Boolean {
498
+ if (times.isEmpty() || now - times.last() > SAME_CRASH_MS) times.addLast(now)
499
+ while (times.first() < now - CRASH_WINDOW_MS) times.removeFirst()
500
+ return times.size <= MAX_CRASHES_PER_WINDOW
501
+ }
502
+
503
+ // shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
504
+ private const val MAX_CRASHES_PER_WINDOW = 3
505
+ private const val CRASH_WINDOW_MS = 60_000L
506
+ private const val SAME_CRASH_MS = 100L
507
+ private const val FRAME_MS = 16L