Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/native-ui-engine.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ jobs:
-derivedDataPath "$RUNNER_TEMP/swift-package" \
-parallel-testing-enabled NO \
-collect-test-diagnostics never \
-skip-testing:WebViewNativeUIEngineTests/DocumentObservationTests \
-skip-testing:WebViewNativeUIEngineTests/NativeUIProjectionTests \
-skip-testing:WebViewNativeUIEngineTests/NativeUIScrollTrackerTests \
-skip-testing:WebViewNativeUIControlsTests/NativeUISnapshotTests/testNativePopoverClosureNotifiesWebBeforeReopening \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ import org.junit.Assert.*
import org.junit.Test

class NativeUIEngineTest {
@Test
fun cssFramesRoundDimensionsAndRejectUnsafeCoordinates() {
val rect = JSONObject("""{"x":-2.5,"y":3.2,"width":3.5,"height":0}""")
val pixels = NativeUIPixelFrame.fromCss(rect, 2f)!!
assertEquals(RectF(5f, 16f, 12f, 16f), pixels.bounds(10f, 10f))
assertNull(NativeUIPixelFrame.fromCss(rect, Float.NaN))
assertNull(NativeUIPixelFrame.fromCss(rect.put("width", -1), 2f))
assertNull(NativeUIPixelFrame.fromCss(rect.put("width", Int.MAX_VALUE), 2f))
assertNull(NativeUIPixelFrame.fromCss(rect.put("width", "12"), 2f))
rect.remove("width")
assertNull(NativeUIPixelFrame.fromCss(rect, 2f))
}

@Test
fun configuredOriginsExcludeNavigationDestinations() {
val config =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.github.webview_native_ui.engine

import android.content.Intent
import android.graphics.RectF
import android.os.SystemClock
import android.view.InputDevice
import android.view.MotionEvent
Expand All @@ -28,7 +27,7 @@ class NativeUIScrollHostingTest {

private lateinit var activity: EngineTestActivity
private lateinit var button: Button
private lateinit var clipped: NativeUIClippedView
private lateinit var clipped: NativeUIScrollHosting
private var projection: NativeUIProjection? = null
private var firstWebMove: (() -> Unit)? = null
private var softwareDraws = 0
Expand Down Expand Up @@ -60,7 +59,17 @@ class NativeUIScrollHostingTest {
return result
}

private fun load(kind: String = "overflow") {
private fun frame(x: Float, y: Float, width: Float, height: Float) =
NativeUIPixelFrame.fromCss(
JSONObject()
.put("x", x.toDouble())
.put("y", y.toDouble())
.put("width", width.toDouble())
.put("height", height.toDouble()),
scale,
)!!

private fun load(kind: String = "overflow", useHostingClip: Boolean = false) {
activity =
instrumentation.startActivitySync(
Intent(instrumentation.targetContext, EngineTestActivity::class.java)
Expand Down Expand Up @@ -121,13 +130,17 @@ class NativeUIScrollHostingTest {
true
}
}
val host = NativeUIScrollHosting(activity.web, button)
clipped = NativeUIClippedView(host)
activity.root.addView(clipped, FrameLayout.LayoutParams(1, 1))
clipped.place(
RectF(20 * scale, 80 * scale, (20 + (cssWidth - 40) / 2) * scale, 580 * scale),
RectF(20 * scale, 80 * scale, (cssWidth - 20) * scale, 580 * scale),
)
clipped = NativeUIScrollHosting(activity.web, button)
val bounds = frame(20f, 80f, (cssWidth - 40) / 2, 500f)
val clip = frame(20f, 80f, cssWidth - 40, 500f)
if (useHostingClip) {
activity.root.addView(clipped, FrameLayout.LayoutParams(1, 1))
clipped.place(bounds, clip)
} else {
val wrapper = NativeUIClippedView(clipped)
activity.root.addView(wrapper, FrameLayout.LayoutParams(1, 1))
wrapper.place(bounds.bounds(0f, 0f), clip.bounds(0f, 0f))
}
activity.web.setOnTouchListener { _, event ->
if (event.actionMasked == MotionEvent.ACTION_MOVE) {
val check = firstWebMove
Expand Down Expand Up @@ -254,7 +267,7 @@ class NativeUIScrollHostingTest {
androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT
)
)
load()
load(useHostingClip = true)
js(
"""
var slot=document.createElement('div'); slot.id='slot';slot.style.cssText='width:50%;height:250px';feed.prepend(slot);
Expand All @@ -270,8 +283,8 @@ class NativeUIScrollHostingTest {
main {
button.setBackgroundColor(android.graphics.Color.RED)
clipped.place(
RectF(20 * scale, 80 * scale, (20 + (cssWidth - 40) / 2) * scale, 330 * scale),
RectF(20 * scale, 80 * scale, (cssWidth - 20) * scale, 580 * scale),
frame(20f, 80f, (cssWidth - 40) / 2, 250f),
frame(20f, 80f, cssWidth - 40, 500f),
)
activity.web.webViewClient =
object : WebViewClient() {
Expand Down Expand Up @@ -300,16 +313,10 @@ class NativeUIScrollHostingTest {
captureMode = NativeUIProjection.CaptureMode.VIEW,
updatePlacement = { value ->
val clip = value.getJSONObject("clip")
fun rect(raw: JSONObject) =
RectF(
(raw.getDouble("x") * scale).toFloat(),
(raw.getDouble("y") * scale).toFloat(),
((raw.getDouble("x") + raw.getDouble("width")) * scale)
.toFloat(),
((raw.getDouble("y") + raw.getDouble("height")) * scale)
.toFloat(),
)
clipped.place(rect(value), rect(clip))
clipped.place(
NativeUIPixelFrame.fromCss(value, scale)!!,
NativeUIPixelFrame.fromCss(clip, scale)!!,
)
},
view = { button },
)
Expand Down Expand Up @@ -455,6 +462,20 @@ class NativeUIScrollHostingTest {
assertTrue(clicked)
}

@Test
fun onlyTheVisiblePartOfThePhotoReceivesSdkTaps() {
load(useHostingClip = true)
main {
clipped.place(frame(20f, 80f, cssWidth / 2, 500f), frame(20f, 200f, cssWidth / 2, 200f))
}
instrumentation.waitForIdleSync()
touch(true, y = 120f)
touch(true, y = 300f)
instrumentation.waitForIdleSync()
main { assertEquals(1, taps) }
assertEquals("1", js("webClicks"))
}

@Test
fun nativeTapAndLongPressNeverReachWeb() {
load()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.github.webview_native_ui.engine

import android.app.Activity

/** Native SDK work queued for an activity must recheck its owner when it runs. */
object NativeUIActivityLifecycle {
@JvmStatic
fun isAvailable(activity: Activity?): Boolean =
activity != null && !activity.isFinishing && !activity.isDestroyed

/** Check again on the UI thread, immediately before creating or presenting SDK UI. */
@JvmStatic
fun runOnUiThread(activity: Activity?, unavailable: Runnable, action: Runnable) {
if (activity == null) unavailable.run()
else
activity.runOnUiThread {
if (isAvailable(activity)) action.run() else unavailable.run()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,36 +31,38 @@ class NativeUIClippedView(val content: View) : FrameLayout(content.context) {
addView(content)
}

fun place(frame: RectF, clip: RectF): Boolean {
check(Looper.myLooper() == Looper.getMainLooper())
val visible = RectF(frame)
if (!frame.valid() || !clip.valid() || !visible.intersect(clip)) {
visibility = View.INVISIBLE
return false
}
val width = ceil(visible.width().toDouble()).toInt()
val height = ceil(visible.height().toDouble()).toInt()
val params = layoutParams ?: LayoutParams(width, height)
if (layoutParams == null || params.width != width || params.height != height) {
params.width = width
params.height = height
layoutParams = params
}
x = visible.left
y = visible.top
val contentWidth = ceil(frame.width().toDouble()).toInt()
val contentHeight = ceil(frame.height().toDouble()).toInt()
val child = content.layoutParams
if (child.width != contentWidth || child.height != contentHeight) {
child.width = contentWidth
child.height = contentHeight
content.layoutParams = child
}
content.x = frame.left - visible.left
content.y = frame.top - visible.top
visibility = View.VISIBLE
return true
fun place(frame: RectF, clip: RectF): Boolean = placeClippedContent(content, frame, clip)
}

internal fun FrameLayout.placeClippedContent(content: View, frame: RectF, clip: RectF): Boolean {
check(Looper.myLooper() == Looper.getMainLooper())
val visible = RectF(frame)
if (!frame.valid() || !clip.valid() || !visible.intersect(clip)) {
visibility = View.INVISIBLE
return false
}
val width = ceil(visible.width().toDouble()).toInt()
val height = ceil(visible.height().toDouble()).toInt()
val params = layoutParams ?: FrameLayout.LayoutParams(width, height)
if (layoutParams == null || params.width != width || params.height != height) {
params.width = width
params.height = height
layoutParams = params
}
x = visible.left
y = visible.top
val contentWidth = ceil(frame.width().toDouble()).toInt()
val contentHeight = ceil(frame.height().toDouble()).toInt()
val child = content.layoutParams
if (child.width != contentWidth || child.height != contentHeight) {
child.width = contentWidth
child.height = contentHeight
content.layoutParams = child
}
content.x = frame.left - visible.left
content.y = frame.top - visible.top
visibility = View.VISIBLE
return true
}

internal fun RectF.valid(): Boolean =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package io.github.webview_native_ui.engine

import android.graphics.RectF
import kotlin.math.roundToInt
import org.json.JSONObject

/** A viewport CSS rectangle converted to integer device pixels, including empty clips. */
class NativeUIPixelFrame
private constructor(val x: Int, val y: Int, val width: Int, val height: Int) {
internal fun bounds(offsetX: Float, offsetY: Float): RectF =
RectF(offsetX + x, offsetY + y, offsetX + (x + width), offsetY + (y + height))

companion object {
@JvmStatic
fun fromCss(value: JSONObject?, density: Float): NativeUIPixelFrame? {
if (value == null || !density.isFinite() || density <= 0) return null
// MeasureSpec reserves two bits. This limit also keeps endpoint sums inside Int.
val limit = 0x3fffffff.toDouble()
fun pixel(key: String, min: Double): Int? {
val scaled = (value.opt(key) as? Number)?.toDouble()?.times(density) ?: return null
return if (scaled in min..limit) scaled.roundToInt() else null
}
return NativeUIPixelFrame(
pixel("x", -limit) ?: return null,
pixel("y", -limit) ?: return null,
pixel("width", 0.0) ?: return null,
pixel("height", 0.0) ?: return null,
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import android.widget.FrameLayout

/** SDK taps stay native; only a drag is handed to the WebView's own scroll recognizer. */
@SuppressLint("ViewConstructor")
class NativeUIScrollHosting(private val webView: WebView, content: View) :
class NativeUIScrollHosting(private val webView: WebView, private val content: View) :
FrameLayout(content.context) {
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private var down: MotionEvent? = null
Expand All @@ -20,6 +20,14 @@ class NativeUIScrollHosting(private val webView: WebView, content: View) :
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}

/** Place a sibling of the WebView from viewport-relative device pixels. */
fun place(frame: NativeUIPixelFrame, clip: NativeUIPixelFrame): Boolean =
placeClippedContent(
content,
frame.bounds(webView.x, webView.y),
clip.bounds(webView.x, webView.y),
)

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
reset()
Expand Down
35 changes: 35 additions & 0 deletions docs/reference/platforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,38 @@ Prepared images stay in the app's private temporary storage. iOS uses `FileManag
`Capacitor.convertFileSrc` maps the returned file URL to the existing WebView local server. It grants no filesystem permission and does not upload the image. If the application sets a Content Security Policy, its `img-src` must allow the local app origin used by that URL; do not enable broad `file:` access or unrelated WebView file-access settings.

`release(token)` and owner teardown remove owned snapshot files. Abrupt process termination can leave temporary images until the operating system clears the cache or the app is uninstalled; immediate deletion after a crash is not guaranteed. Keep this storage private and treat it as disposable, not persistent application data.

## Document-bound SDK views

Measure the DOM host with `measureProjectionFrame(element)`. The returned frame
and clip use viewport CSS pixels and account for scaled, axis-aligned overflow
ancestors, including slots and shadow hosts. A renderer that owns native scrolling
can pass `scrollOwner` and translate the result into that container's coordinates.
Use `observeProjectionLayout(window, hosts, update)` for author attribute changes,
scrolls in the document and shadow trees, and viewport resize or pan. Only DOM
scroll passes its event to `update`. Observe element sizes with `ResizeObserver`
as needed. Call the returned function on teardown or before rebinding a changed
set of hosts or ancestors.

If the app supplies a viewport clip, pass the same callback to
`bindSnapshotVisibleArea(element, visibleArea)` and pass its current result to `measureProjectionFrame` as `visibleArea`.
The Engine clips each snapshot image in viewport coordinates while it moves.
If the callback throws, the image stays clipped to an empty area until a later read succeeds.
Release the binding when the plugin detaches the host.

On Android, `NativeUIPixelFrame.fromCss(rect, density)` validates and rounds
bridge rectangle components to device pixels. It accepts empty clips and returns
null for malformed values. For fixed-size SDK views, `NativeUIScrollHosting.place`
applies the same clipping geometry as `NativeUIClippedView.place` while preserving SDK taps and WebView drags.

On iOS, retain a `NativeUIDocumentObservation(webView:onReplacement:)` when
the first document-bound session starts. Its closure runs at the start of the
next main document in that WebView, including a reload after WebContent process
termination. Release resources and discard pending bridge replies for the old
document there. Capture the session owner weakly.

On Android, release SDK resources in the plugin teardown callback (for Capacitor,
`handleOnDestroy`). Queue SDK presentation with
`NativeUIActivityLifecycle.runOnUiThread(activity, unavailable, action)` so a
finishing or destroyed Activity is checked when queued work actually runs.
The plugin supplies the SDK cleanup and the response to a cancelled operation.
38 changes: 38 additions & 0 deletions ios/Sources/WebViewNativeUIEngine/DocumentObservation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import WebKit

/// Retain the observation for the lifetime of the renderer. Only new main documents trigger cleanup.
@MainActor
public final class NativeUIDocumentObservation {
fileprivate weak var webView: WKWebView?
fileprivate let documentStarted: () -> Void

public init(webView: WKWebView, onReplacement: @escaping () -> Void) {
self.webView = webView
documentStarted = onReplacement
DocumentHandler.shared(webView.configuration.userContentController).observations.add(self)
}
}

@MainActor
private final class DocumentHandler: NSObject, WKScriptMessageHandler {
static let handlers = NSMapTable<WKUserContentController, DocumentHandler>.weakToWeakObjects()
let observations = NSHashTable<NativeUIDocumentObservation>.weakObjects()

static func shared(_ controller: WKUserContentController) -> DocumentHandler {
if let existing = handlers.object(forKey: controller) { return existing }
let handler = DocumentHandler()
let world = WKContentWorld.world(name: "WebViewNativeUIEngine.Document")
controller.add(handler, contentWorld: world, name: "documentStarted")
controller.addUserScript(WKUserScript(source: "window.webkit.messageHandlers.documentStarted.postMessage(null)",
injectionTime: .atDocumentStart, forMainFrameOnly: true, in: world))
handlers.setObject(handler, forKey: controller)
return handler
}

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard message.frameInfo.isMainFrame, let source = message.webView else { return }
for observation in observations.allObjects where observation.webView === source {
observation.documentStarted()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,7 @@ final class NativeUICoveredSnapshotsTests: XCTestCase {
let backCapture = await capture("back")
let background = try XCTUnwrap(backCapture["token"] as? String)
XCTAssertTrue(snapshots.cover(background, in: view, views: []))
snapshots.retireCopy(background)
let modalCapture = await capture("modal")
let foreground = try XCTUnwrap(modalCapture["token"] as? String)
XCTAssertTrue(snapshots.cover(foreground, in: view, views: [], transient: true))
Expand Down
Loading
Loading