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

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 +130 -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 +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -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 +191 -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 +306 -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 +258 -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 +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -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 +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -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 +60 -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 +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -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 +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -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 +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -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 +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -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 +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -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 +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -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 +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,496 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.content.Context
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.util.Log
7
+ import android.view.View
8
+ import android.webkit.ConsoleMessage
9
+ import android.webkit.SafeBrowsingResponse
10
+ import android.webkit.WebChromeClient
11
+ import android.webkit.WebResourceError
12
+ import android.webkit.WebResourceRequest
13
+ import android.webkit.WebView
14
+ import android.webkit.WebViewClient
15
+ import androidx.webkit.SafeBrowsingResponseCompat
16
+ import androidx.webkit.WebResourceErrorCompat
17
+ import androidx.webkit.WebViewClientCompat
18
+ import java.util.concurrent.ConcurrentHashMap
19
+ import java.util.concurrent.CopyOnWriteArrayList
20
+ import java.util.concurrent.atomic.AtomicBoolean
21
+
22
+ /**
23
+ * Native hooks: Kotlin in an app's or a package's own Expo module that gets the real [WebView] behind this package's
24
+ * WebViews and chains its own clients to it, with no protocol to implement.
25
+ *
26
+ * The [native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
27
+ * walks through one.
28
+ *
29
+ * Leave alone what the core owns: the WebView's own client slots (add to [WebViewContext.clients] and
30
+ * [WebViewContext.chromeClients] instead), its touch and scroll-change listeners ([WebViewContext.touchListeners] and
31
+ * [WebViewContext.scrollListeners]), the bridge's web message listener and document-start scripts, and the download
32
+ * listener ([WebViewContext.onDownloadStart]).
33
+ */
34
+ object MinimalWebViewHooks {
35
+ internal class Hook(
36
+ val key: String,
37
+ val webViewFactory: ((Context) -> WebView)?,
38
+ val configure: ((WebView, WebViewContext) -> Unit)?,
39
+ val attach: (WebView, WebViewContext) -> Unit
40
+ )
41
+
42
+ internal val hooks = mutableListOf<Hook>()
43
+
44
+ /**
45
+ * Registers the hook for [key]. Call it from your module's `OnCreate`, before the first WebView.
46
+ *
47
+ * The same `register` call running again replaces its hook: a JS reload creates the modules anew and runs their
48
+ * `OnCreate` again. A helper that calls `register` for other code is one call, so a second hook through it replaces
49
+ * the first silently.
50
+ *
51
+ * The hook attaches to each WebView whose `extensions` prop has an extension with [key] that is on;
52
+ * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
53
+ * says when. After a renderer crash it attaches again, to the WebView that replaces the dead one.
54
+ *
55
+ * Hooks attach in registration order, which across packages is autolinking's (packages sorted by name), so an
56
+ * earlier hook's clients come first. A hook whose key turns on after the WebView was created attaches after the
57
+ * hooks attached already; after a crash it takes its place in registration order again.
58
+ *
59
+ * @param key the key of the app's extension that turns on the hook. Keys are global, so prefix yours with your
60
+ * package's name. `core` is reserved for the package's own events: a hook under it is logged and not registered.
61
+ * @param webViewFactory makes each WebView this hook is attached to, on or off: the first one and each after a
62
+ * renderer crash, as a subclass that overrides what WebView lets a subclass override. Null leaves it to the other
63
+ * hooks. When the attached hooks name different factories (the same object is one), the first one's in
64
+ * registration order makes the WebView, and a warning names the others. Those still attach, so check the
65
+ * class `attach` gets.
66
+ * @param configure runs on the main thread as soon as each WebView this hook is attached to, on or off, is made,
67
+ * before the package sets it up ([WebViewCompat.setProfile][androidx.webkit.WebViewCompat.setProfile] goes here).
68
+ * It gets the same context that [attach] gets next for that WebView, so state it makes can be keyed by the context.
69
+ * @param attach runs on the main thread once the WebView has its settings and is in the view hierarchy, so what it
70
+ * sets wins over those settings. Register what to run when that WebView goes away with
71
+ * [WebViewContext.onDestroyed]. Document-start scripts you add here run before the package's, so
72
+ * `window.nativeBridge` and `injectedScripts` aren't there yet (on iOS yours run after them).
73
+ * @throws IllegalStateException when a different hook is registered under [key] already. Don't rely on it: a minified
74
+ * build can't tell the two apart and may replace the first hook instead, so give each hook its own key.
75
+ */
76
+ fun register(
77
+ key: String,
78
+ webViewFactory: ((Context) -> WebView)? = null,
79
+ configure: ((WebView, WebViewContext) -> Unit)? = null,
80
+ attach: (WebView, WebViewContext) -> Unit
81
+ ) {
82
+ if (key == "core") {
83
+ Log.e(TAG, "the hook key `core` is reserved: the hook is not registered")
84
+ return
85
+ }
86
+ val hook = Hook(key, webViewFactory, configure, attach)
87
+ val index = hooks.indexOfFirst { it.key == key }
88
+ if (index < 0) {
89
+ hooks += hook
90
+ return
91
+ }
92
+ // Each lambda in the source compiles to a class of its own: the same class is the same call running again.
93
+ // shortcut: R8 can merge two lambdas' classes in a minified build; upgrade if a duplicate must throw there too.
94
+ val first = hooks[index].attach.javaClass
95
+ check(first == attach.javaClass) {
96
+ "two hooks are registered under `$key` (${first.name} and ${attach.javaClass.name}): " +
97
+ "prefix yours with your package's name"
98
+ }
99
+ hooks[index] = hook
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Which [hooks] attach to a WebView created with the enabled `hookOptions` [keys]: the ones registered under them, in
105
+ * registration order. Second, the keys no hook is registered under.
106
+ */
107
+ internal fun selectHooks(
108
+ hooks: List<MinimalWebViewHooks.Hook>,
109
+ keys: Set<String>
110
+ ): Pair<List<MinimalWebViewHooks.Hook>, Set<String>> {
111
+ val attaching = hooks.filter { it.key in keys }
112
+ return attaching to keys - attaching.map { it.key }.toSet()
113
+ }
114
+
115
+ /** [keys] in the order of the [registered] hook keys, then the keys no hook is registered under, sorted. */
116
+ internal fun inRegistrationOrder(keys: Set<String>, registered: List<String>) =
117
+ registered.filter { it in keys } + (keys - registered.toSet()).sorted()
118
+
119
+ /**
120
+ * Which of [attaching] makes the WebView: the first with a factory, or null for a plain WebView. Second, the keys of the
121
+ * others whose factory is a different object.
122
+ */
123
+ internal fun pickFactory(attaching: List<MinimalWebViewHooks.Hook>): Pair<MinimalWebViewHooks.Hook?, List<String>> {
124
+ val named = attaching.filter { it.webViewFactory != null }
125
+ val maker = named.firstOrNull()
126
+ return maker to named.filter { it.webViewFactory !== maker?.webViewFactory }.map { it.key }
127
+ }
128
+
129
+ /**
130
+ * Picks the hook client that gets a decision callback: the first of the clients that override it. It calls [warn] with
131
+ * a warning naming the callback, once per callback and reason: when more than one client overrides it,
132
+ * and, when the caller passes `lost` (what stops applying once a client takes the decision: the app's props or their
133
+ * defaults that would decide it otherwise), when one client takes it.
134
+ */
135
+ internal class Deciders(private val warn: (String) -> Unit) {
136
+ // Concurrent: shouldInterceptRequest decides on Chromium's IO thread.
137
+ private val warned = ConcurrentHashMap.newKeySet<String>()
138
+
139
+ fun <T> first(callback: String, clients: List<T>, lost: String? = null, overrides: (T) -> Boolean): T? {
140
+ val overriding = clients.filter(overrides)
141
+ if (overriding.size > 1 && warned.add(callback)) {
142
+ warn("$callback: more than one hook client overrides it; only the first one gets it")
143
+ }
144
+ if (lost != null && overriding.isNotEmpty() && warned.add("$callback taken")) {
145
+ warn("$callback: a hook client takes it, so $lost")
146
+ }
147
+ return overriding.firstOrNull()
148
+ }
149
+ }
150
+
151
+ /**
152
+ * One WebView as one hook sees it, for one attach.
153
+ *
154
+ * Each attach gets a new context, and the handlers registered on it belong to that attach: after a renderer crash, the
155
+ * new WebView's `attach` registers them again.
156
+ *
157
+ * Call [emit] and [ask] from any thread, and the rest on the main thread, where the handlers and the answers run.
158
+ *
159
+ * Values from JS, the [options], an [ask]'s answer and a [handle] handler's arguments, come in JSON types: a number as
160
+ * a `Double`, an object as a `Map<String, Any?>`, an array as a `List<Any?>`, and a string, a boolean and null as
161
+ * themselves.
162
+ *
163
+ * The hook is on while its extension's `options` are not null or false;
164
+ * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
165
+ * says what off means. [onOptions] runs when the hook turns off, so it can release what it holds, and again when it
166
+ * turns on.
167
+ *
168
+ * A context kept after its attach ended (the view closed, or a renderer crash replaced the WebView) does nothing and
169
+ * holds nothing of the WebView: its lists are emptied and reach no WebView, its handlers are dropped once the
170
+ * [onDestroyed] ones ran, its [url] is empty and its [emit] reaches nothing.
171
+ */
172
+ interface WebViewContext {
173
+ /**
174
+ * This hook's extension's `options`, the new ones after a change; null while the hook is off.
175
+ *
176
+ * After a change they are the new value already when the [onOptions] handlers run.
177
+ */
178
+ val options: Any?
179
+
180
+ /**
181
+ * The committed URL, the one `useWebViewState` reports; empty before the first commit and after the attach ended.
182
+ *
183
+ * Inside [onDocumentEnd] it is still the page that ended. With WebView 146 and later, `onPageStarted` comes after the
184
+ * commit that ends the Document, so `url` is already the new page there.
185
+ */
186
+ val url: String
187
+
188
+ /**
189
+ * The hook clients, in order; add yours in `attach`. While the hook is off, none of them gets a callback.
190
+ *
191
+ * Each callback reaches the clients by one of these rules:
192
+ * - A callback that returns a decision goes to the first client that overrides it, instead of the core and the
193
+ * app's props.
194
+ * - Every other callback reaches the core first, then each client that overrides it.
195
+ *
196
+ * Taking a decision the core makes from the app's props or their defaults switches them off, the default navigation
197
+ * rules' security checks included, and a warning names the callback and what stops applying.
198
+ *
199
+ * A client that overrides `shouldOverrideUrlLoading` decides navigations instead of the navigation rules, which still
200
+ * decide new windows unless a chrome client overrides `onCreateWindow`. A new window the rules allow loads in place
201
+ * with `loadUrl`, which doesn't reach `shouldOverrideUrlLoading` (on iOS that load reaches the deciding delegate).
202
+ *
203
+ * A decision more than one client overrides still goes only to the first, and a warning names it. Each warning
204
+ * comes once per WebView, when its decision first comes.
205
+ *
206
+ * Overriding a variant the base class forwards to counts as overriding the callback: [WebViewClientCompat]'s
207
+ * `onReceivedError`, `onSafeBrowsingHit` and `shouldOverrideUrlLoading(WebView, String)`, and the platform's
208
+ * deprecated `shouldOverrideUrlLoading(WebView, String)`, `shouldInterceptRequest(WebView, String)` and 4-argument
209
+ * `onReceivedError`.
210
+ *
211
+ * `shouldInterceptRequest` runs on a background thread.
212
+ */
213
+ val clients: MutableList<WebViewClient>
214
+
215
+ /**
216
+ * The hook chrome clients, routed as [clients] are.
217
+ *
218
+ * Overriding the deprecated `onConsoleMessage(String, Int, String)` counts as overriding `onConsoleMessage`.
219
+ * Favicon downloads are off, so `onReceivedIcon` gets no icon until the hook's `attach` turns `downloadFaviconsEnabled`
220
+ * on.
221
+ */
222
+ val chromeClients: MutableList<WebChromeClient>
223
+
224
+ /**
225
+ * The hooks' touch listeners, in order, called until one returns true: that one consumes the touch, which neither the
226
+ * later listeners nor the WebView get.
227
+ */
228
+ val touchListeners: MutableList<View.OnTouchListener>
229
+
230
+ /** The hooks' scroll listeners: each one gets every scroll change, in order. */
231
+ val scrollListeners: MutableList<View.OnScrollChangeListener>
232
+
233
+ /**
234
+ * Sends an event to JS: the extension with the hook's key gets `{ name, payload }` in its `onEvent`. It is dropped
235
+ * while the hook is off, and after the context's attach ended.
236
+ */
237
+ fun emit(name: String, payload: Map<String, Any?>)
238
+
239
+ /**
240
+ * Sends the event as [emit] does, and calls [onAnswer] with JS's answer: the extension's `onEvent` return value, a
241
+ * promise awaited, in JSON types as [handle]'s arguments are.
242
+ *
243
+ * It answers null when the handler throws or there is none, or when the Document ends first; there is no timeout. It
244
+ * answers null at once while the hook is off, and after the context's attach ended. An ask made before the WebView's
245
+ * first commit (in `attach`) belongs to the Document that commit opens.
246
+ */
247
+ fun ask(name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit)
248
+
249
+ /**
250
+ * Runs [handler] at once with this hook's extension's `options`, then with the new ones each time they change, live
251
+ * on the same WebView; null while the hook is off.
252
+ *
253
+ * The hook turns off when the extension is removed, or its `options` become null or false. A change from one off
254
+ * value to another doesn't run it, and a context kept after its attach ended never does.
255
+ */
256
+ fun onOptions(handler: (options: Any?) -> Unit)
257
+
258
+ /**
259
+ * Runs [handler] at each end of the Document (see [DocumentEnd]), after the core's own resets: per-page state
260
+ * belongs here.
261
+ */
262
+ fun onDocumentEnd(handler: (DocumentEnd) -> Unit)
263
+
264
+ /**
265
+ * Runs [handler] once this attach's WebView is destroyed: with [DocumentEnd.CLOSING] at unmount, or with
266
+ * [DocumentEnd.CRASHED] after a renderer crash. It comes after the [onDocumentEnd] handlers that get the same
267
+ * reason, and the context does nothing by then.
268
+ *
269
+ * Clean up here, and release what must outlive the WebView, such as a [ProfileStore][androidx.webkit.ProfileStore]
270
+ * profile.
271
+ */
272
+ fun onDestroyed(handler: (DocumentEnd) -> Unit)
273
+
274
+ /**
275
+ * Offers [handler] each download the page starts, with [DownloadListener][android.webkit.DownloadListener]'s
276
+ * arguments (an unknown disposition or MIME type is empty), before the `onDownload` prop and the core's opening it
277
+ * externally.
278
+ *
279
+ * Return true to take it: neither of those gets it then. The hooks that are on are offered it in registration order,
280
+ * and the first that takes it ends the round.
281
+ */
282
+ fun onDownloadStart(
283
+ handler: (url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) -> Boolean
284
+ )
285
+
286
+ /**
287
+ * Answers JS's `ref.hook("<key>", method, args)`: [handler] gets the arguments and a [HookReply], which it calls with
288
+ * the reply or [fails][HookReply.fail], then or later.
289
+ *
290
+ * One handler per method: the last one wins.
291
+ *
292
+ * A handler that throws before it replies rejects the JS call with `handler_error` and the exception's message. A
293
+ * handler that never replies leaves the call waiting until the WebView unmounts: a navigation or a crash doesn't
294
+ * settle it.
295
+ */
296
+ fun handle(method: String, handler: (args: List<Any?>, reply: HookReply) -> Unit)
297
+ }
298
+
299
+ /**
300
+ * The answer to one JS `ref.hook` call, which a [WebViewContext.handle] handler gets: call it with the value the call
301
+ * resolves with, or [fail] it.
302
+ *
303
+ * Only the first reply or fail counts: any after it does nothing. Call it from any thread.
304
+ */
305
+ class HookReply internal constructor(
306
+ private val resolve: (Any?) -> Unit,
307
+ private val reject: (String) -> Unit
308
+ ) : (Any?) -> Unit {
309
+ private val settled = AtomicBoolean()
310
+
311
+ /** Resolves the JS call with [value]. A value JSON can't encode rejects it with `native_error` instead. */
312
+ override fun invoke(value: Any?) {
313
+ if (settled.compareAndSet(false, true)) resolve(value)
314
+ }
315
+
316
+ /** Rejects the JS call with `handler_error` and [message]. */
317
+ fun fail(message: String) {
318
+ if (settled.compareAndSet(false, true)) reject(message)
319
+ }
320
+ }
321
+
322
+ /**
323
+ * [HookContext]'s base: the hook's `hookOptions` value (null while its key is absent), its lists, and whether the core
324
+ * routes them. Chromium's IO thread reads [routed] and [clients] (shouldInterceptRequest), so [options] and the detach
325
+ * are volatile; the rest is main thread only. [detach] empties the lists and drops the handlers.
326
+ */
327
+ internal open class Attachment(value: Any?) {
328
+ @Volatile var options: Any? = value
329
+ private set
330
+ @Volatile private var detached = false
331
+ private val optionsHandlers = mutableListOf<(Any?) -> Unit>()
332
+ private val downloadHandlers = mutableListOf<(String, String, String, String, Long) -> Boolean>()
333
+
334
+ // Copy-on-write: Chromium reads the clients on its IO thread (shouldInterceptRequest) while attach and the hook's
335
+ // own changes write them.
336
+ val clients: MutableList<WebViewClient> = CopyOnWriteArrayList()
337
+ val chromeClients = mutableListOf<WebChromeClient>()
338
+ // Copy-on-write too: the core iterates them live, and a listener may remove itself while it runs.
339
+ val touchListeners: MutableList<View.OnTouchListener> = CopyOnWriteArrayList()
340
+ val scrollListeners: MutableList<View.OnScrollChangeListener> = CopyOnWriteArrayList()
341
+
342
+ /** Whether the hook is on and the attach is still there: the core routes the lists and passes events and asks. */
343
+ val routed get() = options != null && !detached
344
+
345
+ /** Runs [handler] with the options now and after each change; never once detached. */
346
+ fun onOptions(handler: (Any?) -> Unit) {
347
+ if (detached) return
348
+ optionsHandlers += handler
349
+ handler(options)
350
+ }
351
+
352
+ /** The hook's new `hookOptions` [value], null when its key is gone; the view calls it only for a changed value. */
353
+ fun optionsChanged(value: Any?) {
354
+ options = value
355
+ optionsHandlers.forEach { it(value) }
356
+ }
357
+
358
+ /** The attach ended: the core routes nothing of it, and the emits and asks that follow reach nothing. */
359
+ open fun detach() {
360
+ detached = true
361
+ optionsHandlers.clear()
362
+ downloadHandlers.clear()
363
+ clients.clear()
364
+ chromeClients.clear()
365
+ touchListeners.clear()
366
+ scrollListeners.clear()
367
+ }
368
+
369
+ fun onDownloadStart(handler: (String, String, String, String, Long) -> Boolean) {
370
+ downloadHandlers += handler
371
+ }
372
+
373
+ /** Whether one of the download handlers took the download; none is offered it while the hook is off or detached. */
374
+ fun downloadStarted(url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) =
375
+ routed && downloadHandlers.any { it(url, userAgent, contentDisposition, mimeType, contentLength) }
376
+
377
+ fun ifRouted(send: () -> Unit) {
378
+ if (routed) send()
379
+ }
380
+
381
+ fun askIfRouted(onAnswer: (Any?) -> Unit, send: () -> Unit) {
382
+ if (routed) send() else onAnswer(null)
383
+ }
384
+ }
385
+
386
+ /** The lists [pick] takes from the [attachments] that are [routed][Attachment.routed], one after the other. */
387
+ internal fun <T> routed(attachments: List<Attachment>, pick: (Attachment) -> List<T>) =
388
+ attachments.filter { it.routed }.flatMap(pick)
389
+
390
+ /**
391
+ * A hook's view of the WebView, one per hook and WebView: the core's context with the hook's key on its events. The
392
+ * handlers live here, so the WebView after a crash gets the ones its `attach` registers again. A hook can keep the
393
+ * context past its attach (an async callback): [detach] then leaves it holding nothing of the view.
394
+ */
395
+ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebView) :
396
+ Attachment(view.hookOptions[hook.key]), WebViewContext {
397
+ /** Null once the attach ended. Main thread only. */
398
+ private var view: MinimalWebView? = view
399
+ val key get() = hook.key
400
+ override val url get() = view?.url.orEmpty()
401
+ private val documentEndHandlers = mutableListOf<(DocumentEnd) -> Unit>()
402
+ private val destroyedHandlers = mutableListOf<(DocumentEnd) -> Unit>()
403
+ val handlers = mutableMapOf<String, (List<Any?>, HookReply) -> Unit>()
404
+
405
+ /** The attach ended: also drops the view and what the hook gave it, bar the [onDestroyed] handlers [destroyed] runs next. */
406
+ override fun detach() {
407
+ super.detach()
408
+ view = null
409
+ handlers.clear()
410
+ documentEndHandlers.clear()
411
+ }
412
+
413
+ override fun emit(name: String, payload: Map<String, Any?>) =
414
+ onMain { ifRouted { view?.emit(key, name, payload) } }
415
+
416
+ override fun ask(name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit) =
417
+ onMain { askIfRouted(onAnswer) { view?.asks?.ask(key, name, payload, onAnswer) } }
418
+
419
+ override fun onDocumentEnd(handler: (DocumentEnd) -> Unit) {
420
+ documentEndHandlers += handler
421
+ }
422
+
423
+ override fun onDestroyed(handler: (DocumentEnd) -> Unit) {
424
+ destroyedHandlers += handler
425
+ }
426
+
427
+ override fun handle(method: String, handler: (args: List<Any?>, reply: HookReply) -> Unit) {
428
+ handlers[method] = handler
429
+ }
430
+
431
+ fun documentEnded(reason: DocumentEnd) = documentEndHandlers.forEach { it(reason) }
432
+
433
+ /** The attach's WebView is destroyed: the handlers run once, and the context drops them. */
434
+ fun destroyed(reason: DocumentEnd) {
435
+ val handlers = destroyedHandlers.toList()
436
+ destroyedHandlers.clear()
437
+ handlers.forEach { it(reason) }
438
+ }
439
+
440
+ // A hook's shouldInterceptRequest runs on Chromium's IO thread; the view's events and asks are main-thread state.
441
+ private fun onMain(block: () -> Unit) {
442
+ if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post { block() }
443
+ }
444
+
445
+ private companion object {
446
+ val main = Handler(Looper.getMainLooper())
447
+ }
448
+ }
449
+
450
+ // Concurrent: shouldInterceptRequest asks on Chromium's IO thread while the main thread fills it.
451
+ private val overrideCache = ConcurrentHashMap<String, Boolean>()
452
+ private val BASES = setOf<Class<*>>(WebViewClient::class.java, WebChromeClient::class.java, WebViewClientCompat::class.java)
453
+
454
+ /**
455
+ * The base classes' own methods that only forward to a variant of the callback: the variant's parameter types, by the
456
+ * declaring class and the callback's signature. WebViewClient's and WebChromeClient's forward to a deprecated variant;
457
+ * WebViewClientCompat's first two are final.
458
+ */
459
+ private val VARIANTS: Map<Class<*>, Map<String, Array<Class<*>>>> = mapOf(
460
+ WebViewClient::class.java to mapOf(
461
+ signature("shouldOverrideUrlLoading", WebView::class.java, WebResourceRequest::class.java) to
462
+ arrayOf(WebView::class.java, String::class.java),
463
+ signature("shouldInterceptRequest", WebView::class.java, WebResourceRequest::class.java) to
464
+ arrayOf(WebView::class.java, String::class.java),
465
+ signature("onReceivedError", WebView::class.java, WebResourceRequest::class.java, WebResourceError::class.java) to
466
+ arrayOf(WebView::class.java, Integer.TYPE, String::class.java, String::class.java)
467
+ ),
468
+ WebChromeClient::class.java to mapOf(
469
+ signature("onConsoleMessage", ConsoleMessage::class.java) to arrayOf(String::class.java, Integer.TYPE, String::class.java)
470
+ ),
471
+ WebViewClientCompat::class.java to mapOf(
472
+ signature("onReceivedError", WebView::class.java, WebResourceRequest::class.java, WebResourceError::class.java) to
473
+ arrayOf(WebView::class.java, WebResourceRequest::class.java, WebResourceErrorCompat::class.java),
474
+ signature("onSafeBrowsingHit", WebView::class.java, WebResourceRequest::class.java, Integer.TYPE, SafeBrowsingResponse::class.java) to
475
+ arrayOf(WebView::class.java, WebResourceRequest::class.java, Integer.TYPE, SafeBrowsingResponseCompat::class.java),
476
+ signature("shouldOverrideUrlLoading", WebView::class.java, WebResourceRequest::class.java) to
477
+ arrayOf(WebView::class.java, String::class.java)
478
+ )
479
+ )
480
+
481
+ private fun signature(callback: String, vararg types: Class<*>) = "$callback(${types.joinToString { it.name }})"
482
+
483
+ /** Whether this client's class overrides the callback [callback] taking [types]; the base classes' own methods don't count. */
484
+ internal fun Any.overrides(callback: String, vararg types: Class<*>): Boolean = javaClass.overrides(callback, *types)
485
+
486
+ /**
487
+ * [Any.overrides] for the class. A subclass that leaves one of the base classes' forwarding methods in place
488
+ * (VARIANTS) overrides the callback only through the variant the forwarder calls.
489
+ */
490
+ internal fun Class<*>.overrides(callback: String, vararg types: Class<*>): Boolean =
491
+ overrideCache.getOrPut("$name#${signature(callback, *types)}") {
492
+ val declared = getMethod(callback, *types).declaringClass
493
+ if (declared !in BASES) return@getOrPut true
494
+ val variant = VARIANTS[declared]?.get(signature(callback, *types)) ?: return@getOrPut false
495
+ getMethod(callback, *variant).declaringClass !in BASES
496
+ }