diff --git a/.gitattributes b/.gitattributes index d48d983ded..f9a162946d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ # Vendored-crate patches apply to the published LF crates; keep them byte-exact on every checkout. packages/tauri-app/vendor/patches/*.patch -text +packages/tauri-app/tests/webkit-capabilities/*.sh text eol=lf diff --git a/.github/scripts/tauri-webkit-workflow.test.cjs b/.github/scripts/tauri-webkit-workflow.test.cjs new file mode 100644 index 0000000000..7d83e7b0d9 --- /dev/null +++ b/.github/scripts/tauri-webkit-workflow.test.cjs @@ -0,0 +1,29 @@ +const assert = require('node:assert/strict') +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') + +test('Windows native qualification also runs authorized drafts without signing secrets', () => { + const workflow = fs.readFileSync(path.join(__dirname, '../workflows/pr-build.yml'), 'utf8').replace(/\r\n/g, '\n') + const job = workflow.split(' tests-tauri-windows:\n')[1].split('\n tests-')[0] + assert.match(job, /needs: authorize/) + assert.match(job, /if: \$\{\{ needs\.authorize\.outputs\.allowed == 'true' \}\}/) + assert.doesNotMatch(job, /pull_request\.draft|secrets\.|secrets:|actions: write/) + assert.match(job, /cargo test --locked -- --test-threads=1/) +}) + +test('WebKit qualification runs authorized drafts on Intel, ARM64 and Linux without secrets', () => { + const workflow = fs.readFileSync(path.join(__dirname, '../workflows/pr-build.yml'), 'utf8').replace(/\r\n/g, '\n') + const job = workflow.split(' tests-tauri-webkit:\n')[1].split('\n # Exercise the window persistence')[0] + assert.match(job, /needs: authorize/) + assert.match(job, /if: \$\{\{ needs\.authorize\.outputs\.allowed == 'true' \}\}/) + assert.doesNotMatch(job, /pull_request\.draft|secrets\.|secrets:|actions: write/) + for (const runner of ['macos-15-intel', 'macos-26', 'ubuntu-24.04']) assert.ok(job.includes(`os: ${runner}`)) + for (const command of ['cargo check --locked', 'cargo clippy --locked', 'cargo test --locked', 'tauri build --no-bundle', 'tauri bundle --bundles app ', 'tauri bundle --bundles appimage']) assert.ok(job.includes(command), command) + assert.ok(job.includes('cargo build --locked --example browser-parent-webkit --features browser-parent-qualification')) + assert.match(job, /Print :LSMinimumSystemVersion/) + assert.match(job, /test "\$minimum" = '14\.0'/) + assert.ok(job.includes('lipo "${apps[0]}/Contents/MacOS/$executable" -verify_arch "$EXPECTED_ARCH"')) + assert.match(job, /path: .*\/appimage\/\*\.AppImage/) + assert.match(job, /persist-credentials: false/) +}) diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index ae6372d36f..3fba8118b7 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -55,6 +55,7 @@ jobs: - tests-session-pruning-native - tests-runtime-contracts - tests-tauri-macos + - tests-tauri-webkit if: ${{ needs.authorize.outputs.allowed == 'true' && !github.event.pull_request.draft }} uses: ./.github/workflows/build-and-upload.yml with: @@ -628,7 +629,7 @@ jobs: tests-tauri-windows: needs: authorize - if: ${{ needs.authorize.outputs.allowed == 'true' && !github.event.pull_request.draft }} + if: ${{ needs.authorize.outputs.allowed == 'true' }} runs-on: windows-latest steps: - name: Checkout @@ -782,6 +783,103 @@ jobs: if ($LASTEXITCODE) { exit $LASTEXITCODE } } + # Native WebKit qualification also runs on drafts, without signing credentials. + tests-tauri-webkit: + needs: authorize + if: ${{ needs.authorize.outputs.allowed == 'true' }} + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - os: macos-15-intel + arch: x86_64 + - os: macos-26 + arch: arm64 + - os: ubuntu-24.04 + arch: x86_64 + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + env: + CARGO_INCREMENTAL: "0" + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_TEST_DEBUG: "0" + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: actions/setup-node@v7.1.0 + with: + node-version-file: .node-version + cache: npm + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - name: Install Linux WebKit dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y build-essential pkg-config zsh libgtk-3-dev \ + libglib2.0-dev libwebkit2gtk-4.1-dev libsoup-3.0-dev \ + libayatana-appindicator3-dev librsvg2-dev + - run: npm ci --workspaces --include=optional + - name: Test WebKit qualification workflow contract + run: node --test .github/scripts/tauri-webkit-workflow.test.cjs + - name: Prepare packaged server and browser resources + run: npm run prebuild --workspace @codenomad/tauri-app + - name: Check Tauri crate + working-directory: packages/tauri-app + run: cargo check --locked + - name: Clippy Tauri crate + working-directory: packages/tauri-app + run: cargo clippy --locked --no-deps + - name: Build native parent qualification example + working-directory: packages/tauri-app + run: cargo build --locked --example browser-parent-webkit --features browser-parent-qualification + - name: Test Tauri crate + working-directory: packages/tauri-app + run: CODENOMAD_TEST_ZSH=/bin/zsh CODENOMAD_TEST_NODE="$(command -v node)" cargo test --locked -- --test-threads=4 + - name: Build Tauri without bundling + working-directory: packages/tauri-app + run: npm exec -- tauri build --no-bundle --config src-tauri/tauri.prebuilt.conf.json + - name: Bundle unsigned macOS app + if: runner.os == 'macOS' + working-directory: packages/tauri-app + run: npm exec -- tauri bundle --bundles app --config src-tauri/tauri.prebuilt.conf.json + - name: Verify macOS minimum and architecture + if: runner.os == 'macOS' + env: + EXPECTED_ARCH: ${{ matrix.arch }} + run: | + set -euo pipefail + shopt -s nullglob + apps=(packages/tauri-app/target/release/bundle/macos/*.app) + test "${#apps[@]}" -eq 1 + plist="${apps[0]}/Contents/Info.plist" + minimum=$(/usr/libexec/PlistBuddy -c 'Print :LSMinimumSystemVersion' "$plist") + test "$minimum" = '14.0' + executable=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$plist") + lipo "${apps[0]}/Contents/MacOS/$executable" -verify_arch "$EXPECTED_ARCH" + echo "Verified $EXPECTED_ARCH bundle: LSMinimumSystemVersion=$minimum" >> "$GITHUB_STEP_SUMMARY" + - name: Bundle unsigned Linux AppImage + if: runner.os == 'Linux' + working-directory: packages/tauri-app + env: + APPIMAGE_EXTRACT_AND_RUN: "1" + # Keep the WSLg/system display and GPU stack, as in release packaging. + LINUXDEPLOY_EXCLUDED_LIBRARIES: libwayland-*;libxkbcommon*;libxcb*;libX11*;libXau*;libXdmcp*;libEGL*;libGL*;libgbm*;libdrm* + run: npm exec -- tauri bundle --bundles appimage --verbose --config src-tauri/tauri.prebuilt.conf.json + - name: Upload Linux AppImage for WSLg trials + if: runner.os == 'Linux' + uses: actions/upload-artifact@v7.0.2 + with: + name: pr-${{ github.event.pull_request.number }}-tauri-webkit-linux-x64 + path: packages/tauri-app/target/release/bundle/appimage/*.AppImage + if-no-files-found: error + retention-days: 7 + # Exercise the window persistence regressions on the architecture reported in # #676, independently of the Linux server gate. Packaging alone cannot test them. tests-tauri-macos: diff --git a/BUILD.md b/BUILD.md index 167a6230e4..42979a0240 100644 --- a/BUILD.md +++ b/BUILD.md @@ -30,8 +30,8 @@ then rebuild and smoke-test the packaged applications on Windows, macOS, and Linux. Check the upstream platform requirements before changing a pin or the Electron version: Tauri's bundled Node 24 requires macOS 13.5 or later, and the pinned Electron (`packages/electron-app/package.json`) requires macOS 13 -or later and Windows 10 or later. Both macOS bundles declare 13.5 so the two -desktop builds share one minimum; keep them aligned. Keep the versions exact +or later and Windows 10 or later. Electron declares macOS 13.5; Tauri declares macOS 14 for identified +WKWebView preview stores. Keep the versions exact rather than resolving `latest` or `lts/*` at build time so release inputs remain reproducible. @@ -142,8 +142,9 @@ Electron names deb architectures the Debian way (`amd64`) and Tauri keeps its na ### macOS -- **Build on:** macOS 13.5+ with the required Xcode tools (CI uses macOS 15) -- **Run on:** macOS 13.5+ (Intel and Apple Silicon; required by Tauri's bundled Node 24, shared by Electron) +- **Build on:** macOS 13.5+ for Electron, macOS 14+ for Tauri, with the required Xcode tools (CI uses macOS 15) +- **Run on:** Electron macOS 13.5+; Tauri macOS 14+ (Intel and Apple Silicon) +- **Tauri bundles:** keep `minimumSystemVersion` and `LSMinimumSystemVersion` at 14.0 for both architectures; scope any `MACOSX_DEPLOYMENT_TARGET=14.0` override to Tauri build steps. - **Code signing:** Optional (recommended for distribution) ### Windows diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index 649d603cc0..9a98958e39 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -52,12 +52,12 @@ only a qualified path is retained across calls. ## Page engine -`codenomad.inspect` / `codenomad.act` (the CodeNomad window) and `codenomad.browser` (the session preview) run on the same page engine in `packages/server/src/automation/page/`, which only needs a DevTools protocol channel: `snapshot.ts` renders the accessibility tree, `actions.ts` performs actions, `input.ts` dispatches trusted pointer, wheel and keyboard input, `keys.ts` maps key chords, `parse.ts` validates tool input on both sides of the bridge, `protocol.ts` holds the shared protocol primitives and `refs.ts` names DOM nodes. The app uses `DeveloperCdp`; previews use `automation/browser-page.ts`. The preview's `snapshot({ ref, query })` has the same outline and scoping as the app's `inspect`. +`codenomad.inspect` / `codenomad.act` (the CodeNomad window) and `codenomad.browser` (the session preview) run on the same page engine in `packages/server/src/automation/page/`. `protocol.ts` defines the semantic `PageDriver`: normalized tree, stable node/handle resolution, predefined function calls with JSON arguments, geometry, viewport, hit testing, native input, handle release and checkpoints. `cdp-driver.ts` adapts that contract to DevTools; `native-driver.ts` uses the fenced parent channel. `snapshot.ts` retains the outline renderer and budgets, `actions.ts`/`input.ts` retain action orchestration, `keys.ts` maps chords, and `refs.ts` owns document-scoped references. The app uses `DeveloperCdp`; previews use `automation/browser-page.ts`. The preview's `snapshot({ ref, query })` has the same outline and scoping as the app's `inspect`. - Inspection is an indented outline with refs, read as plain text. Wrappers, unnamed images and text repeating its parent's name are dropped; fields show their value instead of their inner nodes; native selects list their options with `selected`/`disabled`. A character budget (32 000 by default) is shared among siblings: small parts stay whole while large ones collapse in place with `(+N hidden)` or `(+N more)`, keeping their first and last items, so nothing is cut silently. `ref` expands one subtree and `query` keeps elements whose name, value or description contains it, or whose role is exactly it, with their contents and ancestors. - A ref names one node within one target, run and navigation epoch. It keeps its name and stays usable for the life of that page generation, whatever is inspected later; a node that left the page fails its action explicitly. - `type` focuses the field and refuses one that cannot take focus (hidden, disabled, behind a modal dialog), because native text insertion goes to the focused element. It then replaces the field's text by default (select, then native insertion, so framework input handlers fire); `clear: false` appends. Date, time, range and color inputs are validated before anything changes, then set with `input`/`change`, keeping the browser's normalization; email and number inputs append as a value. `select` picks native `` + : `` + const html = `
${field}
` + const dialog = new BrowserWindow({ parent: owner, modal: true, show: false, width: 520, height: "text" in input ? 240 : 440, + title: origin, autoHideMenuBar: true, + webPreferences: { partition: `browser-dialog-${randomUUID()}`, nodeIntegration: false, contextIsolation: true, sandbox: true, + webSecurity: true, webviewTag: false, disableDialogs: true } }) + dialogs.add(dialog) + dialog.webContents.session.setPermissionCheckHandler(() => false) + dialog.webContents.session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)) + dialog.setMenu(null) + dialog.webContents.setWindowOpenHandler(() => ({ action: "deny" })) + return new Promise(resolve => { + let settled = false + const finish = (value: string | null) => { + if (settled) return + settled = true + owner.removeListener("closed", cancel) + source?.removeListener("destroyed", cancel) + source?.removeListener("did-navigate", cancel) + source?.removeListener("did-frame-navigate", cancel) + source?.removeListener("render-process-gone", cancel) + resolve(current() ? value : null) + if (!dialog.isDestroyed()) dialog.destroy() + } + const cancel = () => finish(null) + owner.once("closed", cancel) + source?.once("destroyed", cancel) + source?.once("did-navigate", cancel) + source?.once("did-frame-navigate", cancel) + source?.once("render-process-gone", cancel) + dialog.once("closed", cancel) + dialog.webContents.on("will-navigate", (event, url) => { + event.preventDefault() + try { + const result = new URL(url) + if (`${result.origin}${result.pathname}` !== target) return + finish(result.searchParams.get("action") === "accept" ? result.searchParams.get("value") ?? "" : null) + } catch { finish(null) } + }) + dialog.webContents.on("before-input-event", (_event, key) => { if (key.type === "keyDown" && key.key === "Escape") cancel() }) + dialog.once("ready-to-show", () => { if (!dialog.isDestroyed()) dialog.show() }) + void dialog.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(cancel) + }) +} diff --git a/packages/electron-app/electron/main/browser-display-chooser.ts b/packages/electron-app/electron/main/browser-display-chooser.ts new file mode 100644 index 0000000000..6754ca0cc5 --- /dev/null +++ b/packages/electron-app/electron/main/browser-display-chooser.ts @@ -0,0 +1,34 @@ +import { desktopCapturer, webContents, type Session, type Streams } from "electron" +import { permissionOrigin } from "./browser-permission-policy" +import { nativeMenuLabels } from "./view-menu" +import { showBrowserDialog } from "./browser-dialog" +import { browserGuestLifetime } from "./browser-guest-lifetime" + +export function configureBrowserDisplayChooser(target: Session): void { + target.setDisplayMediaRequestHandler((request, callback) => { + const frame = request.frame + const origin = permissionOrigin(request.securityOrigin) + if (!frame || !origin || !request.userGesture || !request.videoRequested) { callback(null); return } + void (async () => { + let streams: Streams | null = null + try { + const contents = webContents.fromFrame(frame) + if (!contents) throw new Error("Expired browser frame") + const owner = browserGuestLifetime.owner(contents) + const revision = browserGuestLifetime.revision(contents) + const current = () => browserGuestLifetime.owner(contents) === owner && browserGuestLifetime.revision(contents) === revision + && !frame.detached && permissionOrigin(frame.origin) === origin + const l = nativeMenuLabels(owner ?? null) + const sources = await desktopCapturer.getSources({ types: ["screen", "window"], thumbnailSize: { width: 0, height: 0 } }) + if (owner && sources.length && current()) { + const result = await showBrowserDialog(owner, origin, + l.browserPermission.replace("{permission}", "display-capture").replace("{origin}", origin), + { choices: sources.map(source => source.name) }, contents, current) + const selected = result !== null && /^(0|[1-9]\d*)$/.test(result) ? sources[Number(result)] : undefined + if (selected && current()) streams = { video: selected } + } + } catch (error) { console.warn("[browser-display] request unavailable", error) } + callback(streams) + })() + }, { useSystemPicker: true }) +} diff --git a/packages/electron-app/electron/main/browser-downloads.test.ts b/packages/electron-app/electron/main/browser-downloads.test.ts new file mode 100644 index 0000000000..fc2453a036 --- /dev/null +++ b/packages/electron-app/electron/main/browser-downloads.test.ts @@ -0,0 +1,23 @@ +import assert from "node:assert/strict" +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { dirname, join, basename } from "node:path" +import { test } from "node:test" +import { reserveBrowserDownload } from "./browser-downloads" + +test("download reservations are confined, sanitized, unique and never replace files", () => { + const directory = mkdtempSync(join(tmpdir(), "codenomad-download-")) + try { + for (const name of ["../../secret.txt", "..\\..\\secret.txt", "..", "a\n:b?.txt", "é".repeat(300)]) { + const first = reserveBrowserDownload(directory, name) + writeFileSync(first, "original") + const second = reserveBrowserDownload(directory, name) + assert.notEqual(first, second) + assert.equal(dirname(first), directory) + assert.equal(/[\x00-\x1f/\\:*?"<>|]/.test(basename(first)), false) + assert.ok(Buffer.byteLength(basename(first)) <= 217) + assert.equal(readFileSync(first, "utf8"), "original") + } + assert.throws(() => reserveBrowserDownload(join(directory, "missing"), "file")) + } finally { rmSync(directory, { recursive: true, force: true }) } +}) diff --git a/packages/electron-app/electron/main/browser-downloads.ts b/packages/electron-app/electron/main/browser-downloads.ts new file mode 100644 index 0000000000..1a0f9d5ac9 --- /dev/null +++ b/packages/electron-app/electron/main/browser-downloads.ts @@ -0,0 +1,41 @@ +import { randomUUID } from "node:crypto" +import { closeSync, openSync, statSync, unlinkSync } from "node:fs" +import { basename, join } from "node:path" +import type { Session } from "electron" + +export function reserveBrowserDownload(directory: string, suggested: string): string { + if (!statSync(directory).isDirectory()) throw new Error("Downloads directory unavailable") + const source = basename(suggested.replaceAll("\\", "/")).replace(/[\x00-\x1f\x7f/\\:*?"<>|]/g, "") + let name = "" + for (const character of source) { + if (Buffer.byteLength(name + character) > 180) break + name += character + } + name = name.replace(/^[ .]+|[ .]+$/g, "") || "download" + const path = join(directory, `${randomUUID()}-${name}`) + closeSync(openSync(path, "wx")) + return path +} + +export function configureBrowserDownloads(target: Session, directory: string): void { + target.on("will-download", (event, item, contents) => { + let path: string | undefined + try { + const url = new URL(item.getURL()) + if (!contents || contents.isDestroyed() || !["http:", "https:", "blob:", "data:"].includes(url.protocol) + || url.username || url.password) throw new Error("Blocked browser download") + path = reserveBrowserDownload(directory, item.getFilename()) + item.setSavePath(path) + const reserved = path + item.once("done", (_event, state) => { + if (state !== "completed") { + try { if (statSync(reserved).size === 0) unlinkSync(reserved) } catch {} + } + }) + } catch (error) { + event.preventDefault() + if (path) { try { unlinkSync(path) } catch {} } + console.warn("[browser-download]", error) + } + }) +} diff --git a/packages/electron-app/electron/main/browser-guest-lifetime.test.ts b/packages/electron-app/electron/main/browser-guest-lifetime.test.ts new file mode 100644 index 0000000000..c2bad43c75 --- /dev/null +++ b/packages/electron-app/electron/main/browser-guest-lifetime.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { BrowserGuestLifetime } from "./browser-guest-lifetime" + +function fixture() { + const lifetime = new BrowserGuestLifetime() + const closed: string[] = [] + const guest = (name: string) => ({ isDestroyed: () => false, close: (options: unknown) => { + assert.deepEqual(options, { waitForBeforeUnload: false }) + assert.equal(lifetime.owner(root as never), undefined) + assert.equal(lifetime.owner(child as never), undefined) + closed.push(name) + } }) + const owner = { isDestroyed: () => false, webContents: { isDestroyed: () => false } } + const root = guest("root"), child = guest("child"), grandchild = guest("grandchild") + lifetime.register(owner as never, root as never) + lifetime.register(owner as never, child as never, root as never) + lifetime.register(owner as never, grandchild as never, child as never) + return { lifetime, closed, owner, root, child, grandchild } +} + +test("owner cleanup atomically invalidates nested previews before forced destruction and isolates peers", () => { + const f = fixture() + const peerOwner = { isDestroyed: () => false, webContents: { isDestroyed: () => false } } + const peer = { isDestroyed: () => false } + f.lifetime.register(peerOwner as never, peer as never) + f.lifetime.removeOwner(f.owner as never) + assert.deepEqual(new Set(f.closed), new Set(["root", "child", "grandchild"])) + assert.equal(f.lifetime.owner(peer as never), peerOwner) + f.lifetime.removeOwner(f.owner as never) + assert.equal(f.closed.length, 3) + assert.throws(() => f.lifetime.register(f.owner as never, {} as never, f.root as never), /Expired/) +}) + +test("document replacement rotates the callback fence and destroys every descendant", () => { + const f = fixture() + // Destruction callbacks see the retained root, but all descendants are absent. + const popup = { isDestroyed: () => false, destroy: () => { + assert.equal(f.lifetime.owner(f.child as never), undefined) + assert.equal(f.lifetime.owner(f.grandchild as never), undefined) + } } + f.lifetime.register(f.owner as never, f.child as never, f.root as never, popup as never) + f.lifetime.register(f.owner as never, f.grandchild as never, f.child as never, popup as never) + const before = f.lifetime.revision(f.root as never) + f.lifetime.replaceDocument(f.root as never) + assert.notEqual(f.lifetime.revision(f.root as never), before) + assert.equal(f.lifetime.owner(f.root as never), f.owner) + const other = { isDestroyed: () => false, webContents: { isDestroyed: () => false } } + assert.throws(() => f.lifetime.register(other as never, {} as never, f.root as never), /Expired/) +}) diff --git a/packages/electron-app/electron/main/browser-guest-lifetime.ts b/packages/electron-app/electron/main/browser-guest-lifetime.ts new file mode 100644 index 0000000000..b9761fc8a8 --- /dev/null +++ b/packages/electron-app/electron/main/browser-guest-lifetime.ts @@ -0,0 +1,58 @@ +import type { BrowserWindow, WebContents } from "electron" + +/** Invalidate the whole tree before native destruction can dispatch callbacks. */ +export class BrowserGuestLifetime { + private readonly entries = new Map() + + register(owner: BrowserWindow, guest: WebContents, parent?: WebContents, popup?: BrowserWindow): void { + if (owner.isDestroyed() || owner.webContents.isDestroyed() || (parent && this.owner(parent) !== owner)) throw new Error("Expired preview owner") + this.entries.set(guest, { owner, parent, popup, document: Symbol() }) + } + + owner(guest: WebContents | null): BrowserWindow | undefined { + return guest && this.live(guest) ? this.entries.get(guest)?.owner : undefined + } + + live(guest: WebContents): boolean { + const entry = this.entries.get(guest) + return Boolean(entry && !entry.owner.isDestroyed() && !entry.owner.webContents.isDestroyed() && !guest.isDestroyed()) + } + + descendants(opener: WebContents): void { this.dispose(new Set([opener]), false) } + revision(guest: WebContents): symbol | undefined { return this.entries.get(guest)?.document } + invalidateCallbacks(guest: WebContents): void { + const entry = this.entries.get(guest) + if (entry) entry.document = Symbol() + } + replaceDocument(guest: WebContents): void { + this.invalidateCallbacks(guest) + this.descendants(guest) + } + remove(guest: WebContents): void { this.dispose(new Set([guest]), true) } + removeOwner(owner: BrowserWindow): void { + this.dispose(new Set([...this.entries].filter(([, entry]) => entry.owner === owner).map(([guest]) => guest)), true) + } + + private dispose(roots: Set, includeRoots: boolean): void { + const selected = new Set(includeRoots ? roots : []) + // ponytail: scan per tree depth; index parents if preview trees become large. + let changed = true + while (changed) { + changed = false + for (const [guest, entry] of this.entries) { + if (entry.parent && (roots.has(entry.parent) || selected.has(entry.parent)) && !selected.has(guest)) { + selected.add(guest); changed = true + } + } + } + const entries = [...selected].map(guest => [guest, this.entries.get(guest)] as const) + for (const [guest] of entries) this.entries.delete(guest) + for (const [guest, entry] of entries.reverse()) { + if (!entry) continue + if (entry.popup && !entry.popup.isDestroyed()) entry.popup.destroy() + else if (!guest.isDestroyed()) guest.close({ waitForBeforeUnload: false }) + } + } +} + +export const browserGuestLifetime = new BrowserGuestLifetime() diff --git a/packages/electron-app/electron/main/browser-guests.ts b/packages/electron-app/electron/main/browser-guests.ts new file mode 100644 index 0000000000..187c3289a7 --- /dev/null +++ b/packages/electron-app/electron/main/browser-guests.ts @@ -0,0 +1,99 @@ +import { BrowserWindow, clipboard, dialog, Menu, type WebContents } from "electron" +import { isBrowserDownloadUrlAllowed, isBrowserSiteUrlAllowed, isBrowserUrlAllowed } from "./browser-webview-security" +import { nativeMenuLabels } from "./view-menu" +import { isBrowserDialog } from "./browser-dialog" +import { installBrowserPrompt } from "./browser-prompt" +import { browserGuestLifetime } from "./browser-guest-lifetime" + +const windows = new WeakSet() +const observedOwners = new WeakSet() +export const isBrowserAuxiliaryWindow = (window: BrowserWindow) => windows.has(window) || isBrowserDialog(window) +export const browserGuestOwner = (contents: WebContents | null) => browserGuestLifetime.owner(contents) +let promptConfigured = false +export function configureBrowserGuests(): void { + if (promptConfigured) return + promptConfigured = true + installBrowserPrompt(browserGuestOwner) +} + +export function focusedBrowserGuest(window: BrowserWindow, focused: WebContents | null): WebContents | undefined { + return focused && browserGuestOwner(focused) === window ? focused : undefined +} + +/** Called before a popup's first navigation, and on each attached preview root. */ +export function protectBrowserGuest(owner: BrowserWindow, guest: WebContents, inheritedOrigin = "", parent?: WebContents, popup?: BrowserWindow): void { + browserGuestLifetime.register(owner, guest, parent, popup) + if (!observedOwners.has(owner)) { + observedOwners.add(owner) + const cleanup = () => browserGuestLifetime.removeOwner(owner) + owner.on("close", event => { if (!event.defaultPrevented) cleanup() }) + owner.once("closed", cleanup) + owner.webContents.once("destroyed", cleanup) + owner.webContents.on("did-navigate", cleanup) + owner.webContents.on("render-process-gone", cleanup) + } + const live = () => browserGuestLifetime.live(guest) + let origin = isBrowserUrlAllowed(guest.getURL()) ? guest.getURL() : inheritedOrigin + guest.once("destroyed", () => browserGuestLifetime.remove(guest)) + guest.on("render-process-gone", () => browserGuestLifetime.replaceDocument(guest)) + guest.on("did-navigate", (_event, url) => { + browserGuestLifetime.replaceDocument(guest) + if (live() && isBrowserUrlAllowed(url)) origin = url + }) + guest.on("did-frame-navigate", (_event, _url, _code, _status, main) => { + if (!main) browserGuestLifetime.invalidateCallbacks(guest) + }) + const guard = (event: Electron.Event, url: string) => { + if (!live() || !isBrowserSiteUrlAllowed(url, origin)) event.preventDefault() + } + guest.on("will-navigate", guard) + guest.on("will-redirect", guard) + guest.on("will-prevent-unload", event => { + if (!live()) { event.preventDefault(); return } + const l = nativeMenuLabels(owner) + const response = dialog.showMessageBoxSync(BrowserWindow.fromWebContents(guest) ?? owner, { + type: "question", title: origin, + message: l.browserPermission.replace("{permission}", "navigation").replace("{origin}", origin), + buttons: [l.browserDeny, l.browserAllow], defaultId: 0, cancelId: 0, noLink: true, + }) + if (response === 1) event.preventDefault() + }) + guest.setWindowOpenHandler(({ url }) => { + if (!live() || !isBrowserSiteUrlAllowed(url, origin)) return { action: "deny" } + const document = browserGuestLifetime.revision(guest) + return { action: "allow", outlivesOpener: false, createWindow: options => { + if (!live() || browserGuestLifetime.revision(guest) !== document) throw new Error("Expired preview opener") + const popup = new BrowserWindow({ ...options, parent: owner, width: 520, height: 680, + frame: true, titleBarStyle: "default", autoHideMenuBar: true, + webPreferences: { ...options.webPreferences, preload: undefined, session: guest.session, nodeIntegration: false, nodeIntegrationInWorker: false, + nodeIntegrationInSubFrames: true, contextIsolation: true, sandbox: true, webviewTag: false, + webSecurity: true, allowRunningInsecureContent: false, disableDialogs: false } }) + windows.add(popup) + popup.setMenu(null) + protectBrowserGuest(owner, popup.webContents, origin, guest, popup) + return popup.webContents + } } + }) + guest.on("context-menu", (_event, params) => { + if (!live()) return + const document = browserGuestLifetime.revision(guest) + const current = () => live() && browserGuestLifetime.revision(guest) === document + const l = nativeMenuLabels(owner) + const items: Electron.MenuItemConstructorOptions[] = [] + if (params.isEditable) items.push({ role: "undo", label: l.undo }, { role: "redo", label: l.redo }, + { role: "cut", label: l.cut }, { role: "copy", label: l.copy }, { role: "paste", label: l.paste }, + { role: "selectAll", label: l.selectAll }) + else if (params.selectionText) items.push({ label: l.copy, click: () => guest.copy() }) + if (params.linkURL) items.push({ label: l.browserCopyLink, click: () => { if (current()) clipboard.writeText(params.linkURL) } }) + if (isBrowserSiteUrlAllowed(params.linkURL, origin)) items.push( + { label: l.browserOpenLink, click: () => { + const frame = params.frame + if (current() && frame && !frame.detached) void frame.executeJavaScript(`window.open(${JSON.stringify(params.linkURL)},'_blank')`, true) + .catch(error => console.warn("[browser-popup] expired frame", error)) + } }) + if (params.mediaType === "image" && isBrowserDownloadUrlAllowed(params.srcURL, origin)) + items.push({ label: l.browserSaveImage, click: () => { if (current()) guest.downloadURL(params.srcURL) } }) + items.push({ label: l.browserInspect, click: () => { if (current()) guest.inspectElement(params.x, params.y) } }) + Menu.buildFromTemplate(items).popup({ window: BrowserWindow.fromWebContents(guest) ?? owner }) + }) +} diff --git a/packages/electron-app/electron/main/browser-permission-policy.test.ts b/packages/electron-app/electron/main/browser-permission-policy.test.ts new file mode 100644 index 0000000000..6bb1ad6b4b --- /dev/null +++ b/packages/electron-app/electron/main/browser-permission-policy.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { browserPermissionDecision, permissionOrigin, permissionResource } from "./browser-permission-policy" + +test("four protected permissions stay denied and unknown kinds fail closed", () => { + for (const permission of ["media", "camera", "microphone", "geolocation", "geolocation-approximate", "notifications"]) + assert.equal(browserPermissionDecision(permission), "deny") + for (const permission of ["unknown", "future-permission", "openExternal"]) assert.equal(browserPermissionDecision(permission), "unknown") + for (const permission of ["clipboard-read", "local-network-access", "local-network", "loopback-network", "fullscreen", "pointerLock", "midi", "local-fonts", "sensors", "screen-wake-lock", "storage-access", "window-management", "payment-handler"]) + assert.equal(browserPermissionDecision(permission), "consent") + for (const permission of ["hid", "usb", "serial"]) assert.equal(browserPermissionDecision(permission), "chooser") + assert.equal(browserPermissionDecision("clipboard-sanitized-write"), "browser") +}) + +test("file grants remain path/access scoped and storage access remains embedder scoped", () => { + const file = { filePath: "/tmp/one", fileAccessType: "readable", isDirectory: false } + assert.notEqual(permissionResource("fileSystem", file), permissionResource("fileSystem", { ...file, filePath: "/tmp/two" })) + assert.notEqual(permissionResource("fileSystem", file), permissionResource("fileSystem", { ...file, fileAccessType: "writable" })) + assert.equal(permissionResource("fileSystem", {}), undefined) + assert.notEqual(permissionResource("storage-access", {}, "https://one.example"), permissionResource("storage-access", {}, "https://two.example")) + assert.equal(permissionResource("storage-access", {}), undefined) +}) + +test("permission identity is the requesting HTTP origin, never its embedding page", () => { + assert.equal(permissionOrigin("https://frame.example:8443/path"), "https://frame.example:8443") + for (const raw of ["about:blank", "file:///private", "https://user:pass@example.com", "null", "blob:https://example.com/id"]) + assert.equal(permissionOrigin(raw), undefined) +}) diff --git a/packages/electron-app/electron/main/browser-permission-policy.ts b/packages/electron-app/electron/main/browser-permission-policy.ts new file mode 100644 index 0000000000..b5c859c12d --- /dev/null +++ b/packages/electron-app/electron/main/browser-permission-policy.ts @@ -0,0 +1,37 @@ +export type BrowserPermissionDecision = "deny" | "browser" | "chooser" | "consent" | "unknown" + +const denied = new Set(["media", "camera", "microphone", "geolocation", "geolocation-approximate", "notifications"]) +const consent = new Set([ + "clipboard-read", "deprecated-sync-clipboard-read", "local-network-access", "local-network", "loopback-network", + "fullscreen", "pointerLock", "midi", "midiSysex", "hid", "usb", "serial", "local-fonts", "sensors", + "screen-wake-lock", "system-wake-lock", "persistent-storage", "storage-access", "top-level-storage-access", + "window-management", "payment-handler", "fileSystem", "mediaKeySystem", "speaker-selection", "idle-detection", + "background-fetch", "background-sync", "periodic-background-sync", "display-capture", "keyboardLock", + "automatic-downloads", +]) + +export function browserPermissionDecision(permission: string): BrowserPermissionDecision { + if (denied.has(permission)) return "deny" + if (permission === "clipboard-sanitized-write") return "browser" + if (["hid", "usb", "serial", "display-capture"].includes(permission)) return "chooser" + return consent.has(permission) ? "consent" : "unknown" +} + +export function permissionOrigin(raw: string | undefined): string | undefined { + try { + const url = new URL(raw ?? "") + if ((url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password) return url.origin + } catch {} +} + +export function permissionResource(permission: string, details: unknown, embeddingOrigin?: string): string | undefined { + if (permission === "fileSystem") { + if (!details || typeof details !== "object") return undefined + const value = details as { filePath?: unknown; fileAccessType?: unknown; isDirectory?: unknown } + if (typeof value.filePath !== "string" || !value.filePath || (value.fileAccessType !== "readable" && value.fileAccessType !== "writable") + || typeof value.isDirectory !== "boolean") return undefined + return JSON.stringify([value.filePath, value.fileAccessType, value.isDirectory]) + } + if (permission === "storage-access" || permission === "top-level-storage-access") return permissionOrigin(embeddingOrigin) + return "" +} diff --git a/packages/electron-app/electron/main/browser-prompt-policy.test.ts b/packages/electron-app/electron/main/browser-prompt-policy.test.ts new file mode 100644 index 0000000000..46c5c7aa92 --- /dev/null +++ b/packages/electron-app/electron/main/browser-prompt-policy.test.ts @@ -0,0 +1,70 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { readFileSync } from "node:fs" +import vm from "node:vm" +import { createBrowserPromptHandler, validPromptRequest } from "./browser-prompt-policy" +import type { BrowserWindow, IpcMainEvent, WebContents } from "electron" + +test("preview preload exposes only standard prompt and can send only its dedicated channel", () => { + const page: Record = { prompt: () => { throw Error("unsupported") } } + const calls: unknown[][] = [] + const source = readFileSync(new URL("../preload/browser-prompt.cjs", import.meta.url), "utf8") + vm.runInNewContext(source, { require: (name: string) => { + assert.equal(name, "electron") + return { contextBridge: { + executeInMainWorld: ({ func }: { func: Function }) => vm.runInNewContext(`(${func.toString()})()`, { window: page }), + exposeInMainWorld: (key: string, value: unknown) => { assert.equal(key, "prompt"); page[key] = value }, + }, ipcRenderer: { sendSync: (...args: unknown[]) => { calls.push(args); return "answer" } } } + } }) + assert.deepEqual(Object.keys(page), ["prompt"]) + assert.equal((page.prompt as Function)("message", "default"), "answer") + assert.deepEqual(JSON.parse(JSON.stringify(calls)), [["codenomad:browser-prompt", { message: "message", value: "default" }]]) + for (const key of ["require", "ipcRenderer", "electronAPI", "contextBridge", "send", "invoke"]) assert.equal(page[key], undefined) +}) + +test("main rejects non-preview and foreign frames, accepts only bounded prompt values", async () => { + const frame = { origin: "https://frame.example", detached: false } + const sender = { isDestroyed: () => false, mainFrame: { framesInSubtree: [frame] } } as unknown as WebContents + const owner = { isDestroyed: () => false } as BrowserWindow + let shown = 0 + const handler = createBrowserPromptHandler(contents => contents === sender ? owner : undefined, + async (_owner, origin, message, value) => { shown++; assert.equal(origin, frame.origin); assert.equal(message, "m"); return value }) + const event = (contents: WebContents = sender, source = frame) => ({ sender: contents, senderFrame: source } as unknown as IpcMainEvent) + const foreign = event({} as WebContents); handler(foreign, { message: "m", value: "s" }); assert.equal(foreign.returnValue, null) + const forged = event(sender, { ...frame }); handler(forged, { message: "m", value: "s" }); assert.equal(forged.returnValue, null) + const valid = event(); handler(valid, { message: "m", value: "s" }); await new Promise(resolve => setImmediate(resolve)); + assert.equal(valid.returnValue, "s"); assert.equal(shown, 1) + const next = event() + const immediate = event() + Object.defineProperty(immediate, "returnValue", { set: () => handler(next, { message: "m", value: "next" }) }) + handler(immediate, { message: "m", value: "first" }) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(next.returnValue, "next") + assert.equal(shown, 3) + for (const args of [null, [], { message: "m", value: "s", channel: "other" }, { message: "m", value: "x".repeat(65_537) }]) assert.equal(validPromptRequest(args), false) +}) + +test("late prompt replies are cancelled after document replacement or owner retirement", async () => { + for (const cause of ["document", "owner", "frame"] as const) { + const frame = { origin: "https://frame.example", detached: false } + const sender = { isDestroyed: () => false, mainFrame: { framesInSubtree: [frame] } } as unknown as WebContents + const owner = { isDestroyed: () => false } as BrowserWindow + let live = true, revision = Symbol() + let resolve!: (value: string) => void + let current!: () => boolean + const handler = createBrowserPromptHandler(() => live ? owner : undefined, + (_owner, _origin, _message, _value, source, guard) => { + assert.equal(source, sender); current = guard + return new Promise(answer => { resolve = answer }) + }, () => revision) + const event = { sender, senderFrame: frame } as unknown as IpcMainEvent + handler(event, { message: "m", value: "s" }) + if (cause === "document") revision = Symbol() + if (cause === "owner") live = false + if (cause === "frame") frame.detached = true + assert.equal(current(), false) + resolve("stale-answer") + await new Promise(resolve => setImmediate(resolve)) + assert.equal(event.returnValue, null) + } +}) diff --git a/packages/electron-app/electron/main/browser-prompt-policy.ts b/packages/electron-app/electron/main/browser-prompt-policy.ts new file mode 100644 index 0000000000..7628b30491 --- /dev/null +++ b/packages/electron-app/electron/main/browser-prompt-policy.ts @@ -0,0 +1,31 @@ +import type { BrowserWindow, IpcMainEvent, WebContents } from "electron" + +export function validPromptRequest(value: unknown): value is { message: string; value: string } { + if (!value || typeof value !== "object" || Array.isArray(value)) return false + const args = value as Record + return Object.keys(args).length === 2 && typeof args.message === "string" && args.message.length <= 65_536 + && typeof args.value === "string" && args.value.length <= 65_536 +} + +export function createBrowserPromptHandler(ownerOf: (contents: WebContents) => BrowserWindow | undefined, + show: (owner: BrowserWindow, origin: string, message: string, value: string, source: WebContents, current: () => boolean) => Promise, + revisionOf: (contents: WebContents) => unknown = () => null) { + const pending = new Set() + return (event: IpcMainEvent, args: unknown) => { + const owner = ownerOf(event.sender) + try { + if (!owner || owner.isDestroyed() || event.sender.isDestroyed() || pending.has(event.sender) + || !validPromptRequest(args) || !event.senderFrame || event.senderFrame.detached + || !event.sender.mainFrame.framesInSubtree.includes(event.senderFrame)) { event.returnValue = null; return } + const origin = event.senderFrame.origin + const revision = revisionOf(event.sender) + const current = () => !owner.isDestroyed() && !event.sender.isDestroyed() && ownerOf(event.sender) === owner + && revisionOf(event.sender) === revision && !event.senderFrame?.detached + pending.add(event.sender) + const reply = (value: string | null) => { try { if (!event.sender.isDestroyed()) event.returnValue = current() ? value : null } catch {} } + void show(owner, origin, args.message, args.value, event.sender, current) + .then(result => { pending.delete(event.sender); reply(typeof result === "string" ? result : null) }, + () => { pending.delete(event.sender); reply(null) }) + } catch { pending.delete(event.sender); event.returnValue = null } + } +} diff --git a/packages/electron-app/electron/main/browser-prompt.ts b/packages/electron-app/electron/main/browser-prompt.ts new file mode 100644 index 0000000000..3c047f2835 --- /dev/null +++ b/packages/electron-app/electron/main/browser-prompt.ts @@ -0,0 +1,19 @@ +import { ipcMain, type WebContents, type BrowserWindow, type Session } from "electron" +import { showBrowserDialog } from "./browser-dialog" +import { createBrowserPromptHandler } from "./browser-prompt-policy" +import { browserGuestLifetime } from "./browser-guest-lifetime" + +export const browserPromptChannel = "codenomad:browser-prompt" +const sessions = new WeakSet() +export function configureBrowserPromptSession(target: Session, preload: string): void { + if (sessions.has(target)) return + target.registerPreloadScript({ id: browserPromptChannel, type: "frame", filePath: preload, + matches: ["http://*/*", "https://*/*"], matchOriginAsFallback: true }) + sessions.add(target) +} + +export function installBrowserPrompt(ownerOf: (contents: WebContents) => BrowserWindow | undefined): void { + ipcMain.on(browserPromptChannel, createBrowserPromptHandler(ownerOf, + (owner, origin, message, value, source, current) => showBrowserDialog(owner, origin, message, { text: value }, source, current), + source => browserGuestLifetime.revision(source))) +} diff --git a/packages/electron-app/electron/main/browser-webview-security.test.ts b/packages/electron-app/electron/main/browser-webview-security.test.ts index b973be4d3e..7b2bc16d49 100644 --- a/packages/electron-app/electron/main/browser-webview-security.test.ts +++ b/packages/electron-app/electron/main/browser-webview-security.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import { describe, it } from "node:test" import type { WebPreferences } from "electron" -import { browserPartition, isBrowserUrlAllowed, secureBrowserWebview } from "./browser-webview-security" +import { browserPartition, isBrowserUrlAllowed, isBrowserSiteUrlAllowed, isBrowserDownloadUrlAllowed, secureBrowserWebview } from "./browser-webview-security" describe("browser webview security", () => { it("accepts only credential-free HTTP(S) URLs in the browser partition", () => { @@ -15,10 +15,23 @@ describe("browser webview security", () => { assert.equal(secureBrowserWebview(preferences, { partition: browserPartition("session_1"), src: "https://github.com/" }), true) assert.equal(preferences.preload, undefined) assert.equal(preferences.nodeIntegration, false) + assert.equal(preferences.nodeIntegrationInWorker, false) + assert.equal(preferences.nodeIntegrationInSubFrames, true) assert.equal(preferences.contextIsolation, true) assert.equal(preferences.sandbox, true) + assert.equal(preferences.webSecurity, true) + assert.equal(preferences.allowRunningInsecureContent, false) assert.equal(secureBrowserWebview({}, { partition: "persist:other", src: "https://github.com/" }), false) assert.equal(secureBrowserWebview({}, { partition: "persist:codenomad-browser-../other", src: "https://github.com/" }), false) assert.notEqual(browserPartition("session_1"), browserPartition("session_2")) }) + it("allows blank OAuth windows and only same-origin blob documents without weakening typed URLs", () => { + assert.equal(isBrowserSiteUrlAllowed("about:blank", "https://example.com/"), true) + assert.equal(isBrowserSiteUrlAllowed("blob:https://example.com/id", "https://example.com/"), true) + assert.equal(isBrowserSiteUrlAllowed("blob:https://other.example/id", "https://example.com/"), false) + assert.equal(isBrowserSiteUrlAllowed("file:///private", "https://example.com/"), false) + assert.equal(isBrowserUrlAllowed("about:blank"), false) + assert.equal(isBrowserDownloadUrlAllowed("data:image/png;base64,AA", "https://example.com/"), true) + assert.equal(isBrowserDownloadUrlAllowed("file:///private", "https://example.com/"), false) + }) }) diff --git a/packages/electron-app/electron/main/browser-webview-security.ts b/packages/electron-app/electron/main/browser-webview-security.ts index 8830df7913..e203e2dd8a 100644 --- a/packages/electron-app/electron/main/browser-webview-security.ts +++ b/packages/electron-app/electron/main/browser-webview-security.ts @@ -16,15 +16,36 @@ export function isBrowserUrlAllowed(rawUrl: string): boolean { } } +export function isBrowserSiteUrlAllowed(rawUrl: string, openerUrl: string): boolean { + if (isBrowserUrlAllowed(rawUrl) || /^about:blank(?:[?#]|$)/.test(rawUrl)) return true + try { + const url = new URL(rawUrl) + return url.protocol === "blob:" && isBrowserUrlAllowed(openerUrl) && url.origin === new URL(openerUrl).origin + } catch { return false } +} + +export function isBrowserDownloadUrlAllowed(rawUrl: string, openerUrl: string): boolean { + try { + const url = new URL(rawUrl) + return url.protocol === "data:" || (url.protocol !== "about:" && isBrowserSiteUrlAllowed(rawUrl, openerUrl)) + } catch { return false } +} + export function secureBrowserWebview(webPreferences: WebPreferences, params: Record): boolean { if (!params.partition.startsWith(browserPartitionPrefix) || !/^[A-Za-z0-9_-]{1,256}$/.test(params.partition.slice(browserPartitionPrefix.length)) || !isBrowserUrlAllowed(params.src)) return false delete webPreferences.preload webPreferences.nodeIntegration = false + webPreferences.nodeIntegrationInWorker = false + // Electron gates frame preloads behind this flag, even with sandbox enabled. + // The separate preview session has only the prompt preload; page Node stays off. + webPreferences.nodeIntegrationInSubFrames = true + webPreferences.webviewTag = false webPreferences.contextIsolation = true webPreferences.sandbox = true webPreferences.webSecurity = true webPreferences.allowRunningInsecureContent = false + webPreferences.disableDialogs = false return true } diff --git a/packages/electron-app/electron/main/client-state-cross-host-child.ts b/packages/electron-app/electron/main/client-state-cross-host-child.ts index 079032bb40..d752184db5 100644 --- a/packages/electron-app/electron/main/client-state-cross-host-child.ts +++ b/packages/electron-app/electron/main/client-state-cross-host-child.ts @@ -3,6 +3,7 @@ import { CrossHostRegistration, createCrossHostOwner } from "./client-state-cros import { getProcessStartIdentity } from "./client-state-process-identity" import { isPidAlive } from "./client-state-process" import { ClientStateManager } from "./client-state" +import { spawnSync } from "node:child_process" const [directory, startPath, readyPath, mode, userDataPath, participantReadyPath, participantContinuePath, legacyTauriDataPath, operation, payload] = process.argv.slice(2) if (!directory || !startPath) throw new Error("Expected election directory and start path") @@ -36,8 +37,14 @@ if (manager?.isPrimary && operation === "save") { await manager.setRestoreEnabled(true) await manager.saveClientState(JSON.parse(payload)) } +const acquired = manager?.isPrimary ?? Boolean(registration?.isPrimary) +const identityProbe = !acquired && !owner?.processStartIdentity && process.platform === "win32" + ? spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${process.pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`], + { encoding: "utf8", windowsHide: true, timeout: 10000 }) : undefined process.stdout.write(`${JSON.stringify({ - acquired: manager?.isPrimary ?? Boolean(registration?.isPrimary), + acquired, + diagnostics: identityProbe && { status: identityProbe.status, error: identityProbe.error?.message, + stdout: identityProbe.stdout?.slice(0, 1000), stderr: identityProbe.stderr?.slice(0, 1000) }, state: operation === "load" ? manager?.loadClientState() : undefined, })}\n`) process.stdin.resume() diff --git a/packages/electron-app/electron/main/main.ts b/packages/electron-app/electron/main/main.ts index a081d5dc20..a541def21e 100644 --- a/packages/electron-app/electron/main/main.ts +++ b/packages/electron-app/electron/main/main.ts @@ -10,6 +10,9 @@ import { fileURLToPath, pathToFileURL } from "node:url" import { appendNodeOption, DeveloperMode } from "./developer-mode" import { BrowserController, handleNativeBrowserRequest } from "./browser-controller" import { isBrowserUrlAllowed, secureBrowserWebview } from "./browser-webview-security" +import { protectBrowserGuest, isBrowserAuxiliaryWindow, configureBrowserGuests } from "./browser-guests" +import { configureBrowserDownloads } from "./browser-downloads" +import { configureBrowserPromptSession } from "./browser-prompt" import { ClientStateManager } from "./client-state" import { setupClientStateIPC } from "./client-state-ipc" import { ClientStateNavigationController } from "./client-state-navigation" @@ -215,7 +218,7 @@ function runPrimary(firstIntent: LaunchIntent) { lifecycle = new MultiwindowLifecycle({ app, clientStateManager: clientState, cliManager: cli, getLocalWindows: () => registry.all(), getAllWindows: () => BrowserWindow.getAllWindows(), - isSupportWindow: (window) => preferencesWindows.current() === window, + isSupportWindow: (window) => preferencesWindows.current() === window || isBrowserAuxiliaryWindow(window), isLaunchWindow: (window) => launchWindows.has(window), flushSupportWindows: async () => { const window = preferencesWindows.current() @@ -290,6 +293,7 @@ function runPrimary(firstIntent: LaunchIntent) { (error) => console.error("[cli] bootstrap token exchange failed", error), ) + configureBrowserGuests() const createWindow = (windowId: string, persisted = true, connectOnly = false): LocalWindowRecord => { const saved = persisted ? clientState.getWindowState(windowId) : undefined const minimum = zoomedWindowMinimum(saved?.zoomFactor ?? 1) @@ -333,27 +337,16 @@ function runPrimary(firstIntent: LaunchIntent) { return } const browserSession = session.fromPartition(params.partition) + configureBrowserPromptSession(browserSession, join(mainDirname, "../preload/browser-prompt.js")) if (!securedBrowserSessions.has(browserSession)) { securedBrowserSessions.add(browserSession) configureBrowserPermissionHandlers(browserSession) - browserSession.on("will-download", (downloadEvent) => downloadEvent.preventDefault()) + configureBrowserDownloads(browserSession, app.getPath("downloads")) } }) window.webContents.on("did-attach-webview", (_event, guest) => { browserController.observeGuest(window.webContents, guest) - const guardNavigation = (event: Electron.Event, url: string) => { - if (!isBrowserUrlAllowed(url)) event.preventDefault() - } - guest.on("will-navigate", guardNavigation) - guest.on("will-redirect", guardNavigation) - guest.setWindowOpenHandler(({ url }) => { - if (isBrowserUrlAllowed(url)) queueMicrotask(() => { - try { - if (!guest.isDestroyed()) void guest.loadURL(url).catch(() => undefined) - } catch {} - }) - return { action: "deny" } - }) + protectBrowserGuest(window, guest) }) window.webContents.on("did-start-navigation", (_event, _url, _isInPlace, isMainFrame) => { if (isMainFrame) setWorkspaceMenuEnabled(window, false) diff --git a/packages/electron-app/electron/main/menu.ts b/packages/electron-app/electron/main/menu.ts index c5898a9bc4..53c5ec108f 100644 --- a/packages/electron-app/electron/main/menu.ts +++ b/packages/electron-app/electron/main/menu.ts @@ -1,4 +1,5 @@ -import { app, BrowserWindow, Menu, shell, dialog, type MenuItemConstructorOptions } from "electron" +import { app, BrowserWindow, Menu, shell, dialog, webContents, type MenuItemConstructorOptions } from "electron" +import { browserGuestOwner, focusedBrowserGuest } from "./browser-guests" import { NEW_WINDOW_ACCELERATOR } from "./menu-target" import { setWindowZoomLevel } from "./window-state" import { nativeMenuLabels, setViewMenuState, updateViewMenu, viewMenuItems } from "./view-menu" @@ -23,7 +24,8 @@ let builtLabels: string | undefined export type TitlebarMenu = "file" | "edit" | "view" | "window" | "help" function target(local: boolean): BrowserWindow | null { - const window = (local ? actions?.getLocalTarget() : actions?.getWindowTarget()) ?? null + const window = (!local ? browserGuestOwner(webContents.getFocusedWebContents()) : undefined) + ?? (local ? actions?.getLocalTarget() : actions?.getWindowTarget()) ?? null return window && !window.isDestroyed() ? window : null } @@ -91,6 +93,13 @@ function buildApplicationMenu() { const window = target(false) if (window) operation(window) } + const withGuest = (guestAction: (guest: Electron.WebContents) => void, appAction: (window: BrowserWindow) => void) => withTarget(window => { + const guest = focusedBrowserGuest(window, webContents.getFocusedWebContents()) + if (guest) guestAction(guest) + else appAction(window) + }) + const zoom = (change: number | null) => withGuest(guest => guest.setZoomLevel(change === null ? 0 : guest.getZoomLevel() + change), + window => setWindowZoomLevel(window, change === null ? 0 : window.webContents.getZoomLevel() + change)) const template: MenuItemConstructorOptions[] = [ ...(isMac ? [{ label: "CodeNomad", submenu: [ @@ -122,13 +131,13 @@ function buildApplicationMenu() { { id: "menu-view", label: l.view, submenu: [ ...viewMenuItems(sendCommand, target(true)), { type: "separator" }, - { label: l.reload, accelerator: "CmdOrCtrl+R", click: withTarget((window) => actions?.reload(window)) }, - { label: l.forceReload, accelerator: "CmdOrCtrl+Shift+R", click: withTarget((window) => actions?.forceReload(window)) }, - { label: l.devTools, accelerator: isMac ? "Alt+Command+I" : "Ctrl+Shift+I", click: withTarget((window) => window.webContents.toggleDevTools()) }, + { label: l.reload, accelerator: "CmdOrCtrl+R", click: withGuest(guest => guest.reload(), window => actions?.reload(window)) }, + { label: l.forceReload, accelerator: "CmdOrCtrl+Shift+R", click: withGuest(guest => guest.reloadIgnoringCache(), window => actions?.forceReload(window)) }, + { label: l.devTools, accelerator: isMac ? "Alt+Command+I" : "Ctrl+Shift+I", click: withGuest(guest => guest.toggleDevTools(), window => window.webContents.toggleDevTools()) }, { type: "separator" }, - { label: l.actualSize, accelerator: "CmdOrCtrl+0", click: withTarget((window) => setWindowZoomLevel(window, 0)) }, - { label: l.zoomIn, accelerator: "CmdOrCtrl+Plus", click: withTarget((window) => setWindowZoomLevel(window, window.webContents.getZoomLevel() + 0.5)) }, - { label: l.zoomOut, accelerator: "CmdOrCtrl+-", click: withTarget((window) => setWindowZoomLevel(window, window.webContents.getZoomLevel() - 0.5)) }, + { label: l.actualSize, accelerator: "CmdOrCtrl+0", click: zoom(null) }, + { label: l.zoomIn, accelerator: "CmdOrCtrl+Plus", click: zoom(0.5) }, + { label: l.zoomOut, accelerator: "CmdOrCtrl+-", click: zoom(-0.5) }, { type: "separator" }, { label: l.fullScreen, accelerator: isMac ? "Ctrl+Command+F" : "F11", click: withTarget((window) => window.setFullScreen(!window.isFullScreen())) }, ] }, diff --git a/packages/electron-app/electron/main/permissions.ts b/packages/electron-app/electron/main/permissions.ts index 4fae3e0596..602117285d 100644 --- a/packages/electron-app/electron/main/permissions.ts +++ b/packages/electron-app/electron/main/permissions.ts @@ -1,5 +1,10 @@ -import { session, systemPreferences, type Session } from "electron" +import { dialog, session, systemPreferences, type Session } from "electron" import { isAllowedRendererOrigin } from "./renderer-origin" +import { browserPermissionDecision, permissionOrigin, permissionResource } from "./browser-permission-policy" +import { nativeMenuLabels } from "./view-menu" +import { configureBrowserDeviceChoosers } from "./browser-device-chooser" +import { configureBrowserDisplayChooser } from "./browser-display-chooser" +import { browserGuestLifetime } from "./browser-guest-lifetime" export { isAllowedRendererOrigin } from "./renderer-origin" @@ -35,9 +40,70 @@ export function configureMediaPermissionHandlers(getAllowedOrigins: () => string } export function configureBrowserPermissionHandlers(targetSession: Session) { - targetSession.setPermissionCheckHandler(() => false) - targetSession.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false)) - targetSession.setDevicePermissionHandler(() => false) + const grants = new Set() + const pending = new Map>() + const unknown = new Set() + const key = (origin: string, permission: string, resource = "") => JSON.stringify([origin, permission, resource]) + targetSession.setPermissionCheckHandler((_webContents, permission, requestingOrigin, details) => { + if (!_webContents || !browserGuestLifetime.live(_webContents)) return false + const origin = permissionOrigin(details.securityOrigin ?? requestingOrigin) + if (!origin) return false + const decision = browserPermissionDecision(permission) + if (decision !== "consent") return decision === "browser" || decision === "chooser" + let embeddingOrigin = details.embeddingOrigin + try { embeddingOrigin ??= _webContents?.mainFrame.origin } catch {} + const resource = permissionResource(permission, details, embeddingOrigin) + return resource !== undefined && grants.has(key(origin, permission, resource)) + }) + targetSession.setPermissionRequestHandler((contents, permission, callback, details) => { + const revision = browserGuestLifetime.revision(contents) + const owner = browserGuestLifetime.owner(contents) + const live = () => Boolean(owner && browserGuestLifetime.owner(contents) === owner && browserGuestLifetime.revision(contents) === revision) + const decision = browserPermissionDecision(permission) + if (decision === "deny" || !live()) { callback(false); return } + const frameOrigins = new Set(contents.mainFrame.framesInSubtree + .filter(frame => frame.url === details.requestingUrl && (!details.isMainFrame || frame === contents.mainFrame)) + .map(frame => permissionOrigin(frame.origin)).filter((origin): origin is string => Boolean(origin))) + const origin = permissionOrigin(details.requestingUrl) ?? (frameOrigins.size === 1 ? [...frameOrigins][0] : undefined) + const resource = permissionResource(permission, details, contents.mainFrame.origin) + const labels = nativeMenuLabels(owner ?? null) + const requestKey = key(origin ?? "null", permission, resource) + if (decision === "unknown" || !origin || resource === undefined) { + callback(false) + if (!unknown.has(requestKey)) { + unknown.add(requestKey) + const options = { type: "warning" as const, title: origin ?? "null", message: labels.browserPermissionUnknown.replace("{permission}", permission) } + void (owner ? dialog.showMessageBox(owner, options) : dialog.showMessageBox(options)) + .catch(error => console.warn("[browser-permission] closed owner", error)) + } + return + } + if (decision === "browser" || decision === "chooser") { callback(true); return } + if (grants.has(requestKey)) { callback(true); return } + let request = pending.get(requestKey) + if (!request) { + const options = { type: "question" as const, title: origin, + message: labels.browserPermission.replace("{permission}", permission).replace("{origin}", origin), + ...("filePath" in details && typeof details.filePath === "string" ? { detail: details.filePath } : {}), + buttons: [labels.browserDeny, labels.browserAllow], defaultId: 0, cancelId: 0, noLink: true } + request = (owner ? dialog.showMessageBox(owner, options) : dialog.showMessageBox(options)) + .then(result => { + if (result.response !== 1 || !live()) return false + grants.add(requestKey) + return true + }, () => false).finally(() => pending.delete(requestKey)) + pending.set(requestKey, request) + } + void request.then(allowed => { + let current = false + try { current = allowed && live() + && contents.mainFrame.framesInSubtree.some(frame => permissionOrigin(frame.origin) === origin) } catch {} + callback(current) + }).catch(error => console.warn("[browser-permission] expired request", error)) + }) + // Device grants require a chooser selection, not just a general API consent. + configureBrowserDeviceChoosers(targetSession) + configureBrowserDisplayChooser(targetSession) } export async function requestMicrophoneAccess(): Promise { diff --git a/packages/electron-app/electron/preload/browser-prompt.cjs b/packages/electron-app/electron/preload/browser-prompt.cjs new file mode 100644 index 0000000000..c891d5329f --- /dev/null +++ b/packages/electron-app/electron/preload/browser-prompt.cjs @@ -0,0 +1,12 @@ +const { contextBridge, ipcRenderer } = require("electron") + +// Replace only the standard Web API. No bridge object, IPC method or Node value +// crosses into the page, and the channel is fixed inside this isolated closure. +contextBridge.executeInMainWorld({ func: () => { delete window.prompt } }) +contextBridge.exposeInMainWorld("prompt", (message, value) => { + const result = ipcRenderer.sendSync("codenomad:browser-prompt", { + message: message === undefined ? "" : String(message), + value: value === undefined ? "" : String(value), + }) + return typeof result === "string" ? result : null +}) diff --git a/packages/electron-app/package.json b/packages/electron-app/package.json index 5d3b0aeaf4..1ab7cd0f88 100644 --- a/packages/electron-app/package.json +++ b/packages/electron-app/package.json @@ -25,6 +25,7 @@ "prebuild": "npm run prepare:resources", "build": "electron-vite build", "typecheck": "tsc --noEmit -p tsconfig.json", + "pretest:native": "node --import tsx --test electron/main/browser-permission-policy.test.ts electron/main/browser-downloads.test.ts electron/main/browser-prompt-policy.test.ts", "test:native": "node --import tsx --test electron/main/backend-runtime.test.ts electron/main/browser-controller.test.ts electron/main/browser-webview-security.test.ts electron/main/client-state-cross-host.test.ts electron/main/client-state-process.test.ts electron/main/client-state.test.ts electron/main/client-state-ipc.test.ts electron/main/client-state-navigation.test.ts electron/main/connect-launch.test.ts electron/main/data-profile.test.ts electron/main/data-profile-cleanup.test.ts electron/main/data-profile-cleanup-ipc.test.ts electron/main/developer-mode.test.ts electron/main/dialog-ipc.test.ts electron/main/local-window-registry.test.ts electron/main/menu-target.test.ts electron/main/multiwindow-lifecycle.test.ts electron/main/native-request.test.ts electron/main/native-service-start.test.ts electron/main/navigation-security.test.ts electron/main/notification-badge.test.ts electron/main/opener-startup-state.test.ts electron/main/preferences-ipc.test.ts electron/main/preferences-window.test.ts electron/main/process-exit.test.ts electron/main/profile-transition.test.ts electron/main/process-output.test.ts electron/main/process-stop.test.ts electron/main/windows-process-worker.test.ts electron/main/remote-recovery.test.ts electron/main/remote-window-registry.test.ts electron/main/renderer-client-state-flush.test.ts electron/main/renderer-origin.test.ts electron/main/serialized-lifecycle.test.ts electron/main/startup.test.ts electron/main/user-shell.test.ts electron/main/window-state.test.ts electron/main/workspace-open.test.ts electron/preload/index.test.ts", "preview": "install-electron && electron-vite preview", "build:binaries": "node scripts/build.js", diff --git a/packages/electron-app/tests/browser-capabilities/beforeunload-acceptance.ts b/packages/electron-app/tests/browser-capabilities/beforeunload-acceptance.ts new file mode 100644 index 0000000000..c4c22389ee --- /dev/null +++ b/packages/electron-app/tests/browser-capabilities/beforeunload-acceptance.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict" +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { mkdir, writeFile } from "node:fs/promises" +import { resolve } from "node:path" +import { app, BrowserWindow, type WebContents } from "electron" +import { isBrowserDialog } from "../../electron/main/browser-dialog" + +const exec = promisify(execFile) +const pause = () => new Promise(resolve => setTimeout(resolve, 30)) + +/** Real production guest hooks and native dialogs, on the fixture's own X display. */ +export async function qualifyBeforeUnload(owner: BrowserWindow, root: WebContents): Promise { + const driver = process.env.CODENOMAD_FIXTURE_DIALOG_DRIVER + assert.ok(driver, "Set CODENOMAD_FIXTURE_DIALOG_DRIVER to linux-answer-beforeunload.sh") + const evidence = resolve(process.env.CODENOMAD_FIXTURE_EVIDENCE ?? `.tmp/beforeunload-${process.pid}`) + await mkdir(evidence, { recursive: true }) + const timeout = setTimeout(() => { console.error("beforeunload acceptance timed out"); app.exit(1) }, 90_000) + const capture = async (guest: WebContents, name: string) => writeFile(resolve(evidence, `${name}.png`), (await guest.capturePage()).toPNG()) + const fresh = async (guest: WebContents) => { + const end = Date.now() + 5000 + while (Date.now() < end) { + if (!guest.isLoading() && await guest.executeJavaScript("document.readyState==='complete' && !document.body.dataset.retained")) return + await pause() + } + assert.fail("Leave did not replace the document") + } + const arm = async (guest: WebContents) => { + guest.focus() + await guest.capturePage() + await pause() + guest.sendInputEvent({ type: "mouseDown", x: 4, y: 4, button: "left", clickCount: 1 }) + guest.sendInputEvent({ type: "mouseUp", x: 4, y: 4, button: "left", clickCount: 1 }) + await pause() + assert.equal(await guest.executeJavaScript("navigator.userActivation.hasBeenActive"), true) + await guest.executeJavaScript("document.body.dataset.retained='yes'; window.onbeforeunload=e=>{e.preventDefault(); e.returnValue='unsaved'; return 'unsaved'}; void 0") + } + const decide = async (guest: WebContents, name: string, answer: "stay" | "leave", action: () => void) => { + const prevented = new Promise((resolve, reject) => guest.once("will-prevent-unload", event => { + try { assert.equal(event.defaultPrevented, answer === "leave"); resolve() } + catch (error) { reject(error) } + })) + const input = exec("bash", [driver, answer, String(process.pid), resolve(evidence, `${name}-confirm.png`)], { timeout: 13_000, windowsHide: true }) + action() + await Promise.all([prevented, input]) + if (answer === "stay") { + assert.equal(guest.isDestroyed(), false) + assert.equal(await guest.executeJavaScript("document.body.dataset.retained"), "yes") + await capture(guest, name) + } + } + try { + await arm(root) + await decide(root, "navigation-stay", "stay", () => { void root.loadURL("http://127.0.0.1:18741/next").catch(() => {}) }) + await decide(root, "navigation-leave", "leave", () => { void root.loadURL("http://127.0.0.1:18741/next").catch(() => {}) }) + await fresh(root) + assert.equal(new URL(root.getURL()).pathname, "/next") + await capture(root, "navigation-leave") + await arm(root) + await decide(root, "reload-stay", "stay", () => root.reload()) + await decide(root, "reload-leave", "leave", () => root.reload()) + await fresh(root) + await capture(root, "reload-leave") + await root.executeJavaScript("window.open('/close-test'); void 0", true) + const popup = BrowserWindow.getAllWindows().find(window => window !== owner && !isBrowserDialog(window))! + assert.ok(popup) + while (popup.webContents.isLoading()) await pause() + await popup.webContents.executeJavaScript("window.close=()=>{};void 0") + await arm(popup.webContents) + await decide(popup.webContents, "popup-close-stay", "stay", () => popup.close()) + const closed = new Promise(resolve => popup.once("closed", () => resolve())) + await decide(popup.webContents, "popup-close-leave", "leave", () => popup.close()) + await closed + assert.equal(popup.isDestroyed(), true) + console.log(`PASS native Electron beforeunload navigation/reload/popup-close Stay/Leave; evidence=${evidence}`) + app.exit(0) + } catch (error) { console.error(error); app.exit(1) } + finally { clearTimeout(timeout) } +} diff --git a/packages/electron-app/tests/browser-capabilities/fixture.ts b/packages/electron-app/tests/browser-capabilities/fixture.ts new file mode 100644 index 0000000000..0490d3c190 --- /dev/null +++ b/packages/electron-app/tests/browser-capabilities/fixture.ts @@ -0,0 +1,44 @@ +import { app, BrowserWindow, session } from "electron" +import { secureBrowserWebview } from "../../electron/main/browser-webview-security" +import { configureBrowserPermissionHandlers } from "../../electron/main/permissions" +import { configureBrowserDownloads } from "../../electron/main/browser-downloads" +import { protectBrowserGuest, configureBrowserGuests } from "../../electron/main/browser-guests" +import { configureBrowserPromptSession } from "../../electron/main/browser-prompt" +import { qualifyPrompt } from "./prompt-acceptance" +import { qualifyBeforeUnload } from "./beforeunload-acceptance" +import { qualifyLifetime } from "./lifetime-acceptance" + +if (!process.env.CODENOMAD_PROFILE) throw new Error("Set an isolated CODENOMAD_PROFILE directory") +app.setPath("userData", process.env.CODENOMAD_PROFILE) +void app.whenReady().then(async () => { +const partition = "persist:codenomad-browser-capabilities" +const store = session.fromPartition(partition) +configureBrowserGuests() +configureBrowserPromptSession(store, process.env.CODENOMAD_FIXTURE_PROMPT_PRELOAD!) +configureBrowserPermissionHandlers(store) +configureBrowserDownloads(store, app.getPath("downloads")) +const owner = new BrowserWindow({ width: 920, height: 820, + webPreferences: { webviewTag: true, nodeIntegration: false, contextIsolation: true, sandbox: true } }) +owner.webContents.on("will-attach-webview", (event, preferences, params) => { + if (!secureBrowserWebview(preferences, params)) event.preventDefault() +}) +owner.webContents.on("did-attach-webview", (_event, guest) => { + protectBrowserGuest(owner, guest) + if (process.env.CODENOMAD_FIXTURE_PROMPT_TEST) guest.once("did-finish-load", () => { void qualifyPrompt(owner, guest) }) + else if (process.env.CODENOMAD_FIXTURE_BEFOREUNLOAD_TEST) guest.once("did-finish-load", () => { void qualifyBeforeUnload(owner, guest) }) + else if (process.env.CODENOMAD_FIXTURE_LIFETIME) guest.once("did-finish-load", () => { void qualifyLifetime(owner, guest) }) + guest.on("console-message", details => console.log("guest", details.message)) + if (process.env.CODENOMAD_FIXTURE_NETWORK) guest.once("did-finish-load", () => { + void guest.loadURL("https://example.com").then(() => guest.executeJavaScript(` + document.body.innerHTML=''; + document.getElementById('network').onclick=()=>fetch('http://127.0.0.1:18741/').then(r=>r.text()).then(v=>console.log('network-result',v.length),e=>console.log('network-error',e.name)); + void 0; + `)) + }) + if (process.env.CODENOMAD_FIXTURE_CLOSE_AFTER) setTimeout(() => guest.close({ waitForBeforeUnload: false }), + Number(process.env.CODENOMAD_FIXTURE_CLOSE_AFTER) * 1000) +}) +const path = process.env.CODENOMAD_FIXTURE_CONTROLS ? "controls" : "" +await owner.loadURL(`data:text/html,${encodeURIComponent(``)}`) +}) +app.on("window-all-closed", () => app.quit()) diff --git a/packages/electron-app/tests/browser-capabilities/lifetime-acceptance.ts b/packages/electron-app/tests/browser-capabilities/lifetime-acceptance.ts new file mode 100644 index 0000000000..84c61deaea --- /dev/null +++ b/packages/electron-app/tests/browser-capabilities/lifetime-acceptance.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict" +import { writeFile } from "node:fs/promises" +import { app, BrowserWindow, type WebContents } from "electron" +import { browserGuestLifetime } from "../../electron/main/browser-guest-lifetime" + +export async function qualifyLifetime(owner: BrowserWindow, guest: WebContents): Promise { + const mode = process.env.CODENOMAD_FIXTURE_LIFETIME! + const pause = () => new Promise(resolve => setTimeout(resolve, 50)) + const wait = async (condition: () => boolean) => { + for (let i = 0; i < 200; i++) { if (condition()) return; await pause() } + assert.fail("native lifetime condition timed out") + } + // Keep the process alive so owner destruction can be asserted before app.exit. + const sentinel = new BrowserWindow({ show: false }) + try { + await guest.executeJavaScript("window.onbeforeunload=()=>true;window.open('/lifetime-child');void 0", true) + await wait(() => BrowserWindow.getAllWindows().length === 3) + const child = BrowserWindow.getAllWindows().find(window => window !== owner && window !== sentinel)! + await wait(() => !child.webContents.isLoading()) + await child.webContents.executeJavaScript("window.onbeforeunload=()=>true;window.open('/hold');void 0", true) + await wait(() => BrowserWindow.getAllWindows().length === 4) + const descendants = BrowserWindow.getAllWindows().filter(window => window !== owner && window !== sentinel) + const contents = descendants.map(window => window.webContents) + if (mode === "opener-close") guest.close({ waitForBeforeUnload: false }) + else if (mode === "opener-reload") { await guest.executeJavaScript("window.onbeforeunload=null;void 0"); guest.reload() } + else if (mode === "owner-destroy") owner.destroy() + else if (mode === "owner-close") owner.close() + else if (mode === "renderer-reload") owner.reload() + else assert.fail(`Unknown lifetime mode ${mode}`) + await wait(() => descendants.every(window => window.isDestroyed())) + for (const source of contents) assert.equal(browserGuestLifetime.owner(source), undefined) + if (mode !== "opener-reload") assert.equal(browserGuestLifetime.owner(guest), undefined) + await writeFile(`${process.env.CODENOMAD_PROFILE}/lifetime-${mode}.txt`, `PASS ${mode}: two native descendants destroyed; registries empty; armed child beforeunload bypassed\n`) + app.exit(0) + } catch (error) { console.error(error); app.exit(1) } +} diff --git a/packages/electron-app/tests/browser-capabilities/prompt-acceptance.ts b/packages/electron-app/tests/browser-capabilities/prompt-acceptance.ts new file mode 100644 index 0000000000..e8ca6c325f --- /dev/null +++ b/packages/electron-app/tests/browser-capabilities/prompt-acceptance.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict" +import { app, BrowserWindow, type WebContents } from "electron" +import { isBrowserDialog, showBrowserDialog } from "../../electron/main/browser-dialog" + +/** Run inside the real-engine fixture with CODENOMAD_FIXTURE_PROMPT_TEST=1. */ +export async function qualifyPrompt(owner: BrowserWindow, guest: WebContents): Promise { + const answer = async (expression: string, value: string | null, target: Pick = guest) => { + let handled = false + const timer = setInterval(() => { + const dialog = BrowserWindow.getAllWindows().find(isBrowserDialog) + if (handled || !dialog || dialog.webContents.isLoading()) return + handled = true + void dialog.webContents.executeJavaScript(`(() => { + const field = document.querySelector('input'); + if (field) field.value = ${JSON.stringify(value ?? "")}; + document.querySelector('button[value="${value === null ? "cancel" : "accept"}"]').click(); + })()`) + }, 30) + try { return await target.executeJavaScript(expression, true) } + finally { clearInterval(timer) } + } + const timeout = setTimeout(() => { console.error("prompt acceptance timed out"); app.exit(1) }, 20_000) + try { + assert.deepEqual(await guest.executeJavaScript(`[ + typeof require, typeof ipcRenderer, typeof electronAPI, typeof contextBridge, + prompt.constructor('return typeof require')(), typeof process + ]`), Array(6).fill("undefined")) + assert.equal(await owner.webContents.executeJavaScript("typeof require + '/' + typeof electronAPI"), "undefined/undefined") + assert.equal(await answer("prompt('root', 'default')", "root-answer"), "root-answer") + assert.equal(await answer("prompt('cancel')", null), null) + assert.equal(await answer("prompt('empty')", ""), "") + await guest.executeJavaScript("new Promise(resolve => { const f = document.createElement('iframe'); f.srcdoc = 'frame'; f.onload = () => resolve(); document.body.append(f) })") + assert.equal(await answer("document.querySelector('iframe').contentWindow.prompt('subframe')", "frame-answer"), "frame-answer") + assert.deepEqual(await guest.executeJavaScript("['require','process','ipcRenderer','electronAPI','contextBridge'].map(k=>typeof document.querySelector('iframe').contentWindow[k])"), Array(5).fill("undefined")) + assert.equal(guest.getLastWebPreferences().sandbox, true) + assert.equal(guest.getLastWebPreferences().nodeIntegration, false) + await guest.executeJavaScript("new Promise(resolve => { const f=document.createElement('iframe'); f.src='http://localhost:18741/hold'; f.onload=()=>resolve(); document.body.append(f) })") + const crossOrigin = guest.mainFrame.framesInSubtree.find(frame => frame.url === "http://localhost:18741/hold")! + assert.ok(crossOrigin) + assert.equal(await answer("prompt('cross-origin frame')", "cross-frame-answer", crossOrigin), "cross-frame-answer") + assert.deepEqual(await crossOrigin.executeJavaScript("[typeof require,typeof process,typeof ipcRenderer,typeof electronAPI]"), Array(4).fill("undefined")) + await guest.executeJavaScript("window.open('about:blank', 'prompt-test'); void 0", true) + const popup = BrowserWindow.getAllWindows().find(window => window !== owner && !isBrowserDialog(window))! + assert.ok(popup) + assert.equal(await answer("prompt('blank popup')", "popup-answer", popup.webContents), "popup-answer") + popup.destroy() + let selected = false + const choose = setInterval(() => { + const dialog = BrowserWindow.getAllWindows().find(isBrowserDialog) + if (selected || !dialog || dialog.webContents.isLoading()) return + selected = true + void dialog.webContents.executeJavaScript("document.querySelector('select').value='24'; document.querySelector('button[value=accept]').click()") + }, 30) + try { assert.equal(await showBrowserDialog(owner, "https://fixture.invalid", "choose", { choices: Array.from({ length: 25 }, (_, i) => `Device ${i + 1}`) }), "24") } + finally { clearInterval(choose) } + console.log("PASS real-engine prompt: string/cancel/empty/blank-popup/srcdoc/cross-origin subframe; sandbox retained; isolated globals; chooser entry 25") + app.exit(0) + } catch (error) { console.error(error); app.exit(1) } + finally { clearTimeout(timeout) } +} diff --git a/packages/server/package.json b/packages/server/package.json index 73752bd255..612ad8815f 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -37,6 +37,7 @@ "@opencode/client": "2.2.3", "@opencode/schema": "2.2.3", "commander": "^12.1.0", + "dom-accessibility-api": "0.7.1", "effect": "4.0.6", "fastify": "^4.28.1", "fuzzysort": "^2.0.4", diff --git a/packages/server/src/automation/browser-page.test.ts b/packages/server/src/automation/browser-page.test.ts index 0503db8ce1..8c4ecdb1a7 100644 --- a/packages/server/src/automation/browser-page.test.ts +++ b/packages/server/src/automation/browser-page.test.ts @@ -1,12 +1,15 @@ import assert from "node:assert/strict" import { test } from "node:test" import { BrowserPage } from "./browser-page" +import { executeCdpOperation } from "./page/cdp-driver" +import type { PageOperation } from "./page/protocol" class Native { generation = "run/guest/document-1" hidden = false failMethod?: string calls: Array<{ method: string; input: Record }> = [] + protocol: Array<{method: string; params: Record}> = [] gate?: () => Promise leases = new Map() nodes = [{ nodeId: "one", backendDOMNodeId: 42, role: { value: "button" }, name: { value: "Save" } }] @@ -16,15 +19,18 @@ class Native { if (this.hidden) throw new Error("No visible browser") if (method === "browser.page.begin") { this.leases.set(input.operationID, this.generation) - return { generation: this.generation, url: "https://example.test/" } as T + return { generation: this.generation, url: "https://example.test/", driver: "cdp", contractVersion: 1 } as T } if (input.generation !== this.generation || this.leases.get(input.operationID) !== this.generation) throw new Error("Browser document changed") if (method === "browser.page.check") return { url: "https://example.test/" } as T - if (input.method === this.failMethod) throw new Error("Native reply uncertain") - if (input.method === "Accessibility.getFullAXTree") { await this.gate?.(); return { nodes: this.nodes } as T } - if (input.method === "DOM.resolveNode") return { object: { objectId: "object-1" } } as T - if (input.method === "Runtime.callFunctionOn") return { result: { value: null } } as T - return {} as T + return await executeCdpOperation({ send: async (method, params = {}) => { + this.protocol.push({method, params}) + if (method === this.failMethod) throw new Error("Native reply uncertain") + if (method === "Accessibility.getFullAXTree") { await this.gate?.(); return { nodes: this.nodes } } + if (method === "DOM.resolveNode") return { object: { objectId: "object-1" } } + if (method === "Runtime.callFunctionOn") return { result: { value: null } } + return {} + } }, input.operation as PageOperation) as T } } @@ -36,11 +42,14 @@ test("preview operations use the shared outline/actions without a CodeNomad inpu assert.match(String(first.snapshot), /- button "Save" \[b1e1\]/) const ref = firstRef(first.snapshot) assert.deepEqual(await page.execute("session", { action: "click", ref }), { url: "https://example.test/" }) - const functions = native.calls.filter(call => call.input.method === "Runtime.callFunctionOn") + const functions = native.protocol.filter(call => call.method === "Runtime.callFunctionOn") assert.ok(functions.length > 0) - assert.ok(functions.every(call => !String(call.input.params.functionDeclaration).includes("__codenomadAutomation")), + assert.ok(functions.every(call => !String(call.params.functionDeclaration).includes("__codenomadAutomation")), "a user's web page never receives the app's input provenance variables") assert.equal(native.leases.size, 0) + assert.ok(native.calls.filter(call => call.method === "browser.page.send").every(call => + call.input.operation && !Object.hasOwn(call.input, "method") && !Object.hasOwn(call.input, "params") + && !JSON.stringify(call.input).includes("functionDeclaration")), "the private wire carries IDs/JSON operations, never program source") const starts = native.calls.filter(call => call.method === "browser.page.begin") assert.equal(starts.length, 2) assert.notEqual(starts[0].input.operationID, starts[1].input.operationID) @@ -97,7 +106,7 @@ test("a failed native mutation is never replayed, and queue admission is bounded const ref = firstRef((await page.execute("a", { action: "snapshot" })).snapshot) native.failMethod = "Runtime.callFunctionOn" await assert.rejects(page.execute("a", { action: "click", ref }), /reply uncertain/) - assert.equal(native.calls.filter(call => call.input.method === "Runtime.callFunctionOn").length, 1) + assert.equal(native.protocol.filter(call => call.method === "Runtime.callFunctionOn").length, 1) assert.equal(native.leases.size, 0) native.failMethod = undefined let release!: () => void, entered!: () => void @@ -112,3 +121,12 @@ test("a failed native mutation is never replayed, and queue admission is bounded assert.ok((await Promise.all([first, ...pending])).every(result => result instanceof Error)) assert.equal(native.leases.size, 0) }) + +test("a failed native scroll seals its lease and preserves the original failure before any mutation", async () => { + const native = new Native(), page = new BrowserPage(native) + const ref = firstRef((await page.execute("a", { action: "snapshot" })).snapshot) + native.failMethod = "DOM.scrollIntoViewIfNeeded" + await assert.rejects(page.execute("a", { action: "type", ref, text: "unsent", clear: true }), /reply uncertain/) + assert.equal(native.protocol.filter(call => call.method === "Runtime.callFunctionOn").length, 0) + assert.equal(native.leases.size, 0) +}) diff --git a/packages/server/src/automation/browser-page.ts b/packages/server/src/automation/browser-page.ts index 0ec40f24d6..cb4b7ee61a 100644 --- a/packages/server/src/automation/browser-page.ts +++ b/packages/server/src/automation/browser-page.ts @@ -3,6 +3,7 @@ import type { NativeParent } from "../native-parent" import { bindRefs, performAction, snapshotPage, type PageSession } from "./page/actions" import type { RefAction } from "./page/parse" import { RefTable } from "./page/refs" +import { nativeDriver } from "./page/native-driver" export type BrowserPageAction = RefAction | { action: "snapshot"; ref?: string; query?: string } const OPERATION_MS = 25_000 @@ -40,32 +41,35 @@ export class BrowserPage { private async run(sessionID: string, action: BrowserPageAction, signal?: AbortSignal): Promise> { const operationID = randomUUID(), deadline = Date.now() + OPERATION_MS + let failure: Error | undefined const current = () => { + if (failure) throw failure signal?.throwIfAborted() if (this.closed) throw new Error("Browser automation is shutting down") if (Date.now() >= deadline) throw new Error("Browser operation timed out; inspect before another action") } const request = async (method: string, params: Record): Promise => { current() - const result = await this.native.request(method, { sessionID, operationID, ...params }, Math.max(1, deadline - Date.now())) + const result = await this.native.request(method, { sessionID, operationID, ...params }, Math.max(1, deadline - Date.now())).catch(error => { + failure = error instanceof Error ? error : new Error(String(error)) + throw failure + }) current() return result } try { - const target = await request<{ generation: string; url: string }>("browser.page.begin", {}) + const target = await request<{ generation: string; url: string; driver: unknown; contractVersion: unknown }>("browser.page.begin", {}) if (!target || typeof target.generation !== "string" || !target.generation || target.generation.length > 512 || typeof target.url !== "string") throw new Error("Invalid native browser target") const generation = target.generation let url = target.url - const page: PageSession = { - markAutomation: false, - channel: { send: (method, params) => request("browser.page.send", { generation, method, params: params ?? {} }) }, - checkpoint: async () => { + const checkpoint = async () => { const result = await request<{ url: string }>("browser.page.check", { generation }) if (!result || typeof result.url !== "string") throw new Error("Invalid native browser target") url = result.url - }, } + const driver = nativeDriver(target, operation => request("browser.page.send", { generation, operation }), checkpoint) + const page: PageSession = { driver, markAutomation: false, checkpoint } const refs = this.table(sessionID) if (action.action === "snapshot") { const rootBackendNodeId = action.ref ? refs.resolve(action.ref, generation) : undefined diff --git a/packages/server/src/automation/page/actions.ts b/packages/server/src/automation/page/actions.ts index 3197fdd981..c1cf320044 100644 --- a/packages/server/src/automation/page/actions.ts +++ b/packages/server/src/automation/page/actions.ts @@ -1,12 +1,11 @@ import { aim, clickAt, dragBetween, hoverAt, pressKeys, waitForText, wheelAt, type MouseButton } from "./input" -import { callOn, markedInput, OBJECT_GROUP, releaseObjects, resolveElement, VALUE_LIMIT, type PageSession } from "./protocol" +import { callOn, markedInput, releaseObjects, resolveElement, PageDriverUnsupportedError, type PageSession } from "./protocol" +import { snapshotTree } from "./semantic-tree" import type { RefAction } from "./parse" import { renderSnapshot, type AxNode, type Snapshot, type SnapshotOptions } from "./snapshot" - export type { PageChannel, PageSession } from "./protocol" interface Target { ref: string; backendNodeId: number } - export type PageAction = | Target & { kind: "click"; button?: MouseButton } | Target & { kind: "type"; text: string; clear: boolean } @@ -16,20 +15,8 @@ export type PageAction = | { kind: "scroll"; target?: Target; direction: "up" | "down" | "left" | "right"; amount: number } | { kind: "press"; key: string; target?: Target } | { kind: "wait"; text: string; gone: boolean; timeoutMs: number } +export interface PageActionResult { value?: string; selected?: string[]; focused?: string; found?: boolean; waitedMs?: number } -export interface PageActionResult { - /** The field's value after typing; passwords are masked. */ - value?: string - /** The select's chosen option labels. */ - selected?: string[] - /** The element focused after a key press. */ - focused?: string - /** Whether wait found its text, and after how long. */ - found?: boolean - waitedMs?: number -} - -/** Resolves a tool's refs to DOM nodes before any page access; a stale ref fails the whole action. */ export function bindRefs(action: RefAction, resolve: (ref: string) => number): PageAction { const target = (ref: string): Target => ({ ref, backendNodeId: resolve(ref) }) switch (action.action) { @@ -43,20 +30,15 @@ export function bindRefs(action: RefAction, resolve: (ref: string) => number): P case "wait": return { kind: "wait", text: action.text, gone: action.gone, timeoutMs: action.timeout } } } - export async function readAccessibilityTree(session: PageSession): Promise { - const result = await session.channel.send("Accessibility.getFullAXTree") + const nodes = await session.driver.tree() await session.checkpoint() - return Array.isArray(result.nodes) ? result.nodes as AxNode[] : [] + return snapshotTree(nodes) } - -export async function snapshotPage(session: PageSession, issue: () => (backendNodeId: number) => string, - options: SnapshotOptions = {}): Promise { +export async function snapshotPage(session: PageSession, issue: () => (backendNodeId: number) => string, options: SnapshotOptions = {}): Promise { const nodes = await readAccessibilityTree(session) - // Refs are issued only after the tree was confirmed current. return renderSnapshot(nodes, issue(), options) } - export async function performAction(session: PageSession, action: PageAction): Promise { try { switch (action.kind) { @@ -64,7 +46,7 @@ export async function performAction(session: PageSession, action: PageAction): P case "type": return await type(session, action) case "select": { const element = await resolveElement(session, action.ref, action.backendNodeId) - return { selected: (await callOn(session, action.ref, element, SELECT, [action.values]) as unknown[]).map(String) } + return { selected: (await callOn(session, action.ref, element, "select", [action.values]) as unknown[]).map(String) } } case "hover": { const point = await aim(session, action.ref, action.backendNodeId) @@ -73,8 +55,6 @@ export async function performAction(session: PageSession, action: PageAction): P return {} } case "drag": { - // Both ends must already be visible: scrolling to the second target would - // invalidate the first point and could press a different row underneath it. const from = await aim(session, action.ref, action.backendNodeId, { scroll: false }) const to = await aim(session, action.to.ref, action.to.backendNodeId, { scroll: false }) if (!from || !to) throw new Error(`${!from ? action.ref : action.to.ref} has no visible box to drag ${!from ? "from" : "to"}`) @@ -92,167 +72,41 @@ export async function performAction(session: PageSession, action: PageAction): P case "press": { if (action.target) { const element = await resolveElement(session, action.target.ref, action.target.backendNodeId) - await callOn(session, action.target.ref, element, FOCUS, []) + await callOn(session, action.target.ref, element, "focus", []) } await pressKeys(session, action.key) return { focused: await focusedElement(session) } } case "wait": return await waitForText(session, action.text, action.gone, action.timeoutMs) } - } finally { - await releaseObjects(session) - } + } finally { await releaseObjects(session) } } - async function click(session: PageSession, action: Target & { button?: MouseButton }): Promise { const element = await resolveElement(session, action.ref, action.backendNodeId) - const selected = await callOn(session, action.ref, element, OPTION_CLICK, []) + const selected = await callOn(session, action.ref, element, "option-click", []) if (Array.isArray(selected)) return { selected: selected.map(String) } const point = await aim(session, action.ref, action.backendNodeId) - // An element without a visible box (zero-size or offscreen-only) is activated programmatically. if (!point) { if (action.button && action.button !== "left") throw new Error(`${action.ref} has no visible box to ${action.button}-click`) - await callOn(session, action.ref, element, PROGRAMMATIC_CLICK, []) + await callOn(session, action.ref, element, "programmatic-click", []) } else await clickAt(session, point, action.button) return {} } - async function type(session: PageSession, action: Target & { text: string; clear: boolean }): Promise { const element = await resolveElement(session, action.ref, action.backendNodeId) - await session.channel.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: action.backendNodeId }).catch(() => undefined) + await session.driver.scrollIntoView(action.backendNodeId).catch(error => { if (error instanceof PageDriverUnsupportedError) throw error }) await session.checkpoint() - const field = await callOn(session, action.ref, element, FIELD, [], false) as string - const mode = await callOn(session, action.ref, field, PREPARE, [action.clear]) - if (mode === "value" || mode === "append") await callOn(session, action.ref, field, SET_VALUE, [action.text, mode === "append"]) - else if (action.text) await markedInput(session, dispatch => dispatch("Input.insertText", { text: action.text })) - else if (action.clear) await callOn(session, action.ref, field, DELETE_SELECTION, []) - return { value: String(await callOn(session, action.ref, field, READ_VALUE, [])) } + const field = await callOn(session, action.ref, element, "field", [], false) as string + const mode = await callOn(session, action.ref, field, "prepare", [action.clear]) + if (mode === "value" || mode === "append") await callOn(session, action.ref, field, "set-value", [action.text, mode === "append"]) + else if (action.text) await markedInput(session, dispatch => dispatch("insert-text", { text: action.text })) + else if (action.clear) await callOn(session, action.ref, field, "delete-selection", []) + return { value: String(await callOn(session, action.ref, field, "read-value", [])) } } - async function focusedElement(session: PageSession): Promise { - const active = await session.channel.send("Runtime.evaluate", { expression: "document.activeElement", objectGroup: OBJECT_GROUP }) + const active = await session.driver.call("active-element", undefined, []) await session.checkpoint() - const objectId = (active.result as { objectId?: unknown } | undefined)?.objectId - if (typeof objectId !== "string") return undefined - const described = await callOn(session, "the focused element", objectId, DESCRIBE, []) + if (typeof active.handle !== "string") return undefined + const described = await callOn(session, "the focused element", active.handle, "describe", []) return typeof described === "string" ? described : undefined } - -const LABEL = `const label = option => (option.label || option.textContent || "").replace(/\\s+/g, " ").trim();` - -/** Picks options like a user would: by visible label, else by value; change fires only on a change. - * `:disabled` also covers disabled fieldsets and optgroups. */ -const CHOOSE = `${LABEL} - const apply = (select, picked) => { - if (select.matches(":disabled")) throw new Error("codenomad:disabled"); - for (const option of picked) if (option.matches(":disabled")) throw new Error("codenomad:option-disabled:" + label(option)); - if (!select.multiple && picked.length !== 1) throw new Error("codenomad:single"); - select.focus(); - const options = Array.from(select.options); - if (options.some(option => option.selected !== picked.includes(option))) { - for (const option of options) option.selected = picked.includes(option); - select.dispatchEvent(new Event("input", { bubbles: true, composed: true })); - select.dispatchEvent(new Event("change", { bubbles: true })); - } - return Array.from(select.selectedOptions).map(label); - }; - const choose = (select, wanted) => { - if (select.matches(":disabled")) throw new Error("codenomad:disabled"); - const options = Array.from(select.options), picked = []; - for (const raw of wanted) { - const target = String(raw).replace(/\\s+/g, " ").trim(); - const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw)); - if (!option) throw new Error("codenomad:no-option:" + target); - if (!picked.includes(option)) picked.push(option); - } - return apply(select, picked); - };` - -/** A native select's popup is not part of the page: clicking an option picks that exact option, - * and the select itself is changed with `select` rather than opened. */ -const OPTION_CLICK = `${CHOOSE} - const option = element.closest("option"), select = option && option.closest("select"); - if (option && select) return apply(select, [option]); - if (element instanceof HTMLSelectElement) throw new Error("codenomad:is-select"); - return null;` - -const PROGRAMMATIC_CLICK = `if (element instanceof HTMLElement) element.click(); - else element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, composed: true })); - return null;` - -const SELECT = `${CHOOSE} - const control = element instanceof HTMLLabelElement ? element.control : element; - const select = control instanceof HTMLSelectElement ? control : control && control.closest("select"); - if (!select) throw new Error("codenomad:not-select"); - return choose(select, args[0]);` - -const FOCUS = `if (element.matches(":disabled")) throw new Error("codenomad:disabled"); - if (element instanceof HTMLElement || element instanceof SVGElement) element.focus(); - if (element.getRootNode().activeElement !== element) throw new Error("codenomad:unfocusable"); - return null;` - -const DESCRIBE = `const role = element.getAttribute("role") || element.tagName.toLowerCase(); - const name = (element.getAttribute("aria-label") || element.getAttribute("title") || element.getAttribute("placeholder") - || (element.labels && element.labels[0] && element.labels[0].textContent) || element.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 80); - return role + (name ? " " + JSON.stringify(name) : "");` - -const NOT_TEXT = ["checkbox", "radio", "button", "submit", "reset", "file", "image", "hidden"] -const VALUE_TYPES = ["date", "time", "datetime-local", "month", "week", "range", "color"] -/** Types whose value sanitization empties an invalid value. */ -const PROBED_TYPES = ["date", "time", "datetime-local", "month", "week", "number"] -const TEXT_FIELD = `const textField = item => item instanceof HTMLInputElement || item instanceof HTMLTextAreaElement - || (item instanceof HTMLElement && item.isContentEditable);` - -/** The field a ref designates: itself, its labelled control, or its first editable descendant. */ -const FIELD = `${TEXT_FIELD} - const control = element instanceof HTMLLabelElement ? element.control : element; - const field = control && textField(control) ? control - : element.querySelector('input:not([type="hidden"]), textarea, [contenteditable]:not([contenteditable="false"])'); - if (!field || !textField(field)) throw new Error("codenomad:not-editable"); - return field;` - -/** Native text insertion goes to the focused element, so a field that cannot take focus - * (hidden, disabled, behind a modal dialog) fails here instead of typing into another one. */ -const PREPARE = `const field = element, clear = args[0]; - if (field.matches(":disabled")) throw new Error("codenomad:disabled"); - if (field.readOnly) throw new Error("codenomad:readonly"); - if (field instanceof HTMLInputElement && ${JSON.stringify(NOT_TEXT)}.includes(field.type)) throw new Error("codenomad:not-text"); - field.focus(); - const active = field.getRootNode().activeElement; - const editable = !(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement); - if (active !== field && !(editable && active instanceof HTMLElement && active.isContentEditable && active.contains(field))) { - throw new Error("codenomad:unfocusable"); - } - if (field instanceof HTMLInputElement && ${JSON.stringify(VALUE_TYPES)}.includes(field.type)) return "value"; - if (editable) { - const range = document.createRange(); - range.selectNodeContents(field); - if (!clear) range.collapse(false); - const selection = getSelection(); - selection.removeAllRanges(); - selection.addRange(range); - } else if (clear) field.select(); - // Email and number inputs have no caret API: their text is appended as a value. - else { try { field.setSelectionRange(field.value.length, field.value.length); } catch { return "append"; } } - return "insert";` - -/** Sets an input's value like a picker would. An invalid value is refused before anything changes; - * a valid one keeps the browser's normalization (lowercase colors, snapped ranges). */ -const SET_VALUE = `const [text, append] = args, next = append ? element.value + text : text; - // Ranges and colors have no empty value: the browser would substitute its default. - const valid = element.type === "color" ? /^#[0-9a-f]{6}$/i.test(next) - : element.type === "range" ? /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/.test(next) - : next !== "" && ${JSON.stringify(PROBED_TYPES)}.includes(element.type) ? (() => { const probe = document.createElement("input"); probe.type = element.type; probe.value = next; return probe.value !== ""; })() - : true; - if (!valid) throw new Error("codenomad:invalid-value:" + next); - if (next === element.value) return null; - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(element, next); - element.dispatchEvent(new Event("input", { bubbles: true, composed: true })); - element.dispatchEvent(new Event("change", { bubbles: true })); - return null;` - -const DELETE_SELECTION = `document.execCommand("delete"); return null;` - -const READ_VALUE = `const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ? element.value : element.innerText || element.textContent || ""; - if (element instanceof HTMLInputElement && element.type === "password") return "•".repeat(Math.min(value.length, 16)); - return value.length > ${VALUE_LIMIT} ? value.slice(0, ${VALUE_LIMIT - 1}) + "…" : value;` diff --git a/packages/server/src/automation/page/cdp-driver.ts b/packages/server/src/automation/page/cdp-driver.ts new file mode 100644 index 0000000000..9c0517a9a7 --- /dev/null +++ b/packages/server/src/automation/page/cdp-driver.ts @@ -0,0 +1,49 @@ +import { declaration, ELEMENT_FUNCTIONS, GLOBAL_FUNCTIONS, handleResult } from "./functions" +import { OBJECT_GROUP, type PageChannel, type PageOperation } from "./protocol" +import { semanticTree } from "./semantic-tree" +import type { AxNode } from "./snapshot" +import { operationDriver } from "./driver" +import { parsePageOperation } from "./operations" +const optional = (key: string, value: unknown): Record => value === undefined ? {} : { [key]: value } + +/** Used in the app's CDP connection and Electron's native guest dispatcher. */ +export async function executeCdpOperation(channel: PageChannel, raw: PageOperation, mark = false): Promise> { + const operation = parsePageOperation(raw, mark) + switch (operation.op) { + case "tree": { const result = await channel.send("Accessibility.getFullAXTree"); return { nodes: semanticTree(Array.isArray(result.nodes) ? result.nodes as AxNode[] : []) } } + case "resolve": { const result = await channel.send("DOM.resolveNode", { backendNodeId: operation.node, objectGroup: OBJECT_GROUP }); return optional("handle",(result.object as {objectId?: string})?.objectId) } + case "call": { + const id = operation.function + const result = Object.hasOwn(ELEMENT_FUNCTIONS, id) + ? await channel.send("Runtime.callFunctionOn", { objectId: operation.handle, + functionDeclaration: declaration(id as keyof typeof ELEMENT_FUNCTIONS, mark), + arguments: operation.args.map(value => value && typeof value === "object" && Object.hasOwn(value, "handle") ? { objectId: (value as {handle: string}).handle } : { value }), + returnByValue: !handleResult(id), objectGroup: OBJECT_GROUP }) + : await channel.send("Runtime.evaluate", { expression: GLOBAL_FUNCTIONS[id as keyof typeof GLOBAL_FUNCTIONS], + ...(handleResult(id) ? { objectGroup: OBJECT_GROUP } : { returnByValue: true }) }) + const failure = result.exceptionDetails as {exception?: {description?: unknown}; text?: unknown} | undefined + if (failure) return { exception: String(failure.exception?.description ?? failure.text ?? "") } + const value = result.result as {value?: unknown; objectId?: string} | undefined + return handleResult(id) ? optional("handle",value?.objectId) : optional("value",value?.value) + } + case "scroll-into-view": return channel.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: operation.node }) + case "geometry": return channel.send("DOM.getContentQuads", { backendNodeId: operation.node }) + case "viewport": { + const metrics = await channel.send("Page.getLayoutMetrics") + const viewport = (metrics.cssLayoutViewport ?? metrics.layoutViewport) as {clientWidth?: number; clientHeight?: number} | undefined + return { ...optional("width",viewport?.clientWidth), ...optional("height",viewport?.clientHeight) } + } + case "hit-test": { const result = await channel.send("DOM.getNodeForLocation", { x: operation.x, y: operation.y, includeUserAgentShadowDOM: false, ignorePointerEventsNone: false }); return optional("node",result.backendNodeId) } + case "pointer": case "wheel": return channel.send("Input.dispatchMouseEvent", operation.event as unknown as Record) + case "keyboard": return channel.send("Input.dispatchKeyEvent", operation.event as unknown as Record) + case "insert-text": return channel.send("Input.insertText", { text: operation.text }) + case "release-handles": return channel.send("Runtime.releaseObjectGroup", { objectGroup: OBJECT_GROUP }) + case "checkpoint": return {} + } +} +export function cdpDriver(channel: PageChannel, checkpoint: () => Promise, mark = false) { + return operationDriver("cdp", operation => executeCdpOperation(channel, operation, mark), checkpoint, mark) +} +export function cdpSession(channel: PageChannel, checkpoint: () => Promise, markAutomation: boolean) { + return { driver: cdpDriver(channel, checkpoint, markAutomation), checkpoint, markAutomation } +} diff --git a/packages/server/src/automation/page/contract.cases.json b/packages/server/src/automation/page/contract.cases.json new file mode 100644 index 0000000000..eec3ce2749 --- /dev/null +++ b/packages/server/src/automation/page/contract.cases.json @@ -0,0 +1,40 @@ +{ + "valid": [ + {"op":"tree"}, {"op":"viewport"}, {"op":"checkpoint"}, {"op":"release-handles"}, + {"op":"resolve","node":42}, {"op":"geometry","node":42}, {"op":"scroll-into-view","node":42}, + {"op":"hit-test","x":1,"y":2}, + {"op":"call","function":"select","handle":"h","args":[["é漢🙂"]]}, + {"op":"call","function":"field","handle":"h","args":[]}, + {"op":"call","function":"set-value","handle":"h","args":["",false]}, + {"op":"call","function":"receives","handle":"h","args":[{"handle":"other"}]}, + {"op":"call","function":"document-root","args":[]}, + {"op":"call","function":"active-element","args":[]}, + {"op":"call","function":"input-acceptance","args":[]}, + {"op":"pointer","event":{"type":"mousePressed","x":4,"y":5,"button":"left","buttons":1,"clickCount":1}}, + {"op":"wheel","event":{"type":"mouseWheel","x":4,"y":5,"deltaX":0,"deltaY":100}}, + {"op":"keyboard","event":{"type":"keyDown","key":" ","code":"Space","text":" ","windowsVirtualKeyCode":32,"modifiers":0}}, + {"op":"keyboard","event":{"type":"keyUp","key":"Control","buttons":0,"modifiers":0}}, + {"op":"insert-text","text":""} + ], + "invalid": [ + null, [], "tree", {}, {"op":"evaluate","source":"alert(1)"}, + {"op":"tree","extra":true}, {"op":"viewport","extra":true}, {"op":"checkpoint","extra":true}, {"op":"release-handles","extra":true}, + {"op":"resolve","node":0}, {"op":"resolve","node":1.5}, {"op":"resolve","node":1,"extra":true}, + {"op":"call","function":"mark-input","args":[]}, {"op":"call","function":"unmark-input","args":[]}, + {"op":"call","function":"__proto__","args":[]}, {"op":"call","function":"constructor","args":[]}, + {"op":"call","function":"select","handle":"h","args":["label"]}, + {"op":"call","function":"focus","args":[]}, {"op":"call","function":"focus","handle":null,"args":[]}, + {"op":"call","function":"document-root","handle":null,"args":[]}, + {"op":"call","function":"focus","handle":"h","args":[],"source":"evil"}, + {"op":"call","function":"receives","handle":"h","args":[{"handle":"other","value":"evil"}]}, + {"op":"pointer","event":{"type":["mouseMoved"],"x":0,"y":0}}, + {"op":"pointer","event":{"type":"mouseMoved","x":0,"y":0,"button":["left"]}}, + {"op":"pointer","event":{"type":"mouseMoved","x":0,"y":0,"unknown":true}}, + {"op":"pointer","event":{"type":"mouseWheel","x":0,"y":0}}, + {"op":"pointer","event":{"type":"mousePressed","x":0,"y":0,"modifiers":16}}, + {"op":"keyboard","event":{"type":"keyDown","key":null}}, + {"op":"keyboard","event":{"type":"char","key":"a"}}, + {"op":"keyboard","event":{"type":"keyUp","modifiers":null}}, + {"op":"insert-text","text":null}, {"op":"insert-text","text":"ok","script":"evil"} + ] +} diff --git a/packages/server/src/automation/page/driver.fixture.json b/packages/server/src/automation/page/driver.fixture.json new file mode 100644 index 0000000000..ea0fc607a1 --- /dev/null +++ b/packages/server/src/automation/page/driver.fixture.json @@ -0,0 +1,12 @@ +[ + {"nodeId":"root","role":{"value":"RootWebArea"},"childIds":["heading","button","field","check","select","group"]}, + {"nodeId":"heading","parentId":"root","backendDOMNodeId":10,"role":{"value":"heading"},"name":{"value":"Checkout"},"properties":[{"name":"level","value":{"value":2}}]}, + {"nodeId":"button","parentId":"root","backendDOMNodeId":11,"role":{"value":"button"},"name":{"value":"Save"},"childIds":["text"]}, + {"nodeId":"text","parentId":"button","role":{"value":"StaticText"},"name":{"value":"Save"}}, + {"nodeId":"field","parentId":"root","backendDOMNodeId":12,"role":{"value":"textbox"},"name":{"value":"Name"},"value":{"value":"é漢🙂"},"properties":[{"name":"focused","value":{"value":true}}]}, + {"nodeId":"check","parentId":"root","backendDOMNodeId":13,"role":{"value":"checkbox"},"name":{"value":"Remember"},"properties":[{"name":"checked","value":{"value":"mixed"}}]}, + {"nodeId":"select","parentId":"root","backendDOMNodeId":14,"role":{"value":"combobox"},"name":{"value":"Plan"},"childIds":["option"]}, + {"nodeId":"option","parentId":"select","backendDOMNodeId":15,"role":{"value":"option"},"name":{"value":"Pro"},"properties":[{"name":"selected","value":{"value":true}},{"name":"disabled","value":{"value":true}}]}, + {"nodeId":"group","parentId":"root","ignored":true,"childIds":["quantity"]}, + {"nodeId":"quantity","parentId":"group","backendDOMNodeId":16,"role":{"value":"spinbutton"},"name":{"value":"Quantity"},"value":{"value":3}} +] diff --git a/packages/server/src/automation/page/driver.golden.json b/packages/server/src/automation/page/driver.golden.json new file mode 100644 index 0000000000..1179741975 --- /dev/null +++ b/packages/server/src/automation/page/driver.golden.json @@ -0,0 +1,85 @@ +{ + "functions": { + "option-click": { + "plain": "90863b0a65aa2a1c497b545245a8296ad2cfeeab813547ede451d490e2632b1d", + "marked": "0a881e6b538aa589f0d895558513d6a2e1d94cbb793f1339d6f0751fefa2cfcf" + }, + "programmatic-click": { + "plain": "734dbde138679fda25063747d26b0ffa822061aea13db26ed32e8288dcb1980f", + "marked": "80870581fdc8a5751f5da969309b20cbdf0ac425aefc5c9432f3afb9c14b35bd" + }, + "select": { + "plain": "7444c1f9021566b13311d45daf37c2ab866a1c74dbe5783529317d6491a4941c", + "marked": "a141bc08c8d7c5bff6e6f019dc12ef0a75720e69f4e895437cb1d19b077b149a" + }, + "focus": { + "plain": "6fb37154d05f9387248ef22993ebcb95a850c49b561a5627ebaf36ad5854228f", + "marked": "eb92152919a890f84e4073024c27ef00bbfd268f532208fcaa839f9bc6cc6683" + }, + "describe": { + "plain": "dd657dd6820c450f57e498a8a77f1ff0e8b6db40715891a65438462f1dff309e", + "marked": "dd7eed3b51f7a978ef2794caa3a4fad7cf66d817e699de3d3e8dfef056889f39" + }, + "field": { + "plain": "1900b6d0121b51cf4a5d29fc605e8b6434250bc0cc77f65c57c2abe83c10e81d", + "marked": "87931b63b8dc16dfd5d8b5679f39f49c053f6c7de4193349a987315032712c66" + }, + "prepare": { + "plain": "60813db3ea35c405aede8f2509f9d9da1142d1b319615f6fc5c72fa40c0db951", + "marked": "7e204012fa0990c918217f010ed84209bfc6eef3c609bac9af12cdc2e4db661c" + }, + "set-value": { + "plain": "b942b3037f70886892efd5f5e79e8fb1a123f24983bf225cf90c72be25425873", + "marked": "38b3b9535b7269be7352cec9b41603ac88ae9750cc7b58f9b428a4e459d4cd75" + }, + "delete-selection": { + "plain": "708ed8fe629bf30c23328f99a7f0c4f41189e709cde4c533465404797b1e6e9d", + "marked": "e329fbbc7e98ad022fc462f3bf5c4782dec9ddc2dd28ec2133f82e5d55b63da2" + }, + "read-value": { + "plain": "5e2558dd3d0f32375fb371b7f7a9e3244fb4b51e78d601add2b4881d9ad88e5b", + "marked": "6ea9a054e607c5153a2075b502c0518f22c4bbb8c4118d1b9d7fae2b143f96b6" + }, + "receives": { + "plain": "49653a8b7ef3dfd00a12239165d2f5724f21ae04984360dd1129ed117642787d", + "marked": "e82e4bdb6c7e188a3ca8b40c3926de1b1e1e29c432eddbb7d789286925526fcf" + }, + "contains": { + "plain": "5d62cfc6187d07d0a964a1eb3db5f6a49a84f375c437d3f606d3e7b07460ed80", + "marked": "7c9d1e411468befe4839f1c066446cc828617a04f0e3c8f7c4db01b2f74b5f8a" + } + }, + "globals": { + "active-element": "07828a2500ef731867740e4ab46774880eac064611688e422bcecb71c6cdc849", + "document-root": "59531dfec0550e8542be5b831f2a3e873ea10ea2ee64d665ffb016f2e2222394", + "input-acceptance": "bb376d5fec62936887da6418209b9be305b372aff93cbd98adb2edaf013a0b67", + "mark-input": "c14fcf467ef073e1b4f0619e60795fa63e3bb17a406f55dcbf75f04b4bc6fb90", + "unmark-input": "c0280c55c747c4208020d8463caf9ce044e3ab36310b09f9ef1b2bb89897469c" + }, + "snapshots": { + "all": { + "text": "- heading \"Checkout\" [b1e1] level=2\n- button \"Save\" [b1e2]\n- textbox \"Name\" [b1e3] value=\"é漢🙂\" focused\n- checkbox \"Remember\" [b1e4] checked=mixed\n- combobox \"Plan\" [b1e5]\n - option \"Pro\" [b1e6] selected disabled\n- spinbutton \"Quantity\" [b1e7] value=\"3\"", + "collapsed": 0, + "total": 7, + "shown": 7 + }, + "query": { + "text": "- combobox \"Plan\" [b1e1]\n - option \"Pro\" [b1e2] selected disabled", + "collapsed": 0, + "total": 2, + "shown": 2 + }, + "scoped": { + "text": "- combobox \"Plan\" [b1e1]\n - option \"Pro\" [b1e2] selected disabled", + "collapsed": 0, + "total": 2, + "shown": 2 + }, + "bounded": { + "text": "- heading \"Checkout\" [b1e1] level=2\n- button \"Save\" [b1e2]\n- (+2 more)\n- combobox \"Plan\" [b1e3] (+1 hidden)\n- spinbutton \"Quantity\" [b1e4] value=\"3\"", + "collapsed": 2, + "total": 7, + "shown": 4 + } + } +} diff --git a/packages/server/src/automation/page/driver.test.ts b/packages/server/src/automation/page/driver.test.ts new file mode 100644 index 0000000000..a0e1b1d5bd --- /dev/null +++ b/packages/server/src/automation/page/driver.test.ts @@ -0,0 +1,64 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { readFileSync } from "node:fs" +import { createHash } from "node:crypto" +import { parsePageOperation, pageEnvelope } from "./operations" +import { cdpSession, executeCdpOperation } from "./cdp-driver" +import { nativeDriver } from "./native-driver" +import { declaration, ELEMENT_FUNCTIONS, GLOBAL_FUNCTIONS, nativeFunctionRegistry } from "./functions" +import { PageDriverUnsupportedError, type PageChannel } from "./protocol" +import { renderSnapshot, type AxNode } from "./snapshot" +import { snapshotPage } from "./actions" +import { RefTable } from "./refs" +const json = (file: string) => JSON.parse(readFileSync(new URL(file, import.meta.url), "utf8")) +const golden = json("./driver.golden.json") + +test("the shared fixed registry matches the qualified program hashes", () => { + const hash = (source: string) => createHash("sha256").update(source).digest("hex") + for (const id of Object.keys(ELEMENT_FUNCTIONS) as (keyof typeof ELEMENT_FUNCTIONS)[]) { + assert.equal(hash(declaration(id, false)), golden.functions[id].plain, id) + assert.equal(hash(declaration(id, true)), golden.functions[id].marked, `${id} application mark`) + } + for (const [id, source] of Object.entries(GLOBAL_FUNCTIONS)) assert.equal(hash(source), golden.globals[id], id) + assert.deepEqual(json("./functions.generated.json"), nativeFunctionRegistry(), "regenerate the checked-in native resource when programs change") +}) + +test("closed driver contract refuses unknown operations, params, programs and malformed arguments", () => { + const corpus = json("./contract.cases.json") + for (const operation of corpus.valid) assert.deepEqual(parsePageOperation(operation), operation) + for (const operation of corpus.invalid) assert.throws(() => parsePageOperation(operation), /Unsupported or invalid/, JSON.stringify(operation)) + assert.throws(() => parsePageOperation({op:"insert-text",text:"x".repeat(256*1024)}), /parameters/) + assert.throws(() => pageEnvelope("browser.page.send", {sessionID:"s",operationID:"o",generation:"g",method:"Runtime.evaluate",params:{expression:"evil()"}})) + assert.throws(() => pageEnvelope("browser.page.begin", {sessionID:"s",operationID:"o",driver:"cdp"})) +}) + +test("CDP snapshots, scoped refs and bounded rendering equal the pre-driver goldens", async () => { + const nodes: AxNode[] = json("./driver.fixture.json") + for (const [name, options] of Object.entries({all:{},query:{query:"plan"},scoped:{rootBackendNodeId:14},bounded:{budget:200}})) { + let before = 0 + assert.deepEqual(renderSnapshot(nodes, () => `b1e${++before}`, options), golden.snapshots[name]) + const calls: string[] = [] + const channel: PageChannel = {send: async method => { calls.push(method); return {nodes} }} + const session = cdpSession(channel, async () => {}, false) + const refs = new RefTable("inspect", "b1e") + assert.deepEqual(await snapshotPage(session, () => refs.issuer("document"), options), golden.snapshots[name]) + assert.deepEqual(calls, ["Accessibility.getFullAXTree"]) + const transport = nativeDriver({driver:"cdp",contractVersion:1}, operation => executeCdpOperation(channel, operation), async () => {}) + const other = new RefTable("inspect", "b1e") + assert.deepEqual(await snapshotPage({driver:transport,markAutomation:false,checkpoint:async()=>{}}, () => other.issuer("document"), options), golden.snapshots[name]) + } +}) + +test("native drivers propagate structured unsupported results without fallback", async () => { + assert.throws(() => nativeDriver({driver:"cdp",contractVersion:2}, async()=>({}), async()=>{}), /contract/) + assert.throws(() => nativeDriver({}, async()=>({}), async()=>{}), /contract/) + const calls: unknown[] = [] + const driver = nativeDriver({driver:"webkit",contractVersion:1}, async operation => { + calls.push(operation) + return {error:{code:"unsupported",driver:"webkit",operation:operation.op}} + }, async()=>{}) + await assert.rejects(driver.tree(), error => error instanceof PageDriverUnsupportedError && error.code === "unsupported" && error.driver === "webkit" && error.operation === "tree") + await assert.rejects(driver.insertText("é漢🙂"), PageDriverUnsupportedError) + assert.deepEqual(calls,[{op:"tree"},{op:"insert-text",text:"é漢🙂"}]) + await assert.rejects(driver.call("mark-input",undefined,[]), /parameters/) +}) diff --git a/packages/server/src/automation/page/driver.ts b/packages/server/src/automation/page/driver.ts new file mode 100644 index 0000000000..377678c585 --- /dev/null +++ b/packages/server/src/automation/page/driver.ts @@ -0,0 +1,27 @@ +import { parsePageOperation } from "./operations" +import { PAGE_DRIVER_VERSION, PageDriverUnsupportedError, type PageDriver, type DriverKind, type PageOperation, type SemanticNode } from "./protocol" + +/** Shared typed surface for direct CDP and the fenced native operation transport. */ +export function operationDriver(kind: DriverKind, send: (operation: PageOperation) => Promise>, checkpoint: () => Promise, application = false): PageDriver { + const run = async (operation: PageOperation) => { + const result = await send(parsePageOperation(operation, application)) + const error = result?.error as { code?: unknown; operation?: unknown } | undefined + if (error?.code === "unsupported") throw new PageDriverUnsupportedError(kind, String(error.operation ?? operation.op)) + return result + } + return { + kind, version: PAGE_DRIVER_VERSION, + tree: async () => { const { nodes } = await run({ op: "tree" }); return Array.isArray(nodes) ? nodes as SemanticNode[] : [] }, + resolve: async node => (await run({ op: "resolve", node })).handle as string | undefined, + call: async (functionId, handle, args) => run({ op: "call", function: functionId, ...(handle === undefined ? {} : { handle }), args }), + scrollIntoView: async node => { await run({ op: "scroll-into-view", node }) }, + geometry: async node => { const { quads } = await run({ op: "geometry", node }); return Array.isArray(quads) ? quads as number[][] : [] }, + viewport: async () => { const result = await run({ op: "viewport" }); return { width: typeof result.width === "number" ? result.width : Infinity, height: typeof result.height === "number" ? result.height : Infinity } }, + hitTest: async (x, y) => (await run({ op: "hit-test", x, y })).node as number | undefined, + pointer: async event => { await run({ op: "pointer", event }) }, + wheel: async event => { await run({ op: "wheel", event }) }, + keyboard: async event => { await run({ op: "keyboard", event }) }, + insertText: async text => { await run({ op: "insert-text", text }) }, + releaseHandles: async () => { await run({ op: "release-handles" }) }, checkpoint, + } +} diff --git a/packages/server/src/automation/page/functions.generated.json b/packages/server/src/automation/page/functions.generated.json new file mode 100644 index 0000000000..cdfd59eced --- /dev/null +++ b/packages/server/src/automation/page/functions.generated.json @@ -0,0 +1,103 @@ +{ + "option-click": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const label = option => (option.label || option.textContent || \"\").replace(/\\s+/g, \" \").trim();\n const apply = (select, picked) => {\n if (select.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n for (const option of picked) if (option.matches(\":disabled\")) throw new Error(\"codenomad:option-disabled:\" + label(option));\n if (!select.multiple && picked.length !== 1) throw new Error(\"codenomad:single\");\n select.focus();\n const options = Array.from(select.options);\n if (options.some(option => option.selected !== picked.includes(option))) {\n for (const option of options) option.selected = picked.includes(option);\n select.dispatchEvent(new Event(\"input\", { bubbles: true, composed: true }));\n select.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n return Array.from(select.selectedOptions).map(label);\n };\n const choose = (select, wanted) => {\n if (select.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n const options = Array.from(select.options), picked = [];\n for (const raw of wanted) {\n const target = String(raw).replace(/\\s+/g, \" \").trim();\n const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw));\n if (!option) throw new Error(\"codenomad:no-option:\" + target);\n if (!picked.includes(option)) picked.push(option);\n }\n return apply(select, picked);\n };\n const option = element.closest(\"option\"), select = option && option.closest(\"select\");\n if (option && select) return apply(select, [option]);\n if (element instanceof HTMLSelectElement) throw new Error(\"codenomad:is-select\");\n return null; }" + }, + "programmatic-click": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); if (element instanceof HTMLElement) element.click();\n else element.dispatchEvent(new MouseEvent(\"click\", { bubbles: true, cancelable: true, composed: true }));\n return null; }" + }, + "select": { + "scope": "element", + "args": [ + "strings" + ], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const label = option => (option.label || option.textContent || \"\").replace(/\\s+/g, \" \").trim();\n const apply = (select, picked) => {\n if (select.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n for (const option of picked) if (option.matches(\":disabled\")) throw new Error(\"codenomad:option-disabled:\" + label(option));\n if (!select.multiple && picked.length !== 1) throw new Error(\"codenomad:single\");\n select.focus();\n const options = Array.from(select.options);\n if (options.some(option => option.selected !== picked.includes(option))) {\n for (const option of options) option.selected = picked.includes(option);\n select.dispatchEvent(new Event(\"input\", { bubbles: true, composed: true }));\n select.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n return Array.from(select.selectedOptions).map(label);\n };\n const choose = (select, wanted) => {\n if (select.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n const options = Array.from(select.options), picked = [];\n for (const raw of wanted) {\n const target = String(raw).replace(/\\s+/g, \" \").trim();\n const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw));\n if (!option) throw new Error(\"codenomad:no-option:\" + target);\n if (!picked.includes(option)) picked.push(option);\n }\n return apply(select, picked);\n };\n const control = element instanceof HTMLLabelElement ? element.control : element;\n const select = control instanceof HTMLSelectElement ? control : control && control.closest(\"select\");\n if (!select) throw new Error(\"codenomad:not-select\");\n return choose(select, args[0]); }" + }, + "focus": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); if (element.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n if (element instanceof HTMLElement || element instanceof SVGElement) element.focus();\n if (element.getRootNode().activeElement !== element) throw new Error(\"codenomad:unfocusable\");\n return null; }" + }, + "describe": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const role = element.getAttribute(\"role\") || element.tagName.toLowerCase();\n const name = (element.getAttribute(\"aria-label\") || element.getAttribute(\"title\") || element.getAttribute(\"placeholder\")\n || (element.labels && element.labels[0] && element.labels[0].textContent) || element.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 80);\n return role + (name ? \" \" + JSON.stringify(name) : \"\"); }" + }, + "field": { + "scope": "element", + "args": [], + "handle": true, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const textField = item => item instanceof HTMLInputElement || item instanceof HTMLTextAreaElement\n || (item instanceof HTMLElement && item.isContentEditable);\n const control = element instanceof HTMLLabelElement ? element.control : element;\n const field = control && textField(control) ? control\n : element.querySelector('input:not([type=\"hidden\"]), textarea, [contenteditable]:not([contenteditable=\"false\"])');\n if (!field || !textField(field)) throw new Error(\"codenomad:not-editable\");\n return field; }" + }, + "prepare": { + "scope": "element", + "args": [ + "boolean" + ], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const field = element, clear = args[0];\n if (field.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n if (field.readOnly) throw new Error(\"codenomad:readonly\");\n if (field instanceof HTMLInputElement && [\"checkbox\",\"radio\",\"button\",\"submit\",\"reset\",\"file\",\"image\",\"hidden\"].includes(field.type)) throw new Error(\"codenomad:not-text\");\n field.focus();\n const active = field.getRootNode().activeElement;\n const editable = !(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement);\n if (active !== field && !(editable && active instanceof HTMLElement && active.isContentEditable && active.contains(field))) {\n throw new Error(\"codenomad:unfocusable\");\n }\n if (field instanceof HTMLInputElement && [\"date\",\"time\",\"datetime-local\",\"month\",\"week\",\"range\",\"color\"].includes(field.type)) return \"value\";\n if (editable) {\n const selection = getSelection();\n selection.setBaseAndExtent(field, clear ? 0 : field.childNodes.length, field, field.childNodes.length);\n } else if (clear) field.select();\n // Email and number inputs have no caret API: their text is appended as a value.\n else { try { field.setSelectionRange(field.value.length, field.value.length); } catch { return \"append\"; } }\n return \"insert\"; }" + }, + "set-value": { + "scope": "element", + "args": [ + "string", + "boolean" + ], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); if (element.matches(\":disabled\")) throw new Error(\"codenomad:disabled\");\n if (element.readOnly) throw new Error(\"codenomad:readonly\");\n const [text, append] = args, next = append ? element.value + text : text;\n // Ranges and colors have no empty value: the browser would substitute its default.\n const valid = element.type === \"color\" ? /^#[0-9a-f]{6}$/i.test(next)\n : element.type === \"range\" ? /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/.test(next)\n : next !== \"\" && [\"date\",\"time\",\"datetime-local\",\"month\",\"week\",\"number\"].includes(element.type) ? (() => { const probe = document.createElement(\"input\"); probe.type = element.type; probe.value = next; return probe.value !== \"\"; })()\n : true;\n if (!valid) throw new Error(\"codenomad:invalid-value:\" + next);\n if (next === element.value) return null;\n Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, \"value\").set.call(element, next);\n element.dispatchEvent(new Event(\"input\", { bubbles: true, composed: true }));\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return null; }" + }, + "delete-selection": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); document.execCommand(\"delete\"); return null; }" + }, + "read-value": { + "scope": "element", + "args": [], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ? element.value : element.innerText || element.textContent || \"\";\n if (element instanceof HTMLInputElement && element.type === \"password\") return \"•\".repeat(Math.min(value.length, 16));\n return value.length > 200 ? value.slice(0, 199) + \"…\" : value; }" + }, + "receives": { + "scope": "element", + "args": [ + "handle" + ], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const hit = args[0] && (args[0].nodeType === Node.ELEMENT_NODE ? args[0] : args[0].parentElement);\n if (!hit) return null;\n const parent = node => {\n if (node.nodeType === 9) { try { return node.defaultView && node.defaultView.frameElement; } catch { return null; } }\n return node.assignedSlot || node.parentNode || (node.nodeType === 11 ? node.host : null);\n };\n for (let node = hit; node; node = parent(node)) {\n if (node === element) return null;\n if (node.nodeType === 1 && node.localName === \"label\" && (node.control === element || node.contains(element))) return null;\n }\n const name = (hit.getAttribute(\"aria-label\") || hit.getAttribute(\"title\") || hit.innerText || \"\").replace(/\\s+/g, \" \").trim().slice(0, 60);\n return hit.tagName.toLowerCase() + (name ? \" \" + JSON.stringify(name) : \"\"); }" + }, + "contains": { + "scope": "element", + "args": [ + "string" + ], + "handle": false, + "source": "function (...args) { const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;\n if (!(element instanceof Element) || !element.isConnected) throw new Error(\"codenomad:gone\"); const needle = String(args[0]).replace(/\\s+/g, \" \").trim().toLowerCase();\n const root = element;\n const text = value => String(value || \"\").replace(/\\s+/g, \" \").toLowerCase();\n if (text(root.innerText || root.textContent).includes(needle)) return true;\n for (const item of root.querySelectorAll(\"[aria-label], [title], [placeholder], input, textarea\")) {\n if ([item.getAttribute(\"aria-label\"), item.getAttribute(\"title\"), item.getAttribute(\"placeholder\"), item.value].some(value => text(value).includes(needle))) return true;\n }\n return false; }" + }, + "active-element": { + "scope": "global", + "args": [], + "handle": true, + "source": "document.activeElement" + }, + "document-root": { + "scope": "global", + "args": [], + "handle": true, + "source": "document.documentElement" + }, + "input-acceptance": { + "scope": "global", + "args": [], + "handle": false, + "source": "({ inputDelayMs: (() => {\n if (!/^https?:$/.test(location.protocol) || performance.getEntriesByType(\"paint\").length > 0) return 0;\n const navigation = performance.getEntriesByType(\"navigation\")[0];\n if (!navigation || !(navigation.domInteractive > 0)) return 50;\n return Math.max(0, Math.ceil(navigation.domInteractive + 500 - performance.now()));\n})() })" + } +} diff --git a/packages/server/src/automation/page/functions.ts b/packages/server/src/automation/page/functions.ts new file mode 100644 index 0000000000..1c7b468c3e --- /dev/null +++ b/packages/server/src/automation/page/functions.ts @@ -0,0 +1,158 @@ +/** Fixed page programs. Arguments are values/handles, never interpolated source. */ +export const VALUE_LIMIT = 200 +export const INPUT_MARK_LEASE_MS = 15_000 +const LABEL = `const label = option => (option.label || option.textContent || "").replace(/\\s+/g, " ").trim();` +const CHOOSE = `${LABEL} + const apply = (select, picked) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + for (const option of picked) if (option.matches(":disabled")) throw new Error("codenomad:option-disabled:" + label(option)); + if (!select.multiple && picked.length !== 1) throw new Error("codenomad:single"); + select.focus(); + const options = Array.from(select.options); + if (options.some(option => option.selected !== picked.includes(option))) { + for (const option of options) option.selected = picked.includes(option); + select.dispatchEvent(new Event("input", { bubbles: true, composed: true })); + select.dispatchEvent(new Event("change", { bubbles: true })); + } + return Array.from(select.selectedOptions).map(label); + }; + const choose = (select, wanted) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + const options = Array.from(select.options), picked = []; + for (const raw of wanted) { + const target = String(raw).replace(/\\s+/g, " ").trim(); + const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw)); + if (!option) throw new Error("codenomad:no-option:" + target); + if (!picked.includes(option)) picked.push(option); + } + return apply(select, picked); + };` +const NOT_TEXT = ["checkbox", "radio", "button", "submit", "reset", "file", "image", "hidden"] +const VALUE_TYPES = ["date", "time", "datetime-local", "month", "week", "range", "color"] +const PROBED_TYPES = ["date", "time", "datetime-local", "month", "week", "number"] +const TEXT_FIELD = `const textField = item => item instanceof HTMLInputElement || item instanceof HTMLTextAreaElement + || (item instanceof HTMLElement && item.isContentEditable);` + +export const ELEMENT_FUNCTIONS = { + "option-click": `${CHOOSE} + const option = element.closest("option"), select = option && option.closest("select"); + if (option && select) return apply(select, [option]); + if (element instanceof HTMLSelectElement) throw new Error("codenomad:is-select"); + return null;`, + "programmatic-click": `if (element instanceof HTMLElement) element.click(); + else element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, composed: true })); + return null;`, + select: `${CHOOSE} + const control = element instanceof HTMLLabelElement ? element.control : element; + const select = control instanceof HTMLSelectElement ? control : control && control.closest("select"); + if (!select) throw new Error("codenomad:not-select"); + return choose(select, args[0]);`, + focus: `if (element.matches(":disabled")) throw new Error("codenomad:disabled"); + if (element instanceof HTMLElement || element instanceof SVGElement) element.focus(); + if (element.getRootNode().activeElement !== element) throw new Error("codenomad:unfocusable"); + return null;`, + describe: `const role = element.getAttribute("role") || element.tagName.toLowerCase(); + const name = (element.getAttribute("aria-label") || element.getAttribute("title") || element.getAttribute("placeholder") + || (element.labels && element.labels[0] && element.labels[0].textContent) || element.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 80); + return role + (name ? " " + JSON.stringify(name) : "");`, + field: `${TEXT_FIELD} + const control = element instanceof HTMLLabelElement ? element.control : element; + const field = control && textField(control) ? control + : element.querySelector('input:not([type="hidden"]), textarea, [contenteditable]:not([contenteditable="false"])'); + if (!field || !textField(field)) throw new Error("codenomad:not-editable"); + return field;`, + prepare: `const field = element, clear = args[0]; + if (field.matches(":disabled")) throw new Error("codenomad:disabled"); + if (field.readOnly) throw new Error("codenomad:readonly"); + if (field instanceof HTMLInputElement && ${JSON.stringify(NOT_TEXT)}.includes(field.type)) throw new Error("codenomad:not-text"); + field.focus(); + const active = field.getRootNode().activeElement; + const editable = !(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement); + if (active !== field && !(editable && active instanceof HTMLElement && active.isContentEditable && active.contains(field))) { + throw new Error("codenomad:unfocusable"); + } + if (field instanceof HTMLInputElement && ${JSON.stringify(VALUE_TYPES)}.includes(field.type)) return "value"; + if (editable) { + const selection = getSelection(); + selection.setBaseAndExtent(field, clear ? 0 : field.childNodes.length, field, field.childNodes.length); + } else if (clear) field.select(); + // Email and number inputs have no caret API: their text is appended as a value. + else { try { field.setSelectionRange(field.value.length, field.value.length); } catch { return "append"; } } + return "insert";`, + "set-value": `if (element.matches(":disabled")) throw new Error("codenomad:disabled"); + if (element.readOnly) throw new Error("codenomad:readonly"); + const [text, append] = args, next = append ? element.value + text : text; + // Ranges and colors have no empty value: the browser would substitute its default. + const valid = element.type === "color" ? /^#[0-9a-f]{6}$/i.test(next) + : element.type === "range" ? /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/.test(next) + : next !== "" && ${JSON.stringify(PROBED_TYPES)}.includes(element.type) ? (() => { const probe = document.createElement("input"); probe.type = element.type; probe.value = next; return probe.value !== ""; })() + : true; + if (!valid) throw new Error("codenomad:invalid-value:" + next); + if (next === element.value) return null; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(element, next); + element.dispatchEvent(new Event("input", { bubbles: true, composed: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return null;`, + "delete-selection": `document.execCommand("delete"); return null;`, + "read-value": `const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ? element.value : element.innerText || element.textContent || ""; + if (element instanceof HTMLInputElement && element.type === "password") return "•".repeat(Math.min(value.length, 16)); + return value.length > ${VALUE_LIMIT} ? value.slice(0, ${VALUE_LIMIT - 1}) + "…" : value;`, + receives: `const hit = args[0] && (args[0].nodeType === Node.ELEMENT_NODE ? args[0] : args[0].parentElement); + if (!hit) return null; + const parent = node => { + if (node.nodeType === 9) { try { return node.defaultView && node.defaultView.frameElement; } catch { return null; } } + return node.assignedSlot || node.parentNode || (node.nodeType === 11 ? node.host : null); + }; + for (let node = hit; node; node = parent(node)) { + if (node === element) return null; + if (node.nodeType === 1 && node.localName === "label" && (node.control === element || node.contains(element))) return null; + } + const name = (hit.getAttribute("aria-label") || hit.getAttribute("title") || hit.innerText || "").replace(/\\s+/g, " ").trim().slice(0, 60); + return hit.tagName.toLowerCase() + (name ? " " + JSON.stringify(name) : "");`, + contains: `const needle = String(args[0]).replace(/\\s+/g, " ").trim().toLowerCase(); + const root = element; + const text = value => String(value || "").replace(/\\s+/g, " ").toLowerCase(); + if (text(root.innerText || root.textContent).includes(needle)) return true; + for (const item of root.querySelectorAll("[aria-label], [title], [placeholder], input, textarea")) { + if ([item.getAttribute("aria-label"), item.getAttribute("title"), item.getAttribute("placeholder"), item.value].some(value => text(value).includes(needle))) return true; + } + return false;`, +} as const + +export const GLOBAL_FUNCTIONS = { + "active-element": "document.activeElement", + "document-root": "document.documentElement", + "input-acceptance": `({ inputDelayMs: (() => { + if (!/^https?:$/.test(location.protocol) || performance.getEntriesByType("paint").length > 0) return 0; + const navigation = performance.getEntriesByType("navigation")[0]; + if (!navigation || !(navigation.domInteractive > 0)) return 50; + return Math.max(0, Math.ceil(navigation.domInteractive + 500 - performance.now())); +})() })`, + "mark-input": `globalThis.__codenomadAutomationInputUntil = performance.now() + ${INPUT_MARK_LEASE_MS}; Date.now() / 1000`, + "unmark-input": "globalThis.__codenomadAutomationInputUntil = Math.min(globalThis.__codenomadAutomationInputUntil || 0, performance.now()); true", +} as const +export type PageFunctionId = keyof typeof ELEMENT_FUNCTIONS | keyof typeof GLOBAL_FUNCTIONS +export const FUNCTION_ARGS: Record = { + "option-click": [], "programmatic-click": [], select: ["strings"], focus: [], describe: [], field: [], prepare: ["boolean"], + "set-value": ["string", "boolean"], "delete-selection": [], "read-value": [], receives: ["handle"], contains: ["string"], + "active-element": [], "document-root": [], "input-acceptance": [], "mark-input": [], "unmark-input": [], +} +export const handleResult = (id: PageFunctionId) => ["field", "active-element", "document-root"].includes(id) +export const applicationOnly = (id: PageFunctionId) => id === "mark-input" || id === "unmark-input" +export function declaration(id: keyof typeof ELEMENT_FUNCTIONS, mark: boolean): string { + const body = ELEMENT_FUNCTIONS[id] + const element = `const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement; + if (!(element instanceof Element) || !element.isConnected) throw new Error("codenomad:gone");` + return mark + ? `function (...args) { ${element} globalThis.__codenomadAutomationDepth = (globalThis.__codenomadAutomationDepth || 0) + 1; + try { return (() => { ${body} })(); } finally { globalThis.__codenomadAutomationDepth--; } }` + : `function (...args) { ${element} ${body} }` +} + +/** Compile-time native resource; generation is checked by the contract tests. */ +export function nativeFunctionRegistry() { + return Object.fromEntries((Object.keys(FUNCTION_ARGS) as PageFunctionId[]).filter(id => !applicationOnly(id)).map(id => [id, { + scope: Object.hasOwn(ELEMENT_FUNCTIONS, id) ? "element" : "global", args: FUNCTION_ARGS[id], handle: handleResult(id), + source: Object.hasOwn(ELEMENT_FUNCTIONS, id) ? declaration(id as keyof typeof ELEMENT_FUNCTIONS, false) : GLOBAL_FUNCTIONS[id as keyof typeof GLOBAL_FUNCTIONS], + }])) +} diff --git a/packages/server/src/automation/page/input.test.ts b/packages/server/src/automation/page/input.test.ts index b4a2430da3..d499399189 100644 --- a/packages/server/src/automation/page/input.test.ts +++ b/packages/server/src/automation/page/input.test.ts @@ -2,20 +2,17 @@ import assert from "node:assert/strict" import { test } from "node:test" import { clickAt, dragBetween, pressKeys } from "./input" import type { PageSession } from "./protocol" +import { cdpSession } from "./cdp-driver" test("failed pointer and key sequences release potentially held inputs without replaying the action", async () => { for (const kind of ["click", "drag", "keys"] as const) { const calls: Array<{ method: string; params: Record }> = [] let pressed = false, failed = false - const session: PageSession = { - markAutomation: true, - channel: { send: async (method, params = {}) => { + const session: PageSession = cdpSession({ send: async (method, params = {}) => { calls.push({ method, params }) if (params.type === "mousePressed" || params.type === "rawKeyDown") pressed = true return method === "Runtime.evaluate" ? { result: { value: 1_700_000_000 } } : {} - } }, - checkpoint: async () => { if (pressed && !failed) { failed = true; throw new Error("Page changed") } }, - } + } }, async () => { if (pressed && !failed) { failed = true; throw new Error("Page changed") } }, true) await assert.rejects(kind === "click" ? clickAt(session, { x: 10, y: 20 }) : kind === "drag" ? dragBetween(session, { x: 10, y: 20 }, { x: 50, y: 60 }) : pressKeys(session, "Control+K"), /Page changed/) const inputs = calls.filter(call => call.method.startsWith("Input.")) @@ -31,10 +28,7 @@ test("a frozen mark write cannot suppress release, and late input effects are re for (const recoversBeforeRelease of [true, false]) { const calls: Array<{ method: string; params: Record }> = [] let frozen = false, clicks = 0, queuedRelease: (() => void) | undefined - const session: PageSession = { - markAutomation: true, - checkpoint: async () => {}, - channel: { send: async (method, params = {}) => { + const session: PageSession = cdpSession({ send: async (method, params = {}) => { calls.push({ method, params }) if (method === "Runtime.evaluate" && frozen) throw new Error("CDP mark timed out") if (params.type === "mousePressed") { frozen = true; throw new Error("CDP input timed out") } @@ -43,8 +37,7 @@ test("a frozen mark write cannot suppress release, and late input effects are re else { queuedRelease = () => { clicks++ }; throw new Error("CDP release timed out") } } return method === "Runtime.evaluate" ? { result: { value: 1_700_000_000 } } : {} - } }, - } + } }, async () => {}, true) await assert.rejects(clickAt(session, { x: 10, y: 20 }), /outcome is unknown.*may still be delivered; inspect before retrying/) assert.equal(calls.filter(call => call.params.type === "mousePressed").length, 1) assert.equal(calls.filter(call => call.params.type === "mouseReleased").length, 1, @@ -61,10 +54,10 @@ test("trusted input waits until a freshly navigated page accepts it, within a bo const calls: string[] = [] const answers = [...delays] const started = Date.now() - await pressKeys({ markAutomation: false, checkpoint: async () => {}, channel: { send: async (method, params = {}) => { + await pressKeys(cdpSession({ send: async (method, params = {}) => { calls.push(method === "Runtime.evaluate" ? "ready?" : `${method}:${params.type}`) return method === "Runtime.evaluate" ? { result: { value: { inputDelayMs: answers.length > 1 ? answers.shift() : answers[0] } } } : {} - } } }, "a") + } }, async () => {}, false), "a") const elapsed = Date.now() - started const firstKey = calls.indexOf("Input.dispatchKeyEvent:keyDown") assert.ok(firstKey > 0 && calls.slice(0, firstKey).every(call => call === "ready?"), "no key precedes acceptance") @@ -80,8 +73,7 @@ test("trusted input waits until a freshly navigated page accepts it, within a bo test("input refuses when the page cannot supply a valid provenance timestamp", async () => { const methods: string[] = [] - await assert.rejects(pressKeys({ markAutomation: true, checkpoint: async () => {}, - channel: { send: async method => { methods.push(method); return { result: { value: null } } } }, - }, "Enter"), /Cannot establish automation input provenance/) + await assert.rejects(pressKeys(cdpSession({ send: async method => { methods.push(method); return { result: { value: null } } } }, + async () => {}, true), "Enter"), /Cannot establish automation input provenance/) assert.ok(methods.every(method => method === "Runtime.evaluate")) }) diff --git a/packages/server/src/automation/page/input.ts b/packages/server/src/automation/page/input.ts index 991bb137f5..c07538e246 100644 --- a/packages/server/src/automation/page/input.ts +++ b/packages/server/src/automation/page/input.ts @@ -1,5 +1,5 @@ import { keyChord } from "./keys" -import { callOn, Handle, markedInput, OBJECT_GROUP, resolveElement, type PageSession } from "./protocol" +import { callOn, Handle, markedInput, resolveElement, PageDriverUnsupportedError, type PageSession } from "./protocol" /** Trusted pointer, wheel and keyboard input through DevTools, aimed like a user would: * at the element's visible centre, only when that point actually reaches the element. */ @@ -8,12 +8,10 @@ export interface Point { x: number; y: number } /** The point a user would click, or undefined for an element without a visible box. */ export async function aim(session: PageSession, ref: string, backendNodeId: number, options: { hitTest?: boolean; scroll?: boolean } = {}): Promise { - const { channel } = session - if (options.scroll !== false) await channel.send("DOM.scrollIntoViewIfNeeded", { backendNodeId }).catch(() => undefined) + if (options.scroll !== false) await session.driver.scrollIntoView(backendNodeId).catch(error => { if (error instanceof PageDriverUnsupportedError) throw error }) await session.checkpoint() - const result = await channel.send("DOM.getContentQuads", { backendNodeId }).catch(() => ({} as Record)) + const quads = await session.driver.geometry(backendNodeId).catch(error => { if (error instanceof PageDriverUnsupportedError) throw error; return [] }) await session.checkpoint() - const quads = Array.isArray(result.quads) ? result.quads as number[][] : [] const viewport = await layoutViewport(session) const quad = quads.find(item => item.length === 8 && area(item) >= 1) if (!quad) return undefined @@ -30,29 +28,18 @@ export async function aim(session: PageSession, ref: string, backendNodeId: numb /** Refuses a point that another element covers, instead of acting on whatever is on top. */ async function assertReceives(session: PageSession, ref: string, backendNodeId: number, point: Point): Promise { // Like real events, hit testing passes through `pointer-events: none` layers (toasts, overlays' gaps). - const hit = await session.channel.send("DOM.getNodeForLocation", { x: Math.floor(point.x), y: Math.floor(point.y), - includeUserAgentShadowDOM: false, ignorePointerEventsNone: false }).catch(() => undefined) + const hitNode = await session.driver.hitTest(Math.floor(point.x), Math.floor(point.y)).catch(error => { if (error instanceof PageDriverUnsupportedError) throw error; return undefined }) await session.checkpoint() - const hitNode = hit?.backendNodeId if (typeof hitNode !== "number" || hitNode === backendNodeId) return const target = await resolveElement(session, ref, backendNodeId) const other = await resolveElement(session, ref, hitNode).catch(() => undefined) if (!other) return - const covered = await callOn(session, ref, target, RECEIVES, [new Handle(other)]) + const covered = await callOn(session, ref, target, "receives", [new Handle(other)]) if (typeof covered === "string") throw new Error(`${ref} is covered by ${covered}; close or move it first, then inspect again`) } -const RECEIVES = `const hit = args[0] && (args[0].nodeType === Node.ELEMENT_NODE ? args[0] : args[0].parentElement); - if (!hit || element === hit || element.contains(hit)) return null; - const label = hit.closest("label"); - if (label && (label.control === element || label.contains(element))) return null; - const name = (hit.getAttribute("aria-label") || hit.getAttribute("title") || hit.innerText || "").replace(/\\s+/g, " ").trim().slice(0, 60); - return hit.tagName.toLowerCase() + (name ? " " + JSON.stringify(name) : "");` - async function layoutViewport(session: PageSession): Promise<{ width: number; height: number }> { - const metrics = await session.channel.send("Page.getLayoutMetrics").catch(() => ({} as Record)) - const viewport = (metrics.cssLayoutViewport ?? metrics.layoutViewport) as { clientWidth?: number; clientHeight?: number } | undefined - return { width: viewport?.clientWidth ?? Number.POSITIVE_INFINITY, height: viewport?.clientHeight ?? Number.POSITIVE_INFINITY } + return session.driver.viewport().catch(error => { if (error instanceof PageDriverUnsupportedError) throw error; return { width: Infinity, height: Infinity } }) } function area(quad: number[]): number { @@ -69,42 +56,42 @@ export type MouseButton = keyof typeof BUTTONS export async function clickAt(session: PageSession, point: Point, button: MouseButton = "left"): Promise { await markedInput(session, async dispatch => { - await dispatch("Input.dispatchMouseEvent", { type: "mouseMoved", ...point }) - await dispatch("Input.dispatchMouseEvent", { type: "mousePressed", ...point, button, buttons: BUTTONS[button], clickCount: 1 }) - await dispatch("Input.dispatchMouseEvent", { type: "mouseReleased", ...point, button, buttons: 0, clickCount: 1 }) + await dispatch("pointer", { type: "mouseMoved", ...point }) + await dispatch("pointer", { type: "mousePressed", ...point, button, buttons: BUTTONS[button], clickCount: 1 }) + await dispatch("pointer", { type: "mouseReleased", ...point, button, buttons: 0, clickCount: 1 }) }) } export async function hoverAt(session: PageSession, point: Point): Promise { - await markedInput(session, dispatch => dispatch("Input.dispatchMouseEvent", { type: "mouseMoved", ...point })) + await markedInput(session, dispatch => dispatch("pointer", { type: "mouseMoved", ...point })) } export async function wheelAt(session: PageSession, point: Point | undefined, delta: { x: number; y: number }): Promise { const at = point ?? await viewportCentre(session) await markedInput(session, async dispatch => { - await dispatch("Input.dispatchMouseEvent", { type: "mouseMoved", ...at }) - await dispatch("Input.dispatchMouseEvent", { type: "mouseWheel", ...at, deltaX: delta.x, deltaY: delta.y }) + await dispatch("pointer", { type: "mouseMoved", ...at }) + await dispatch("wheel", { type: "mouseWheel", ...at, deltaX: delta.x, deltaY: delta.y }) }) } /** A pointer drag in small steps, so pointer-based drag libraries pass their activation distance. */ export async function dragBetween(session: PageSession, from: Point, to: Point): Promise { await markedInput(session, async dispatch => { - await dispatch("Input.dispatchMouseEvent", { type: "mouseMoved", ...from }) - await dispatch("Input.dispatchMouseEvent", { type: "mousePressed", ...from, button: "left", buttons: 1, clickCount: 1 }) + await dispatch("pointer", { type: "mouseMoved", ...from }) + await dispatch("pointer", { type: "mousePressed", ...from, button: "left", buttons: 1, clickCount: 1 }) const steps = 10 for (let step = 1; step <= steps; step++) { - await dispatch("Input.dispatchMouseEvent", { type: "mouseMoved", x: from.x + (to.x - from.x) * step / steps, + await dispatch("pointer", { type: "mouseMoved", x: from.x + (to.x - from.x) * step / steps, y: from.y + (to.y - from.y) * step / steps, button: "left", buttons: 1 }) } - await dispatch("Input.dispatchMouseEvent", { type: "mouseReleased", ...to, button: "left", buttons: 0, clickCount: 1 }) + await dispatch("pointer", { type: "mouseReleased", ...to, button: "left", buttons: 0, clickCount: 1 }) }) } export async function pressKeys(session: PageSession, chord: string): Promise { const events = keyChord(chord) await markedInput(session, async dispatch => { - for (const event of events) await dispatch("Input.dispatchKeyEvent", event) + for (const event of events) await dispatch("keyboard", event) }) } @@ -117,10 +104,10 @@ async function viewportCentre(session: PageSession): Promise { export async function waitForText(session: PageSession, text: string, gone: boolean, timeoutMs: number): Promise<{ found: boolean; waitedMs: number }> { const started = Date.now() for (;;) { - const root = await session.channel.send("Runtime.evaluate", { expression: "document.documentElement", objectGroup: OBJECT_GROUP }) + const root = await session.driver.call("document-root", undefined, []) await session.checkpoint() - const objectId = (root.result as { objectId?: unknown } | undefined)?.objectId - const found = typeof objectId === "string" && await callOn(session, "the page", objectId, CONTAINS, [text]) === true + const objectId = root.handle + const found = typeof objectId === "string" && await callOn(session, "the page", objectId, "contains", [text]) === true const waitedMs = Date.now() - started if (found !== gone) return { found, waitedMs } if (waitedMs >= timeoutMs) { @@ -129,12 +116,3 @@ export async function waitForText(session: PageSession, text: string, gone: bool await new Promise(resolve => setTimeout(resolve, Math.min(200, timeoutMs - waitedMs))) } } - -const CONTAINS = `const needle = String(args[0]).replace(/\\s+/g, " ").trim().toLowerCase(); - const root = element; - const text = value => String(value || "").replace(/\\s+/g, " ").toLowerCase(); - if (text(root.innerText || root.textContent).includes(needle)) return true; - for (const item of root.querySelectorAll("[aria-label], [title], [placeholder], input, textarea")) { - if ([item.getAttribute("aria-label"), item.getAttribute("title"), item.getAttribute("placeholder"), item.value].some(value => text(value).includes(needle))) return true; - } - return false;` diff --git a/packages/server/src/automation/page/native-driver.ts b/packages/server/src/automation/page/native-driver.ts new file mode 100644 index 0000000000..6cef6adf93 --- /dev/null +++ b/packages/server/src/automation/page/native-driver.ts @@ -0,0 +1,7 @@ +import { operationDriver } from "./driver" +import { PAGE_DRIVER_VERSION, type DriverKind, type PageOperation } from "./protocol" + +export function nativeDriver(descriptor: {driver?: unknown; contractVersion?: unknown}, send: (operation: PageOperation) => Promise>, checkpoint: () => Promise) { + if (!descriptor || (descriptor.driver !== "cdp" && descriptor.driver !== "webkit") || descriptor.contractVersion !== PAGE_DRIVER_VERSION) throw new Error("Unsupported native browser page driver contract") + return operationDriver(descriptor.driver as DriverKind, send, checkpoint) +} diff --git a/packages/server/src/automation/page/operations.ts b/packages/server/src/automation/page/operations.ts new file mode 100644 index 0000000000..374a08c591 --- /dev/null +++ b/packages/server/src/automation/page/operations.ts @@ -0,0 +1,89 @@ +import { applicationOnly, FUNCTION_ARGS, GLOBAL_FUNCTIONS, ELEMENT_FUNCTIONS, type PageFunctionId } from "./functions" +import type { PageOperation } from "./protocol" + +const fail = (): never => { throw new Error("Unsupported or invalid browser page operation parameters") } +function object(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return fail() + return value as Record +} +function keys(value: Record, allowed: string[], required: string[] = []) { + if (Object.keys(value).some(key => !allowed.includes(key)) || required.some(key => !Object.hasOwn(value, key))) fail() +} +const string = (value: unknown, limit = 512): value is string => typeof value === "string" && value.length > 0 && value.length <= limit +const number = (value: unknown, max = 10_000_000): value is number => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= max +const integer = (value: unknown, min: number, max: number): value is number => number(value, max) && Number.isSafeInteger(value) && value >= min +function optionalNumber(value: Record, key: string, max: number, integral = false) { + if (Object.hasOwn(value, key) && !(integral ? integer(value[key], 0, max) : number(value[key], max))) fail() +} +/** Strict at both ends of the private channel; application provenance never crosses it. */ +export function parsePageOperation(raw: unknown, allowApplication = false): PageOperation { + const value = object(raw) + try { if (new TextEncoder().encode(JSON.stringify(value)).length > 256 * 1024) fail() } catch { fail() } + if (!Object.hasOwn(value, "op") || typeof value.op !== "string") fail() + switch (value.op) { + case "tree": case "viewport": case "release-handles": case "checkpoint": keys(value, ["op"]); break + case "resolve": case "geometry": case "scroll-into-view": + keys(value, ["op", "node"], ["node"]) + if (!integer(value.node, 1, Number.MAX_SAFE_INTEGER)) fail() + break + case "hit-test": + keys(value, ["op", "x", "y"], ["x", "y"]) + if (!number(value.x) || !number(value.y) || !Number.isInteger(value.x) || !Number.isInteger(value.y)) fail() + break + case "call": { + keys(value, ["op", "function", "handle", "args"], ["function", "args"]) + if (typeof value.function !== "string" || !Object.hasOwn(FUNCTION_ARGS, value.function)) fail() + const id = value.function as PageFunctionId + if (applicationOnly(id) && !allowApplication) fail() + if (Object.hasOwn(ELEMENT_FUNCTIONS, id) ? !string(value.handle) : Object.hasOwn(value, "handle")) fail() + if (!Object.hasOwn(ELEMENT_FUNCTIONS, id) && !Object.hasOwn(GLOBAL_FUNCTIONS, id)) fail() + const args = value.args + if (!Array.isArray(args) || args.length !== FUNCTION_ARGS[id].length) return fail() + for (const [index, rule] of FUNCTION_ARGS[id].entries()) { + const argument = args[index] + if (rule === "string" ? typeof argument !== "string" + : rule === "boolean" ? typeof argument !== "boolean" + : rule === "strings" ? !Array.isArray(argument) || argument.some(item => typeof item !== "string") + : rule === "handle" ? !argument || typeof argument !== "object" || Array.isArray(argument) || Object.keys(argument).join() !== "handle" || !string(argument.handle) + : true) fail() + } + break + } + case "pointer": case "wheel": case "keyboard": { + keys(value, ["op", "event"], ["event"]) + const event = object(value.event) + const common = ["type", "modifiers", "timestamp"] + optionalNumber(event, "modifiers", 15, true) + optionalNumber(event, "timestamp", Number.MAX_SAFE_INTEGER) + if (value.op === "keyboard") { + keys(event, [...common, "key", "code", "windowsVirtualKeyCode", "text", "unmodifiedText", "location", "buttons"], ["type"]) + if (typeof event.type !== "string" || !["keyDown", "rawKeyDown", "keyUp"].includes(event.type)) fail() + for (const key of ["key", "code", "text", "unmodifiedText"]) if (Object.hasOwn(event, key) && !string(event[key], 256)) fail() + optionalNumber(event, "windowsVirtualKeyCode", 65535, true) + optionalNumber(event, "location", 3, true) + optionalNumber(event, "buttons", 7, true) + } else { + const wheel = value.op === "wheel" + keys(event, [...common, "x", "y", ...(wheel ? ["deltaX", "deltaY"] : ["button", "buttons", "clickCount"])], ["type", "x", "y", ...(wheel ? ["deltaX", "deltaY"] : [])]) + if (!number(event.x) || !number(event.y)) fail() + if (wheel) { if (event.type !== "mouseWheel" || !number(event.deltaX) || !number(event.deltaY)) fail() } + else { + if (typeof event.type !== "string" || !["mouseMoved", "mousePressed", "mouseReleased"].includes(event.type)) fail() + if (event.button !== undefined && (typeof event.button !== "string" || !["left", "right", "middle", "none"].includes(event.button))) fail() + optionalNumber(event, "buttons", 7, true) + optionalNumber(event, "clickCount", 3, true) + } + } + break + } + case "insert-text": keys(value, ["op", "text"], ["text"]); if (typeof value.text !== "string") fail(); break + default: fail() + } + return value as unknown as PageOperation +} + +export function pageEnvelope(method: string, input: Record): void { + keys(input, ["sessionID", "operationID", ...(method === "browser.page.send" ? ["generation", "operation"] : method === "browser.page.check" || method === "browser.page.end" ? ["generation"] : [])], + ["sessionID", "operationID", ...(method === "browser.page.send" ? ["generation", "operation"] : method === "browser.page.check" ? ["generation"] : [])]) + if (Object.hasOwn(input, "generation") && !string(input.generation)) fail() +} diff --git a/packages/server/src/automation/page/protocol.ts b/packages/server/src/automation/page/protocol.ts index fc7773dcb0..cd8557f23d 100644 --- a/packages/server/src/automation/page/protocol.ts +++ b/packages/server/src/automation/page/protocol.ts @@ -1,77 +1,76 @@ -/** Protocol primitives shared by the page engine's actions. */ +import { VALUE_LIMIT, type PageFunctionId } from "./functions" +export { VALUE_LIMIT, INPUT_MARK_LEASE_MS } from "./functions" -/** One page's protocol connection, whatever carries it (DevTools socket or a native pipe). */ -export interface PageChannel { - send(method: string, params?: Record): Promise> +/** Low-level CDP transport, used only by the CDP adapter. */ +export interface PageChannel { send(method: string, params?: Record): Promise> } +export const PAGE_DRIVER_VERSION = 1 +export const OBJECT_GROUP = "codenomad-automation" +export type DriverKind = "cdp" | "webkit" +export interface SemanticNode { + id?: string; parent?: string; children?: string[]; ignored?: boolean; node?: number + role?: unknown; name?: unknown; description?: unknown; value?: unknown + properties?: Array<{ name?: string; value?: unknown }> } +export interface PointerInput { type: "mouseMoved" | "mousePressed" | "mouseReleased"; x: number; y: number; button?: "left" | "right" | "middle" | "none"; buttons?: number; clickCount?: number; modifiers?: number; timestamp?: number } +export interface WheelInput { type: "mouseWheel"; x: number; y: number; deltaX: number; deltaY: number; modifiers?: number; timestamp?: number } +export interface KeyboardInput { type: "keyDown" | "rawKeyDown" | "keyUp"; key?: string; code?: string; windowsVirtualKeyCode?: number; modifiers?: number; text?: string; unmodifiedText?: string; location?: number; timestamp?: number; buttons?: number } +export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue } +export type PageArgument = JsonValue +export interface CallResult { value?: unknown; handle?: string; exception?: string } +export type PageOperation = + | { op: "tree" | "viewport" | "release-handles" | "checkpoint" } + | { op: "resolve" | "scroll-into-view" | "geometry"; node: number } + | { op: "hit-test"; x: number; y: number } + | { op: "call"; function: PageFunctionId; handle?: string; args: PageArgument[] } + | { op: "pointer"; event: PointerInput } + | { op: "wheel"; event: WheelInput } + | { op: "keyboard"; event: KeyboardInput } + | { op: "insert-text"; text: string } -export interface PageSession { - channel: PageChannel - /** Throws once the page changed since the operation began; runs between protocol steps. */ +/** One semantic page; drivers own protocol/native adaptation, never arbitrary evaluation. */ +export interface PageDriver { + readonly kind: DriverKind + readonly version: typeof PAGE_DRIVER_VERSION + tree(): Promise + resolve(node: number): Promise + call(functionId: PageFunctionId, handle: string | undefined, args: PageArgument[]): Promise + scrollIntoView(node: number): Promise + geometry(node: number): Promise + viewport(): Promise<{ width: number; height: number }> + hitTest(x: number, y: number): Promise + pointer(event: PointerInput): Promise + wheel(event: WheelInput): Promise + keyboard(event: KeyboardInput): Promise + insertText(text: string): Promise + releaseHandles(): Promise checkpoint(): Promise - /** The trusted CodeNomad window: page-side automation and trusted input are marked so they - * never count as a human answer (`form-answer-interaction.ts`). Never set this in a user's web page. */ - markAutomation: boolean } - -/** An element handle passed to a page function, as opposed to a plain value. */ -export class Handle { - constructor(readonly objectId: string) {} +export class PageDriverUnsupportedError extends Error { + readonly code = "unsupported" + constructor(readonly driver: DriverKind, readonly operation: string) { super(`${driver} page driver does not support ${operation}`) } } +export interface PageSession { driver: PageDriver; checkpoint(): Promise; markAutomation: boolean } +export class Handle { constructor(readonly objectId: string) {} } +export function gone(ref: string): Error { return new Error(`${ref} is no longer in the page; inspect again`) } -export const OBJECT_GROUP = "codenomad-automation" -export const VALUE_LIMIT = 200 - -export function gone(ref: string): Error { - return new Error(`${ref} is no longer in the page; inspect again`) -} - -export async function resolveElement(session: PageSession, ref: string, backendNodeId: number): Promise { - let result: Record - try { - result = await session.channel.send("DOM.resolveNode", { backendNodeId, objectGroup: OBJECT_GROUP }) - } catch { +export async function resolveElement(session: PageSession, ref: string, node: number): Promise { + let handle: string | undefined + try { handle = await session.driver.resolve(node) } catch (error) { + if (error instanceof PageDriverUnsupportedError) throw error throw gone(ref) } await session.checkpoint() - const objectId = (result.object as { objectId?: unknown } | undefined)?.objectId - if (typeof objectId !== "string") throw gone(ref) - return objectId + if (typeof handle !== "string") throw gone(ref) + return handle } - -/** Runs a fixed page function on an element; inputs travel as protocol arguments, never as source. - * `byValue: false` returns another element handle. */ -export async function callOn(session: PageSession, ref: string, objectId: string, body: string, args: unknown[], byValue = true): Promise { - const result = await session.channel.send("Runtime.callFunctionOn", { - objectId, - functionDeclaration: pageFunction(body, session.markAutomation), - arguments: args.map(value => value instanceof Handle ? { objectId: value.objectId } : { value }), - returnByValue: byValue, - objectGroup: OBJECT_GROUP, - }) +export async function callOn(session: PageSession, ref: string, handle: string, functionId: PageFunctionId, args: Array, byValue = true): Promise { + const result = await session.driver.call(functionId, handle, args.map(value => value instanceof Handle ? { handle: value.objectId } : value)) await session.checkpoint() - const failure = result.exceptionDetails as { exception?: { description?: unknown }; text?: unknown } | undefined - if (failure) throw pageError(ref, String(failure.exception?.description ?? failure.text ?? "")) - const value = result.result as { value?: unknown; objectId?: unknown } | undefined - if (!byValue) { - if (typeof value?.objectId !== "string") throw gone(ref) - return value.objectId - } - return value?.value -} - -export async function releaseObjects(session: PageSession): Promise { - await session.channel.send("Runtime.releaseObjectGroup", { objectGroup: OBJECT_GROUP }).catch(() => undefined) -} - -function pageFunction(body: string, mark: boolean): string { - const element = `const element = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement; - if (!(element instanceof Element) || !element.isConnected) throw new Error("codenomad:gone");` - return mark - ? `function (...args) { ${element} globalThis.__codenomadAutomationDepth = (globalThis.__codenomadAutomationDepth || 0) + 1; - try { return (() => { ${body} })(); } finally { globalThis.__codenomadAutomationDepth--; } }` - : `function (...args) { ${element} ${body} }` + if (result.exception !== undefined) throw pageError(ref, result.exception) + if (!byValue) { if (typeof result.handle !== "string") throw gone(ref); return result.handle } + return result.value } +export async function releaseObjects(session: PageSession): Promise { await session.driver.releaseHandles().catch(() => undefined) } function pageError(ref: string, description: string): Error { const [code, detail = ""] = /codenomad:([a-z-]+)(?::(.*))?/.exec(description.split("\n", 1)[0])?.slice(1) ?? [] @@ -93,91 +92,66 @@ function pageError(ref: string, description: string): Error { } } -/** Marks trusted input (DevTools mouse/keyboard events) in the CodeNomad window. A lease, not a - * counter: if the clearing call is lost with the connection, the mark still expires. */ -export async function markedInput(session: PageSession, run: (dispatch: (method: string, params: Record) => Promise) => Promise): Promise { - const held = new Map }>() +type InputKind = "pointer" | "wheel" | "keyboard" | "insert-text" +async function sendInput(session: PageSession, kind: InputKind, params: Record): Promise { + switch (kind) { + case "pointer": return session.driver.pointer(params as unknown as PointerInput) + case "wheel": return session.driver.wheel(params as unknown as WheelInput) + case "keyboard": return session.driver.keyboard(params as unknown as KeyboardInput) + case "insert-text": return session.driver.insertText(params.text as string) + } +} +/** Provenance marking belongs only to the trusted application window. */ +export async function markedInput(session: PageSession, run: (dispatch: (kind: InputKind, params: Record) => Promise) => Promise): Promise { + const held = new Map }>() let point = { x: 0, y: 0 } let attempted = false - const dispatch = async (method: string, params: Record) => { + const dispatch = async (kind: InputKind, params: Record) => { let timestamp: number | undefined if (session.markAutomation) { - const result = await session.channel.send("Runtime.evaluate", { expression: MARK_INPUT, returnByValue: true }) - const stamp = (result.result as { value?: unknown } | undefined)?.value + const stamp = (await session.driver.call("mark-input", undefined, [])).value if (typeof stamp !== "number" || !Number.isFinite(stamp) || stamp <= 0) throw new Error("Cannot establish automation input provenance") timestamp = stamp } - const mouse = method === "Input.dispatchMouseEvent" + const mouse = kind === "pointer" || kind === "wheel" if (mouse && typeof params.x === "number" && typeof params.y === "number") point = { x: params.x, y: params.y } const id = mouse ? `mouse:${params.button}` : `key:${params.code}` const down = mouse ? params.type === "mousePressed" : params.type === "keyDown" || params.type === "rawKeyDown" const up = mouse ? params.type === "mouseReleased" : params.type === "keyUp" - if (down) held.set(id, { method, params: { ...params, type: mouse ? "mouseReleased" : "keyUp", buttons: 0, modifiers: 0, + if (down) held.set(id, { kind, params: { ...params, type: mouse ? "mouseReleased" : "keyUp", buttons: 0, modifiers: 0, ...(timestamp === undefined ? {} : { timestamp }) } }) attempted = true - await session.channel.send(method, { ...params, - ...(timestamp === undefined || !["Input.dispatchMouseEvent", "Input.dispatchKeyEvent"].includes(method) ? {} : { timestamp }) }) + await sendInput(session, kind, { ...params, ...(timestamp === undefined || kind === "insert-text" ? {} : { timestamp }) }) if (up) held.delete(id) await session.checkpoint() } await awaitInputAcceptance(session) - try { - return await run(dispatch) - } catch (error) { - if (attempted && error instanceof Error && /timed out|timeout/i.test(error.message)) { - throw new Error("Input timed out: its outcome is unknown. The page was busy and the input may still be delivered; inspect before retrying.") - } + try { return await run(dispatch) } + catch (error) { + if (attempted && error instanceof Error && /timed out|timeout/i.test(error.message)) throw new Error("Input timed out: its outcome is unknown. The page was busy and the input may still be delivered; inspect before retrying.") throw error } finally { - // Failure may be after admission but before acknowledgement/checkpoint. Release - // anything potentially held, without a failed checkpoint suppressing cleanup. for (const release of [...held.values()].reverse()) { try { - // A frozen page can time out this write too. The release retains the - // original press's timestamp, so provenance never depends on the timeout. - if (session.markAutomation) await session.channel.send("Runtime.evaluate", { expression: MARK_INPUT, returnByValue: true }).catch(() => undefined) + if (session.markAutomation) await session.driver.call("mark-input", undefined, []).catch(() => undefined) const { text: _text, unmodifiedText: _unmodified, ...params } = release.params - await session.channel.send(release.method, { ...params, ...(release.method === "Input.dispatchMouseEvent" ? point : {}) }) - } catch { /* Best effort, exact original channel only; never retry the action. */ } + await sendInput(session, release.kind, { ...params, ...(release.kind === "pointer" ? point : {}) }) + } catch { /* Exact original driver, best effort; never replay a press. */ } } - if (session.markAutomation) await session.channel.send("Runtime.evaluate", { expression: UNMARK_INPUT, returnByValue: true }).catch(() => undefined) + if (session.markAutomation) await session.driver.call("unmark-input", undefined, []).catch(() => undefined) } } - -/** After an HTTP(S) navigation, Chromium's renderer defers compositor commits until the first - * (contentful) paint, for at most about 500 ms after rendering starts, and drops key, click and - * wheel input meanwhile (Blink paint holding: `LocalFrameView` and - * `WidgetInputHandlerManager::DispatchEvent`). A hidden or software-composited page can take that - * long to paint, so its first trusted input waits until the page has painted or roughly that limit - * has passed, approximated from the moment it became interactive. The page's answer only delays - * input, by at most `INPUT_ACCEPTANCE_MAX_WAIT_MS`. */ async function awaitInputAcceptance(session: PageSession): Promise { const started = Date.now() for (;;) { - const result = await session.channel.send("Runtime.evaluate", { expression: INPUT_ACCEPTANCE_DELAY, returnByValue: true }) - .catch(() => undefined) + const result = await session.driver.call("input-acceptance", undefined, []).catch(error => { + if (error instanceof PageDriverUnsupportedError) throw error + return undefined + }) await session.checkpoint() - const delay = ((result?.result as { value?: { inputDelayMs?: unknown } } | undefined)?.value)?.inputDelayMs - const remaining = INPUT_ACCEPTANCE_MAX_WAIT_MS - (Date.now() - started) + const delay = (result?.value as { inputDelayMs?: unknown } | undefined)?.inputDelayMs + const remaining = 1_000 - (Date.now() - started) if (typeof delay !== "number" || !(delay > 0) || remaining <= 0) return await new Promise(resolve => setTimeout(resolve, Math.min(delay, remaining, 50))) } } - -const PAINT_HOLDING_LIMIT_MS = 500 -const INPUT_ACCEPTANCE_MAX_WAIT_MS = 1_000 -// Milliseconds until the page accepts input: 0 once it painted, for non-HTTP(S) documents (no -// paint holding) and after the limit; a short poll while the document is still loading. -const INPUT_ACCEPTANCE_DELAY = `({ inputDelayMs: (() => { - if (!/^https?:$/.test(location.protocol) || performance.getEntriesByType("paint").length > 0) return 0; - const navigation = performance.getEntriesByType("navigation")[0]; - if (!navigation || !(navigation.domInteractive > 0)) return 50; - return Math.max(0, Math.ceil(navigation.domInteractive + ${PAINT_HOLDING_LIMIT_MS} - performance.now())); -})() })` - -export const INPUT_MARK_LEASE_MS = 15_000 -// CDP timestamps use epoch seconds; DOM event.timeStamp uses the page's monotonic -// origin. Reading both in the page keeps delayed input within its original interval. -const MARK_INPUT = `globalThis.__codenomadAutomationInputUntil = performance.now() + ${INPUT_MARK_LEASE_MS}; Date.now() / 1000` -// Keep the interval's end for events queued before a stalled renderer recovered. -const UNMARK_INPUT = "globalThis.__codenomadAutomationInputUntil = Math.min(globalThis.__codenomadAutomationInputUntil || 0, performance.now()); true" diff --git a/packages/server/src/automation/page/semantic-tree.ts b/packages/server/src/automation/page/semantic-tree.ts new file mode 100644 index 0000000000..573a6bfd4f --- /dev/null +++ b/packages/server/src/automation/page/semantic-tree.ts @@ -0,0 +1,15 @@ +import type { SemanticNode } from "./protocol" +import type { AxNode } from "./snapshot" + +/** CDP fields end here; stable numeric node identities remain shared with RefTable. */ +export function semanticTree(nodes: readonly AxNode[]): SemanticNode[] { + return nodes.map(node => ({ id: node.nodeId, parent: node.parentId, children: node.childIds, ignored: node.ignored, + node: node.backendDOMNodeId, role: node.role?.value, name: node.name?.value, description: node.description?.value, + value: node.value?.value, properties: node.properties?.map(property => ({ name: property.name, value: property.value?.value })) })) +} +/** Keep the established snapshot renderer and its budgets unchanged. */ +export function snapshotTree(nodes: readonly SemanticNode[]): AxNode[] { + return nodes.map(node => ({ nodeId: node.id, parentId: node.parent, childIds: node.children, ignored: node.ignored, + backendDOMNodeId: node.node, role: { value: node.role }, name: { value: node.name }, description: { value: node.description }, + value: { value: node.value }, properties: node.properties?.map(property => ({ name: property.name, value: { value: property.value } })) })) +} diff --git a/packages/server/src/automation/page/webkit/LICENSE.dom-accessibility-api b/packages/server/src/automation/page/webkit/LICENSE.dom-accessibility-api new file mode 100644 index 0000000000..17dbaca563 --- /dev/null +++ b/packages/server/src/automation/page/webkit/LICENSE.dom-accessibility-api @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Sebastian Silbermann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/server/src/automation/page/webkit/calls.generated.ts b/packages/server/src/automation/page/webkit/calls.generated.ts new file mode 100644 index 0000000000..bf04a7a1e7 --- /dev/null +++ b/packages/server/src/automation/page/webkit/calls.generated.ts @@ -0,0 +1,136 @@ +// Generated by scripts/build-webkit-read.ts. +// @ts-nocheck +export const readCalls = { +"option-click": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const label = option => (option.label || option.textContent || "").replace(/\s+/g, " ").trim(); + const apply = (select, picked) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + for (const option of picked) if (option.matches(":disabled")) throw new Error("codenomad:option-disabled:" + label(option)); + if (!select.multiple && picked.length !== 1) throw new Error("codenomad:single"); + select.focus(); + const options = Array.from(select.options); + if (options.some(option => option.selected !== picked.includes(option))) { + for (const option of options) option.selected = picked.includes(option); + select.dispatchEvent(new Event("input", { bubbles: true, composed: true })); + select.dispatchEvent(new Event("change", { bubbles: true })); + } + return Array.from(select.selectedOptions).map(label); + }; + const choose = (select, wanted) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + const options = Array.from(select.options), picked = []; + for (const raw of wanted) { + const target = String(raw).replace(/\s+/g, " ").trim(); + const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw)); + if (!option) throw new Error("codenomad:no-option:" + target); + if (!picked.includes(option)) picked.push(option); + } + return apply(select, picked); + }; + const option = element.closest("option"), select = option && option.closest("select"); + if (option && select) return apply(select, [option]); + if (element instanceof HTMLSelectElement) throw new Error("codenomad:is-select"); + return null; }, +"programmatic-click": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); if (element instanceof HTMLElement) element.click(); + else element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, composed: true })); + return null; }, +"select": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const label = option => (option.label || option.textContent || "").replace(/\s+/g, " ").trim(); + const apply = (select, picked) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + for (const option of picked) if (option.matches(":disabled")) throw new Error("codenomad:option-disabled:" + label(option)); + if (!select.multiple && picked.length !== 1) throw new Error("codenomad:single"); + select.focus(); + const options = Array.from(select.options); + if (options.some(option => option.selected !== picked.includes(option))) { + for (const option of options) option.selected = picked.includes(option); + select.dispatchEvent(new Event("input", { bubbles: true, composed: true })); + select.dispatchEvent(new Event("change", { bubbles: true })); + } + return Array.from(select.selectedOptions).map(label); + }; + const choose = (select, wanted) => { + if (select.matches(":disabled")) throw new Error("codenomad:disabled"); + const options = Array.from(select.options), picked = []; + for (const raw of wanted) { + const target = String(raw).replace(/\s+/g, " ").trim(); + const option = options.find(item => label(item) === target) || options.find(item => item.value === String(raw)); + if (!option) throw new Error("codenomad:no-option:" + target); + if (!picked.includes(option)) picked.push(option); + } + return apply(select, picked); + }; + const control = element instanceof HTMLLabelElement ? element.control : element; + const select = control instanceof HTMLSelectElement ? control : control && control.closest("select"); + if (!select) throw new Error("codenomad:not-select"); + return choose(select, args[0]); }, +"focus": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); if (element.matches(":disabled")) throw new Error("codenomad:disabled"); + if (element instanceof HTMLElement || element instanceof SVGElement) element.focus(); + if (element.getRootNode().activeElement !== element) throw new Error("codenomad:unfocusable"); + return null; }, +"describe": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const role = element.getAttribute("role") || element.tagName.toLowerCase(); + const name = (element.getAttribute("aria-label") || element.getAttribute("title") || element.getAttribute("placeholder") + || (element.labels && element.labels[0] && element.labels[0].textContent) || element.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80); + return role + (name ? " " + JSON.stringify(name) : ""); }, +"field": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const textField = item => item instanceof HTMLInputElement || item instanceof HTMLTextAreaElement + || (item instanceof HTMLElement && item.isContentEditable); + const control = element instanceof HTMLLabelElement ? element.control : element; + const field = control && textField(control) ? control + : element.querySelector('input:not([type="hidden"]), textarea, [contenteditable]:not([contenteditable="false"])'); + if (!field || !textField(field)) throw new Error("codenomad:not-editable"); + return field; }, +"prepare": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const field = element, clear = args[0]; + if (field.matches(":disabled")) throw new Error("codenomad:disabled"); + if (field.readOnly) throw new Error("codenomad:readonly"); + if (field instanceof HTMLInputElement && ["checkbox","radio","button","submit","reset","file","image","hidden"].includes(field.type)) throw new Error("codenomad:not-text"); + field.focus(); + const active = field.getRootNode().activeElement; + const editable = !(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement); + if (active !== field && !(editable && active instanceof HTMLElement && active.isContentEditable && active.contains(field))) { + throw new Error("codenomad:unfocusable"); + } + if (field instanceof HTMLInputElement && ["date","time","datetime-local","month","week","range","color"].includes(field.type)) return "value"; + if (editable) { + const selection = getSelection(); + selection.setBaseAndExtent(field, clear ? 0 : field.childNodes.length, field, field.childNodes.length); + } else if (clear) field.select(); + // Email and number inputs have no caret API: their text is appended as a value. + else { try { field.setSelectionRange(field.value.length, field.value.length); } catch { return "append"; } } + return "insert"; }, +"set-value": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); if (element.matches(":disabled")) throw new Error("codenomad:disabled"); + if (element.readOnly) throw new Error("codenomad:readonly"); + const [text, append] = args, next = append ? element.value + text : text; + // Ranges and colors have no empty value: the browser would substitute its default. + const valid = element.type === "color" ? /^#[0-9a-f]{6}$/i.test(next) + : element.type === "range" ? /^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(next) + : next !== "" && ["date","time","datetime-local","month","week","number"].includes(element.type) ? (() => { const probe = document.createElement("input"); probe.type = element.type; probe.value = next; return probe.value !== ""; })() + : true; + if (!valid) throw new Error("codenomad:invalid-value:" + next); + if (next === element.value) return null; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(element, next); + element.dispatchEvent(new Event("input", { bubbles: true, composed: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return null; }, +"delete-selection": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); document.execCommand("delete"); return null; }, +"read-value": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ? element.value : element.innerText || element.textContent || ""; + if (element instanceof HTMLInputElement && element.type === "password") return "•".repeat(Math.min(value.length, 16)); + return value.length > 200 ? value.slice(0, 199) + "…" : value; }, +"receives": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const hit = args[0] && (args[0].nodeType === Node.ELEMENT_NODE ? args[0] : args[0].parentElement); + if (!hit) return null; + const parent = node => { + if (node.nodeType === 9) { try { return node.defaultView && node.defaultView.frameElement; } catch { return null; } } + return node.assignedSlot || node.parentNode || (node.nodeType === 11 ? node.host : null); + }; + for (let node = hit; node; node = parent(node)) { + if (node === element) return null; + if (node.nodeType === 1 && node.localName === "label" && (node.control === element || node.contains(element))) return null; + } + const name = (hit.getAttribute("aria-label") || hit.getAttribute("title") || hit.innerText || "").replace(/\s+/g, " ").trim().slice(0, 60); + return hit.tagName.toLowerCase() + (name ? " " + JSON.stringify(name) : ""); }, +"contains": function (...args) { const element=this.nodeType===1?this:this.parentElement; if (!element || !element.isConnected) throw new Error("codenomad:gone"); const document=element.ownerDocument; const { HTMLInputElement, HTMLTextAreaElement, HTMLLabelElement, HTMLSelectElement, HTMLElement, SVGElement, Node, Event, MouseEvent } = document.defaultView; const getSelection=()=>document.defaultView.getSelection(); const needle = String(args[0]).replace(/\s+/g, " ").trim().toLowerCase(); + const root = element; + const text = value => String(value || "").replace(/\s+/g, " ").toLowerCase(); + if (text(root.innerText || root.textContent).includes(needle)) return true; + for (const item of root.querySelectorAll("[aria-label], [title], [placeholder], input, textarea")) { + if ([item.getAttribute("aria-label"), item.getAttribute("title"), item.getAttribute("placeholder"), item.value].some(value => text(value).includes(needle))) return true; + } + return false; } +}; diff --git a/packages/server/src/automation/page/webkit/geometry.ts b/packages/server/src/automation/page/webkit/geometry.ts new file mode 100644 index 0000000000..c70c6a2d62 --- /dev/null +++ b/packages/server/src/automation/page/webkit/geometry.ts @@ -0,0 +1,107 @@ +import { shadowRoot } from "./shadow" +type Roots=WeakMap> +const element=(node:Node)=>node.nodeType === 1 ? node as Element : node.parentElement +function frame(doc:Document): HTMLIFrameElement | undefined { return doc === document ? undefined : doc.defaultView?.frameElement as HTMLIFrameElement ?? undefined } +export class GeometryUnsupportedError extends Error {} +const parent=(item:Element): Element | null => item.assignedSlot ?? item.parentElement ?? (item.getRootNode() as ShadowRoot).host ?? null +function linearTransform(item:Element): DOMMatrix { + let matrix=new DOMMatrix() + for(let current:Element|null=item;current;current=parent(current)) { + const style=current.ownerDocument.defaultView!.getComputedStyle(current) + const transform=new DOMMatrix(style.transform === "none" ? undefined : style.transform) + // Independent transforms and motion paths need their own composition order. + if(!transform.is2D || style.perspective !== "none" || [style.rotate,style.scale,style.translate,style.offsetPath].some(value=>value && value !== "none")) + throw new GeometryUnsupportedError("WebKit aiming requires an invertible 2D CSS transform; perspective, independent transforms and motion paths are unsupported") + const zoom=Number(style.getPropertyValue("zoom")) || 1 + matrix=transform.scale(zoom).multiply(matrix) + } + if(!Number.isFinite(matrix.a*matrix.d-matrix.b*matrix.c) || Math.abs(matrix.a*matrix.d-matrix.b*matrix.c)<1e-10) + throw new GeometryUnsupportedError("WebKit aiming requires an invertible 2D CSS transform") + return matrix +} +function frameTransform(owner:HTMLIFrameElement): DOMMatrix { + const matrix=linearTransform(owner),style=owner.ownerDocument.defaultView!.getComputedStyle(owner) + const px=(name:string)=>parseFloat(style.getPropertyValue(name)) || 0 + const width=px("width")+(style.boxSizing === "border-box" ? 0 : px("padding-left")+px("padding-right")+px("border-left-width")+px("border-right-width")) + const height=px("height")+(style.boxSizing === "border-box" ? 0 : px("padding-top")+px("padding-bottom")+px("border-top-width")+px("border-bottom-width")) + const corners=[[0,0],[width,0],[width,height],[0,height]].map(([x,y])=>matrix.transformPoint({x,y})) + const box=owner.getBoundingClientRect(),xs=corners.map(p=>p.x),ys=corners.map(p=>p.y) + if(Math.abs(Math.max(...xs)-Math.min(...xs)-box.width)>0.5 || Math.abs(Math.max(...ys)-Math.min(...ys)-box.height)>0.5) + throw new GeometryUnsupportedError("WebKit cannot map this frame's transformed content box exactly") + // The bounding box fixes the translation, including layout, scrolling and every + // transform-origin. Only the composed linear part affects corner differences. + matrix.e+=box.left-Math.min(...xs);matrix.f+=box.top-Math.min(...ys) + return matrix.translate(px("border-left-width")+px("padding-left"),px("border-top-width")+px("padding-top")) +} +type Point={x:number;y:number} +function clip(points:Point[],width:number,height:number): Point[] { + for(const [axis,limit,sign] of [["x",0,1],["x",width,-1],["y",0,1],["y",height,-1]] as const) { + const output:Point[]=[] + for(let i=0;i=0,insideB=(b[axis]-limit)*sign>=0 + if(insideA) output.push(a) + if(insideA !== insideB) {const t=(limit-a[axis])/(b[axis]-a[axis]);output.push({x:a.x+t*(b.x-a.x),y:a.y+t*(b.y-a.y)})} + } + points=output + } + return points +} +function validate(item:Element): void { + linearTransform(item) + for(let doc=item.ownerDocument,owner=frame(doc);owner;owner=frame(doc)) {frameTransform(owner);doc=owner.ownerDocument} +} +export function geometry(node:Node): number[][] { + const item=element(node) + if(!item) return [] + validate(item) + return Array.from(item.getClientRects()).filter(rect=>rect.width>0 && rect.height>0).flatMap(rect=>{ + let points:Point[]=[{x:rect.left,y:rect.top},{x:rect.right,y:rect.top},{x:rect.right,y:rect.bottom},{x:rect.left,y:rect.bottom}],doc=item.ownerDocument + for(let owner=frame(doc);owner;owner=frame(doc)) { + points=clip(points,doc.defaultView!.innerWidth,doc.defaultView!.innerHeight) + if(!points.length) return [] + const matrix=frameTransform(owner) + points=points.map(point=>matrix.transformPoint(point)) + doc=owner.ownerDocument + } + const xs=points.map(p=>p.x),ys=points.map(p=>p.y) + const left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys) + return [[left,top,right,top,right,bottom,left,bottom]] + }) +} +export function scrollIntoView(node:Node): void { + const item=element(node) + if(!item) return + validate(item) + item.scrollIntoView({block:"center",inline:"center",behavior:"instant"}) + for(let doc=item.ownerDocument,owner=frame(doc);owner;owner=frame(doc)) {owner.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"});doc=owner.ownerDocument} +} +export function hitTest(x:number,y:number,roots:Roots): Element | undefined { + let root:Document|ShadowRoot=document,hit:Element|null=null + const seen=new Set() + for(;;) { + const item:Element|null=root.elementFromPoint(x,y) + if(!item || seen.has(item)) break + validate(item) + hit=item;seen.add(item) + const shadow=shadowRoot(item,roots) + if(shadow) {root=shadow;continue} + if(item.localName === "iframe" || item.localName === "frame") { + let doc:Document|null=null + try {doc=(item as HTMLIFrameElement).contentDocument} catch { /* opaque frame */ } + if(doc) {const point=frameTransform(item as HTMLIFrameElement).inverse().transformPoint({x,y});x=point.x;y=point.y;root=doc;continue} + } + break + } + return hit ?? undefined +} +export function activeElement(roots:Roots): Element | null { + let item=document.activeElement + const seen=new Set() + while(item && !seen.has(item)) { + seen.add(item) + const nested=shadowRoot(item,roots)?.activeElement ?? ((item as HTMLIFrameElement).contentDocument?.activeElement) + if(!nested || nested === item) break + item=nested + } + return item +} diff --git a/packages/server/src/automation/page/webkit/hook.ts b/packages/server/src/automation/page/webkit/hook.ts new file mode 100644 index 0000000000..e8fde8108a --- /dev/null +++ b/packages/server/src/automation/page/webkit/hook.ts @@ -0,0 +1,30 @@ +/** Fixed weak capture bridge; identity, traversal and handles stay isolated. */ +export const CLOSED_SHADOW_HOOK = `(() => { + const original = Element.prototype.attachShadow; + const apply = Reflect.apply; + const setAttribute = Element.prototype.setAttribute; + const roots = new WeakMap(); + const Reply = PointerEvent; + const dispatch = EventTarget.prototype.dispatchEvent; + const listen = EventTarget.prototype.addEventListener; + const reply = function (host) { + const root = roots.get(host); + if (root) { + // The nested carrier is never dispatched, preserving its native Node + // reference without shadow retargeting or cross-world JS serialization. + const carrier = new Reply("__codenomad_reference_v1", {relatedTarget:root}); + apply(dispatch,host,[new Reply("__codenomad_shadow_v1",{predictedEvents:[carrier]})]); + } + }; + const wrapped = function (options) { + const root = apply(original, this, [options]); + if (root.mode === "closed") { + const host = this; + roots.set(host, root); + apply(listen,host,["__codenomad_request_shadow_v1",()=>reply(host)]); + apply(setAttribute, this, ["data-codenomad-shadow-boundary", "closed"]); + } + return root; + }; + Object.defineProperty(Element.prototype, "attachShadow", { ...Object.getOwnPropertyDescriptor(Element.prototype, "attachShadow"), value: wrapped }); +})()` diff --git a/packages/server/src/automation/page/webkit/read.generated.js b/packages/server/src/automation/page/webkit/read.generated.js new file mode 100644 index 0000000000..d39980dcad --- /dev/null +++ b/packages/server/src/automation/page/webkit/read.generated.js @@ -0,0 +1,26 @@ +/*! dom-accessibility-api 0.7.1 +MIT License + +Copyright (c) 2020 Sebastian Silbermann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +"use strict";var __codenomadReadModule=(()=>{var ee=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var n in t)ee(e,n,{get:t[n],enumerable:!0})},tt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ue(t))!Ze.call(e,a)&&a!==n&&ee(e,a,{get:()=>t[a],enumerable:!(r=Qe(t,a))||r.enumerable});return e};var nt=e=>tt(ee({},"__esModule",{value:!0}),e);var Gt={};et(Gt,{read:()=>$t});var rt=Object.prototype.toString;function pe(e){return typeof e=="function"||rt.call(e)==="[object Function]"}function ot(e){var t=Number(e);return isNaN(t)?0:t===0||!isFinite(t)?t:(t>0?1:-1)*Math.floor(Math.abs(t))}var it=Math.pow(2,53)-1;function at(e){var t=ot(e);return Math.min(Math.max(t,0),it)}function A(e,t){var n=Array,r=Object(e);if(e==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");if(typeof t<"u"&&!pe(t))throw new TypeError("Array.from: when provided, the second argument must be a function");for(var a=at(r.length),d=pe(n)?Object(new n(a)):new Array(a),i=0,u;i0&&arguments[0]!==void 0?arguments[0]:[];lt(this,e),ut(this,"items",void 0),this.items=t}return st(e,[{key:"add",value:function(n){return this.has(n)===!1&&this.items.push(n),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(n){var r=this.items.length;return this.items=this.items.filter(function(a){return a!==n}),r!==this.items.length}},{key:"forEach",value:function(n){var r=this;this.items.forEach(function(a){n(a,a,r)})}},{key:"has",value:function(n){return this.items.indexOf(n)!==-1}},{key:"size",get:function(){return this.items.length}}])})(),ge=typeof Set>"u"?Set:dt;function x(e){var t;return(t=e.localName)!==null&&t!==void 0?t:e.tagName.toLowerCase()}var ft={article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",form:"form",footer:"contentinfo",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",html:"document",legend:"legend",li:"listitem",math:"math",main:"main",menu:"list",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",progress:"progressbar",section:"region",summary:"button",table:"table",tbody:"rowgroup",textarea:"textbox",tfoot:"rowgroup",td:"cell",th:"columnheader",thead:"rowgroup",tr:"row",ul:"list"},mt={caption:new Set(["aria-label","aria-labelledby"]),code:new Set(["aria-label","aria-labelledby"]),deletion:new Set(["aria-label","aria-labelledby"]),emphasis:new Set(["aria-label","aria-labelledby"]),generic:new Set(["aria-label","aria-labelledby","aria-roledescription"]),insertion:new Set(["aria-label","aria-labelledby"]),none:new Set(["aria-label","aria-labelledby"]),paragraph:new Set(["aria-label","aria-labelledby"]),presentation:new Set(["aria-label","aria-labelledby"]),strong:new Set(["aria-label","aria-labelledby"]),subscript:new Set(["aria-label","aria-labelledby"]),superscript:new Set(["aria-label","aria-labelledby"])};function pt(e,t){return["aria-atomic","aria-busy","aria-controls","aria-current","aria-description","aria-describedby","aria-details","aria-dropeffect","aria-flowto","aria-grabbed","aria-hidden","aria-keyshortcuts","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-roledescription"].some(function(n){var r;return e.hasAttribute(n)&&!((r=mt[t])!==null&&r!==void 0&&r.has(n))})}function we(e,t){return pt(e,t)}function V(e){var t=ht(e);if(t===null||G.indexOf(t)!==-1){var n=bt(e);if(G.indexOf(t||"")===-1||we(e,n||""))return n}return t}function bt(e){var t=ft[x(e)];if(t!==void 0)return t;switch(x(e)){case"a":case"area":case"link":if(e.hasAttribute("href"))return"link";break;case"img":return e.getAttribute("alt")===""&&!we(e,"img")?"presentation":"img";case"input":{var n=e,r=n.type;switch(r){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return r;case"range":return"slider";case"email":case"tel":case"text":case"url":return e.hasAttribute("list")?"combobox":"textbox";case"search":return e.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return e.hasAttribute("multiple")||e.size>1?"listbox":"combobox"}return null}function ht(e){var t=e.getAttribute("role");if(t!==null){var n=t.trim().split(" ")[0];if(n.length>0)return n}return null}var G=["presentation","none"];function T(e){return e!==null&&e.nodeType===e.ELEMENT_NODE}function te(e){return T(e)&&x(e)==="caption"}function q(e){return T(e)&&x(e)==="input"}function Ee(e){return T(e)&&x(e)==="optgroup"}function ye(e){return T(e)&&x(e)==="select"}function ve(e){return T(e)&&x(e)==="table"}function Se(e){return T(e)&&x(e)==="textarea"}function Te(e){var t=e.ownerDocument===null?e:e.ownerDocument,n=t.defaultView;if(n===null)throw new TypeError("no window available");return n}function xe(e){return T(e)&&x(e)==="fieldset"}function Me(e){return T(e)&&x(e)==="legend"}function Le(e){return T(e)&&x(e)==="slot"}function gt(e){return T(e)&&e.ownerSVGElement!==void 0}function Ne(e){return T(e)&&x(e)==="svg"}function Ae(e){return gt(e)&&x(e)==="title"}function P(e,t){if(T(e)&&e.hasAttribute(t)){var n=e.getAttribute(t).split(" "),r=e.getRootNode?e.getRootNode():e.ownerDocument;return n.map(function(a){return r.getElementById(a)}).filter(function(a){return a!==null})}return[]}function H(e,t){return T(e)?t.indexOf(V(e))!==-1:!1}function wt(e){return e.trim().replace(/\s\s+/g," ")}function Et(e,t){if(!T(e))return!1;if(e.hasAttribute("hidden")||e.getAttribute("aria-hidden")==="true")return!0;var n=t(e);return n.getPropertyValue("display")==="none"||n.getPropertyValue("visibility")==="hidden"}function yt(e){return H(e,["button","combobox","listbox","textbox"])||De(e,"range")}function De(e,t){if(!T(e))return!1;switch(t){case"range":return H(e,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(t,"'. This is likely a bug :("))}}function He(e,t){var n=A(e.querySelectorAll(t));return P(e,"aria-owns").forEach(function(r){n.push.apply(n,A(r.querySelectorAll(t)))}),n}function vt(e){return ye(e)?e.selectedOptions||He(e,"[selected]"):He(e,'[aria-selected="true"]')}function St(e){return H(e,G)}function Tt(e){return te(e)}function xt(e){return H(e,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function Mt(e){return!1}function Lt(e){return q(e)||Se(e)?e.value:e.textContent||""}function ke(e){var t=e.getPropertyValue("content");return/^["'].*["']$/.test(t)?t.slice(1,-1):""}function Ce(e){var t=x(e);return t==="button"||t==="input"&&e.getAttribute("type")!=="hidden"||t==="meter"||t==="output"||t==="progress"||t==="select"||t==="textarea"}function Re(e){if(Ce(e))return e;var t=null;return e.childNodes.forEach(function(n){if(t===null&&T(n)){var r=Re(n);r!==null&&(t=r)}}),t}function Nt(e){if(e.control!==void 0)return e.control;var t=e.getAttribute("for");return t!==null?e.ownerDocument.getElementById(t):Re(e)}function At(e){var t=e.labels;if(t===null)return t;if(t!==void 0)return A(t);if(!Ce(e))return null;var n=e.ownerDocument;return A(n.querySelectorAll("label")).filter(function(r){return Nt(r)===e})}function Ht(e){var t=e.assignedNodes();return t.length===0?A(e.childNodes):t}function B(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=new ge,r=typeof Map>"u"?void 0:new Map,a=Te(e),d=t.compute,i=d===void 0?"name":d,u=t.computedStyleSupportsPseudoElements,l=u===void 0?t.getComputedStyle!==void 0:u,c=t.getComputedStyle,b=c===void 0?a.getComputedStyle.bind(a):c,E=t.hidden,S=E===void 0?!1:E,f=function(w,s){if(s!==void 0)throw new Error("use uncachedGetComputedStyle directly for pseudo elements");if(r===void 0)return b(w);var y=r.get(w);if(y)return y;var M=b(w,s);return r.set(w,M),M};function h(o,w){var s="";if(T(o)&&l){var y=b(o,"::before"),M=ke(y);s="".concat(M," ").concat(s)}var L=Le(o)?Ht(o):A(o.childNodes).concat(P(o,"aria-owns"));if(L.forEach(function(k){var R=g(k,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),D=T(k)?f(k).getPropertyValue("display"):"inline",W=D!=="inline"?" ":"";s+="".concat(W).concat(R).concat(W)}),T(o)&&l){var N=b(o,"::after"),C=ke(N);s="".concat(s," ").concat(C)}return s.trim()}function p(o,w){var s=o.getAttributeNode(w);return s!==null&&!n.has(s)&&s.value.trim()!==""?(n.add(s),s.value):null}function m(o){return T(o)?p(o,"title"):null}function v(o){if(!T(o))return null;if(xe(o)){n.add(o);for(var w=A(o.childNodes),s=0;s0}).join(" ");if(q(o)&&o.type==="image"){var de=p(o,"alt");if(de!==null)return de;var fe=p(o,"title");return fe!==null?fe:"Submit Query"}if(H(o,["button"])){var me=h(o,{isEmbeddedInLabel:!1,isReferenced:!1});if(me!=="")return me}return null}function g(o,w){if(n.has(o))return"";if(!S&&Et(o,f)&&!w.isReferenced)return n.add(o),"";var s=T(o)?o.getAttributeNode("aria-labelledby"):null,y=s!==null&&!n.has(s)?P(o,"aria-labelledby"):[];if(i==="name"&&!w.isReferenced&&y.length>0)return n.add(s),y.map(function(D){return g(D,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var M=w.recursion&&yt(o)&&i==="name";if(!M){var L=(T(o)&&o.getAttribute("aria-label")||"").trim();if(L!==""&&i==="name")return n.add(o),L;if(!St(o)){var N=v(o);if(N!==null)return n.add(o),N}}if(H(o,["menu"]))return n.add(o),"";if(M||w.isEmbeddedInLabel||w.isReferenced){if(H(o,["combobox","listbox"])){n.add(o);var C=vt(o);return C.length===0?q(o)?o.value:"":A(C).map(function(D){return g(D,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(De(o,"range"))return n.add(o),o.hasAttribute("aria-valuetext")?o.getAttribute("aria-valuetext"):o.hasAttribute("aria-valuenow")?o.getAttribute("aria-valuenow"):o.getAttribute("value")||"";if(H(o,["textbox"]))return n.add(o),Lt(o)}if(xt(o)||T(o)&&w.isReferenced||Tt(o)||Mt(o)){var k=h(o,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1});if(k!=="")return n.add(o),k}if(o.nodeType===o.TEXT_NODE)return n.add(o),o.textContent||"";if(w.recursion)return n.add(o),h(o,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1});var R=m(o);return R!==null?(n.add(o),R):(n.add(o),"")}return wt(g(e,{isEmbeddedInLabel:!1,isReferenced:i==="description",recursion:!1}))}function F(e){"@babel/helpers - typeof";return F=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},F(e)}function Ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Oe(e){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{},n=P(e,"aria-describedby").map(function(d){return B(d,Oe(Oe({},t),{},{compute:"description"}))}).join(" ");if(n===""){var r=e.getAttribute("aria-description");n=r===null?"":r}if(n===""){var a=e.getAttribute("title");n=a===null?"":a}return n}function Rt(e){return H(e,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function J(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Rt(e)?"":B(e,t)}function Ie(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n.getComputedStyle,a=r===void 0?(t=e.ownerDocument.defaultView)===null||t===void 0?void 0:t.getComputedStyle:r,d=n.isSubtreeInaccessible,i=d===void 0?Vt:d;if(typeof a!="function")throw new TypeError("Owner document of the element needs to have an associated window.");if(a(e).visibility==="hidden")return!0;for(var u=e;u;){if(i(u,{getComputedStyle:a}))return!0;u=u.parentElement}return!1}function Vt(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n.getComputedStyle,a=r===void 0?(t=e.ownerDocument.defaultView)===null||t===void 0?void 0:t.getComputedStyle:r;if(typeof a!="function")throw new TypeError("Owner document of the element needs to have an associated window.");return e.hidden===!0||e.getAttribute("aria-hidden")==="true"||a(e).display==="none"}var re={"option-click":function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=g=>(g.label||g.textContent||"").replace(/\s+/g," ").trim(),h=(g,o)=>{if(g.matches(":disabled"))throw new Error("codenomad:disabled");for(let s of o)if(s.matches(":disabled"))throw new Error("codenomad:option-disabled:"+f(s));if(!g.multiple&&o.length!==1)throw new Error("codenomad:single");g.focus();let w=Array.from(g.options);if(w.some(s=>s.selected!==o.includes(s))){for(let s of w)s.selected=o.includes(s);g.dispatchEvent(new b("input",{bubbles:!0,composed:!0})),g.dispatchEvent(new b("change",{bubbles:!0}))}return Array.from(g.selectedOptions).map(f)},p=(g,o)=>{if(g.matches(":disabled"))throw new Error("codenomad:disabled");let w=Array.from(g.options),s=[];for(let y of o){let M=String(y).replace(/\s+/g," ").trim(),L=w.find(N=>f(N)===M)||w.find(N=>N.value===String(y));if(!L)throw new Error("codenomad:no-option:"+M);s.includes(L)||s.push(L)}return h(g,s)},m=t.closest("option"),v=m&&m.closest("select");if(m&&v)return h(v,[m]);if(t instanceof i)throw new Error("codenomad:is-select");return null},"programmatic-click":function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();return t instanceof u?t.click():t.dispatchEvent(new E("click",{bubbles:!0,cancelable:!0,composed:!0})),null},select:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=g=>(g.label||g.textContent||"").replace(/\s+/g," ").trim(),h=(g,o)=>{if(g.matches(":disabled"))throw new Error("codenomad:disabled");for(let s of o)if(s.matches(":disabled"))throw new Error("codenomad:option-disabled:"+f(s));if(!g.multiple&&o.length!==1)throw new Error("codenomad:single");g.focus();let w=Array.from(g.options);if(w.some(s=>s.selected!==o.includes(s))){for(let s of w)s.selected=o.includes(s);g.dispatchEvent(new b("input",{bubbles:!0,composed:!0})),g.dispatchEvent(new b("change",{bubbles:!0}))}return Array.from(g.selectedOptions).map(f)},p=(g,o)=>{if(g.matches(":disabled"))throw new Error("codenomad:disabled");let w=Array.from(g.options),s=[];for(let y of o){let M=String(y).replace(/\s+/g," ").trim(),L=w.find(N=>f(N)===M)||w.find(N=>N.value===String(y));if(!L)throw new Error("codenomad:no-option:"+M);s.includes(L)||s.push(L)}return h(g,s)},m=t instanceof d?t.control:t,v=m instanceof i?m:m&&m.closest("select");if(!v)throw new Error("codenomad:not-select");return p(v,e[0])},focus:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();if(t.matches(":disabled"))throw new Error("codenomad:disabled");if((t instanceof u||t instanceof l)&&t.focus(),t.getRootNode().activeElement!==t)throw new Error("codenomad:unfocusable");return null},describe:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t.getAttribute("role")||t.tagName.toLowerCase(),h=(t.getAttribute("aria-label")||t.getAttribute("title")||t.getAttribute("placeholder")||t.labels&&t.labels[0]&&t.labels[0].textContent||t.textContent||"").replace(/\s+/g," ").trim().slice(0,80);return f+(h?" "+JSON.stringify(h):"")},field:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=m=>m instanceof r||m instanceof a||m instanceof u&&m.isContentEditable,h=t instanceof d?t.control:t,p=h&&f(h)?h:t.querySelector('input:not([type="hidden"]), textarea, [contenteditable]:not([contenteditable="false"])');if(!p||!f(p))throw new Error("codenomad:not-editable");return p},prepare:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t,h=e[0];if(f.matches(":disabled"))throw new Error("codenomad:disabled");if(f.readOnly)throw new Error("codenomad:readonly");if(f instanceof r&&["checkbox","radio","button","submit","reset","file","image","hidden"].includes(f.type))throw new Error("codenomad:not-text");f.focus();let p=f.getRootNode().activeElement,m=!(f instanceof r||f instanceof a);if(p!==f&&!(m&&p instanceof u&&p.isContentEditable&&p.contains(f)))throw new Error("codenomad:unfocusable");if(f instanceof r&&["date","time","datetime-local","month","week","range","color"].includes(f.type))return"value";if(m)S().setBaseAndExtent(f,h?0:f.childNodes.length,f,f.childNodes.length);else if(h)f.select();else try{f.setSelectionRange(f.value.length,f.value.length)}catch{return"append"}return"insert"},"set-value":function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();if(t.matches(":disabled"))throw new Error("codenomad:disabled");if(t.readOnly)throw new Error("codenomad:readonly");let[f,h]=e,p=h?t.value+f:f;if(!(t.type==="color"?/^#[0-9a-f]{6}$/i.test(p):t.type==="range"?/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(p):p!==""&&["date","time","datetime-local","month","week","number"].includes(t.type)?(()=>{let v=n.createElement("input");return v.type=t.type,v.value=p,v.value!==""})():!0))throw new Error("codenomad:invalid-value:"+p);return p===t.value||(Object.getOwnPropertyDescriptor(r.prototype,"value").set.call(t,p),t.dispatchEvent(new b("input",{bubbles:!0,composed:!0})),t.dispatchEvent(new b("change",{bubbles:!0}))),null},"delete-selection":function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();return n.execCommand("delete"),null},"read-value":function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t instanceof r||t instanceof a?t.value:t.innerText||t.textContent||"";return t instanceof r&&t.type==="password"?"\u2022".repeat(Math.min(f.length,16)):f.length>200?f.slice(0,199)+"\u2026":f},receives:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=e[0]&&(e[0].nodeType===c.ELEMENT_NODE?e[0]:e[0].parentElement);if(!f)return null;let h=m=>{if(m.nodeType===9)try{return m.defaultView&&m.defaultView.frameElement}catch{return null}return m.assignedSlot||m.parentNode||(m.nodeType===11?m.host:null)};for(let m=f;m;m=h(m))if(m===t||m.nodeType===1&&m.localName==="label"&&(m.control===t||m.contains(t)))return null;let p=(f.getAttribute("aria-label")||f.getAttribute("title")||f.innerText||"").replace(/\s+/g," ").trim().slice(0,60);return f.tagName.toLowerCase()+(p?" "+JSON.stringify(p):"")},contains:function(...e){let t=this.nodeType===1?this:this.parentElement;if(!t||!t.isConnected)throw new Error("codenomad:gone");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=String(e[0]).replace(/\s+/g," ").trim().toLowerCase(),h=t,p=m=>String(m||"").replace(/\s+/g," ").toLowerCase();if(p(h.innerText||h.textContent).includes(f))return!0;for(let m of h.querySelectorAll("[aria-label], [title], [placeholder], input, textarea"))if([m.getAttribute("aria-label"),m.getAttribute("title"),m.getAttribute("placeholder"),m.value].some(v=>p(v).includes(f)))return!0;return!1}};function O(e,t){if(e.shadowRoot)return e.shadowRoot;let n=i=>{try{let u=(l,c,b)=>Object.getOwnPropertyDescriptor(l,c).get.call(b);return u(ShadowRoot.prototype,"host",i)!==e||u(ShadowRoot.prototype,"mode",i)!=="closed"||u(Node.prototype,"ownerDocument",i)!==e.ownerDocument?void 0:Node.prototype.getRootNode.call(i)}catch{return}},r=n(t.get(e)?.deref());if(r)return r;if(e.getAttribute("data-codenomad-shadow-boundary")!=="closed")return;let a,d=i=>{try{let u=PointerEvent.prototype.getPredictedEvents.call(i);if(u.length!==1)return;let l=Object.getOwnPropertyDescriptor(MouseEvent.prototype,"relatedTarget").get.call(u[0]),c=n(l);c&&(a=c)}catch{}};e.addEventListener("__codenomad_shadow_v1",d);try{e.dispatchEvent(new Event("__codenomad_request_shadow_v1"))}finally{e.removeEventListener("__codenomad_shadow_v1",d)}return a&&t.set(e,new WeakRef(a)),a}var Pe=e=>e.nodeType===1?e:e.parentElement;function _(e){return e===document?void 0:e.defaultView?.frameElement??void 0}var I=class extends Error{},Ot=e=>e.assignedSlot??e.parentElement??e.getRootNode().host??null;function _e(e){let t=new DOMMatrix;for(let n=e;n;n=Ot(n)){let r=n.ownerDocument.defaultView.getComputedStyle(n),a=new DOMMatrix(r.transform==="none"?void 0:r.transform);if(!a.is2D||r.perspective!=="none"||[r.rotate,r.scale,r.translate,r.offsetPath].some(i=>i&&i!=="none"))throw new I("WebKit aiming requires an invertible 2D CSS transform; perspective, independent transforms and motion paths are unsupported");let d=Number(r.getPropertyValue("zoom"))||1;t=a.scale(d).multiply(t)}if(!Number.isFinite(t.a*t.d-t.b*t.c)||Math.abs(t.a*t.d-t.b*t.c)<1e-10)throw new I("WebKit aiming requires an invertible 2D CSS transform");return t}function oe(e){let t=_e(e),n=e.ownerDocument.defaultView.getComputedStyle(e),r=b=>parseFloat(n.getPropertyValue(b))||0,a=r("width")+(n.boxSizing==="border-box"?0:r("padding-left")+r("padding-right")+r("border-left-width")+r("border-right-width")),d=r("height")+(n.boxSizing==="border-box"?0:r("padding-top")+r("padding-bottom")+r("border-top-width")+r("border-bottom-width")),i=[[0,0],[a,0],[a,d],[0,d]].map(([b,E])=>t.transformPoint({x:b,y:E})),u=e.getBoundingClientRect(),l=i.map(b=>b.x),c=i.map(b=>b.y);if(Math.abs(Math.max(...l)-Math.min(...l)-u.width)>.5||Math.abs(Math.max(...c)-Math.min(...c)-u.height)>.5)throw new I("WebKit cannot map this frame's transformed content box exactly");return t.e+=u.left-Math.min(...l),t.f+=u.top-Math.min(...c),t.translate(r("border-left-width")+r("padding-left"),r("border-top-width")+r("padding-top"))}function It(e,t,n){for(let[r,a,d]of[["x",0,1],["x",t,-1],["y",0,1],["y",n,-1]]){let i=[];for(let u=0;u=0,E=(c[r]-a)*d>=0;if(b&&i.push(l),b!==E){let S=(a-l[r])/(c[r]-l[r]);i.push({x:l.x+S*(c.x-l.x),y:l.y+S*(c.y-l.y)})}}e=i}return e}function ie(e){_e(e);for(let t=e.ownerDocument,n=_(t);n;n=_(t))oe(n),t=n.ownerDocument}function je(e){let t=Pe(e);return t?(ie(t),Array.from(t.getClientRects()).filter(n=>n.width>0&&n.height>0).flatMap(n=>{let r=[{x:n.left,y:n.top},{x:n.right,y:n.top},{x:n.right,y:n.bottom},{x:n.left,y:n.bottom}],a=t.ownerDocument;for(let E=_(a);E;E=_(a)){if(r=It(r,a.defaultView.innerWidth,a.defaultView.innerHeight),!r.length)return[];let S=oe(E);r=r.map(f=>S.transformPoint(f)),a=E.ownerDocument}let d=r.map(E=>E.x),i=r.map(E=>E.y),u=Math.min(...d),l=Math.max(...d),c=Math.min(...i),b=Math.max(...i);return[[u,c,l,c,l,b,u,b]]})):[]}function We(e){let t=Pe(e);if(t){ie(t),t.scrollIntoView({block:"center",inline:"center",behavior:"instant"});for(let n=t.ownerDocument,r=_(n);r;r=_(n))r.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"}),n=r.ownerDocument}}function $e(e,t,n){let r=document,a=null,d=new Set;for(;;){let i=r.elementFromPoint(e,t);if(!i||d.has(i))break;ie(i),a=i,d.add(i);let u=O(i,n);if(u){r=u;continue}if(i.localName==="iframe"||i.localName==="frame"){let l=null;try{l=i.contentDocument}catch{}if(l){let c=oe(i).inverse().transformPoint({x:e,y:t});e=c.x,t=c.y,r=l;continue}}break}return a??void 0}function Ge(e){let t=document.activeElement,n=new Set;for(;t&&!n.has(t);){n.add(t);let r=O(t,e)?.activeElement??t.contentDocument?.activeElement;if(!r||r===t)break;t=r}return t}var Pt=2e4,ae="__codenomadWebkitReadV1",Ke=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,le=globalThis;function ze(){return{document,token:Ke(),next:0,ids:new WeakMap,nodes:new Map,observers:new Set,observed:new WeakSet,roots:new WeakMap,hides:new WeakMap}}function Be(e){if(e.nodeType===9)try{return e.defaultView?.frameElement??null}catch{return null}return e.assignedSlot??e.parentNode??(e.nodeType===11?e.host:null)}function z(e){let t=e.nodeType===9?e:e.ownerDocument;if(!t||e.nodeType!==9&&!e.isConnected)return!1;if(t===document)return!0;try{let n=t.defaultView?.frameElement;return!!n&&n.contentDocument===t&&z(n)}catch{return!1}}function j(e,t){let n=e.ids.get(t);n!==void 0&&(e.nodes.delete(n),e.ids.delete(t));for(let r of Array.from(t.childNodes))j(e,r);if(t.nodeType===1){let r=O(t,e.roots);r&&j(e,r)}if(t.nodeType===1&&["iframe","frame"].includes(t.localName))try{let r=t.contentDocument;r&&j(e,r)}catch{}}function Je(e,t){let n=e.hides.get(t);n||(n=()=>{t===e.document?e.token=Ke():j(e,t)},e.hides.set(t,n)),t.defaultView?.addEventListener("pagehide",n)}function X(e,t){if(t.nodeType===9&&Je(e,t),e.observed.has(t))return;e.observed.add(t);let n=new MutationObserver(r=>Xe(e,r));n.observe(t,{childList:!0,subtree:!0}),e.observers.add({observer:n,root:new WeakRef(t)})}function Xe(e,t){for(let n of t)for(let r of Array.from(n.removedNodes)){if(r.nodeType===1&&r.localName==="html"&&n.target===document){for(let{observer:a}of e.observers)a.disconnect();Object.assign(e,ze(),{hides:e.hides}),X(e,document);return}j(e,r),r.nodeType===1&&r.localName==="html"&&n.target.nodeType===9&&j(e,n.target)}}function _t(e){for(let t of e.observers){Xe(e,t.observer.takeRecords());let n=t.root.deref();n?.nodeType===9&&z(n)&&Je(e,n),(!n||!z(n))&&(t.observer.disconnect(),e.observers.delete(t),n&&e.observed.delete(n))}for(let[t,n]of e.nodes){let r=n.deref();(!r||!z(r))&&(r&&e.ids.delete(r),e.nodes.delete(t))}}function ue(e,t){let n=e.ids.get(t);if(n!==void 0)return n;if(e.nodes.size>=Pt)throw new Error("WebKit semantic identity table exceeds 20000 nodes");let r=++e.next;return e.ids.set(t,r),e.nodes.set(r,new WeakRef(t)),r}function K(e,t){let n=e.nodes.get(t)?.deref();return n&&z(n)&&e.ids.get(n)===t?n:void 0}function se(e,t){return`${e.token}:${ue(e,t)}`}function qe(e,t){let n=`${e.token}:`;return t.startsWith(n)?K(e,Number(t.slice(n.length))):void 0}function Ye(e){if(Ie(e))return!0;for(let t=e;t;t=Be(t)){if(t.nodeType!==1)continue;let n=t;if(n.ownerDocument.defaultView.getComputedStyle(n).display==="none"||n.hasAttribute("inert")||n.getAttribute("aria-hidden")==="true")return!0;if(n.localName==="details"&&!n.hasAttribute("open")){let r=Array.from(n.children).find(a=>a.localName==="summary");if(e!==n&&(!r||e!==r&&!r.contains(e)))return!0}}return!1}var Y=e=>e.replace(/\s+/g," ").trim();function Q(e,t){if(e.nodeType===3)return e.textContent??"";if(e.nodeType===1&&(["script","style","template","noscript","head"].includes(e.localName)||Ye(e)))return" ";let n=e.nodeType===1?e:void 0;if(n?.localName==="br")return" ";if(n&&["iframe","frame"].includes(n.localName))try{let i=n.contentDocument?.body;return i?` ${Q(i,t)} `:" "}catch{return" "}let r=n?.localName==="slot"?n.assignedNodes({flatten:!0}):[],a=Array.from(r.length?r:(n&&O(n,t.roots))?.childNodes??e.childNodes).map(i=>Q(i,t)).join(""),d=n?.ownerDocument.defaultView.getComputedStyle(n).display??"";return/^(block|flow-root|flex|grid|table|list-item)/.test(d)?` ${a} `:a}function jt(e){let t=e.localName,n=e.type;if(e.getAttribute("role")?.trim())return V(e)??"generic";if(t==="input"){if(n==="password")return"textbox";if(n==="date"||n==="month"||n==="week")return"Date";if(n==="datetime-local")return"DateTime";if(n==="time")return"InputTime";if(n==="color")return"ColorWell"}if(t==="summary")return"DisclosureTriangle";if(t==="iframe"||t==="frame")return"Iframe";let r=V(e)??"generic";return["html","body","label","legend"].includes(t)&&(r=t==="label"?"LabelText":"generic"),r==="region"&&!J(e)&&(r="generic"),(t==="header"||t==="footer")&&e.parentElement?.closest("article,aside,main,nav,section")&&(r="generic"),r}function Wt(e){for(let t=e;t;t=Be(t))if(t.nodeType===1&&t.getAttribute("aria-disabled")==="true")return!0;return!1}function Fe(e){let t=[],n=new Set,r=(i,u)=>{let l=ue(e,i),c={id:String(l),node:l,...u?{parent:u}:{},children:[]};return t.push(c),c},a=(i,u,l)=>{let c=`boundary-${i.id}`;i.children.push(c),t.push({id:c,parent:i.id,role:"note",name:u,description:l})},d=(i,u)=>{if(n.has(i))return;if(n.add(i),i.nodeType===3){if(!Y(i.textContent??""))return;let s=r(i,u);return s.role="StaticText",s.name=i.textContent??"",s}if(i.nodeType===9){let s=i;X(e,s);let y=r(i,u);if(y.role="RootWebArea",y.name=s.title,s.body){let M=d(s.body,y.id);M&&y.children.push(M.id)}return y}if(i.nodeType!==1)return;let l=i;if(["script","style","template","noscript","head"].includes(l.localName)||Ye(l))return;let c=r(i,u),b=jt(l);c.role=b;let E=J(l),S=O(l,e.roots);!E&&S&&["button","link","checkbox","tab","heading"].includes(b)&&(E=Y(Q(l,e))),c.name=E,c.description=ne(l);let f=[],h=(s,y)=>f.push({name:s,value:y}),p=s=>l.getAttribute(`aria-${s}`),m=l,v=l.localName;["checkbox","radio","switch","menuitemcheckbox","menuitemradio"].includes(b)&&h("checked",p("checked")??(m.indeterminate?"mixed":!!m.checked)),p("pressed")!==null&&h("pressed",p("pressed")),p("expanded")!==null?h("expanded",p("expanded")==="true"):v==="select"&&!l.multiple&&l.size<=1?h("expanded",!1):v==="summary"&&l.parentElement?.localName==="details"&&h("expanded",l.parentElement.hasAttribute("open")),(p("selected")!==null||v==="option")&&h("selected",p("selected")!==null?p("selected")==="true":l.selected),(l.matches(":disabled")||Wt(l))&&h("disabled",!0),(m.required||p("required")==="true")&&h("required",!0),(m.readOnly||p("readonly")==="true")&&h("readonly",!0),(v==="select"&&l.multiple||p("multiselectable")==="true")&&h("multiselectable",!0),l.tabIndex>=0&&h("focusable",!0);for(let s of["busy","modal"])p(s)==="true"&&h(s,!0);let g=l.getRootNode();(l.ownerDocument.activeElement===l||g.nodeType===11&&g.activeElement===l)&&h("focused",!0),p("invalid")&&p("invalid")!=="false"?h("invalid",p("invalid")):p("invalid")===null&&m.validity&&!m.validity.valid&&h("invalid","true"),b==="heading"&&h("level",Number(p("level")??/^h([1-6])$/.exec(v)?.[1]??2)),v==="a"&&l.hasAttribute("href")&&h("url",l.href);let o=l.isContentEditable;if(o&&h("editable","richtext"),v==="input"&&!["checkbox","radio","button","submit","reset","image","file"].includes(m.type)||v==="textarea"?c.value=m.type==="password"?"\u2022".repeat(Math.min(m.value.length,16)):m.value:v==="select"&&!l.multiple?c.value=Array.from(l.selectedOptions).map(s=>s.label||s.textContent||"").join(" "):o?c.value=l.innerText:(p("valuetext")!==null||p("valuenow")!==null)&&(c.value=p("valuetext")??p("valuenow")),c.properties=f,v==="iframe"||v==="frame"){try{let s=l.contentDocument;if(!s)throw new Error("cross-origin");let y=d(s,c.id);y&&c.children.push(y.id)}catch{delete c.node,a(c,"Cross-origin frame (unavailable)","Frame contents cannot be traversed")}return c}if(!S&&l.getAttribute("data-codenomad-shadow-boundary")==="closed")return a(c,"Closed shadow root (unavailable)","Closed shadow capture could not be validated"),c;S&&X(e,S);let w=v==="slot"&&l.assignedNodes({flatten:!0}).length?l.assignedNodes({flatten:!0}):Array.from(S?.childNodes??l.childNodes);for(let s of w){let y=d(s,c.id);y&&c.children.push(y.id)}return c};return d(document),t}function $t(e){le[ae]?.document!==document&&(le[ae]=ze());let t=le[ae];X(t,document),_t(t);let n;try{switch(e.op){case"tree":n={nodes:Fe(t)};break;case"checkpoint":n={};break;case"release-handles":n={};break;case"resolve":{let r=K(t,e.node);n=r?{handle:se(t,r)}:{};break}case"viewport":n={width:innerWidth,height:innerHeight};break;case"geometry":{let r=K(t,e.node);n=r?{quads:je(r)}:{};break}case"scroll-into-view":{let r=K(t,e.node);r&&We(r),n={};break}case"hit-test":{let r=$e(e.x,e.y,t.roots);n=r?{node:ue(t,r)}:{};break}case"call":{if(e.function==="document-root"||e.function==="active-element"){let a=e.function==="document-root"?document.documentElement:Ge(t.roots);n=a?{handle:se(t,a)}:{};break}if(e.function==="input-acceptance"){n={value:{inputDelayMs:0}};break}if(!Object.hasOwn(re,e.function)){n={error:{code:"unsupported",driver:"webkit",operation:`call:${e.function}`}};break}let r=e.handle?qe(t,e.handle):void 0;if(!r){n={exception:"codenomad:gone"};break}if(e.function==="contains"){let a=Y(String(e.args[0])).toLowerCase();n={value:Fe(t).some(d=>{let i=d.node?K(t,d.node):void 0,u=i?.nodeType===1?i:void 0,l=u?["aria-label","title","placeholder"].map(b=>u.getAttribute(b)):[];return u&&["input","textarea"].includes(u.localName)&&l.push(u.value),[i?.nodeType===9&&i.body?Q(i.body,t):void 0,d.name,d.value,d.description,...l].some(b=>typeof b=="string"&&Y(b).toLowerCase().includes(a))})};break}try{let a=e.args.map(i=>i&&typeof i=="object"&&Object.hasOwn(i,"handle")?qe(t,i.handle):i),d=re[e.function].call(r,...a);n=e.function==="field"?{handle:se(t,d)}:{value:d}}catch(a){n={exception:String(a)}}break}default:n={error:{code:"unsupported",driver:"webkit",operation:e.op}}}}catch(r){if(!(r instanceof I))throw r;n={error:{code:"unsupported",driver:"webkit",operation:`${e.op}: ${r.message}`}}}return{document:t.token,result:n}}return nt(Gt);})(); + +return JSON.stringify(__codenomadReadModule.read(JSON.parse(request))); diff --git a/packages/server/src/automation/page/webkit/read.ts b/packages/server/src/automation/page/webkit/read.ts new file mode 100644 index 0000000000..32e99a03b7 --- /dev/null +++ b/packages/server/src/automation/page/webkit/read.ts @@ -0,0 +1,263 @@ +import { computeAccessibleName, computeAccessibleDescription, getRole, isInaccessible } from "dom-accessibility-api" +import { readCalls } from "./calls.generated" +import type { SemanticNode, PageOperation } from "../protocol" +import { shadowRoot } from "./shadow" +import { geometry, scrollIntoView, hitTest, activeElement, GeometryUnsupportedError } from "./geometry" + +type State = { + document: Document; token: string; next: number; ids: WeakMap; nodes: Map> + observers: Set<{observer: MutationObserver; root: WeakRef}>; observed: WeakSet + roots: WeakMap> + hides: WeakMapvoid> +} +const MAX_NODES = 20_000 +const KEY = "__codenomadWebkitReadV1" +const token = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}` +const globalState = globalThis as typeof globalThis & { [KEY]?: State } +function makeState(): State { return {document,token:token(),next:0,ids:new WeakMap(),nodes:new Map(),observers:new Set(),observed:new WeakSet(),roots:new WeakMap(),hides:new WeakMap()} } +function parent(node: Node): Node | null { + if (node.nodeType === 9) { try { return (node as Document).defaultView?.frameElement ?? null } catch { return null } } + return (node as Element).assignedSlot ?? node.parentNode ?? (node.nodeType === 11 ? (node as ShadowRoot).host : null) +} +function live(node: Node): boolean { + const doc = node.nodeType === 9 ? node as Document : node.ownerDocument + if (!doc || (node.nodeType !== 9 && !node.isConnected)) return false + if (doc === document) return true + try { const frame = doc.defaultView?.frameElement as HTMLIFrameElement | null; return !!frame && frame.contentDocument === doc && live(frame) } catch { return false } +} +function retire(state: State, node: Node) { + const id = state.ids.get(node) + if (id !== undefined) { state.nodes.delete(id); state.ids.delete(node) } + for (const child of Array.from(node.childNodes)) retire(state, child) + if (node.nodeType === 1) { const root=shadowRoot(node as Element,state.roots); if(root) retire(state,root) } + if (node.nodeType === 1 && ["iframe","frame"].includes((node as Element).localName)) { + try { const doc=(node as HTMLIFrameElement).contentDocument; if(doc) retire(state,doc) } catch { /* opaque frame */ } + } +} +function watchDocument(state:State,doc:Document) { + let hide=state.hides.get(doc) + if(!hide) {hide=()=>{if(doc===state.document)state.token=token();else retire(state,doc)};state.hides.set(doc,hide)} + doc.defaultView?.addEventListener('pagehide',hide) +} +function watch(state: State, root: Node) { + if(root.nodeType===9) watchDocument(state,root as Document) + if (state.observed.has(root)) return + state.observed.add(root) + const observer = new MutationObserver(records => retireRecords(state,records)) + observer.observe(root,{childList:true,subtree:true}) + state.observers.add({observer,root:new WeakRef(root)}) +} +function retireRecords(state: State, records: MutationRecord[]) { + for (const record of records) for (const removed of Array.from(record.removedNodes)) { + if (removed.nodeType === 1 && (removed as Element).localName === "html" && record.target === document) { + for (const {observer} of state.observers) observer.disconnect() + Object.assign(state,makeState(),{hides:state.hides}) + watch(state,document) + return + } + retire(state,removed) + if (removed.nodeType === 1 && (removed as Element).localName === "html" && record.target.nodeType === 9) retire(state,record.target) + } +} +function flush(state: State) { + for (const entry of state.observers) { + retireRecords(state,entry.observer.takeRecords()) + const root=entry.root.deref() + if(root?.nodeType===9 && live(root)) watchDocument(state,root as Document) + if (!root || !live(root)) {entry.observer.disconnect();state.observers.delete(entry);if(root)state.observed.delete(root)} + } + for (const [id, reference] of state.nodes) { const node = reference.deref(); if (!node || !live(node)) { if (node) state.ids.delete(node); state.nodes.delete(id) } } +} +function id(state: State,node: Node): number { + const existing=state.ids.get(node) + if (existing !== undefined) return existing + if (state.nodes.size >= MAX_NODES) throw new Error("WebKit semantic identity table exceeds 20000 nodes") + const value=++state.next; state.ids.set(node,value); state.nodes.set(value,new WeakRef(node)); return value +} +function lookup(state: State,value: number): Node | undefined { const node=state.nodes.get(value)?.deref(); return node && live(node) && state.ids.get(node) === value ? node : undefined } +function handle(state: State,node: Node): string { return `${state.token}:${id(state,node)}` } +function fromHandle(state: State,value: string): Node | undefined { const prefix=`${state.token}:`; return value.startsWith(prefix) ? lookup(state,Number(value.slice(prefix.length))) : undefined } +function hidden(element: Element): boolean { + if (isInaccessible(element)) return true + for (let node: Node | null=element; node; node=parent(node)) { + if (node.nodeType !== 1) continue + const item=node as Element + if (item.ownerDocument.defaultView!.getComputedStyle(item).display === "none") return true + if (item.hasAttribute("inert") || item.getAttribute("aria-hidden") === "true") return true + if (item.localName === "details" && !item.hasAttribute("open")) { + const summary=Array.from(item.children).find(child=>child.localName === "summary") + if (element !== item && (!summary || (element !== summary && !summary.contains(element)))) return true + } + } + return false +} +const collapse=(text: string)=>text.replace(/\s+/g," ").trim() +function composedText(root: Node,state:State): string { + if (root.nodeType === 3) return root.textContent ?? "" + if (root.nodeType === 1 && (["script","style","template","noscript","head"].includes((root as Element).localName) || hidden(root as Element))) return " " + const element=root.nodeType === 1 ? root as Element : undefined + if (element?.localName === "br") return " " + if (element && ["iframe","frame"].includes(element.localName)) { + try { const body=(element as HTMLIFrameElement).contentDocument?.body; return body ? ` ${composedText(body,state)} ` : " " } catch { return " " } + } + const assigned=element?.localName === "slot" ? (element as HTMLSlotElement).assignedNodes({flatten:true}) : [] + const text=Array.from(assigned.length ? assigned : (element && shadowRoot(element,state.roots))?.childNodes ?? root.childNodes).map(node=>composedText(node,state)).join("") + const display=element?.ownerDocument.defaultView!.getComputedStyle(element).display ?? "" + return /^(block|flow-root|flex|grid|table|list-item)/.test(display) ? ` ${text} ` : text +} +function role(element: Element): string { + const tag=element.localName, type=(element as HTMLInputElement).type + if (element.getAttribute("role")?.trim()) return getRole(element) ?? "generic" + if (tag === "input") { + if (type === "password") return "textbox" + if (type === "date" || type === "month" || type === "week") return "Date" + if (type === "datetime-local") return "DateTime" + if (type === "time") return "InputTime" + if (type === "color") return "ColorWell" + } + if (tag === "summary") return "DisclosureTriangle" + if (tag === "iframe" || tag === "frame") return "Iframe" + let value=getRole(element) ?? "generic" + if (["html","body","label","legend"].includes(tag)) value=tag === "label" ? "LabelText" : "generic" + if (value === "region" && !computeAccessibleName(element)) value="generic" + if ((tag === "header" || tag === "footer") && element.parentElement?.closest("article,aside,main,nav,section")) value="generic" + return value +} +function ariaDisabled(element: Element): boolean { + for (let node: Node | null=element; node; node=parent(node)) { + if (node.nodeType === 1 && (node as Element).getAttribute("aria-disabled") === "true") return true + } + return false +} +function semanticTree(state: State): SemanticNode[] { + const nodes: SemanticNode[]=[], seen=new Set() + const add=(node: Node, parentId?: string): SemanticNode => { + const key=id(state,node), result: SemanticNode={id:String(key),node:key,...(parentId ? {parent:parentId}:{}),children:[]} + nodes.push(result); return result + } + const boundary=(owner: SemanticNode,name: string,description: string) => { + const key=`boundary-${owner.id}` + owner.children!.push(key) + nodes.push({id:key,parent:owner.id,role:"note",name,description}) + } + const visit=(node: Node,parentId?: string): SemanticNode | undefined => { + if (seen.has(node)) return + seen.add(node) + if (node.nodeType === 3) { + if (!collapse(node.textContent ?? "")) return + const result=add(node,parentId); result.role="StaticText"; result.name=node.textContent ?? ""; return result + } + if (node.nodeType === 9) { + const doc=node as Document; watch(state,doc) + const result=add(node,parentId); result.role="RootWebArea"; result.name=doc.title + if (doc.body) { const child=visit(doc.body,result.id); if (child) result.children!.push(child.id!) } + return result + } + if (node.nodeType !== 1) return + const element=node as Element + if (["script","style","template","noscript","head"].includes(element.localName) || hidden(element)) return + const result=add(node,parentId), currentRole=role(element) + result.role=currentRole + let name=computeAccessibleName(element) + const shadow=shadowRoot(element,state.roots) + if (!name && shadow && ["button","link","checkbox","tab","heading"].includes(currentRole)) name=collapse(composedText(element,state)) + result.name=name + result.description=computeAccessibleDescription(element) + const properties: NonNullable=[] + const property=(name: string,value: unknown)=>properties.push({name,value}) + const attr=(name: string)=>element.getAttribute(`aria-${name}`) + const input=element as HTMLInputElement, tag=element.localName + if (["checkbox","radio","switch","menuitemcheckbox","menuitemradio"].includes(currentRole)) property("checked", attr("checked") ?? (input.indeterminate ? "mixed" : !!input.checked)) + if (attr("pressed") !== null) property("pressed",attr("pressed")) + if (attr("expanded") !== null) property("expanded",attr("expanded") === "true") + else if (tag === "select" && !(element as HTMLSelectElement).multiple && (element as HTMLSelectElement).size <= 1) property("expanded",false) + else if (tag === "summary" && element.parentElement?.localName === "details") property("expanded",element.parentElement.hasAttribute("open")) + if (attr("selected") !== null || tag === "option") property("selected",attr("selected") !== null ? attr("selected") === "true" : (element as HTMLOptionElement).selected) + if (element.matches(":disabled") || ariaDisabled(element)) property("disabled",true) + if (input.required || attr("required") === "true") property("required",true) + if (input.readOnly || attr("readonly") === "true") property("readonly",true) + if (tag === "select" && (element as HTMLSelectElement).multiple || attr("multiselectable") === "true") property("multiselectable",true) + if ((element as HTMLElement).tabIndex >= 0) property("focusable",true) + for (const state of ["busy","modal"]) if(attr(state) === "true") property(state,true) + const root=element.getRootNode() + if (element.ownerDocument.activeElement === element || root.nodeType === 11 && (root as ShadowRoot).activeElement === element) property("focused",true) + if (attr("invalid") && attr("invalid") !== "false") property("invalid",attr("invalid")) + else if (attr("invalid") === null && input.validity && !input.validity.valid) property("invalid","true") + if (currentRole === "heading") property("level",Number(attr("level") ?? /^h([1-6])$/.exec(tag)?.[1] ?? 2)) + if (tag === "a" && element.hasAttribute("href")) property("url",(element as HTMLAnchorElement).href) + const editable=(element as HTMLElement).isContentEditable + if (editable) property("editable","richtext") + if ((tag === "input" && !["checkbox","radio","button","submit","reset","image","file"].includes(input.type)) || tag === "textarea") result.value=input.type === "password" ? "•".repeat(Math.min(input.value.length,16)) : input.value + else if (tag === "select" && !(element as HTMLSelectElement).multiple) result.value=Array.from((element as HTMLSelectElement).selectedOptions).map(option=>option.label||option.textContent||"").join(" ") + else if (editable) result.value=(element as HTMLElement).innerText + else if (attr("valuetext") !== null || attr("valuenow") !== null) result.value=attr("valuetext") ?? attr("valuenow") + result.properties=properties + if (tag === "iframe" || tag === "frame") { + try { + const child=(element as HTMLIFrameElement).contentDocument + if (!child) throw new Error("cross-origin") + const nested=visit(child,result.id); if (nested) result.children!.push(nested.id!) + } catch { delete result.node; boundary(result,"Cross-origin frame (unavailable)","Frame contents cannot be traversed") } + return result + } + if (!shadow && element.getAttribute("data-codenomad-shadow-boundary") === "closed") { boundary(result,"Closed shadow root (unavailable)","Closed shadow capture could not be validated"); return result } + if (shadow) watch(state,shadow) + const children=tag === "slot" && (element as HTMLSlotElement).assignedNodes({flatten:true}).length ? (element as HTMLSlotElement).assignedNodes({flatten:true}) : Array.from(shadow?.childNodes ?? element.childNodes) + for (const child of children) { const nested=visit(child,result.id); if (nested) result.children!.push(nested.id!) } + return result + } + visit(document) + return nodes +} + +export function read(operation: PageOperation): {document: string; result: Record} { + if (globalState[KEY]?.document !== document) { + globalState[KEY]=makeState() + } + const state=globalState[KEY]! + watch(state,document); flush(state) + let result: Record + try { switch (operation.op) { + case "tree": result={nodes:semanticTree(state)}; break + case "checkpoint": result={}; break + case "release-handles": result={}; break // All entries are weak; numeric document identity remains stable. + case "resolve": { const node=lookup(state,operation.node); result=node ? {handle:handle(state,node)} : {}; break } + case "viewport": result={width:innerWidth,height:innerHeight}; break + case "geometry": {const node=lookup(state,operation.node);result=node ? {quads:geometry(node)} : {};break} + case "scroll-into-view": {const node=lookup(state,operation.node);if(node)scrollIntoView(node);result={};break} + case "hit-test": {const node=hitTest(operation.x,operation.y,state.roots);result=node ? {node:id(state,node)} : {};break} + case "call": { + if (operation.function === "document-root" || operation.function === "active-element") { + const node=operation.function === "document-root" ? document.documentElement : activeElement(state.roots) + result=node ? {handle:handle(state,node)} : {}; break + } + if (operation.function === "input-acceptance") { result={value:{inputDelayMs:0}}; break } + if (!Object.hasOwn(readCalls,operation.function)) { result={error:{code:"unsupported",driver:"webkit",operation:`call:${operation.function}`}}; break } + const node=operation.handle ? fromHandle(state,operation.handle) : undefined + if (!node) { result={exception:"codenomad:gone"}; break } + if(operation.function === "contains") { + const needle=collapse(String(operation.args[0])).toLowerCase() + result={value:semanticTree(state).some(item=>{ + const target=item.node ? lookup(state,item.node) : undefined + const element=target?.nodeType === 1 ? target as Element : undefined + const attributes=element ? ['aria-label','title','placeholder'].map(name=>element.getAttribute(name)) : [] + if(element && ['input','textarea'].includes(element.localName)) attributes.push((element as HTMLInputElement).value) + const text=target?.nodeType === 9 && (target as Document).body ? composedText((target as Document).body,state) : undefined + return [text,item.name,item.value,item.description,...attributes].some(value=>typeof value === "string" && collapse(value).toLowerCase().includes(needle)) + })} + break + } + try { + const args=operation.args.map(arg=>arg && typeof arg === "object" && Object.hasOwn(arg,"handle") ? fromHandle(state,(arg as {handle:string}).handle) : arg) + const value=readCalls[operation.function as keyof typeof readCalls].call(node,...args) + result=operation.function === "field" ? {handle:handle(state,value as Node)} : {value} + } catch (error) { result={exception:String(error)} } + break + } + default: result={error:{code:"unsupported",driver:"webkit",operation:operation.op}} + } } catch(error) { + if(!(error instanceof GeometryUnsupportedError)) throw error + result={error:{code:"unsupported",driver:"webkit",operation:`${operation.op}: ${error.message}`}} + } + return {document:state.token,result} +} diff --git a/packages/server/src/automation/page/webkit/shadow.ts b/packages/server/src/automation/page/webkit/shadow.ts new file mode 100644 index 0000000000..cc6558f4ee --- /dev/null +++ b/packages/server/src/automation/page/webkit/shadow.ts @@ -0,0 +1,31 @@ +/** Page-world responses are hints: native DOM getters enforce brand/host/document. */ +export function shadowRoot(host: Element, roots: WeakMap>): ShadowRoot | undefined { + if (host.shadowRoot) return host.shadowRoot + const validate = (candidate: unknown): ShadowRoot | undefined => { + try { + const get = (prototype: object, key: string, value: unknown) => Object.getOwnPropertyDescriptor(prototype,key)!.get!.call(value) + if (get(ShadowRoot.prototype,"host",candidate) !== host || get(ShadowRoot.prototype,"mode",candidate) !== "closed" + || get(Node.prototype,"ownerDocument",candidate) !== host.ownerDocument) return + // Rewrap the native object in this isolated realm before consuming it. + return Node.prototype.getRootNode.call(candidate) as ShadowRoot + } catch { return undefined } + } + const cached=validate(roots.get(host)?.deref()) + if(cached) return cached + if(host.getAttribute("data-codenomad-shadow-boundary") !== "closed") return + let root: ShadowRoot | undefined + const receive=(event:Event)=>{ + try { + const carriers=PointerEvent.prototype.getPredictedEvents.call(event) + if(carriers.length!==1) return + const candidate=Object.getOwnPropertyDescriptor(MouseEvent.prototype,"relatedTarget")!.get!.call(carriers[0]) + const validated=validate(candidate) + if(validated) root=validated + } catch { /* Native brands reject arbitrary page replies. */ } + } + host.addEventListener("__codenomad_shadow_v1",receive) + try { host.dispatchEvent(new Event("__codenomad_request_shadow_v1")) } + finally { host.removeEventListener("__codenomad_shadow_v1",receive) } + if(root) roots.set(host,new WeakRef(root)) + return root +} diff --git a/packages/server/src/developer-cdp.ts b/packages/server/src/developer-cdp.ts index 14efd0edcc..a3e564ded9 100644 --- a/packages/server/src/developer-cdp.ts +++ b/packages/server/src/developer-cdp.ts @@ -1,5 +1,6 @@ import { WebSocket } from "undici" import { bindRefs, performAction, snapshotPage, type PageActionResult, type PageSession } from "./automation/page/actions" +import { cdpSession } from "./automation/page/cdp-driver" import type { RefAction } from "./automation/page/parse" import { RefTable } from "./automation/page/refs" import { SnapshotScopeError } from "./automation/page/snapshot" @@ -176,11 +177,8 @@ export class DeveloperCdp { } private session(state: RunState, epoch: number, message: string): PageSession { - return { - channel: { send: (method, params) => this.command(state, method, params) }, - checkpoint: () => this.assertContextCurrent(state, epoch, message), - markAutomation: true, - } + return cdpSession({ send: (method, params) => this.command(state, method, params) }, + () => this.assertContextCurrent(state, epoch, message), true) } async screenshot(identity: DeveloperCdpIdentity): Promise { diff --git a/packages/server/src/native-parent.test.ts b/packages/server/src/native-parent.test.ts index ba5d6e51fb..3f7b11a6fe 100644 --- a/packages/server/src/native-parent.test.ts +++ b/packages/server/src/native-parent.test.ts @@ -2,6 +2,33 @@ import assert from "node:assert/strict" import test from "node:test" import { NativeParent, NATIVE_REQUEST_PREFIX, NATIVE_RESPONSE_PREFIX } from "./native-parent" +test("WebKit transport exposes browser automation and respects explicit missing capabilities", () => { + const previous = process.env.CODENOMAD_TAURI_WEBKIT + const previousCapability = process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION + try { + process.env.CODENOMAD_TAURI_WEBKIT = "1" + delete process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION + assert.equal(new NativeParent(undefined, true).browserAutomationUnavailable, false) + assert.equal(new NativeParent(undefined, false).browserAutomationUnavailable, false) + process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION = "1" + assert.equal(new NativeParent(undefined, true).browserAutomationUnavailable, false) + process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION = "0" + assert.equal(new NativeParent(undefined, true).browserAutomationUnavailable, true) + assert.equal(new NativeParent(undefined, false).browserAutomationUnavailable, true) + } finally { + if (previous === undefined) delete process.env.CODENOMAD_TAURI_WEBKIT + else process.env.CODENOMAD_TAURI_WEBKIT = previous + if (previousCapability === undefined) delete process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION + else process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION = previousCapability + } +}) + +test("a genuinely unavailable native transport rejects requests", async () => { + const parent = new NativeParent({ write: () => { throw new Error("Unexpected native request") } }, false, true) + assert.equal(parent.browserAutomationUnavailable, true) + await assert.rejects(parent.request("browser.probe", {}), /Native control is unavailable/) +}) + test("matches native responses to requests and rejects pending work on shutdown", async () => { const lines: string[] = [] const parent = new NativeParent({ write: (line: string | Uint8Array) => { lines.push(String(line)); return true } }, true) @@ -16,3 +43,17 @@ test("matches native responses to requests and rejects pending work on shutdown" parent.close() await assert.rejects(pending, /shutting down/) }) + +test("late native replies cannot settle a subsequent request", async () => { + const lines: string[] = [] + const parent = new NativeParent({ write: line => { lines.push(String(line)); return true } }, true) + const first = parent.request("browser.probe", {}, 5) + const old = JSON.parse(lines[0].slice(NATIVE_REQUEST_PREFIX.length)) + await assert.rejects(first, /timed out/) + const second = parent.request("browser.probe", {}, 1000) + const current = JSON.parse(lines[1].slice(NATIVE_REQUEST_PREFIX.length)) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: old.id, ok: true, result: "stale" })}`) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: current.id, ok: true, result: "current" })}`) + assert.equal(await second, "current") + parent.close() +}) diff --git a/packages/server/src/native-parent.ts b/packages/server/src/native-parent.ts index 3f7f6d300b..77ec604932 100644 --- a/packages/server/src/native-parent.ts +++ b/packages/server/src/native-parent.ts @@ -26,6 +26,7 @@ export class NativeParent { constructor( private readonly output: Pick = process.stdout, readonly available = process.env.CODENOMAD_NATIVE_PARENT === "1", + readonly browserAutomationUnavailable = process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION === "0", ) {} request(method: string, params: unknown, timeoutMs = DEFAULT_TIMEOUT_MS): Promise { diff --git a/packages/server/src/opencode/automation-plugin.test.ts b/packages/server/src/opencode/automation-plugin.test.ts index 8c0bc4bf9f..930e801822 100644 --- a/packages/server/src/opencode/automation-plugin.test.ts +++ b/packages/server/src/opencode/automation-plugin.test.ts @@ -20,6 +20,7 @@ import { removeLegacyAutomationPlugin, setupAutomationPlugin, sendMissionInput, + executeBrowserTool, } from "./automation-plugin" type ToolDefinition = { @@ -27,13 +28,13 @@ type ToolDefinition = { execute(input: unknown, context: { sessionID: string }): Promise<{ content: unknown }> } -function listen(handler: (body: Record) => Promise>) { +function listen(handler: (body: Record, response: http.ServerResponse) => Promise>) { return new Promise<{ server: http.Server; url: string }>((resolve) => { const server = http.createServer((request, response) => { const chunks: Buffer[] = [] request.on("data", (chunk) => chunks.push(Buffer.from(chunk))) request.on("end", () => { - void handler(JSON.parse(Buffer.concat(chunks).toString("utf8"))).then((body) => { + void handler(JSON.parse(Buffer.concat(chunks).toString("utf8")), response).then((body) => { response.setHeader("content-type", "application/json") response.end(JSON.stringify(body)) }) @@ -178,6 +179,29 @@ test("mission discovery waits for cold ownership validation and still rejects co } }) +test("browser discovery executes native WebKit open, snapshot and screenshot actions", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-webkit-browser-")) + const restore = isolateAutomationBridgeRegistry(root) + const calls: unknown[] = [] + let remove: (() => Promise) | undefined + const { server, url } = await listen(async (body, response) => { + calls.push(body.mode) + return { result: body.mode === "browser-execute" ? { text: "WebKit native result" } : { available: true } } + }) + try { + remove = await publishAutomationBridge(createAutomationBridgeRegistration(url)) + for (const command of [{ action: "open", url: "https://example.com" }, { action: "snapshot" }, { action: "screenshot" }]) { + assert.match((await executeBrowserTool("ses_webkit", command)).content as string, /WebKit native result/) + } + assert.deepEqual(calls, ["browser-claim", "browser-execute", "browser-probe", "browser-execute", "browser-probe", "browser-execute"]) + } finally { + await remove?.() + await closeServer(server) + restore() + await rm(root, { recursive: true, force: true }) + } +}) + test("validates browser actions", () => { assert.deepEqual(parseBrowserAction({ action: "open", url: "https://example.com" }), { action: "open", diff --git a/packages/server/src/opencode/automation-plugin.ts b/packages/server/src/opencode/automation-plugin.ts index 0ba0fc8634..2c83a55faf 100644 --- a/packages/server/src/opencode/automation-plugin.ts +++ b/packages/server/src/opencode/automation-plugin.ts @@ -558,8 +558,8 @@ async function probeBrowserBridges( for (let index = 0; index < active.length && found.length < 2; index += PROBE_CONCURRENCY) { const batch = await Promise.all(active.slice(index, index + PROBE_CONCURRENCY).map(async (registration) => { try { - return (await callBridge(registration, { mode, sessionID, ...(purpose ? { purpose } : {}) }, timeoutMs)).status === 200 - ? registration : undefined + const response = await callBridge(registration, { mode, sessionID, ...(purpose ? { purpose } : {}) }, timeoutMs) + return response.status === 200 ? registration : undefined } catch { return undefined } diff --git a/packages/server/src/server/routes/automation-plugin.test.ts b/packages/server/src/server/routes/automation-plugin.test.ts index 9d7e2b1b97..d937ae7454 100644 --- a/packages/server/src/server/routes/automation-plugin.test.ts +++ b/packages/server/src/server/routes/automation-plugin.test.ts @@ -10,7 +10,11 @@ test("a slow unrelated workspace cannot hide an already verified automation owne const unrelated = new Promise(resolve => { unblock = resolve }) t.after(async () => { unblock(); await app.close() }) registerAutomationPluginRoute(app, { - authManager: { isLoopbackRequest: () => true }, bridgeToken: "fixture", nativeParent: { available: true }, developerCdp: {}, + authManager: { isLoopbackRequest: () => true }, bridgeToken: "fixture", + nativeParent: { available: true, request: async (method: string) => { + assert.equal(method, "browser.probe") + throw new Error("No visible local browser target for this session") + } }, developerCdp: {}, workspaceManager: { getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), list: () => [{ id: "slow-unrelated" }, { id: "owner" }], @@ -19,7 +23,7 @@ test("a slow unrelated workspace cannot hide an already verified automation owne } as never) const response = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, headers: { "x-codenomad-automation-token": "fixture" }, payload: { mode: "browser-claim", sessionID: "ses_owner" } }) - assert.equal(response.statusCode, 200) + assert.equal(response.statusCode, 200, "a supported host can claim a session before opening its first preview") }) test("targets the inspected window independently of the visible conversation", async () => { @@ -143,9 +147,9 @@ test("browser works with an unavailable developer target and unrelated inventory available: true, request: async (method: string, params: any) => { nativeCalls.push({ method, params }) - if (method === "browser.page.begin") return { generation: "preview-document", url: "https://example.com/" } - if (method === "browser.page.send" && params.method === "Accessibility.getFullAXTree") { - return { nodes: [{ nodeId: "one", backendDOMNodeId: 42, role: { value: "button" }, name: { value: "Preview action" } }] } + if (method === "browser.page.begin") return { generation: "preview-document", url: "https://example.com/", driver: "cdp", contractVersion: 1 } + if (method === "browser.page.send" && params.operation?.op === "tree") { + return { nodes: [{ id: "one", node: 42, role: "button", name: "Preview action" }] } } return method === "developer.status" ? { status: { state: "stopped" } } : method === "browser.probe" ? { available: true } : { url: "https://example.com/" } @@ -193,6 +197,42 @@ test("browser works with an unavailable developer target and unrelated inventory await app.close() }) +test("WebKit browser claims, probes and native actions succeed independently of developer CDP", async t => { + const app = Fastify({ logger: false }) + t.after(() => app.close()) + const nativeCalls: string[] = [] + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: "secret", + nativeParent: { available: true, browserAutomationUnavailable: false, request: async (method: string) => { + nativeCalls.push(method) + return method === "browser.probe" ? { available: true } : { text: "WebKit native result" } + } }, + workspaceManager: { + getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), + list: () => [{ id: "owner" }], ownsLocation: async () => true, + }, + } as never) + const request = (body: Record) => app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": "secret" }, payload: { sessionID: "owned", ...body } }) + + assert.equal((await request({ mode: "browser-claim", purpose: "mission" })).statusCode, 200) + assert.deepEqual(nativeCalls, []) + const claim = await request({ mode: "browser-claim" }) + assert.equal(claim.statusCode, 200) + assert.deepEqual(nativeCalls, [], "claim can open the first preview without an existing target") + const probe = await request({ mode: "browser-probe" }) + assert.equal(probe.statusCode, 200) + assert.equal(probe.json().result.available, true) + for (const command of [ + { action: "open", url: "https://example.com" }, { action: "navigate", url: "https://example.com" }, + { action: "screenshot" }, + ]) { + const response = await request({ mode: "browser-execute", command }) + assert.equal(response.statusCode, 200, command.action) + assert.equal(response.json().result.text, "WebKit native result", command.action) + } +}) + test("a backend without a desktop host claims owned sessions for Mission dispatch only", async () => { const app = Fastify({ logger: false }) const nativeCalls: string[] = [] diff --git a/packages/server/src/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 5038a6f2e7..234f4f5066 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -153,6 +153,11 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa } } + if (["browser-claim", "browser-probe", "browser-execute"].includes(String(body.mode)) && !(body.mode === "browser-claim" && body.purpose === "mission") + && deps.nativeParent.browserAutomationUnavailable) { + return reply.code(409).send({ code: "unsupported", error: "Browser automation is unavailable in this host" }) + } + if (body.mode === "browser-claim") { // Without a desktop host this backend owns sessions only for Mission // dispatch; claiming browsers too would hand the browser tools an owner diff --git a/packages/server/src/shutdown.test.ts b/packages/server/src/shutdown.test.ts index 7cd18a537a..d4cc521f4b 100644 --- a/packages/server/src/shutdown.test.ts +++ b/packages/server/src/shutdown.test.ts @@ -104,6 +104,23 @@ describe("CLI shutdown signal registration", () => { } }) + it("preserves UTF-8 native response text split across stdin buffers", async () => { + const source = new PassThrough() + const lines: string[] = [] + const parent = new NativeParent({ write: line => { lines.push(String(line)); return true } }, true) + installShutdownStdinHandler(source, async () => {}, line => parent.handleLine(line)) + try { + const pending = parent.request("browser.probe", {}) + const { id } = JSON.parse(lines[0].slice(NATIVE_REQUEST_PREFIX.length)) + const response = Buffer.from(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result: "é漢🙂" })}\n`) + for (const byte of response) source.write(Buffer.from([byte])) + assert.equal(await pending, "é漢🙂") + } finally { + parent.close() + source.destroy() + } + }) + it("allows a real piped process to exit naturally after the shutdown command", { timeout: 5_000 }, async () => { const moduleUrl = new URL("./shutdown.ts", import.meta.url).href const child = spawn(process.execPath, ["--import", "tsx", "--input-type=module", "-e", ` diff --git a/packages/server/src/shutdown.ts b/packages/server/src/shutdown.ts index 7b7e96d9b0..9d3d7d6817 100644 --- a/packages/server/src/shutdown.ts +++ b/packages/server/src/shutdown.ts @@ -1,3 +1,5 @@ +import { StringDecoder } from "node:string_decoder" + type ShutdownLogger = Pick type ShutdownOperation = () => void | Promise @@ -30,9 +32,10 @@ export function installShutdownStdinHandler( handleLine?: (line: string) => boolean, ): void { let buffer = "" + const decoder = new StringDecoder("utf8") let requested = false const onData = (chunk: Buffer | string) => { - buffer += chunk.toString() + buffer += decoder.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk) const lines = buffer.split(/\r?\n/) buffer = lines.pop() ?? "" let shutdownRequested = false diff --git a/packages/server/src/workspaces/host-opencode-service.test.ts b/packages/server/src/workspaces/host-opencode-service.test.ts index 903b60f415..f774566fa9 100644 --- a/packages/server/src/workspaces/host-opencode-service.test.ts +++ b/packages/server/src/workspaces/host-opencode-service.test.ts @@ -29,13 +29,15 @@ describe("HostOpenCodeService", () => { it("never hands the desktop profile scope or backend hand-offs to the shared daemon", () => { const keys = ["CODENOMAD_UPDATE_CHANNEL", "CODENOMAD_PROFILE_CONFIG_IDENTITY", - "CODENOMAD_PROFILE", "CLI_CONFIG", "CODENOMAD_NATIVE_PARENT", "ELECTRON_RUN_AS_NODE", "ELECTRON_NO_ASAR", "OPENCODE_DB"] + "CODENOMAD_PROFILE", "CLI_CONFIG", "CODENOMAD_NATIVE_PARENT", "CODENOMAD_NATIVE_BROWSER_AUTOMATION", "CODENOMAD_TAURI_WEBKIT", "ELECTRON_RUN_AS_NODE", "ELECTRON_NO_ASAR", "OPENCODE_DB"] const saved = Object.fromEntries(keys.map(key => [key, process.env[key]])) try { process.env.CODENOMAD_UPDATE_CHANNEL = "stable" process.env.CODENOMAD_PROFILE_CONFIG_IDENTITY = "owned-config.yaml" process.env.CLI_CONFIG = "/owned/config.yaml" process.env.CODENOMAD_NATIVE_PARENT = "1" + process.env.CODENOMAD_NATIVE_BROWSER_AUTOMATION = "0" + process.env.CODENOMAD_TAURI_WEBKIT = "1" process.env.ELECTRON_RUN_AS_NODE = "1" process.env.ELECTRON_NO_ASAR = "1" const environment = daemonProcessEnvironment({ FIXTURE: "kept", CODENOMAD_PROFILE: "team", OPENCODE_DB: "/x.db" }) diff --git a/packages/server/src/workspaces/host-opencode-service.ts b/packages/server/src/workspaces/host-opencode-service.ts index 89a95b7f70..ae8eccd111 100644 --- a/packages/server/src/workspaces/host-opencode-service.ts +++ b/packages/server/src/workspaces/host-opencode-service.ts @@ -42,6 +42,8 @@ const DAEMON_EXCLUDED_ENVIRONMENT = [ "CODENOMAD_PROFILE_CONFIG_IDENTITY", "CLI_CONFIG", "CODENOMAD_NATIVE_PARENT", + "CODENOMAD_NATIVE_BROWSER_AUTOMATION", + "CODENOMAD_TAURI_WEBKIT", "ELECTRON_RUN_AS_NODE", "ELECTRON_NO_ASAR", ] diff --git a/packages/tauri-app/Cargo.lock b/packages/tauri-app/Cargo.lock index 161be804a6..e161ca2122 100644 --- a/packages/tauri-app/Cargo.lock +++ b/packages/tauri-app/Cargo.lock @@ -534,13 +534,17 @@ version = "1.0.1" dependencies = [ "anyhow", "base64 0.22.1", + "cc", "dirs 5.0.1", "fs2", "gtk", "keepawake", "libc", + "objc2", + "objc2-web-kit", "open", "parking_lot", + "pkg-config", "plist", "regex", "reqwest 0.12.28", @@ -569,6 +573,27 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "codenomad-webkit-capabilities-fixture" +version = "0.1.0" +dependencies = [ + "cc", + "dirs 5.0.1", + "gtk", + "objc2", + "pkg-config", + "serde", + "serde_json", + "sha2", + "tauri", + "tauri-plugin-dialog", + "tempfile", + "uuid", + "webkit2gtk", + "webview2-com", + "windows-core", +] + [[package]] name = "codenomad-windows-input-fixture" version = "0.1.0" @@ -937,7 +962,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1114,7 +1139,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2374,7 +2399,7 @@ dependencies = [ "png", "serde", "thiserror 2.0.18", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3407,7 +3432,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3466,7 +3491,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3866,7 +3891,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4433,8 +4458,6 @@ dependencies = [ [[package]] name = "tauri-runtime-wry" version = "2.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f" dependencies = [ "gtk", "http", @@ -4486,7 +4509,7 @@ dependencies = [ "serde_with", "swift-rs", "thiserror 2.0.18", - "toml 0.9.12+spec-1.1.0", + "toml 1.2.1+spec-1.1.0", "url", "urlpattern", "uuid", @@ -4525,7 +4548,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix 1.1.4", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4886,7 +4909,7 @@ dependencies = [ "png", "serde", "thiserror 2.0.18", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4921,7 +4944,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5346,7 +5369,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -5367,7 +5390,7 @@ dependencies = [ "objc2-foundation", "objc2-quartz-core", "raw-window-handle", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "windows-version", ] @@ -5932,8 +5955,6 @@ checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" [[package]] name = "wry" version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9" dependencies = [ "base64 0.23.1", "block2", diff --git a/packages/tauri-app/Cargo.toml b/packages/tauri-app/Cargo.toml index 26ca87c726..11f838c0a9 100644 --- a/packages/tauri-app/Cargo.toml +++ b/packages/tauri-app/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["src-tauri", "tests/windows-input", "tests/windows-runner-refcount", "tests/macos-window", "tests/panel-extension"] +members = ["src-tauri", "tests/windows-input", "tests/windows-runner-refcount", "tests/macos-window", "tests/panel-extension", "tests/webkit-capabilities"] default-members = ["src-tauri"] resolver = "2" @@ -9,3 +9,5 @@ resolver = "2" [patch.crates-io] tao = { path = "vendor/tao-0.37.2" } tauri-plugin-updater = { path = "vendor/tauri-plugin-updater-2.14.1" } +tauri-runtime-wry = { path = "vendor/tauri-runtime-wry-2.12.3" } +wry = { path = "vendor/wry-0.57.1" } diff --git a/packages/tauri-app/scripts/test-browser-parent-webkit.py b/packages/tauri-app/scripts/test-browser-parent-webkit.py new file mode 100644 index 0000000000..de7f6aa21c --- /dev/null +++ b/packages/tauri-app/scripts/test-browser-parent-webkit.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Production native-parent/controller qualification using an isolated fixture child. + +Build the TypeScript fixture with esbuild first; pass its .mjs path via --fixture. +The owning-window inventory and renderer's open-claim callback are fixture-owned. +""" +import argparse +import http.server +import json +import os +from pathlib import Path +import platform +import shutil +import ssl +import subprocess +import tempfile +import threading +import time +import uuid + + +class Fixture(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path.startswith('/mobile'): + directory = Path(__file__).resolve().parents[1] / 'tests/browser-parent' + body = (directory / 'mobile.html').read_text().replace('{{UA}}', json.dumps(self.headers.get('User-Agent','')).replace('<','\\u003c')).replace('{{LOAD}}',json.dumps(uuid.uuid4().hex)).encode('utf-8') + self.send_response(200) + self.send_header('Content-Type','text/html; charset=utf-8') + self.send_header('Content-Length',str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if self.path.startswith('/read/'): + directory = Path(__file__).resolve().parents[1] / 'tests/browser-parent' + name = self.path.split('?',1)[0][len('/read/'):] + fixtures = json.loads((directory / 'read-fixtures.generated.json').read_text()) + if name == 'advanced': + body = (directory / 'read-advanced.html').read_text().replace('{{CROSS}}', f'http://localhost:{self.server.server_port}') + elif name == 'frame': + body = 'Child document' + elif name == 'extra': + body = (directory / 'action-extra.html').read_text() + else: + body = fixtures.get(name, '') + programs = json.loads((directory / 'action-programs.generated.json').read_text()) + body = (body + '').encode('utf-8') + else: + body = b'Parent channel fixture

Native parent fixture

Overlay' + if self.path == '/redirect': + self.send_response(302) + self.send_header('Location', '/ok') + self.end_headers() + return + if self.path == '/slow': + time.sleep(.3) + self.send_response(200) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + try: + self.wfile.write(body) + except BrokenPipeError: + pass + + def log_message(self, *_args): + pass + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--fixture', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--target', type=Path, required=True) + parser.add_argument('--node', default=shutil.which('node')) + parser.add_argument('--nested-kde', action='store_true', help='Own a private KWin Wayland compositor alongside the current desktop') + args = parser.parse_args() + if not args.node: + parser.error('Node executable required: use --node /absolute/path/to/node') + root = Path(__file__).resolve().parents[1] + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + env = os.environ.copy() + env.update(CARGO_TARGET_DIR=str(args.target.resolve()), CARGO_PROFILE_DEV_DEBUG='0', CARGO_INCREMENTAL='0') + if platform.system() == 'Darwin': + env['MACOSX_DEPLOYMENT_TARGET'] = '14.0' + else: + session = subprocess.check_output(['systemctl', '--user', 'show-environment'], text=True) + for line in session.splitlines(): + key, separator, value = line.partition('=') + if separator and key in {'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS'}: + env.setdefault(key, value) + with tempfile.TemporaryDirectory(prefix='codenomad-parent-build-') as directory: + manifest = Path(directory) / 'Cargo.toml' + source = root / 'src-tauri/examples/browser-parent-webkit.rs' + native = root / 'src-tauri/src/embedded_view' + manifest.write_text( + '[package]\nname="codenomad-parent-qualification"\nversion="0.0.0"\nedition="2021"\n' + '[dependencies]\ntauri={version="=2.12.5",features=["unstable","test"]}\ntauri-plugin-dialog="2.8.4"\nserde={version="1",features=["derive"]}\nserde_json="1"\nuuid={version="1",features=["v4"]}\nbase64="0.22"\nsha2="0.10"\n' + '[target.\'cfg(target_os="linux")\'.dependencies]\ngtk="0.18"\nwebkit2gtk="=2.0.2"\n' + '[target.\'cfg(target_os="macos")\'.dependencies]\nobjc2="0.6.4"\nobjc2-web-kit={version="0.3.2",default-features=false,features=["std","objc2-app-kit","WKWebView","WKBackForwardList","WKBackForwardListItem","WKNavigation"]}\n' + '[build-dependencies]\ncc="1"\npkg-config="0.3"\n' + f'[[bin]]\nname="browser-parent-webkit"\npath={json.dumps(str(source))}\n' + '[patch.crates-io]\n' + ''.join(f'{name}={{path={json.dumps(str(root / "vendor" / folder))}}}\n' for name, folder in [('tao','tao-0.37.2'),('wry','wry-0.57.1'),('tauri-runtime-wry','tauri-runtime-wry-2.12.3')]), + encoding='utf-8') + (Path(directory) / 'build.rs').write_text( + f'#[path={json.dumps(str(root / "src-tauri/build_webkit.rs"))}] mod build_webkit;\nfn main() {{ build_webkit::build(std::path::Path::new({json.dumps(str(native))})); let mut b=cc::Build::new(); b.file({json.dumps(str(root / "tests/browser-parent" / ("mobile-trial-macos.m" if platform.system()=="Darwin" else "mobile-trial-linux.c")))}); ' + + ('b.flag("-fobjc-arc").flag("-fblocks").flag("-mmacosx-version-min=14.0");' if platform.system()=='Darwin' else 'b.includes(pkg_config::Config::new().probe("webkit2gtk-4.1").unwrap().include_paths);') + + 'b.compile("mobile_trial"); }\n', encoding='utf-8') + shutil.copyfile(root / 'Cargo.lock', Path(directory) / 'Cargo.lock') + subprocess.run(['cargo', 'build', '--offline', '--manifest-path', str(manifest)], env=env, check=True, timeout=300) + certificate, key = Path(directory) / 'certificate.pem', Path(directory) / 'key.pem' + subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', + '-subj', '/CN=localhost', '-keyout', str(key), '-out', str(certificate)], + check=True, timeout=20, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + with http.server.ThreadingHTTPServer(('127.0.0.1', 0), Fixture) as server, http.server.ThreadingHTTPServer(('127.0.0.1', 0), Fixture) as tls_server: + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.load_cert_chain(certificate, key) + tls_server.socket = tls.wrap_socket(tls_server.socket, server_side=True) + env['CN_FIXTURE_TLS_URL'] = f'https://127.0.0.1:{tls_server.server_port}/ok' + thread = threading.Thread(target=server.serve_forever, daemon=True) + tls_thread = threading.Thread(target=tls_server.serve_forever, daemon=True) + thread.start() + tls_thread.start() + compositor = None + try: + if args.nested_kde: + socket = f'codenomad-parent-{os.getpid()}' + env.update(WAYLAND_DISPLAY=socket, GDK_BACKEND='wayland') + with (output / 'kwin.log').open('w') as log: + compositor = subprocess.Popen(['kwin_wayland', '--virtual', '--socket', socket, '--width', '1024', '--height', '768'], + env={**env, 'QT_QPA_PLATFORM': 'offscreen', 'KWIN_COMPOSE': 'Q'}, stdout=log, stderr=subprocess.STDOUT) + deadline = time.monotonic() + 15 + while not (Path(env['XDG_RUNTIME_DIR']) / socket).exists(): + assert compositor.poll() is None, (output / 'kwin.log').read_text() + assert time.monotonic() < deadline, 'KWin socket startup timed out' + time.sleep(.1) + subprocess.run([str(args.target.resolve() / 'debug/browser-parent-webkit'), args.node, + str(args.fixture.resolve()), f'http://127.0.0.1:{server.server_port}', str(output)], + env=env, check=True, timeout=150) + finally: + if compositor: + compositor.terminate() + compositor.wait(timeout=10) + server.shutdown() + tls_server.shutdown() + thread.join() + tls_thread.join() + + +if __name__ == '__main__': + main() diff --git a/packages/tauri-app/scripts/test-webkit-history-linux.py b/packages/tauri-app/scripts/test-webkit-history-linux.py new file mode 100644 index 0000000000..45bef810ad --- /dev/null +++ b/packages/tauri-app/scripts/test-webkit-history-linux.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Run the production history adapters against real GTK/WebKit without Tauri. + +Usage on Linux with GTK 3 / WebKitGTK 4.1 development packages and a display: + python3 packages/tauri-app/scripts/test-webkit-history-linux.py +Only a temporary standalone Cargo manifest is generated; sources are included +directly from this checkout. CARGO_TARGET_DIR can reuse an existing build cache. +""" +import http.server +import json +import os +from pathlib import Path +import subprocess +import tempfile +import threading + + +class Fixture(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/redirect": + self.send_response(302) + self.send_header("Location", "/target") + self.end_headers() + return + body = b"Native history fixture

History fixture

" + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_args): + pass + + +def main(): + source = Path(__file__).resolve().parents[1] / "src-tauri/examples/browser-history-linux.rs" + environment = os.environ.copy() + # SSH users can inherit the real GNOME display/session without shell eval. + if not environment.get("DISPLAY") and not environment.get("WAYLAND_DISPLAY"): + session = subprocess.run( + ["systemctl", "--user", "show-environment"], text=True, + capture_output=True, check=True, + ) + for line in session.stdout.splitlines(): + key, separator, value = line.partition("=") + if separator and key in {"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"}: + environment[key] = value + with tempfile.TemporaryDirectory(prefix="codenomad-webkit-history-") as directory: + manifest = Path(directory) / "Cargo.toml" + manifest.write_text( + '[package]\nname = "codenomad-webkit-history-regression"\nversion = "0.0.0"\nedition = "2021"\n' + '[dependencies]\ngtk = "0.18"\nwebkit2gtk = { version = "=2.0.2", features = ["v2_40"] }\n' + f'[[bin]]\nname = "browser-history-linux"\npath = {json.dumps(str(source))}\n', + encoding="utf-8", + ) + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Fixture) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + subprocess.run( + ["cargo", "run", "--manifest-path", str(manifest), "--", + f"http://127.0.0.1:{server.server_port}"], + env=environment, check=True, timeout=600, + ) + finally: + server.shutdown() + thread.join() + + +if __name__ == "__main__": + main() diff --git a/packages/tauri-app/scripts/test-webkit-input.py b/packages/tauri-app/scripts/test-webkit-input.py new file mode 100644 index 0000000000..9b72c768da --- /dev/null +++ b/packages/tauri-app/scripts/test-webkit-input.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Compile and exercise the production native primitives on a graphical session. + +Linux: GDK_BACKEND=wayland|x11 python3 packages/tauri-app/scripts/test-webkit-input.py +macOS: python3 packages/tauri-app/scripts/test-webkit-input.py +Artifacts remain in --output (default: a printed temporary directory). +""" +import argparse +import json +import os +from pathlib import Path +import platform +import shlex +import shutil +import struct +import subprocess +import tempfile +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path) + parser.add_argument('--nested-kde', action='store_true', help='Own a separate headless KWin Wayland compositor; leave the desktop session intact') + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = args.output or Path(tempfile.mkdtemp(prefix='codenomad-webkit-input-')) + output.mkdir(parents=True, exist_ok=True) + output = output.resolve() + source = root / 'src-tauri/src/embedded_view' + test = root / 'tests/webkit-input' + env = os.environ.copy() + binary = output / 'native-input' + if platform.system() == 'Darwin': + command = ['clang', '-Wall', '-Wextra', '-Werror', '-fobjc-arc', '-fblocks', '-DCN_INPUT_SELF_TEST', + '-mmacosx-version-min=14.0', '-framework', 'AppKit', '-framework', 'WebKit', + '-framework', 'ApplicationServices', str(source / 'input_macos.m'), str(test / 'macos.m')] + else: + session = subprocess.run(['systemctl', '--user', 'show-environment'], + check=True, capture_output=True, text=True).stdout + for line in session.splitlines(): + key, separator, value = line.partition('=') + if separator and key in {'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS'}: + env.setdefault(key, value) + flags = subprocess.run(['pkg-config', '--cflags', '--libs', 'webkit2gtk-4.1'], + check=True, capture_output=True, text=True).stdout + command = ['cc', '-Wall', '-Wextra', '-Werror', str(source / 'input_linux.c'), str(test / 'linux.c'), *shlex.split(flags)] + subprocess.run([*command, '-o', str(binary)], check=True, timeout=120) + print(f'Artifacts: {output}', flush=True) + compositor = None + desktop_pointer = None + if platform.system() == 'Linux' and env.get('DISPLAY') and shutil.which('xdotool'): + # Observation only: synthetic input goes exclusively through the native adapter. + desktop_pointer = subprocess.check_output(['xdotool', 'getmouselocation', '--shell'], env=env, text=True) + try: + if args.nested_kde: + socket = f'codenomad-input-{os.getpid()}' + env['WAYLAND_DISPLAY'] = socket + env['GDK_BACKEND'] = 'wayland' + env['CN_NESTED_KDE'] = '1' + compositor_env = {**env, 'QT_QPA_PLATFORM': 'offscreen', 'KWIN_COMPOSE': 'Q'} + with (output / 'kwin.log').open('w') as log: + compositor = subprocess.Popen(['kwin_wayland', '--virtual', '--socket', socket, + '--width', '1024', '--height', '768'], + env=compositor_env, stdout=log, stderr=subprocess.STDOUT) + deadline = time.monotonic() + 15 + while not (Path(env['XDG_RUNTIME_DIR']) / socket).exists(): + assert compositor.poll() is None, (output / 'kwin.log').read_text() + assert time.monotonic() < deadline, 'KWin socket startup timed out' + time.sleep(.1) + run = subprocess.run([str(binary), str(test / 'fixture.html')], env=env, cwd=output, + capture_output=True, text=True, timeout=30) + (output / 'native.log').write_text(run.stdout + run.stderr) + print(run.stdout + run.stderr, flush=True) + run.check_returncode() + finally: + if compositor: + compositor.terminate() + compositor.wait(timeout=10) + pointer_unchanged = True + if desktop_pointer is not None: + after = subprocess.check_output(['xdotool', 'getmouselocation', '--shell'], env=env, text=True) + # WINDOW identifies the surface under a stationary pointer and can change on mapping. + coordinates = lambda value: [line for line in value.splitlines() if line.startswith(('X=', 'Y='))] + pointer_unchanged = coordinates(desktop_pointer) == coordinates(after) + (output / 'desktop-pointer.json').write_text(json.dumps({'before': desktop_pointer, 'after': after})) + checkpoint = json.loads((output / 'checkpoint.json').read_text()) + # innerText contains the pointer pad label followed by the fixture JSON. + body = checkpoint['body'] + observations = json.loads(body[body.index('{'):]) + events = observations['observations'] + required = {'click', 'contextmenu', 'pointermove', 'pointerdown', 'pointerup', 'wheel', 'keydown', 'keyup', 'input', 'beforeinput'} + png = (output / 'capture.png').read_bytes() + dimensions = struct.unpack('>II', png[16:24]) + criteria = { + 'isolated_world': checkpoint['pageGlobal'] == 'undefined', + 'trusted_events': bool(events) and all(event['trusted'] for event in events), + 'event_types': required <= {event['type'] for event in events}, + 'hover': any(event['type'] == 'pointermove' and event.get('buttons') == 0 and event.get('x') == 30 and event.get('y') == 160 for event in events), + 'hover_enter_css': all(any(event['type'] == kind and event.get('x') == 30 and event.get('y') == 160 and event['padHover'] for event in events) for kind in ('mouseover', 'mouseenter')), + 'drag_buttons': any(event['type'] == 'pointermove' and event.get('buttons') == 1 for event in events), + 'chord_event': any(event['type'] == 'keydown' and (event.get('ctrl') or event.get('meta')) for event in events), + 'chord_select_all': observations['input'] == 'remplacé漢🙂', + 'contenteditable_unicode': observations['editor'].startswith('éditeur漢🙂'), + 'contenteditable_enter': any(event['type'] == 'keydown' and event.get('key') == 'Enter' and event['target'] == 'DIV' for event in events), + 'contenteditable_enter_dom': any(event['type'] == 'input' and event.get('inputType') in {'insertParagraph', 'insertLineBreak'} and event['target'] == 'DIV' for event in events) and '<' in observations['editorHtml'], + 'contenteditable_enter_once': all(sum(event['type'] == kind and event.get('inputType') == 'insertParagraph' and event['target'] == 'DIV' for event in events) == 1 for kind in ('beforeinput', 'input')), + 'visible_png': png[:8] == b'\x89PNG\r\n\x1a\n' and all(0 < value <= 2000 for value in dimensions), + 'desktop_pointer_unchanged': pointer_unchanged, + } + result = {'passed': all(criteria.values()), 'criteria': criteria, 'events': len(events), 'png': dimensions, + 'platform': platform.platform(), 'native': run.stdout} + (output / 'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2)) + print(json.dumps(result, ensure_ascii=False)) + assert result['passed'], [name for name, passed in criteria.items() if not passed] + + +if __name__ == '__main__': + main() diff --git a/packages/tauri-app/scripts/vendored-patches.test.mjs b/packages/tauri-app/scripts/vendored-patches.test.mjs index 72051afe59..1025e2c95f 100644 --- a/packages/tauri-app/scripts/vendored-patches.test.mjs +++ b/packages/tauri-app/scripts/vendored-patches.test.mjs @@ -50,3 +50,40 @@ test("an update past the vendored version is detected", () => { assert.deepEqual(lockedPackages(lock, "tao"), [{ name: "tao", version: "9.0.0", source: "registry+https://github.com/rust-lang/crates.io-index" }]) assert.deepEqual(patchedCrates('[patch.crates-io]\ntao = { path = "vendor/tao-1.0.0" }\n'), [{ name: "tao", dir: "vendor/tao-1.0.0" }]) }) + +test("preview runtime fence separates app IPC, scripts and protocols from browser globals", () => { + const runtime = read("vendor/tauri-runtime-wry-2.12.3/src/lib.rs") + assert.match(runtime, /let browser_guest = label\.starts_with\("browser-"\);/) + assert.match(runtime, /if !browser_guest \{\s*webview_builder = webview_builder\.with_ipc_handler/) + assert.match(runtime, /for \(scheme, protocol\) in uri_scheme_protocols \{[\s\S]*?if browser_guest\s*\{\s*continue;\s*\}/) + assert.doesNotMatch(read("src-tauri/src/embedded_view.rs"), /\.clipboard\(true\)/) +}) + +test("WK preview print and beforeunload callbacks retain native completion and app policy", () => { + const delegate = read("vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs") + assert.match(delegate, /method\(_webView:printFrame:pdfFirstPageSize:completionHandler:\)/) + assert.match(delegate, /if self\.ivars\(\)\.preview_dialogs \{ preview_print\(webview\); \}\s*completion\.call\(\(\)\)/) + assert.match(delegate, /fn before_unload[\s\S]*?if !self\.ivars\(\)\.preview_dialogs \{ completion\.call\(\(true\.into\(\),\)\); return; \}/) + assert.match(delegate, /webview\.printOperationWithPrintInfo\(&info\)/) + assert.match(delegate, /operation\.runOperation\(\)/) +}) + +test("GTK pointer consent preserves the requesting surface and cancels on navigation", () => { + const source = read("src-tauri/src/embedded_view/linux.rs") + assert.match(source, /if kind == "pointer-lock"[\s\S]*?pointer_lock_consent\([\s\S]*?return true/) + assert.match(source, /gtk::InfoBar::new\(\)/) + assert.match(source, /button\.set_focus_on_click\(false\)/) + assert.match(source, /LoadEvent::Started[\s\S]*?bar\.response\(gtk::ResponseType::Cancel\)/) + assert.match(source, /allowed\s*&& epoch\.get\(\) == captured/) + assert.match(source, /&& answer_policy\.current\(&answer_label, token\)/) +}) + +test("native popup closure runs each engine's beforeunload path", () => { + assert.match(read("src-tauri/src/embedded_view/browser.rs"), /CloseRequested \{ api, \.\. \}[\s\S]*?api\.prevent_close\(\)/) + assert.match(read("src-tauri/src/embedded_view/linux.rs"), /native\.inner\(\)\.try_close\(\)/) + assert.match(read("src-tauri/src/embedded_view/macos.rs"), /msg_send!\[view, _tryClose\]/) + const windows = read("src-tauri/src/embedded_view/windows.rs") + assert.match(windows, /CoTaskMemPWSTR::from\("Page.close"\)/) + assert.doesNotMatch(windows, /view\.eval\("window.close/) + assert.match(windows, /policy.current\(&label, token\)/) +}) diff --git a/packages/tauri-app/src-tauri/Cargo.toml b/packages/tauri-app/src-tauri/Cargo.toml index 6f9b103470..f9451f2e8f 100644 --- a/packages/tauri-app/src-tauri/Cargo.toml +++ b/packages/tauri-app/src-tauri/Cargo.toml @@ -4,8 +4,17 @@ version = "1.0.1" edition = "2021" license = "MIT" +[features] +browser-parent-qualification = [] + +[[example]] +name = "browser-parent-webkit" +required-features = ["browser-parent-qualification"] + [build-dependencies] tauri-build = { version = "2.7.4", features = [] } +cc = "1" +pkg-config = "0.3" [dependencies] tauri = { version = "2.12.5", features = ["devtools", "unstable"] } @@ -48,6 +57,8 @@ windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Securit [target.'cfg(target_os = "macos")'.dependencies] # Already built through tauri; reads the bundle executable for restarts. plist = "1.8" +objc2 = "0.6.4" +objc2-web-kit = { version = "0.3.2", default-features = false, features = ["std", "objc2-app-kit", "WKWebView", "WKBackForwardList", "WKBackForwardListItem", "WKNavigation"] } [target.'cfg(target_os = "linux")'.dependencies] open = "5.3" diff --git a/packages/tauri-app/src-tauri/build.rs b/packages/tauri-app/src-tauri/build.rs index 2ad2438db8..fac54a4179 100644 --- a/packages/tauri-app/src-tauri/build.rs +++ b/packages/tauri-app/src-tauri/build.rs @@ -1,4 +1,6 @@ +mod build_webkit; fn main() { + build_webkit::build(std::path::Path::new("src/embedded_view")); let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by Cargo"); let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is set by Cargo"); diff --git a/packages/tauri-app/src-tauri/build_webkit.rs b/packages/tauri-app/src-tauri/build_webkit.rs new file mode 100644 index 0000000000..19c6d46f9a --- /dev/null +++ b/packages/tauri-app/src-tauri/build_webkit.rs @@ -0,0 +1,64 @@ +pub fn build(directory: &std::path::Path) { + let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if os != "macos" && os != "linux" { + return; + } + let source = directory.join(format!( + "input_{os}.{}", + if os == "macos" { "m" } else { "c" } + )); + println!("cargo:rerun-if-changed={}", source.display()); + println!( + "cargo:rerun-if-changed={}", + directory.join("input.h").display() + ); + println!( + "cargo:rerun-if-changed={}", + directory.join("page_read.generated.h").display() + ); + let mut build = cc::Build::new(); + build.file(source); + let mobile = directory.join(format!( + "mobile_{os}.{}", + if os == "macos" { "m" } else { "c" } + )); + println!("cargo:rerun-if-changed={}", mobile.display()); + build.file(mobile); + let zoom = directory.join(format!( + "zoom_{os}.{}", + if os == "macos" { "m" } else { "c" } + )); + println!("cargo:rerun-if-changed={}", zoom.display()); + println!( + "cargo:rerun-if-changed={}", + directory.join("zoom.h").display() + ); + build.file(zoom); + if std::env::var_os("CARGO_FEATURE_BROWSER_PARENT_QUALIFICATION").is_some() { + let trial = directory.join(format!( + "../../../tests/browser-parent/mobile-trial-{os}.{}", + if os == "macos" { "m" } else { "c" } + )); + println!("cargo:rerun-if-changed={}", trial.display()); + build.file(trial); + } + if os == "macos" { + let navigation = directory.join("input_navigation_macos.m"); + println!("cargo:rerun-if-changed={}", navigation.display()); + build + .file(navigation) + .flag("-fobjc-arc") + .flag("-fblocks") + .flag("-mmacosx-version-min=14.0"); + for framework in ["AppKit", "WebKit", "ApplicationServices"] { + println!("cargo:rustc-link-lib=framework={framework}"); + } + } else { + let webkit = pkg_config::Config::new() + .atleast_version("2.40") + .probe("webkit2gtk-4.1") + .expect("WebKitGTK 4.1 development files"); + build.includes(webkit.include_paths); + } + build.compile("codenomad_webkit_input"); +} diff --git a/packages/tauri-app/src-tauri/examples/browser-history-linux.rs b/packages/tauri-app/src-tauri/examples/browser-history-linux.rs new file mode 100644 index 0000000000..c6092e74a3 --- /dev/null +++ b/packages/tauri-app/src-tauri/examples/browser-history-linux.rs @@ -0,0 +1,241 @@ +//! Run with scripts/test-webkit-history-linux.py on a Linux graphical session. +#[path = "../src/browser_history.rs"] +#[cfg(target_os = "linux")] +mod browser_history; +#[path = "../src/browser_history_linux.rs"] +#[cfg(target_os = "linux")] +mod browser_history_linux; + +#[cfg(target_os = "linux")] +use browser_history::{bounded, HistoryIds}; +#[cfg(target_os = "linux")] +use browser_history_linux::{go, observe, snapshot, Entry}; +#[cfg(target_os = "linux")] +use gtk::prelude::*; +#[cfg(target_os = "linux")] +use std::{ + cell::RefCell, + rc::Rc, + time::{Duration, Instant}, +}; +#[cfg(target_os = "linux")] +use webkit2gtk::WebViewExt; + +#[cfg(target_os = "linux")] +fn until(label: &str, condition: impl Fn() -> bool) { + let deadline = Instant::now() + Duration::from_secs(15); + loop { + while gtk::events_pending() { + gtk::main_iteration_do(false); + } + if condition() { + return; + } + assert!(Instant::now() < deadline, "timeout: {label}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[cfg(target_os = "linux")] +fn script(view: &webkit2gtk::WebView, source: &str) { + let result = Rc::new(RefCell::new(None)); + let done = result.clone(); + #[allow(deprecated)] + view.run_javascript(source, None::<>k::gio::Cancellable>, move |value| { + *done.borrow_mut() = Some(value.map(|_| ()).map_err(|error| error.to_string())); + }); + until(source, || result.borrow().is_some()); + result.borrow_mut().take().unwrap().unwrap(); +} + +#[cfg(target_os = "linux")] +struct History { + allocator: HistoryIds, + entries: Vec, + ids: Vec, + current: usize, +} + +#[cfg(target_os = "linux")] +impl History { + fn read(&mut self, view: &webkit2gtk::WebView) { + let (entries, current) = snapshot(view); + let entries = bounded(entries, current, Entry::token); + // Keep the preceding native objects alive through reconciliation. + let ids = self.allocator.reconcile(entries.iter().map(Entry::token)); + self.current = entries + .iter() + .position(|entry| Some(entry.token()) == current) + .expect("current native object retained in snapshot"); + self.entries = entries; + self.ids = ids; + } + + fn current_id(&self) -> i64 { + self.ids[self.current] + } +} + +#[cfg(not(target_os = "linux"))] +fn main() {} + +#[cfg(target_os = "linux")] +fn main() { + gtk::init().unwrap(); + let base = std::env::args().nth(1).expect("fixture URL"); + let view = webkit2gtk::WebView::new(); + let window = gtk::Window::new(gtk::WindowType::Toplevel); + window.add(&view); + window.set_default_size(400, 240); + // Realize without presenting or stealing focus from the desktop user. + window.set_accept_focus(false); + window.show_all(); + let events = Rc::new(RefCell::new(Vec::new())); + let observed = events.clone(); + observe(&view, move |uri| observed.borrow_mut().push(uri)); + let mut history = History { + allocator: HistoryIds::default(), + entries: Vec::new(), + ids: Vec::new(), + current: 0, + }; + + view.load_uri(&format!("{base}/start")); + until("initial page", || { + !view.is_loading() && view.uri().as_deref() == Some(&format!("{base}/start")) + }); + history.read(&view); + let start_id = history.current_id(); + view.load_uri(&format!("{base}/redirect")); + until("HTTP redirect", || { + !view.is_loading() && view.uri().as_deref() == Some(&format!("{base}/target")) + }); + history.read(&view); + assert_eq!( + history.entries.len(), + 2, + "redirect must not create an intermediate entry" + ); + assert_eq!(history.ids[0], start_id); + assert!(history + .entries + .iter() + .all(|entry| !entry.url().ends_with("/redirect"))); + println!("PASS redirect: final URL and retained initial identity"); + + for (source, suffix) in [ + ("location.hash = 'fragment'", "/target#fragment"), + ("history.pushState({step: 1}, '', '/same')", "/same"), + ("history.pushState({step: 2}, '', '/same')", "/same"), + ] { + let previous = history.ids.clone(); + let count = events.borrow().len(); + script(&view, source); + until(source, || { + snapshot(&view).0.len() == previous.len() + 1 && events.borrow().len() > count + }); + history.read(&view); + assert_eq!(&history.ids[..previous.len()], previous.as_slice()); + assert!(!previous.contains(&history.current_id())); + assert_eq!( + history.entries[history.current].url(), + format!("{base}{suffix}") + ); + println!("PASS same-document observed: {source}"); + } + let duplicate_ids = history.ids.clone(); + let duplicate_entries = history.entries.clone(); + assert_eq!(duplicate_entries[3].url(), duplicate_entries[4].url()); + assert_ne!(duplicate_entries[3].token(), duplicate_entries[4].token()); + assert_ne!(duplicate_ids[3], duplicate_ids[4]); + + for (source, changes_url) in [ + ("history.replaceState({step: 3}, '', '/same')", false), + ("history.replaceState({step: 4}, '', '/replaced')", true), + ] { + let count = events.borrow().len(); + script(&view, source); + if changes_url { + until(source, || events.borrow().len() > count); + } + history.read(&view); + assert_eq!( + history.ids, duplicate_ids, + "replaceState preserves object identity" + ); + assert_eq!(history.entries[4].token(), duplicate_entries[4].token()); + println!( + "PASS replaceState identity ({} callbacks): {source}", + events.borrow().len() - count + ); + } + assert_eq!(history.entries[4].url(), format!("{base}/replaced")); + + for index in [3, 4, 2] { + let count = events.borrow().len(); + go(&view, &duplicate_entries[index]).unwrap(); + until("native back/forward", || { + snapshot(&view).1 == Some(duplicate_entries[index].token()) + && events.borrow().len() > count + }); + history.read(&view); + assert_eq!(history.ids, duplicate_ids); + assert_eq!(history.current_id(), duplicate_ids[index]); + } + println!("PASS native back/forward: identity and same-document callbacks"); + + let count = events.borrow().len(); + script(&view, "history.pushState({}, '', '/branch')"); + until("branch callback", || events.borrow().len() > count); + history.read(&view); + assert_eq!(history.ids.len(), 4); + assert_eq!(&history.ids[..3], &duplicate_ids[..3]); + assert!(!history.ids.contains(&duplicate_ids[3])); + assert!(!history.ids.contains(&duplicate_ids[4])); + assert!(!duplicate_ids.contains(&history.current_id())); + println!("PASS branch: stale forward IDs absent and new object gets new ID"); + + script( + &view, + "for (let i = 0; i < 50; i++) history.pushState({i}, '', '/bounded-' + i)", + ); + history.read(&view); + assert_eq!(history.ids.len(), 32, "numeric handles bounded to 32"); + assert_eq!( + history.entries[history.current].url(), + format!("{base}/bounded-49") + ); + let bounded_ids = history.ids.clone(); + history.read(&view); + assert_eq!(history.ids, bounded_ids); + let middle = history.entries[16].clone(); + go(&view, &middle).unwrap(); + until("middle of bounded history", || { + snapshot(&view).1 == Some(middle.token()) + }); + let (wide, current) = snapshot(&view); + assert!( + wide.len() > 32, + "exercise allocator with an oversized native snapshot" + ); + let history_window = bounded(wide, current, Entry::token); + assert!(history_window + .iter() + .any(|entry| Some(entry.token()) == current)); + let mut allocator = HistoryIds::default(); + let ids = allocator.reconcile(history_window.iter().map(Entry::token)); + assert_eq!(ids.len(), 32); + assert_eq!( + allocator.reconcile(history_window.iter().map(Entry::token)), + ids + ); + println!( + "PASS bound: {} retained entries, current entry present, stable IDs", + history.ids.len() + ); + println!( + "PASS WebKitGTK history regression ({} native observation callbacks)", + events.borrow().len() + ); + window.close(); +} diff --git a/packages/tauri-app/src-tauri/examples/browser-parent-webkit.rs b/packages/tauri-app/src-tauri/examples/browser-parent-webkit.rs new file mode 100644 index 0000000000..f9f3caa940 --- /dev/null +++ b/packages/tauri-app/src-tauri/examples/browser-parent-webkit.rs @@ -0,0 +1,356 @@ +//! Real native guests and production parent framing with an isolated fixture child. +#[cfg(not(windows))] +#[path = "../src/browser_controller.rs"] +mod browser_controller; +#[cfg(not(windows))] +#[path = "../src/embedded_view.rs"] +mod embedded_view; +#[cfg(not(windows))] +#[path = "../src/identity/local_window.rs"] +mod identity; +#[cfg(not(windows))] +#[path = "../src/native_request.rs"] +mod native_request; + +// Only the shell's owning-window inventory is fixture-supplied. Browser target +// claims, generations, leases, native loads, visibility and captures are real. +#[cfg(not(windows))] +mod local_windows { + #[derive(Clone)] + pub(crate) struct Record { + pub(crate) label: String, + } + pub(crate) struct LocalWindows(pub(crate) Vec); + impl LocalWindows { + pub(crate) fn records(&self) -> Vec { + self.0.clone() + } + } +} +#[cfg(not(windows))] +use browser_controller::{BrowserController, BrowserTargetRegistration, BrowserTargetUpdate}; +#[cfg(not(windows))] +use serde_json::{json, Value}; +#[cfg(not(windows))] +use std::{ + io::{BufRead, BufReader, Write}, + process::{Command, Stdio}, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, Mutex, + }, + time::Duration, +}; +#[cfg(not(windows))] +use tauri::{Listener, Manager}; +#[cfg(not(windows))] +const OWNER: &str = "local-11111111-1111-4111-8111-111111111111"; +#[cfg(not(windows))] +const OTHER: &str = "local-22222222-2222-4222-8222-222222222222"; +#[cfg(not(windows))] +const SESSION: &str = "fixture-session"; +#[cfg(not(windows))] +#[path = "../../tests/browser-parent/mobile-native.rs"] +mod mobile_fixture; +#[cfg(not(windows))] +#[path = "../src/menu_labels.rs"] +mod menu_labels; +#[cfg(not(windows))] +struct AppState { + menu_labels: menu_labels::MenuLabels, +} + +#[cfg(not(windows))] +fn bounds() -> Value { + json!({"x":10,"y":60,"width":600,"height":400}) +} +#[cfg(not(windows))] +fn create_primary(app: &tauri::App, label: &str, base: &str) { + let window = tauri::WindowBuilder::new(app, label) + .title("Native parent qualification") + .inner_size(740.0, 560.0) + .focused(false) + .build() + .unwrap(); + window + .add_child( + tauri::webview::WebviewBuilder::new( + label, + tauri::WebviewUrl::External(format!("{base}/renderer").parse().unwrap()), + ) + .focused(false), + tauri::LogicalPosition::new(0.0, 0.0), + tauri::LogicalSize::new(740.0, 560.0), + ) + .unwrap(); +} +#[cfg(not(windows))] +fn register( + app: &tauri::AppHandle, + controller: &BrowserController, + owner: &str, + id: &str, + url: &str, +) -> Result<(), String> { + let input: BrowserTargetRegistration = serde_json::from_value(json!({"sessionId":SESSION,"registrationId":id,"url":url,"bounds":bounds(),"visible":false})).unwrap(); + controller.register(&app.get_window(owner).ok_or("Fixture owner closed")?, input)?; + update(app, controller, owner, id, true) +} +#[cfg(not(windows))] +fn update( + app: &tauri::AppHandle, + controller: &BrowserController, + owner: &str, + id: &str, + visible: bool, +) -> Result<(), String> { + let input: BrowserTargetUpdate = + serde_json::from_value(json!({"registrationId":id,"bounds":bounds(),"visible":visible})) + .unwrap(); + controller.update(app, owner, input) +} + +#[cfg(not(windows))] +fn capture_at_revocation( + app: &tauri::AppHandle, + controller: &BrowserController, + id: &str, + close: bool, + deadline_ms: u64, + fence: native_request::RequestFence, +) -> Result { + use std::sync::atomic::AtomicUsize; + let prefix = format!("browser-{id}-"); + let view = app + .webviews() + .into_values() + .find(|view| view.label().starts_with(&prefix)) + .ok_or("Fixture preview missing")?; + let controller = controller.clone(); + let app = app.clone(); + let id = id.to_string(); + let reads = AtomicUsize::new(0); + // The third guard runs in the actual native PNG completion callback, after + // admission and dispatch. Revoke authority at that acceptance boundary. + embedded_view::input::read( + &view, + embedded_view::input::Read::Capture, + std::time::Instant::now() + Duration::from_secs(15), + move || { + fence.check()?; + if reads.fetch_add(1, Ordering::SeqCst) == 2 { + if close { + controller.unregister(&app, OWNER, &id)?; + } else { + update(&app, &controller, OWNER, &id, false)?; + } + } + controller + .handle_native( + &app, + "browser.probe", + Some(json!({"sessionID":SESSION})), + deadline_ms, + fence.clone(), + ) + .map(|_| ()) + }, + ) + .map(|_| Value::Null) +} + +#[cfg(windows)] +fn main() {} +#[cfg(not(windows))] +fn main() { + let args = std::env::args().skip(1).collect::>(); + assert_eq!(args.len(), 4, "node fixture.mjs base-url profile"); + let controller = BrowserController::new(args[3].clone().into()); + let live = Arc::new(Mutex::new(String::new())); + let generation = Arc::new(AtomicU64::new(1)); + tauri::Builder::default() + .manage(local_windows::LocalWindows(vec![local_windows::Record { + label: OWNER.into(), + }])) + .manage(embedded_view::StorageIdentity::new( + "parent-fixture".into(), + args[3].clone(), + )) + .setup(move |app| { + #[cfg(target_os = "linux")] + { + use gtk::glib::object::ObjectExt; + eprintln!( + "native-display={}", + gtk::gdk::Display::default().unwrap().type_().name() + ); + } + create_primary(app, OWNER, &args[2]); + create_primary(app, OTHER, &args[2]); + let open_app = app.handle().clone(); + let open_controller = controller.clone(); + let open_live = live.clone(); + app.listen("browser-target:open", move |event| { + let payload: Value = serde_json::from_str(event.payload()).unwrap(); + let request = payload["requestID"].as_str().unwrap().to_string(); + if !open_controller.claim_open(OWNER, &request) { + return; + } + let app = open_app.clone(); + let controller = open_controller.clone(); + let live = open_live.clone(); + std::thread::spawn(move || { + let id = format!("fixture-{}", uuid::Uuid::new_v4()); + let result = register( + &app, + &controller, + OWNER, + &id, + payload["url"].as_str().unwrap(), + ); + if result.is_ok() { + *live.lock().unwrap() = id; + } else { + eprintln!("open fixture failed: {result:?}"); + controller.release_open(&app, OWNER, &request); + } + }); + }); + let app = app.handle().clone(); + std::thread::spawn(move || { + // Allow the primary documents' initial loads to settle; no daemon starts. + std::thread::sleep(Duration::from_millis(500)); + let mut child = Command::new(&args[0]) + .arg("--enable-source-maps") + .arg(&args[1]) + .arg(&args[2]) + .arg(&args[3]) + .env("CODENOMAD_NATIVE_PARENT", "1") + .env("CODENOMAD_TAURI_WEBKIT", "1") + .env("CODENOMAD_NATIVE_BROWSER_AUTOMATION", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + let mut reader = BufReader::new(child.stdout.take().unwrap()); + let mut line = String::new(); + loop { + line.clear(); + if reader.read_line(&mut line).unwrap() == 0 { + break; + } + let Some(request) = native_request::parse(line.trim_end()) else { + panic!("Unexpected child output: {line}"); + }; + let current = generation.clone(); + let fence = native_request::RequestFence::new(request.deadline, move || { + current.load(Ordering::SeqCst) == 1 + }); + let response = native_request::dispatch(request, fence, |request, fence| { + let id = live.lock().unwrap().clone(); + match request.method.as_str() { + method if method.starts_with("fixture.mobile-") => mobile_fixture::handle(&app,&controller,&id,method,request.params.as_ref().unwrap_or(&Value::Null),fence), + "fixture.action-probe" | "fixture.action-control" => { + let programs:Value=serde_json::from_str(include_str!("../../tests/browser-parent/action-programs.generated.json")).unwrap(); + let kind=if request.method=="fixture.action-probe" {"observe"} else {request.params.as_ref().and_then(|value|value["kind"].as_str()).ok_or("Invalid fixture control")?}; + let script=programs["programs"][kind].as_str().ok_or("Invalid fixture control")?; + let view=app.webviews().into_values().find(|view|view.label().starts_with(&format!("browser-{id}-"))).ok_or("Fixture preview missing")?; + view.eval(script).map_err(|error|error.to_string())?; + if request.method=="fixture.action-probe" { + let bytes=embedded_view::input::read(&view,embedded_view::input::Read::Checkpoint,std::time::Instant::now()+Duration::from_secs(5),move ||fence.check())?; + let checkpoint:Value=serde_json::from_slice(&bytes).map_err(|error|error.to_string())?; + let text=checkpoint["body"].as_str().and_then(|body|body.split_once("__CN_PROBE__").map(|(_,value)|value)).ok_or("Fixture observation missing")?; + let observed=serde_json::from_str(text.trim()).map_err(|error|error.to_string())?; + let _=view.eval(programs["programs"]["remove-probe"].as_str().unwrap()); + Ok(observed) + } else { + if kind=="recreate-shadow" { std::thread::sleep(Duration::from_millis(100)); } + Ok(Value::Null) + } + } + "fixture.read-mutation" => { + let script = match request.params.as_ref().and_then(|value| value["kind"].as_str()) { + Some("pushstate") => "history.pushState({}, '', '?same-document')", + Some("reinsert") => "{ const item=document.querySelector('#aria-button');item.remove();document.querySelector('main').append(item); }", + Some("recreate") => "document.open();document.write('');document.close()", + _ => return Err("Invalid read fixture mutation".into()), + }; + let view = app.webviews().into_values().find(|view| view.label().starts_with(&format!("browser-{id}-"))).ok_or("Fixture preview missing")?; + view.eval(script).map_err(|error| error.to_string())?; + // eval is queued; the next isolated read observes its completion. + std::thread::sleep(Duration::from_millis(100)); + Ok(Value::Null) + } + "fixture.hide" => { + update(&app, &controller, OWNER, &id, false).map(|()| Value::Null) + } + "fixture.overlay" => { + app.get_webview(OWNER) + .ok_or("Fixture renderer missing")? + .eval("document.querySelector('dialog').showModal()") + .map_err(|error| error.to_string())?; + update(&app, &controller, OWNER, &id, false).map(|()| Value::Null) + } + "fixture.show" => { + app.get_webview(OWNER) + .ok_or("Fixture renderer missing")? + .eval("document.querySelector('dialog').close()") + .map_err(|error| error.to_string())?; + update(&app, &controller, OWNER, &id, true).map(|()| Value::Null) + } + "fixture.duplicate" => register( + &app, + &controller, + OTHER, + "fixture-duplicate", + &format!("{}/ok", args[2]), + ) + .map(|()| Value::Null), + "fixture.removeDuplicate" => controller + .unregister(&app, OTHER, "fixture-duplicate") + .map(|()| Value::Null), + "fixture.close" => controller + .unregister(&app, OWNER, &id) + .map(|()| Value::Null), + "fixture.capture-hide" | "fixture.capture-close" => { + capture_at_revocation( + &app, + &controller, + &id, + request.method == "fixture.capture-close", + request.deadline, + fence, + ) + } + "fixture.late" => { + std::thread::sleep(Duration::from_millis(100)); + Ok(json!({"stale":true})) + } + "fixture.retire" => { + generation.store(2, Ordering::SeqCst); + Ok(json!({"stale":true})) + } + _ => controller.handle_native( + &app, + &request.method, + request.params.clone(), + request.deadline, + fence, + ), + } + }); + if let Some(response) = response { + input.write_all(response.as_bytes()).unwrap(); + input.flush().unwrap(); + } + } + let status = child.wait().unwrap(); + app.exit(if status.success() { 0 } else { 1 }); + }); + Ok(()) + }) + .run(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); +} diff --git a/packages/tauri-app/src-tauri/src/browser_controller.rs b/packages/tauri-app/src-tauri/src/browser_controller.rs index fed3cd96f9..b47fd250b9 100644 --- a/packages/tauri-app/src-tauri/src/browser_controller.rs +++ b/packages/tauri-app/src-tauri/src/browser_controller.rs @@ -1,3 +1,6 @@ +use crate::embedded_view::{ + is_allowed_url, validate_bounds, Bounds as BrowserTargetBounds, EmbeddedViews, +}; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet}; @@ -5,15 +8,33 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use tauri::webview::PageLoadEvent; -use tauri::{AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, Window}; +use tauri::{AppHandle, Emitter, Manager, Window}; +#[cfg(test)] +use tauri::{PhysicalPosition, PhysicalSize}; #[cfg(windows)] #[path = "browser_emulation.rs"] mod emulation; +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "browser_emulation_webkit.rs"] +mod emulation; +#[path = "browser_emulation_layout.rs"] +mod viewport; #[path = "browser_controller_page.rs"] mod page; +#[cfg(any(test, target_os = "linux", target_os = "macos"))] +#[path = "browser_history.rs"] +mod history_ids; + +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "browser_history_webkit.rs"] +mod webkit_history; +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "browser_navigation_webkit.rs"] +mod webkit_navigation; + #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct BrowserTargetRegistration { @@ -21,14 +42,8 @@ pub(crate) struct BrowserTargetRegistration { registration_id: String, url: String, bounds: BrowserTargetBounds, -} - -#[derive(Clone, Copy, Debug, Deserialize)] -pub(crate) struct BrowserTargetBounds { - x: i32, - y: i32, - width: u32, - height: u32, + visible: Option, + presentation: Option, } #[derive(Clone, Debug, Deserialize)] @@ -37,6 +52,7 @@ pub(crate) struct BrowserTargetUpdate { registration_id: String, bounds: Option, visible: Option, + presentation: Option, } #[derive(Clone, Debug, Deserialize)] @@ -47,6 +63,7 @@ pub(crate) struct BrowserTargetAction { url: Option, preset: Option, entry_id: Option, + viewport: Option, } #[derive(Clone, PartialEq, Eq)] @@ -73,12 +90,16 @@ struct OpenClaim { url: String, owner: Option, failed_owners: HashSet, + fence: Option, } #[derive(Default)] struct Inner { emulation_profiles: HashMap, + #[cfg(any(target_os = "linux", target_os = "macos"))] + canvases: HashMap, registrations: HashMap, + published_generations: HashMap, renderer_versions: HashMap, page_leases: HashMap, navigation_versions: HashMap, @@ -94,11 +115,12 @@ pub(crate) struct BrowserController { profile: Arc, registration_sequence: Arc, run_id: Arc, + pub(crate) embedded_views: EmbeddedViews, } impl BrowserController { fn storage_directory(&self) -> std::path::PathBuf { - self.profile.join("shared-v1") + crate::embedded_view::browser_storage(&self.profile) } pub(crate) fn new(profile: std::path::PathBuf) -> Self { @@ -108,29 +130,25 @@ impl BrowserController { profile: Arc::new(profile), registration_sequence: Arc::new(AtomicU64::new(1)), run_id: Arc::new(uuid::Uuid::new_v4().to_string()), + embedded_views: EmbeddedViews::default(), } } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] pub(crate) fn register( &self, window: &Window, input: BrowserTargetRegistration, ) -> Result<(), String> { - use tauri::webview::{NewWindowResponse, WebviewBuilder}; - use tauri::WebviewUrl; - validate_id(&input.session_id, 256)?; validate_id(&input.registration_id, 128)?; let url = allowed_url(&input.url)?; - let blank = "about:blank" - .parse() - .map_err(|error| format!("failed to prepare browser preview: {error}"))?; validate_bounds(input.bounds)?; let renderer_version = self.renderer_version(window.label())?; - let label = format!("browser-{}", input.registration_id); let registration_id = input.registration_id.clone(); let generation = self.registration_sequence.fetch_add(1, Ordering::Relaxed); + // Native labels are unique across replacements, including in-flight creations. + let label = format!("browser-{}-{generation}", input.registration_id); let navigation_controller = self.clone(); let navigation_registration_id = registration_id.clone(); let policy_controller = self.clone(); @@ -138,21 +156,17 @@ impl BrowserController { // Every preview is a tab in the same browser profile. Its navigation // history and automation attachment remain owned by its session. let profile = self.storage_directory(); - let builder = WebviewBuilder::new(label.clone(), WebviewUrl::External(blank)) - .data_directory(profile) - .on_navigation(move |url| { - let allowed = url.as_str() == "about:blank" || is_allowed_url(url); - if allowed { - policy_controller - .invalidate_page_for_generation(&policy_registration_id, generation); - } - allowed - }) - .on_new_window(|_, _| NewWindowResponse::Deny) - .on_download(|_, _| false) - .on_page_load(move |webview, payload| { + let webview = self.embedded_views.create( + window, + &label, + profile, + input.bounds, + move |webview, payload| { if payload.event() == PageLoadEvent::Started && payload.url().as_str() != "about:blank" + && navigation_controller + .owned_registration(webview.window().label(), &navigation_registration_id) + .is_ok_and(|current| current.generation == generation) { navigation_controller .invalidate_page_for_generation(&navigation_registration_id, generation); @@ -161,57 +175,115 @@ impl BrowserController { json!({ "registrationId": registration_id, "url": payload.url().as_str() }), ); } - }); - let webview = window - .add_child( - builder, - PhysicalPosition::new(input.bounds.x, input.bounds.y), - PhysicalSize::new(input.bounds.width, input.bounds.height), - ) - .map_err(|error| format!("failed to create browser preview: {error}"))?; + }, + move |_| { + policy_controller + .invalidate_page_for_generation(&policy_registration_id, generation); + true + }, + )?; + let registration = Registration { + session_id: input.session_id, + registration_id: input.registration_id.clone(), + window_label: window.label().to_string(), + webview_label: label.clone(), + generation, + visible: input.visible.unwrap_or(true), + }; #[cfg(windows)] - crate::windows_browser_accelerators::bind(&webview); - if let Err(error) = install_webview2_handlers( + let installed = install_webview2_handlers( &webview, self.clone(), input.registration_id.clone(), window.label().to_string(), generation, - ) { - let _ = webview.close(); + ); + #[cfg(any(target_os = "linux", target_os = "macos"))] + let installed = webkit_history::install(&webview, self.clone(), registration.clone()) + .and_then(|()| webkit_navigation::install(&webview, self.clone(), registration.clone())) + .and_then(|()| crate::embedded_view::input::install_read(&webview)); + if let Err(error) = installed { + let _ = self + .embedded_views + .close(window.app_handle(), window.label(), &label); return Err(error); } - if let Err(error) = webview.show() { - let _ = webview.close(); - return Err(error.to_string()); - } - let registration = Registration { - session_id: input.session_id, - registration_id: input.registration_id.clone(), - window_label: window.label().to_string(), - webview_label: label, - generation, - visible: true, - }; + #[cfg(target_os = "macos")] + let observation = registration.clone(); let previous = match self.publish_registration(registration, renderer_version, url.as_str()) { Ok(previous) => previous, Err(error) => { - let _ = webview.close(); + let _ = self + .embedded_views + .close(window.app_handle(), window.label(), &label); return Err(error); } }; if let Some(previous) = previous { - if let Some(previous_webview) = window.app_handle().get_webview(&previous.webview_label) - { - let _ = previous_webview.close(); + #[cfg(any(target_os = "linux", target_os = "macos"))] + webkit_history::remove(window.app_handle(), previous.webview_label.clone()); + let _ = self.embedded_views.close( + window.app_handle(), + &previous.window_label, + &previous.webview_label, + ); + } + #[cfg(any(target_os = "linux", target_os = "macos"))] + { + let current = self.owned_registration(window.label(), &input.registration_id)?; + if let Err(error) = self.resize_webkit( + window.app_handle(), + ¤t, + input.bounds, + input.presentation, + ) { + let _ = self.unregister_generation( + window.app_handle(), + window.label(), + &input.registration_id, + Some(generation), + ); + return Err(error); } } if let Err(error) = webview.navigate(url) { - let _ = self.unregister(window.app_handle(), window.label(), &input.registration_id); + let _ = self.unregister_generation( + window.app_handle(), + window.label(), + &input.registration_id, + Some(generation), + ); return Err(error.to_string()); } + let current = self.owned_registration(window.label(), &input.registration_id); + match current { + Ok(current) if current.generation == generation => { + if let Err(error) = self.embedded_views.set_visible( + window.app_handle(), + window.label(), + &label, + current.visible, + ) { + let _ = self.unregister_generation( + window.app_handle(), + window.label(), + &input.registration_id, + Some(generation), + ); + return Err(error); + } + } + _ => { + let _ = self + .embedded_views + .close(window.app_handle(), window.label(), &label); + return Err("Browser target changed during creation".into()); + } + } + #[cfg(target_os = "macos")] + webkit_history::observe(window.app_handle().clone(), self.clone(), observation); Ok(()) } @@ -242,7 +314,30 @@ impl BrowserController { return Err("Browser preview renderer is no longer current".to_string()); } let id = registration.registration_id.clone(); + if inner + .registrations + .get(&id) + .is_some_and(|current| current.window_label != registration.window_label) + { + return Err("Browser target belongs to another window".into()); + } + if inner + .published_generations + .get(&id) + .is_some_and(|(_, generation)| *generation > registration.generation) + { + return Err("Browser target changed during creation".into()); + } + // Keep the high-water mark through unregister so an older in-flight + // creation cannot resurrect a replacement that has already been closed. + inner.published_generations.insert( + id.clone(), + (registration.window_label.clone(), registration.generation), + ); let previous = inner.registrations.insert(id.clone(), registration); + inner.emulation_profiles.remove(&id); + #[cfg(any(target_os = "linux", target_os = "macos"))] + inner.canvases.remove(&id); inner .page_leases .retain(|_, lease| lease.registration.registration_id != id); @@ -263,7 +358,7 @@ impl BrowserController { Ok(previous) } - #[cfg(not(windows))] + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] pub(crate) fn register( &self, _window: &Window, @@ -272,27 +367,33 @@ impl BrowserController { Err(unsupported()) } - pub(crate) fn update( + pub(crate) fn update( &self, - app: &AppHandle, + app: &AppHandle, window_label: &str, input: BrowserTargetUpdate, ) -> Result<(), String> { let registration = self.owned_registration(window_label, &input.registration_id)?; - let webview = app - .get_webview(®istration.webview_label) - .ok_or_else(|| "Browser preview is no longer available".to_string())?; let visible = input.visible.unwrap_or(true); if visible { let bounds = input .bounds .ok_or_else(|| "Visible browser target bounds are required".to_string())?; - validate_bounds(bounds)?; - webview - .set_position(PhysicalPosition::new(bounds.x, bounds.y)) - .and_then(|()| webview.set_size(PhysicalSize::new(bounds.width, bounds.height))) - .and_then(|()| webview.show()) - .map_err(|error| error.to_string())?; + #[cfg(any(target_os = "linux", target_os = "macos"))] + self.resize_webkit(app, ®istration, bounds, input.presentation)?; + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + self.embedded_views.set_bounds( + app, + window_label, + ®istration.webview_label, + bounds, + )?; + self.embedded_views.set_visible( + app, + window_label, + ®istration.webview_label, + true, + )?; } else { // Revoke authority before the native hide's UI-thread round trip. let mut inner = self.inner.0.lock().map_err(|error| error.to_string())?; @@ -306,7 +407,12 @@ impl BrowserController { .page_leases .retain(|_, lease| lease.registration.registration_id != input.registration_id); drop(inner); - webview.hide().map_err(|error| error.to_string())?; + self.embedded_views.set_visible( + app, + window_label, + ®istration.webview_label, + false, + )?; } let mut inner = self.inner.0.lock().map_err(|error| error.to_string())?; if let Some(current) = inner.registrations.get_mut(&input.registration_id) { @@ -374,7 +480,69 @@ impl BrowserController { .map(|()| Value::Null) } - #[cfg(not(windows))] + #[cfg(any(target_os = "linux", target_os = "macos"))] + fn emit_webkit_navigation(&self, app: &AppHandle, registration: &Registration, url: &str) { + if allowed_url(url).is_err() + || !self + .owned_registration(®istration.window_label, ®istration.registration_id) + .is_ok_and(|current| current.generation == registration.generation) + { + return; + } + // History sampling publishes URL metadata; navigation/load callbacks + // own document fences, including while a new page lease is binding. + if let Some(webview) = app.get_webview(®istration.window_label) { + let _ = webview.emit( + "browser-target:navigated", + json!({ "registrationId": registration.registration_id, "url": url }), + ); + } + } + + #[cfg(any(target_os = "linux", target_os = "macos"))] + pub(crate) fn action( + &self, + app: &AppHandle, + window_label: &str, + input: BrowserTargetAction, + ) -> Result { + let registration = self.owned_registration(window_label, &input.registration_id)?; + let webview = app + .get_webview(®istration.webview_label) + .ok_or("Browser preview is no longer available")?; + match input.action.as_str() { + "emulate" => self + .emulate(app, window_label, &input) + .map(|()| Value::Null), + "history" => webkit_history::action(self, &webview, ®istration, None), + "history-go" => webkit_history::action( + self, + &webview, + ®istration, + Some(input.entry_id.ok_or("Browser history entry is required")?), + ), + "back" => webview + .eval("history.back()") + .map(|()| Value::Null) + .map_err(|error| error.to_string()), + "reload" => webview + .reload() + .map(|()| Value::Null) + .map_err(|error| error.to_string()), + "navigate" => webview + .navigate(allowed_url( + input + .url + .as_deref() + .ok_or("Browser navigation URL is required")?, + )?) + .map(|()| Value::Null) + .map_err(|error| error.to_string()), + _ => Err("Unsupported browser target action".into()), + } + } + + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] pub(crate) fn action( &self, _app: &AppHandle, @@ -389,6 +557,16 @@ impl BrowserController { app: &AppHandle, window_label: &str, registration_id: &str, + ) -> Result<(), String> { + self.unregister_generation(app, window_label, registration_id, None) + } + + fn unregister_generation( + &self, + app: &AppHandle, + window_label: &str, + registration_id: &str, + generation: Option, ) -> Result<(), String> { let (inner, ready) = &*self.inner; let mut inner = inner.lock().map_err(|error| error.to_string())?; @@ -398,8 +576,13 @@ impl BrowserController { if registration.window_label != window_label { return Err("Browser target belongs to another window".to_string()); } + if generation.is_some_and(|generation| generation != registration.generation) { + return Ok(()); + } let registration = inner.registrations.remove(registration_id).unwrap(); inner.emulation_profiles.remove(registration_id); + #[cfg(any(target_os = "linux", target_os = "macos"))] + inner.canvases.remove(registration_id); inner .page_leases .retain(|_, lease| lease.registration.registration_id != registration_id); @@ -407,9 +590,10 @@ impl BrowserController { inner.page_load_expectations.remove(registration_id); drop(inner); ready.notify_all(); - if let Some(webview) = app.get_webview(®istration.webview_label) { - webview.close().map_err(|error| error.to_string())?; - } + #[cfg(any(target_os = "linux", target_os = "macos"))] + webkit_history::remove(app, registration.webview_label.clone()); + self.embedded_views + .close(app, window_label, ®istration.webview_label)?; Ok(()) } @@ -420,6 +604,13 @@ impl BrowserController { let Some(claim) = inner.open_claims.get_mut(request_id) else { return false; }; + if claim + .fence + .as_ref() + .is_some_and(|fence| fence.check().is_err()) + { + return false; + } if claim .owner .as_deref() @@ -448,6 +639,13 @@ impl BrowserController { fn release_claim(&self, window_label: &str, request_id: &str) -> Option { let mut inner = self.inner.0.lock().ok()?; let claim = inner.open_claims.get_mut(request_id)?; + if claim + .fence + .as_ref() + .is_some_and(|fence| fence.check().is_err()) + { + return None; + } if claim.owner.as_deref() != Some(window_label) { return None; } @@ -467,32 +665,41 @@ impl BrowserController { } pub(crate) fn remove_window(&self, app: &AppHandle, window_label: &str) { - let (labels, retries) = if let Ok(mut inner) = self.inner.0.lock() { + let (retries, children) = if let Ok(mut inner) = self.inner.0.lock() { let version = inner .renderer_versions .entry(window_label.to_string()) .or_default(); *version = version.wrapping_add(1); + inner + .published_generations + .retain(|_, (owner, _)| owner != window_label); let ids = inner .registrations .values() .filter(|registration| registration.window_label == window_label) .map(|registration| registration.registration_id.clone()) .collect::>(); - let labels = ids - .into_iter() + let children = ids + .iter() .filter_map(|id| { - inner - .page_leases - .retain(|_, lease| lease.registration.registration_id != id); - inner.navigation_versions.remove(&id); - inner.page_load_expectations.remove(&id); inner .registrations - .remove(&id) - .map(|item| item.webview_label) + .get(id) + .map(|registration| registration.webview_label.clone()) }) .collect::>(); + for id in ids { + inner + .page_leases + .retain(|_, lease| lease.registration.registration_id != id); + inner.navigation_versions.remove(&id); + inner.page_load_expectations.remove(&id); + inner.registrations.remove(&id); + inner.emulation_profiles.remove(&id); + #[cfg(any(target_os = "linux", target_os = "macos"))] + inner.canvases.remove(&id); + } let retries = inner .open_claims .iter_mut() @@ -505,15 +712,17 @@ impl BrowserController { Some((request_id.clone(), claim.clone())) }) .collect::>(); - (labels, retries) + (retries, children) } else { (Vec::new(), Vec::new()) }; - for label in labels { - if let Some(webview) = app.get_webview(&label) { - let _ = webview.close(); - } + for child in children { + #[cfg(any(target_os = "linux", target_os = "macos"))] + webkit_history::remove(app, child); + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + let _ = child; } + self.embedded_views.remove_owner(app, window_label); for (request_id, claim) in retries { Self::emit_open_request(app, &request_id, &claim); } @@ -526,14 +735,16 @@ impl BrowserController { method: &str, params: Option, deadline_ms: u64, + fence: crate::native_request::RequestFence, ) -> Result { - #[cfg(not(windows))] + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] { - let _ = (app, method, params, deadline_ms); + let _ = (app, method, params, deadline_ms, fence); return Err(unsupported()); } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] { + fence.check()?; let input = params.ok_or_else(|| "Invalid browser request".to_string())?; let deadline = request_deadline(deadline_ms)?; let session_id = input @@ -542,9 +753,10 @@ impl BrowserController { .ok_or_else(|| "Invalid browser request".to_string())?; match method { "browser.page.begin" | "browser.page.send" | "browser.page.check" - | "browser.page.end" => self.page_request(app, method, &input, deadline), + | "browser.page.end" => self.page_request(app, method, &input, deadline, &fence), "browser.probe" => { - self.resolve(app, session_id)?; + let registration = self.resolve(app, session_id)?; + self.check_target(app, ®istration, deadline, &fence)?; Ok(json!({ "available": true })) } "browser.execute" => self.execute( @@ -555,19 +767,21 @@ impl BrowserController { .cloned() .ok_or_else(|| "Invalid browser request".to_string())?, deadline, + &fence, ), _ => Err(format!("Unsupported native method: {method}")), } } } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] fn execute( &self, app: &AppHandle, session_id: &str, command: Value, deadline: Instant, + fence: &crate::native_request::RequestFence, ) -> Result { let action = command .get("action") @@ -575,30 +789,82 @@ impl BrowserController { .ok_or_else(|| "Invalid browser command".to_string())?; if action == "open" { let url = command_url(&command)?; - return self.open(app, session_id, url, deadline); + return self.open(app, session_id, url, deadline, fence); } let registration = self.resolve(app, session_id)?; + if action == "navigate" { + self.check_target_identity(app, ®istration, deadline, fence)?; + } else { + self.check_target(app, ®istration, deadline, fence)?; + } let webview = app .get_webview(®istration.webview_label) .ok_or_else(|| "Browser preview is no longer available".to_string())?; match action { "navigate" => { let url = allowed_url(command_url(&command)?)?; - self.navigate_and_wait(®istration, &webview, &url, deadline)?; + self.navigate_and_wait(app, ®istration, &webview, &url, deadline, fence)?; + self.check_target(app, ®istration, deadline, fence)?; Ok(json!({ "url": webview.url().map_err(|error| error.to_string())? })) } "screenshot" => { - let result = cdp( - &webview, - "Page.captureScreenshot", - json!({ "format": "png", "fromSurface": true }), - deadline, - )?; + let document = self.document_version(®istration)?; + #[cfg(windows)] + let result = { + let controller = self.clone(); + let expected = registration.clone(); + let app = app.clone(); + let fence = fence.clone(); + cdp_guarded( + &webview, + "Page.captureScreenshot", + json!({ "format": "png", "fromSurface": true }), + deadline, + move || { + controller.check_target(&app, &expected, deadline, &fence)?; + if controller.document_version(&expected)? != document { + return Err("Browser document changed during capture".into()); + } + Ok(()) + }, + 24 * 1024 * 1024, + )? + }; + #[cfg(windows)] let data = result .get("data") .and_then(Value::as_str) .filter(|data| data.len() <= 16 * 1024 * 1024) .ok_or_else(|| "Browser screenshot is unavailable or too large".to_string())?; + #[cfg(any(target_os = "linux", target_os = "macos"))] + let data = { + use base64::Engine; + let controller = self.clone(); + let expected = registration.clone(); + let app = app.clone(); + let fence = fence.clone(); + let bytes = crate::embedded_view::input::read( + &webview, + crate::embedded_view::input::Read::Capture, + deadline, + move || { + controller.check_target(&app, &expected, deadline, &fence)?; + if controller.document_version(&expected)? != document { + return Err("Browser document changed during capture".into()); + } + Ok(()) + }, + )?; + let encoded = base64::engine::general_purpose::STANDARD.encode(bytes); + if encoded.len() > 16 * 1024 * 1024 { + return Err("Browser screenshot is unavailable or too large".into()); + } + encoded + }; + self.check_target(app, ®istration, deadline, fence)?; + if self.document_version(®istration)? != document { + return Err("Browser document changed during capture".into()); + } Ok( json!({ "image": { "mime": "image/png", "data": data }, "url": webview.url().map_err(|error| error.to_string())? }), ) @@ -607,13 +873,14 @@ impl BrowserController { } } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] fn open( &self, app: &AppHandle, session_id: &str, raw_url: &str, deadline: Instant, + fence: &crate::native_request::RequestFence, ) -> Result { let url = allowed_url(raw_url)?; match self.resolve(app, session_id) { @@ -621,7 +888,8 @@ impl BrowserController { let webview = app .get_webview(®istration.webview_label) .ok_or_else(|| "Browser preview is no longer available".to_string())?; - self.navigate_and_wait(®istration, &webview, &url, deadline)?; + self.navigate_and_wait(app, ®istration, &webview, &url, deadline, fence)?; + self.check_target(app, ®istration, deadline, fence)?; return Ok(json!({ "url": webview.url().map_err(|error| error.to_string())? })); } Err(error) if error == no_browser_target_error() => {} @@ -629,24 +897,17 @@ impl BrowserController { } let request_id = uuid::Uuid::new_v4().to_string(); - { - let mut inner = self.inner.0.lock().map_err(|error| error.to_string())?; - inner.open_claims.insert( - request_id.clone(), - OpenClaim { - session_id: session_id.to_string(), - url: raw_url.to_string(), - owner: None, - failed_owners: HashSet::new(), - }, - ); - } let claim = OpenClaim { session_id: session_id.to_string(), url: raw_url.to_string(), owner: None, failed_owners: HashSet::new(), + fence: Some(fence.clone()), }; + { + let mut inner = self.inner.0.lock().map_err(|error| error.to_string())?; + inner.open_claims.insert(request_id.clone(), claim.clone()); + } Self::emit_open_request(app, &request_id, &claim); let result = (|| -> Result { let registration_deadline = deadline.min(Instant::now() + Duration::from_secs(10)); @@ -654,6 +915,7 @@ impl BrowserController { let mut guard = inner.lock().map_err(|error| error.to_string())?; loop { drop(guard); + fence.check()?; match self.resolve(app, session_id) { Ok(registration) => { let webview = app @@ -667,6 +929,7 @@ impl BrowserController { sequence, deadline, )?; + self.check_target(app, ®istration, deadline, fence)?; return Ok( json!({ "url": webview.url().map_err(|error| error.to_string())? }), ); @@ -711,8 +974,13 @@ impl BrowserController { } } - #[cfg(windows)] - fn resolve(&self, app: &AppHandle, session_id: &str) -> Result { + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + fn resolve( + &self, + app: &AppHandle, + session_id: &str, + ) -> Result { + validate_id(session_id, 256)?; let registrations = self .inner .0 @@ -740,37 +1008,30 @@ impl BrowserController { } } - pub(crate) fn navigation_allowed(&self, webview_label: &str, url: &tauri::Url) -> Option { - if webview_label - .strip_prefix("browser-") - .is_some_and(|id| validate_id(id, 128).is_ok()) - { - return Some(is_allowed_url(url)); - } - self.inner.0.lock().ok().and_then(|inner| { - inner - .registrations - .values() - .any(|registration| registration.webview_label == webview_label) - .then(|| is_allowed_url(url)) - }) - } - #[cfg(windows)] fn navigate_and_wait( &self, + app: &AppHandle, registration: &Registration, webview: &tauri::Webview, url: &tauri::Url, deadline: Instant, + fence: &crate::native_request::RequestFence, ) -> Result<(), String> { + self.check_target_identity(app, registration, deadline, fence)?; self.invalidate_page(®istration.registration_id); let sequence = self.prepare_page_load(®istration.registration_id, url.as_str())?; - let result = cdp( + let controller = self.clone(); + let expected = registration.clone(); + let app = app.clone(); + let fence = fence.clone(); + let result = cdp_guarded( webview, "Page.navigate", json!({ "url": url.as_str() }), deadline, + move || controller.check_target_identity(&app, &expected, deadline, &fence), + 24 * 1024 * 1024, )?; if let Some(error) = result .get("errorText") @@ -798,11 +1059,76 @@ impl BrowserController { Ok(registration.clone()) } + fn document_version(&self, expected: &Registration) -> Result { + let inner = self.inner.0.lock().map_err(|error| error.to_string())?; + if inner.registrations.get(&expected.registration_id) != Some(expected) { + return Err("Browser target is no longer current".into()); + } + inner + .navigation_versions + .get(&expected.registration_id) + .copied() + .ok_or_else(|| "Browser document is unavailable".into()) + } + + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + fn check_target( + &self, + app: &AppHandle, + expected: &Registration, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) -> Result<(), String> { + self.check_target_identity(app, expected, deadline, fence)?; + let view = app + .get_webview(&expected.webview_label) + .ok_or("Browser preview is no longer available")?; + allowed_url(view.url().map_err(|error| error.to_string())?.as_str())?; + self.document_version(expected)?; + fence.check() + } + + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + fn check_target_identity( + &self, + app: &AppHandle, + expected: &Registration, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) -> Result<(), String> { + fence.check()?; + if Instant::now() >= deadline { + return Err("Native request expired before execution".into()); + } + if self.resolve(app, &expected.session_id)? != *expected { + return Err("Browser target is no longer current".into()); + } + let view = app + .get_webview(&expected.webview_label) + .ok_or("Browser preview is no longer available")?; + if view.window().label() != expected.window_label { + return Err("Browser target belongs to another window".into()); + } + self.document_version(expected)?; + fence.check() + } + + #[cfg(any(test, target_os = "linux", target_os = "macos"))] + fn check_history_registration(&self, expected: &Registration) -> Result<(), String> { + let current = self.owned_registration(&expected.window_label, &expected.registration_id)?; + if current.generation != expected.generation + || current.webview_label != expected.webview_label + { + return Err("Browser target changed during history request".into()); + } + Ok(()) + } + fn invalidate_page(&self, registration_id: &str) { if let Ok(mut inner) = self.inner.0.lock() { - inner - .page_leases - .retain(|_, lease| lease.registration.registration_id != registration_id); + inner.page_leases.retain(|_, lease| { + lease.registration.registration_id != registration_id || lease.document.is_some() + }); if let Some(version) = inner.navigation_versions.get_mut(registration_id) { *version = version.wrapping_add(1); } @@ -819,9 +1145,9 @@ impl BrowserController { { return; } - inner - .page_leases - .retain(|_, lease| lease.registration.registration_id != registration_id); + inner.page_leases.retain(|_, lease| { + lease.registration.registration_id != registration_id || lease.document.is_some() + }); if let Some(version) = inner.navigation_versions.get_mut(registration_id) { *version = version.wrapping_add(1); } @@ -909,7 +1235,13 @@ impl BrowserController { == Some(generation) { if let Some(expectation) = inner.page_load_expectations.get_mut(registration_id) { - if expectation.url == url && expectation.navigation_id.is_none() { + if expectation + .navigation_id + .is_some_and(|id| id != navigation_id) + { + expectation.result = + Some(Err("Browser preview navigation is no longer current".into())); + } else if expectation.url == url && expectation.navigation_id.is_none() { expectation.navigation_id = Some(navigation_id); } } @@ -935,7 +1267,8 @@ impl BrowserController { return; } if let Some(expectation) = inner.page_load_expectations.get_mut(registration_id) { - if expectation.navigation_id == Some(navigation_id) { + if expectation.navigation_id == Some(navigation_id) && expectation.result.is_none() + { expectation.result = Some(error.map_or(Ok(()), Err)); } } @@ -1026,13 +1359,6 @@ fn request_deadline(deadline_ms: u64) -> Result { .ok_or_else(|| "Invalid native request deadline".to_string()) } -fn validate_bounds(bounds: BrowserTargetBounds) -> Result<(), String> { - if bounds.width == 0 || bounds.height == 0 || bounds.width > 16_384 || bounds.height > 16_384 { - return Err("Invalid browser target bounds".to_string()); - } - Ok(()) -} - fn allowed_url(raw: &str) -> Result { let url = tauri::Url::parse(raw).map_err(|_| navigation_error())?; is_allowed_url(&url) @@ -1040,13 +1366,6 @@ fn allowed_url(raw: &str) -> Result { .ok_or_else(navigation_error) } -fn is_allowed_url(url: &tauri::Url) -> bool { - matches!(url.scheme(), "http" | "https") - && url.host().is_some() - && url.username().is_empty() - && url.password().is_none() -} - fn navigation_error() -> String { "Browser navigation requires a credential-free HTTP(S) URL".to_string() } @@ -1055,12 +1374,12 @@ fn no_browser_target_error() -> String { "No visible local browser target for this session".to_string() } -#[cfg(not(windows))] +#[cfg(any(test, not(windows)))] fn unsupported() -> String { - "Native browser control is only supported by the Tauri Windows runtime".to_string() + "Native browser previews are unavailable on this platform.".to_string() } -#[cfg(windows)] +#[cfg(any(windows, target_os = "linux", target_os = "macos"))] fn command_url(command: &Value) -> Result<&str, String> { command .get("url") @@ -1078,9 +1397,8 @@ fn install_webview2_handlers( ) -> Result<(), String> { use std::sync::mpsc; use webview2_com::{ - CoTaskMemPWSTR, Microsoft::Web::WebView2::Win32::COREWEBVIEW2_PERMISSION_STATE_DENY, - NavigationCompletedEventHandler, NavigationStartingEventHandler, - PermissionRequestedEventHandler, SourceChangedEventHandler, + CoTaskMemPWSTR, NavigationCompletedEventHandler, NavigationStartingEventHandler, + SourceChangedEventHandler, }; let app = webview.app_handle().clone(); @@ -1089,15 +1407,6 @@ fn install_webview2_handlers( .with_webview(move |platform| { let result = (|| { let core = unsafe { platform.controller().CoreWebView2() }?; - let permission = PermissionRequestedEventHandler::create(Box::new(|_, args| { - if let Some(args) = args { - unsafe { args.SetState(COREWEBVIEW2_PERMISSION_STATE_DENY)? }; - } - Ok(()) - })); - let mut permission_token = 0; - unsafe { core.add_PermissionRequested(&permission, &mut permission_token)? }; - let started_controller = controller.clone(); let started_registration_id = registration_id.clone(); let started = NavigationStartingEventHandler::create(Box::new(move |_, args| { @@ -1298,6 +1607,27 @@ mod regressions; #[cfg(test)] mod tests { + #[test] + fn webkit_hosts_publish_native_browser_profiles_and_automation() { + let source = include_str!("local_windows.rs"); + let webkit = source + .lines() + .find(|line| line.contains("reason:'webkit'")) + .unwrap(); + assert!(webkit.contains("emulation:true,automation:true")); + assert!(include_str!("cli_manager.rs") + .contains("cfg!(any(windows, target_os = \"macos\", target_os = \"linux\"))")); + } + + #[test] + fn renderer_registration_can_require_hidden_creation() { + let input: super::BrowserTargetRegistration = serde_json::from_value(serde_json::json!({ + "sessionId": "session", "registrationId": "registration", "url": "https://example.org", + "bounds": { "x": 0, "y": 0, "width": 300, "height": 200 }, "visible": false + })) + .unwrap(); + assert_eq!(input.visible, Some(false)); + } use super::*; #[test] @@ -1334,6 +1664,7 @@ mod tests { url: "https://example.com/".to_string(), owner: None, failed_owners: HashSet::new(), + fence: None, }, ); @@ -1400,6 +1731,8 @@ mod tests { 7, Some("Browser navigation failed: ConnectionAborted".to_string()), ); + // WebKitGTK emits Finished after LoadFailed for the same load. + controller.mark_page_finished("registration", 1, 7, None); assert_eq!( controller .wait_for_page_load( diff --git a/packages/tauri-app/src-tauri/src/browser_controller_page.rs b/packages/tauri-app/src-tauri/src/browser_controller_page.rs index cfc3a68346..bc56854ec6 100644 --- a/packages/tauri-app/src-tauri/src/browser_controller_page.rs +++ b/packages/tauri-app/src-tauri/src/browser_controller_page.rs @@ -1,5 +1,10 @@ //! Private backend-only protocol adapter. Never register these methods as Tauri commands. use super::*; +#[path = "browser_page_operation.rs"] +mod operations; +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "browser_page_webkit.rs"] +mod webkit; #[derive(Clone)] pub(super) struct PageLease { @@ -8,34 +13,9 @@ pub(super) struct PageLease { operation_id: String, pub(super) generation: String, pub(super) expires: Instant, -} - -fn page_method_allowed(method: &str) -> bool { - matches!( - method, - "Accessibility.getFullAXTree" - | "DOM.resolveNode" - | "DOM.scrollIntoViewIfNeeded" - | "DOM.getContentQuads" - | "DOM.getNodeForLocation" - | "Page.getLayoutMetrics" - | "Runtime.callFunctionOn" - | "Runtime.evaluate" - | "Runtime.releaseObjectGroup" - | "Input.insertText" - | "Input.dispatchMouseEvent" - | "Input.dispatchKeyEvent" - ) -} - -fn page_params(method: &str, params: Value) -> Result { - if !page_method_allowed(method) { - return Err("Unsupported browser page command".into()); - } - if !params.is_object() || params.to_string().len() > 256 * 1024 { - return Err("Invalid or oversized browser page parameters".into()); - } - Ok(params) + pub(super) document: Option, + #[cfg(any(target_os = "linux", target_os = "macos"))] + pub(super) held: crate::embedded_view::input::Held, } impl BrowserController { @@ -84,6 +64,9 @@ impl BrowserController { generation: self.page_generation(®istration, navigation), registration, expires: Instant::now() + Duration::from_secs(30), + document: None, + #[cfg(any(target_os = "linux", target_os = "macos"))] + held: Default::default(), }; inner.page_leases.insert(operation_id.into(), lease.clone()); Ok(lease) @@ -121,12 +104,13 @@ impl BrowserController { }) || inner.registrations.get(&lease.registration.registration_id) != Some(&lease.registration) - || !inner - .navigation_versions - .get(&lease.registration.registration_id) - .is_some_and(|navigation| { - self.page_generation(&lease.registration, *navigation) == lease.generation - }) + || (lease.document.is_none() + && !inner + .navigation_versions + .get(&lease.registration.registration_id) + .is_some_and(|navigation| { + self.page_generation(&lease.registration, *navigation) == lease.generation + })) { return Err("Browser page lease is no longer current".into()); } @@ -176,13 +160,15 @@ impl BrowserController { } } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] fn check_page( &self, app: &AppHandle, lease: &PageLease, deadline: Instant, + fence: &crate::native_request::RequestFence, ) -> Result { + fence.check()?; self.check_page_state(lease, deadline)?; if self.resolve(app, &lease.session_id)? != lease.registration { return Err("Browser page lease is no longer current".into()); @@ -197,17 +183,28 @@ impl BrowserController { return Err("Browser page lease is no longer current".into()); } self.check_page_state(lease, deadline)?; + fence.check()?; + #[cfg(any(target_os = "linux", target_os = "macos"))] + if let Some(document) = &lease.document { + let response = + self.webkit_read(app, lease, &json!({"op":"checkpoint"}), deadline, fence)?; + if response["document"].as_str() != Some(document.as_str()) { + return Err("Browser page document changed; inspect again".into()); + } + } Ok(url) } - #[cfg(windows)] + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] pub(super) fn page_request( &self, app: &AppHandle, method: &str, input: &Value, deadline: Instant, + fence: &crate::native_request::RequestFence, ) -> Result { + operations::envelope(method, input)?; let session_id = input["sessionID"] .as_str() .ok_or("Invalid browser page identity")?; @@ -219,85 +216,137 @@ impl BrowserController { return Err("Invalid browser page identity".into()); } if method == "browser.page.end" { + #[cfg(any(target_os = "linux", target_os = "macos"))] + self.webkit_cleanup(app, session_id, operation_id, deadline, fence); self.end_page(session_id, operation_id); return Ok(json!({})); } let begin = method == "browser.page.begin"; + #[cfg(any(target_os = "linux", target_os = "macos"))] + if begin { + self.webkit_expire(app, deadline, fence); + } let lease = if begin { self.reserve_page(self.resolve(app, session_id)?, operation_id)? } else { self.page_lease(input)? }; + #[cfg(any(target_os = "linux", target_os = "macos"))] + let mut lease = lease; + let operation = if method == "browser.page.send" { + Some(operations::parse( + input + .get("operation") + .cloned() + .ok_or("Invalid browser page operation")?, + )?) + } else { + None + }; let result = (|| { - let url = self.check_page(app, &lease, deadline)?; + let url = self.check_page(app, &lease, deadline, fence)?; + #[cfg(any(target_os = "linux", target_os = "macos"))] + if begin { + let response = + self.webkit_read(app, &lease, &json!({"op":"checkpoint"}), deadline, fence)?; + let document = response["document"] + .as_str() + .ok_or("Missing WebKit document identity")? + .to_string(); + self.check_page_state(&lease, deadline)?; + lease.generation = format!( + "{}:{}:{}", + self.run_id, lease.registration.generation, document + ); + lease.document = Some(document); + self.inner + .0 + .lock() + .map_err(|error| error.to_string())? + .page_leases + .insert(operation_id.into(), lease.clone()); + } if method == "browser.page.check" { return Ok(json!({ "url": url })); } + if !begin && method != "browser.page.send" { + return Err("Invalid browser page method".into()); + } + #[cfg(windows)] let command = if begin { - "Accessibility.enable" + Some(("Accessibility.enable", json!({}))) } else { - input["method"] - .as_str() - .ok_or("Invalid browser page command")? + operation.as_ref().and_then(operations::Operation::cdp) }; - let params = if begin { + #[cfg(windows)] + let response = if let Some((command, params)) = command { + let webview = app + .get_webview(&lease.registration.webview_label) + .ok_or("Browser preview is no longer available")?; + let controller = self.clone(); + let guard_lease = lease.clone(); + let guard_app = app.clone(); + let guard_fence = fence.clone(); + cdp_guarded( + &webview, + command, + params, + deadline.min(lease.expires), + move || { + controller + .check_page(&guard_app, &guard_lease, deadline, &guard_fence) + .map(|_| ()) + }, + 4 * 1024 * 1024, + )? + } else { json!({}) + }; + #[cfg(any(target_os = "linux", target_os = "macos"))] + let response = if let Some(_) = &operation { + let response = + self.webkit_read(app, &lease, &input["operation"], deadline, fence)?; + if response["document"].as_str() != lease.document.as_deref() { + return Err("Browser page document changed; inspect again".into()); + } + response["result"].clone() } else { - page_params(command, input.get("params").cloned().unwrap_or(json!({})))? + json!({}) }; - let webview = app - .get_webview(&lease.registration.webview_label) - .ok_or("Browser preview is no longer available")?; - let controller = self.clone(); - let guard_lease = lease.clone(); - let guard_app = app.clone(); - let response = cdp_guarded( - &webview, - command, - params, - deadline.min(lease.expires), - move || { - controller - .check_page(&guard_app, &guard_lease, deadline) - .map(|_| ()) - }, - 4 * 1024 * 1024, - )?; - let url = self.check_page(app, &lease, deadline)?; + let url = self.check_page(app, &lease, deadline, fence)?; if begin { - Ok(json!({ "generation": lease.generation, "url": url })) + Ok( + json!({ "generation": lease.generation, "url": url, "driver": if cfg!(windows) {"cdp"} else {"webkit"}, "contractVersion":1 }), + ) } else { - Ok(response) + #[cfg(windows)] + { + let operation = operation.as_ref().ok_or("Invalid browser page operation")?; + Ok(operation.result(response)) + } + #[cfg(any(target_os = "linux", target_os = "macos"))] + { + Ok(response) + } } })(); if result.is_err() { + #[cfg(any(target_os = "linux", target_os = "macos"))] + if std::env::var_os("CN_INPUT_TRACE").is_some() { + eprintln!( + "native page {method} op={} function={}: {}", + input["operation"]["op"], + input["operation"]["function"], + result.as_ref().unwrap_err() + ); + } + #[cfg(windows)] self.release_page(&lease); + #[cfg(any(target_os = "linux", target_os = "macos"))] + if lease.held.lock().is_ok_and(|held| held.is_empty()) { + self.release_page(&lease); + } } result } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn protocol_allowlist_and_parameter_budget_are_fixed() { - for method in [ - "Page.navigate", - "Network.enable", - "Browser.close", - "DOM.getBoxModel", - "Accessibility.enable", - ] { - assert!(page_params(method, json!({})).is_err()); - } - assert!(page_params("Input.insertText", json!({ "text": "x" })).is_ok()); - assert!(page_params( - "Runtime.evaluate", - json!({ "expression": "x".repeat(256 * 1024) }) - ) - .is_err()); - assert!(page_params("Runtime.evaluate", Value::Null).is_err()); - } -} diff --git a/packages/tauri-app/src-tauri/src/browser_controller_regressions.rs b/packages/tauri-app/src-tauri/src/browser_controller_regressions.rs index 3c83312b2f..31c15355e4 100644 --- a/packages/tauri-app/src-tauri/src/browser_controller_regressions.rs +++ b/packages/tauri-app/src-tauri/src/browser_controller_regressions.rs @@ -47,12 +47,18 @@ fn tauri_authority_does_not_grant_parent_capabilities_to_preview_children() { url: url.parse().unwrap(), }; for command in &commands { - assert!( - authority - .resolve_access(command, OWNER, "browser-preview", &origin) - .is_none(), - "preview inherited {command} at {url}" - ); + for (window, child) in [ + (OWNER, "browser-preview"), + (OWNER, "embedded-remote-preview"), + ("browser-popup-preview", "browser-popup-preview"), + ] { + assert!( + authority + .resolve_access(command, window, child, &origin) + .is_none(), + "{child} inherited {command} at {url}" + ); + } } } let origin = tauri::ipc::Origin::Remote { @@ -139,8 +145,9 @@ fn registration() -> Registration { } fn controller_with_registration() -> (BrowserController, Registration) { - let controller = BrowserController::new(std::path::PathBuf::new()); + let mut controller = BrowserController::new(std::path::PathBuf::new()); let registration = registration(); + controller.embedded_views = EmbeddedViews::for_test(OWNER, ®istration.webview_label); { let mut inner = controller.inner.0.lock().unwrap(); inner @@ -153,6 +160,219 @@ fn controller_with_registration() -> (BrowserController, Registration) { (controller, registration) } +#[test] +fn windows_and_webkit_navigation_recover_from_blank_without_relaxing_reads() { + // Both dispatchers must admit recovery by identity, not the current document's URL. + for source in [ + include_str!("browser_controller.rs"), + include_str!("browser_navigation_webkit.rs"), + ] { + let admission = source + .split("fn navigate_and_wait(") + .nth(1) + .unwrap() + .split("self.invalidate_page(") + .next() + .unwrap(); + assert!(admission.contains("self.check_target_identity(")); + assert!(!admission.contains("self.check_target(")); + + let (app, _, child) = app_with_preview(); + let (controller, registration) = controller_with_registration(); + let deadline = Instant::now() + Duration::from_secs(10); + let expires = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64 + + 10_000; + let fence = crate::native_request::RequestFence::new(expires, || true); + controller + .check_target(app.handle(), ®istration, deadline, &fence) + .unwrap(); + child.navigate("about:blank".parse().unwrap()).unwrap(); + controller + .check_target_identity(app.handle(), ®istration, deadline, &fence) + .unwrap(); + assert!(controller + .check_target(app.handle(), ®istration, deadline, &fence) + .is_err()); + assert!(allowed_url("file:///private").is_err()); + let target = allowed_url("https://example.com/recovered").unwrap(); + child.navigate(target).unwrap(); + controller + .check_target(app.handle(), ®istration, deadline, &fence) + .unwrap(); + assert_eq!( + child.url().unwrap().as_str(), + "https://example.com/recovered" + ); + + // Results and visibility retain their stricter checks after recovery. + child.navigate("about:blank".parse().unwrap()).unwrap(); + assert!(controller + .check_target(app.handle(), ®istration, deadline, &fence) + .is_err()); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .get_mut(®istration.registration_id) + .unwrap() + .visible = false; + assert!(controller + .check_target_identity(app.handle(), ®istration, deadline, &fence) + .is_err()); + } +} + +#[test] +fn replacing_a_registration_clears_its_emulation_profile() { + let (controller, mut current) = controller_with_registration(); + controller + .inner + .0 + .lock() + .unwrap() + .emulation_profiles + .insert(current.registration_id.clone(), "mobile".into()); + current.generation += 1; + controller + .publish_registration(current.clone(), 0, "https://example.com/") + .unwrap(); + assert!(!controller + .inner + .0 + .lock() + .unwrap() + .emulation_profiles + .contains_key(¤t.registration_id)); +} + +#[test] +fn capture_document_identity_changes_on_navigation_hide_and_replacement() { + let (controller, expected) = controller_with_registration(); + let document = controller.document_version(&expected).unwrap(); + controller.invalidate_page(&expected.registration_id); + assert_ne!(controller.document_version(&expected).unwrap(), document); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .get_mut(&expected.registration_id) + .unwrap() + .visible = false; + assert!(controller.document_version(&expected).is_err()); + controller.inner.0.lock().unwrap().registrations.insert( + expected.registration_id.clone(), + Registration { + generation: expected.generation + 1, + ..expected.clone() + }, + ); + assert!(controller.document_version(&expected).is_err()); +} + +#[test] +fn native_open_claim_cannot_be_reclaimed_after_deadline_or_backend_retirement() { + use std::sync::atomic::AtomicBool; + let (controller, _) = controller_with_registration(); + let current = Arc::new(AtomicBool::new(true)); + let predicate = current.clone(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + controller.inner.0.lock().unwrap().open_claims.insert( + "pending".into(), + OpenClaim { + session_id: "session".into(), + url: "https://example.com/".into(), + owner: None, + failed_owners: HashSet::new(), + fence: Some(crate::native_request::RequestFence::new( + now + 10_000, + move || predicate.load(Ordering::SeqCst), + )), + }, + ); + assert!(controller.claim_open(OWNER, "pending")); + current.store(false, Ordering::SeqCst); + assert!(!controller.claim_open(OWNER, "pending")); + assert!(controller.release_claim(OWNER, "pending").is_none()); + controller + .inner + .0 + .lock() + .unwrap() + .open_claims + .get_mut("pending") + .unwrap() + .fence = Some(crate::native_request::RequestFence::new(0, || true)); + assert!(!controller.claim_open(OWNER, "pending")); +} + +#[test] +fn a_different_native_navigation_supersedes_a_bound_load_even_if_it_finishes_late() { + let (controller, expected) = controller_with_registration(); + let sequence = controller + .prepare_page_load(&expected.registration_id, "https://example.com/wanted") + .unwrap(); + controller.mark_page_started( + &expected.registration_id, + expected.generation, + 1, + "https://example.com/wanted".into(), + ); + controller.mark_page_started( + &expected.registration_id, + expected.generation, + 2, + "https://example.com/user".into(), + ); + controller.mark_page_finished(&expected.registration_id, expected.generation, 1, None); + assert!(controller + .wait_for_page_load( + &expected.registration_id, + sequence, + Instant::now() + Duration::from_secs(1) + ) + .unwrap_err() + .contains("no longer current")); +} + +#[test] +fn history_requires_current_owner_and_generation_but_survives_hide() { + let (controller, expected) = controller_with_registration(); + assert!(controller.check_history_registration(&expected).is_ok()); + let mut foreign = expected.clone(); + foreign.window_label = OTHER.into(); + assert!(controller.check_history_registration(&foreign).is_err()); + let mut stale = expected.clone(); + stale.generation += 1; + assert!(controller.check_history_registration(&stale).is_err()); + { + let mut inner = controller.inner.0.lock().unwrap(); + inner + .registrations + .get_mut(&expected.registration_id) + .unwrap() + .visible = false; + } + assert!(controller.check_history_registration(&expected).is_ok()); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .remove(&expected.registration_id); + assert!(controller.check_history_registration(&expected).is_err()); +} + #[test] fn only_primary_renderer_reload_disposes_its_native_browser_children() { let (app, owner, child) = app_with_preview(); @@ -218,6 +438,76 @@ fn only_primary_renderer_reload_disposes_its_native_browser_children() { .is_ok()); } +#[test] +fn older_creation_and_foreign_window_cannot_replace_current_registration() { + let (controller, mut current) = controller_with_registration(); + current.generation = 3; + controller + .publish_registration(current.clone(), 0, "https://example.com/") + .unwrap(); + let mut stale = current.clone(); + stale.generation = 2; + assert!(controller + .publish_registration(stale, 0, "https://example.com/") + .is_err()); + let mut foreign = current.clone(); + foreign.window_label = OTHER.into(); + foreign.generation = 4; + assert!(controller + .publish_registration(foreign, 0, "https://example.com/") + .is_err()); + assert_eq!( + controller + .owned_registration(OWNER, "preview") + .unwrap() + .generation, + 3 + ); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .remove("preview"); + current.generation = 2; + assert!(controller + .publish_registration(current, 0, "https://example.com/") + .is_err()); +} + +#[test] +fn hiding_revokes_page_authority_even_when_native_hide_fails() { + let (app, _, child) = app_with_preview(); + let (controller, registration) = controller_with_registration(); + let lease = controller + .reserve_page(registration, &uuid::Uuid::new_v4().to_string()) + .unwrap(); + child.close().unwrap(); + assert!(controller + .update( + app.handle(), + OWNER, + BrowserTargetUpdate { + registration_id: "preview".into(), + bounds: None, + visible: Some(false), + presentation: None, + } + ) + .is_err()); + assert!( + !controller + .owned_registration(OWNER, "preview") + .unwrap() + .visible + ); + assert!(controller + .check_page_state(&lease, Instant::now() + Duration::from_secs(1)) + .is_err()); + assert!(controller.inner.0.lock().unwrap().page_leases.is_empty()); +} + #[test] fn fragment_navigation_completes_without_webview2_document_events() { let (controller, registration) = controller_with_registration(); @@ -385,6 +675,58 @@ fn page_generation_survives_end_but_not_navigation_registration_or_host_replacem assert_ne!(other.generation, first.generation); } +#[test] +fn document_bound_page_leases_preserve_uri_changes_and_registration_fences() { + let (controller, registration) = controller_with_registration(); + let operation = uuid::Uuid::new_v4().to_string(); + let mut lease = controller.reserve_page(registration, &operation).unwrap(); + lease.document = Some("isolated-document-token".into()); + controller + .inner + .0 + .lock() + .unwrap() + .page_leases + .insert(operation.clone(), lease.clone()); + controller.invalidate_page_for_generation("preview", 1); + controller.invalidate_page("preview"); + let deadline = Instant::now() + Duration::from_secs(1); + assert!(controller.check_page_state(&lease, deadline).is_ok()); + // The native adapter checks the document token; URI callbacks keep the lease. + assert!(controller.check_page_state(&lease, Instant::now()).is_err()); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .get_mut("preview") + .unwrap() + .visible = false; + assert!(controller.check_page_state(&lease, deadline).is_err()); + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .get_mut("preview") + .unwrap() + .visible = true; + controller + .inner + .0 + .lock() + .unwrap() + .registrations + .get_mut("preview") + .unwrap() + .generation += 1; + assert!(controller.check_page_state(&lease, deadline).is_err()); + controller.end_page("session", &operation); + assert!(controller.check_page_state(&lease, deadline).is_err()); +} + #[test] fn page_lease_identity_limits_expiry_and_cleanup_are_exact() { let (controller, registration) = controller_with_registration(); diff --git a/packages/tauri-app/src-tauri/src/browser_emulation_layout.rs b/packages/tauri-app/src-tauri/src/browser_emulation_layout.rs new file mode 100644 index 0000000000..49c2743b3d --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_emulation_layout.rs @@ -0,0 +1,229 @@ +use super::{validate_bounds, BrowserTargetBounds}; +use serde::Deserialize; +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +pub(crate) struct Viewport { + pub width: u32, + pub height: u32, +} +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Presentation { + #[serde(default)] + pub css: bool, + pub viewport: Option, +} +#[derive(Clone, Copy, Debug)] +pub(super) struct Canvas { + pub bounds: BrowserTargetBounds, + pub presentation: Presentation, +} +pub(super) struct Layout { + pub bounds: BrowserTargetBounds, + pub zoom: f64, +} +pub(super) fn validate(size: Viewport) -> Result<(), String> { + if size.width == 0 || size.height == 0 || size.width > 16384 || size.height > 16384 { + Err("Invalid browser CSS viewport".into()) + } else { + Ok(()) + } +} +pub(super) fn layout( + canvas: Canvas, + pixel_scale: f64, + device_scale: f64, + target: Option, +) -> Result { + validate_bounds(canvas.bounds)?; + if !pixel_scale.is_finite() + || !device_scale.is_finite() + || pixel_scale <= 0.0 + || device_scale <= 0.0 + { + return Err("Invalid native preview scale".into()); + } + let mut area = canvas.bounds; + if canvas.presentation.css { + area = BrowserTargetBounds { + x: (area.x as f64 * pixel_scale).round() as i32, + y: (area.y as f64 * pixel_scale).round() as i32, + width: (area.width as f64 * pixel_scale).round() as u32, + height: (area.height as f64 * pixel_scale).round() as u32, + }; + } + validate_bounds(area)?; + let target = target.or(canvas.presentation.viewport).or_else(|| { + canvas.presentation.css.then_some(Viewport { + width: canvas.bounds.width, + height: canvas.bounds.height, + }) + }); + let Some(size) = target else { + return Ok(Layout { + bounds: area, + zoom: 1.0, + }); + }; + validate(size)?; + let aw = (area.width as f64 / device_scale).floor() as u32; + let ah = (area.height as f64 / device_scale).floor() as u32; + // Native GTK allocations are integer DIPs. Find a nearby aspect ratio whose + // zoom interval gives the exact integer CSS dimensions on both axes. + let max_width = aw.min((ah as f64 * size.width as f64 / size.height as f64).ceil() as u32 + 1); + for width in (1..=max_width).rev() { + let height = width as f64 * size.height as f64 / size.width as f64; + for height in [height.floor() as u32, height.ceil() as u32] { + if height == 0 || height > ah { + continue; + } + let lower = (width as f64 / (size.width + 1) as f64) + .max(height as f64 / (size.height + 1) as f64); + let upper = (width as f64 / size.width as f64).min(height as f64 / size.height as f64); + if lower >= upper { + continue; + } + let exact = width as f64 == size.width as f64 * upper + && height as f64 == size.height as f64 * upper + && (upper * 64.0).fract() == 0.0; + let zoom = if exact { upper } else { (lower + upper) / 2.0 }; + let w = (width as f64 * device_scale).round() as u32; + let h = (height as f64 * device_scale).round() as u32; + return Ok(Layout { + bounds: BrowserTargetBounds { + x: area + .x + .checked_add(((area.width - w) / 2) as i32) + .ok_or("Invalid browser target bounds")?, + y: area.y, + width: w, + height: h, + }, + zoom, + }); + } + } + Err("Browser preview is too small for this viewport".into()) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn css_viewports_survive_native_scale_and_clipping() { + for size in [ + Viewport { + width: 1440, + height: 900, + }, + Viewport { + width: 768, + height: 1024, + }, + Viewport { + width: 1024, + height: 768, + }, + Viewport { + width: 390, + height: 844, + }, + Viewport { + width: 844, + height: 390, + }, + ] { + for (width, height, scale) in [ + (500, 600, 1.0), + (750, 900, 1.0), + (1000, 1200, 2.0), + (585, 1266, 1.0), + ] { + let result = layout( + Canvas { + bounds: BrowserTargetBounds { + x: 10, + y: 60, + width, + height, + }, + presentation: Presentation::default(), + }, + 1.0, + scale, + Some(size), + ) + .unwrap(); + let zoom = result.zoom as f32 as f64; + assert_eq!( + (result.bounds.width as f64 / scale / zoom).floor() as u32, + size.width + ); + assert_eq!( + (result.bounds.height as f64 / scale / zoom).floor() as u32, + size.height + ); + assert!(result.bounds.width <= width && result.bounds.height <= height); + } + } + for device in [1.0, 2.0] { + for app_zoom in [0.8, 1.0, 1.25, 1.5] { + let result = layout( + Canvas { + bounds: BrowserTargetBounds { + x: 10, + y: 60, + width: 500, + height: 400, + }, + presentation: Presentation { + css: true, + viewport: None, + }, + }, + device * app_zoom, + device, + None, + ) + .unwrap(); + let zoom = result.zoom as f32 as f64; + assert_eq!( + (result.bounds.width as f64 / device / zoom).floor() as u32, + 500 + ); + assert_eq!( + (result.bounds.height as f64 / device / zoom).floor() as u32, + 400 + ); + } + } + for (x, width) in [(0, u32::MAX), (i32::MAX, 500)] { + assert!(layout( + Canvas { + bounds: BrowserTargetBounds { + x, + y: 0, + width, + height: 400 + }, + presentation: Presentation::default(), + }, + 1.0, + 1.0, + Some(Viewport { + width: 390, + height: 844 + }) + ) + .is_err()); + } + assert!(validate(Viewport { + width: 0, + height: 844 + }) + .is_err()); + assert!(validate(Viewport { + width: 390, + height: 16385 + }) + .is_err()); + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_emulation_webkit.rs b/packages/tauri-app/src-tauri/src/browser_emulation_webkit.rs new file mode 100644 index 0000000000..341a4c6fb3 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_emulation_webkit.rs @@ -0,0 +1,172 @@ +use super::viewport::{Canvas, Presentation, Viewport}; +use super::*; +const MOBILE_UA: &str = + "Mozilla/5.0 (Mobile) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile Safari/605.1.15"; +fn profile(preset: &str) -> Result<(Option, f64), String> { + if preset == "none" { + return Ok((None, 0.0)); + } + if !matches!(preset, "mobile" | "mobileLandscape") { + return Err("Invalid browser emulation profile".into()); + } + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Profiles { + mobile: Viewport, + device_scale_factor: f64, + } + let data: Profiles = serde_json::from_str(include_str!( + "../../../ui/src/lib/native/browser-emulation.json" + )) + .map_err(|e| e.to_string())?; + let size = if preset == "mobileLandscape" { + Viewport { + width: data.mobile.height, + height: data.mobile.width, + } + } else { + data.mobile + }; + Ok((Some(size), data.device_scale_factor)) +} +impl BrowserController { + fn configure_webkit( + &self, + app: &AppHandle, + registration: &Registration, + canvas: Canvas, + preset: &str, + ) -> Result<(), String> { + let primary = app + .get_webview(®istration.window_label) + .ok_or("Browser renderer is unavailable")?; + let (scale, device) = crate::embedded_view::mobile::scale(&primary)?; + let (target, density) = profile(preset)?; + let layout = viewport::layout(canvas, scale, device, target)?; + validate_bounds(layout.bounds)?; + let view = app + .get_webview(®istration.webview_label) + .ok_or("Browser preview is unavailable")?; + if self.owned_registration(®istration.window_label, ®istration.registration_id)? + != *registration + { + return Err("Browser target changed before emulation".into()); + } + self.inner + .0 + .lock() + .map_err(|e| e.to_string())? + .page_leases + .retain(|_, lease| lease.registration.registration_id != registration.registration_id); + self.invalidate_page_for_generation(®istration.registration_id, registration.generation); + crate::embedded_view::mobile::profile( + &view, + if preset == "none" { "" } else { MOBILE_UA }, + layout.zoom, + density, + )?; + self.embedded_views.set_bounds( + app, + ®istration.window_label, + ®istration.webview_label, + layout.bounds, + )?; + if self.owned_registration(®istration.window_label, ®istration.registration_id)? + != *registration + { + return Err("Browser target changed during emulation".into()); + } + Ok(()) + } + pub(super) fn resize_webkit( + &self, + app: &AppHandle, + registration: &Registration, + bounds: BrowserTargetBounds, + presentation: Option, + ) -> Result<(), String> { + let _lock = self.emulation_lock.lock().map_err(|e| e.to_string())?; + let canvas = Canvas { + bounds, + presentation: presentation.unwrap_or_default(), + }; + let (preset, previous) = { + let inner = self.inner.0.lock().map_err(|e| e.to_string())?; + ( + inner + .emulation_profiles + .get(®istration.registration_id) + .cloned() + .unwrap_or_else(|| "none".into()), + inner.canvases.get(®istration.registration_id).copied(), + ) + }; + if let Err(error) = self.configure_webkit(app, registration, canvas, &preset) { + if let Some(previous) = previous { + let _ = self.configure_webkit(app, registration, previous, &preset); + } + return Err(error); + } + let mut inner = self.inner.0.lock().map_err(|e| e.to_string())?; + if inner.registrations.get(®istration.registration_id) != Some(registration) { + return Err("Browser target changed before viewport publication".into()); + } + inner + .canvases + .insert(registration.registration_id.clone(), canvas); + Ok(()) + } + pub(super) fn emulate( + &self, + app: &AppHandle, + owner: &str, + input: &BrowserTargetAction, + ) -> Result<(), String> { + let preset = input.preset.as_deref().unwrap_or(""); + profile(preset)?; + if let Some(size) = input.viewport { + viewport::validate(size)?; + } + let _lock = self.emulation_lock.lock().map_err(|e| e.to_string())?; + let registration = self.owned_registration(owner, &input.registration_id)?; + let (previous, canvas) = { + let inner = self.inner.0.lock().map_err(|e| e.to_string())?; + ( + inner + .emulation_profiles + .get(&input.registration_id) + .cloned() + .unwrap_or_else(|| "none".into()), + *inner + .canvases + .get(&input.registration_id) + .ok_or("Browser viewport is unavailable")?, + ) + }; + let mut next = canvas; + next.presentation.viewport = input.viewport; + if previous == preset && canvas.presentation == next.presentation { + return Ok(()); + } + if let Err(error) = self.configure_webkit(app, ®istration, next, preset) { + let _ = self.configure_webkit(app, ®istration, canvas, &previous); + return Err(error); + } + let view = app + .get_webview(®istration.webview_label) + .ok_or("Browser preview is unavailable")?; + if let Err(error) = view.reload() { + let _ = self.configure_webkit(app, ®istration, canvas, &previous); + return Err(error.to_string()); + } + let mut inner = self.inner.0.lock().map_err(|e| e.to_string())?; + if inner.registrations.get(&input.registration_id) != Some(®istration) { + return Err("Browser target changed before emulation publication".into()); + } + inner + .emulation_profiles + .insert(input.registration_id.clone(), preset.into()); + inner.canvases.insert(input.registration_id.clone(), next); + Ok(()) + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_history.rs b/packages/tauri-app/src-tauri/src/browser_history.rs new file mode 100644 index 0000000000..591fb7a6d8 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_history.rs @@ -0,0 +1,76 @@ +//! Numeric handles for a bounded window of retained native history objects. +use std::sync::atomic::{AtomicI64, Ordering}; + +static NEXT_ID: AtomicI64 = AtomicI64::new(1); + +pub(super) fn bounded( + entries: Vec, + current: Option, + token: impl Fn(&T) -> usize, +) -> Vec { + let index = entries + .iter() + .position(|entry| Some(token(entry)) == current) + .unwrap_or(0); + let start = index + .saturating_sub(16) + .min(entries.len().saturating_sub(32)); + entries.into_iter().skip(start).take(32).collect() +} + +#[derive(Default)] +pub(super) struct HistoryIds { + entries: Vec<(usize, i64)>, +} + +impl HistoryIds { + // Call while the preceding snapshot's objects are still retained: a removed + // native object's address cannot be recycled into a live numeric handle. + pub(super) fn reconcile(&mut self, tokens: impl Iterator) -> Vec { + let entries = tokens + .take(32) + .map(|token| { + let id = self + .entries + .iter() + .find(|(old, _)| *old == token) + .map(|(_, id)| *id) + .unwrap_or_else(|| NEXT_ID.fetch_add(1, Ordering::Relaxed)); + (token, id) + }) + .collect::>(); + let ids = entries.iter().map(|(_, id)| *id).collect(); + self.entries = entries; + ids + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn browser_history_native_identity_branch_and_registration() { + let mut history = HistoryIds::default(); + let original = history.reconcile([10, 20, 30].into_iter()); + // URL changes (redirect/replaceState), duplicate URLs and cursor moves + // do not enter identity assignment; only the native object does. + assert_eq!(history.reconcile([10, 20, 30].into_iter()), original); + let branch = history.reconcile([10, 20, 40].into_iter()); + assert_eq!(&branch[..2], &original[..2]); + assert!(!branch.contains(&original[2])); + let reused = history.reconcile([10, 20, 30].into_iter()); + assert_ne!(reused[2], original[2]); + let mut replacement = HistoryIds::default(); + assert!(!replacement + .reconcile([10, 20, 30].into_iter()) + .iter() + .any(|id| reused.contains(id))); + assert_eq!(history.reconcile(0..100).len(), 32); + for current in 0..100 { + let entries = bounded((0..100).collect(), Some(current), |token| *token); + assert_eq!(entries.len(), 32); + assert!(entries.contains(¤t)); + } + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_history_linux.rs b/packages/tauri-app/src-tauri/src/browser_history_linux.rs new file mode 100644 index 0000000000..b9fe5fe8ef --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_history_linux.rs @@ -0,0 +1,58 @@ +use gtk::glib::object::{ObjectExt, ObjectType}; +use webkit2gtk::{BackForwardListExt, BackForwardListItem, BackForwardListItemExt, WebViewExt}; + +#[derive(Clone)] +pub(super) struct Entry(BackForwardListItem); + +impl Entry { + pub(super) fn token(&self) -> usize { + self.0.as_ptr() as usize + } + + pub(super) fn url(&self) -> String { + self.0.uri().map(|uri| uri.to_string()).unwrap_or_default() + } +} + +pub(super) fn snapshot(webview: &webkit2gtk::WebView) -> (Vec, Option) { + let Some(list) = webview.back_forward_list() else { + return (Vec::new(), None); + }; + let current = list.current_item().map(|item| item.as_ptr() as usize); + // nth_item is relative to the current item and keeps native ordering, + // including multiple same-document entries with identical URLs. + let entries = (-31..32) + .filter_map(|offset| list.nth_item(offset)) + .map(Entry) + .collect(); + (entries, current) +} + +pub(super) fn go(webview: &webkit2gtk::WebView, entry: &Entry) -> Result<(), String> { + webview.go_to_back_forward_list_item(&entry.0); + Ok(()) +} + +pub(super) fn observe(webview: &webkit2gtk::WebView, changed: impl Fn(String) + 'static) { + use std::rc::Rc; + let changed = Rc::new(changed); + let uri_changed = changed.clone(); + webview.connect_uri_notify(move |view| { + if let Some(uri) = view.uri() { + uri_changed(uri.to_string()); + } + }); + if let Some(list) = webview.back_forward_list() { + let weak = webview.downgrade(); + // The generated binding omits this signal's GList argument. GLib's + // generic signal API handles it without taking ownership of that list. + list.connect_local("changed", false, move |_| { + if let Some(view) = weak.upgrade() { + if let Some(uri) = view.uri() { + changed(uri.to_string()); + } + } + None + }); + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_history_macos.rs b/packages/tauri-app/src-tauri/src/browser_history_macos.rs new file mode 100644 index 0000000000..76f4534647 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_history_macos.rs @@ -0,0 +1,108 @@ +//! WKWebView history, called exclusively from Tauri's UI-thread callback. +//! +//! Keep the previous snapshot alive while taking its replacement. Retention +//! prevents pointer reuse while the common registry assigns monotonic public IDs. +//! Store entries in the UI-thread registry and drop them there during cleanup. + +use std::ffi::c_void; + +use objc2::{rc::Retained, MainThreadMarker}; +use objc2_web_kit::{WKBackForwardListItem, WKWebView}; + +const LIMIT: usize = 32; + +#[derive(Clone)] +pub(super) struct Entry(Retained); + +impl Entry { + pub(super) fn token(&self) -> usize { + Retained::as_ptr(&self.0) as usize + } + + pub(super) fn url(&self) -> String { + // SAFETY: Entry is main-thread-only, as is its retained WebKit item. + unsafe { self.0.URL() } + .absoluteString() + .map(|url| url.to_string()) + .unwrap_or_default() + } +} + +// Select a contiguous chronological window, filling spare capacity at either end. +fn window(back: usize, forward: usize) -> (isize, isize) { + let before = back + .min(LIMIT / 2) + .max(LIMIT.saturating_sub(1 + forward).min(back)); + let after = forward.min(LIMIT - 1 - before); + (-(before as isize), after as isize) +} + +/// `webview` must be a live WKWebView supplied by Tauri's UI-thread callback. +/// A null pointer yields an empty snapshot. +pub(super) fn snapshot(webview: *mut c_void) -> (Vec, Option) { + assert!( + MainThreadMarker::new().is_some(), + "WebKit history requires the UI thread" + ); + // SAFETY: The caller supplies the live native view for the duration of this call. + let Some(webview) = (unsafe { webview.cast::().as_ref() }) else { + return (Vec::new(), None); + }; + // SAFETY: All WebKit accesses occur on the main thread with a live view. + unsafe { + let list = webview.backForwardList(); + let Some(current) = list.currentItem() else { + return (Vec::new(), None); + }; + let current_token = Retained::as_ptr(¤t) as usize; + // Probe only the bounded neighbourhood; avoid materializing the full list. + let back = (1..LIMIT) + .take_while(|offset| list.itemAtIndex(-(*offset as isize)).is_some()) + .count(); + let forward = (1..LIMIT) + .take_while(|offset| list.itemAtIndex(*offset as isize).is_some()) + .count(); + let (start, end) = window(back, forward); + let entries = (start..=end) + .filter_map(|offset| list.itemAtIndex(offset).map(Entry)) + .collect(); + (entries, Some(current_token)) + } +} + +/// `webview` must be a live WKWebView supplied by Tauri's UI-thread callback. +pub(super) fn go(webview: *mut c_void, entry: &Entry) -> Result<(), String> { + let (entries, current) = snapshot(webview); + if !entries + .iter() + .any(|candidate| candidate.token() == entry.token()) + { + return Err("Native history entry is stale".into()); + } + if current == Some(entry.token()) { + return Ok(()); + } + // SAFETY: snapshot validated the live view and membership on this UI thread. + let navigation = unsafe { (&*webview.cast::()).goToBackForwardListItem(&entry.0) }; + navigation + .map(|_| ()) + .ok_or_else(|| "Native history navigation was rejected".into()) +} + +#[cfg(test)] +mod tests { + use super::{window, LIMIT}; + + #[test] + fn bounded_window_keeps_current_and_fills_edges() { + for back in 0..=64 { + for forward in 0..=64 { + let (start, end) = window(back, forward); + assert!(start <= 0 && end >= 0); + assert!(-start <= back as isize && end <= forward as isize); + assert_eq!((end - start + 1) as usize, LIMIT.min(back + 1 + forward)); + } + } + assert_eq!(window(64, 64), (-16, 15)); + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_history_webkit.rs b/packages/tauri-app/src-tauri/src/browser_history_webkit.rs new file mode 100644 index 0000000000..d0bf39e5ff --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_history_webkit.rs @@ -0,0 +1,187 @@ +use super::history_ids::{bounded, HistoryIds}; +use super::{allowed_url, BrowserController, Registration}; +use serde_json::{json, Value}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::mpsc; +use std::time::{Duration, Instant}; +use tauri::Manager; + +#[cfg(target_os = "linux")] +#[path = "browser_history_linux.rs"] +mod platform; +#[cfg(target_os = "macos")] +#[path = "browser_history_macos.rs"] +mod platform; + +#[derive(Default)] +struct History { + ids: HistoryIds, + retained: Vec, + handles: Vec, +} + +thread_local! { + // Native objects are retained and released only on the UI thread. + static HISTORIES: RefCell> = RefCell::new(HashMap::new()); +} + +pub(super) fn remove(app: &tauri::AppHandle, label: String) { + let _ = app.run_on_main_thread(move || { + HISTORIES.with(|histories| histories.borrow_mut().remove(&label)); + }); +} + +#[cfg(target_os = "linux")] +pub(super) fn install( + webview: &tauri::Webview, + controller: BrowserController, + registration: Registration, +) -> Result<(), String> { + let app = webview.app_handle().clone(); + let (sender, receiver) = mpsc::sync_channel(1); + webview + .with_webview(move |native| { + let changed = move |url: String| { + controller.emit_webkit_navigation(&app, ®istration, &url); + }; + #[cfg(target_os = "linux")] + platform::observe(&native.inner(), changed); + let _ = sender.send(()); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Timed out configuring native browser history".to_string()) +} + +#[cfg(target_os = "macos")] +pub(super) fn install( + _: &tauri::Webview, + _: BrowserController, + _: Registration, +) -> Result<(), String> { + Ok(()) +} + +#[cfg(target_os = "macos")] +pub(super) fn observe( + app: tauri::AppHandle, + controller: BrowserController, + registration: Registration, +) { + // WKBackForwardList has no public change notification for repeated same-URL + // pushState. Hidden previews also publish navigations for saved restoration. + // ponytail: one sleeping worker per preview; share a sampler if tab counts + // make worker stacks significant. Native objects stay on the UI thread. + std::thread::spawn(move || { + let mut previous = Value::Null; + loop { + let Ok(current) = controller + .owned_registration(®istration.window_label, ®istration.registration_id) + else { + break; + }; + if current.generation != registration.generation { + break; + } + let Some(webview) = app.get_webview(¤t.webview_label) else { + break; + }; + if let Ok(history) = action(&controller, &webview, ¤t, None) { + if previous != history { + if let Some(index) = history["index"].as_u64() { + if let Some(url) = history["entries"][index as usize]["url"].as_str() { + controller.emit_webkit_navigation(&app, ®istration, url); + } + } + previous = history; + } + } + std::thread::sleep(Duration::from_millis(if current.visible { + 250 + } else { + 1000 + })); + } + }); +} + +pub(super) fn action( + controller: &BrowserController, + webview: &tauri::Webview, + registration: &Registration, + entry_id: Option, +) -> Result { + let expected = registration.clone(); + let current = controller.clone(); + let deadline = Instant::now() + Duration::from_secs(5); + let (sender, receiver) = mpsc::sync_channel(1); + webview + .with_webview(move |native| { + let result: Result = (|| { + if Instant::now() >= deadline { + return Err("Native browser history request expired".into()); + } + current.check_history_registration(&expected)?; + let view = native.inner(); + #[cfg(target_os = "linux")] + let view = &view; + let (entries, current_token) = platform::snapshot(view); + let entries = bounded(entries, current_token, platform::Entry::token) + .into_iter() + .filter(|entry| { + let url = entry.url(); + url.len() <= 2048 && allowed_url(&url).is_ok() + }) + .collect::>(); + HISTORIES.with(|histories| { + let mut histories = histories.borrow_mut(); + let history = histories.entry(expected.webview_label.clone()).or_default(); + let handles = history + .ids + .reconcile(entries.iter().map(|entry| entry.token())); + // Reconcile before dropping the old native references. + history.retained = entries; + history.handles = handles; + if let Some(id) = entry_id { + let index = history + .handles + .iter() + .position(|handle| *handle == id) + .ok_or("Invalid browser history entry")?; + // Release the RefCell borrow before native navigation, whose + // signals can reenter the observer synchronously. + let entry = history.retained[index].clone(); + drop(histories); + current.check_history_registration(&expected)?; + if Instant::now() >= deadline { + return Err("Native browser history request expired".into()); + } + platform::go(view, &entry)?; + return Ok(Value::Null); + } + let index = history + .retained + .iter() + .position(|entry| Some(entry.token()) == current_token) + .map(|index| index as i64) + .unwrap_or(-1); + let entries = history + .retained + .iter() + .zip(&history.handles) + .map(|(entry, id)| json!({ "id": id, "url": entry.url() })) + .collect::>(); + Ok(json!({ "entries": entries, "index": index })) + }) + })(); + let _ = sender.send(result); + }) + .map_err(|error| error.to_string())?; + let result = receiver + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .map_err(|_| "Timed out reading native browser history".to_string())??; + controller.check_history_registration(registration)?; + Ok(result) +} diff --git a/packages/tauri-app/src-tauri/src/browser_navigation_webkit.rs b/packages/tauri-app/src-tauri/src/browser_navigation_webkit.rs new file mode 100644 index 0000000000..0316576f50 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_navigation_webkit.rs @@ -0,0 +1,240 @@ +//! Native load completion/failure for the private backend browser channel. +use super::*; +use std::sync::mpsc; + +#[cfg(target_os = "linux")] +pub(super) fn install( + view: &tauri::Webview, + controller: BrowserController, + registration: Registration, +) -> Result<(), String> { + use std::cell::Cell; + use std::rc::Rc; + use webkit2gtk::WebViewExt; + let (sender, receiver) = mpsc::sync_channel(1); + view.with_webview(move |native| { + let token = Rc::new(Cell::new(0u64)); + let started_token = token.clone(); + let started = controller.clone(); + let expected = registration.clone(); + native + .inner() + .connect_load_changed(move |view, event| match event { + webkit2gtk::LoadEvent::Started => { + started_token.set(started_token.get().wrapping_add(1)); + if let Some(url) = view.uri().filter(|url| url.as_str() != "about:blank") { + started.mark_page_started( + &expected.registration_id, + expected.generation, + started_token.get(), + url.to_string(), + ); + } + } + webkit2gtk::LoadEvent::Finished => started.mark_page_finished( + &expected.registration_id, + expected.generation, + started_token.get(), + None, + ), + _ => {} + }); + native.inner().connect_load_failed(move |_, _, _, error| { + controller.mark_page_finished( + ®istration.registration_id, + registration.generation, + token.get(), + Some(format!("Browser navigation failed: {error}")), + ); + false + }); + let _ = sender.send(()); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Timed out configuring native navigation".to_string()) +} + +#[cfg(target_os = "macos")] +mod macos { + use super::*; + use std::ffi::{c_char, c_void, CStr}; + struct Observer { + controller: BrowserController, + registration: Registration, + } + extern "C" { + fn cn_observe_load( + view: *mut c_void, + callback: unsafe extern "C" fn(*mut c_void, u64, i32, *const c_char, *const c_char), + release: unsafe extern "C" fn(*mut c_void), + context: *mut c_void, + ) -> i32; + pub(super) fn cn_navigate(view: *mut c_void, url: *const c_char) -> u64; + } + unsafe extern "C" fn released(context: *mut c_void) { + drop(unsafe { Box::from_raw(context.cast::()) }); + } + unsafe extern "C" fn changed( + context: *mut c_void, + token: u64, + event: i32, + url: *const c_char, + error: *const c_char, + ) { + let observer = unsafe { &*context.cast::() }; + let registration = &observer.registration; + if event == 0 { + if !url.is_null() { + let url = unsafe { CStr::from_ptr(url) } + .to_string_lossy() + .into_owned(); + if url != "about:blank" { + observer.controller.mark_page_started( + ®istration.registration_id, + registration.generation, + token, + url, + ); + } + } + } else { + let failure = (event == 2).then(|| { + if error.is_null() { + "Browser navigation failed".into() + } else { + format!( + "Browser navigation failed: {}", + unsafe { CStr::from_ptr(error) }.to_string_lossy() + ) + } + }); + observer.controller.mark_page_finished( + ®istration.registration_id, + registration.generation, + token, + failure, + ); + } + } + pub(crate) fn install( + view: &tauri::Webview, + controller: BrowserController, + registration: Registration, + ) -> Result<(), String> { + let (sender, receiver) = mpsc::sync_channel(1); + view.with_webview(move |native| { + let context = Box::into_raw(Box::new(Observer { + controller, + registration, + })) + .cast::(); + let ok = unsafe { cn_observe_load(native.inner(), changed, released, context) }; + if ok == 0 { + unsafe { released(context) }; + } + let _ = sender.send(if ok == 0 { + Err("Native navigation delegate is unavailable".to_string()) + } else { + Ok(()) + }); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Timed out configuring native navigation".to_string())? + } +} +#[cfg(target_os = "macos")] +pub(super) use macos::install; + +impl BrowserController { + pub(super) fn navigate_and_wait( + &self, + app: &AppHandle, + registration: &Registration, + view: &tauri::Webview, + url: &tauri::Url, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) -> Result<(), String> { + self.check_target_identity(app, registration, deadline, fence)?; + let previous = view.url().map_err(|error| error.to_string())?; + let mut previous_base = previous.clone(); + previous_base.set_fragment(None); + let mut target_base = url.clone(); + target_base.set_fragment(None); + let fragment_only = previous != *url && previous_base == target_base; + self.invalidate_page(®istration.registration_id); + let sequence = self.prepare_page_load(®istration.registration_id, url.as_str())?; + let expected = registration.clone(); + let controller = self.clone(); + let app = app.clone(); + let queued_fence = fence.clone(); + let target = url.clone(); + let (sender, receiver) = mpsc::sync_channel(1); + view.with_webview(move |native| { + let result: Result<(), String> = (|| { + controller.check_target_identity(&app, &expected, deadline, &queued_fence)?; + if controller.page_load_expectation(&expected.registration_id, target.as_str())? + != Some(sequence) + { + return Err("Browser preview navigation is no longer current".into()); + } + #[cfg(target_os = "linux")] + { + use webkit2gtk::WebViewExt; + native.inner().load_uri(target.as_str()); + } + #[cfg(target_os = "macos")] + { + let target = std::ffi::CString::new(target.as_str()) + .map_err(|error| error.to_string())?; + let token = unsafe { macos::cn_navigate(native.inner(), target.as_ptr()) }; + if token == 0 { + return Err("Native browser navigation was refused".into()); + } + let mut inner = controller + .inner + .0 + .lock() + .map_err(|error| error.to_string())?; + let expectation = inner + .page_load_expectations + .get_mut(&expected.registration_id) + .filter(|entry| entry.sequence == sequence) + .ok_or("Browser preview navigation is no longer current")?; + // WKWebView can return a navigation object for a fragment + // change without issuing document completion callbacks. + if !fragment_only { + expectation.navigation_id = Some(token); + } + } + Ok(()) + })(); + let _ = sender.send(result); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .map_err(|_| "Timed out dispatching native navigation".to_string())??; + if fragment_only { + loop { + self.check_target(view.app_handle(), registration, deadline, fence)?; + let current = view.url().map_err(|error| error.to_string())?; + if current == *url { + self.complete_same_document_navigation( + registration, + sequence, + current.as_str(), + )?; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + } + self.wait_for_page_load(®istration.registration_id, sequence, deadline)?; + self.check_target(view.app_handle(), registration, deadline, fence) + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_page_operation.rs b/packages/tauri-app/src-tauri/src/browser_page_operation.rs new file mode 100644 index 0000000000..daf09d363f --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_page_operation.rs @@ -0,0 +1,445 @@ +//! Closed semantic operation schema; fixed programs come from the shared registry. +use serde::Deserialize; +use serde_json::{json, Map, Value}; +use std::sync::OnceLock; +const GROUP: &str = "codenomad-automation"; +const INVALID: &str = "Unsupported or invalid browser page operation parameters"; +fn registry() -> &'static Value { + static REGISTRY: OnceLock = OnceLock::new(); + REGISTRY.get_or_init(|| { + serde_json::from_str(include_str!( + "../../../server/src/automation/page/functions.generated.json" + )) + .expect("generated fixed function registry") + }) +} + +#[derive(Deserialize)] +#[serde(tag = "op", rename_all = "kebab-case", deny_unknown_fields)] +pub(super) enum Operation { + Tree, + Viewport, + ReleaseHandles, + Checkpoint, + Resolve { + node: u64, + }, + ScrollIntoView { + node: u64, + }, + Geometry { + node: u64, + }, + HitTest { + x: f64, + y: f64, + }, + Call { + function: String, + handle: Option, + args: Vec, + }, + Pointer { + event: Value, + }, + Wheel { + event: Value, + }, + Keyboard { + event: Value, + }, + InsertText { + text: String, + }, +} +fn keys(value: &Value, allowed: &[&str], required: &[&str]) -> Result<(), String> { + let object = value.as_object().ok_or(INVALID)?; + if object.keys().any(|key| !allowed.contains(&key.as_str())) + || required.iter().any(|key| !object.contains_key(*key)) + { + return Err(INVALID.into()); + } + Ok(()) +} +fn number(value: &Value, max: f64) -> bool { + value + .as_f64() + .is_some_and(|value| value.is_finite() && value.abs() <= max) +} +fn integer(value: &Value, max: u64) -> bool { + value.as_u64().is_some_and(|value| value <= max) +} +fn handle(value: &Value) -> bool { + value + .as_str() + .is_some_and(|value| !value.is_empty() && value.len() <= 512) +} +pub(super) fn envelope(method: &str, value: &Value) -> Result<(), String> { + let mut allowed = vec!["sessionID", "operationID"]; + let mut required = allowed.clone(); + if method == "browser.page.send" { + allowed.extend(["generation", "operation"]); + required.extend(["generation", "operation"]); + } else if method == "browser.page.check" { + allowed.push("generation"); + required.push("generation"); + } else if method == "browser.page.end" { + allowed.push("generation"); + } + keys(value, &allowed, &required)?; + if value.get("generation").is_some_and(|value| !handle(value)) { + return Err(INVALID.into()); + } + Ok(()) +} + +pub(super) fn parse(value: Value) -> Result { + if value.to_string().len() > 256 * 1024 { + return Err(INVALID.into()); + } + let operation: Operation = + serde_json::from_value(value.clone()).map_err(|_| INVALID.to_string())?; + match &operation { + Operation::Tree + | Operation::Viewport + | Operation::ReleaseHandles + | Operation::Checkpoint => keys(&value, &["op"], &["op"])?, + Operation::Resolve { node } + | Operation::Geometry { node } + | Operation::ScrollIntoView { node } + if *node == 0 || *node > 9_007_199_254_740_991 => + { + return Err(INVALID.into()) + } + Operation::HitTest { x, y } + if !x.is_finite() + || !y.is_finite() + || x.abs() > 10_000_000.0 + || y.abs() > 10_000_000.0 + || x.fract() != 0.0 + || y.fract() != 0.0 => + { + return Err(INVALID.into()) + } + Operation::Call { + function, + handle: target, + args, + } => { + let definition = registry().get(function).ok_or(INVALID)?; + if definition["scope"] == "element" { + if !target.as_ref().is_some_and(|id| handle(&json!(id))) { + return Err(INVALID.into()); + } + } else if value.get("handle").is_some() { + return Err(INVALID.into()); + } + let rules = definition["args"].as_array().ok_or(INVALID)?; + if rules.len() != args.len() { + return Err(INVALID.into()); + } + for (rule, argument) in rules.iter().zip(args) { + let valid = match rule.as_str() { + Some("string") => argument.is_string(), + Some("boolean") => argument.is_boolean(), + Some("strings") => argument + .as_array() + .is_some_and(|items| items.iter().all(Value::is_string)), + Some("handle") => { + keys(argument, &["handle"], &["handle"]).is_ok() + && handle(&argument["handle"]) + } + _ => false, + }; + if !valid { + return Err(INVALID.into()); + } + } + } + Operation::Pointer { event } + | Operation::Wheel { event } + | Operation::Keyboard { event } => { + let keyboard = matches!(&operation, Operation::Keyboard { .. }); + let wheel = matches!(&operation, Operation::Wheel { .. }); + if keyboard { + keys( + event, + &[ + "type", + "key", + "code", + "windowsVirtualKeyCode", + "modifiers", + "text", + "unmodifiedText", + "location", + "timestamp", + "buttons", + ], + &["type"], + )?; + if !matches!( + event["type"].as_str(), + Some("keyDown" | "rawKeyDown" | "keyUp") + ) { + return Err(INVALID.into()); + } + for key in ["key", "code", "text", "unmodifiedText"] { + if let Some(value) = event.get(key) { + if !value + .as_str() + .is_some_and(|text| !text.is_empty() && text.len() <= 256) + { + return Err(INVALID.into()); + } + } + } + } else { + let allowed = if wheel { + vec![ + "type", + "x", + "y", + "deltaX", + "deltaY", + "modifiers", + "timestamp", + ] + } else { + vec![ + "type", + "x", + "y", + "button", + "buttons", + "clickCount", + "modifiers", + "timestamp", + ] + }; + keys( + event, + &allowed, + if wheel { + &["type", "x", "y", "deltaX", "deltaY"] + } else { + &["type", "x", "y"] + }, + )?; + if !number(&event["x"], 10_000_000.0) || !number(&event["y"], 10_000_000.0) { + return Err(INVALID.into()); + } + if wheel { + if event["type"] != "mouseWheel" + || !number(&event["deltaX"], 10_000_000.0) + || !number(&event["deltaY"], 10_000_000.0) + { + return Err(INVALID.into()); + } + } else { + if !matches!( + event["type"].as_str(), + Some("mouseMoved" | "mousePressed" | "mouseReleased") + ) { + return Err(INVALID.into()); + } + if let Some(button) = event.get("button") { + if !matches!(button.as_str(), Some("left" | "right" | "middle" | "none")) { + return Err(INVALID.into()); + } + } + } + } + for (key, max) in [ + ("modifiers", 15), + ("buttons", 7), + ("clickCount", 3), + ("windowsVirtualKeyCode", 65535), + ("location", 3), + ] { + if let Some(value) = event.get(key) { + if !integer(value, max) { + return Err(INVALID.into()); + } + } + } + if let Some(value) = event.get("timestamp") { + if !number(value, 9_007_199_254_740_991.0) { + return Err(INVALID.into()); + } + } + } + _ => {} + } + Ok(operation) +} + +impl Operation { + pub(super) fn cdp(&self) -> Option<(&'static str, Value)> { + Some(match self { + Self::Tree => ("Accessibility.getFullAXTree", json!({})), + Self::Resolve { node } => ( + "DOM.resolveNode", + json!({"backendNodeId":node,"objectGroup":GROUP}), + ), + Self::ScrollIntoView { node } => { + ("DOM.scrollIntoViewIfNeeded", json!({"backendNodeId":node})) + } + Self::Geometry { node } => ("DOM.getContentQuads", json!({"backendNodeId":node})), + Self::Viewport => ("Page.getLayoutMetrics", json!({})), + Self::HitTest { x, y } => ( + "DOM.getNodeForLocation", + json!({"x":*x as i64,"y":*y as i64,"includeUserAgentShadowDOM":false,"ignorePointerEventsNone":false}), + ), + Self::Call { + function, + handle, + args, + } => { + let definition = ®istry()[function]; + if definition["scope"] == "element" { + ( + "Runtime.callFunctionOn", + json!({"objectId":handle,"functionDeclaration":definition["source"],"arguments":args.iter().map(|arg| if arg.get("handle").is_some() { json!({"objectId":arg["handle"]}) } else { json!({"value":arg}) }).collect::>(),"returnByValue":definition["handle"] != true,"objectGroup":GROUP}), + ) + } else if definition["handle"] == true { + ( + "Runtime.evaluate", + json!({"expression":definition["source"],"objectGroup":GROUP}), + ) + } else { + ( + "Runtime.evaluate", + json!({"expression":definition["source"],"returnByValue":true}), + ) + } + } + Self::Pointer { event } | Self::Wheel { event } => { + ("Input.dispatchMouseEvent", event.clone()) + } + Self::Keyboard { event } => ("Input.dispatchKeyEvent", event.clone()), + Self::InsertText { text } => ("Input.insertText", json!({"text":text})), + Self::ReleaseHandles => ("Runtime.releaseObjectGroup", json!({"objectGroup":GROUP})), + Self::Checkpoint => return None, + }) + } + pub(super) fn result(&self, raw: Value) -> Value { + match self { + Self::Tree => { + json!({"nodes":raw["nodes"].as_array().map(|nodes| nodes.iter().map(semantic_node).collect::>()).unwrap_or_default()}) + } + Self::Resolve { .. } => optional("handle", raw["object"].get("objectId")), + Self::Call { function, .. } => { + if let Some(error) = raw.get("exceptionDetails") { + return json!({"exception":error["exception"]["description"].as_str().or_else(||error["text"].as_str()).unwrap_or("")}); + } + if registry()[function]["handle"] == true { + optional("handle", raw["result"].get("objectId")) + } else { + optional("value", raw["result"].get("value")) + } + } + Self::Viewport => { + let viewport = raw + .get("cssLayoutViewport") + .filter(|value| !value.is_null()) + .unwrap_or(&raw["layoutViewport"]); + let mut result = optional("width", viewport.get("clientWidth")); + if let Some(height) = viewport.get("clientHeight") { + result["height"] = height.clone(); + } + result + } + Self::HitTest { .. } => optional("node", raw.get("backendNodeId")), + _ => raw, + } + } +} +fn optional(key: &str, value: Option<&Value>) -> Value { + let mut result = Map::new(); + if let Some(value) = value { + result.insert(key.into(), value.clone()); + } + Value::Object(result) +} +fn semantic_node(raw: &Value) -> Value { + let mut result = Map::new(); + for (key, source) in [ + ("id", "nodeId"), + ("parent", "parentId"), + ("children", "childIds"), + ("ignored", "ignored"), + ("node", "backendDOMNodeId"), + ] { + if let Some(value) = raw.get(source) { + result.insert(key.into(), value.clone()); + } + } + for key in ["role", "name", "description", "value"] { + if let Some(value) = raw[key].get("value") { + result.insert(key.into(), value.clone()); + } + } + if let Some(properties) = raw["properties"].as_array() { + result.insert( + "properties".into(), + Value::Array( + properties + .iter() + .map(|property| { + let mut result = optional("name", property.get("name")); + if let Some(value) = property["value"].get("value") { + result["value"] = value.clone(); + } + result + }) + .collect(), + ), + ); + } + Value::Object(result) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn closed_operations_refuse_scripts_unknown_fields_and_bad_args() { + let cases: Value = serde_json::from_str(include_str!( + "../../../server/src/automation/page/contract.cases.json" + )) + .unwrap(); + for value in cases["valid"].as_array().unwrap() { + assert!( + parse(value.clone()).is_ok(), + "valid operation rejected: {value}" + ); + } + for value in cases["invalid"].as_array().unwrap() { + assert!( + parse(value.clone()).is_err(), + "invalid operation accepted: {value}" + ); + } + for bad in [ + json!({"op":"Runtime.evaluate","expression":"alert(1)"}), + json!({"op":"tree","extra":true}), + json!({"op":"call","function":"mark-input","args":[]}), + json!({"op":"call","function":"select","handle":"h","args":["wrong"]}), + json!({"op":"pointer","event":{"type":"mouseMoved","x":0,"y":0,"arbitrary":true}}), + ] { + assert!(parse(bad).is_err()); + } + let call = parse( + json!({"op":"call","function":"set-value","handle":"h","args":["\";evil()",false]}), + ) + .unwrap(); + let (_, params) = call.cdp().unwrap(); + assert_eq!(params["arguments"][0]["value"], "\";evil()"); + assert!(!params["functionDeclaration"] + .as_str() + .unwrap() + .contains("evil()")); + assert!(parse(json!({"op":"checkpoint"})).unwrap().cdp().is_none()); + } +} diff --git a/packages/tauri-app/src-tauri/src/browser_page_webkit.rs b/packages/tauri-app/src-tauri/src/browser_page_webkit.rs new file mode 100644 index 0000000000..913ad7280c --- /dev/null +++ b/packages/tauri-app/src-tauri/src/browser_page_webkit.rs @@ -0,0 +1,166 @@ +//! Fixed isolated-world reads with registration/deadline fences on both sides. +use super::*; + +impl BrowserController { + pub(super) fn webkit_read( + &self, + app: &AppHandle, + lease: &PageLease, + operation: &Value, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) -> Result { + self.webkit_operation(app, lease, operation, deadline, fence, false) + } + fn webkit_operation( + &self, + app: &AppHandle, + lease: &PageLease, + operation: &Value, + deadline: Instant, + fence: &crate::native_request::RequestFence, + cleanup: bool, + ) -> Result { + let webview = app + .get_webview(&lease.registration.webview_label) + .ok_or("Browser preview is no longer available")?; + let controller = self.clone(); + let expected = lease.clone(); + let app = app.clone(); + let fence = fence.clone(); + let native = matches!( + operation["op"].as_str(), + Some("pointer" | "wheel" | "keyboard" | "insert-text") + ); + let version = self.document_version(&lease.registration)?; + let read = if native { + crate::embedded_view::input::Read::Input { + document: lease + .document + .clone() + .ok_or("Missing WebKit document identity")?, + operation: operation.clone(), + held: lease.held.clone(), + } + } else { + crate::embedded_view::input::Read::Page(operation.to_string()) + }; + let bytes = crate::embedded_view::input::read( + &webview, + read, + if cleanup { + deadline + } else { + deadline.min(lease.expires) + }, + move || { + fence.check()?; + if cleanup { + if !controller + .inner + .0 + .lock() + .map_err(|error| error.to_string())? + .page_leases + .get(&expected.operation_id) + .is_some_and(|lease| { + lease.generation == expected.generation + && lease.expires == expected.expires + }) + { + return Err("Browser page lease is no longer current".into()); + } + } else { + controller.check_page_state(&expected, deadline)?; + } + if native && controller.document_version(&expected.registration)? != version { + return Err("Browser page changed during native input".into()); + } + if controller.resolve(&app, &expected.session_id)? != expected.registration { + return Err("Browser page lease is no longer current".into()); + } + Ok(()) + }, + )?; + let response: Value = serde_json::from_slice(&bytes).map_err(|error| error.to_string())?; + if !response["document"] + .as_str() + .is_some_and(|token| !token.is_empty() && token.len() <= 128) + || !response["result"].is_object() + { + return Err("Invalid native semantic read response".into()); + } + Ok(response) + } + + pub(super) fn webkit_cleanup( + &self, + app: &AppHandle, + session: &str, + operation: &str, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) { + let lease = self.inner.0.lock().ok().and_then(|inner| { + inner + .page_leases + .get(operation) + .filter(|lease| lease.session_id == session) + .cloned() + }); + let Some(lease) = lease else { return }; + let releases = lease + .held + .lock() + .map(|held| held.clone()) + .unwrap_or_default(); + for (identity, release) in releases.into_iter().rev() { + let mut result = self.webkit_operation(app, &lease, &release, deadline, fence, true); + // A same-document navigation can fence an unsent release. Renew its + // document check once, only while that release is still outstanding. + // Admitted mutations and completed releases are never replayed. + if result + .as_ref() + .is_err_and(|error| error == "Browser page changed during native input") + && lease + .held + .lock() + .is_ok_and(|held| held.iter().any(|(id, _)| id == &identity)) + { + result = self.webkit_operation(app, &lease, &release, deadline, fence, true); + } + if let Err(error) = result { + if std::env::var_os("CN_INPUT_TRACE").is_some() { + eprintln!("native input cleanup: {error}"); + } + } + } + if let Ok(mut held) = lease.held.lock() { + held.clear(); + }; + } + pub(super) fn webkit_expire( + &self, + app: &AppHandle, + deadline: Instant, + fence: &crate::native_request::RequestFence, + ) { + let expired = self + .inner + .0 + .lock() + .map(|inner| { + inner + .page_leases + .values() + .filter(|lease| lease.expires <= Instant::now()) + .cloned() + .collect::>() + }) + .unwrap_or_default(); + for lease in expired { + self.webkit_cleanup(app, &lease.session_id, &lease.operation_id, deadline, fence); + self.end_page(&lease.session_id, &lease.operation_id); + } + } +} diff --git a/packages/tauri-app/src-tauri/src/cli_manager.rs b/packages/tauri-app/src-tauri/src/cli_manager.rs index 04d02dd130..b894eae9a0 100644 --- a/packages/tauri-app/src-tauri/src/cli_manager.rs +++ b/packages/tauri-app/src-tauri/src/cli_manager.rs @@ -1234,7 +1234,7 @@ impl CliProcessManager { #[cfg(not(windows))] let mut c = Command::new(&cmd.program); #[cfg(not(windows))] - c.args(&cmd.args); + c.args(&cmd.args).stdin(Stdio::piped()); #[cfg(target_os = "linux")] if shell_env.is_none() { crate::appimage_environment::use_host_environment(&mut c); @@ -1252,8 +1252,16 @@ impl CliProcessManager { // comes after Unix shell_env's env_clear, and the Windows launcher // inherits it before it starts Node. configure_backend_profile(&mut c, &manager.channel, &manager.config_identity, manager.original_config.as_deref()); - #[cfg(windows)] + c.env( + "CODENOMAD_TAURI_WEBKIT", + if cfg!(any(target_os = "macos", target_os = "linux")) { + "1" + } else { + "0" + }, + ); c.env("CODENOMAD_NATIVE_PARENT", "1"); + c.env("CODENOMAD_NATIVE_BROWSER_AUTOMATION", if cfg!(any(windows, target_os = "macos", target_os = "linux")) { "1" } else { "0" }); configure_spawn(&mut c); if let Some(ref cwd) = cwd { c.current_dir(cwd); @@ -1491,24 +1499,19 @@ impl CliProcessManager { && line.starts_with(crate::native_request::REQUEST_PREFIX) { if let Some(request) = crate::native_request::parse(line) { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_millis() as u64) - .unwrap_or(u64::MAX); - let result = if now >= request.deadline { - Err("Native request expired before execution".to_string()) - } else { + let current = manager.clone(); + let fence = crate::native_request::RequestFence::new(request.deadline, move || current.is_current_generation(generation)); + if let Some(response) = crate::native_request::dispatch(request, fence, |request, fence| { crate::handle_native_request( app, &request.method, - request.params, + request.params.clone(), request.deadline, + fence, ) - }; - manager.write_native_response( - generation, - &crate::native_request::response(&request.id, result), - ); + }) { + manager.write_native_response(generation, &response); + } } continue; } diff --git a/packages/tauri-app/src-tauri/src/client_state/cross_host.rs b/packages/tauri-app/src-tauri/src/client_state/cross_host.rs index 9b83e31898..7b3acaebcb 100644 --- a/packages/tauri-app/src-tauri/src/client_state/cross_host.rs +++ b/packages/tauri-app/src-tauri/src/client_state/cross_host.rs @@ -985,9 +985,10 @@ mod tests { .read_line(&mut line) .unwrap(); assert!(!line.is_empty()); - serde_json::from_str::(&line).unwrap()["acquired"] - .as_bool() - .unwrap() + let result: serde_json::Value = serde_json::from_str(&line).unwrap(); + let acquired = result["acquired"].as_bool().unwrap(); + if !acquired { eprintln!("Node election result: {result}"); } + acquired } fn stop_node(mut child: std::process::Child) { diff --git a/packages/tauri-app/src-tauri/src/embedded_view.rs b/packages/tauri-app/src-tauri/src/embedded_view.rs new file mode 100644 index 0000000000..cb9ee18e28 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view.rs @@ -0,0 +1,632 @@ +//! Owner-fenced native child views. Business/session state belongs to consumers. +use serde::Deserialize; +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime}; + +#[cfg(any(windows, target_os = "linux", target_os = "macos", test))] +#[path = "embedded_view/browser.rs"] +mod browser; +#[path = "embedded_view/fullscreen.rs"] +mod fullscreen; +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "embedded_view/input.rs"] +pub(crate) mod input; +#[cfg(target_os = "linux")] +#[path = "embedded_view/linux.rs"] +mod linux; +#[cfg(target_os = "macos")] +#[path = "embedded_view/macos.rs"] +mod macos; +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[path = "embedded_view/mobile.rs"] +pub(crate) mod mobile; +#[cfg(windows)] +#[path = "embedded_view/windows.rs"] +mod windows; +#[path = "embedded_view/zoom.rs"] +pub(crate) mod zoom; + +/// Full, normalized desktop identity. The caller resolves config aliases before startup. +pub(crate) struct StorageIdentity { + profile: String, + config: String, +} + +impl StorageIdentity { + pub(crate) fn new(profile: String, config: String) -> Self { + Self { profile, config } + } + + pub(crate) fn identifier(&self, domain: &str) -> [u8; 16] { + use sha2::{Digest, Sha256}; + let mut hash = Sha256::new(); + for part in [domain, self.profile.as_str(), self.config.as_str()] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + hash.finalize()[..16] + .try_into() + .expect("16-byte store identifier") + } +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +pub(crate) struct Bounds { + pub(crate) x: i32, + pub(crate) y: i32, + pub(crate) width: u32, + pub(crate) height: u32, +} + +pub(crate) fn validate_bounds(bounds: Bounds) -> Result<(), String> { + if bounds.width == 0 || bounds.height == 0 || bounds.width > 16_384 || bounds.height > 16_384 { + return Err("Invalid browser target bounds".to_string()); + } + Ok(()) +} + +pub(crate) fn is_allowed_url(url: &tauri::Url) -> bool { + matches!(url.scheme(), "http" | "https") + && url.host().is_some() + && url.username().is_empty() + && url.password().is_none() +} + +fn site_url_allowed(url: &tauri::Url, origin: Option<&str>) -> bool { + is_allowed_url(url) + || (url.scheme() == "about" && url.path() == "blank") + || (url.scheme() == "blob" + && tauri::Url::parse(url.path()).is_ok_and(|inner| { + is_allowed_url(&inner) + && Some(inner.origin().ascii_serialization().as_str()) == origin + })) +} + +pub(crate) fn browser_storage(profile: &Path) -> PathBuf { + profile.join("shared-v1") +} + +/// The directory selects file-backed stores; the domain separates macOS stores. +pub(crate) struct Storage { + pub(crate) directory: PathBuf, + pub(crate) domain: String, +} + +impl From for Storage { + fn from(directory: PathBuf) -> Self { + Self { + directory, + domain: "browser/shared-v1".into(), + } + } +} + +fn reserved_label(label: &str) -> bool { + label.starts_with("browser-") || label.starts_with("embedded-remote-") +} + +#[derive(Default)] +struct Inner { + records: HashMap, + sequence: u64, + fullscreen_windows: HashSet, +} + +#[derive(Clone, PartialEq, Eq)] +struct Record { + owner: String, + token: u64, + document: u64, + preparing: bool, + opener: Option, + origin: Option, + bounds: Option, + fullscreen: Option, +} + +#[derive(Clone, Default)] +pub(crate) struct EmbeddedViews(Arc>); + +impl EmbeddedViews { + #[cfg(test)] + pub(crate) fn for_test(owner: &str, label: &str) -> Self { + let views = Self::default(); + let record = views.reserve(owner, label).unwrap(); + views.finish_creation(label, &record).unwrap(); + views + } + + fn reserve(&self, owner: &str, label: &str) -> Result { + crate::identity::local_window_id(owner)?; + if !reserved_label(label) || label.ends_with('-') { + return Err("Invalid embedded view label".into()); + } + let mut inner = self.0.lock().map_err(|error| error.to_string())?; + if inner.records.contains_key(label) { + return Err("Embedded view already exists".into()); + } + inner.sequence = inner.sequence.wrapping_add(1); + let record = Record { + owner: owner.into(), + token: inner.sequence, + document: 0, + preparing: true, + opener: None, + origin: None, + bounds: None, + fullscreen: None, + }; + inner.records.insert(label.into(), record.clone()); + Ok(record) + } + + fn owned(&self, owner: &str, label: &str) -> Result { + crate::identity::local_window_id(owner)?; + let inner = self.0.lock().map_err(|error| error.to_string())?; + let record = inner + .records + .get(label) + .ok_or("Embedded view is no longer available")?; + if record.owner != owner { + return Err("Embedded view belongs to another window".into()); + } + Ok(record.clone()) + } + + fn remove_exact(&self, label: &str, record: &Record) -> bool { + let Ok(mut inner) = self.0.lock() else { + return false; + }; + if inner + .records + .get(label) + .is_some_and(|current| current.token == record.token) + { + inner.records.remove(label); + return true; + } + false + } + + fn finish_creation(&self, label: &str, record: &Record) -> Result<(), String> { + let mut inner = self.0.lock().map_err(|error| error.to_string())?; + let current = inner + .records + .get_mut(label) + .filter(|current| current.token == record.token) + .ok_or("Embedded view changed during creation")?; + current.preparing = false; + Ok(()) + } + + /// A reserved child always produces a decision, including when its record is missing. + /// Only the initial neutral document is allowed while native protections are installed. + pub(crate) fn navigation_allowed(&self, label: &str, url: &tauri::Url) -> Option { + let inner = self.0.lock().ok(); + if let Some(record) = inner.as_ref().and_then(|inner| inner.records.get(label)) { + let allowed = if label.starts_with("browser-") { + site_url_allowed(url, record.origin.as_deref()) + } else { + is_allowed_url(url) || (record.preparing && url.as_str() == "about:blank") + }; + return Some(allowed); + } + reserved_label(label).then_some(false) + } + + fn current(&self, label: &str, token: u64) -> bool { + self.0.lock().is_ok_and(|inner| { + inner + .records + .get(label) + .is_some_and(|record| record.token == token) + }) + } + + fn token(&self, label: &str) -> Option { + self.0 + .lock() + .ok()? + .records + .get(label) + .map(|record| record.token) + } + + fn observe_origin(&self, label: &str, token: u64, url: &tauri::Url) { + if is_allowed_url(url) { + if let Ok(mut inner) = self.0.lock() { + if let Some(record) = inner + .records + .get_mut(label) + .filter(|record| record.token == token) + { + record.origin = Some(url.origin().ascii_serialization()); + } + } + } + } + + /// Invalidate the whole tree before native destruction dispatches callbacks. + fn take_tree( + inner: &mut Inner, + label: &str, + token: u64, + include_root: bool, + ) -> Vec<(String, Record)> { + let Some(root) = inner + .records + .get(label) + .filter(|record| record.token == token) + else { + return Vec::new(); + }; + let owner = root.owner.clone(); + let mut labels = HashSet::from([label.to_string()]); + // ponytail: scan per tree depth; index parents if preview trees become large. + loop { + let count = labels.len(); + for (child, record) in &inner.records { + if record.owner == owner + && record + .opener + .as_ref() + .is_some_and(|parent| labels.contains(parent)) + { + labels.insert(child.clone()); + } + } + if labels.len() == count { + break; + } + } + if !include_root { + labels.remove(label); + } + labels + .into_iter() + .filter_map(|label| inner.records.remove(&label).map(|record| (label, record))) + .collect() + } + + fn dispose_records( + app: &AppHandle, + records: Vec<(String, Record)>, + ) -> Result<(), String> { + let mut failure = None; + for (label, record) in records { + if let Some(before) = record.fullscreen { + if let Some(view) = app.get_webview(&label) { + let _ = view.window().set_fullscreen(before); + } + } + let result = if record.opener.is_some() { + app.get_webview_window(&label) + .map(|window| window.destroy()) + } else { + app.get_webview(&label).map(|view| view.close()) + }; + if let Some(Err(error)) = result { + eprintln!("[browser-cleanup] {label}: {error}"); + failure.get_or_insert_with(|| error.to_string()); + } + } + failure.map_or(Ok(()), Err) + } + + fn dispose_tree( + &self, + app: &AppHandle, + label: &str, + token: u64, + ) -> Result<(), String> { + let records = self + .0 + .lock() + .map(|mut inner| Self::take_tree(&mut inner, label, token, true)) + .unwrap_or_default(); + Self::dispose_records(app, records) + } + + fn page_load( + &self, + view: &tauri::Webview, + token: u64, + payload: &tauri::webview::PageLoadPayload<'_>, + ) -> bool { + let Ok(mut inner) = self.0.lock() else { + return false; + }; + let Some(record) = inner + .records + .get_mut(view.label()) + .filter(|record| record.token == token) + else { + return false; + }; + let records = if matches!(payload.event(), tauri::webview::PageLoadEvent::Started) { + record.document = record.document.wrapping_add(1); + Self::take_tree(&mut inner, view.label(), token, false) + } else { + Vec::new() + }; + drop(inner); + let _ = Self::dispose_records(view.app_handle(), records); + self.observe_origin(view.label(), token, payload.url()); + self.current(view.label(), token) + } + + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + pub(crate) fn create( + &self, + window: &tauri::Window, + label: &str, + storage: impl Into, + bounds: Bounds, + on_page_load: impl Fn(tauri::Webview, tauri::webview::PageLoadPayload<'_>) + + Send + + Sync + + 'static, + on_navigation: impl Fn(&tauri::Url) -> bool + Send + Sync + 'static, + ) -> Result { + self.create_with( + window, + label, + storage, + bounds, + on_page_load, + on_navigation, + { + #[cfg(windows)] + { + windows::install + } + #[cfg(target_os = "linux")] + { + linux::install + } + #[cfg(target_os = "macos")] + { + macos::install + } + }, + ) + } + + #[cfg(any(windows, target_os = "linux", target_os = "macos", test))] + fn create_with( + &self, + window: &tauri::Window, + label: &str, + storage: impl Into, + bounds: Bounds, + on_page_load: impl Fn(tauri::Webview, tauri::webview::PageLoadPayload<'_>) + + Send + + Sync + + 'static, + on_navigation: impl Fn(&tauri::Url) -> bool + Send + Sync + 'static, + install: impl FnOnce(&tauri::Webview) -> Result<(), String>, + ) -> Result, String> { + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] + use tauri::webview::NewWindowResponse; + use tauri::webview::WebviewBuilder; + let storage = storage.into(); + validate_bounds(bounds)?; + #[cfg(target_os = "macos")] + let storage_identifier = window + .app_handle() + .try_state::() + .ok_or("Embedded view storage identity is unavailable")? + .identifier(&storage.domain); + if !window + .app_handle() + .get_webview(window.label()) + .is_some_and(|primary| primary.window().label() == window.label()) + { + return Err("Embedded view requires a local primary renderer".into()); + } + // Register before add_child: the host navigation interceptor runs during creation. + let record = self.reserve(window.label(), label)?; + if label.starts_with("browser-") { + self.install_fullscreen_window(window); + } + let policy = self.clone(); + let navigation_label = label.to_string(); + let page_policy = self.clone(); + let token = record.token; + let builder = WebviewBuilder::new( + label, + tauri::WebviewUrl::External("about:blank".parse().expect("static neutral URL")), + ) + .data_directory(storage.directory.clone()) + .focused(false) + .disable_drag_drop_handler() + .zoom_hotkeys_enabled(cfg!(windows)) + .on_page_load(move |view, payload| { + if page_policy.page_load(&view, token, &payload) { + on_page_load(view, payload); + } + }) + .on_navigation(move |url| { + let allowed = policy.current(&navigation_label, token) + && policy.navigation_allowed(&navigation_label, url) == Some(true); + allowed && on_navigation(url) + }) + .on_permission_request({ + let permissions = self.clone(); + let permission_label = label.to_string(); + move |view, kind| { + if permissions.current(&permission_label, token) { + browser::permission(view, kind) + } else { + tauri::webview::PermissionResponse::Deny + } + } + }); + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] + let builder = builder + .on_new_window(|_, _| NewWindowResponse::Deny) + .on_download(|_, _| false); + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let builder = { + let views = self.clone(); + let app = window.app_handle().clone(); + let owner = window.label().to_string(); + let opener = label.to_string(); + let browser = label.starts_with("browser-"); + let downloads = self.clone(); + let download_label = label.to_string(); + builder + .on_download(move |webview, event| { + browser + && downloads.current(&download_label, token) + && browser::download(webview, event) + }) + .on_new_window(move |url, features| { + if !views.current(&opener, token) { + return tauri::webview::NewWindowResponse::Deny; + } + views.open_popup(&app, &owner, &opener, &storage, url, features) + }) + }; + #[cfg(target_os = "macos")] + let builder = builder.data_store_identifier(storage_identifier); + // Tauri has no hidden-child builder flag. Keep the neutral child off-canvas + // until hide completes, then apply its real physical bounds while hidden. + let result = window + .add_child( + builder, + PhysicalPosition::new(-32_768, -32_768), + PhysicalSize::new(1, 1), + ) + .map_err(|error| format!("failed to create browser preview: {error}")); + let webview = match result { + Ok(webview) => webview, + Err(error) => { + self.remove_exact(label, &record); + return Err(error); + } + }; + let configured = webview + .hide() + .map_err(|error| error.to_string()) + .and_then(|()| install(&webview)) + .and_then(|()| self.set_bounds(window.app_handle(), window.label(), label, bounds)) + .and_then(|()| self.finish_creation(label, &record)); + if let Err(error) = configured { + self.remove_exact(label, &record); + let _ = webview.close(); + return Err(error); + } + Ok(webview) + } + + pub(crate) fn set_bounds( + &self, + app: &AppHandle, + owner: &str, + label: &str, + bounds: Bounds, + ) -> Result<(), String> { + validate_bounds(bounds)?; + let webview = self.webview(app, owner, label)?; + if let Ok(mut inner) = self.0.lock() { + if let Some(record) = inner.records.get_mut(label) { + if record.fullscreen.is_some() { + return Ok(()); + } + record.bounds = Some(bounds); + } + } + webview + .set_position(PhysicalPosition::new(bounds.x, bounds.y)) + .and_then(|()| webview.set_size(PhysicalSize::new(bounds.width, bounds.height))) + .map_err(|error| error.to_string()) + } + + pub(crate) fn set_visible( + &self, + app: &AppHandle, + owner: &str, + label: &str, + visible: bool, + ) -> Result<(), String> { + let webview = self.webview(app, owner, label)?; + if !visible { + let _ = self.set_fullscreen(app, label, false); + } + if visible { + webview.show() + } else { + webview.hide() + } + .map_err(|error| error.to_string()) + } + + fn webview( + &self, + app: &AppHandle, + owner: &str, + label: &str, + ) -> Result, String> { + self.owned(owner, label)?; + let webview = app + .get_webview(label) + .ok_or("Embedded view is no longer available")?; + if webview.window().label() != owner { + return Err("Embedded view belongs to another window".into()); + } + Ok(webview) + } + + pub(crate) fn close( + &self, + app: &AppHandle, + owner: &str, + label: &str, + ) -> Result<(), String> { + crate::identity::local_window_id(owner)?; + // Read once so concurrent closes stay idempotent. + let record = { + let inner = self.0.lock().map_err(|error| error.to_string())?; + let Some(record) = inner.records.get(label) else { + return Ok(()); + }; + if record.owner != owner { + return Err("Embedded view belongs to another window".into()); + } + record.clone() + }; + let webview = app.get_webview(label); + if webview + .as_ref() + .is_some_and(|webview| webview.window().label() != owner) + { + return Err("Embedded view belongs to another window".into()); + } + self.dispose_tree(app, label, record.token) + } + + pub(crate) fn remove_owner(&self, app: &AppHandle, owner: &str) { + let labels = if let Ok(mut inner) = self.0.lock() { + let labels = inner + .records + .iter() + .filter(|(_, record)| record.owner == owner) + .map(|(label, record)| (label.clone(), record.clone())) + .collect::>(); + for (label, _) in &labels { + inner.records.remove(label); + } + labels + } else { + Vec::new() + }; + let _ = Self::dispose_records(app, labels); + } +} + +#[cfg(test)] +#[path = "embedded_view_tests.rs"] +mod tests; diff --git a/packages/tauri-app/src-tauri/src/embedded_view/browser.rs b/packages/tauri-app/src-tauri/src/embedded_view/browser.rs new file mode 100644 index 0000000000..5e0af1e483 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/browser.rs @@ -0,0 +1,358 @@ +//! Native guest windows retain the engine's real opener, never an app IPC bridge. +use super::*; + +pub(super) fn page_permission_subject(raw: &str) -> Option { + let url = tauri::Url::parse(raw).ok()?; + if is_allowed_url(&url) { + return Some(url.origin().ascii_serialization()); + } + if url.scheme() == "about" && url.path() == "blank" { + return Some("about:blank".into()); + } + if url.scheme() == "blob" { + let inner = tauri::Url::parse(url.path()).ok()?; + if is_allowed_url(&inner) { + return Some(inner.origin().ascii_serialization()); + } + } + None +} + +fn download_path(directory: &Path, suggested: &Path) -> Option { + if !directory.is_dir() { + return None; + } + let name: String = suggested + .file_name()? + .to_string_lossy() + .chars() + .filter(|c| !c.is_control() && !"/\\:*?\"<>|".contains(*c)) + .scan(0, |bytes, c| { + *bytes += c.len_utf8(); + (*bytes <= 180).then_some(c) + }) + .collect(); + let name = name.trim_matches([' ', '.']); + let name = if name.is_empty() { "download" } else { name }; + // WebKit refuses an existing destination; the random prefix also separates + // concurrent downloads before either engine has created its file. + let path = directory.join(format!("{}-{name}", uuid::Uuid::new_v4())); + if path.exists() { + return None; + } + #[cfg(windows)] + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .ok()?; + Some(path) +} + +pub(super) fn permission( + webview: tauri::Webview, + kind: tauri::webview::PermissionKind, +) -> tauri::webview::PermissionResponse { + use tauri::webview::{PermissionKind as K, PermissionResponse as R}; + match kind { + K::Camera | K::Microphone | K::Geolocation | K::Notifications => R::Deny, + // Mandatory desktop adapters classify the raw request, including its + // requester metadata, before allowing consent or reporting a denial. + K::Other if cfg!(any(windows, target_os = "linux")) => R::Default, + K::ClipboardRead + | K::DisplayCapture + | K::Midi + | K::Sensors + | K::MediaKeySystemAccess + | K::LocalFonts + | K::WindowManagement + | K::PointerLock + | K::AutomaticDownloads + | K::FileSystemAccess + | K::Autoplay => R::Default, + _ => { + unknown_permission(&webview, &kind.to_string()); + R::Deny + } + } +} + +pub(super) fn unknown_permission(webview: &tauri::Webview, kind: &str) { + use tauri_plugin_dialog::DialogExt; + let text = webview + .app_handle() + .try_state::() + .map(|state| state.menu_labels.text("browserPermissionUnknown")) + .unwrap_or_else(|| crate::menu_labels::label("browserPermissionUnknown").to_string()) + .replace("{permission}", kind); + webview + .app_handle() + .dialog() + .message(text) + .parent(&webview.window()) + .show(|_| {}); +} + +#[cfg(any(windows, target_os = "linux", target_os = "macos"))] +pub(super) fn download( + _: tauri::Webview, + event: tauri::webview::DownloadEvent<'_>, +) -> bool { + match event { + tauri::webview::DownloadEvent::Requested { url, destination } => { + if !is_allowed_url(&url) && !matches!(url.scheme(), "blob" | "data") { + return false; + } + let Some(path) = dirs::download_dir().and_then(|dir| download_path(&dir, destination)) + else { + return false; + }; + *destination = path; + true + } + _ => true, + } +} + +#[cfg(any(windows, target_os = "linux", target_os = "macos"))] +impl EmbeddedViews { + pub(super) fn open_popup( + &self, + app: &AppHandle, + owner: &str, + opener: &str, + storage: &Storage, + url: tauri::Url, + features: tauri::webview::NewWindowFeatures, + ) -> tauri::webview::NewWindowResponse { + use tauri::webview::NewWindowResponse; + // Only browser previews opt in; remote-view consumers keep their policy. + let Ok(opener_record) = self.owned(owner, opener) else { + return NewWindowResponse::Deny; + }; + if !opener.starts_with("browser-") + || !site_url_allowed(&url, opener_record.origin.as_deref()) + { + return NewWindowResponse::Deny; + } + let Some(parent) = app.get_window(owner) else { + return NewWindowResponse::Deny; + }; + let label = format!("browser-popup-{}", uuid::Uuid::new_v4()); + let Ok(mut record) = self.reserve(owner, &label) else { + return NewWindowResponse::Deny; + }; + record.opener = Some(opener.into()); + record.origin = opener_record.origin.clone(); + if let Ok(mut inner) = self.0.lock() { + if !inner.records.get(opener).is_some_and(|current| { + current.token == opener_record.token && current.document == opener_record.document + }) { + inner.records.remove(&label); + return NewWindowResponse::Deny; + } + let Some(current) = inner + .records + .get_mut(&label) + .filter(|current| current.token == record.token) + else { + return NewWindowResponse::Deny; + }; + current.opener = record.opener.clone(); + current.origin = record.origin.clone(); + } else { + return NewWindowResponse::Deny; + } + let policy = self.clone(); + let navigation_label = label.clone(); + let page_policy = self.clone(); + let token = record.token; + let downloads = self.clone(); + let download_label = label.clone(); + let popups = self.clone(); + let popup_app = app.clone(); + let popup_owner = owner.to_string(); + let popup_opener = label.clone(); + let popup_storage = Storage { + directory: storage.directory.clone(), + domain: storage.domain.clone(), + }; + let builder = tauri::WebviewWindowBuilder::new( + app, + &label, + tauri::WebviewUrl::External("about:blank".parse().unwrap()), + ) + .window_features(features) + .title(url.origin().ascii_serialization()) + .inner_size(520.0, 680.0) + .disable_drag_drop_handler() + .zoom_hotkeys_enabled(cfg!(windows)) + .visible(false); + #[cfg(target_os = "linux")] + let builder = parent + .gtk_window() + .map(|parent| builder.transient_for_raw(&parent)); + #[cfg(target_os = "macos")] + let builder = parent.ns_window().map(|parent| builder.parent_raw(parent)); + #[cfg(windows)] + let builder = parent.hwnd().map(|parent| builder.owner_raw(parent)); + let builder = builder.map(|builder| { + builder + .data_directory(storage.directory.clone()) + .on_page_load(move |view, payload| { + page_policy.page_load(view.as_ref(), token, &payload); + }) + .on_navigation(move |url| { + policy.current(&navigation_label, token) + && policy.navigation_allowed(&navigation_label, url) == Some(true) + }) + .on_permission_request({ + let permissions = self.clone(); + let permission_label = label.clone(); + move |view, kind| { + if permissions.current(&permission_label, token) { + permission(view, kind) + } else { + tauri::webview::PermissionResponse::Deny + } + } + }) + .on_download(move |view, event| { + downloads.current(&download_label, token) && download(view, event) + }) + .on_new_window(move |url, features| { + if !popups.current(&popup_opener, token) { + return NewWindowResponse::Deny; + } + popups.open_popup( + &popup_app, + &popup_owner, + &popup_opener, + &popup_storage, + url, + features, + ) + }) + }); + let result = builder.and_then(|builder| builder.build()); + let window = match result { + Ok(window) => window, + Err(_) => { + self.remove_exact(&label, &record); + return NewWindowResponse::Deny; + } + }; + self.install_fullscreen_window(&window.as_ref().window()); + let cleanup = self.clone(); + let cleanup_app = app.clone(); + let cleanup_label = label.clone(); + let cleanup_record = record.clone(); + let close_view: tauri::Webview = window.as_ref().clone(); + window.on_window_event(move |event| { + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + if !cleanup.current(&cleanup_label, cleanup_record.token) { + return; + } + #[cfg(target_os = "linux")] + let result = super::linux::request_close(&close_view); + #[cfg(target_os = "macos")] + let result = super::macos::request_close(&close_view); + #[cfg(windows)] + let result = super::windows::request_close(&close_view); + if let Err(error) = result { + eprintln!("[browser-close] {error}"); + } + return; + } + if matches!(event, tauri::WindowEvent::Destroyed) { + let _ = cleanup.dispose_tree(&cleanup_app, &cleanup_label, cleanup_record.token); + } + }); + #[cfg(target_os = "linux")] + let configured = super::linux::install(window.as_ref()); + #[cfg(target_os = "macos")] + let configured = super::macos::install(window.as_ref()); + #[cfg(windows)] + let configured = super::windows::install(window.as_ref()); + if configured + .and_then(|()| self.finish_creation(&label, &record)) + .is_err() + || !self.owned(owner, opener).is_ok_and(|current| { + current.token == opener_record.token && current.document == opener_record.document + }) + { + self.remove_exact(&label, &record); + let _ = window.destroy(); + return NewWindowResponse::Deny; + } + if window.show().is_err() { + self.remove_exact(&label, &record); + let _ = window.destroy(); + return NewWindowResponse::Deny; + } + // WebKit performs the requested navigation after this return, using the + // supplied related-view/configuration so opener/postMessage stay native. + NewWindowResponse::Create { window } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn page_scoped_permission_subject_is_native_document_identity() { + assert_eq!( + page_permission_subject("https://example.com:8443/path?q=secret"), + Some("https://example.com:8443".into()) + ); + assert_eq!( + page_permission_subject("about:blank"), + Some("about:blank".into()) + ); + assert_eq!( + page_permission_subject("blob:https://example.com/id"), + Some("https://example.com".into()) + ); + for raw in [ + "file:///private", + "tauri://localhost", + "https://user:pass@example.com", + "blob:null/id", + ] { + assert_eq!(page_permission_subject(raw), None); + } + } + #[test] + fn downloads_are_sanitized_unique_and_confined() { + let dir = tempfile::tempdir().unwrap(); + for name in [ + "../../report.txt", + "..\\..\\report.txt", + ".", + "...", + "a\n:b?.txt", + "résumé.txt", + ] { + let first = download_path(dir.path(), Path::new(name)); + if name == "." { + assert!(first.is_none()); + continue; + } + let first = first.unwrap(); + assert_eq!(first.parent(), Some(dir.path())); + assert!(!first + .file_name() + .unwrap() + .to_string_lossy() + .contains(['\\', '/', '\n', ':', '?'])); + std::fs::write(&first, "original").unwrap(); + assert_ne!( + Some(first.clone()), + download_path(dir.path(), Path::new(name)) + ); + assert_eq!(std::fs::read_to_string(first).unwrap(), "original"); + } + assert!(download_path(&dir.path().join("missing"), Path::new("file")).is_none()); + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/fullscreen.rs b/packages/tauri-app/src-tauri/src/embedded_view/fullscreen.rs new file mode 100644 index 0000000000..d8051f89c6 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/fullscreen.rs @@ -0,0 +1,130 @@ +use super::*; + +impl EmbeddedViews { + pub(super) fn install_fullscreen_window(&self, window: &tauri::Window) { + let Ok(mut inner) = self.0.lock() else { return }; + if !inner.fullscreen_windows.insert(window.label().into()) { + return; + } + drop(inner); + let views = self.clone(); + let app = window.app_handle().clone(); + let label = window.label().to_string(); + window.on_window_event(move |event| match event { + tauri::WindowEvent::Resized(size) => views.fit_fullscreen(&app, &label, *size), + tauri::WindowEvent::Destroyed => { + if let Ok(mut inner) = views.0.lock() { + inner.fullscreen_windows.remove(&label); + } + } + _ => {} + }); + } + + fn fit_fullscreen( + &self, + app: &AppHandle, + window: &str, + size: PhysicalSize, + ) { + let labels = self + .0 + .lock() + .map(|inner| { + inner + .records + .iter() + .filter(|(_, record)| record.fullscreen.is_some()) + .map(|(label, _)| label.clone()) + .collect::>() + }) + .unwrap_or_default(); + for label in labels { + if let Some(view) = app + .get_webview(&label) + .filter(|view| view.window().label() == window) + { + let _ = view.set_position(PhysicalPosition::new(0, 0)); + let _ = view.set_size(size); + } + } + } + + pub(super) fn set_fullscreen( + &self, + app: &AppHandle, + label: &str, + active: bool, + ) -> Result<(), String> { + let record = self + .0 + .lock() + .map_err(|error| error.to_string())? + .records + .get(label) + .cloned() + .ok_or("Browser view unavailable")?; + if !label.starts_with("browser-") || active == record.fullscreen.is_some() { + return Ok(()); + } + let view = app.get_webview(label).ok_or("Browser view unavailable")?; + let window = view.window(); + let before = if active { + window.is_fullscreen().map_err(|error| error.to_string())? + } else { + record.fullscreen.unwrap() + }; + let normal = if active { + view.position() + .ok() + .zip(view.size().ok()) + .filter(|(_, size)| size.width > 0 && size.height > 0) + .map(|(position, size)| Bounds { + x: position.x, + y: position.y, + width: size.width, + height: size.height, + }) + } else { + None + }; + { + let mut inner = self.0.lock().map_err(|error| error.to_string())?; + let current = inner + .records + .get_mut(label) + .filter(|current| current.token == record.token) + .ok_or("Browser view changed")?; + current.fullscreen = active.then_some(before); + if active { + current.bounds = normal.or(record.bounds); + } + } + if let Err(error) = window.set_fullscreen(active || before) { + if let Ok(mut inner) = self.0.lock() { + if let Some(current) = inner + .records + .get_mut(label) + .filter(|current| current.token == record.token) + { + current.fullscreen = record.fullscreen; + } + } + return Err(error.to_string()); + } + if active { + if let Ok(size) = window.inner_size() { + self.fit_fullscreen(app, window.label(), size); + } + } else { + // Host hide/close can end fullscreen before the engine's exit event. + let _ = + view.eval("if(document.fullscreenElement)document.exitFullscreen().catch(()=>{})"); + if let Some(bounds) = record.bounds { + let _ = view.set_position(PhysicalPosition::new(bounds.x, bounds.y)); + let _ = view.set_size(PhysicalSize::new(bounds.width, bounds.height)); + } + } + Ok(()) + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input.h b/packages/tauri-app/src-tauri/src/embedded_view/input.h new file mode 100644 index 0000000000..d94f946cbb --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input.h @@ -0,0 +1,23 @@ +#pragma once +#include +#include + +/* UI-thread only. Bytes passed to completion are borrowed until it returns. + * The caller owns the exact guest, visibility/generation and deadline fences. + * No function raises a window or injects global desktop input. */ +typedef void (*CNCompletion)(void *, const unsigned char *, size_t, const char *); +enum CNPointer { CN_MOVE, CN_LEFT_DOWN, CN_LEFT_UP, CN_RIGHT_DOWN, CN_RIGHT_UP, CN_DRAG }; +enum CNModifier { CN_SHIFT = 1, CN_CONTROL = 2, CN_ALT = 4, CN_META = 8 }; +void cn_checkpoint(void *view, CNCompletion done, void *context); +int cn_pointer(void *view, int action, double x, double y, unsigned modifiers); +int cn_wheel(void *view, double x, double y, double dx, double dy, unsigned modifiers); +int cn_key(void *view, const char *key, unsigned modifiers, int down); +int cn_text(void *view, const char *text); +void cn_capture(void *view, CNCompletion done, void *context); +int cn_install_page_read(void *view); +void cn_page_read(void *view, const char *request, unsigned timeout_ms, CNCompletion done, void *context); + +/* Fixed isolated-world program. A page-global value must never leak into it. + * The document fields also permit an external fixture to publish observations. */ +#define CN_CHECKPOINT "JSON.stringify({url:location.href,title:document.title,body:document.body?document.body.innerText:'',width:innerWidth,height:innerHeight,pageGlobal:typeof window.__codenomadPageOnly})" +#define CN_WORLD "com.codenomad.preview.automation.v1" diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input.rs b/packages/tauri-app/src-tauri/src/embedded_view/input.rs new file mode 100644 index 0000000000..b8000c6ad0 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input.rs @@ -0,0 +1,180 @@ +//! UI-thread native reads. Ownership/document fences belong to BrowserController. +use std::ffi::{c_char, c_void, CStr, CString}; +use std::sync::{mpsc, Arc}; +use std::time::Instant; +#[path = "input_native.rs"] +mod native; +pub(crate) use native::Held; + +type Guard = Arc Result<(), String> + Send + Sync>; +type Completion = unsafe extern "C" fn(*mut c_void, *const u8, usize, *const c_char); +extern "C" { + fn cn_checkpoint(view: *mut c_void, done: Completion, context: *mut c_void); + fn cn_capture(view: *mut c_void, done: Completion, context: *mut c_void); + fn cn_install_page_read(view: *mut c_void) -> i32; + fn cn_page_read( + view: *mut c_void, + request: *const c_char, + timeout_ms: u32, + done: Completion, + context: *mut c_void, + ); +} + +#[derive(Clone)] +pub(crate) enum Read { + Checkpoint, + Capture, + Page(String), + Input { + document: String, + operation: serde_json::Value, + held: Held, + }, +} + +struct Pending { + sender: mpsc::SyncSender, String>>, + guard: Guard, + limit: usize, + input: Option<(*mut c_void, String, serde_json::Value, Held)>, +} + +unsafe extern "C" fn completed( + context: *mut c_void, + bytes: *const u8, + length: usize, + error: *const c_char, +) { + // Native adapters invoke exactly once and lend their buffers until return. + let pending = unsafe { Box::from_raw(context.cast::()) }; + let result = (|| { + (pending.guard)()?; + if !error.is_null() { + return Err(unsafe { CStr::from_ptr(error) } + .to_string_lossy() + .into_owned()); + } + if length > pending.limit || (length != 0 && bytes.is_null()) { + return Err("Native browser result exceeds its byte budget".into()); + } + let bytes = if length == 0 { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(bytes, length) }.to_vec() + }; + if let Some((view, document, operation, held)) = &pending.input { + let response: serde_json::Value = + serde_json::from_slice(&bytes).map_err(|error| error.to_string())?; + if response["document"].as_str() != Some(document.as_str()) { + return Err("Browser page document changed before input".into()); + } + if operation["op"] == "wheel" && response["result"]["node"].as_u64().is_none() { + return Err("Native wheel point is unavailable".into()); + } + unsafe { native::dispatch(*view, operation, held) }?; + (pending.guard)()?; + return serde_json::to_vec(&serde_json::json!({"document":document,"result":{}})) + .map_err(|error| error.to_string()); + } + Ok(bytes) + })(); + let _ = pending.sender.send(result); +} + +pub(crate) fn read( + webview: &tauri::Webview, + operation: Read, + deadline: Instant, + guard: impl Fn() -> Result<(), String> + Send + Sync + 'static, +) -> Result, String> { + let guard: Guard = Arc::new(guard); + guard()?; + let (sender, receiver) = mpsc::sync_channel(1); + let queued_guard = guard.clone(); + webview + .with_webview(move |native| { + if Instant::now() >= deadline { + let _ = sender.send(Err("Native request expired before execution".into())); + return; + } + if let Err(error) = queued_guard() { + let _ = sender.send(Err(error)); + return; + } + #[cfg(target_os = "linux")] + let view = { + use gtk::glib::object::ObjectType; + native.inner().as_ptr().cast::() + }; + #[cfg(target_os = "macos")] + let view = native.inner(); + let context = Box::into_raw(Box::new(Pending { + sender, + guard: queued_guard, + limit: match &operation { + Read::Checkpoint => 1024 * 1024, + Read::Capture => 16 * 1024 * 1024, + Read::Page(_) => 4 * 1024 * 1024, + Read::Input {..} => 4 * 1024 * 1024, + }, + input:match &operation {Read::Input {document,operation,held}=>Some((view,document.clone(),operation.clone(),held.clone())),_=>None}, + })) + .cast::(); + unsafe { + match operation { + Read::Checkpoint => cn_checkpoint(view, completed, context), + Read::Capture => cn_capture(view, completed, context), + Read::Page(request) => { + let request = CString::new(request).expect("serialized JSON request"); + cn_page_read( + view, + request.as_ptr(), + deadline + .saturating_duration_since(Instant::now()) + .as_millis() + .clamp(1, u32::MAX as u128) as u32, + completed, + context, + ); + } + Read::Input {operation,..}=> { + let preflight=if operation["op"]=="wheel" {serde_json::json!({"op":"hit-test","x":operation["event"]["x"].as_f64().unwrap_or(0.0).floor(),"y":operation["event"]["y"].as_f64().unwrap_or(0.0).floor()})} else {serde_json::json!({"op":"checkpoint"})}; + let request=CString::new(preflight.to_string()).expect("serialized input preflight"); + cn_page_read(view,request.as_ptr(),deadline.saturating_duration_since(Instant::now()).as_millis().clamp(1,u32::MAX as u128) as u32,completed,context); + }, + } + } + }) + .map_err(|error| error.to_string())?; + let result = receiver + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .map_err(|_| "Timed out reading the native browser".to_string())??; + guard()?; + Ok(result) +} + +pub(crate) fn install_read(webview: &tauri::Webview) -> Result<(), String> { + let (sender, receiver) = mpsc::sync_channel(1); + webview + .with_webview(move |native| { + #[cfg(target_os = "linux")] + let view = { + use gtk::glib::object::ObjectType; + native.inner().as_ptr().cast::() + }; + #[cfg(target_os = "macos")] + let view = native.inner(); + let installed = unsafe { cn_install_page_read(view) }; + let _ = sender.send(installed != 0); + }) + .map_err(|error| error.to_string())?; + if receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .map_err(|_| "Timed out installing native read hooks".to_string())? + { + Ok(()) + } else { + Err("Native read hooks are unavailable".into()) + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input_linux.c b/packages/tauri-app/src-tauri/src/embedded_view/input_linux.c new file mode 100644 index 0000000000..acf8621987 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input_linux.c @@ -0,0 +1,193 @@ +#include "input.h" +#include "page_read.generated.h" +#include +#include +#include +#include + +typedef struct { CNCompletion done; void *context; } Completion; + +static void evaluated(GObject *object, GAsyncResult *result, gpointer data) { + Completion *completion = data; + GError *error = NULL; + JSCValue *value = webkit_web_view_evaluate_javascript_finish(WEBKIT_WEB_VIEW(object), result, &error); + char *text = value ? jsc_value_to_string(value) : NULL; + completion->done(completion->context, (unsigned char *)text, text ? strlen(text) : 0, + error ? error->message : (text ? NULL : "WebKit evaluation returned no value")); + g_free(text); + g_clear_object(&value); + g_clear_error(&error); + g_free(completion); +} + +void cn_checkpoint(void *view, CNCompletion done, void *context) { + Completion *completion = g_new(Completion, 1); + *completion = (Completion){done, context}; + webkit_web_view_evaluate_javascript(WEBKIT_WEB_VIEW(view), CN_CHECKPOINT, -1, + CN_WORLD, "codenomad-checkpoint", NULL, evaluated, completion); +} + +typedef struct { CNCompletion done; void *context; GCancellable *cancel; guint timeout; } PageRead; +static gboolean cancel_page_read(gpointer data) { g_cancellable_cancel(data); return G_SOURCE_REMOVE; } +static void page_read_done(GObject *object, GAsyncResult *result, gpointer data) { + PageRead *read = data; + GError *error = NULL; + JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(object), result, &error); + char *text = value ? jsc_value_to_string(value) : NULL; + const char *failure = error ? error->message : (webkit_web_view_is_loading(WEBKIT_WEB_VIEW(object)) ? "Native browser page is loading" : NULL); + read->done(read->context, (unsigned char *)text, text ? strlen(text) : 0, failure); + if (read->timeout && g_main_context_find_source_by_id(NULL, read->timeout)) g_source_remove(read->timeout); + g_object_unref(read->cancel); + g_free(text); g_clear_object(&value); g_clear_error(&error); g_free(read); +} +int cn_install_page_read(void *view) { + /* Pin the named content world between async calls. WebKit otherwise releases + * an unused world and its document identity table after each callback. */ + WebKitUserScript *world = webkit_user_script_new_for_world("void 0", WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, CN_WORLD, NULL, NULL); + webkit_user_content_manager_add_script(webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(view)), world); + webkit_user_script_unref(world); + WebKitUserScript *script = webkit_user_script_new(CN_PAGE_HOOK, WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, NULL, NULL); + webkit_user_content_manager_add_script(webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(view)), script); + webkit_user_script_unref(script); + return 1; +} +void cn_page_read(void *view, const char *request, unsigned timeout_ms, CNCompletion done, void *context) { + if (webkit_web_view_is_loading(WEBKIT_WEB_VIEW(view))) { done(context,NULL,0,"Native browser page is loading"); return; } + PageRead *read = g_new0(PageRead,1); + read->done=done; read->context=context; read->cancel=g_cancellable_new(); + read->timeout=g_timeout_add_full(G_PRIORITY_DEFAULT, MAX(1,timeout_ms),cancel_page_read,g_object_ref(read->cancel),g_object_unref); + GVariantBuilder args; g_variant_builder_init(&args,G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&args,"{sv}","request",g_variant_new_string(request)); + GVariant *arguments=g_variant_ref_sink(g_variant_builder_end(&args)); + webkit_web_view_call_async_javascript_function(WEBKIT_WEB_VIEW(view),CN_PAGE_READ,-1,arguments,CN_WORLD,"codenomad-page-read",read->cancel,page_read_done,read); + g_variant_unref(arguments); +} + +static GdkModifierType modifiers(unsigned flags) { + return ((flags & CN_SHIFT) ? GDK_SHIFT_MASK : 0) | + ((flags & CN_CONTROL) ? GDK_CONTROL_MASK : 0) | + ((flags & CN_ALT) ? GDK_MOD1_MASK : 0) | + ((flags & CN_META) ? GDK_META_MASK : 0); +} + +static GdkEvent *event_for(GtkWidget *view, GdkEventType type, int keyboard) { + GdkWindow *window = gtk_widget_get_window(view); + if (!window || !gtk_widget_get_mapped(view)) return NULL; + GdkSeat *seat = gdk_display_get_default_seat(gtk_widget_get_display(view)); + GdkDevice *device = keyboard ? gdk_seat_get_keyboard(seat) : gdk_seat_get_pointer(seat); + if (!device) return NULL; + GdkEvent *event = gdk_event_new(type); + event->any.window = g_object_ref(window); + /* WebKit accepts these as targeted native events on either display backend. */ + event->any.send_event = FALSE; + gdk_event_set_device(event, device); + return event; +} + +static int valid_point(GtkWidget *view, double x, double y) { + return isfinite(x) && isfinite(y) && x >= 0 && y >= 0 && + x < gtk_widget_get_allocated_width(view) && y < gtk_widget_get_allocated_height(view); +} + +static int deliver(GdkEvent *event) { + if (!event) return 0; + gtk_main_do_event(event); + gdk_event_free(event); + return 1; +} + +int cn_pointer(void *opaque, int action, double x, double y, unsigned flags) { + double zoom=webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(opaque));x*=zoom;y*=zoom; + GtkWidget *view = GTK_WIDGET(opaque); + if (!valid_point(view, x, y) || action < CN_MOVE || action > CN_DRAG) return 0; + GdkEventType type = (action == CN_MOVE || action == CN_DRAG) ? GDK_MOTION_NOTIFY : + ((action == CN_LEFT_DOWN || action == CN_RIGHT_DOWN) ? GDK_BUTTON_PRESS : GDK_BUTTON_RELEASE); + GdkEvent *event = event_for(view, type, 0); + if (!event) return 0; + if (type == GDK_MOTION_NOTIFY) { + event->motion.time = GDK_CURRENT_TIME; + event->motion.x = x; event->motion.y = y; + event->motion.state = modifiers(flags) | (action == CN_DRAG ? GDK_BUTTON1_MASK : 0); + } else { + event->button.time = GDK_CURRENT_TIME; + event->button.x = x; event->button.y = y; + event->button.button = (action == CN_RIGHT_DOWN || action == CN_RIGHT_UP) ? 3 : 1; + event->button.state = modifiers(flags) | (type == GDK_BUTTON_RELEASE ? + (event->button.button == 1 ? GDK_BUTTON1_MASK : GDK_BUTTON3_MASK) : 0); + } + return deliver(event); +} + +int cn_wheel(void *opaque, double x, double y, double dx, double dy, unsigned flags) { + double zoom=webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(opaque));x*=zoom;y*=zoom;dx*=zoom;dy*=zoom; + GtkWidget *view = GTK_WIDGET(opaque); + if (!valid_point(view, x, y) || !isfinite(dx) || !isfinite(dy)) return 0; + GdkEvent *event = event_for(view, GDK_SCROLL, 0); + if (!event) return 0; + event->scroll.time = GDK_CURRENT_TIME; + event->scroll.x = x; event->scroll.y = y; + event->scroll.state = modifiers(flags); + event->scroll.direction = GDK_SCROLL_SMOOTH; + /* GDK smooth deltas are wheel steps (WebKit maps one step to 40 CSS px). */ + event->scroll.delta_x = dx / 40; event->scroll.delta_y = dy / 40; + return deliver(event); +} + +int cn_key(void *opaque, const char *key, unsigned flags, int down) { + GtkWidget *view = GTK_WIDGET(opaque); + guint keyval = gdk_keyval_from_name(key); + if (keyval == GDK_KEY_VoidSymbol && g_utf8_strlen(key, -1) == 1) + keyval = gdk_unicode_to_keyval(g_utf8_get_char(key)); + if (keyval == GDK_KEY_VoidSymbol) return 0; + GdkEvent *event = event_for(view, down ? GDK_KEY_PRESS : GDK_KEY_RELEASE, 1); + if (!event) return 0; + event->key.time = GDK_CURRENT_TIME; + event->key.state = modifiers(flags); + event->key.keyval = keyval; + GdkKeymapKey *entries = NULL; + gint count = 0; + if (gdk_keymap_get_entries_for_keyval(gdk_keymap_get_for_display(gtk_widget_get_display(view)), + keyval, &entries, &count) && count) { + event->key.hardware_keycode = entries[0].keycode; + event->key.group = entries[0].group; + } + g_free(entries); + /* gtk_main_do_event routes keys by toplevel focus; dispatch directly to the + * exact WebKit widget so another child cannot receive a background key. */ + gtk_widget_event(view, event); + gdk_event_free(event); + return 1; +} + +int cn_text(void *view, const char *text) { + if (!text || !g_utf8_validate(text, -1, NULL) || !gtk_widget_get_mapped(GTK_WIDGET(view))) return 0; + webkit_web_view_execute_editing_command_with_argument(WEBKIT_WEB_VIEW(view), "InsertText", text); + return 1; +} + +static void captured(GObject *object, GAsyncResult *result, gpointer data); +static cairo_status_t png_write(void *context, const unsigned char *data, unsigned length) { + GByteArray *bytes = context; + if (bytes->len + (size_t)length > 16 * 1024 * 1024) return CAIRO_STATUS_WRITE_ERROR; + g_byte_array_append(bytes, data, length); + return CAIRO_STATUS_SUCCESS; +} +static void captured(GObject *object, GAsyncResult *result, gpointer data) { + Completion *completion = data; + GError *error = NULL; + cairo_surface_t *surface = webkit_web_view_get_snapshot_finish(WEBKIT_WEB_VIEW(object), result, &error); + GByteArray *bytes = g_byte_array_new(); + cairo_status_t status = surface ? cairo_surface_write_to_png_stream(surface, png_write, bytes) : CAIRO_STATUS_NULL_POINTER; + completion->done(completion->context, bytes->data, bytes->len, + error ? error->message : (status == CAIRO_STATUS_SUCCESS ? NULL : cairo_status_to_string(status))); + g_byte_array_unref(bytes); + if (surface) cairo_surface_destroy(surface); + g_clear_error(&error); + g_free(completion); +} +void cn_capture(void *view, CNCompletion done, void *context) { + Completion *completion = g_new(Completion, 1); + *completion = (Completion){done, context}; + webkit_web_view_get_snapshot(WEBKIT_WEB_VIEW(view), WEBKIT_SNAPSHOT_REGION_VISIBLE, + WEBKIT_SNAPSHOT_OPTIONS_NONE, NULL, captured, completion); +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input_macos.m b/packages/tauri-app/src-tauri/src/embedded_view/input_macos.m new file mode 100644 index 0000000000..41ca1a758d --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input_macos.m @@ -0,0 +1,348 @@ +#import +#import +#include "input.h" +#include "page_read.generated.h" +#include +#include +#include +#include +#include + +/* WebKit samples this class method while translating native mouse input. + * Only the dispatching UI thread sees synthetic state. Other threads retain + * the original behavior, and every exit path restores the implementation. */ +static _Thread_local unsigned synthetic_depth; +static _Thread_local NSUInteger synthetic_buttons; +static _Atomic(IMP) original_buttons; +static NSUInteger pressed_buttons(id object, SEL selector) { + if (synthetic_depth) return synthetic_buttons; + return ((NSUInteger (*)(id, SEL))atomic_load(&original_buttons))(object, selector); +} +static void with_buttons(NSUInteger buttons, void (^dispatch)(void)) { + NSCAssert(NSThread.isMainThread, @"Native input requires the UI thread"); + Method method = class_getClassMethod(NSEvent.class, @selector(pressedMouseButtons)); + NSUInteger previous = synthetic_buttons; + BOOL outer = synthetic_depth == 0; + IMP original = NULL; + if (outer) { + original = method_getImplementation(method); + atomic_store(&original_buttons, original); + method_setImplementation(method, (IMP)pressed_buttons); + } + synthetic_depth++; + synthetic_buttons = buttons; + @try { dispatch(); } + @finally { + synthetic_buttons = previous; + synthetic_depth--; + if (outer) method_setImplementation(method, original); + } +} +static void trace(NSString *message) { + if (getenv("CN_INPUT_TRACE")) fprintf(stderr, "%s\n", message.UTF8String); +} +static _Thread_local unsigned modifier_depth; +static _Thread_local NSEventModifierFlags synthetic_modifiers; +static _Atomic(IMP) original_modifiers; +static NSEventModifierFlags modifier_flags(id object, SEL selector) { + if (modifier_depth) return synthetic_modifiers; + return ((NSEventModifierFlags (*)(id, SEL))atomic_load(&original_modifiers))(object, selector); +} +static void with_modifiers(NSEventModifierFlags flags, void (^dispatch)(void)) { + NSCAssert(NSThread.isMainThread, @"Native input requires the UI thread"); + Method method = class_getClassMethod(NSEvent.class, @selector(modifierFlags)); + BOOL outer = modifier_depth == 0; + NSEventModifierFlags previous = synthetic_modifiers; + IMP original = NULL; + if (outer) { + original = method_getImplementation(method); + atomic_store(&original_modifiers, original); + method_setImplementation(method, (IMP)modifier_flags); + } + modifier_depth++; + synthetic_modifiers = flags; + @try { dispatch(); } + @finally { + synthetic_modifiers = previous; + modifier_depth--; + if (outer) method_setImplementation(method, original); + } +} +#ifdef CN_INPUT_SELF_TEST +void cn_test_scoped_buttons(void) { + Method method = class_getClassMethod(NSEvent.class, @selector(pressedMouseButtons)); + IMP original = method_getImplementation(method); + NSUInteger physical = NSEvent.pressedMouseButtons; + @try { + with_buttons(1, ^{ + NSCAssert(NSEvent.pressedMouseButtons == 1, @"synthetic button missing"); + with_buttons(2, ^{ NSCAssert(NSEvent.pressedMouseButtons == 2, @"nested button missing"); }); + NSCAssert(NSEvent.pressedMouseButtons == 1, @"nested state leaked"); + dispatch_semaphore_t observed = dispatch_semaphore_create(0); + dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{ + NSCAssert(NSEvent.pressedMouseButtons == physical, @"synthetic state leaked to another thread"); + dispatch_semaphore_signal(observed); + }); + NSCAssert(dispatch_semaphore_wait(observed, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0, @"background check timed out"); + @throw [NSException exceptionWithName:@"Qualification" reason:@"test cleanup" userInfo:nil]; + }); + } @catch (NSException *exception) { + NSCAssert([exception.name isEqualToString:@"Qualification"], @"unexpected exception"); + } + NSCAssert(method_getImplementation(method) == original, @"method implementation leaked"); + NSCAssert(NSEvent.pressedMouseButtons == physical, @"button state leaked"); + Method modifier_method = class_getClassMethod(NSEvent.class, @selector(modifierFlags)); + IMP modifier_original = method_getImplementation(modifier_method); + NSEventModifierFlags physical_modifiers = NSEvent.modifierFlags; + @try { + with_modifiers(NSEventModifierFlagCommand, ^{ + NSCAssert(NSEvent.modifierFlags == NSEventModifierFlagCommand, @"synthetic modifier missing"); + with_modifiers(0, ^{ NSCAssert(NSEvent.modifierFlags == 0, @"zero modifier missing"); }); + NSCAssert(NSEvent.modifierFlags == NSEventModifierFlagCommand, @"nested modifier leaked"); + @throw [NSException exceptionWithName:@"Qualification" reason:@"modifier cleanup" userInfo:nil]; + }); + } @catch (NSException *exception) { + NSCAssert([exception.name isEqualToString:@"Qualification"], @"unexpected exception"); + } + NSCAssert(method_getImplementation(modifier_method) == modifier_original, @"modifier implementation leaked"); + NSCAssert(NSEvent.modifierFlags == physical_modifiers, @"modifier state leaked"); +} +#endif + +/* Public mouseMoved: is inherited from NSView on the qualified WebKit build. + * This SPI is explicitly checked at runtime; its DOM behavior stays gated by + * the strict hover assertion before application integration. */ +@interface WKWebView (CNTargetedMouseMove) +- (void)_simulateMouseMove:(NSEvent *)event; +@end +#ifdef CN_INPUT_SELF_TEST +int cn_test_direct_hover(void *opaque, double x, double y) { + WKWebView *view = (__bridge WKWebView *)opaque; + NSPoint local = NSMakePoint(x, view.isFlipped ? y : view.bounds.size.height - y); + NSPoint point = [view convertPoint:local toView:nil]; + NSEvent *entered = [NSEvent enterExitEventWithType:NSEventTypeMouseEntered location:point + modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:view.window.windowNumber + context:nil eventNumber:1 trackingNumber:0 userData:NULL]; + NSEvent *moved = [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:point + modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:view.window.windowNumber + context:nil eventNumber:2 clickCount:0 pressure:0]; + trace([NSString stringWithFormat:@"hover direct mouseEntered+mouseMoved css=%g,%g window=%g,%g flipped=%d keyWindow=%d", x, y, point.x, point.y, view.isFlipped, view.window.isKeyWindow]); + [view mouseEntered:entered]; + [view mouseMoved:moved]; + return 1; +} +#endif + +static void fail(CNCompletion done, void *context, NSString *error) { + done(context, NULL, 0, error.UTF8String); +} +static WKContentWorld *read_world(void) { + // WKContentWorld's named cache is weak. Keep the world alive between reads + // so its per-document identity table survives separate native callbacks. + static WKContentWorld *world; + static dispatch_once_t once; + dispatch_once(&once, ^{ world = [WKContentWorld worldWithName:@CN_WORLD]; }); + return world; +} +int cn_install_page_read(void *opaque) { + WKWebView *view = (__bridge WKWebView *)opaque; + WKUserScript *hook = [[WKUserScript alloc] initWithSource:[NSString stringWithUTF8String:CN_PAGE_HOOK] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO inContentWorld:WKContentWorld.pageWorld]; + [view.configuration.userContentController addUserScript:hook]; + return 1; +} +void cn_page_read(void *opaque, const char *request, unsigned timeout_ms, CNCompletion done, void *context) { + (void)timeout_ms; // The Rust request fence rejects late WKWebView callbacks. + WKWebView *view = (__bridge WKWebView *)opaque; + if (view.loading) { fail(done,context,@"Native browser page is loading"); return; } + NSDictionary *arguments = @{ @"request": [NSString stringWithUTF8String:request] }; + [view callAsyncJavaScript:[NSString stringWithUTF8String:CN_PAGE_READ] arguments:arguments inFrame:nil inContentWorld:read_world() + completionHandler:^(id result, NSError *error) { + if (error || view.loading || ![result isKindOfClass:NSString.class]) { + fail(done,context,error.localizedDescription ?: @"Native browser page changed or is loading"); return; + } + NSData *bytes = [result dataUsingEncoding:NSUTF8StringEncoding]; + done(context,bytes.bytes,bytes.length,NULL); + }]; +} +void cn_checkpoint(void *opaque, CNCompletion done, void *context) { + WKWebView *view = (__bridge WKWebView *)opaque; + [view evaluateJavaScript:@CN_CHECKPOINT inFrame:nil + inContentWorld:read_world() + completionHandler:^(id result, NSError *error) { + if (error || ![result isKindOfClass:NSString.class]) { + fail(done, context, error.localizedDescription ?: @"WebKit evaluation returned no value"); + return; + } + NSData *bytes = [result dataUsingEncoding:NSUTF8StringEncoding]; + done(context, bytes.bytes, bytes.length, NULL); + }]; +} +static NSEventModifierFlags modifiers(unsigned flags) { + return ((flags & CN_SHIFT) ? NSEventModifierFlagShift : 0) | + ((flags & CN_CONTROL) ? NSEventModifierFlagControl : 0) | + ((flags & CN_ALT) ? NSEventModifierFlagOption : 0) | + ((flags & CN_META) ? NSEventModifierFlagCommand : 0); +} +static BOOL target(WKWebView *view, double x, double y, NSPoint *point) { + x*=view.pageZoom;y*=view.pageZoom; + if (!view.window || view.hidden || !isfinite(x) || !isfinite(y) || + x < 0 || y < 0 || x >= view.bounds.size.width || y >= view.bounds.size.height) return NO; + NSPoint local = NSMakePoint(x, view.isFlipped ? y : view.bounds.size.height - y); + *point = [view convertPoint:local toView:nil]; + return YES; +} +int cn_pointer(void *opaque, int action, double x, double y, unsigned flags) { + WKWebView *view = (__bridge WKWebView *)opaque; + NSPoint point; + if (!target(view, x, y, &point) || action < CN_MOVE || action > CN_DRAG) return 0; + IMP inherited = class_getMethodImplementation(NSView.class, @selector(mouseMoved:)); + BOOL public_move = class_getMethodImplementation(view.class, @selector(mouseMoved:)) != inherited; + if (action == CN_MOVE && !public_move && ![view respondsToSelector:@selector(_simulateMouseMove:)]) return 0; + NSEventType types[] = {NSEventTypeMouseMoved, NSEventTypeLeftMouseDown, + NSEventTypeLeftMouseUp, NSEventTypeRightMouseDown, NSEventTypeRightMouseUp, + NSEventTypeLeftMouseDragged}; + static char sequence_key; + NSInteger number = [objc_getAssociatedObject(view, &sequence_key) integerValue] + 1; + objc_setAssociatedObject(view, &sequence_key, @(number), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + NSEvent *event = [NSEvent mouseEventWithType:types[action] location:point + modifierFlags:modifiers(flags) timestamp:NSProcessInfo.processInfo.systemUptime + windowNumber:view.window.windowNumber context:nil eventNumber:number + clickCount:action == CN_MOVE ? 0 : 1 + pressure:(action == CN_LEFT_DOWN || action == CN_DRAG) ? 1 : 0]; + NSUInteger buttons = (action == CN_LEFT_DOWN || action == CN_DRAG) ? 1 : (action == CN_RIGHT_DOWN ? 2 : 0); + with_buttons(buttons, ^{ + switch (action) { + case CN_MOVE: + trace([NSString stringWithFormat:@"hover css=%g,%g window=%g,%g flipped=%d", x, y, point.x, point.y, view.isFlipped]); + if (public_move) { trace(@"hover public-mouseMoved"); [view mouseMoved:event]; } + else { trace(@"hover SPI=_simulateMouseMove:"); [view _simulateMouseMove:event]; } + break; + case CN_LEFT_DOWN: [view mouseDown:event]; break; + case CN_LEFT_UP: [view mouseUp:event]; break; + case CN_RIGHT_DOWN: [view rightMouseDown:event]; break; + case CN_RIGHT_UP: [view rightMouseUp:event]; break; + case CN_DRAG: [view mouseDragged:event]; break; + } + }); + return 1; +} +int cn_wheel(void *opaque, double x, double y, double dx, double dy, unsigned flags) { + WKWebView *view = (__bridge WKWebView *)opaque; + NSPoint point; + if (!target(view, x, y, &point) || !isfinite(dx) || !isfinite(dy)) return 0; + /* Construct a native event value; never post it to the system queue. */ + CGEventRef cg = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 2, (int32_t)(-dy*view.pageZoom), (int32_t)(-dx*view.pageZoom)); + if (!cg) return 0; + CGEventSetFlags(cg, (CGEventFlags)modifiers(flags)); + // Direct view dispatch consumes window-local Cocoa coordinates. The CGEvent + // constructor flips Y when producing locationInWindow, even with no window. + CGEventSetLocation(cg, CGPointMake(point.x, NSMaxY(NSScreen.screens.firstObject.frame) - point.y)); + [view scrollWheel:[NSEvent eventWithCGEvent:cg]]; + CFRelease(cg); + return 1; +} +static NSString *characters(const char *key, unsigned short *code) { + NSString *text = [NSString stringWithUTF8String:key]; + NSDictionary *special = @{ + @"Return": @[@13, @36], @"Tab": @[@9, @48], @"Escape": @[@27, @53], + @"BackSpace": @[@127, @51], @"Delete": @[@(NSDeleteFunctionKey), @117], + @"Left": @[@(NSLeftArrowFunctionKey), @123], @"Right": @[@(NSRightArrowFunctionKey), @124], + @"Down": @[@(NSDownArrowFunctionKey), @125], @"Up": @[@(NSUpArrowFunctionKey), @126], + @"Home": @[@(NSHomeFunctionKey), @115], @"End": @[@(NSEndFunctionKey), @119], + @"Page_Up": @[@(NSPageUpFunctionKey), @116], @"Page_Down": @[@(NSPageDownFunctionKey), @121], + @"Insert": @[@(NSInsertFunctionKey), @114], @"Menu": @[@(NSMenuFunctionKey), @110] + }; + NSArray *entry = special[text]; + if ([text hasPrefix:@"F"] && text.length<=3) { + int number=[[text substringFromIndex:1] intValue]; + const unsigned short codes[]={122,120,99,118,96,97,98,100,101,109,103,111}; + if (number>=1 && number<=12) entry=@[@(NSF1FunctionKey+number-1),@(codes[number-1])]; + } + if (entry) { + unichar character = [entry[0] unsignedShortValue]; + *code = [entry[1] unsignedShortValue]; + return [NSString stringWithCharacters:&character length:1]; + } + // ANSI keycodes serve native shortcuts; Unicode insertion uses the responder API. + NSArray *keys = @[@"a", @"s", @"d", @"f", @"h", @"g", @"z", @"x", @"c", @"v", @"", @"b", @"q", @"w", @"e", @"r", @"y", @"t", @"1", @"2", @"3", @"4", @"6", @"5", @"=", @"9", @"7", @"-", @"8", @"0", @"]", @"o", @"u", @"[", @"i", @"p", @"", @"l", @"j", @"'", @"k", @";", @"\\", @",", @"/", @"n", @"m", @".", @"", @" ", @"`"]; + NSDictionary *shifted=@{@"~":@"`",@"!":@"1",@"@":@"2",@"#":@"3",@"$":@"4",@"%":@"5",@"^":@"6",@"&":@"7",@"*":@"8",@"(":@"9",@")":@"0",@"_":@"-",@"+":@"=",@"{":@"[",@"}":@"]",@"|":@"\\",@":":@";",@"\"":@"'",@"<":@",",@">":@".",@"?":@"/"}; + NSUInteger index = [keys indexOfObject:shifted[text] ?: text.lowercaseString]; + if (index == NSNotFound || !text.length) return nil; + *code = (unsigned short)index; + return text; +} +static void change_modifiers(WKWebView *view, unsigned before, unsigned after) { + const unsigned bits[] = {CN_SHIFT, CN_CONTROL, CN_ALT, CN_META}; + const unsigned short codes[] = {56, 59, 58, 55}; + unsigned current = before; + for (int i = 0; i < 4; i++) { + if (!((before ^ after) & bits[i])) continue; + current = (current & ~bits[i]) | (after & bits[i]); + NSEvent *changed = [NSEvent keyEventWithType:NSEventTypeFlagsChanged location:NSZeroPoint + modifierFlags:modifiers(current) timestamp:NSProcessInfo.processInfo.systemUptime + windowNumber:view.window.windowNumber context:nil characters:@"" charactersIgnoringModifiers:@"" + isARepeat:NO keyCode:codes[i]]; + trace([NSString stringWithFormat:@"flagsChanged receiver=%@ code=%hu flags=0x%lx timestamp=%.6f window=%ld", view.class, codes[i], (unsigned long)changed.modifierFlags, changed.timestamp, (long)changed.windowNumber]); + with_modifiers(changed.modifierFlags, ^{ [view flagsChanged:changed]; }); + } +} +int cn_key(void *opaque, const char *key, unsigned flags, int down) { + WKWebView *view = (__bridge WKWebView *)opaque; + if (!view.window || view.hidden) return 0; + static char held_modifiers_key; + unsigned held = [objc_getAssociatedObject(view, &held_modifiers_key) unsignedIntValue]; + NSString *name=[NSString stringWithUTF8String:key]; + if ([@[@"Shift_L",@"Control_L",@"Alt_L",@"Meta_L"] containsObject:name]) { + change_modifiers(view,held,flags); + objc_setAssociatedObject(view,&held_modifiers_key,@(flags),OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return 1; + } + unsigned short code = 0; + NSString *text = characters(key, &code); + if (!text) return 0; + change_modifiers(view, held, flags); + objc_setAssociatedObject(view, &held_modifiers_key, @(flags), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + NSEvent *event = [NSEvent keyEventWithType:down ? NSEventTypeKeyDown : NSEventTypeKeyUp + location:NSZeroPoint modifierFlags:modifiers(flags) + timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:view.window.windowNumber + context:nil characters:text charactersIgnoringModifiers:text isARepeat:NO keyCode:code]; + [view.window makeFirstResponder:view]; + trace([NSString stringWithFormat:@"%@ key=%@ flags=0x%lx timestamp=%.6f window=%ld held=0x%x", down ? @"keyDown" : @"keyUp", [NSString stringWithUTF8String:key], (unsigned long)event.modifierFlags, event.timestamp, (long)event.windowNumber, flags]); + with_modifiers(event.modifierFlags, ^{ + NSDictionary *commands = @{@"a": @"selectAll:", @"c": @"copy:", @"v": @"paste:", @"x": @"cut:", @"z": @"undo:"}; + NSString *selector = flags == CN_META ? commands[text.lowercaseString] + : (flags == (CN_META | CN_SHIFT) && [text.lowercaseString isEqualToString:@"z"]) ? @"redo:" : nil; + SEL command = selector ? NSSelectorFromString(selector) : NULL; + // Execute editing equivalents once on this view. Acknowledged native input + // is never followed by a second command as an inactive-window fallback. + if (down && command && [view respondsToSelector:command]) { + [view tryToPerform:command with:nil]; + } else if (down) { + trace([NSString stringWithFormat:@"key %@ keyDown", [NSString stringWithUTF8String:key]]); + [view keyDown:event]; + } else { trace([NSString stringWithFormat:@"key %@ keyUp", [NSString stringWithUTF8String:key]]); [view keyUp:event]; } + }); + return 1; +} +int cn_text(void *opaque, const char *text) { + WKWebView *view = (__bridge WKWebView *)opaque; + if (!view.window || view.hidden) return 0; + [view.window makeFirstResponder:view]; + NSResponder *receiver = view.window.firstResponder; + if (!view.window || view.hidden || ![receiver isKindOfClass:NSView.class] || + ![(NSView *)receiver isDescendantOf:view] || ![receiver respondsToSelector:@selector(insertText:replacementRange:)]) return 0; + [(id)receiver insertText:[NSString stringWithUTF8String:text] replacementRange:NSMakeRange(NSNotFound, 0)]; + return 1; +} +void cn_capture(void *opaque, CNCompletion done, void *context) { + WKWebView *view = (__bridge WKWebView *)opaque; + WKSnapshotConfiguration *config = [WKSnapshotConfiguration new]; + config.rect = view.bounds; + [view takeSnapshotWithConfiguration:config completionHandler:^(NSImage *image, NSError *error) { + if (error || !image) { fail(done, context, error.localizedDescription ?: @"WebKit snapshot failed"); return; } + NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData:image.TIFFRepresentation]; + NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; + if (!png || png.length > 16 * 1024 * 1024) { fail(done, context, @"WebKit snapshot exceeds PNG budget"); return; } + done(context, png.bytes, png.length, NULL); + }]; +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input_native.rs b/packages/tauri-app/src-tauri/src/embedded_view/input_native.rs new file mode 100644 index 0000000000..79ed3fae34 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input_native.rs @@ -0,0 +1,161 @@ +//! Semantic input mapped to the already-qualified, target-local native adapters. +use serde_json::{json, Value}; +use std::{ + ffi::{c_char, c_void, CString}, + sync::{Arc, Mutex}, +}; +extern "C" { + fn cn_pointer(view: *mut c_void, action: i32, x: f64, y: f64, modifiers: u32) -> i32; + fn cn_wheel(view: *mut c_void, x: f64, y: f64, dx: f64, dy: f64, modifiers: u32) -> i32; + fn cn_key(view: *mut c_void, key: *const c_char, modifiers: u32, down: i32) -> i32; + fn cn_text(view: *mut c_void, text: *const c_char) -> i32; +} +pub(crate) type Held = Arc>>; +fn flags(event: &Value) -> u32 { + let flags = event["modifiers"].as_u64().unwrap_or(0) as u32; + ((flags & 8) >> 3) | (flags & 2) | ((flags & 1) << 2) | ((flags & 4) << 1) +} +fn key(value: &str) -> &str { + match value { + "Enter" => "Return", + "Backspace" => "BackSpace", + "ArrowUp" => "Up", + "ArrowDown" => "Down", + "ArrowLeft" => "Left", + "ArrowRight" => "Right", + "PageUp" => "Page_Up", + "PageDown" => "Page_Down", + "Shift" => "Shift_L", + "Control" => "Control_L", + "Alt" => "Alt_L", + "Meta" => "Meta_L", + "ContextMenu" => "Menu", + other => other, + } +} +pub(crate) unsafe fn dispatch( + view: *mut c_void, + operation: &Value, + held: &Held, +) -> Result<(), String> { + let event = &operation["event"]; + let kind = operation["op"].as_str().unwrap_or(""); + if kind == "pointer" && event["button"] == "middle" { + return Err("Native middle-button input is unsupported".into()); + } + let down = matches!( + event["type"].as_str(), + Some("mousePressed" | "keyDown" | "rawKeyDown") + ); + let up = matches!(event["type"].as_str(), Some("mouseReleased" | "keyUp")); + let identity = format!( + "{kind}:{}", + if kind == "pointer" { + event["button"].as_str().unwrap_or("") + } else { + event["code"].as_str().unwrap_or("") + } + ); + { + let mut held = held.lock().map_err(|error| error.to_string())?; + if kind == "pointer" { + for (_, release) in held.iter_mut().filter(|(_, item)| item["op"] == "pointer") { + release["event"]["x"] = event["x"].clone(); + release["event"]["y"] = event["y"].clone(); + } + } + if down { + if held.len() >= 64 && !held.iter().any(|(id, _)| id == &identity) { + return Err("Too many held native inputs".into()); + } + let mut release = operation.clone(); + release["event"]["type"] = json!(if kind == "pointer" { + "mouseReleased" + } else { + "keyUp" + }); + release["event"]["buttons"] = json!(0); + release["event"]["modifiers"] = json!(0); + if let Some(event) = release["event"].as_object_mut() { + event.remove("text"); + event.remove("unmodifiedText"); + } + held.retain(|(id, _)| id != &identity); + held.push((identity.clone(), release)); + } + } + let number = |key: &str| event[key].as_f64().unwrap_or(0.0); + let accepted = match kind { + "pointer" => { + let right = event["button"] == "right"; + let action = match event["type"].as_str() { + Some("mousePressed") => { + if right { + 3 + } else { + 1 + } + } + Some("mouseReleased") => { + if right { + 4 + } else { + 2 + } + } + _ => { + if event["buttons"].as_u64().unwrap_or(0) & 1 != 0 { + 5 + } else { + 0 + } + } + }; + unsafe { cn_pointer(view, action, number("x"), number("y"), flags(event)) } + } + "wheel" => unsafe { + cn_wheel( + view, + number("x"), + number("y"), + number("deltaX"), + number("deltaY"), + flags(event), + ) + }, + "keyboard" => { + let value = CString::new(key(event["key"].as_str().unwrap_or(""))) + .map_err(|_| "Invalid native key")?; + unsafe { cn_key(view, value.as_ptr(), flags(event), i32::from(down)) } + } + "insert-text" => { + let value = CString::new(operation["text"].as_str().unwrap_or("")) + .map_err(|_| "Native text contains a NUL character")?; + unsafe { cn_text(view, value.as_ptr()) } + } + _ => return Err("Unsupported native input operation".into()), + }; + if accepted == 0 { + return Err("Native browser input was refused".into()); + } + if up { + held.lock() + .map_err(|error| error.to_string())? + .retain(|(id, _)| id != &identity); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn semantic_modifiers_and_keys_match_native_adapters() { + for (cdp, native) in [(0, 0), (1, 4), (2, 2), (4, 8), (8, 1), (15, 15)] { + assert_eq!(flags(&json!({"modifiers":cdp})), native); + } + assert_eq!(key("Enter"), "Return"); + assert_eq!(key("Meta"), "Meta_L"); + assert_eq!(key("ArrowDown"), "Down"); + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/input_navigation_macos.m b/packages/tauri-app/src-tauri/src/embedded_view/input_navigation_macos.m new file mode 100644 index 0000000000..fe5d8efb84 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/input_navigation_macos.m @@ -0,0 +1,56 @@ +#import +#import +#include + +typedef void (*CNLoad)(void *, uint64_t, int, const char *, const char *); +typedef void (*CNRelease)(void *); +@interface CNLoadObserver : NSObject +@property (strong) id original; +@property CNLoad callback; +@property CNRelease releaseContext; +@property void *context; +@end +@implementation CNLoadObserver +- (BOOL)respondsToSelector:(SEL)selector { + return [super respondsToSelector:selector] || [self.original respondsToSelector:selector]; +} +- (id)forwardingTargetForSelector:(SEL)selector { return self.original; } +- (void)webView:(WKWebView *)view didStartProvisionalNavigation:(WKNavigation *)navigation { + if ([self.original respondsToSelector:_cmd]) [self.original webView:view didStartProvisionalNavigation:navigation]; + self.callback(self.context, (uint64_t)(uintptr_t)(__bridge void *)navigation, 0, view.URL.absoluteString.UTF8String, NULL); +} +- (void)webView:(WKWebView *)view didFinishNavigation:(WKNavigation *)navigation { + if ([self.original respondsToSelector:_cmd]) [self.original webView:view didFinishNavigation:navigation]; + self.callback(self.context, (uint64_t)(uintptr_t)(__bridge void *)navigation, 1, view.URL.absoluteString.UTF8String, NULL); +} +- (void)webView:(WKWebView *)view didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { + if ([self.original respondsToSelector:_cmd]) [self.original webView:view didFailProvisionalNavigation:navigation withError:error]; + self.callback(self.context, (uint64_t)(uintptr_t)(__bridge void *)navigation, 2, view.URL.absoluteString.UTF8String, error.localizedDescription.UTF8String); +} +- (void)webView:(WKWebView *)view didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { + if ([self.original respondsToSelector:_cmd]) [self.original webView:view didFailNavigation:navigation withError:error]; + self.callback(self.context, (uint64_t)(uintptr_t)(__bridge void *)navigation, 2, view.URL.absoluteString.UTF8String, error.localizedDescription.UTF8String); +} +- (void)dealloc { if (self.releaseContext) self.releaseContext(self.context); } +@end + +int cn_observe_load(void *opaque, CNLoad callback, CNRelease releaseContext, void *context) { + WKWebView *view = (__bridge WKWebView *)opaque; + if (!view.navigationDelegate) return 0; + CNLoadObserver *observer = [CNLoadObserver new]; + observer.original = view.navigationDelegate; + observer.callback = callback; + observer.context = context; + observer.releaseContext = releaseContext; + static char key; + objc_setAssociatedObject(view, &key, observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + view.navigationDelegate = observer; + return 1; +} + +uint64_t cn_navigate(void *opaque, const char *url) { + WKWebView *view = (__bridge WKWebView *)opaque; + NSURL *target = [NSURL URLWithString:[NSString stringWithUTF8String:url]]; + WKNavigation *navigation = [view loadRequest:[NSURLRequest requestWithURL:target]]; + return (uint64_t)(uintptr_t)(__bridge void *)navigation; +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/linux.rs b/packages/tauri-app/src-tauri/src/embedded_view/linux.rs new file mode 100644 index 0000000000..dfa310999f --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/linux.rs @@ -0,0 +1,272 @@ +pub(super) fn request_close(view: &tauri::Webview) -> Result<(), String> { + use webkit2gtk::WebViewExt; + view.with_webview(|native| native.inner().try_close()) + .map_err(|error| error.to_string()) +} + +pub(super) fn install(webview: &tauri::Webview) -> Result<(), String> { + use std::sync::mpsc; + use std::time::Duration; + use tauri::Manager; + use webkit2gtk::{PermissionRequestExt, WebViewExt}; + + let (sender, receiver) = mpsc::sync_channel(1); + let view = webview.clone(); + let policy = webview + .app_handle() + .try_state::() + .ok_or("Missing browser registry")? + .inner() + .clone(); + let token = policy + .token(webview.label()) + .ok_or("Expired browser view")?; + webview + .with_webview(move |platform| { + use std::{cell::Cell, rc::Rc}; + use tauri::Manager; + let generation = Rc::new(Cell::new(0u64)); + let loading = generation.clone(); + platform.inner().connect_load_changed(move |_, event| { + if event == webkit2gtk::LoadEvent::Started { + loading.set(loading.get().wrapping_add(1)); + } + }); + let enter = view.clone(); + let enter_policy = policy.clone(); + platform.inner().connect_enter_fullscreen(move |_| { + if !enter_policy.current(enter.label(), token) { + return true; + } + if let Some(views) = enter.app_handle().try_state::() { + let _ = views.set_fullscreen(enter.app_handle(), enter.label(), true); + } + false + }); + let leave = view.clone(); + let leave_policy = policy.clone(); + platform.inner().connect_leave_fullscreen(move |_| { + if !leave_policy.current(leave.label(), token) { + return false; + } + if let Some(views) = leave.app_handle().try_state::() { + let _ = views.set_fullscreen(leave.app_handle(), leave.label(), false); + } + false + }); + platform + .inner() + .connect_permission_request(move |page, request| { + if !policy.current(view.label(), token) { + request.deny(); + return true; + } + use gtk::glib::{Cast, ObjectExt}; + use webkit2gtk::{ + DeviceInfoPermissionRequest, GeolocationPermissionRequest, + NotificationPermissionRequest, PointerLockPermissionRequest, + UserMediaPermissionRequest, UserMediaPermissionRequestExt, + WebsiteDataAccessPermissionRequest, WebsiteDataAccessPermissionRequestExt, + }; + if request.is::() + || request.is::() + || request + .downcast_ref::() + .is_some_and(|media| { + media.is_for_audio_device() || media.is_for_video_device() + }) + || request.is::() + { + request.deny(); + return true; + } + // WebKit's pointer-lock API grants the WebView's pointer, + // not a frame resource. Its own MiniBrowser attributes this + // page-scoped request to the displayed WebView origin. + // https://github.com/WebKit/WebKit/blob/main/Tools/MiniBrowser/gtk/BrowserTab.c + let consent = if request.is::() { + page.uri() + .and_then(|uri| super::browser::page_permission_subject(&uri)) + .map(|subject| ("pointer-lock", subject)) + } else if let Some(storage) = + request.downcast_ref::() + { + storage + .requesting_domain() + .zip(storage.current_domain()) + .map(|(requester, current)| { + ("storage-access", format!("{requester} → {current}")) + }) + } else { + None + }; + if let Some((kind, subject)) = consent { + use tauri::Manager; + use tauri_plugin_dialog::{DialogExt, MessageDialogButtons}; + let label = |key| { + view.app_handle() + .try_state::() + .map(|state| state.menu_labels.text(key)) + .unwrap_or_else(|| crate::menu_labels::label(key).to_string()) + }; + let message = label("browserPermission") + .replace("{permission}", kind) + .replace("{origin}", &subject); + let request = request.clone(); + let epoch = generation.clone(); + let captured = epoch.get(); + let weak_page = page.downgrade(); + let answer_policy = policy.clone(); + let answer_label = view.label().to_string(); + let (reply, answer) = + gtk::glib::MainContext::channel::(gtk::glib::Priority::DEFAULT); + answer.attach(None, move |allowed| { + if allowed + && epoch.get() == captured + && weak_page.upgrade().is_some() + && answer_policy.current(&answer_label, token) + { + request.allow(); + } else { + request.deny(); + } + gtk::glib::ControlFlow::Break + }); + if kind == "pointer-lock" { + let denied = reply.clone(); + if pointer_lock_consent( + page, + &message, + &label("browserAllow"), + &label("browserDeny"), + move |allowed| { + let _ = reply.send(allowed); + }, + ) + .is_err() + { + let _ = denied.send(false); + super::browser::unknown_permission( + &view, + "pointer-lock: consent unavailable", + ); + } + return true; + } + view.app_handle() + .dialog() + .message(message) + .parent(&view.window()) + .buttons(MessageDialogButtons::OkCancelCustom( + label("browserAllow"), + label("browserDeny"), + )) + .show(move |allowed| { + let _ = reply.send(allowed); + }); + return true; + } + // This API exposes no requesting-frame origin for these request + // classes. Never substitute the top-level page's origin. + request.deny(); + super::browser::unknown_permission(&view, request.type_().name()); + true + }); + let _ = sender.send(()); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Timed out configuring WebKitGTK browser security".to_string())?; + super::zoom::install(webview) +} + +// Keep the requesting Wayland surface focused: a separate modal window causes +// WebKit to cancel pointer lock before its permission response arrives. +fn pointer_lock_consent( + page: &webkit2gtk::WebView, + message: &str, + allow: &str, + deny: &str, + answer: impl FnOnce(bool) + 'static, +) -> Result<(), ()> { + use gtk::{ + glib::{Cast, ObjectExt}, + prelude::*, + }; + use std::{cell::RefCell, rc::Rc}; + use webkit2gtk::WebViewExt; + + let mut ancestor = page.parent(); + let mut overlay = None; + while let Some(widget) = ancestor { + overlay = widget.clone().downcast::().ok(); + if overlay.is_some() { + break; + } + ancestor = widget.parent(); + } + let overlay = match overlay { + Some(overlay) => overlay, + None => { + let window = page + .toplevel() + .and_then(|widget| widget.downcast::().ok()) + .ok_or(())?; + let child = window.child().ok_or(())?; + let overlay = gtk::Overlay::new(); + window.remove(&child); + overlay.add(&child); + window.add(&overlay); + overlay.show(); + overlay + } + }; + let bar = gtk::InfoBar::new(); + bar.set_halign(gtk::Align::Fill); + bar.set_valign(gtk::Align::Start); + bar.set_message_type(gtk::MessageType::Question); + let text = gtk::Label::new(Some(message)); + text.set_line_wrap(true); + bar.content_area().add(&text); + for (label, response) in [ + (deny, gtk::ResponseType::Cancel), + (allow, gtk::ResponseType::Accept), + ] { + let button = bar.add_button(&format!("_{label}"), response).ok_or(())?; + button.set_use_underline(true); + button.set_focus_on_click(false); + } + let answer = Rc::new(RefCell::new(Some(answer))); + let response = answer.clone(); + bar.connect_response(move |bar, value| { + if let Some(answer) = response.borrow_mut().take() { + answer(value == gtk::ResponseType::Accept); + } + unsafe { + bar.destroy(); + } + }); + bar.connect_close(|bar| bar.response(gtk::ResponseType::Cancel)); + let weak_bar = bar.downgrade(); + let loading = page.connect_load_changed(move |_, event| { + if event == webkit2gtk::LoadEvent::Started { + if let Some(bar) = weak_bar.upgrade() { + bar.response(gtk::ResponseType::Cancel); + } + } + }); + let weak_page = page.downgrade(); + let loading = RefCell::new(Some(loading)); + bar.connect_destroy(move |_| { + if let (Some(page), Some(loading)) = (weak_page.upgrade(), loading.borrow_mut().take()) { + page.disconnect(loading); + } + if let Some(answer) = answer.borrow_mut().take() { + answer(false); + } + }); + overlay.add_overlay(&bar); + bar.show_all(); + Ok(()) +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/macos.rs b/packages/tauri-app/src-tauri/src/embedded_view/macos.rs new file mode 100644 index 0000000000..4c2d191110 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/macos.rs @@ -0,0 +1,25 @@ +pub(super) fn request_close(view: &tauri::Webview) -> Result<(), String> { + let window = view.window(); + view.with_webview(move |native| unsafe { + let Some(view) = native.inner().cast::().as_ref() else { + return; + }; + // WebKit's native tryClose runs beforeunload, then webViewDidClose. + // An immediate YES means no asynchronous confirmation was needed. + let available: objc2::runtime::Bool = + objc2::msg_send![view, respondsToSelector: objc2::sel!(_tryClose)]; + if !available.as_bool() { + eprintln!("[browser-close] WKWebView tryClose unavailable"); + return; + } + let close: objc2::runtime::Bool = objc2::msg_send![view, _tryClose]; + if close.as_bool() { + let _ = window.destroy(); + } + }) + .map_err(|error| error.to_string()) +} + +pub(super) fn install(view: &tauri::Webview) -> Result<(), String> { + super::zoom::install(view) +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/mobile.rs b/packages/tauri-app/src-tauri/src/embedded_view/mobile.rs new file mode 100644 index 0000000000..2d51ef62fd --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/mobile.rs @@ -0,0 +1,50 @@ +use std::{ + ffi::{c_char, c_void, CString}, + sync::mpsc, + time::Duration, +}; +extern "C" { + fn cn_preview_scale(view: *mut c_void, device: *mut f64) -> f64; + fn cn_preview_profile(view: *mut c_void, ua: *const c_char, zoom: f64, density: f64) -> i32; +} +pub(crate) fn scale(view: &tauri::Webview) -> Result<(f64, f64), String> { + native(view, |ptr| { + let mut device = 1.0; + let scale = unsafe { cn_preview_scale(ptr, &mut device) }; + if !scale.is_finite() || scale <= 0.0 || !device.is_finite() || device <= 0.0 { + return Err("Native preview scale is unavailable".into()); + } + Ok((scale, device)) + }) +} +pub(crate) fn profile( + view: &tauri::Webview, + ua: &str, + zoom: f64, + density: f64, +) -> Result { + let ua = CString::new(ua).map_err(|_| "Invalid preview identity")?; + native(view, move |ptr| { + Ok(unsafe { cn_preview_profile(ptr, ua.as_ptr(), zoom, density) } != 0) + }) +} +pub(super) fn native( + view: &tauri::Webview, + run: impl FnOnce(*mut c_void) -> Result + Send + 'static, +) -> Result { + let (sender, receiver) = mpsc::sync_channel(1); + view.with_webview(move |native| { + #[cfg(target_os = "macos")] + let ptr = native.inner(); + #[cfg(target_os = "linux")] + let ptr = { + use gtk::glib::object::ObjectType; + native.inner().as_ptr().cast::() + }; + let _ = sender.send(run(ptr)); + }) + .map_err(|e| e.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Native preview profile timed out".to_string())? +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/mobile_linux.c b/packages/tauri-app/src-tauri/src/embedded_view/mobile_linux.c new file mode 100644 index 0000000000..0ebba5d3f5 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/mobile_linux.c @@ -0,0 +1,72 @@ +#include +#include +#include "zoom.h" +typedef struct { gboolean mobile, active, sending; double x, y; } TouchState; +static void touch(GtkWidget *view, TouchState *state, GdkEventType type, double x, double y) { + GdkWindow *window = gtk_widget_get_window(view); + GdkSeat *seat = gdk_display_get_default_seat(gtk_widget_get_display(view)); + if (!window || !seat) return; + GdkEvent *event = gdk_event_new(type); + event->touch.window = g_object_ref(window); + event->touch.send_event = FALSE; + event->touch.time = GDK_CURRENT_TIME; + event->touch.x = x; event->touch.y = y; + event->touch.sequence = (GdkEventSequence *)state; + event->touch.emulating_pointer = TRUE; + int ox = 0, oy = 0; + gdk_window_get_origin(window, &ox, &oy); + event->touch.x_root = ox + x; event->touch.y_root = oy + y; + gdk_event_set_device(event, gdk_seat_get_pointer(seat)); + state->sending = TRUE; + gtk_widget_event(view, event); + state->sending = FALSE; + gdk_event_free(event); + state->x = x; state->y = y; +} +static gboolean pressed(GtkWidget *view, GdkEventButton *event, gpointer data) { + TouchState *state = data; + if (state->sending || gdk_event_get_pointer_emulated((GdkEvent *)event)) return FALSE; + if (!state->mobile || event->button != 1) return FALSE; + // GTK also emits multi-click notifications after the ordinary press. + if (event->type != GDK_BUTTON_PRESS) return TRUE; + state->active = TRUE; + touch(view, state, GDK_TOUCH_BEGIN, event->x, event->y); + return TRUE; +} +static gboolean released(GtkWidget *view, GdkEventButton *event, gpointer data) { + TouchState *state = data; + if (state->sending || gdk_event_get_pointer_emulated((GdkEvent *)event)) return FALSE; + if (!state->mobile || event->button != 1 || !state->active) return FALSE; + state->active = FALSE; + touch(view, state, GDK_TOUCH_END, event->x, event->y); + return TRUE; +} +static gboolean moved(GtkWidget *view, GdkEventMotion *event, gpointer data) { + TouchState *state = data; + if (state->sending || gdk_event_get_pointer_emulated((GdkEvent *)event)) return FALSE; + if (!state->mobile) return FALSE; + if (state->active) touch(view, state, GDK_TOUCH_UPDATE, event->x, event->y); + return TRUE; +} +double cn_preview_scale(void *opaque, double *device) { + *device = gtk_widget_get_scale_factor(GTK_WIDGET(opaque)); + return webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(opaque)) * *device; +} +int cn_preview_profile(void *opaque, const char *ua, double zoom, double density) { + (void)density; + GtkWidget *view = GTK_WIDGET(opaque); + TouchState *state = g_object_get_data(G_OBJECT(view), "codenomad-mobile-touch"); + if (!state) { + state = g_new0(TouchState, 1); + g_object_set_data_full(G_OBJECT(view), "codenomad-mobile-touch", state, g_free); + g_signal_connect(view, "button-press-event", G_CALLBACK(pressed), state); + g_signal_connect(view, "button-release-event", G_CALLBACK(released), state); + g_signal_connect(view, "motion-notify-event", G_CALLBACK(moved), state); + } + if (state->active) touch(view, state, GDK_TOUCH_CANCEL, state->x, state->y); + state->active = FALSE; state->mobile = ua && *ua; + WebKitWebView *web = WEBKIT_WEB_VIEW(view); + webkit_settings_set_user_agent(webkit_web_view_get_settings(web), state->mobile ? ua : NULL); + cn_preview_zoom_base(opaque, zoom); + return 0; +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/mobile_macos.m b/packages/tauri-app/src-tauri/src/embedded_view/mobile_macos.m new file mode 100644 index 0000000000..87fb0a5fa7 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/mobile_macos.m @@ -0,0 +1,20 @@ +#import +#import +#include "zoom.h" +@interface WKWebView (CNDeviceScale) +- (void)_setOverrideDeviceScaleFactor:(CGFloat)scale; +@end +double cn_preview_scale(void *opaque,double *device) { + WKWebView *view=(__bridge WKWebView *)opaque; + *device=view.window.backingScaleFactor; + return view.pageZoom * *device; +} +int cn_preview_profile(void *opaque,const char *ua,double zoom,double density) { + WKWebView *view=(__bridge WKWebView *)opaque; + view.customUserAgent=ua&&*ua?[NSString stringWithUTF8String:ua]:nil; + cn_preview_zoom_base(opaque,zoom); + if([view respondsToSelector:@selector(_setOverrideDeviceScaleFactor:)]) { + [view _setOverrideDeviceScaleFactor:density];return 1; + } + return 0; +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/page_read.generated.h b/packages/tauri-app/src-tauri/src/embedded_view/page_read.generated.h new file mode 100644 index 0000000000..c7be40d239 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/page_read.generated.h @@ -0,0 +1,4 @@ +#pragma once +/* Generated fixed isolated-world program; MIT notice is embedded in the source. */ +static const char CN_PAGE_READ[] = "/*! dom-accessibility-api 0.7.1\nMIT License\n\nCopyright (c) 2020 Sebastian Silbermann\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\"use strict\";var __codenomadReadModule=(()=>{var ee=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var n in t)ee(e,n,{get:t[n],enumerable:!0})},tt=(e,t,n,r)=>{if(t&&typeof t==\"object\"||typeof t==\"function\")for(let a of Ue(t))!Ze.call(e,a)&&a!==n&&ee(e,a,{get:()=>t[a],enumerable:!(r=Qe(t,a))||r.enumerable});return e};var nt=e=>tt(ee({},\"__esModule\",{value:!0}),e);var Gt={};et(Gt,{read:()=>$t});var rt=Object.prototype.toString;function pe(e){return typeof e==\"function\"||rt.call(e)===\"[object Function]\"}function ot(e){var t=Number(e);return isNaN(t)\?0:t===0||!isFinite(t)\?t:(t>0\?1:-1)*Math.floor(Math.abs(t))}var it=Math.pow(2,53)-1;function at(e){var t=ot(e);return Math.min(Math.max(t,0),it)}function A(e,t){var n=Array,r=Object(e);if(e==null)throw new TypeError(\"Array.from requires an array-like object - not null or undefined\");if(typeof t<\"u\"&&!pe(t))throw new TypeError(\"Array.from: when provided, the second argument must be a function\");for(var a=at(r.length),d=pe(n)\?Object(new n(a)):new Array(a),i=0,u;i0&&arguments[0]!==void 0\?arguments[0]:[];lt(this,e),ut(this,\"items\",void 0),this.items=t}return st(e,[{key:\"add\",value:function(n){return this.has(n)===!1&&this.items.push(n),this}},{key:\"clear\",value:function(){this.items=[]}},{key:\"delete\",value:function(n){var r=this.items.length;return this.items=this.items.filter(function(a){return a!==n}),r!==this.items.length}},{key:\"forEach\",value:function(n){var r=this;this.items.forEach(function(a){n(a,a,r)})}},{key:\"has\",value:function(n){return this.items.indexOf(n)!==-1}},{key:\"size\",get:function(){return this.items.length}}])})(),ge=typeof Set>\"u\"\?Set:dt;function x(e){var t;return(t=e.localName)!==null&&t!==void 0\?t:e.tagName.toLowerCase()}var ft={article:\"article\",aside:\"complementary\",button:\"button\",datalist:\"listbox\",dd:\"definition\",details:\"group\",dialog:\"dialog\",dt:\"term\",fieldset:\"group\",figure:\"figure\",form:\"form\",footer:\"contentinfo\",h1:\"heading\",h2:\"heading\",h3:\"heading\",h4:\"heading\",h5:\"heading\",h6:\"heading\",header:\"banner\",hr:\"separator\",html:\"document\",legend:\"legend\",li:\"listitem\",math:\"math\",main:\"main\",menu:\"list\",nav:\"navigation\",ol:\"list\",optgroup:\"group\",option:\"option\",output:\"status\",progress:\"progressbar\",section:\"region\",summary:\"button\",table:\"table\",tbody:\"rowgroup\",textarea:\"textbox\",tfoot:\"rowgroup\",td:\"cell\",th:\"columnheader\",thead:\"rowgroup\",tr:\"row\",ul:\"list\"},mt={caption:new Set([\"aria-label\",\"aria-labelledby\"]),code:new Set([\"aria-label\",\"aria-labelledby\"]),deletion:new Set([\"aria-label\",\"aria-labelledby\"]),emphasis:new Set([\"aria-label\",\"aria-labelledby\"]),generic:new Set([\"aria-label\",\"aria-labelledby\",\"aria-roledescription\"]),insertion:new Set([\"aria-label\",\"aria-labelledby\"]),none:new Set([\"aria-label\",\"aria-labelledby\"]),paragraph:new Set([\"aria-label\",\"aria-labelledby\"]),presentation:new Set([\"aria-label\",\"aria-labelledby\"]),strong:new Set([\"aria-label\",\"aria-labelledby\"]),subscript:new Set([\"aria-label\",\"aria-labelledby\"]),superscript:new Set([\"aria-label\",\"aria-labelledby\"])};function pt(e,t){return[\"aria-atomic\",\"aria-busy\",\"aria-controls\",\"aria-current\",\"aria-description\",\"aria-describedby\",\"aria-details\",\"aria-dropeffect\",\"aria-flowto\",\"aria-grabbed\",\"aria-hidden\",\"aria-keyshortcuts\",\"aria-label\",\"aria-labelledby\",\"aria-live\",\"aria-owns\",\"aria-relevant\",\"aria-roledescription\"].some(function(n){var r;return e.hasAttribute(n)&&!((r=mt[t])!==null&&r!==void 0&&r.has(n))})}function we(e,t){return pt(e,t)}function V(e){var t=ht(e);if(t===null||G.indexOf(t)!==-1){var n=bt(e);if(G.indexOf(t||\"\")===-1||we(e,n||\"\"))return n}return t}function bt(e){var t=ft[x(e)];if(t!==void 0)return t;switch(x(e)){case\"a\":case\"area\":case\"link\":if(e.hasAttribute(\"href\"))return\"link\";break;case\"img\":return e.getAttribute(\"alt\")===\"\"&&!we(e,\"img\")\?\"presentation\":\"img\";case\"input\":{var n=e,r=n.type;switch(r){case\"button\":case\"image\":case\"reset\":case\"submit\":return\"button\";case\"checkbox\":case\"radio\":return r;case\"range\":return\"slider\";case\"email\":case\"tel\":case\"text\":case\"url\":return e.hasAttribute(\"list\")\?\"combobox\":\"textbox\";case\"search\":return e.hasAttribute(\"list\")\?\"combobox\":\"searchbox\";case\"number\":return\"spinbutton\";default:return null}}case\"select\":return e.hasAttribute(\"multiple\")||e.size>1\?\"listbox\":\"combobox\"}return null}function ht(e){var t=e.getAttribute(\"role\");if(t!==null){var n=t.trim().split(\" \")[0];if(n.length>0)return n}return null}var G=[\"presentation\",\"none\"];function T(e){return e!==null&&e.nodeType===e.ELEMENT_NODE}function te(e){return T(e)&&x(e)===\"caption\"}function q(e){return T(e)&&x(e)===\"input\"}function Ee(e){return T(e)&&x(e)===\"optgroup\"}function ye(e){return T(e)&&x(e)===\"select\"}function ve(e){return T(e)&&x(e)===\"table\"}function Se(e){return T(e)&&x(e)===\"textarea\"}function Te(e){var t=e.ownerDocument===null\?e:e.ownerDocument,n=t.defaultView;if(n===null)throw new TypeError(\"no window available\");return n}function xe(e){return T(e)&&x(e)===\"fieldset\"}function Me(e){return T(e)&&x(e)===\"legend\"}function Le(e){return T(e)&&x(e)===\"slot\"}function gt(e){return T(e)&&e.ownerSVGElement!==void 0}function Ne(e){return T(e)&&x(e)===\"svg\"}function Ae(e){return gt(e)&&x(e)===\"title\"}function P(e,t){if(T(e)&&e.hasAttribute(t)){var n=e.getAttribute(t).split(\" \"),r=e.getRootNode\?e.getRootNode():e.ownerDocument;return n.map(function(a){return r.getElementById(a)}).filter(function(a){return a!==null})}return[]}function H(e,t){return T(e)\?t.indexOf(V(e))!==-1:!1}function wt(e){return e.trim().replace(/\\s\\s+/g,\" \")}function Et(e,t){if(!T(e))return!1;if(e.hasAttribute(\"hidden\")||e.getAttribute(\"aria-hidden\")===\"true\")return!0;var n=t(e);return n.getPropertyValue(\"display\")===\"none\"||n.getPropertyValue(\"visibility\")===\"hidden\"}function yt(e){return H(e,[\"button\",\"combobox\",\"listbox\",\"textbox\"])||De(e,\"range\")}function De(e,t){if(!T(e))return!1;switch(t){case\"range\":return H(e,[\"meter\",\"progressbar\",\"scrollbar\",\"slider\",\"spinbutton\"]);default:throw new TypeError(\"No knowledge about abstract role '\".concat(t,\"'. This is likely a bug :(\"))}}function He(e,t){var n=A(e.querySelectorAll(t));return P(e,\"aria-owns\").forEach(function(r){n.push.apply(n,A(r.querySelectorAll(t)))}),n}function vt(e){return ye(e)\?e.selectedOptions||He(e,\"[selected]\"):He(e,'[aria-selected=\"true\"]')}function St(e){return H(e,G)}function Tt(e){return te(e)}function xt(e){return H(e,[\"button\",\"cell\",\"checkbox\",\"columnheader\",\"gridcell\",\"heading\",\"label\",\"legend\",\"link\",\"menuitem\",\"menuitemcheckbox\",\"menuitemradio\",\"option\",\"radio\",\"row\",\"rowheader\",\"switch\",\"tab\",\"tooltip\",\"treeitem\"])}function Mt(e){return!1}function Lt(e){return q(e)||Se(e)\?e.value:e.textContent||\"\"}function ke(e){var t=e.getPropertyValue(\"content\");return/^[\"'].*[\"']$/.test(t)\?t.slice(1,-1):\"\"}function Ce(e){var t=x(e);return t===\"button\"||t===\"input\"&&e.getAttribute(\"type\")!==\"hidden\"||t===\"meter\"||t===\"output\"||t===\"progress\"||t===\"select\"||t===\"textarea\"}function Re(e){if(Ce(e))return e;var t=null;return e.childNodes.forEach(function(n){if(t===null&&T(n)){var r=Re(n);r!==null&&(t=r)}}),t}function Nt(e){if(e.control!==void 0)return e.control;var t=e.getAttribute(\"for\");return t!==null\?e.ownerDocument.getElementById(t):Re(e)}function At(e){var t=e.labels;if(t===null)return t;if(t!==void 0)return A(t);if(!Ce(e))return null;var n=e.ownerDocument;return A(n.querySelectorAll(\"label\")).filter(function(r){return Nt(r)===e})}function Ht(e){var t=e.assignedNodes();return t.length===0\?A(e.childNodes):t}function B(e){var t=arguments.length>1&&arguments[1]!==void 0\?arguments[1]:{},n=new ge,r=typeof Map>\"u\"\?void 0:new Map,a=Te(e),d=t.compute,i=d===void 0\?\"name\":d,u=t.computedStyleSupportsPseudoElements,l=u===void 0\?t.getComputedStyle!==void 0:u,c=t.getComputedStyle,b=c===void 0\?a.getComputedStyle.bind(a):c,E=t.hidden,S=E===void 0\?!1:E,f=function(w,s){if(s!==void 0)throw new Error(\"use uncachedGetComputedStyle directly for pseudo elements\");if(r===void 0)return b(w);var y=r.get(w);if(y)return y;var M=b(w,s);return r.set(w,M),M};function h(o,w){var s=\"\";if(T(o)&&l){var y=b(o,\"::before\"),M=ke(y);s=\"\".concat(M,\" \").concat(s)}var L=Le(o)\?Ht(o):A(o.childNodes).concat(P(o,\"aria-owns\"));if(L.forEach(function(k){var R=g(k,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),D=T(k)\?f(k).getPropertyValue(\"display\"):\"inline\",W=D!==\"inline\"\?\" \":\"\";s+=\"\".concat(W).concat(R).concat(W)}),T(o)&&l){var N=b(o,\"::after\"),C=ke(N);s=\"\".concat(s,\" \").concat(C)}return s.trim()}function p(o,w){var s=o.getAttributeNode(w);return s!==null&&!n.has(s)&&s.value.trim()!==\"\"\?(n.add(s),s.value):null}function m(o){return T(o)\?p(o,\"title\"):null}function v(o){if(!T(o))return null;if(xe(o)){n.add(o);for(var w=A(o.childNodes),s=0;s0}).join(\" \");if(q(o)&&o.type===\"image\"){var de=p(o,\"alt\");if(de!==null)return de;var fe=p(o,\"title\");return fe!==null\?fe:\"Submit Query\"}if(H(o,[\"button\"])){var me=h(o,{isEmbeddedInLabel:!1,isReferenced:!1});if(me!==\"\")return me}return null}function g(o,w){if(n.has(o))return\"\";if(!S&&Et(o,f)&&!w.isReferenced)return n.add(o),\"\";var s=T(o)\?o.getAttributeNode(\"aria-labelledby\"):null,y=s!==null&&!n.has(s)\?P(o,\"aria-labelledby\"):[];if(i===\"name\"&&!w.isReferenced&&y.length>0)return n.add(s),y.map(function(D){return g(D,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(\" \");var M=w.recursion&&yt(o)&&i===\"name\";if(!M){var L=(T(o)&&o.getAttribute(\"aria-label\")||\"\").trim();if(L!==\"\"&&i===\"name\")return n.add(o),L;if(!St(o)){var N=v(o);if(N!==null)return n.add(o),N}}if(H(o,[\"menu\"]))return n.add(o),\"\";if(M||w.isEmbeddedInLabel||w.isReferenced){if(H(o,[\"combobox\",\"listbox\"])){n.add(o);var C=vt(o);return C.length===0\?q(o)\?o.value:\"\":A(C).map(function(D){return g(D,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(\" \")}if(De(o,\"range\"))return n.add(o),o.hasAttribute(\"aria-valuetext\")\?o.getAttribute(\"aria-valuetext\"):o.hasAttribute(\"aria-valuenow\")\?o.getAttribute(\"aria-valuenow\"):o.getAttribute(\"value\")||\"\";if(H(o,[\"textbox\"]))return n.add(o),Lt(o)}if(xt(o)||T(o)&&w.isReferenced||Tt(o)||Mt(o)){var k=h(o,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1});if(k!==\"\")return n.add(o),k}if(o.nodeType===o.TEXT_NODE)return n.add(o),o.textContent||\"\";if(w.recursion)return n.add(o),h(o,{isEmbeddedInLabel:w.isEmbeddedInLabel,isReferenced:!1});var R=m(o);return R!==null\?(n.add(o),R):(n.add(o),\"\")}return wt(g(e,{isEmbeddedInLabel:!1,isReferenced:i===\"description\",recursion:!1}))}function F(e){\"@babel/helpers - typeof\";return F=typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?function(t){return typeof t}:function(t){return t&&typeof Symbol==\"function\"&&t.constructor===Symbol&&t!==Symbol.prototype\?\"symbol\":typeof t},F(e)}function Ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Oe(e){for(var t=1;t1&&arguments[1]!==void 0\?arguments[1]:{},n=P(e,\"aria-describedby\").map(function(d){return B(d,Oe(Oe({},t),{},{compute:\"description\"}))}).join(\" \");if(n===\"\"){var r=e.getAttribute(\"aria-description\");n=r===null\?\"\":r}if(n===\"\"){var a=e.getAttribute(\"title\");n=a===null\?\"\":a}return n}function Rt(e){return H(e,[\"caption\",\"code\",\"deletion\",\"emphasis\",\"generic\",\"insertion\",\"none\",\"paragraph\",\"presentation\",\"strong\",\"subscript\",\"superscript\"])}function J(e){var t=arguments.length>1&&arguments[1]!==void 0\?arguments[1]:{};return Rt(e)\?\"\":B(e,t)}function Ie(e){var t,n=arguments.length>1&&arguments[1]!==void 0\?arguments[1]:{},r=n.getComputedStyle,a=r===void 0\?(t=e.ownerDocument.defaultView)===null||t===void 0\?void 0:t.getComputedStyle:r,d=n.isSubtreeInaccessible,i=d===void 0\?Vt:d;if(typeof a!=\"function\")throw new TypeError(\"Owner document of the element needs to have an associated window.\");if(a(e).visibility===\"hidden\")return!0;for(var u=e;u;){if(i(u,{getComputedStyle:a}))return!0;u=u.parentElement}return!1}function Vt(e){var t,n=arguments.length>1&&arguments[1]!==void 0\?arguments[1]:{},r=n.getComputedStyle,a=r===void 0\?(t=e.ownerDocument.defaultView)===null||t===void 0\?void 0:t.getComputedStyle:r;if(typeof a!=\"function\")throw new TypeError(\"Owner document of the element needs to have an associated window.\");return e.hidden===!0||e.getAttribute(\"aria-hidden\")===\"true\"||a(e).display===\"none\"}var re={\"option-click\":function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=g=>(g.label||g.textContent||\"\").replace(/\\s+/g,\" \").trim(),h=(g,o)=>{if(g.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");for(let s of o)if(s.matches(\":disabled\"))throw new Error(\"codenomad:option-disabled:\"+f(s));if(!g.multiple&&o.length!==1)throw new Error(\"codenomad:single\");g.focus();let w=Array.from(g.options);if(w.some(s=>s.selected!==o.includes(s))){for(let s of w)s.selected=o.includes(s);g.dispatchEvent(new b(\"input\",{bubbles:!0,composed:!0})),g.dispatchEvent(new b(\"change\",{bubbles:!0}))}return Array.from(g.selectedOptions).map(f)},p=(g,o)=>{if(g.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");let w=Array.from(g.options),s=[];for(let y of o){let M=String(y).replace(/\\s+/g,\" \").trim(),L=w.find(N=>f(N)===M)||w.find(N=>N.value===String(y));if(!L)throw new Error(\"codenomad:no-option:\"+M);s.includes(L)||s.push(L)}return h(g,s)},m=t.closest(\"option\"),v=m&&m.closest(\"select\");if(m&&v)return h(v,[m]);if(t instanceof i)throw new Error(\"codenomad:is-select\");return null},\"programmatic-click\":function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();return t instanceof u\?t.click():t.dispatchEvent(new E(\"click\",{bubbles:!0,cancelable:!0,composed:!0})),null},select:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=g=>(g.label||g.textContent||\"\").replace(/\\s+/g,\" \").trim(),h=(g,o)=>{if(g.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");for(let s of o)if(s.matches(\":disabled\"))throw new Error(\"codenomad:option-disabled:\"+f(s));if(!g.multiple&&o.length!==1)throw new Error(\"codenomad:single\");g.focus();let w=Array.from(g.options);if(w.some(s=>s.selected!==o.includes(s))){for(let s of w)s.selected=o.includes(s);g.dispatchEvent(new b(\"input\",{bubbles:!0,composed:!0})),g.dispatchEvent(new b(\"change\",{bubbles:!0}))}return Array.from(g.selectedOptions).map(f)},p=(g,o)=>{if(g.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");let w=Array.from(g.options),s=[];for(let y of o){let M=String(y).replace(/\\s+/g,\" \").trim(),L=w.find(N=>f(N)===M)||w.find(N=>N.value===String(y));if(!L)throw new Error(\"codenomad:no-option:\"+M);s.includes(L)||s.push(L)}return h(g,s)},m=t instanceof d\?t.control:t,v=m instanceof i\?m:m&&m.closest(\"select\");if(!v)throw new Error(\"codenomad:not-select\");return p(v,e[0])},focus:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();if(t.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");if((t instanceof u||t instanceof l)&&t.focus(),t.getRootNode().activeElement!==t)throw new Error(\"codenomad:unfocusable\");return null},describe:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t.getAttribute(\"role\")||t.tagName.toLowerCase(),h=(t.getAttribute(\"aria-label\")||t.getAttribute(\"title\")||t.getAttribute(\"placeholder\")||t.labels&&t.labels[0]&&t.labels[0].textContent||t.textContent||\"\").replace(/\\s+/g,\" \").trim().slice(0,80);return f+(h\?\" \"+JSON.stringify(h):\"\")},field:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=m=>m instanceof r||m instanceof a||m instanceof u&&m.isContentEditable,h=t instanceof d\?t.control:t,p=h&&f(h)\?h:t.querySelector('input:not([type=\"hidden\"]), textarea, [contenteditable]:not([contenteditable=\"false\"])');if(!p||!f(p))throw new Error(\"codenomad:not-editable\");return p},prepare:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t,h=e[0];if(f.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");if(f.readOnly)throw new Error(\"codenomad:readonly\");if(f instanceof r&&[\"checkbox\",\"radio\",\"button\",\"submit\",\"reset\",\"file\",\"image\",\"hidden\"].includes(f.type))throw new Error(\"codenomad:not-text\");f.focus();let p=f.getRootNode().activeElement,m=!(f instanceof r||f instanceof a);if(p!==f&&!(m&&p instanceof u&&p.isContentEditable&&p.contains(f)))throw new Error(\"codenomad:unfocusable\");if(f instanceof r&&[\"date\",\"time\",\"datetime-local\",\"month\",\"week\",\"range\",\"color\"].includes(f.type))return\"value\";if(m)S().setBaseAndExtent(f,h\?0:f.childNodes.length,f,f.childNodes.length);else if(h)f.select();else try{f.setSelectionRange(f.value.length,f.value.length)}catch{return\"append\"}return\"insert\"},\"set-value\":function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();if(t.matches(\":disabled\"))throw new Error(\"codenomad:disabled\");if(t.readOnly)throw new Error(\"codenomad:readonly\");let[f,h]=e,p=h\?t.value+f:f;if(!(t.type===\"color\"\?/^#[0-9a-f]{6}$/i.test(p):t.type===\"range\"\?/^-\?(\?:\\d+(\?:\\.\\d+)\?|\\.\\d+)(\?:[eE][+-]\?\\d+)\?$/.test(p):p!==\"\"&&[\"date\",\"time\",\"datetime-local\",\"month\",\"week\",\"number\"].includes(t.type)\?(()=>{let v=n.createElement(\"input\");return v.type=t.type,v.value=p,v.value!==\"\"})():!0))throw new Error(\"codenomad:invalid-value:\"+p);return p===t.value||(Object.getOwnPropertyDescriptor(r.prototype,\"value\").set.call(t,p),t.dispatchEvent(new b(\"input\",{bubbles:!0,composed:!0})),t.dispatchEvent(new b(\"change\",{bubbles:!0}))),null},\"delete-selection\":function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection();return n.execCommand(\"delete\"),null},\"read-value\":function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=t instanceof r||t instanceof a\?t.value:t.innerText||t.textContent||\"\";return t instanceof r&&t.type===\"password\"\?\"\\u2022\".repeat(Math.min(f.length,16)):f.length>200\?f.slice(0,199)+\"\\u2026\":f},receives:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=e[0]&&(e[0].nodeType===c.ELEMENT_NODE\?e[0]:e[0].parentElement);if(!f)return null;let h=m=>{if(m.nodeType===9)try{return m.defaultView&&m.defaultView.frameElement}catch{return null}return m.assignedSlot||m.parentNode||(m.nodeType===11\?m.host:null)};for(let m=f;m;m=h(m))if(m===t||m.nodeType===1&&m.localName===\"label\"&&(m.control===t||m.contains(t)))return null;let p=(f.getAttribute(\"aria-label\")||f.getAttribute(\"title\")||f.innerText||\"\").replace(/\\s+/g,\" \").trim().slice(0,60);return f.tagName.toLowerCase()+(p\?\" \"+JSON.stringify(p):\"\")},contains:function(...e){let t=this.nodeType===1\?this:this.parentElement;if(!t||!t.isConnected)throw new Error(\"codenomad:gone\");let n=t.ownerDocument,{HTMLInputElement:r,HTMLTextAreaElement:a,HTMLLabelElement:d,HTMLSelectElement:i,HTMLElement:u,SVGElement:l,Node:c,Event:b,MouseEvent:E}=n.defaultView,S=()=>n.defaultView.getSelection(),f=String(e[0]).replace(/\\s+/g,\" \").trim().toLowerCase(),h=t,p=m=>String(m||\"\").replace(/\\s+/g,\" \").toLowerCase();if(p(h.innerText||h.textContent).includes(f))return!0;for(let m of h.querySelectorAll(\"[aria-label], [title], [placeholder], input, textarea\"))if([m.getAttribute(\"aria-label\"),m.getAttribute(\"title\"),m.getAttribute(\"placeholder\"),m.value].some(v=>p(v).includes(f)))return!0;return!1}};function O(e,t){if(e.shadowRoot)return e.shadowRoot;let n=i=>{try{let u=(l,c,b)=>Object.getOwnPropertyDescriptor(l,c).get.call(b);return u(ShadowRoot.prototype,\"host\",i)!==e||u(ShadowRoot.prototype,\"mode\",i)!==\"closed\"||u(Node.prototype,\"ownerDocument\",i)!==e.ownerDocument\?void 0:Node.prototype.getRootNode.call(i)}catch{return}},r=n(t.get(e)\?.deref());if(r)return r;if(e.getAttribute(\"data-codenomad-shadow-boundary\")!==\"closed\")return;let a,d=i=>{try{let u=PointerEvent.prototype.getPredictedEvents.call(i);if(u.length!==1)return;let l=Object.getOwnPropertyDescriptor(MouseEvent.prototype,\"relatedTarget\").get.call(u[0]),c=n(l);c&&(a=c)}catch{}};e.addEventListener(\"__codenomad_shadow_v1\",d);try{e.dispatchEvent(new Event(\"__codenomad_request_shadow_v1\"))}finally{e.removeEventListener(\"__codenomad_shadow_v1\",d)}return a&&t.set(e,new WeakRef(a)),a}var Pe=e=>e.nodeType===1\?e:e.parentElement;function _(e){return e===document\?void 0:e.defaultView\?.frameElement\?\?void 0}var I=class extends Error{},Ot=e=>e.assignedSlot\?\?e.parentElement\?\?e.getRootNode().host\?\?null;function _e(e){let t=new DOMMatrix;for(let n=e;n;n=Ot(n)){let r=n.ownerDocument.defaultView.getComputedStyle(n),a=new DOMMatrix(r.transform===\"none\"\?void 0:r.transform);if(!a.is2D||r.perspective!==\"none\"||[r.rotate,r.scale,r.translate,r.offsetPath].some(i=>i&&i!==\"none\"))throw new I(\"WebKit aiming requires an invertible 2D CSS transform; perspective, independent transforms and motion paths are unsupported\");let d=Number(r.getPropertyValue(\"zoom\"))||1;t=a.scale(d).multiply(t)}if(!Number.isFinite(t.a*t.d-t.b*t.c)||Math.abs(t.a*t.d-t.b*t.c)<1e-10)throw new I(\"WebKit aiming requires an invertible 2D CSS transform\");return t}function oe(e){let t=_e(e),n=e.ownerDocument.defaultView.getComputedStyle(e),r=b=>parseFloat(n.getPropertyValue(b))||0,a=r(\"width\")+(n.boxSizing===\"border-box\"\?0:r(\"padding-left\")+r(\"padding-right\")+r(\"border-left-width\")+r(\"border-right-width\")),d=r(\"height\")+(n.boxSizing===\"border-box\"\?0:r(\"padding-top\")+r(\"padding-bottom\")+r(\"border-top-width\")+r(\"border-bottom-width\")),i=[[0,0],[a,0],[a,d],[0,d]].map(([b,E])=>t.transformPoint({x:b,y:E})),u=e.getBoundingClientRect(),l=i.map(b=>b.x),c=i.map(b=>b.y);if(Math.abs(Math.max(...l)-Math.min(...l)-u.width)>.5||Math.abs(Math.max(...c)-Math.min(...c)-u.height)>.5)throw new I(\"WebKit cannot map this frame's transformed content box exactly\");return t.e+=u.left-Math.min(...l),t.f+=u.top-Math.min(...c),t.translate(r(\"border-left-width\")+r(\"padding-left\"),r(\"border-top-width\")+r(\"padding-top\"))}function It(e,t,n){for(let[r,a,d]of[[\"x\",0,1],[\"x\",t,-1],[\"y\",0,1],[\"y\",n,-1]]){let i=[];for(let u=0;u=0,E=(c[r]-a)*d>=0;if(b&&i.push(l),b!==E){let S=(a-l[r])/(c[r]-l[r]);i.push({x:l.x+S*(c.x-l.x),y:l.y+S*(c.y-l.y)})}}e=i}return e}function ie(e){_e(e);for(let t=e.ownerDocument,n=_(t);n;n=_(t))oe(n),t=n.ownerDocument}function je(e){let t=Pe(e);return t\?(ie(t),Array.from(t.getClientRects()).filter(n=>n.width>0&&n.height>0).flatMap(n=>{let r=[{x:n.left,y:n.top},{x:n.right,y:n.top},{x:n.right,y:n.bottom},{x:n.left,y:n.bottom}],a=t.ownerDocument;for(let E=_(a);E;E=_(a)){if(r=It(r,a.defaultView.innerWidth,a.defaultView.innerHeight),!r.length)return[];let S=oe(E);r=r.map(f=>S.transformPoint(f)),a=E.ownerDocument}let d=r.map(E=>E.x),i=r.map(E=>E.y),u=Math.min(...d),l=Math.max(...d),c=Math.min(...i),b=Math.max(...i);return[[u,c,l,c,l,b,u,b]]})):[]}function We(e){let t=Pe(e);if(t){ie(t),t.scrollIntoView({block:\"center\",inline:\"center\",behavior:\"instant\"});for(let n=t.ownerDocument,r=_(n);r;r=_(n))r.scrollIntoView({block:\"nearest\",inline:\"nearest\",behavior:\"instant\"}),n=r.ownerDocument}}function $e(e,t,n){let r=document,a=null,d=new Set;for(;;){let i=r.elementFromPoint(e,t);if(!i||d.has(i))break;ie(i),a=i,d.add(i);let u=O(i,n);if(u){r=u;continue}if(i.localName===\"iframe\"||i.localName===\"frame\"){let l=null;try{l=i.contentDocument}catch{}if(l){let c=oe(i).inverse().transformPoint({x:e,y:t});e=c.x,t=c.y,r=l;continue}}break}return a\?\?void 0}function Ge(e){let t=document.activeElement,n=new Set;for(;t&&!n.has(t);){n.add(t);let r=O(t,e)\?.activeElement\?\?t.contentDocument\?.activeElement;if(!r||r===t)break;t=r}return t}var Pt=2e4,ae=\"__codenomadWebkitReadV1\",Ke=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,le=globalThis;function ze(){return{document,token:Ke(),next:0,ids:new WeakMap,nodes:new Map,observers:new Set,observed:new WeakSet,roots:new WeakMap,hides:new WeakMap}}function Be(e){if(e.nodeType===9)try{return e.defaultView\?.frameElement\?\?null}catch{return null}return e.assignedSlot\?\?e.parentNode\?\?(e.nodeType===11\?e.host:null)}function z(e){let t=e.nodeType===9\?e:e.ownerDocument;if(!t||e.nodeType!==9&&!e.isConnected)return!1;if(t===document)return!0;try{let n=t.defaultView\?.frameElement;return!!n&&n.contentDocument===t&&z(n)}catch{return!1}}function j(e,t){let n=e.ids.get(t);n!==void 0&&(e.nodes.delete(n),e.ids.delete(t));for(let r of Array.from(t.childNodes))j(e,r);if(t.nodeType===1){let r=O(t,e.roots);r&&j(e,r)}if(t.nodeType===1&&[\"iframe\",\"frame\"].includes(t.localName))try{let r=t.contentDocument;r&&j(e,r)}catch{}}function Je(e,t){let n=e.hides.get(t);n||(n=()=>{t===e.document\?e.token=Ke():j(e,t)},e.hides.set(t,n)),t.defaultView\?.addEventListener(\"pagehide\",n)}function X(e,t){if(t.nodeType===9&&Je(e,t),e.observed.has(t))return;e.observed.add(t);let n=new MutationObserver(r=>Xe(e,r));n.observe(t,{childList:!0,subtree:!0}),e.observers.add({observer:n,root:new WeakRef(t)})}function Xe(e,t){for(let n of t)for(let r of Array.from(n.removedNodes)){if(r.nodeType===1&&r.localName===\"html\"&&n.target===document){for(let{observer:a}of e.observers)a.disconnect();Object.assign(e,ze(),{hides:e.hides}),X(e,document);return}j(e,r),r.nodeType===1&&r.localName===\"html\"&&n.target.nodeType===9&&j(e,n.target)}}function _t(e){for(let t of e.observers){Xe(e,t.observer.takeRecords());let n=t.root.deref();n\?.nodeType===9&&z(n)&&Je(e,n),(!n||!z(n))&&(t.observer.disconnect(),e.observers.delete(t),n&&e.observed.delete(n))}for(let[t,n]of e.nodes){let r=n.deref();(!r||!z(r))&&(r&&e.ids.delete(r),e.nodes.delete(t))}}function ue(e,t){let n=e.ids.get(t);if(n!==void 0)return n;if(e.nodes.size>=Pt)throw new Error(\"WebKit semantic identity table exceeds 20000 nodes\");let r=++e.next;return e.ids.set(t,r),e.nodes.set(r,new WeakRef(t)),r}function K(e,t){let n=e.nodes.get(t)\?.deref();return n&&z(n)&&e.ids.get(n)===t\?n:void 0}function se(e,t){return`${e.token}:${ue(e,t)}`}function qe(e,t){let n=`${e.token}:`;return t.startsWith(n)\?K(e,Number(t.slice(n.length))):void 0}function Ye(e){if(Ie(e))return!0;for(let t=e;t;t=Be(t)){if(t.nodeType!==1)continue;let n=t;if(n.ownerDocument.defaultView.getComputedStyle(n).display===\"none\"||n.hasAttribute(\"inert\")||n.getAttribute(\"aria-hidden\")===\"true\")return!0;if(n.localName===\"details\"&&!n.hasAttribute(\"open\")){let r=Array.from(n.children).find(a=>a.localName===\"summary\");if(e!==n&&(!r||e!==r&&!r.contains(e)))return!0}}return!1}var Y=e=>e.replace(/\\s+/g,\" \").trim();function Q(e,t){if(e.nodeType===3)return e.textContent\?\?\"\";if(e.nodeType===1&&([\"script\",\"style\",\"template\",\"noscript\",\"head\"].includes(e.localName)||Ye(e)))return\" \";let n=e.nodeType===1\?e:void 0;if(n\?.localName===\"br\")return\" \";if(n&&[\"iframe\",\"frame\"].includes(n.localName))try{let i=n.contentDocument\?.body;return i\?` ${Q(i,t)} `:\" \"}catch{return\" \"}let r=n\?.localName===\"slot\"\?n.assignedNodes({flatten:!0}):[],a=Array.from(r.length\?r:(n&&O(n,t.roots))\?.childNodes\?\?e.childNodes).map(i=>Q(i,t)).join(\"\"),d=n\?.ownerDocument.defaultView.getComputedStyle(n).display\?\?\"\";return/^(block|flow-root|flex|grid|table|list-item)/.test(d)\?` ${a} `:a}function jt(e){let t=e.localName,n=e.type;if(e.getAttribute(\"role\")\?.trim())return V(e)\?\?\"generic\";if(t===\"input\"){if(n===\"password\")return\"textbox\";if(n===\"date\"||n===\"month\"||n===\"week\")return\"Date\";if(n===\"datetime-local\")return\"DateTime\";if(n===\"time\")return\"InputTime\";if(n===\"color\")return\"ColorWell\"}if(t===\"summary\")return\"DisclosureTriangle\";if(t===\"iframe\"||t===\"frame\")return\"Iframe\";let r=V(e)\?\?\"generic\";return[\"html\",\"body\",\"label\",\"legend\"].includes(t)&&(r=t===\"label\"\?\"LabelText\":\"generic\"),r===\"region\"&&!J(e)&&(r=\"generic\"),(t===\"header\"||t===\"footer\")&&e.parentElement\?.closest(\"article,aside,main,nav,section\")&&(r=\"generic\"),r}function Wt(e){for(let t=e;t;t=Be(t))if(t.nodeType===1&&t.getAttribute(\"aria-disabled\")===\"true\")return!0;return!1}function Fe(e){let t=[],n=new Set,r=(i,u)=>{let l=ue(e,i),c={id:String(l),node:l,...u\?{parent:u}:{},children:[]};return t.push(c),c},a=(i,u,l)=>{let c=`boundary-${i.id}`;i.children.push(c),t.push({id:c,parent:i.id,role:\"note\",name:u,description:l})},d=(i,u)=>{if(n.has(i))return;if(n.add(i),i.nodeType===3){if(!Y(i.textContent\?\?\"\"))return;let s=r(i,u);return s.role=\"StaticText\",s.name=i.textContent\?\?\"\",s}if(i.nodeType===9){let s=i;X(e,s);let y=r(i,u);if(y.role=\"RootWebArea\",y.name=s.title,s.body){let M=d(s.body,y.id);M&&y.children.push(M.id)}return y}if(i.nodeType!==1)return;let l=i;if([\"script\",\"style\",\"template\",\"noscript\",\"head\"].includes(l.localName)||Ye(l))return;let c=r(i,u),b=jt(l);c.role=b;let E=J(l),S=O(l,e.roots);!E&&S&&[\"button\",\"link\",\"checkbox\",\"tab\",\"heading\"].includes(b)&&(E=Y(Q(l,e))),c.name=E,c.description=ne(l);let f=[],h=(s,y)=>f.push({name:s,value:y}),p=s=>l.getAttribute(`aria-${s}`),m=l,v=l.localName;[\"checkbox\",\"radio\",\"switch\",\"menuitemcheckbox\",\"menuitemradio\"].includes(b)&&h(\"checked\",p(\"checked\")\?\?(m.indeterminate\?\"mixed\":!!m.checked)),p(\"pressed\")!==null&&h(\"pressed\",p(\"pressed\")),p(\"expanded\")!==null\?h(\"expanded\",p(\"expanded\")===\"true\"):v===\"select\"&&!l.multiple&&l.size<=1\?h(\"expanded\",!1):v===\"summary\"&&l.parentElement\?.localName===\"details\"&&h(\"expanded\",l.parentElement.hasAttribute(\"open\")),(p(\"selected\")!==null||v===\"option\")&&h(\"selected\",p(\"selected\")!==null\?p(\"selected\")===\"true\":l.selected),(l.matches(\":disabled\")||Wt(l))&&h(\"disabled\",!0),(m.required||p(\"required\")===\"true\")&&h(\"required\",!0),(m.readOnly||p(\"readonly\")===\"true\")&&h(\"readonly\",!0),(v===\"select\"&&l.multiple||p(\"multiselectable\")===\"true\")&&h(\"multiselectable\",!0),l.tabIndex>=0&&h(\"focusable\",!0);for(let s of[\"busy\",\"modal\"])p(s)===\"true\"&&h(s,!0);let g=l.getRootNode();(l.ownerDocument.activeElement===l||g.nodeType===11&&g.activeElement===l)&&h(\"focused\",!0),p(\"invalid\")&&p(\"invalid\")!==\"false\"\?h(\"invalid\",p(\"invalid\")):p(\"invalid\")===null&&m.validity&&!m.validity.valid&&h(\"invalid\",\"true\"),b===\"heading\"&&h(\"level\",Number(p(\"level\")\?\?/^h([1-6])$/.exec(v)\?.[1]\?\?2)),v===\"a\"&&l.hasAttribute(\"href\")&&h(\"url\",l.href);let o=l.isContentEditable;if(o&&h(\"editable\",\"richtext\"),v===\"input\"&&![\"checkbox\",\"radio\",\"button\",\"submit\",\"reset\",\"image\",\"file\"].includes(m.type)||v===\"textarea\"\?c.value=m.type===\"password\"\?\"\\u2022\".repeat(Math.min(m.value.length,16)):m.value:v===\"select\"&&!l.multiple\?c.value=Array.from(l.selectedOptions).map(s=>s.label||s.textContent||\"\").join(\" \"):o\?c.value=l.innerText:(p(\"valuetext\")!==null||p(\"valuenow\")!==null)&&(c.value=p(\"valuetext\")\?\?p(\"valuenow\")),c.properties=f,v===\"iframe\"||v===\"frame\"){try{let s=l.contentDocument;if(!s)throw new Error(\"cross-origin\");let y=d(s,c.id);y&&c.children.push(y.id)}catch{delete c.node,a(c,\"Cross-origin frame (unavailable)\",\"Frame contents cannot be traversed\")}return c}if(!S&&l.getAttribute(\"data-codenomad-shadow-boundary\")===\"closed\")return a(c,\"Closed shadow root (unavailable)\",\"Closed shadow capture could not be validated\"),c;S&&X(e,S);let w=v===\"slot\"&&l.assignedNodes({flatten:!0}).length\?l.assignedNodes({flatten:!0}):Array.from(S\?.childNodes\?\?l.childNodes);for(let s of w){let y=d(s,c.id);y&&c.children.push(y.id)}return c};return d(document),t}function $t(e){le[ae]\?.document!==document&&(le[ae]=ze());let t=le[ae];X(t,document),_t(t);let n;try{switch(e.op){case\"tree\":n={nodes:Fe(t)};break;case\"checkpoint\":n={};break;case\"release-handles\":n={};break;case\"resolve\":{let r=K(t,e.node);n=r\?{handle:se(t,r)}:{};break}case\"viewport\":n={width:innerWidth,height:innerHeight};break;case\"geometry\":{let r=K(t,e.node);n=r\?{quads:je(r)}:{};break}case\"scroll-into-view\":{let r=K(t,e.node);r&&We(r),n={};break}case\"hit-test\":{let r=$e(e.x,e.y,t.roots);n=r\?{node:ue(t,r)}:{};break}case\"call\":{if(e.function===\"document-root\"||e.function===\"active-element\"){let a=e.function===\"document-root\"\?document.documentElement:Ge(t.roots);n=a\?{handle:se(t,a)}:{};break}if(e.function===\"input-acceptance\"){n={value:{inputDelayMs:0}};break}if(!Object.hasOwn(re,e.function)){n={error:{code:\"unsupported\",driver:\"webkit\",operation:`call:${e.function}`}};break}let r=e.handle\?qe(t,e.handle):void 0;if(!r){n={exception:\"codenomad:gone\"};break}if(e.function===\"contains\"){let a=Y(String(e.args[0])).toLowerCase();n={value:Fe(t).some(d=>{let i=d.node\?K(t,d.node):void 0,u=i\?.nodeType===1\?i:void 0,l=u\?[\"aria-label\",\"title\",\"placeholder\"].map(b=>u.getAttribute(b)):[];return u&&[\"input\",\"textarea\"].includes(u.localName)&&l.push(u.value),[i\?.nodeType===9&&i.body\?Q(i.body,t):void 0,d.name,d.value,d.description,...l].some(b=>typeof b==\"string\"&&Y(b).toLowerCase().includes(a))})};break}try{let a=e.args.map(i=>i&&typeof i==\"object\"&&Object.hasOwn(i,\"handle\")\?qe(t,i.handle):i),d=re[e.function].call(r,...a);n=e.function===\"field\"\?{handle:se(t,d)}:{value:d}}catch(a){n={exception:String(a)}}break}default:n={error:{code:\"unsupported\",driver:\"webkit\",operation:e.op}}}}catch(r){if(!(r instanceof I))throw r;n={error:{code:\"unsupported\",driver:\"webkit\",operation:`${e.op}: ${r.message}`}}}return{document:t.token,result:n}}return nt(Gt);})();\n\nreturn JSON.stringify(__codenomadReadModule.read(JSON.parse(request)));\n"; +static const char CN_PAGE_HOOK[] = "(() => {\n const original = Element.prototype.attachShadow;\n const apply = Reflect.apply;\n const setAttribute = Element.prototype.setAttribute;\n const roots = new WeakMap();\n const Reply = PointerEvent;\n const dispatch = EventTarget.prototype.dispatchEvent;\n const listen = EventTarget.prototype.addEventListener;\n const reply = function (host) {\n const root = roots.get(host);\n if (root) {\n // The nested carrier is never dispatched, preserving its native Node\n // reference without shadow retargeting or cross-world JS serialization.\n const carrier = new Reply(\"__codenomad_reference_v1\", {relatedTarget:root});\n apply(dispatch,host,[new Reply(\"__codenomad_shadow_v1\",{predictedEvents:[carrier]})]);\n }\n };\n const wrapped = function (options) {\n const root = apply(original, this, [options]);\n if (root.mode === \"closed\") {\n const host = this;\n roots.set(host, root);\n apply(listen,host,[\"__codenomad_request_shadow_v1\",()=>reply(host)]);\n apply(setAttribute, this, [\"data-codenomad-shadow-boundary\", \"closed\"]);\n }\n return root;\n };\n Object.defineProperty(Element.prototype, \"attachShadow\", { ...Object.getOwnPropertyDescriptor(Element.prototype, \"attachShadow\"), value: wrapped });\n})()"; diff --git a/packages/tauri-app/src-tauri/src/embedded_view/windows.rs b/packages/tauri-app/src-tauri/src/embedded_view/windows.rs new file mode 100644 index 0000000000..f739834702 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/windows.rs @@ -0,0 +1,165 @@ +use std::sync::mpsc; +use std::time::Duration; + +pub(super) fn request_close(view: &tauri::Webview) -> Result<(), String> { + use tauri::Manager; + use webview2_com::{CallDevToolsProtocolMethodCompletedHandler, CoTaskMemPWSTR}; + let policy = view + .app_handle() + .try_state::() + .ok_or("Missing browser registry")? + .inner() + .clone(); + let label = view.label().to_string(); + let token = policy.token(&label).ok_or("Expired browser view")?; + view.with_webview(move |native| { + if !policy.current(&label, token) { + return; + } + // Page.close runs beforeunload and requests native window closure without + // evaluating the site's replaceable window.close. Never wait on the UI thread. + let result = (|| unsafe { + let core = native.controller().CoreWebView2()?; + let method = CoTaskMemPWSTR::from("Page.close"); + let params = CoTaskMemPWSTR::from("{}"); + let callback = + CallDevToolsProtocolMethodCompletedHandler::create(Box::new(|result, _| { + if let Err(error) = result { + eprintln!("[browser-close] {error}"); + } + Ok(()) + })); + core.CallDevToolsProtocolMethod( + *method.as_ref().as_pcwstr(), + *params.as_ref().as_pcwstr(), + &callback, + ) + })(); + if let Err(error) = result { + eprintln!("[browser-close] {error}"); + } + }) + .map_err(|error| error.to_string()) +} + +pub(super) fn install(webview: &tauri::Webview) -> Result<(), String> { + use tauri::Manager; + use webview2_com::{Microsoft::Web::WebView2::Win32::*, PermissionRequestedEventHandler}; + crate::windows_browser_accelerators::bind(webview); + let (sender, receiver) = mpsc::sync_channel(1); + let view = webview.clone(); + let policy = webview + .app_handle() + .try_state::() + .ok_or("Missing browser registry")? + .inner() + .clone(); + let token = policy + .token(webview.label()) + .ok_or("Expired browser view")?; + webview + .with_webview(move |platform| { + let result = (|| { + let core = unsafe { platform.controller().CoreWebView2() }?; + let fullscreen_view = view.clone(); + let fullscreen_policy = policy.clone(); + let permission = + PermissionRequestedEventHandler::create(Box::new(move |_, args| { + if let Some(args) = args { + unsafe { + if !policy.current(view.label(), token) { + args.SetState(COREWEBVIEW2_PERMISSION_STATE_DENY)?; + return Ok(()); + } + let mut kind = COREWEBVIEW2_PERMISSION_KIND::default(); + args.PermissionKind(&mut kind)?; + let state = permission_state(kind); + if state == COREWEBVIEW2_PERMISSION_STATE_DENY + && !matches!(kind.0, 1..=4) + { + super::browser::unknown_permission( + &view, + &format!("WebView2:{}", kind.0), + ); + } + args.SetState(state)?; + } + } + Ok(()) + })); + let mut event_token = 0; + unsafe { core.add_PermissionRequested(&permission, &mut event_token)? }; + unsafe { + core.Settings()?.SetIsStatusBarEnabled(true)?; + } + unsafe { + core.add_ContainsFullScreenElementChanged( + &webview2_com::ContainsFullScreenElementChangedEventHandler::create( + Box::new(move |sender, _| { + if !fullscreen_policy.current(fullscreen_view.label(), token) { + return Ok(()); + } + if let Some(core) = sender { + use tauri::Manager; + let mut active = Default::default(); + core.ContainsFullScreenElement(&mut active)?; + if let Some(views) = fullscreen_view + .app_handle() + .try_state::() + { + if let Err(error) = views.set_fullscreen( + fullscreen_view.app_handle(), + fullscreen_view.label(), + active.as_bool(), + ) { + eprintln!("[browser-fullscreen] {error}"); + } + } + } + Ok(()) + }), + ), + &mut 0, + )?; + } + Ok::<(), webview2_com::Error>(()) + })(); + let _ = sender.send(result.map_err(|error| error.to_string())); + }) + .map_err(|error| error.to_string())?; + receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Timed out configuring WebView2 browser security".to_string())? +} + +fn permission_state( + kind: webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_PERMISSION_KIND, +) -> webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_PERMISSION_STATE { + use webview2_com::Microsoft::Web::WebView2::Win32::*; + // Current documented values: sensors through PersistentStorage (13). + // https://learn.microsoft.com/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2permissionkind + if matches!(kind.0, 5..=13) { + COREWEBVIEW2_PERMISSION_STATE_DEFAULT + } else { + COREWEBVIEW2_PERMISSION_STATE_DENY + } +} + +#[cfg(test)] +mod tests { + use super::*; + use webview2_com::Microsoft::Web::WebView2::Win32::*; + #[test] + fn only_classified_non_forbidden_permissions_reach_browser_consent() { + for kind in -1..=30 { + assert_eq!( + permission_state(COREWEBVIEW2_PERMISSION_KIND(kind)), + if (5..=13).contains(&kind) { + COREWEBVIEW2_PERMISSION_STATE_DEFAULT + } else { + COREWEBVIEW2_PERMISSION_STATE_DENY + } + ); + } + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/zoom.h b/packages/tauri-app/src-tauri/src/embedded_view/zoom.h new file mode 100644 index 0000000000..1d3bb0ba10 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/zoom.h @@ -0,0 +1,11 @@ +#pragma once +#include + +static inline double cn_preview_next_zoom(double current, int action) { + if (!isfinite(current) || current <= 0) current = 1; + double next = action == 0 ? 1 : current + action * 0.2; + return round(fmin(5, fmax(0.25, next)) * 1000000) / 1000000; +} +void cn_preview_zoom_install(void *view); +int cn_preview_zoom_focused(void *view, int action); +void cn_preview_zoom_base(void *view, double base); diff --git a/packages/tauri-app/src-tauri/src/embedded_view/zoom.rs b/packages/tauri-app/src-tauri/src/embedded_view/zoom.rs new file mode 100644 index 0000000000..49bd36bbd1 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/zoom.rs @@ -0,0 +1,87 @@ +//! Native focused-preview zoom. Guests receive no application scripts or commands. +use super::*; + +fn action(command: &str) -> Option { + match command { + "zoom_in" => Some(1), + "zoom_out" => Some(-1), + "reset_zoom" => Some(0), + _ => None, + } +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +extern "C" { + fn cn_preview_zoom_install(view: *mut std::ffi::c_void); + fn cn_preview_zoom_focused(view: *mut std::ffi::c_void, action: i32) -> i32; +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +pub(super) fn install(view: &tauri::Webview) -> Result<(), String> { + if !view.label().starts_with("browser-") { + return Ok(()); + } + super::mobile::native(view, |ptr| { + unsafe { cn_preview_zoom_install(ptr) }; + Ok(()) + }) +} + +/// Called on the menu's UI thread, before falling back to primary-window zoom. +pub(crate) fn focused(app: &AppHandle, command: &str) -> bool { + let Some(action) = action(command) else { + return false; + }; + #[cfg(any(target_os = "linux", target_os = "macos"))] + { + let Some(policy) = app.try_state::() else { + return false; + }; + let candidates = policy + .0 + .lock() + .map(|inner| { + inner + .records + .iter() + .filter(|(label, record)| label.starts_with("browser-") && !record.preparing) + .map(|(label, record)| (label.clone(), record.token)) + .collect::>() + }) + .unwrap_or_default(); + for (label, token) in candidates { + let Some(view) = app.get_webview(&label) else { + continue; + }; + let guard = policy.inner().clone(); + match super::mobile::native(&view, move |ptr| { + Ok(guard.current(&label, token) + && unsafe { cn_preview_zoom_focused(ptr, action) } != 0) + }) { + Ok(true) => return true, + Ok(false) => {} + Err(error) => { + eprintln!("[browser-zoom] {error}"); + return true; + } + } + } + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + let _ = (app, action); + false +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn native_zoom_accepts_only_the_three_menu_actions() { + assert_eq!(action("zoom_in"), Some(1)); + assert_eq!(action("zoom_out"), Some(-1)); + assert_eq!(action("reset_zoom"), Some(0)); + for other in ["zoom", "set_zoom", "reload", "", "100"] { + assert_eq!(action(other), None); + } + } +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/zoom_linux.c b/packages/tauri-app/src-tauri/src/embedded_view/zoom_linux.c new file mode 100644 index 0000000000..a5fedaff72 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/zoom_linux.c @@ -0,0 +1,56 @@ +#include +#include +#include "zoom.h" + +typedef struct { double base, user; gboolean installed; } Zoom; +static Zoom *state(WebKitWebView *view) { + Zoom *zoom = g_object_get_data(G_OBJECT(view), "codenomad-preview-zoom"); + if (!zoom) { + zoom = g_new0(Zoom, 1); + zoom->base = webkit_web_view_get_zoom_level(view); zoom->user = 1; + g_object_set_data_full(G_OBJECT(view), "codenomad-preview-zoom", zoom, g_free); + } + return zoom; +} +static gboolean focused(GtkWidget *view) { + GtkWidget *window = gtk_widget_get_toplevel(view); + return gtk_widget_get_mapped(view) && GTK_IS_WINDOW(window) + && gtk_window_is_active(GTK_WINDOW(window)) + && gtk_window_get_focus(GTK_WINDOW(window)) == view; +} +int cn_preview_zoom_focused(void *opaque, int action) { + GtkWidget *view = GTK_WIDGET(opaque); + if (action < -1 || action > 1 || !focused(view)) return 0; + Zoom *zoom = state(WEBKIT_WEB_VIEW(view)); + zoom->user = cn_preview_next_zoom(zoom->user, action); + webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(view), zoom->base * zoom->user); + return 1; +} +static gboolean key_press(GtkWidget *view, GdkEventKey *event, gpointer unused) { + (void)unused; + GdkModifierType modifiers = event->state & gtk_accelerator_get_default_mod_mask(); + modifiers &= ~GDK_SHIFT_MASK; + if (modifiers != GDK_CONTROL_MASK) return FALSE; + int action; + switch (event->keyval) { + case GDK_KEY_plus: case GDK_KEY_equal: case GDK_KEY_KP_Add: action = 1; break; + case GDK_KEY_minus: case GDK_KEY_KP_Subtract: action = -1; break; + case GDK_KEY_0: case GDK_KEY_KP_0: action = 0; break; + default: return FALSE; + } + return cn_preview_zoom_focused(view, action); +} +void cn_preview_zoom_install(void *opaque) { + WebKitWebView *view = WEBKIT_WEB_VIEW(opaque); + Zoom *zoom = state(view); + if (!zoom->installed) { + zoom->installed = TRUE; + g_signal_connect(view, "key-press-event", G_CALLBACK(key_press), NULL); + } +} +void cn_preview_zoom_base(void *opaque, double base) { + WebKitWebView *view = WEBKIT_WEB_VIEW(opaque); + Zoom *zoom = state(view); + zoom->base = base; + webkit_web_view_set_zoom_level(view, base * zoom->user); +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view/zoom_macos.m b/packages/tauri-app/src-tauri/src/embedded_view/zoom_macos.m new file mode 100644 index 0000000000..3ca38edd7e --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view/zoom_macos.m @@ -0,0 +1,60 @@ +#import +#import +#import +#include "zoom.h" + +@interface CNPreviewZoom : NSObject +@property double base; +@property double user; +@property(strong) id monitor; +@end +@implementation CNPreviewZoom +- (void)dealloc { if (_monitor) [NSEvent removeMonitor:_monitor]; } +@end +static char zoomKey; +static CNPreviewZoom *state(WKWebView *view) { + CNPreviewZoom *zoom = objc_getAssociatedObject(view, &zoomKey); + if (!zoom) { + zoom = [CNPreviewZoom new]; zoom.base = view.pageZoom; zoom.user = 1; + objc_setAssociatedObject(view, &zoomKey, zoom, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return zoom; +} +static BOOL focused(WKWebView *view) { + NSResponder *responder = view.window.firstResponder; + return view.window.isKeyWindow && !view.isHiddenOrHasHiddenAncestor + && [responder isKindOfClass:NSView.class] + && [(NSView *)responder isDescendantOf:view]; +} +int cn_preview_zoom_focused(void *opaque, int action) { + WKWebView *view = (__bridge WKWebView *)opaque; + if (action < -1 || action > 1 || !focused(view)) return 0; + CNPreviewZoom *zoom = state(view); + zoom.user = cn_preview_next_zoom(zoom.user, action); + view.pageZoom = zoom.base * zoom.user; + return 1; +} +void cn_preview_zoom_install(void *opaque) { + WKWebView *view = (__bridge WKWebView *)opaque; + CNPreviewZoom *zoom = state(view); + if (zoom.monitor) return; + __weak WKWebView *weakView = view; + zoom.monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *(NSEvent *event) { + NSEventModifierFlags flags = event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagControl | NSEventModifierFlagOption); + if (flags != NSEventModifierFlagCommand) return event; + NSString *key = event.charactersIgnoringModifiers; + int action; + if ([key isEqualToString:@"+"] || [key isEqualToString:@"="]) action = 1; + else if ([key isEqualToString:@"-"]) action = -1; + else if ([key isEqualToString:@"0"]) action = 0; + else return event; + WKWebView *target = weakView; + return target && cn_preview_zoom_focused((__bridge void *)target, action) ? nil : event; + }]; +} +void cn_preview_zoom_base(void *opaque, double base) { + WKWebView *view = (__bridge WKWebView *)opaque; + CNPreviewZoom *zoom = state(view); + zoom.base = base; + view.pageZoom = base * zoom.user; +} diff --git a/packages/tauri-app/src-tauri/src/embedded_view_tests.rs b/packages/tauri-app/src-tauri/src/embedded_view_tests.rs new file mode 100644 index 0000000000..d9e74d756b --- /dev/null +++ b/packages/tauri-app/src-tauri/src/embedded_view_tests.rs @@ -0,0 +1,426 @@ +use super::*; +use tauri::test::{mock_builder, mock_context, noop_assets}; +use tauri::{WebviewUrl, WebviewWindowBuilder}; + +const OWNER: &str = "local-11111111-1111-4111-8111-111111111111"; +const OTHER: &str = "local-22222222-2222-4222-8222-222222222222"; + +#[test] +fn child_policy_is_registered_before_creation_and_fails_closed() { + let views = EmbeddedViews::default(); + let http = "https://example.com".parse().unwrap(); + let blank = "about:blank".parse().unwrap(); + assert_eq!( + views.navigation_allowed("browser-missing", &http), + Some(false) + ); + assert_eq!(views.navigation_allowed(OWNER, &http), None); + assert!(views.reserve("remote-guest", "browser-child").is_err()); + let remote = views.reserve(OWNER, "embedded-remote-child").unwrap(); + assert_eq!( + views.navigation_allowed("embedded-remote-child", &http), + Some(true) + ); + views.remove_exact("embedded-remote-child", &remote); + assert_eq!( + views.navigation_allowed("embedded-remote-child", &http), + Some(false) + ); + let record = views.reserve(OWNER, "browser-child").unwrap(); + assert!(views.owned(OTHER, "browser-child").is_err()); + assert!(views.owned(OWNER, "browser-missing").is_err()); + assert_eq!( + views.navigation_allowed("browser-child", &blank), + Some(true) + ); + assert_eq!(views.navigation_allowed("browser-child", &http), Some(true)); + views.finish_creation("browser-child", &record).unwrap(); + assert_eq!( + views.navigation_allowed("browser-child", &blank), + Some(true) + ); + for raw in [ + "file:///secret", + "https://user:pass@example.com", + "javascript:alert(1)", + "data:text/html,test", + ] { + assert_eq!( + views.navigation_allowed("browser-child", &raw.parse().unwrap()), + Some(false) + ); + } +} + +#[test] +fn failed_creation_rolls_back_only_its_exact_reservation() { + let views = EmbeddedViews::default(); + let failed = views.reserve(OWNER, "browser-child").unwrap(); + assert!(views.remove_exact("browser-child", &failed)); + assert_eq!( + views.navigation_allowed("browser-child", &"https://example.com".parse().unwrap()), + Some(false) + ); + let replacement = views.reserve(OWNER, "browser-child").unwrap(); + let stale = views.clone(); + let worker = std::thread::spawn(move || { + assert!(!stale.remove_exact("browser-child", &failed)); + assert!(stale.finish_creation("browser-child", &failed).is_err()); + }); + worker.join().unwrap(); + views + .finish_creation("browser-child", &replacement) + .unwrap(); + assert_eq!( + views.owned(OWNER, "browser-child").unwrap().token, + replacement.token + ); +} + +#[test] +fn native_creation_installs_protections_before_return_and_rolls_back_failure() { + let app = mock_builder().build(mock_context(noop_assets())).unwrap(); + app.manage(StorageIdentity::new( + "dev".into(), + "/home/me/config.yaml".into(), + )); + WebviewWindowBuilder::new(&app, OWNER, WebviewUrl::default()) + .build() + .unwrap(); + let owner = app.get_window(OWNER).unwrap(); + let views = EmbeddedViews::default(); + app.manage(views.clone()); + let bounds = Bounds { + x: 10, + y: 20, + width: 300, + height: 200, + }; + let result = views.create_with( + &owner, + "browser-failed", + PathBuf::new(), + bounds, + |_, _| {}, + |_| true, + |webview| { + assert!(views.owned(OWNER, webview.label()).is_ok()); + assert_eq!( + views.navigation_allowed(webview.label(), &"about:blank".parse().unwrap()), + Some(true) + ); + Err("mandatory protection failed".into()) + }, + ); + assert_eq!(result.err().unwrap(), "mandatory protection failed"); + assert!(views.owned(OWNER, "browser-failed").is_err()); + assert!(app.get_webview("browser-failed").is_none()); + let child = views + .create_with( + &owner, + "browser-ready", + PathBuf::new(), + bounds, + |_, _| {}, + |_| true, + |_| Ok(()), + ) + .unwrap(); + assert!(crate::intercept_navigation( + &child, + &"https://example.com".parse().unwrap() + )); + assert!(!crate::intercept_navigation( + &child, + &"file:///secret".parse().unwrap() + )); + assert_eq!( + views.navigation_allowed(child.label(), &"about:blank".parse().unwrap()), + Some(true) + ); + let record = views.owned(OWNER, child.label()).unwrap(); + views.remove_exact(child.label(), &record); + assert!(!crate::intercept_navigation( + &child, + &"https://example.com".parse().unwrap() + )); + let duplicate = views.create_with( + &owner, + child.label(), + PathBuf::new(), + bounds, + |_, _| {}, + |_| true, + |_| Ok(()), + ); + assert!(duplicate.is_err()); + assert!(views.owned(OWNER, child.label()).is_err()); + child.close().unwrap(); + + let reloaded = views.create_with( + &owner, + "browser-reloading", + PathBuf::new(), + bounds, + |_, _| {}, + |_| true, + |_| { + views.remove_owner(app.handle(), OWNER); + Ok(()) + }, + ); + assert!(reloaded.is_err()); + assert!(views.owned(OWNER, "browser-reloading").is_err()); + assert!(app.get_webview("browser-reloading").is_none()); +} + +#[test] +fn document_policy_allows_blank_and_only_owned_blob_origins() { + let views = EmbeddedViews::for_test(OWNER, "browser-origin"); + views.observe_origin( + "browser-origin", + views.owned(OWNER, "browser-origin").unwrap().token, + &"https://example.com/page".parse().unwrap(), + ); + for url in [ + "https://example.com/page", + "about:blank", + "blob:https://example.com/id", + ] { + assert_eq!( + views.navigation_allowed("browser-origin", &url.parse().unwrap()), + Some(true) + ); + } + for url in [ + "blob:https://other.example/id", + "blob:null/id", + "file:///private", + "tauri://localhost", + ] { + assert_eq!( + views.navigation_allowed("browser-origin", &url.parse().unwrap()), + Some(false) + ); + } + assert!(!is_allowed_url(&"about:blank".parse().unwrap())); + assert!(!is_allowed_url( + &"blob:https://example.com/id".parse().unwrap() + )); +} + +#[test] +fn tree_invalidation_includes_pending_descendants_and_fences_stale_callbacks() { + let views = EmbeddedViews::default(); + let root = views.reserve(OWNER, "browser-tree").unwrap(); + let child = views.reserve(OWNER, "browser-popup-child").unwrap(); + let grandchild = views.reserve(OWNER, "browser-popup-grandchild").unwrap(); + let peer = views.reserve(OWNER, "browser-peer").unwrap(); + { + let mut inner = views.0.lock().unwrap(); + inner.records.get_mut("browser-popup-child").unwrap().opener = Some("browser-tree".into()); + inner + .records + .get_mut("browser-popup-grandchild") + .unwrap() + .opener = Some("browser-popup-child".into()); + let removed = EmbeddedViews::take_tree(&mut inner, "browser-tree", root.token, true); + assert_eq!(removed.len(), 3); + assert_eq!(inner.records.len(), 1); + } + assert!(views + .finish_creation("browser-popup-child", &child) + .is_err()); + assert!(views + .finish_creation("browser-popup-grandchild", &grandchild) + .is_err()); + let replacement = views.reserve(OWNER, "browser-tree").unwrap(); + assert!(!views.current("browser-tree", root.token)); + views.observe_origin( + "browser-tree", + root.token, + &"https://stale.invalid".parse().unwrap(), + ); + assert_eq!(views.owned(OWNER, "browser-tree").unwrap().origin, None); + assert!(EmbeddedViews::take_tree( + &mut views.0.lock().unwrap(), + "browser-tree", + root.token, + true + ) + .is_empty()); + assert!(views.current("browser-tree", replacement.token)); + assert!(views.current("browser-peer", peer.token)); +} + +#[test] +fn reload_tree_invalidation_retains_root_and_isolates_other_owners() { + let views = EmbeddedViews::default(); + let root = views.reserve(OWNER, "browser-reload-tree").unwrap(); + let child = views.reserve(OWNER, "browser-popup-reload").unwrap(); + let other = "local-22222222-2222-4222-8222-222222222222"; + let peer = views.reserve(other, "browser-popup-peer").unwrap(); + let mut inner = views.0.lock().unwrap(); + for label in ["browser-popup-reload", "browser-popup-peer"] { + inner.records.get_mut(label).unwrap().opener = Some("browser-reload-tree".into()); + } + let removed = EmbeddedViews::take_tree(&mut inner, "browser-reload-tree", root.token, false); + assert_eq!(removed.len(), 1); + assert_eq!(removed[0].1.token, child.token); + assert_eq!( + inner.records.get("browser-reload-tree").unwrap().token, + root.token + ); + assert_eq!( + inner.records.get("browser-popup-peer").unwrap().token, + peer.token + ); +} + +#[test] +fn owner_cleanup_removes_ready_and_pending_children_without_touching_other_owners() { + let app = mock_builder().build(mock_context(noop_assets())).unwrap(); + WebviewWindowBuilder::new(&app, OWNER, WebviewUrl::default()) + .build() + .unwrap(); + let window = app.get_window(OWNER).unwrap(); + let child = window + .add_child( + tauri::webview::WebviewBuilder::new("browser-ready", WebviewUrl::default()), + PhysicalPosition::new(0, 0), + PhysicalSize::new(300, 200), + ) + .unwrap(); + let views = EmbeddedViews::for_test(OWNER, child.label()); + let pending = views.reserve(OWNER, "browser-pending").unwrap(); + views.reserve(OTHER, "browser-other").unwrap(); + assert!(views + .set_visible(app.handle(), OTHER, child.label(), true) + .is_err()); + assert!(views + .set_bounds( + app.handle(), + OTHER, + child.label(), + Bounds { + x: 0, + y: 0, + width: 1, + height: 1 + } + ) + .is_err()); + assert!(views.close(app.handle(), OTHER, child.label()).is_err()); + assert!(app.get_webview(child.label()).is_some()); + views.remove_owner(app.handle(), OWNER); + assert!(app.get_webview(child.label()).is_none()); + assert!(views.finish_creation("browser-pending", &pending).is_err()); + assert!(views.owned(OTHER, "browser-other").is_ok()); + views.close(app.handle(), OWNER, "browser-ready").unwrap(); + assert!(app.get_webview(OWNER).is_some()); +} + +#[test] +fn fullscreen_keeps_normal_bounds_and_owner_cleanup_restores_the_window() { + let app = mock_builder().build(mock_context(noop_assets())).unwrap(); + WebviewWindowBuilder::new(&app, OWNER, WebviewUrl::default()) + .build() + .unwrap(); + let window = app.get_window(OWNER).unwrap(); + let child = window + .add_child( + tauri::webview::WebviewBuilder::new("browser-fullscreen", WebviewUrl::default()), + PhysicalPosition::new(10, 20), + PhysicalSize::new(300, 200), + ) + .unwrap(); + let views = EmbeddedViews::for_test(OWNER, child.label()); + let normal = Bounds { + x: 10, + y: 20, + width: 300, + height: 200, + }; + views + .set_bounds(app.handle(), OWNER, child.label(), normal) + .unwrap(); + views + .set_fullscreen(app.handle(), child.label(), true) + .unwrap(); + let saved = views.owned(OWNER, child.label()).unwrap().bounds; + views + .set_bounds( + app.handle(), + OWNER, + child.label(), + Bounds { + width: 1600, + height: 900, + ..normal + }, + ) + .unwrap(); + assert_eq!(views.owned(OWNER, child.label()).unwrap().bounds, saved); + views + .set_fullscreen(app.handle(), child.label(), false) + .unwrap(); + assert!(views + .owned(OWNER, child.label()) + .unwrap() + .fullscreen + .is_none()); + views + .set_fullscreen(app.handle(), child.label(), true) + .unwrap(); + views.remove_owner(app.handle(), OWNER); + assert!(app.get_webview(child.label()).is_none()); + assert!(!window.is_fullscreen().unwrap()); +} +#[test] +fn storage_identifiers_share_only_the_same_full_identity_and_domain() { + let storage = Storage::from(browser_storage(std::path::Path::new("profile/browser"))); + assert_eq!( + storage.directory, + std::path::Path::new("profile/browser/shared-v1") + ); + assert_eq!(storage.domain, "browser/shared-v1"); + let identity = super::StorageIdentity::new("dev".into(), "/home/me/config.yaml".into()); + let id = identity.identifier("browser/shared-v1"); + assert_eq!( + id, + [ + 0xf8, 0x14, 0x9e, 0x7f, 0x1a, 0x96, 0x3c, 0x98, 0xdd, 0x87, 0xcc, 0xfa, 0x46, 0x6b, + 0x6f, 0xad + ] + ); + assert_eq!(id, identity.identifier("browser/shared-v1")); + assert_ne!(id, identity.identifier("local")); + assert_ne!(id, identity.identifier("remote/server")); + assert_ne!( + id, + super::StorageIdentity::new("stable".into(), "/home/me/config.yaml".into()) + .identifier("browser/shared-v1") + ); + assert_ne!( + id, + super::StorageIdentity::new("dev".into(), "/home/other/config.yaml".into()) + .identifier("browser/shared-v1") + ); + // Length framing also separates identities containing the delimiter used by older stores. + assert_ne!( + super::StorageIdentity::new("a\0b".into(), "c".into()).identifier("browser/shared-v1"), + super::StorageIdentity::new("a".into(), "b\0c".into()).identifier("browser/shared-v1"), + ); + use sha2::{Digest, Sha256}; + let app_store: [u8; 16] = Sha256::digest(b"local")[..16].try_into().unwrap(); + assert_ne!(id, app_store); + let cwd = std::path::Path::new("/home/me"); + let home = std::path::Path::new("/home/me"); + let normalized = |path| crate::identity::normalize_config_identity(Some(path), cwd, home); + assert_eq!( + super::StorageIdentity::new("dev".into(), normalized("config.json")) + .identifier("browser/shared-v1"), + super::StorageIdentity::new("dev".into(), normalized("./config.yaml")) + .identifier("browser/shared-v1"), + ); +} diff --git a/packages/tauri-app/src-tauri/src/identity.rs b/packages/tauri-app/src-tauri/src/identity.rs index d0ba52957b..c41b3a4d48 100644 --- a/packages/tauri-app/src-tauri/src/identity.rs +++ b/packages/tauri-app/src-tauri/src/identity.rs @@ -3,7 +3,8 @@ use std::path::{Component, Path, PathBuf}; use std::time::SystemTime; pub(crate) const STABLE_IDENTIFIER: &str = "ai.neuralnomads.codenomad.client"; -pub(crate) const LOCAL_WINDOW_PREFIX: &str = "local-"; +mod local_window; +pub(crate) use local_window::{local_window_id, local_window_label}; const DEFAULT_CONFIG: &str = "~/.config/codenomad/config.json"; #[derive(Clone, Debug, Eq, PartialEq)] @@ -18,24 +19,6 @@ pub(crate) struct IdentityScope { pub(crate) webview_data_directory: PathBuf, } -pub(crate) fn local_window_label(window_id: &str) -> Result { - let uuid = - uuid::Uuid::parse_str(window_id).map_err(|_| "Invalid local window UUID".to_string())?; - let normalized = uuid.to_string(); - if normalized != window_id { - return Err("Local window UUID must be lowercase".to_string()); - } - Ok(format!("{LOCAL_WINDOW_PREFIX}{normalized}")) -} - -pub(crate) fn local_window_id(label: &str) -> Result { - let id = label - .strip_prefix(LOCAL_WINDOW_PREFIX) - .ok_or_else(|| "Native operation is limited to local windows".to_string())?; - local_window_label(id)?; - Ok(id.to_string()) -} - #[derive(Debug, Eq, PartialEq)] pub(crate) struct LaunchProfile { pub(crate) key: String, @@ -117,10 +100,18 @@ fn resolve_config_input(value: &str, cwd: &Path, home: &Path) -> PathBuf { /** Keep the caller's original filename for backend config/legacy migration, * but remove dependence on the backend process's different working directory. */ -pub(crate) fn resolve_selected_config(raw: Option<&str>, cwd: &Path, home: &Path) -> Option { +pub(crate) fn resolve_selected_config( + raw: Option<&str>, + cwd: &Path, + home: &Path, +) -> Option { raw.map(str::trim) .filter(|value| !value.is_empty()) - .map(|value| resolve_config_input(value, cwd, home).to_string_lossy().into_owned()) + .map(|value| { + resolve_config_input(value, cwd, home) + .to_string_lossy() + .into_owned() + }) } pub(crate) fn normalize_config_identity(raw: Option<&str>, cwd: &Path, home: &Path) -> String { @@ -282,13 +273,25 @@ mod tests { for extension in ["json", "yaml"] { let raw = format!("alternate/../selected/custom.{extension}"); let selected = resolve_selected_config(Some(&raw), &cwd, &home).unwrap(); - assert_eq!(PathBuf::from(&selected), cwd.join("selected").join(format!("custom.{extension}"))); + assert_eq!( + PathBuf::from(&selected), + cwd.join("selected").join(format!("custom.{extension}")) + ); if extension == "json" { assert_ne!(selected, normalize_config_identity(Some(&raw), &cwd, &home)); } assert_eq!( - resolve_selected_config(Some(&format!("~/selected/custom.{extension}")), &cwd, &home), - Some(home.join("selected").join(format!("custom.{extension}")).to_string_lossy().into_owned()) + resolve_selected_config( + Some(&format!("~/selected/custom.{extension}")), + &cwd, + &home + ), + Some( + home.join("selected") + .join(format!("custom.{extension}")) + .to_string_lossy() + .into_owned() + ) ); } assert_eq!(resolve_selected_config(None, &cwd, &home), None); diff --git a/packages/tauri-app/src-tauri/src/identity/local_window.rs b/packages/tauri-app/src-tauri/src/identity/local_window.rs new file mode 100644 index 0000000000..7037e350e3 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/identity/local_window.rs @@ -0,0 +1,19 @@ +pub(crate) const LOCAL_WINDOW_PREFIX: &str = "local-"; + +pub(crate) fn local_window_label(window_id: &str) -> Result { + let uuid = + uuid::Uuid::parse_str(window_id).map_err(|_| "Invalid local window UUID".to_string())?; + let normalized = uuid.to_string(); + if normalized != window_id { + return Err("Local window UUID must be lowercase".to_string()); + } + Ok(format!("{LOCAL_WINDOW_PREFIX}{normalized}")) +} + +pub(crate) fn local_window_id(label: &str) -> Result { + let id = label + .strip_prefix(LOCAL_WINDOW_PREFIX) + .ok_or_else(|| "Native operation is limited to local windows".to_string())?; + local_window_label(id)?; + Ok(id.to_string()) +} diff --git a/packages/tauri-app/src-tauri/src/local_windows.rs b/packages/tauri-app/src-tauri/src/local_windows.rs index df87a2d567..ed43089c13 100644 --- a/packages/tauri-app/src-tauri/src/local_windows.rs +++ b/packages/tauri-app/src-tauri/src/local_windows.rs @@ -8,8 +8,12 @@ use url::Url; const MAX_LOCAL_WINDOWS: usize = 16; const MAX_FOLDER_ATTEMPTS: u8 = 3; -const LOCAL_WINDOW_CONTEXT_SCRIPT: &str = - "window.__CODENOMAD_RUNTIME_HOST__ = 'tauri'; window.__CODENOMAD_WINDOW_CONTEXT__ = 'local';"; +#[cfg(target_os = "windows")] +const LOCAL_WINDOW_CONTEXT_SCRIPT: &str = "window.__CODENOMAD_RUNTIME_HOST__ = 'tauri'; window.__CODENOMAD_WINDOW_CONTEXT__ = 'local'; window.__CODENOMAD_BROWSER_CAPABILITIES__ = Object.freeze({embedding:true,history:true,emulation:true,automation:true});"; +#[cfg(any(target_os = "macos", target_os = "linux"))] +const LOCAL_WINDOW_CONTEXT_SCRIPT: &str = "window.__CODENOMAD_RUNTIME_HOST__ = 'tauri'; window.__CODENOMAD_WINDOW_CONTEXT__ = 'local'; window.__CODENOMAD_BROWSER_CAPABILITIES__ = Object.freeze({embedding:true,history:true,emulation:true,automation:true,reason:'webkit'});"; +#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] +const LOCAL_WINDOW_CONTEXT_SCRIPT: &str = "window.__CODENOMAD_RUNTIME_HOST__ = 'tauri'; window.__CODENOMAD_WINDOW_CONTEXT__ = 'local'; window.__CODENOMAD_BROWSER_CAPABILITIES__ = Object.freeze({embedding:false,history:false,emulation:false,automation:false,reason:'unsupported-platform'});"; #[derive(Clone, Debug)] pub(crate) struct LocalWindowRecord { diff --git a/packages/tauri-app/src-tauri/src/main.rs b/packages/tauri-app/src-tauri/src/main.rs index 17642ea6c1..56b59d584a 100644 --- a/packages/tauri-app/src-tauri/src/main.rs +++ b/packages/tauri-app/src-tauri/src/main.rs @@ -12,6 +12,7 @@ mod client_state; mod data_profile; mod data_profile_cleanup; mod developer_mode; +mod embedded_view; mod external_open; mod identity; mod launch; @@ -289,13 +290,14 @@ pub(crate) fn handle_native_request( method: &str, params: Option, deadline: u64, + fence: native_request::RequestFence, ) -> Result { let state = app.state::(); match method { "browser.probe" | "browser.execute" | "browser.page.begin" | "browser.page.send" | "browser.page.check" | "browser.page.end" => state .browser_controller - .handle_native(app, method, params, deadline), + .handle_native(app, method, params, deadline, fence), "opencode.service.start" => native_service_start::start(params, deadline), "developer.status" => state.developer_mode.native_snapshot(app), "developer.restart" => state.developer_mode.request_restart(app), @@ -513,20 +515,25 @@ async fn browser_target_register( ) -> Result<(), String> { require_local_app_webview(&webview, &state)?; let window = webview.window(); - state.browser_controller.register(&window, payload) + let controller = state.browser_controller.clone(); + tauri::async_runtime::spawn_blocking(move || controller.register(&window, payload)) + .await + .map_err(|e| e.to_string())? } #[tauri::command] -fn browser_target_update( +async fn browser_target_update( webview: tauri::Webview, app: AppHandle, state: tauri::State<'_, AppState>, payload: browser_controller::BrowserTargetUpdate, ) -> Result<(), String> { require_local_app_webview(&webview, &state)?; - state - .browser_controller - .update(&app, webview.label(), payload) + let controller = state.browser_controller.clone(); + let owner = webview.label().to_string(); + tauri::async_runtime::spawn_blocking(move || controller.update(&app, &owner, payload)) + .await + .map_err(|e| e.to_string())? } #[tauri::command] @@ -833,9 +840,8 @@ fn open_remote_external_url(url: &Url, open: impl FnOnce(&Url)) -> bool { fn intercept_navigation(webview: &Webview, url: &Url) -> bool { let window_label = webview.label().to_string(); - let state = webview.app_handle().state::(); - if let Some(allowed) = state - .browser_controller + if let Some(allowed) = webview.app_handle() + .state::() .navigation_allowed(&window_label, url) { return allowed; @@ -1652,6 +1658,7 @@ fn is_final_application_window<'a>( !labels.any(|label| { label != closing_label && label != preferences_window::LABEL + && !label.starts_with("browser-popup-") && !launch_windows.iter().any(|launch| launch == label) }) } @@ -1839,6 +1846,9 @@ fn main() { let notification_badge_host = Arc::new(Mutex::new(None::>)); let setup_notification_badge_host = Arc::clone(¬ification_badge_host); + let browser_controller = browser_controller::BrowserController::new( + setup_scope.webview_data_directory.join("browser"), + ); desktop_updater::register(tauri::Builder::default(), context.config()) .plugin(single_instance) .plugin(tauri_plugin_dialog::init()) @@ -1869,6 +1879,11 @@ fn main() { ) .plugin(tauri_plugin_notification::init()) .plugin(navigation_guard) + .manage(browser_controller.embedded_views.clone()) + .manage(embedded_view::StorageIdentity::new( + scope.profile.clone(), + scope.config_identity.clone(), + )) .manage(local_windows::LocalWindows::default()) .manage(notification_badge::NotificationBadge::default()) .manage(window_constraints::WindowConstraints::default()) @@ -1898,9 +1913,7 @@ fn main() { backend_config.clone(), ), developer_mode, - browser_controller: browser_controller::BrowserController::new( - setup_scope.webview_data_directory.join("browser"), - ), + browser_controller, wake_lock: Mutex::new(WakeLockState::default()), remote_navigation: Mutex::new(HashMap::new()), remote_navigation_generation: AtomicU64::new(0), @@ -2059,6 +2072,9 @@ fn main() { browser_target_release_open ]) .on_menu_event(|app_handle, event| { + if embedded_view::zoom::focused(app_handle, event.id().0.as_str()) { + return; + } match event.id().0.as_str() { // File menu action @ ("new-instance" @@ -2720,6 +2736,23 @@ mod menu_tests { )); } + #[test] + fn webkit_popups_follow_the_last_application_window_lifetime() { + assert_eq!( + is_final_application_window( + "local-a", + ["local-a", "browser-popup-a"].into_iter(), + &[], + ), + true, + ); + assert!(!is_final_application_window( + "local-a", + ["local-a", "browser-popup-a", "local-b"].into_iter(), + &[], + )); + } + #[test] fn hidden_launch_windows_do_not_keep_the_last_application_window_alive() { let launch = vec!["local-launch".to_string()]; diff --git a/packages/tauri-app/src-tauri/src/menu_labels.rs b/packages/tauri-app/src-tauri/src/menu_labels.rs index b2af6c1285..0f61a6268b 100644 --- a/packages/tauri-app/src-tauri/src/menu_labels.rs +++ b/packages/tauri-app/src-tauri/src/menu_labels.rs @@ -5,7 +5,7 @@ use tauri::{menu::MenuItemKind, Wry}; /// English labels until a renderer reports its locale. Keys and texts mirror /// `NATIVE_MENU_LABEL_KEYS` and the English messages in the UI package /// (`packages/ui/src/lib/native/menu-labels.ts`); a UI test keeps them in sync. -pub(crate) const DEFAULTS: [(&str, &str); 39] = [ +pub(crate) const DEFAULTS: [(&str, &str); 49] = [ ("file", "File"), ("edit", "Edit"), ("view", "View"), @@ -45,6 +45,19 @@ pub(crate) const DEFAULTS: [(&str, &str); 39] = [ ("maximize", "Maximize"), ("zoom", "Zoom"), ("bringAllToFront", "Bring All to Front"), + ("browserPermission", "Allow {permission} for {origin}?"), + ( + "browserPermissionUnknown", + "Unknown permission blocked: {permission}.", + ), + ("browserAllow", "Allow"), + ("browserDeny", "Deny"), + ("browserCopyLink", "Copy Link"), + ("browserSaveImage", "Save Image"), + ("browserOpenLink", "Open Link in New Window"), + ("browserInspect", "Inspect"), + ("browserPromptAccept", "OK"), + ("browserPromptCancel", "Cancel"), ]; const MAX_LABEL_CHARS: usize = 200; @@ -94,6 +107,13 @@ pub(crate) struct MenuLabels { } impl MenuLabels { + pub(crate) fn text(&self, key: &str) -> String { + self.latest + .lock() + .ok() + .and_then(|labels| labels.as_ref().and_then(|labels| labels.get(key)).cloned()) + .unwrap_or_else(|| label(key).to_string()) + } pub(crate) fn replace_targets(&self, targets: Vec<(&'static str, MenuItemKind)>) { if let Ok(mut current) = self.targets.lock() { *current = targets; @@ -106,7 +126,9 @@ impl MenuLabels { /// Runs on the main thread. Native menu calls happen outside our mutexes. pub(crate) fn apply(&self, reported: Option<&BTreeMap>) { let labels = { - let Ok(mut latest) = self.latest.lock() else { return }; + let Ok(mut latest) = self.latest.lock() else { + return; + }; if let Some(reported) = reported { *latest = Some(reported.clone()); } @@ -114,7 +136,9 @@ impl MenuLabels { }; let Some(labels) = labels else { return }; { - let Ok(mut applied) = self.applied.lock() else { return }; + let Ok(mut applied) = self.applied.lock() else { + return; + }; if applied.as_ref() == Some(&labels) { return; } @@ -143,7 +167,10 @@ mod tests { use std::collections::BTreeMap; fn labels(entries: &[(&str, &str)]) -> BTreeMap { - entries.iter().map(|(key, text)| (key.to_string(), text.to_string())).collect() + entries + .iter() + .map(|(key, text)| (key.to_string(), text.to_string())) + .collect() } #[test] @@ -165,6 +192,9 @@ mod tests { #[cfg(not(target_os = "macos"))] #[test] fn a_literal_ampersand_is_not_a_mnemonic() { - assert_eq!(resolve("copy", Some(&labels(&[("copy", "Copy & paste")]))), "Copy && paste"); + assert_eq!( + resolve("copy", Some(&labels(&[("copy", "Copy & paste")]))), + "Copy && paste" + ); } } diff --git a/packages/tauri-app/src-tauri/src/native_request.rs b/packages/tauri-app/src-tauri/src/native_request.rs index 76c465b012..a45e9c033f 100644 --- a/packages/tauri-app/src-tauri/src/native_request.rs +++ b/packages/tauri-app/src-tauri/src/native_request.rs @@ -1,5 +1,69 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +#[derive(Clone)] +pub(crate) struct RequestFence { + deadline: Instant, + deadline_ms: u64, + current: Arc bool + Send + Sync>, +} + +impl RequestFence { + pub(crate) fn new( + deadline_ms: u64, + current: impl Fn() -> bool + Send + Sync + 'static, + ) -> Self { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|value| value.as_millis() as u64) + .unwrap_or(u64::MAX); + let deadline = Instant::now() + .checked_add(Duration::from_millis(deadline_ms.saturating_sub(now))) + .unwrap_or_else(Instant::now); + Self { + deadline, + deadline_ms, + current: Arc::new(current), + } + } + + pub(crate) fn check(&self) -> Result<(), String> { + if !(self.current)() { + return Err("Native backend process is no longer current".into()); + } + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|value| value.as_millis() as u64) + .unwrap_or(u64::MAX); + if Instant::now() >= self.deadline || now_ms >= self.deadline_ms { + return Err("Native request expired before execution".into()); + } + Ok(()) + } +} + +/// Shared by the desktop stream reader and native-engine regression harness. +/// A replacement process never receives its predecessor's result. +pub(crate) fn dispatch( + request: NativeRequest, + fence: RequestFence, + handle: impl FnOnce(&NativeRequest, RequestFence) -> Result, +) -> Option { + if !(fence.current)() { + return None; + } + let result = fence.check().and_then(|()| handle(&request, fence.clone())); + if !(fence.current)() { + return None; + } + let result = match fence.check() { + Ok(()) => result, + Err(error) => Err(error), + }; + Some(response(&request.id, result)) +} pub(crate) const REQUEST_PREFIX: &str = "CODENOMAD_NATIVE_REQUEST:"; pub(crate) const RESPONSE_PREFIX: &str = "CODENOMAD_NATIVE_RESPONSE:"; @@ -88,4 +152,53 @@ mod tests { "CODENOMAD_NATIVE_RESPONSE:{\"v\":1,\"id\":\"r1\",\"ok\":true,\"result\":{\"available\":true}}\n" ); } + + #[test] + fn fences_expired_dispatch_retired_processes_and_late_results() { + use std::sync::atomic::{AtomicBool, Ordering}; + let request = || NativeRequest { + v: 1, + id: "request".into(), + method: "browser.probe".into(), + params: None, + deadline: u64::MAX, + }; + let expired = RequestFence::new(0, || true); + let response = + dispatch(request(), expired, |_, _| panic!("expired work dispatched")).unwrap(); + assert!(response.contains("expired")); + let current = Arc::new(AtomicBool::new(true)); + let predicate = current.clone(); + let fence = RequestFence::new(u64::MAX - 1, move || predicate.load(Ordering::SeqCst)); + // Use a representable deadline while keeping this test independent of clock changes. + let fence = RequestFence { + deadline: Instant::now() + Duration::from_secs(10), + ..fence + }; + let queued = fence.clone(); + assert!(dispatch(request(), fence, |_, _| { + current.store(false, Ordering::SeqCst); + Ok(json!({"secret":"old process"})) + }) + .is_none()); + assert!(queued.check().unwrap_err().contains("no longer current")); + let late = RequestFence { + deadline: Instant::now() + Duration::from_millis(5), + deadline_ms: u64::MAX, + current: Arc::new(|| true), + }; + let response = dispatch(request(), late, |_, _| { + std::thread::sleep(Duration::from_millis(10)); + Ok(json!({"stale":true})) + }) + .unwrap(); + assert!(response.contains("expired")); + assert!(!response.contains("stale")); + let absolute = RequestFence { + deadline: Instant::now() + Duration::from_secs(10), + deadline_ms: 0, + current: Arc::new(|| true), + }; + assert!(absolute.check().unwrap_err().contains("expired")); + } } diff --git a/packages/tauri-app/src-tauri/src/windows_browser_accelerators.rs b/packages/tauri-app/src-tauri/src/windows_browser_accelerators.rs index 42724ebf09..83b7fe9ed9 100644 --- a/packages/tauri-app/src-tauri/src/windows_browser_accelerators.rs +++ b/packages/tauri-app/src-tauri/src/windows_browser_accelerators.rs @@ -39,7 +39,7 @@ pub(crate) fn install(controller: &ICoreWebView2Controller) -> webview2_com::Res Ok(()) } -pub(crate) fn bind(webview: &tauri::Webview) { +pub(crate) fn bind(webview: &tauri::Webview) { if let Err(error) = webview.with_webview(|platform| { if let Err(error) = install(&platform.controller()) { eprintln!("[browser-accelerators] failed to protect F6: {error}"); diff --git a/packages/tauri-app/src-tauri/tauri.conf.json b/packages/tauri-app/src-tauri/tauri.conf.json index 18ebc998c4..24a57b1afb 100644 --- a/packages/tauri-app/src-tauri/tauri.conf.json +++ b/packages/tauri-app/src-tauri/tauri.conf.json @@ -25,7 +25,7 @@ "active": true, "copyright": "Copyright © 2025-2026 CodeNomad contributors", "macOS": { - "minimumSystemVersion": "13.5" + "minimumSystemVersion": "14.0" }, "linux": { "deb": { diff --git a/packages/tauri-app/tests/browser-parent/README.md b/packages/tauri-app/tests/browser-parent/README.md new file mode 100644 index 0000000000..35b09a3012 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/README.md @@ -0,0 +1,63 @@ +# WebKit private parent-channel regression + +Build the Node side from the checkout root: + +```sh +npx --no-install esbuild packages/tauri-app/tests/browser-parent/fixture.ts --bundle --platform=node --format=esm --outfile=.tmp/browser-parent-fixture.mjs +``` + +On a macOS or Linux graphical session: + +```sh +python3 packages/tauri-app/scripts/test-browser-parent-webkit.py \ + --fixture /path/to/browser-parent-fixture.mjs \ + --output /path/to/artifacts --target /path/to/owned-cargo-target \ + --node /absolute/path/to/node +``` + +Requirements: Rust, Node, OpenSSL, and the host's native development libraries (GTK 3 / WebKitGTK 4.1, version 2.40+ for isolated-world `evaluate_javascript`, on Linux). Linux inherits display/session variables from the user manager; `GDK_BACKEND=x11` or `wayland` selects the engine display backend. `--nested-kde` owns a separate virtual KWin Wayland compositor alongside an existing desktop and terminates only that compositor. The Cargo target is caller-owned and reusable. The initial offline build reuses the checkout lockfile's resolved versions and the production native build helper; it has a five-minute bound. Native execution is bounded to 150 seconds. Output includes `parent-result.json` and the native `parent-capture.png`. + +The in-tree example builds with `cargo build --locked --example browser-parent-webkit --features browser-parent-qualification`. That feature links the exploratory native trial adapters into the example; normal application builds keep their production adapters. Native CI builds the example explicitly alongside the regular crate tests. + +The harness compiles production `BrowserController`, `EmbeddedViews`, local-window identity validation, native adapters and `native_request::dispatch`. Its child uses production `NativeParent`, real prefixed stdout requests and piped stdin responses. The owning-window inventory and renderer's open-claim callback are fixture-supplied; the existing application UI subscription has its own regression. The harness starts its own fixture child and HTTP/self-signed TLS servers. Keep its temporary data profile separate from application profiles. Native browser automation is available on all supported desktop hosts. + +The full application qualification runs with `node scripts/qualify-native-browser-app.mjs `. It starts a private OpenCode daemon, a deterministic provider issuing actual `codenomad.browser` agent tool calls, the packaged application under a unique data profile/configuration, and a local page. Lifecycle discovery is pinned to that retained private daemon by a fixture CLI adapter; shared services remain untouched. The real UI opens the session preview through the real backend and native-parent channel. Checks cover open, snapshot, all page actions, screenshot, OAuth opener/postMessage, a downloaded file and a native JavaScript dialog. Artifacts contain completed native tool messages, the app hash, PNG and process logs. Run on a graphical desktop; dialog acceptance targets the owned app process. + +Debug applications receive a private static server containing the built UI. Linux downloads follow `xdg-user-dir DOWNLOAD`. The harness shuts down its exact backend process group after verifying the app-specific cookie identity. Windows dialog acceptance uses UI Automation; macOS uses process-targeted native Return; Linux X11 uses the owned native window. Set `P7_SKIP_NATIVE_DIALOG=1` for page/capability diagnostics on displays requiring another native dialog operator; `result.json` records `nativeDialog: false` explicitly. + +The fixed fixture-only operations control visibility, a renderer dialog, duplicate ownership, close/reopen, response delay and backend retirement. Native capture-completion tests revoke authority at the callback guard's acceptance boundary, after the real engine has produced its result. The controller's native navigation and capture operations remain unchanged by the fixture. These operations belong only to this example executable, never renderer IPC or the application parent-method allowlist. + +## Semantic reads + +Regenerate the fixed reader and extracted Electron fixtures, then build the read child: + +```sh +node --import tsx scripts/build-webkit-read.ts +npx --no-install esbuild packages/tauri-app/tests/browser-parent/read-fixture.ts --bundle --platform=node --format=esm --outfile=.tmp/read-fixture.mjs +``` + +Pass that child as `--fixture` to the same native harness. It saves each fixture's tree and shared-renderer snapshot, and `read-result.json`. Checks include stable same-document refs, fragment/pushState preservation, removal/reinsertion, recreation, cross-document navigation, scope/query and visibility/closure fences. Fixture-only mutations use fixed scripts in the example. Read identities and semantic traversal stay inside the production isolated-world program. The document-start closed-root hook weakly associates roots with hosts; the isolated reader validates native reference-event endpoints against their exact host and document. Declarative closed roots are opaque to this public-DOM capture path. + +Run `node --import tsx scripts/compare-webkit-read.ts ` to assert rendered control parity and produce a side-by-side table for each fixture. The native parent contains `macos`, `x11` and `wayland` folders; the default prefix is `p3-read-`. Frame contents are compared explicitly; native date-editor internals are filtered by the production snapshot renderer. + +## Native actions + +```sh +npx --no-install esbuild packages/tauri-app/tests/browser-parent/action-fixture.ts --bundle --platform=node --format=esm --sourcemap=inline --outfile=.tmp/p4-action-fixture.mjs +node --import tsx scripts/compare-webkit-actions.ts .tmp/p4-comparison +``` + +Run the native harness with that action child as `--fixture` on macOS, Linux X11 and private Wayland. The shared `action-scenarios.ts` drives the production BrowserPage/PageDriver over real parent pipes and the direct CDP driver over Chromium. HTML input/form/preview fixtures are extracted from the Electron tests. Additional cases cover captured closed-root click/text/contenteditable/select, same-origin frame click/text, forged root endpoints, native ten-step drags, special input append/validation, modal/hidden/covered refusal, waits and declarative parser boundaries. Fixed observation/control programs belong only to the example host. + +`action-result.json` records assertions, DOM event trust/modifiers and engine limitations. Native-only timeout cases cover both an expired unsent insertion and an admitted pointer whose handler blocks the page: each down appears once, exact-lease cleanup releases buttons/keys, and the insertion stays unsent. macOS traces can be enabled with `CN_INPUT_TRACE=1`; preserve the standalone-hover and Meta-equivalent event differences alongside the normalized state comparison. + +## Device profiles + +```sh +npx --no-install esbuild packages/tauri-app/tests/browser-parent/mobile-fixture.ts --bundle --platform=node --format=esm --outfile=.tmp/mobile-fixture.mjs +node --import tsx scripts/compare-webkit-mobile.ts .tmp/mobile-comparison +``` + +Pass `mobile-fixture.mjs` to the graphical harness on macOS, GTK X11 and `--nested-kde` Wayland; repeat X11 with `GDK_SCALE=2`. `mobile-result.json` reports all six CSS viewports, HTTP/JS user-agent identity, screen/orientation, density, media and touch support. Assertions cover renderer zoom 1.5, native trusted click/touch, unchanged-profile no-op, invalid-profile refusal, resize/replacement lifetime, desktop reset and independent renderer/preview state. The Chromium comparison uses the same HTML and production Electron emulation adapter and records `chromium-mobile.json`. + +Build `mobile-trial.ts` the same way for isolated page-zoom, DPR override, layout/view-scale and native GDK-touch experiments. Trial controls compile only into this qualification executable; profile application uses the production modules. The native WebKit limitations and optional macOS density selector are specified in `dev-docs/BROWSER_DEVICE_EMULATION.md`. diff --git a/packages/tauri-app/tests/browser-parent/action-extra.html b/packages/tauri-app/tests/browser-parent/action-extra.html new file mode 100644 index 0000000000..67151e4b64 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/action-extra.html @@ -0,0 +1,10 @@ +Action edge cases + +
+ + + + + + +
Old rich
diff --git a/packages/tauri-app/tests/browser-parent/action-fixture.ts b/packages/tauri-app/tests/browser-parent/action-fixture.ts new file mode 100644 index 0000000000..4ec61b6ca3 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/action-fixture.ts @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import { writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { NativeParent } from '../../../server/src/native-parent' +import { installShutdownStdinHandler } from '../../../server/src/shutdown' +import { BrowserPage } from '../../../server/src/automation/browser-page' +import { parsePageAction } from '../../../server/src/automation/page/parse' +import { nativeDriver } from '../../../server/src/automation/page/native-driver' +import { actionScenarios } from './action-scenarios' +process.setSourceMapsEnabled(true) +const parent=new NativeParent(process.stdout,true),browser=new BrowserPage(parent) +installShutdownStdinHandler(process.stdin,async()=>{},line=>parent.handleLine(line)) +const [base,output]=process.argv.slice(2),engine=process.platform==='darwin'?'macos':output.includes('wayland')?'wayland':'x11' +const request=(method:string,params:object={},timeout=20_000)=>parent.request(method,{sessionID:'fixture-session',...params},timeout) +const control=(kind:string)=>request('fixture.action-control',{kind}) +const observe=()=>request('fixture.action-probe') +async function main(){ + assert.equal(parent.browserAutomationUnavailable,false) + await request('browser.execute',{command:{action:'open',url:`${base}/read/preview`}}) + const result=await actionScenarios({ + navigate:name=>{console.error(`action fixture: ${name}`);return request('browser.execute',{command:{action:'navigate',url:`${base}/read/${name}`}})}, + snapshot:async()=>(await browser.execute('fixture-session',{action:'snapshot'})).snapshot as string, + act:action=>{console.error(`action: ${action.action}${action.key?` ${action.key}`:''}`);return browser.execute('fixture-session',parsePageAction(action,'snapshot')!)},observe,control, + },engine) + for(const admitted of [false,true]) { + await request('browser.execute',{command:{action:'navigate',url:`${base}/read/inputs`}}) + const operationID=randomUUID(),descriptor=await request('browser.page.begin',{operationID}) + const send=(operation:any,timeout?:number)=>request('browser.page.send',{operationID,generation:descriptor.generation,operation},timeout) + const driver=nativeDriver(descriptor,operation=>send(operation),async()=>{}) + const target=(await driver.tree()).find(node=>node.role==='button' && node.name==='Hover me')! + const quad=(await driver.geometry(target.node!))[0],x=(quad[0]+quad[4])/2,y=(quad[1]+quad[5])/2 + const pointer={type:'mousePressed' as const,x,y,button:'left' as const,buttons:1,clickCount:1} + if(admitted) { + await control('arm-busy-click') + await assert.rejects(send({op:'pointer',event:pointer},150),/expired|timed out|timeout/i) + } else { + await driver.pointer(pointer) + const query=(await driver.tree()).find(node=>node.role==='textbox' && node.name==='Query')! + await driver.call('focus',await driver.resolve(query.node!),[]) + await driver.keyboard({type:'rawKeyDown',key:'Shift',code:'ShiftLeft',modifiers:8}) + await control('busy') + await assert.rejects(send({op:'insert-text',text:'MUST-NOT-REPLAY'},20),/expired|timed out|timeout/i) + } + await request('browser.page.end',{operationID}) + const observed=await observe();result.observations[admitted?'admittedTimeout':'queuedTimeout']=observed + writeFileSync(join(output,'action-observations.json'),JSON.stringify(result,null,2)) + assert.equal(observed.audit.filter((event:any)=>event.type==='pointerdown').length,1) + assert.equal(observed.audit.filter((event:any)=>event.type==='pointerup').length,1) + if(!admitted) assert.ok(observed.audit.some((event:any)=>event.type==='keyup' && event.key==='Shift')) + assert.ok(!JSON.stringify(observed.fields).includes('MUST-NOT-REPLAY')) + } + result.checks.push('native parent timeouts: queued mutation refused, admitted pointer not replayed; held pointer/key released on exact lease end') + writeFileSync(join(output,'action-result.json'),JSON.stringify(result,null,2)) + console.error(JSON.stringify({passed:true,engine,checks:result.checks,limitations:result.limitations})) +} +main().then(()=>{parent.close();process.exit(0)},error=>{writeFileSync(join(output,'action-result.json'),JSON.stringify({passed:false,engine,error:String(error)},null,2));console.error(error);parent.close();process.exit(1)}) diff --git a/packages/tauri-app/tests/browser-parent/action-programs.generated.json b/packages/tauri-app/tests/browser-parent/action-programs.generated.json new file mode 100644 index 0000000000..54fa3b2896 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/action-programs.generated.json @@ -0,0 +1,22 @@ +{ + "auditor": "(() => {\n window.__actionAudit=[];\n for(const type of ['keydown','keyup','pointerdown','pointerup','pointermove','click','contextmenu','wheel','beforeinput','input','change']) document.addEventListener(type,event=>{\n if(window.__actionAudit.length<1000) window.__actionAudit.push({type,id:event.target.id,key:event.key||'',inputType:event.inputType||'',trusted:event.isTrusted,buttons:event.buttons||0,meta:!!event.metaKey,ctrl:!!event.ctrlKey,shift:!!event.shiftKey});\n },true);\n document.addEventListener('contextmenu',event=>event.preventDefault());\n})()", + "programs": { + "observe": "(() => {\n const fields={};for(const item of document.querySelectorAll('input,textarea,select,[contenteditable]')) {const editable=item.hasAttribute('contenteditable')&&item.getAttribute('contenteditable')!=='false';fields[item.id||item.getAttribute('aria-label')||item.type]={value:item.type==='password'?'masked':editable?item.innerText:item.value,html:editable?item.innerHTML:undefined,checked:['checkbox','radio'].includes(item.type)?item.checked:undefined,selected:item.selectedOptions?Array.from(item.selectedOptions).map(option=>option.label):undefined};}\n for(const host of document.querySelectorAll('x-button')) fields[host.id]={clicked:host.dataset.clicked};\n const value={fields,audit:window.__actionAudit||[],log:window.log||[],dropped:!!window.dropped,closedClicks:window.closedClicks||0,closedTrusted:!!window.closedTrusted,nestedClicked:document.body.dataset.nestedClicked,recreatedClicked:document.body.dataset.recreatedClicked,frameClicked:document.querySelector('#same')?.contentDocument?.body.dataset.clicked,hover:document.querySelector('#hover-state')?.textContent,scroll:document.querySelector('#scroller')?.scrollTop||0,pageScroll:scrollY,declarative:{height:document.querySelector('#declarative')?.getBoundingClientRect().height||0,marker:document.querySelector('#declarative')?.getAttribute('data-codenomad-shadow-boundary'),open:!!document.querySelector('#declarative')?.shadowRoot,templates:window.declarativeTemplates||0}};\n value.capabilities={predictedEvents:typeof PointerEvent.prototype.getPredictedEvents};\n let output=document.getElementById('__cn_probe');if(!output){output=document.createElement('output');output.id='__cn_probe';output.style='position:fixed;right:0;bottom:0;font-size:1px;pointer-events:none';document.body.append(output)}output.textContent='__CN_PROBE__'+JSON.stringify(value);\n })()", + "remove-probe": "document.getElementById('__cn_probe')?.remove()", + "remove-ready": "document.querySelector('#later').textContent=''", + "split-text": "document.querySelector('#later').innerHTML='

Hello world

'", + "shadow-hosts": "{for(const mode of ['open','closed']){const host=document.createElement('x-button');host.id=mode+'-host';host.setAttribute('role','button');host.setAttribute('aria-label',mode+' Host action');host.style='display:block;width:160px;height:40px';host.attachShadow({mode}).innerHTML='Press';host.addEventListener('click',event=>host.dataset.clicked=event.isTrusted);document.body.prepend(host)}}", + "schedule-ready": "{document.querySelector('#later').textContent='';setTimeout(()=>document.querySelector('#later').textContent='Ready now',250)}", + "hidden-open": "{const details=document.createElement('details');details.id='hidden-details';details.open=true;details.innerHTML='Target';document.body.append(details)}", + "hidden-close": "document.querySelector('#hidden-details').open=false", + "long-rows": "{const section=document.createElement('section');section.innerHTML=Array.from({length:35},(_,index)=>'').join('');document.body.append(section);scrollTo(0,0)}", + "busy": "{const until=performance.now()+500;while(performance.now(){const until=performance.now()+500;while(performance.now()');document.close();{const root=document.querySelector('#recreated').attachShadow({mode:'closed'});root.innerHTML='';root.querySelector('button').addEventListener('click',event=>document.body.dataset.recreatedClicked=event.isTrusted)}", + "pagehide": "dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}))", + "frame-pagehide": "document.querySelector('#same').contentWindow.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}))", + "show-modal": "document.querySelector('#modal').showModal()", + "forge-shadow": "{const host=document.createElement('div');host.id='forged';host.setAttribute('data-codenomad-shadow-boundary','closed');document.body.append(host);host.addEventListener('__codenomad_request_shadow_v1',()=>{for(const candidate of [document.body,...(typeof closedRoot==='undefined'?[]:[closedRoot])])host.dispatchEvent(new PointerEvent('__codenomad_shadow_v1',{predictedEvents:[new PointerEvent('__codenomad_reference_v1',{relatedTarget:candidate})]}))})}" + } +} diff --git a/packages/tauri-app/tests/browser-parent/action-programs.ts b/packages/tauri-app/tests/browser-parent/action-programs.ts new file mode 100644 index 0000000000..3de3fa8d14 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/action-programs.ts @@ -0,0 +1,33 @@ +/** Fixed fixture-only programs, consumed by both the CDP and native test hosts. */ +export const ACTION_AUDITOR=`(() => { + window.__actionAudit=[]; + for(const type of ['keydown','keyup','pointerdown','pointerup','pointermove','click','contextmenu','wheel','beforeinput','input','change']) document.addEventListener(type,event=>{ + if(window.__actionAudit.length<1000) window.__actionAudit.push({type,id:event.target.id,key:event.key||'',inputType:event.inputType||'',trusted:event.isTrusted,buttons:event.buttons||0,meta:!!event.metaKey,ctrl:!!event.ctrlKey,shift:!!event.shiftKey}); + },true); + document.addEventListener('contextmenu',event=>event.preventDefault()); +})()` +export const ACTION_PROGRAMS={ + observe:`(() => { + const fields={};for(const item of document.querySelectorAll('input,textarea,select,[contenteditable]')) {const editable=item.hasAttribute('contenteditable')&&item.getAttribute('contenteditable')!=='false';fields[item.id||item.getAttribute('aria-label')||item.type]={value:item.type==='password'?'masked':editable?item.innerText:item.value,html:editable?item.innerHTML:undefined,checked:['checkbox','radio'].includes(item.type)?item.checked:undefined,selected:item.selectedOptions?Array.from(item.selectedOptions).map(option=>option.label):undefined};} + for(const host of document.querySelectorAll('x-button')) fields[host.id]={clicked:host.dataset.clicked}; + const value={fields,audit:window.__actionAudit||[],log:window.log||[],dropped:!!window.dropped,closedClicks:window.closedClicks||0,closedTrusted:!!window.closedTrusted,nestedClicked:document.body.dataset.nestedClicked,recreatedClicked:document.body.dataset.recreatedClicked,frameClicked:document.querySelector('#same')?.contentDocument?.body.dataset.clicked,hover:document.querySelector('#hover-state')?.textContent,scroll:document.querySelector('#scroller')?.scrollTop||0,pageScroll:scrollY,declarative:{height:document.querySelector('#declarative')?.getBoundingClientRect().height||0,marker:document.querySelector('#declarative')?.getAttribute('data-codenomad-shadow-boundary'),open:!!document.querySelector('#declarative')?.shadowRoot,templates:window.declarativeTemplates||0}}; + value.capabilities={predictedEvents:typeof PointerEvent.prototype.getPredictedEvents}; + let output=document.getElementById('__cn_probe');if(!output){output=document.createElement('output');output.id='__cn_probe';output.style='position:fixed;right:0;bottom:0;font-size:1px;pointer-events:none';document.body.append(output)}output.textContent='__CN_PROBE__'+JSON.stringify(value); + })()`, + "remove-probe":"document.getElementById('__cn_probe')?.remove()", + "remove-ready":"document.querySelector('#later').textContent=''", + "split-text":"document.querySelector('#later').innerHTML='

Hello world

'", + "shadow-hosts":`{for(const mode of ['open','closed']){const host=document.createElement('x-button');host.id=mode+'-host';host.setAttribute('role','button');host.setAttribute('aria-label',mode+' Host action');host.style='display:block;width:160px;height:40px';host.attachShadow({mode}).innerHTML='Press';host.addEventListener('click',event=>host.dataset.clicked=event.isTrusted);document.body.prepend(host)}}`, + "schedule-ready":"{document.querySelector('#later').textContent='';setTimeout(()=>document.querySelector('#later').textContent='Ready now',250)}", + "hidden-open":"{const details=document.createElement('details');details.id='hidden-details';details.open=true;details.innerHTML='Target';document.body.append(details)}", + "hidden-close":"document.querySelector('#hidden-details').open=false", + "long-rows":"{const section=document.createElement('section');section.innerHTML=Array.from({length:35},(_,index)=>'').join('');document.body.append(section);scrollTo(0,0)}", + busy:"{const until=performance.now()+500;while(performance.now(){const until=performance.now()+500;while(performance.now()');document.close();{const root=document.querySelector('#recreated').attachShadow({mode:'closed'});root.innerHTML='';root.querySelector('button').addEventListener('click',event=>document.body.dataset.recreatedClicked=event.isTrusted)}`, + pagehide:"dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}))", + "frame-pagehide":"document.querySelector('#same').contentWindow.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}))", + "show-modal":"document.querySelector('#modal').showModal()", + "forge-shadow":`{const host=document.createElement('div');host.id='forged';host.setAttribute('data-codenomad-shadow-boundary','closed');document.body.append(host);host.addEventListener('__codenomad_request_shadow_v1',()=>{for(const candidate of [document.body,...(typeof closedRoot==='undefined'?[]:[closedRoot])])host.dispatchEvent(new PointerEvent('__codenomad_shadow_v1',{predictedEvents:[new PointerEvent('__codenomad_reference_v1',{relatedTarget:candidate})]}))})}`, +} as const diff --git a/packages/tauri-app/tests/browser-parent/action-scenarios.ts b/packages/tauri-app/tests/browser-parent/action-scenarios.ts new file mode 100644 index 0000000000..991a13fdc2 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/action-scenarios.ts @@ -0,0 +1,196 @@ +import assert from "node:assert/strict" +export interface Harness { + navigate(name:string):Promise + snapshot():Promise + act(action:Record):Promise> + observe():Promise + control(kind:string):Promise +} +export async function actionScenarios(h:Harness,engine:string) { + const checks:string[]=[],limitations:string[]=[],observations:Record={} + const ref=async(pattern:RegExp)=>{const snapshot=await h.snapshot();const line=snapshot.split('\n').find(line=>pattern.test(line));assert.ok(line,`${pattern}: ${snapshot}`);return /\[([^\]]+)\]/.exec(line)![1]} + const type=async(pattern:RegExp,text:string,clear=true)=>h.act({action:"type",ref:await ref(pattern),text,clear}) + const press=async(key:string,target?:string)=>h.act({action:"press",key,...target?{ref:target}:{}}) + const until=async(predicate:(value:any)=>boolean)=>{const deadline=Date.now()+3000;let value;do{value=await h.observe();if(predicate(value))return value;await new Promise(resolve=>setTimeout(resolve,30))}while(Date.now()event.type==='click' && event.trusted)) + checks.push('automation-preview: Unicode clear/append, select, trusted click') + + await h.navigate('forms') + assert.equal((await type(/textbox "Notes"/,'New notes')).value,'New notes') + assert.equal((await type(/textbox "Rich"/,'Rich é🙂')).value,'Rich é🙂') + assert.equal((await type(/Date "Due"/,'2026-11-07')).value,'2026-11-07') + const select=await ref(/combobox "Scenario"/) + await h.act({action:'select',ref:select,values:['wayfinder']}) + const before=(await h.observe()).audit.filter((event:any)=>event.id==='scenario' && ['input','change'].includes(event.type)).length + await h.act({action:'select',ref:select,values:['Exploration']}) + assert.equal((await h.observe()).audit.filter((event:any)=>event.id==='scenario' && ['input','change'].includes(event.type)).length,before) + await assert.rejects(h.act({action:'select',ref:select,values:['Debugging']}),/disabled/) + await h.act({action:'click',ref:await ref(/checkbox "Agree"/)}) + observations.forms=await h.observe();assert.equal((observations.forms as any).fields.agree.checked,true) + checks.push('automation-forms: native/contenteditable/date, select value/label, unchanged events, disabled option') + + await h.navigate('edges') + await assert.rejects(type(/textbox "Locked"/,'Forbidden'),/disabled/) + await type(/textbox "Mail"/,'x@y.test') + assert.equal((await type(/textbox "Mail"/,'.ok',false)).value,'x@y.test.ok') + await type(/spinbutton "Count"/,'42') + assert.equal((await type(/spinbutton "Count"/,'3',false)).value,'423') + await type(/ColorWell "Tint"/,'#123abc') + await type(/slider "Volume"/,'60') + await assert.rejects(type(/Date "Day"/,'invalid'),/not a valid/) + assert.equal((await h.observe()).fields.day.value,'2026-01-02') + const outside=await ref(/textbox "Outside"/);await h.control('show-modal') + await assert.rejects(h.act({action:'type',ref:outside,text:'Forbidden'}),/cannot take focus/) + observations.edges=await h.observe() + checks.push('automation-forms edges: disabled, email/number/color/range setters and date validation') + + await h.navigate('inputs') + const query=await ref(/textbox "Query"/) + await type(/textbox "Query"/,'hello') + await press('Enter',query) + let observed=await h.observe() + observations.enter=observed + if(!observed.log.includes('submit:hello') && engine==='macos') limitations.push('Enter in a background WKWebView input did not submit the form') + else assert.ok(observed.log.includes('submit:hello')) + await press('Tab') + await press('Shift+Tab') + await press('Mod+K',query) + await type(/textbox "Query"/,'',false) + await press('Shift+a',query);await press('+');await press('`') + assert.equal((await h.observe()).fields.query.value,'helloA+`') + await type(/textbox "Query"/,'hello') + await h.act({action:'hover',ref:await ref(/button "Hover me"/)}) + observed=await h.observe() + if(observed.hover!=='hovered' && engine==='macos') limitations.push('Initial standalone hover did not deliver pointerenter') + else assert.equal(observed.hover,'hovered') + await h.act({action:'click',ref:await ref(/button "Open menu"/)}) + await h.act({action:'click',ref:await ref(/menuitem "Menu item"/)}) + await h.act({action:'click',ref:await ref(/button "Open menu"/),button:'right'}) + await h.act({action:'scroll',ref:await ref(/region "Scroller"/),direction:'down',amount:500}) + observed=await until(value=>value.scroll>0) + await h.act({action:'drag',ref:await ref(/button "Handle"/),to:await ref(/region "Drop zone"/)}) + observed=await until(value=>value.dropped) + await assert.rejects(h.act({action:'click',ref:await ref(/button "Under"/)}),/covered/) + await h.control('schedule-ready') + assert.equal((await h.act({action:'wait',text:'Ready now',timeout:15000})).found,true) + await h.control('remove-ready') + assert.equal((await h.act({action:'wait',text:'Ready now',gone:true,timeout:15000})).found,false) + await assert.rejects(h.act({action:'wait',text:'absent',timeout:50}),/did not appear/) + await h.control('split-text') + assert.equal((await h.act({action:'wait',text:'Hello world',timeout:500})).found,true) + await assert.rejects(h.act({action:'wait',text:'Hello world',gone:true,timeout:50}),/still shown/) + await h.control('remove-ready') + assert.equal((await h.act({action:'wait',text:'Hello world',gone:true,timeout:500})).found,false) + checks.push('split-node text: appear, gone refuses while present, gone after removal') + observed=await h.observe() + assert.ok(observed.audit.some((event:any)=>event.type==='contextmenu' && event.trusted)) + assert.ok(observed.audit.some((event:any)=>event.type==='wheel' && event.trusted)) + const textInputs=observed.audit.filter((event:any)=>event.type==='input' && event.id==='query') + assert.ok(textInputs.length>0 && textInputs.every((event:any)=>event.trusted)) + assert.ok(observed.audit.some((event:any)=>event.type==='keydown' && event.key.toLowerCase()==='k' && (engine==='macos' ? event.meta : event.ctrl))) + assert.ok(observed.audit.filter((event:any)=>['pointerdown','pointerup','pointermove','wheel','keydown','keyup','click'].includes(event.type)).every((event:any)=>event.trusted)) + observations.inputs=observed + await h.control('hidden-open');const hidden=await ref(/textbox "Hidden target"/);await h.control('hidden-close') + await assert.rejects(press('Enter',hidden),/cannot take focus/) + await h.control('long-rows') + await assert.rejects(h.act({action:'drag',ref:await ref(/button "Row 1"/),to:await ref(/button "Row 35"/)}),/no visible box/) + await h.act({action:'scroll',direction:'down',amount:500}) + await until(value=>value.pageScroll>0) + checks.push('automation-input: Enter/Tab, hover, left/right pointer, native element/page wheel, drag, covered/hidden/offscreen refusal, wait appear/disappear') + + await h.navigate('advanced') + await h.control('shadow-hosts') + for(const mode of ['open','closed']) { + await h.act({action:'click',ref:await ref(new RegExp(`button "${mode} Host action"`))}) + assert.equal((await h.observe()).fields[mode+'-host'].clicked,'true') + } + checks.push('interactive open/captured-closed shadow hosts accept trusted clicks through descendant spans') + await h.act({action:'click',ref:await ref(/button "Closed action"/)}) + assert.equal((await type(/textbox "Closed field"/,'Closed é🙂')).value,'Closed é🙂') + assert.equal((await type(/textbox "Closed rich"/,'Closed rich é🙂')).value,'Closed rich é🙂') + assert.equal((await type(/textbox "Closed rich"/,' appended',false)).value,'Closed rich é🙂 appended') + await press('Enter',await ref(/textbox "Closed rich"/)) + assert.equal((await type(/textbox "Closed rich"/,'tail',false)).value,'Closed rich é🙂 appended\ntail') + assert.deepEqual((await h.act({action:'select',ref:await ref(/combobox "Closed plan"/),values:['Two']})).selected,['Two']) + assert.equal((await type(/textbox "Nested closed field"/,'Nested é🙂')).value,'Nested é🙂') + await h.act({action:'click',ref:await ref(/button "Nested closed action"/)}) + assert.equal((await h.observe()).nestedClicked,'true') + if(engine!=='chromium') assert.equal((await h.act({action:'wait',text:'Closed é🙂',timeout:1000})).found,true) + assert.equal((await type(/textbox "Shadow field"/,'Open shadow')).value,'Open shadow') + if(engine!=='chromium') { + assert.equal((await type(/textbox "Frame field"/,'Frame é🙂')).value,'Frame é🙂') + await h.act({action:'click',ref:await ref(/button "Frame action"/)}) + assert.equal((await h.observe()).frameClicked,'true') + const frameRef=await ref(/textbox "Frame field"/);await h.control('frame-pagehide') + await assert.rejects(h.act({action:'type',ref:frameRef,text:'stale frame'}),/no longer|snapshot/) + assert.equal((await type(/textbox "Frame field"/,'Fresh frame')).value,'Fresh frame') + } + else observations.frame='Contents absent from Chromium main-frame AX tree' + observed=await h.observe();assert.equal(observed.closedClicks,1);assert.equal(observed.closedTrusted,true) + observations.closed=observed + observations.closedSnapshot=await h.snapshot() + assert.equal(observed.audit.filter((event:any)=>event.id==='closed' && event.type==='input' && event.inputType==='insertParagraph').length,1) + await h.control('forge-shadow') + const forged=await h.snapshot();assert.equal(forged.split('button "Closed action"').length-1,1) + if(engine!=='chromium') assert.match(forged,/Closed shadow root \(unavailable\)/) + const old=await ref(/textbox "Closed field"/);await h.control('remove-closed') + await assert.rejects(h.act({action:'type',ref:old,text:'stale'}),/no longer|snapshot/) + await h.control('recreate-shadow') + assert.equal((await type(/textbox "Recreated closed field"/,'Recreated é🙂')).value,'Recreated é🙂') + await h.act({action:'click',ref:await ref(/button "Recreated closed action"/)}) + assert.equal((await h.observe()).recreatedClicked,'true') + if(engine!=='chromium') { + const recreated=await ref(/textbox "Recreated closed field"/);await h.control('pagehide') + await assert.rejects(h.act({action:'type',ref:recreated,text:'stale recreated'}),/stale|snapshot|changed/) + } + checks.push('closed/nested/open shadow: click/text/contenteditable/select, forged roots, stale/recreated refs; same-origin frame on WebKit') + + await h.navigate('extra') + const extraSnapshot=await h.snapshot() + if(engine==='chromium') assert.match(extraSnapshot,/Declarative closed action/) + else assert.ok(!extraSnapshot.includes('Declarative closed action')) + await assert.rejects(type(/textbox "Readonly"/,'Forbidden'),/read-only/) + assert.equal((await type(/textbox "Password"/,'secret')).value,'•'.repeat(6)) + assert.equal((await type(/textbox "Password"/,'')).value,'') + await type(/InputTime "Clock"/,'12:34') + await assert.rejects(type(/InputTime "Focus locked clock"/,'12:34'),/read-only/) + assert.equal((await h.observe()).fields['focus-locked'].value,'') + await type(/DateTime "Moment"/,'2026-11-07T12:34') + const multiple=await ref(/listbox "Multiple"/) + assert.deepEqual((await h.act({action:'select',ref:multiple,values:['one','Two']})).selected,['One','Two']) + await assert.rejects(h.act({action:'select',ref:multiple,values:['Three']}),/disabled/) + assert.deepEqual((await h.observe()).fields.multiple.selected,['One','Two']) + assert.deepEqual((await h.act({action:'click',ref:await ref(/option "Two"/)})).selected,['Two']) + await assert.rejects(h.act({action:'click',ref:multiple}),/native select/) + await type(/textbox "Rich lines"/,'one') + await press('Enter',await ref(/textbox "Rich lines"/)) + await type(/textbox "Rich lines"/,'two',false) + const enterRich=await h.observe();observations.richEnter=enterRich + assert.equal(enterRich.fields.rich.value,'one\ntwo') + assert.equal(enterRich.audit.filter((event:any)=>event.id==='rich' && event.type==='input' && event.inputType==='insertParagraph').length,1) + await press('Mod+A',await ref(/textbox "Rich lines"/));await press('Enter') + observations.modThenEnter=await h.observe() + assert.equal((observations.modThenEnter as any).audit.filter((event:any)=>event.id==='rich' && event.type==='input' && event.inputType==='insertParagraph').length,2) + assert.ok(!((observations.modThenEnter as any).fields.rich.value as string).includes('one'),'Mod+A selects the editable text before Enter') + assert.equal((observations.inputs as any).audit.filter((event:any)=>event.type==='pointermove' && event.id==='handle' && event.buttons===1).length,10) + observations.declarative=observations.modThenEnter + const declarative=(observations.modThenEnter as any).declarative + assert.ok(declarative.height>0);assert.equal(declarative.marker,null);assert.equal(declarative.open,false);assert.equal(declarative.templates,0) + if(engine==='macos') { + const audit=(observations.modThenEnter as any).audit + if(!audit.some((event:any)=>event.type==='keyup' && event.key==='Meta')) limitations.push('Mod+A: WKWebView did not expose the Meta keyup in DOM events') + if(!audit.some((event:any)=>event.type==='keydown' && event.key.toLowerCase()==='a' && event.meta)) limitations.push('Mod+A selects through the native responder; WKWebView consumes the A keydown before DOM listeners') + const enters=audit.filter((event:any)=>event.type==='keydown' && event.key==='Enter') + if(enters.length<2) limitations.push('Enter following Mod+A was not delivered to contenteditable') + if(!audit.some((event:any)=>event.type==='keyup' && event.key==='Enter')) limitations.push('Standalone Enter: WKWebView omitted DOM keyup') + } + checks.push('multiple select/disabled optgroup, readonly, password masking, time/datetime, contenteditable Enter and Mod chord') + return {passed:true,engine,checks,limitations,observations} +} diff --git a/packages/tauri-app/tests/browser-parent/app.html b/packages/tauri-app/tests/browser-parent/app.html new file mode 100644 index 0000000000..9f4cfd6c9f --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/app.html @@ -0,0 +1,22 @@ +Native app qualification + +

Ready native browser

+Count 0 + +Keys idleHover idle +
Drag source
Drop target
Drag idle
+
Scrollable content
Scroll idle +OAuth idle +Download fixtureDialog idle + diff --git a/packages/tauri-app/tests/browser-parent/fixture.ts b/packages/tauri-app/tests/browser-parent/fixture.ts new file mode 100644 index 0000000000..91d32fc27a --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/fixture.ts @@ -0,0 +1,85 @@ +import assert from "node:assert/strict" +import { writeFileSync } from "node:fs" +import { join } from "node:path" +import { NativeParent } from "../../../server/src/native-parent" +import { installShutdownStdinHandler } from "../../../server/src/shutdown" + +const parent = new NativeParent(process.stdout, true) +installShutdownStdinHandler(process.stdin, async () => { throw new Error("Unexpected fixture shutdown command") }, line => parent.handleLine(line)) +const [base, output] = process.argv.slice(2) +const request = (method: string, params: unknown = {}, timeout = 15_000) => parent.request(method, { sessionID: "fixture-session", ...params as object }, timeout) +const execute = (action: string, url?: string, timeout?: number) => request("browser.execute", { command: { action, url } }, timeout) +const checks: string[] = [] +async function check(name: string, run: () => Promise) { await run(); checks.push(name); console.error(`PASS ${name}`) } +try { + assert.equal(parent.browserAutomationUnavailable, false, "native browser automation is available") + await check("no preview", async () => { await assert.rejects(request("browser.probe"), /No visible/ ) }) + await check("autonomous open and redirect", async () => { + assert.equal((await execute("open", `${base}/redirect`)).url, `${base}/ok`) + assert.deepEqual(await request("browser.probe"), { available: true }) + }) + await check("visible PNG", async () => { + const screenshot = await execute<{ image: {mime: string; data: string}; url: string }>("screenshot") + assert.equal(screenshot.image.mime, "image/png") + assert.ok(screenshot.image.data.length <= 16 * 1024 * 1024) + const png = Buffer.from(screenshot.image.data, "base64") + assert.equal(png.subarray(0,8).toString("hex"), "89504e470d0a1a0a") + writeFileSync(join(output, "parent-capture.png"), png) + }) + await check("fragment navigation", async () => { assert.equal((await execute("navigate", `${base}/ok#fragment`)).url, `${base}/ok#fragment`) }) + await check("cross-document redirect", async () => { assert.equal((await execute("navigate", `${base}/redirect`)).url, `${base}/ok`) }) + await check("failed load", async () => { await assert.rejects(execute("navigate", "http://127.0.0.1:1/unavailable"), /failed|load|navigation/i) }) + await execute("navigate", `${base}/ok`) + await check("TLS failure", async () => { + assert.ok(process.env.CN_FIXTURE_TLS_URL) + await assert.rejects(execute("navigate", process.env.CN_FIXTURE_TLS_URL), /failed|load|navigation/i) + }) + await execute("navigate", `${base}/ok`) + await check("navigation deadline", async () => { + await assert.rejects(execute("navigate", `${base}/slow`, 30), /timed out|expired/i) + }) + await execute("navigate", `${base}/ok`) + await check("hidden target", async () => { + await request("fixture.hide") + await assert.rejects(request("browser.probe"), /No visible/) + await assert.rejects(execute("screenshot"), /No visible/) + await request("fixture.show") + }) + await check("overlay hides authority", async () => { + await request("fixture.overlay") + await assert.rejects(execute("screenshot"), /No visible/) + await request("fixture.show") + }) + await check("duplicate target", async () => { + await request("fixture.duplicate") + await assert.rejects(request("browser.probe"), /Multiple visible/) + await request("fixture.removeDuplicate") + }) + await check("native capture callback after hide", async () => { + await assert.rejects(request("fixture.capture-hide"), /No visible/) + await request("fixture.show") + }) + await check("native capture callback after close", async () => { + await assert.rejects(request("fixture.capture-close"), /No visible/) + assert.equal((await execute("open", `${base}/ok`)).url, `${base}/ok`) + }) + await check("late reply is discarded", async () => { + await assert.rejects(request("fixture.late", {}, 20), /timed out/) + assert.deepEqual(await request("browser.probe"), { available: true }) + }) + await check("close and reopen", async () => { + await request("fixture.close") + await assert.rejects(request("browser.probe"), /No visible/) + assert.equal((await execute("open", `${base}/ok`)).url, `${base}/ok`) + await request("fixture.close") + }) + await check("retired process gets no response", async () => { await assert.rejects(request("fixture.retire", {}, 50), /timed out/) }) + writeFileSync(join(output, "parent-result.json"), JSON.stringify({passed: true, checks}, null, 2)) + parent.close() + process.exit(0) +} catch (error) { + writeFileSync(join(output, "parent-result.json"), JSON.stringify({passed: false, checks, error: String(error)}, null, 2)) + console.error(error) + parent.close() + process.exit(1) +} diff --git a/packages/tauri-app/tests/browser-parent/mobile-fixture.ts b/packages/tauri-app/tests/browser-parent/mobile-fixture.ts new file mode 100644 index 0000000000..1e1331e129 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile-fixture.ts @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict' +import {writeFileSync} from 'node:fs' +import {NativeParent} from '../../../server/src/native-parent' +import {installShutdownStdinHandler} from '../../../server/src/shutdown' +import {BrowserPage} from '../../../server/src/automation/browser-page' +const parent=new NativeParent(process.stdout,true),page=new BrowserPage(parent) +installShutdownStdinHandler(process.stdin,async()=>{},line=>parent.handleLine(line)) +const [base,output]=process.argv.slice(2),request=(method:string,input:object={})=>parent.request(method,{sessionID:'fixture-session',...input},20000) +const probe=(target?:string)=>request('fixture.mobile-probe',{target}) +async function until(check:(v:any)=>boolean,target?:string){const end=Date.now()+8000;let last;do{try{last=await probe(target);if(check(last))return last}catch{}await new Promise(r=>setTimeout(r,40))}while(Date.now()v.ua===v.httpUA,'primary'),other=await until(v=>v.ua===v.httpUA,'other'),baseline=await until(v=>v.ua===v.httpUA) + const rows=[] + for(const [name,width,height] of [['responsive',600,400],['desktop',1440,900],['tablet',768,1024],['tabletLandscape',1024,768],['mobile',390,844],['mobileLandscape',844,390]] as const){ + const viewport=name==='responsive'?undefined:{width,height} + const preset=name==='mobile'||name==='mobileLandscape'?name:'none' + await request('fixture.mobile-size',{width:600,height:400,presentation:{css:true}}) + const before=await until(v=>v.ua===v.httpUA) + await request('fixture.mobile-profile',{preset,viewport}) + const value=await until(v=>v.inner[0]===width&&v.inner[1]===height&&v.ua===v.httpUA&&(name==='responsive'||v.load!==before.load)) + if(name!=='responsive')assert.notEqual(value.load,before.load,'changing viewport/profile reloads') + assert.equal(value.ua.includes('(Mobile)'),preset!=='none') + assert.deepEqual((await probe('primary')).inner,primary.inner);assert.equal((await probe('primary')).ua,primary.ua) + assert.deepEqual((await probe('other')).inner,other.inner);assert.equal((await probe('other')).ua,other.ua) + rows.push({name,...value});console.error(`PASS profile ${name}: ${value.inner} DPR ${value.dpr}`) + } + // Native renderer zoom is read by the host, rather than inferred from JS DPR. + await request('fixture.mobile-trial',{target:'primary',zoom:1.5}) + await until(v=>v.inner[0]v.inner[0]===390&&v.inner[1]===844&&v.ua===v.httpUA&&v.load!==beforeZoomed.load) + const snapshot=await page.execute('fixture-session',{action:'snapshot'}) + const ref=/button "Touch target" \[([^\]]+)\]/.exec(snapshot.snapshot as string)![1] + await page.execute('fixture-session',{action:'click',ref}) + const clicked=await until(v=>v.events.some((e:any)=>e.type==='click')) + assert.equal(clicked.events.filter((e:any)=>e.type==='click').length,1) + assert.ok(clicked.events.every((e:any)=>e.trusted)) + if(process.platform==='linux')assert.ok(clicked.events.some((e:any)=>e.type==='touchstart')) + else assert.equal(clicked.events.some((e:any)=>e.type==='touchstart'),false) + const currentLoad=clicked.load + await request('fixture.mobile-profile',{preset:'mobile',viewport:{width:390,height:844}}) + assert.equal((await probe()).load,currentLoad,'identical profile is a no-op') + await assert.rejects(request('fixture.mobile-profile',{preset:'arbitrary'}),/Invalid browser/) + assert.equal((await probe()).load,currentLoad) + await assert.rejects(request('fixture.mobile-profile',{preset:'none',viewport:{width:0,height:844}}),/Invalid browser/) + assert.equal((await probe()).load,currentLoad) + await request('fixture.mobile-size',{width:500,height:300,presentation:{css:true,viewport:{width:390,height:844}}}) + const resized=await until(v=>v.inner[0]===390&&v.inner[1]===844) + assert.equal(resized.ua,clicked.ua);assert.equal(resized.load,currentLoad,'resizing retains the document/profile') + await request('fixture.mobile-trial',{target:'primary',zoom:1}) + await request('fixture.mobile-size',{width:600,height:400,presentation:{css:true}}) + await request('fixture.mobile-profile',{preset:'none'}) + const reset=await until(v=>v.ua===baseline.ua&&v.httpUA===baseline.ua&&v.inner[0]===600&&v.inner[1]===400) + assert.notEqual(reset.load,currentLoad) + assert.equal((await probe('other')).ua,other.ua) + const resetSnapshot=await page.execute('fixture-session',{action:'snapshot'}) + const resetRef=/button "Touch target" \[([^\]]+)\]/.exec(resetSnapshot.snapshot as string)![1] + await page.execute('fixture-session',{action:'click',ref:resetRef}) + const resetClicked=await until(v=>v.events.some((e:any)=>e.type==='click')) + assert.equal(resetClicked.events.some((e:any)=>e.type==='touchstart'),false,'reset restores mouse input') + await request('fixture.mobile-profile',{preset:'mobile'}) + await until(v=>v.ua===clicked.ua&&v.httpUA===clicked.ua) + await request('fixture.mobile-replace',{url:base+'/mobile'}) + const replaced=await until(v=>v.ua===baseline.ua&&v.httpUA===baseline.ua) + assert.equal(replaced.dpr,baseline.dpr,'replacement clears profile density') + const result={passed:true,platform:process.platform,rows,zoomed,clicked,resized,reset,resetClicked,replaced,primary,other} + writeFileSync(output+'/mobile-result.json',JSON.stringify(result,null,2));console.error(JSON.stringify({passed:true,profiles:rows.length,zoomed:zoomed.inner,reset:reset.inner}));parent.close();process.exit(0) +} +main().catch(error=>{writeFileSync(output+'/mobile-result.json',JSON.stringify({passed:false,error:String(error)},null,2));console.error(error);parent.close();process.exit(1)}) diff --git a/packages/tauri-app/tests/browser-parent/mobile-native.rs b/packages/tauri-app/tests/browser-parent/mobile-native.rs new file mode 100644 index 0000000000..c272b27652 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile-native.rs @@ -0,0 +1,123 @@ +use super::*; +use std::ffi::{c_char, c_void, CString}; +extern "C" { + fn cn_mobile_trial( + view: *mut c_void, + ua: *const c_char, + zoom: f64, + dpr: f64, + width: f64, + height: f64, + mode: i32, + ) -> i32; + fn cn_mobile_touch(view: *mut c_void, phase: i32, x: f64, y: f64) -> i32; +} +pub(super) fn handle( + app: &tauri::AppHandle, + controller: &BrowserController, + id: &str, + method: &str, + input: &Value, + fence: native_request::RequestFence, +) -> Result { + fence.check()?; + let prefix = if input["target"] == "other" { + "browser-mobile-other-".into() + } else { + format!("browser-{id}-") + }; + let view = if input["target"] == "primary" { + app.get_webview(OWNER) + } else { + app.webviews() + .into_values() + .find(|view| view.label().starts_with(&prefix)) + } + .ok_or("Mobile fixture view missing")?; + if method == "fixture.mobile-init" { + let url = input["url"].as_str().ok_or("Missing fixture URL")?; + app.get_webview(OWNER) + .ok_or("Missing renderer")? + .navigate(url.parse().map_err(|_| "Invalid fixture URL")?) + .map_err(|e| e.to_string())?; + let registration=serde_json::from_value(json!({"sessionId":"mobile-other","registrationId":"mobile-other","url":url,"bounds":bounds(),"visible":false})).unwrap(); + controller.register(&app.get_window(OTHER).unwrap(), registration)?; + update(app, controller, OTHER, "mobile-other", true)?; + std::thread::sleep(Duration::from_millis(200)); + return Ok(Value::Null); + } + if method == "fixture.mobile-replace" { + let registration=serde_json::from_value(json!({"sessionId":SESSION,"registrationId":id,"url":input["url"],"bounds":bounds(),"visible":true})).map_err(|e|e.to_string())?; + controller.register( + &app.get_window(OWNER).ok_or("Missing renderer")?, + registration, + )?; + return Ok(Value::Null); + } + if method == "fixture.mobile-size" { + let update=serde_json::from_value(json!({"registrationId":id,"visible":true,"presentation":input["presentation"],"bounds":{"x":10,"y":60,"width":input["width"],"height":input["height"]}})).map_err(|e|e.to_string())?; + controller.update(app, OWNER, update)?; + return Ok(Value::Null); + } + if method == "fixture.mobile-probe" { + view.eval("report()").map_err(|e| e.to_string())?; + let bytes = embedded_view::input::read( + &view, + embedded_view::input::Read::Checkpoint, + std::time::Instant::now() + Duration::from_secs(5), + move || fence.check(), + )?; + let value: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::from_str( + value["body"] + .as_str() + .and_then(|s| s.split_once("__CN_MOBILE__").map(|(_, v)| v)) + .ok_or("Mobile report missing")? + .trim(), + ) + .map_err(|e| e.to_string()); + } + if method == "fixture.mobile-profile" { + let action=serde_json::from_value(json!({"registrationId":id,"action":"emulate","preset":input["preset"],"viewport":input["viewport"]})).unwrap(); + return controller.action(app, OWNER, action); + } + let ua = CString::new(input["ua"].as_str().unwrap_or("")).map_err(|_| "Invalid trial UA")?; + let zoom = input["zoom"].as_f64().unwrap_or(1.0); + let dpr = input["dpr"].as_f64().unwrap_or(0.0); + let mode = input["mode"].as_i64().unwrap_or(0) as i32; + let width = input["cssWidth"].as_f64().unwrap_or(390.0); + let height = input["cssHeight"].as_f64().unwrap_or(844.0); + let phase = input["phase"].as_i64().unwrap_or(0) as i32; + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + let touch = method == "fixture.mobile-touch"; + view.with_webview(move |native| { + if let Err(error) = fence.check() { + let _ = sender.send(Err(error)); + return; + } + #[cfg(target_os = "macos")] + let ptr = native.inner(); + #[cfg(target_os = "linux")] + let ptr = { + use gtk::glib::object::ObjectType; + native.inner().as_ptr().cast::() + }; + let result = unsafe { + if touch { + cn_mobile_touch(ptr, phase, 40.0, 140.0) + } else { + cn_mobile_trial(ptr, ua.as_ptr(), zoom, dpr, width, height, mode) + } + }; + let _ = sender.send(Ok(result)); + }) + .map_err(|e| e.to_string())?; + let result = receiver + .recv_timeout(Duration::from_secs(5)) + .map_err(|_| "Native mobile trial timed out")??; + if !touch && input["reload"] != false { + view.reload().map_err(|e| e.to_string())?; + } + std::thread::sleep(Duration::from_millis(150)); + Ok(json!({"native":result})) +} diff --git a/packages/tauri-app/tests/browser-parent/mobile-trial-linux.c b/packages/tauri-app/tests/browser-parent/mobile-trial-linux.c new file mode 100644 index 0000000000..034a925ca6 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile-trial-linux.c @@ -0,0 +1,23 @@ +#include +#include +int cn_mobile_trial(void *opaque,const char *ua,double zoom,double dpr,double width,double height,int mode) { + (void)dpr;(void)width;(void)height;(void)mode; + WebKitWebView *view=WEBKIT_WEB_VIEW(opaque); + webkit_settings_set_user_agent(webkit_web_view_get_settings(view),ua&&*ua?ua:NULL); + webkit_web_view_set_zoom_level(view,zoom); + return 0; +} +int cn_mobile_touch(void *opaque,int phase,double x,double y) { + int emulating=phase<10;phase%=10; + GtkWidget *view=GTK_WIDGET(opaque); + GdkWindow *window=gtk_widget_get_window(view); + GdkSeat *seat=gdk_display_get_default_seat(gtk_widget_get_display(view)); + if(!window||!seat)return 0; + GdkEvent *event=gdk_event_new(phase==0?GDK_TOUCH_BEGIN:phase==1?GDK_TOUCH_UPDATE:GDK_TOUCH_END); + event->touch.window=g_object_ref(window);event->touch.send_event=FALSE; + event->touch.time=GDK_CURRENT_TIME;event->touch.x=x;event->touch.y=y; + event->touch.sequence=(GdkEventSequence *)view;event->touch.emulating_pointer=emulating; + int ox=0,oy=0;gdk_window_get_origin(window,&ox,&oy);event->touch.x_root=ox+x;event->touch.y_root=oy+y; + gdk_event_set_device(event,gdk_seat_get_pointer(seat)); + gtk_widget_event(view,event);gdk_event_free(event);return 1; +} diff --git a/packages/tauri-app/tests/browser-parent/mobile-trial-macos.m b/packages/tauri-app/tests/browser-parent/mobile-trial-macos.m new file mode 100644 index 0000000000..70a0370e5b --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile-trial-macos.m @@ -0,0 +1,21 @@ +#import +#import +@interface WKWebView (CNMobileTrial) +- (void)_setOverrideDeviceScaleFactor:(CGFloat)scale; +- (void)_setLayoutMode:(NSUInteger)mode; +- (void)_setFixedLayoutSize:(CGSize)size; +- (void)_setViewScale:(CGFloat)scale; +@end +int cn_mobile_trial(void *opaque,const char *ua,double zoom,double dpr,double width,double height,int mode) { + WKWebView *view=(__bridge WKWebView *)opaque; + view.customUserAgent=ua&&*ua?[NSString stringWithUTF8String:ua]:nil; + view.pageZoom=zoom; + int flags=0; + if([view respondsToSelector:@selector(_setOverrideDeviceScaleFactor:)]) {flags|=1;[view _setOverrideDeviceScaleFactor:dpr];} + if([view respondsToSelector:@selector(_setLayoutMode:)] && [view respondsToSelector:@selector(_setFixedLayoutSize:)]) { + flags|=2;[view _setLayoutMode:mode==1?1:0];[view _setFixedLayoutSize:CGSizeMake(width,height)]; + } + if([view respondsToSelector:@selector(_setViewScale:)]) {flags|=4;[view _setViewScale:mode==2?0.5:1];} + return flags; +} +int cn_mobile_touch(void *opaque,int phase,double x,double y) {(void)opaque;(void)phase;(void)x;(void)y;return 0;} diff --git a/packages/tauri-app/tests/browser-parent/mobile-trial.ts b/packages/tauri-app/tests/browser-parent/mobile-trial.ts new file mode 100644 index 0000000000..49ff3b82b3 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile-trial.ts @@ -0,0 +1,25 @@ +import { NativeParent } from '../../../server/src/native-parent' +import { installShutdownStdinHandler } from '../../../server/src/shutdown' +import { writeFileSync } from 'node:fs' +const parent=new NativeParent(process.stdout,true) +installShutdownStdinHandler(process.stdin,async()=>{},line=>parent.handleLine(line)) +const [base,output]=process.argv.slice(2) +const request=(method:string,input:object={})=>parent.request(method,{sessionID:'fixture-session',...input},20000) +async function main(){ + await request('browser.execute',{command:{action:'open',url:base+'/mobile'}}) + await request('fixture.mobile-init',{url:base+'/mobile'}) + const rows=[] + for(const [name,settings] of Object.entries({baseline:{},zoom:{zoom:1.5},density:{dpr:2.75},combined:{zoom:1.5,dpr:2.75},fixed:{mode:1,cssWidth:390,cssHeight:844},viewScale:{mode:2},mobileUA:{ua:'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'}})) { + await request('fixture.mobile-size',{width:600,height:400}) + const native=await request('fixture.mobile-trial',settings) + const row={name,native,guest:await request('fixture.mobile-probe'),primary:await request('fixture.mobile-probe',{target:'primary'}),other:await request('fixture.mobile-probe',{target:'other'})};rows.push(row) + } + await request('fixture.mobile-trial',{}) + for(const phase of [0,1,2]) await request('fixture.mobile-touch',{phase}) + rows.push({name:'touch',guest:await request('fixture.mobile-probe')}) + await request('fixture.mobile-trial',{}) + for(const phase of [10,11,12]) await request('fixture.mobile-touch',{phase}) + rows.push({name:'touchNoEmulation',guest:await request('fixture.mobile-probe')}) + writeFileSync(output+'/mobile-trial.json',JSON.stringify(rows,null,2));console.error(JSON.stringify(rows.map(row=>({name:row.name,inner:row.guest.inner,dpr:row.guest.dpr,events:row.guest.events}))));parent.close();process.exit(0) +} +main().catch(e=>{console.error(e);parent.close();process.exit(1)}) diff --git a/packages/tauri-app/tests/browser-parent/mobile.html b/packages/tauri-app/tests/browser-parent/mobile.html new file mode 100644 index 0000000000..dcab909e0a --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/mobile.html @@ -0,0 +1,9 @@ +Native device profile + +Overlay + diff --git a/packages/tauri-app/tests/browser-parent/read-advanced.html b/packages/tauri-app/tests/browser-parent/read-advanced.html new file mode 100644 index 0000000000..eb54eac26e --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/read-advanced.html @@ -0,0 +1,34 @@ +Semantic boundaries +
+ First choice

Detailed help

+ + + + + + + + + +
+
+ +
+
+ + + + +
+ diff --git a/packages/tauri-app/tests/browser-parent/read-fixture.ts b/packages/tauri-app/tests/browser-parent/read-fixture.ts new file mode 100644 index 0000000000..be42674ccf --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/read-fixture.ts @@ -0,0 +1,95 @@ +import assert from "node:assert/strict" +import { randomUUID } from "node:crypto" +import { writeFileSync } from "node:fs" +import { join } from "node:path" +import { NativeParent } from "../../../server/src/native-parent" +import { installShutdownStdinHandler } from "../../../server/src/shutdown" +import { BrowserPage } from "../../../server/src/automation/browser-page" +import { snapshotTree } from "../../../server/src/automation/page/semantic-tree" +import { renderSnapshot } from "../../../server/src/automation/page/snapshot" +import type { SemanticNode, PageOperation } from "../../../server/src/automation/page/protocol" + +const parent=new NativeParent(process.stdout,true) +installShutdownStdinHandler(process.stdin,async()=>{},line=>parent.handleLine(line)) +const [base,output]=process.argv.slice(2), checks:string[]=[] +const request=>(method:string,params:object={})=>parent.request(method,{sessionID:"fixture-session",...params},20_000) +const navigate=(url:string)=>request("browser.execute",{command:{action:"navigate",url}}) +const browser=new BrowserPage(parent) +async function lease() { + const operationID=randomUUID() + const target=await request<{generation:string;driver:string}>("browser.page.begin",{operationID}) + assert.equal(target.driver,"webkit") + return { + generation:target.generation, + send:>(operation:PageOperation)=>request("browser.page.send",{operationID,generation:target.generation,operation}), + end:()=>request("browser.page.end",{operationID}), + check:()=>request("browser.page.check",{operationID,generation:target.generation}), + } +} +async function main() { + assert.equal(parent.browserAutomationUnavailable,false) + await request("browser.execute",{command:{action:"open",url:`${base}/read/preview`}}) + for(const name of ["preview","forms","edges","inputs","advanced"]) { + await navigate(`${base}/read/${name}`) + if(name === 'inputs') await browser.execute('fixture-session',{action:'wait',text:'Ready now',gone:false,timeout:5000}) + const current=await lease() + const {nodes}=await current.send<{nodes:SemanticNode[]}>({op:"tree"}) + assert.ok(nodes.length) + assert.deepEqual((await current.send<{nodes:SemanticNode[]}>({op:"tree"})).nodes,nodes) + const snapshot=renderSnapshot(snapshotTree(nodes),id=>`n${id}`).text + writeFileSync(join(output,`${name}.json`),JSON.stringify({nodes,snapshot},null,2)) + writeFileSync(join(output,`${name}.txt`),snapshot) + if(name === "advanced") { + assert.ok(!JSON.stringify(nodes).includes("never-expose-this-secret")) + for(const label of ["First choice","Shadow label","Frame action","Closed action","Closed field","Cross-origin frame (unavailable)"]) assert.ok(snapshot.includes(label),`${label}: ${snapshot}`) + for(const hidden of ["Hidden attribute","Hidden display","Hidden inert","Hidden ARIA","Hidden shadow action"]) assert.ok(!snapshot.includes(hidden)) + const secret=nodes.find(node=>node.role === "textbox" && node.name === "Secret")! + const secretHandle=(await current.send({op:"resolve",node:secret.node!})).handle as string + assert.deepEqual(await current.send({op:"call",function:"read-value",handle:secretHandle,args:[]}),{value:"•".repeat(16)}) + assert.deepEqual(await current.send({op:"call",function:"field",handle:secretHandle,args:[]}),{handle:secretHandle}) + const button=nodes.find(node=>node.role === "button" && node.name === "First choice")! + const handle=(await current.send({op:"resolve",node:button.node!})).handle + assert.equal(typeof handle,"string") + await navigate(`${base}/read/advanced#stable`) + await current.check() + assert.equal((await current.send({op:"resolve",node:button.node!})).handle,handle) + await request("fixture.read-mutation",{kind:"pushstate"}) + await current.check() + assert.equal((await current.send({op:"resolve",node:button.node!})).handle,handle) + await request("fixture.read-mutation",{kind:"reinsert"}) + assert.equal((await current.send({op:"resolve",node:button.node!})).handle,undefined) + assert.equal((await current.send({op:"call",function:"read-value",handle:handle as string,args:[]})).exception,"codenomad:gone") + await request("fixture.read-mutation",{kind:"recreate"}) + await assert.rejects(current.check(),/document changed|no longer current/i) + checks.push("refs: stable snapshots/fragments/pushState; removal/reinsertion/recreation refused") + } + await current.end() + checks.push(`${name}: real native semantic tree`) + } + await navigate(`${base}/read/advanced`) + const snapshot=await browser.execute("fixture-session",{action:"snapshot"}) + const ref=/button "First choice" \[([^\]]+)\]/.exec(snapshot.snapshot as string)![1] + assert.match((await browser.execute("fixture-session",{action:"snapshot",ref})).snapshot as string,/Detailed help/) + assert.match((await browser.execute("fixture-session",{action:"snapshot",query:"Detailed help"})).snapshot as string,/First choice/) + const current=await lease() + await navigate(`${base}/read/preview`) + await assert.rejects(current.check(),/document changed|no longer current/i) + await current.end() + await assert.rejects(browser.execute("fixture-session",{action:"snapshot",ref}),/snapshot|page/i) + const hidden=await lease() + await request("fixture.hide") + await assert.rejects(hidden.check(),/current|visible/i) + await hidden.end() + await request("fixture.show") + const closed=await lease() + await request("fixture.close") + await assert.rejects(closed.check(),/current|visible/i) + await closed.end() + checks.push("shared renderer scope/query; navigation/hide/close refuse stale leases and refs") + writeFileSync(join(output,"read-result.json"),JSON.stringify({passed:true,checks},null,2)) + console.error(JSON.stringify({passed:true,checks})) +} +main().then(()=>{parent.close();process.exit(0)},error=>{ + writeFileSync(join(output,"read-result.json"),JSON.stringify({passed:false,checks,error:String(error)},null,2)) + console.error(error);parent.close();process.exit(1) +}) diff --git a/packages/tauri-app/tests/browser-parent/read-fixtures.generated.json b/packages/tauri-app/tests/browser-parent/read-fixtures.generated.json new file mode 100644 index 0000000000..bec4b6ba40 --- /dev/null +++ b/packages/tauri-app/tests/browser-parent/read-fixtures.generated.json @@ -0,0 +1,6 @@ +{ + "preview": "
\n \n \n Pending\n
", + "forms": "
\n \n \n
Old rich
\n \n \n \n
", + "edges": "
\n \n
More
\n
\n \n \n \n \n \n \n
one
two
\n

Mission

\n \n
", + "inputs": "
\n
\n idle\n \n
tall
\n
\n
\n
\n
\n
\n
\n

\n
" +} diff --git a/packages/tauri-app/tests/embedded-webkit-security.test.mjs b/packages/tauri-app/tests/embedded-webkit-security.test.mjs new file mode 100644 index 0000000000..ab3bc75097 --- /dev/null +++ b/packages/tauri-app/tests/embedded-webkit-security.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import test from "node:test" +import { crc32, inflateSync } from "node:zlib" + +const read = (file) => readFileSync(new URL(file, import.meta.url), "utf8") + +test("WKWebView permission classification reaches the native delegate before construction", () => { + const builder = read("../src-tauri/src/embedded_view.rs") + const runtime = read("../vendor/tauri-runtime-wry-2.12.3/src/lib.rs") + const webview = read("../vendor/wry-0.57.1/src/wkwebview/mod.rs") + const delegate = read("../vendor/wry-0.57.1/src/wkwebview/class/wry_web_view_ui_delegate.rs") + const policy = read("../src-tauri/src/embedded_view/browser.rs") + assert.match(builder, /\.on_permission_request\([\s\S]*?current\(&permission_label, token\)[\s\S]*?browser::permission\(view, kind\)[\s\S]*?PermissionResponse::Deny/) + assert.match(policy, /K::Camera \| K::Microphone \| K::Geolocation \| K::Notifications => R::Deny/) + assert.match(policy, /K::ClipboardRead[\s\S]*?K::Autoplay => R::Default/) + assert.match(policy, /_ => \{\s*unknown_permission[\s\S]*?R::Deny/) + assert.match(runtime, /with_permission_handler[\s\S]*?permission_request_handler\(kind\)/) + assert.match(webview, /WryWebViewUIDelegate::new\([\s\S]*?attributes.permission_handler/) + assert.match(delegate, /request_media_capture_permission[\s\S]*?self.ivars\(\).permission_handler[\s\S]*?PermissionResponse::Deny => WKPermissionDecision::Deny/) +}) + +test("WK native context-menu downloads share navigation download policy", () => { + const delegate = read("../vendor/wry-0.57.1/src/wkwebview/class/wry_navigation_delegate.rs") + const download = read("../vendor/wry-0.57.1/src/wkwebview/download.rs") + assert.match(delegate, /method\(_webView:contextMenuDidCreateDownload:\)[\s\S]*?attach_download_delegate\(self, download\)/) + assert.equal((download.match(/attach_download_delegate\(this, download\)/g) ?? []).length, 2) + assert.match(download, /fn attach_download_delegate[\s\S]*?download.setDelegate/) +}) + +test("native download image fixture has valid PNG chunks and a decoded RGBA pixel", () => { + const fixture = read("./webkit-capabilities/fixture.py") + const png = Buffer.from(fixture.match(/PNG_BASE64 = '([^']+)'/)[1], "base64") + assert.equal(png.subarray(0, 8).toString("hex"), "89504e470d0a1a0a") + const compressed = [] + for (let offset = 8; offset < png.length;) { + const size = png.readUInt32BE(offset) + const body = png.subarray(offset + 4, offset + 8 + size) + assert.equal(crc32(body), png.readUInt32BE(offset + 8 + size)) + if (body.subarray(0, 4).toString() === "IDAT") compressed.push(body.subarray(4)) + offset += size + 12 + } + assert.deepEqual(inflateSync(Buffer.concat(compressed)), Buffer.from([0, 255, 0, 255, 255])) +}) + +test("Linux denies protected and unidentified requests and fences classified consent", () => { + const adapter = read("../src-tauri/src/embedded_view/linux.rs") + assert.match(adapter, /connect_permission_request\(move \|page, request\|[\s\S]*?!policy.current\(view.label\(\), token\)[\s\S]*?request.deny\(\)/) + for (const kind of ["GeolocationPermissionRequest", "NotificationPermissionRequest", "UserMediaPermissionRequest", "DeviceInfoPermissionRequest"]) assert.ok(adapter.includes(kind)) + assert.match(adapter, /PointerLockPermissionRequest[\s\S]*?WebsiteDataAccessPermissionRequest/) + assert.match(adapter, /allowed\s*&& epoch.get\(\) == captured[\s\S]*?answer_policy.current\(&answer_label, token\)[\s\S]*?request.allow\(\)/) + assert.match(adapter, /request.deny\(\);\s*super::browser::unknown_permission/) +}) + +test("WebKit guest zoom stays native and precedes primary-window menu fallback", () => { + const main = read("../src-tauri/src/main.rs") + assert.match(main, /on_menu_event\(\|app_handle, event\|[\s\S]*?embedded_view::zoom::focused[\s\S]*?match event.id/) + const zoom = read("../src-tauri/src/embedded_view/zoom.rs") + assert.match(zoom, /label.starts_with\("browser-"\)/) + assert.match(zoom, /guard.current\(&label, token\)/) + assert.doesNotMatch(zoom, /initialization_script|\.eval\(|tauri::command/) + assert.match(read("../src-tauri/src/embedded_view/zoom_macos.m"), /firstResponder[\s\S]*?isDescendantOf:view/) + assert.match(read("../src-tauri/src/embedded_view/zoom_linux.c"), /gtk_window_get_focus[\s\S]*?webkit_web_view_set_zoom_level/) +}) diff --git a/packages/tauri-app/tests/webkit-capabilities/Cargo.toml b/packages/tauri-app/tests/webkit-capabilities/Cargo.toml new file mode 100644 index 0000000000..a34074f286 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "codenomad-webkit-capabilities-fixture" +version = "0.1.0" +edition = "2021" +publish = false + +[[bin]] +name = "codenomad-webkit-capabilities-fixture" +path = "src/main.rs" +test = false + +[dependencies] +tauri = { version = "2.12.5", features = ["devtools", "unstable", "test"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +uuid = { version = "1", features = ["v4"] } +dirs = "5" +tauri-plugin-dialog = "2.8.4" + +[target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.18" +webkit2gtk = "2.0.2" + +[target.'cfg(windows)'.dependencies] +webview2-com = "0.39" +windows-core = "0.62" + +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "0.6.4" + +[dev-dependencies] +tempfile = "3" + +[build-dependencies] +cc = "1" +pkg-config = "0.3" diff --git a/packages/tauri-app/tests/webkit-capabilities/README.md b/packages/tauri-app/tests/webkit-capabilities/README.md new file mode 100644 index 0000000000..69b187caa6 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/README.md @@ -0,0 +1,137 @@ +# Native WebKit capabilities fixture + +Run in a graphical Windows, macOS or Linux session, with the Tauri workspace's locked +dependencies installed. This harness includes the production embedded-view layer +and uses neither a CodeNomad backend nor OpenCode. + +1. Start `python3 tests/webkit-capabilities/fixture.py` from `packages/tauri-app`. +2. Run `CODENOMAD_PROFILE= cargo run --locked -p + codenomad-webkit-capabilities-fixture`. +3. Open **OAuth popup**, then **Finish OAuth**. Expect shared cookie/localStorage + in the round-trip result, `closed: true` and disposal of the native popup. + Also exercise **Target blank** and **Blocked file popup**. +4. Download twice. Check two distinct `*-capabilities-fixture.txt` files in the + system Downloads directory, each containing `webkit-capabilities-download`. + Exercise data downloads and blob downloads where the engine exposes object URLs. +5. Exercise **Dialogs**, accepting and cancelling confirm/prompt. Check the + returned boolean and string/null, including the prompt's default value. + Start a download immediately before opening a dialog to check responsiveness. +6. Exercise **Permissions**. Expect geolocation error 1 and media/notification + rejection or an unavailable API on engines without that API. + +On Linux repeat with `GDK_BACKEND=x11` and `GDK_BACKEND=wayland` in their +corresponding graphical sessions. A nested KWin Wayland compositor supports +native Wayland clients and forwards native pointer/key input from its host window. + +For opener cleanup, set `CODENOMAD_FIXTURE_CLOSE_AFTER=30` (1–60 seconds), then +open **Hold popup for opener cleanup**. The harness closes the production opener +and asserts that both the child view and popup tree disappear within five seconds. +`mac-input.py` supplies native macOS pointer/key/text events for VM trials; +Linux X11 and nested-compositor input can use `xdotool`. + +Windows uses the shared common-controls manifest and a GUI-subsystem release +fixture. Start the page with `node tests/webkit-capabilities/server.mjs`, then build +`cargo build --release --locked -p codenomad-webkit-capabilities-fixture`. +Launch the executable with an isolated absolute `CODENOMAD_PROFILE` directory. +`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--force-renderer-accessibility` enables the +fixture accessibility driver without a fixed debugging port. Run `windows-ui.ps1` +with Windows PowerShell, the fixture PID, `-Invoke ` and +`-NativePointer -Activate` for gesture-sensitive actions; `-Escape` exits browser +fullscreen/pointer lock. The driver restricts actions to this checkout's fixture +and creation-time-fenced descendants. Node/PowerShell console launchers use hidden +windows. App release smoke launches use `src-tauri` as their working directory. + +The **Browser APIs** section additionally exercises blank/named pop-ups, prompt +string/cancel, fullscreen, pointer lock, clipboard consent, beforeunload, print, +file selection/drop and WebAuthn availability. Availability is recorded separately +from authentication success. The page reports absent app IPC/Node globals. + +Electron uses `packages/electron-app/tests/browser-capabilities/fixture.ts` bundled +with esbuild (`--platform=node --format=esm --external:electron`) and run by the +installed Electron executable (`--loader:.css=text` when bundling). Its own profile directory is mandatory. Set +`CODENOMAD_FIXTURE_NETWORK=1` to test a trusted HTTPS page (`example.com`) requesting +the loopback fixture: the permission dialog must identify the HTTPS origin. The +fixture requires `CODENOMAD_FIXTURE_PROMPT_PRELOAD` pointing to the preview-only +`electron/preload/browser-prompt.cjs`. Set `CODENOMAD_FIXTURE_PROMPT_TEST=1` for +assertions covering root/blank-popup prompt strings, empty strings, cancellation, +page-global isolation, suppressed subframe prompts and selection of entry 25. + +For extended qualification, open **Print** and cancel the system print panel; +select a known local fixture through the native file input and drop it on the HTML +zone; open **PDF display** and verify its text, then **PDF download** and verify a +unique 593-byte PDF in Downloads. Arm beforeunload before **Navigate**, **Reload +page** and native closure, testing cancellation and acceptance separately. Record +native closure independently from navigation. **Hardware APIs** reports interface +availability; **WebAuthn availability** reports platform-authenticator availability. + +## Isolated native inputs + +`windows-beforeunload.ps1 -CloseOnly` focuses the native close regression. It +redefines the page's `window.close`, verifies an unarmed popup closes, then +checks that Stay retains an armed popup and Leave closes it. The default run +also covers navigation and reload confirmations. Native closure uses the engine +path independently of page globals on every host. + +Set `CODENOMAD_FIXTURE_CONTROLS=1` and `CODENOMAD_FIXTURE_ZOOM_EVIDENCE=1` for +focused WebKit zoom trials. Native Cmd/Ctrl +, − and 0 and the fixture's **View** +menu exercise the production native zoom handlers and focused-menu routing. +`native-zoom.log` records actual primary/guest page zoom, independently of DOM +viewport reports. Run `assert-zoom.py ` after both key and menu sequences; +`--app-fallback` also checks primary zoom after explicitly focusing the app. +Compile/run `zoom-policy.c` with the system C compiler and `-lm` for range/reset +assertions. The user zoom factor composes with fitted mobile-profile zoom. + +For image downloads, mark the trial start with a file, activate the native image +menu, then run `assert-image-download.py [Downloads-directory]`. +It checks unique UUID names and exact generated PNG bytes. WKWebView context-menu +and navigation downloads share the same native download delegate and policy. + +`CODENOMAD_FIXTURE_LIFETIME` selects `opener-close`, `opener-reload`, +`owner-destroy` or `renderer-reload`. Activate **Lifetime tree**, then **Create +descendant** in its child using native input. The child arms beforeunload and +opens a grandchild. The harness asserts forced descendant disposal, empty +descendant registries and the expected retained/root state, writing the result +inside the isolated profile. A hidden harness window keeps the event loop alive +for assertions after owner destruction. The renderer case replaces the neutral +primary document with the loopback page and uses the production cleanup contract. +Electron's same flag runs the equivalent production-guest assertions directly. + +`CODENOMAD_FIXTURE_CONTROLS=1` opens the focused clipboard, file-picker, +context-menu and viewport probe. The fixture enables Tauri's `devtools` feature, +matching the production application. Native chooser input must target its owned +window; the selected filename is reported by the page's actual FileList. + +Linux fixtures and native file sources share the same session bus. Set `DISPLAY` +before `dbus-run-session` and update its activation environment before launching +portal clients; a portal with a different display can open its print dialog +outside the test display. Use a dedicated Xvfb display and compositor, with native +Wayland clients connected to that compositor's own socket. Capture both client and +server Wayland traces when qualifying pointer lock, including the compositor's +`locked` event to establish effective lock. + +`gtk-file-source.py ` offers a genuine `text/uri-list` drag. +Move inside the destination after its initial drag-enter so WebKit receives a +drag-over before release. `mac-file-source.swift`, built with the system `swiftc`, +offers a native NSURL drag; `mac-input.py drag X Y X Y` sends native mouse events. +On Windows, launch `windows-file-source.ps1 -FixtureProcessId ` in hidden +PowerShell and use `windows-file-drop.ps1` with that source PID and fixture PID. +The source is the checked-in `drop-fixture.txt`; the page reports FileList count +and name. WebKitGTK 2.52.6 reproduces WebKit bug 323277 (CVE-2025-13947 protection) +in both the production layer and a bare native WebKit view. Preserve the engine's +file security policy; uploading through the file input is the available path. + +For reproducible WebView2 beforeunload checks, start a fresh isolated release +fixture, then run `windows-beforeunload.ps1 -FixtureProcessId +-EvidenceDirectory `. It asserts Stay/Leave for navigation, reload +and native popup closure, capturing each stage. The driver admits external-browser +dialog windows only through their live HWND owner chain, restores owned minimized +windows and refuses covered controls before foreground pointer input. + +Electron's `CODENOMAD_FIXTURE_BEFOREUNLOAD_TEST=1` runs equivalent assertions against +the production guest hooks. Set `CODENOMAD_FIXTURE_DIALOG_DRIVER` to the absolute +`linux-answer-beforeunload.sh` path and `CODENOMAD_FIXTURE_EVIDENCE` to an isolated +output directory. The native answer helper needs `xdotool`, ImageMagick and the +fixture's display; it matches both the owning PID and origin-labelled dialog. +Run the test process under an external `timeout` too, since a synchronous native +dialog can block the main JavaScript event loop. These checks cover individual +popup closure; owning-window/opener teardown is recorded independently. diff --git a/packages/tauri-app/tests/webkit-capabilities/assert-image-download.py b/packages/tauri-app/tests/webkit-capabilities/assert-image-download.py new file mode 100644 index 0000000000..7c8b1ba156 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/assert-image-download.py @@ -0,0 +1,25 @@ +"""Assert native context-menu downloads after an owned trial's marker file.""" +import base64 +import hashlib +import json +from pathlib import Path +import sys +import time +import uuid +from fixture import PNG_BASE64 + +marker = Path(sys.argv[1]).stat().st_mtime_ns +expected_count = int(sys.argv[2]) +directory = Path(sys.argv[3]) if len(sys.argv) > 3 else Path.home() / 'Downloads' +expected = base64.b64decode(PNG_BASE64) +for _ in range(100): + files = [p for p in directory.glob('*-image.png') if p.stat().st_mtime_ns >= marker] + if len(files) == expected_count and all(p.read_bytes() == expected for p in files): + break + time.sleep(0.05) +assert len(files) == expected_count, [p.name for p in files] +for path in files: + uuid.UUID(path.name.removesuffix('-image.png')) + assert path.read_bytes() == expected, path.name +print(json.dumps({'files': [p.name for p in files], 'bytes': len(expected), + 'sha256': hashlib.sha256(expected).hexdigest()})) diff --git a/packages/tauri-app/tests/webkit-capabilities/assert-zoom.py b/packages/tauri-app/tests/webkit-capabilities/assert-zoom.py new file mode 100644 index 0000000000..3f3fcc3e19 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/assert-zoom.py @@ -0,0 +1,17 @@ +"""Check actual native app/guest scales after keys and native zoom-menu trials.""" +from pathlib import Path +import re +import sys + +samples = [tuple(map(float, match)) for match in re.findall( + r'app=([0-9.]+) guest=([0-9.]+)', Path(sys.argv[1]).read_text())] +expected = [(1, 1), (1, 1.2), (1, 1), (1, .8), (1, 1), + (1, 1.2), (1, 1), (1, .8), (1, 1)] +remaining = iter(samples) +for wanted in expected: + assert any(sample == wanted for sample in remaining), (wanted, samples) +if '--app-fallback' in sys.argv: + assert (1.2, 1) in samples and samples[-1] == (1, 1), samples +else: + assert all(app == 1 for app, _ in samples), samples +print('PASS native keys/menu in-out-reset, isolated guest zoom; samples=' + str(samples)) diff --git a/packages/tauri-app/tests/webkit-capabilities/build.rs b/packages/tauri-app/tests/webkit-capabilities/build.rs new file mode 100644 index 0000000000..87eea0055d --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/build.rs @@ -0,0 +1,12 @@ +#[path = "../../src-tauri/build_webkit.rs"] +mod build_webkit; +fn main() { + build_webkit::build(std::path::Path::new("../../src-tauri/src/embedded_view")); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let manifest = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()) + .join("../../src-tauri/examples/window_constraints_windows.manifest"); + println!("cargo:rerun-if-changed={}", manifest.display()); + println!("cargo:rustc-link-arg=/MANIFEST:EMBED"); + println!("cargo:rustc-link-arg=/MANIFESTINPUT:{}", manifest.display()); + } +} diff --git a/packages/tauri-app/tests/webkit-capabilities/drop-fixture.txt b/packages/tauri-app/tests/webkit-capabilities/drop-fixture.txt new file mode 100644 index 0000000000..2d450a53c1 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/drop-fixture.txt @@ -0,0 +1 @@ +Native browser file drop fixture. diff --git a/packages/tauri-app/tests/webkit-capabilities/fixture.py b/packages/tauri-app/tests/webkit-capabilities/fixture.py new file mode 100644 index 0000000000..63d6b65913 --- /dev/null +++ b/packages/tauri-app/tests/webkit-capabilities/fixture.py @@ -0,0 +1,135 @@ +"""Loopback-only native browser acceptance page; logs results to stdout.""" +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlsplit +import base64 + +# Generated 1x1 opaque magenta RGBA PNG, including CRCs for every chunk. +PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z/D/PwAG/gL+DHWJ3gAAAABJRU5ErkJggg==' + +PDF_BASE64 = 'JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCAzMDAgMjAwXSAvUmVzb3VyY2VzIDw8IC9Gb250IDw8IC9GMSA0IDAgUiA+PiA+PiAvQ29udGVudHMgNSAwIFIgPj4KZW5kb2JqCjQgMCBvYmoKPDwgL1R5cGUgL0ZvbnQgL1N1YnR5cGUgL1R5cGUxIC9CYXNlRm9udCAvSGVsdmV0aWNhID4+CmVuZG9iago1IDAgb2JqCjw8IC9MZW5ndGggNDkgPj4Kc3RyZWFtCkJUIC9GMSAxNiBUZiAzMCAxMDAgVGQgKE5hdGl2ZSBwcmV2aWV3IFBERikgVGogRVQKZW5kc3RyZWFtCmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMDkgMDAwMDAgbiAKMDAwMDAwMDA1OCAwMDAwMCBuIAowMDAwMDAwMTE1IDAwMDAwIG4gCjAwMDAwMDAyNDEgMDAwMDAgbiAKMDAwMDAwMDMxMSAwMDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDYgL1Jvb3QgMSAwIFIgPj4Kc3RhcnR4cmVmCjQxMAolJUVPRgo=' + +PAGE = b'''WebKit capabilities + + +Target blank +Download + + + + + +Data download + +
Browser APIs + + + + + + + +Navigate + + + + + +
Drop file
+ + +PDF displayPDF download +
+Additional controls +
'''
+POPUP = b'''OAuth fixture'''
+LIFETIME = b'''Lifetime child'''
+CONTROLS = b'''Additional controls
+
+
+
+
+
+Context link
+Context image
+PDF display + +
'''
+
+class Handler(BaseHTTPRequestHandler):
+    def end_headers(self):
+        self.send_header('Access-Control-Allow-Origin', '*')
+        self.send_header('Access-Control-Allow-Private-Network', 'true')
+        super().end_headers()
+
+    def do_OPTIONS(self):
+        self.send_response(204)
+        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
+        self.send_header('Access-Control-Allow-Headers', '*')
+        self.end_headers()
+
+    def do_GET(self):
+        route = urlsplit(self.path).path
+        if route == '/image.png':
+            body = base64.b64decode(PNG_BASE64)
+            self.send_response(200)
+            self.send_header('Content-Type', 'image/png')
+            self.end_headers()
+            self.wfile.write(body)
+            return
+        if route in ('/pdf', '/pdf-download'):
+            body = base64.b64decode(PDF_BASE64)
+            self.send_response(200)
+            self.send_header('Content-Type', 'application/pdf')
+            if route == '/pdf-download':
+                self.send_header('Content-Disposition', 'attachment; filename="capabilities-fixture.pdf"')
+            self.send_header('Content-Length', str(len(body)))
+            self.end_headers()
+            self.wfile.write(body)
+            return
+        if route == '/download':
+            body = b'webkit-capabilities-download\n'
+            self.send_response(200)
+            self.send_header('Content-Type', 'application/octet-stream')
+            self.send_header('Content-Disposition', 'attachment; filename="capabilities-fixture.txt"')
+            self.send_header('Content-Length', str(len(body)))
+            self.end_headers()
+            self.wfile.write(body)
+            return
+        body = CONTROLS if route == '/controls' else LIFETIME if route == '/lifetime-child' else POPUP if route == '/popup' else b'Held popupheld' if route == '/hold' else PAGE
+        self.send_response(200)
+        self.send_header('Content-Type', 'text/html; charset=utf-8')
+        self.send_header('Content-Length', str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+
+if __name__ == '__main__':
+    ThreadingHTTPServer(('127.0.0.1', 18741), Handler).serve_forever()
diff --git a/packages/tauri-app/tests/webkit-capabilities/gtk-file-source.py b/packages/tauri-app/tests/webkit-capabilities/gtk-file-source.py
new file mode 100644
index 0000000000..ff50d876ac
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/gtk-file-source.py
@@ -0,0 +1,27 @@
+"""Native file drag source for the isolated Linux engine fixture."""
+import pathlib
+import sys
+import gi
+
+gi.require_version('Gtk', '3.0')
+gi.require_version('Gdk', '3.0')
+from gi.repository import Gdk, Gtk
+
+uri = pathlib.Path(sys.argv[1]).resolve(strict=True).as_uri()
+window = Gtk.Window(title='Capabilities file source')
+window.set_default_size(160, 80)
+window.move(1110, 100)
+button = Gtk.Button(label='Drag fixture file')
+button.drag_source_set(Gdk.ModifierType.BUTTON1_MASK,
+                       [Gtk.TargetEntry.new('text/uri-list', 0, 0)], Gdk.DragAction.COPY)
+button.connect('drag-begin', lambda *_: print('drag-begin', flush=True))
+button.connect('drag-end', lambda *_: print('drag-end', flush=True))
+button.connect('drag-failed', lambda _button, _context, result: print('drag-failed', result.value_nick, flush=True) or False)
+def provide(_button, _context, data, _info, _time):
+    data.set_uris([uri])
+    print('drag-data-get', data.get_target().name(), bytes(data.get_data()), flush=True)
+button.connect('drag-data-get', provide)
+window.add(button)
+window.connect('destroy', Gtk.main_quit)
+window.show_all()
+Gtk.main()
diff --git a/packages/tauri-app/tests/webkit-capabilities/linux-answer-beforeunload.sh b/packages/tauri-app/tests/webkit-capabilities/linux-answer-beforeunload.sh
new file mode 100644
index 0000000000..255554f3f6
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/linux-answer-beforeunload.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Answer only the fixture process's origin-labelled native dialog on its display.
+set -eu
+answer=$1
+pid=$2
+output=$3
+case "$answer" in stay|leave) ;; *) exit 2;; esac
+[[ "$pid" =~ ^[0-9]+$ ]] && [[ "$output" = /* ]] && test -n "${DISPLAY:-}"
+window=$(timeout 10s xdotool search --all --sync --onlyvisible --pid "$pid" --name '^http://127\.0\.0\.1:18741/' | head -n 1)
+while IFS='=' read -r key value; do
+  case "$key" in X|Y|WIDTH|HEIGHT)
+    [[ "$value" =~ ^-?[0-9]+$ ]] || exit 2
+    printf -v "$key" '%s' "$value";;
+  esac
+done < <(xdotool getwindowgeometry --shell "$window")
+import -window "$window" "$output"
+x=$((WIDTH / 4))
+test "$answer" = stay || x=$((WIDTH * 3 / 4))
+xdotool windowfocus "$window" mousemove --sync --window "$window" "$x" "$((HEIGHT - 23))" click 1
diff --git a/packages/tauri-app/tests/webkit-capabilities/mac-file-source.swift b/packages/tauri-app/tests/webkit-capabilities/mac-file-source.swift
new file mode 100644
index 0000000000..641107a228
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/mac-file-source.swift
@@ -0,0 +1,37 @@
+// Native NSURL drag source, built with `swiftc mac-file-source.swift -o file-source`.
+import AppKit
+
+final class FileSource: NSView, NSDraggingSource {
+    let file: URL
+    init(file: URL) {
+        self.file = file
+        super.init(frame: NSRect(x: 0, y: 0, width: 200, height: 80))
+    }
+    required init?(coder: NSCoder) { fatalError("Use init(file:)") }
+    override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+    override func draw(_ dirtyRect: NSRect) {
+        ("Drag fixture file" as NSString).draw(at: NSPoint(x: 30, y: 35), withAttributes: nil)
+    }
+    override func mouseDown(with event: NSEvent) {
+        let item = NSDraggingItem(pasteboardWriter: file as NSURL)
+        item.setDraggingFrame(bounds, contents: NSImage(named: NSImage.multipleDocumentsName))
+        beginDraggingSession(with: [item], event: event, source: self)
+    }
+    func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .copy }
+    func draggingSession(_ session: NSDraggingSession, endedAt point: NSPoint, operation: NSDragOperation) {
+        print("drag-end \(operation.rawValue)")
+        fflush(stdout)
+    }
+}
+
+let file = URL(fileURLWithPath: CommandLine.arguments[1]).standardizedFileURL
+precondition(FileManager.default.fileExists(atPath: file.path))
+let app = NSApplication.shared
+app.setActivationPolicy(.accessory)
+let window = NSWindow(contentRect: NSRect(x: 800, y: 30, width: 200, height: 80),
+                      styleMask: [.titled, .closable], backing: .buffered, defer: false)
+window.title = "Capabilities file source"
+window.level = .floating
+window.contentView = FileSource(file: file)
+window.makeKeyAndOrderFront(nil)
+app.run()
diff --git a/packages/tauri-app/tests/webkit-capabilities/mac-input.py b/packages/tauri-app/tests/webkit-capabilities/mac-input.py
new file mode 100644
index 0000000000..d8f551e67d
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/mac-input.py
@@ -0,0 +1,58 @@
+"""Native VM input helper: click/right-click X Y, key virtual-keycode, or text VALUE."""
+import ctypes as c
+import sys
+import time
+
+class Point(c.Structure):
+    _fields_ = [('x', c.c_double), ('y', c.c_double)]
+
+cg = c.CDLL('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics')
+cf = c.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')
+cg.CGEventCreateMouseEvent.argtypes = [c.c_void_p, c.c_uint32, Point, c.c_uint32]
+cg.CGEventCreateMouseEvent.restype = c.c_void_p
+cg.CGEventCreateKeyboardEvent.argtypes = [c.c_void_p, c.c_uint16, c.c_bool]
+cg.CGEventCreateKeyboardEvent.restype = c.c_void_p
+cg.CGEventKeyboardSetUnicodeString.argtypes = [c.c_void_p, c.c_ulong, c.c_void_p]
+cg.CGEventPost.argtypes = [c.c_uint32, c.c_void_p]
+cg.CGEventSetFlags.argtypes = [c.c_void_p, c.c_uint64]
+cf.CFRelease.argtypes = [c.c_void_p]
+
+def post(event):
+    cg.CGEventPost(0, event)
+    cf.CFRelease(event)
+    time.sleep(0.05)
+
+if sys.argv[1] in ('click', 'right-click'):
+    point = Point(float(sys.argv[2]), float(sys.argv[3]))
+    right = sys.argv[1] == 'right-click'
+    for kind in ((5, 3, 4) if right else (5, 1, 2)):
+        post(cg.CGEventCreateMouseEvent(None, kind, point, 1 if right else 0))
+elif sys.argv[1] == 'key':
+    for down in (True, False):
+        event = cg.CGEventCreateKeyboardEvent(None, int(sys.argv[2]), down)
+        cg.CGEventSetFlags(event, 0)
+        post(event)
+elif sys.argv[1] == 'chord':
+    for down in (True, False):
+        event = cg.CGEventCreateKeyboardEvent(None, int(sys.argv[3]), down)
+        cg.CGEventSetFlags(event, int(sys.argv[2], 0) if down else 0)
+        post(event)
+elif sys.argv[1] == 'drag':
+    x, y, end_x, end_y = map(float, sys.argv[2:6])
+    post(cg.CGEventCreateMouseEvent(None, 5, Point(x, y), 0))
+    post(cg.CGEventCreateMouseEvent(None, 1, Point(x, y), 0))
+    for step in range(1, 31):
+        point = Point(x + (end_x - x) * step / 30, y + (end_y - y) * step / 30)
+        post(cg.CGEventCreateMouseEvent(None, 6, point, 0))
+    post(cg.CGEventCreateMouseEvent(None, 2, Point(end_x, end_y), 0))
+elif sys.argv[1] == 'text':
+    for character in sys.argv[2]:
+        text = character.encode('utf-16-le')
+        buf = c.create_string_buffer(text)
+        for down in (True, False):
+            event = cg.CGEventCreateKeyboardEvent(None, 0, down)
+            cg.CGEventSetFlags(event, 0)
+            cg.CGEventKeyboardSetUnicodeString(event, len(text) // 2, buf)
+            post(event)
+else:
+    raise ValueError('click, right-click, key, chord, drag or text required')
diff --git a/packages/tauri-app/tests/webkit-capabilities/server.mjs b/packages/tauri-app/tests/webkit-capabilities/server.mjs
new file mode 100644
index 0000000000..2fd052fcae
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/server.mjs
@@ -0,0 +1,31 @@
+// Node launcher for the same acceptance page used by fixture.py (Windows hosts).
+import { readFileSync } from "node:fs"
+import { createServer } from "node:http"
+const source = readFileSync(new URL("./fixture.py", import.meta.url), "utf8")
+const page = source.match(/PAGE = b'''([\s\S]*?)'''/)[1].replaceAll("\\\\", "\\")
+const popup = source.match(/POPUP = b'''([\s\S]*?)'''/)[1]
+const lifetime = source.match(/LIFETIME = b'''([\s\S]*?)'''/)[1]
+const controls = source.match(/CONTROLS = b'''([\s\S]*?)'''/)[1].replaceAll("\\\\", "\\")
+const pdf = Buffer.from(source.match(/PDF_BASE64 = '([^']+)'/)[1], 'base64')
+createServer((request, response) => {
+  console.log(request.method, request.url)
+  response.setHeader("Access-Control-Allow-Origin", "*")
+  response.setHeader("Access-Control-Allow-Private-Network", "true")
+  response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS")
+  response.setHeader("Access-Control-Allow-Headers", "*")
+  if (request.method === "OPTIONS") { response.writeHead(204); response.end(); return }
+  const route = new URL(request.url, "http://127.0.0.1:18741").pathname
+  if (route === "/image.png") {
+    response.setHeader("Content-Type", "image/png")
+    response.end(Buffer.from(source.match(/PNG_BASE64 = '([^']+)'/)[1], 'base64'))
+    return
+  }
+  const download = route === "/download"
+  const pdfRoute = route === "/pdf" || route === "/pdf-download"
+  const body = pdfRoute ? pdf : download ? "webkit-capabilities-download\n" : route === "/controls" ? controls : route === "/lifetime-child" ? lifetime : route === "/popup" ? popup : route === "/hold" ? "held" : page
+  response.setHeader("Content-Type", pdfRoute ? "application/pdf" : download ? "application/octet-stream" : "text/html; charset=utf-8")
+  if (route === "/pdf-download") response.setHeader("Content-Disposition", 'attachment; filename="capabilities-fixture.pdf"')
+  if (download) response.setHeader("Content-Disposition", 'attachment; filename="capabilities-fixture.txt"')
+  response.setHeader("Content-Length", Buffer.byteLength(body))
+  response.end(body)
+}).listen(18741, "127.0.0.1")
diff --git a/packages/tauri-app/tests/webkit-capabilities/src/main.rs b/packages/tauri-app/tests/webkit-capabilities/src/main.rs
new file mode 100644
index 0000000000..658ee23aff
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/src/main.rs
@@ -0,0 +1,360 @@
+//! Isolated real-engine harness: no backend, daemon or application commands.
+//! Start fixture.py, then cargo run -p codenomad-webkit-capabilities-fixture.
+#![allow(dead_code)]
+#![cfg_attr(windows, windows_subsystem = "windows")]
+#[path = "../../../src-tauri/src/embedded_view.rs"]
+#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
+mod embedded_view;
+#[path = "../../../src-tauri/src/menu_labels.rs"]
+mod menu_labels;
+struct AppState {
+    menu_labels: menu_labels::MenuLabels,
+}
+#[cfg(windows)]
+#[path = "../../../src-tauri/src/windows_browser_accelerators.rs"]
+mod windows_browser_accelerators;
+
+// The harness has one fixed local owner; production uses identity.rs.
+mod identity {
+    pub fn local_window_id(label: &str) -> Result {
+        (label == super::OWNER)
+            .then(|| label.into())
+            .ok_or_else(|| "Invalid fixture owner".into())
+    }
+}
+
+#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
+use tauri::Manager;
+const OWNER: &str = "local-11111111-1111-4111-8111-111111111111";
+
+#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
+fn main() {}
+
+#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
+fn main() {
+    let root =
+        std::env::var_os("CODENOMAD_PROFILE").expect("set an isolated CODENOMAD_PROFILE directory");
+    let root = std::path::PathBuf::from(root);
+    std::fs::create_dir_all(&root).unwrap();
+    let log = root.join("stages.log");
+    std::fs::write(&log, "main\n").unwrap();
+    let panic_log = log.clone();
+    std::panic::set_hook(Box::new(move |panic| {
+        let _ = std::fs::write(&panic_log, panic.to_string());
+    }));
+    tauri::Builder::default()
+        .plugin(tauri_plugin_dialog::init())
+        .manage(embedded_view::StorageIdentity::new(
+            root.to_string_lossy().into(),
+            "capabilities-fixture".into(),
+        ))
+        .manage(embedded_view::EmbeddedViews::default())
+        .on_menu_event(|app, event| {
+            #[cfg(windows)]
+            let _ = (app, event);
+            #[cfg(any(target_os = "linux", target_os = "macos"))]
+            if embedded_view::zoom::focused(app, event.id().0.as_str()) {
+                return;
+            }
+            // Fixture-only primary fallback, so native menu routing can be qualified.
+            #[cfg(any(target_os = "linux", target_os = "macos"))]
+            if let Some(primary) = app.get_webview(OWNER) {
+                if let Ok((current, device)) = embedded_view::mobile::scale(&primary) {
+                    let next = match event.id().0.as_str() {
+                        "zoom_in" => current / device + 0.2,
+                        "zoom_out" => current / device - 0.2,
+                        "reset_zoom" => 1.0,
+                        _ => return,
+                    };
+                    let _ = primary.set_zoom(next.clamp(0.25, 5.0));
+                }
+            }
+        })
+        .setup(move |app| {
+            #[cfg(any(target_os = "linux", target_os = "macos"))]
+            {
+                use tauri::menu::{Menu, MenuItem, Submenu};
+                let zoom_in =
+                    MenuItem::with_id(app, "zoom_in", "Zoom In", true, Some("CmdOrCtrl+="))?;
+                let zoom_out =
+                    MenuItem::with_id(app, "zoom_out", "Zoom Out", true, Some("CmdOrCtrl+-"))?;
+                let zoom_reset =
+                    MenuItem::with_id(app, "reset_zoom", "Reset Zoom", true, Some("CmdOrCtrl+0"))?;
+                let view =
+                    Submenu::with_items(app, "View", true, &[&zoom_in, &zoom_out, &zoom_reset])?;
+                app.set_menu(Menu::with_items(app, &[&view])?)?;
+            }
+            std::fs::write(&log, "setup\n").unwrap();
+            let window = tauri::WebviewWindowBuilder::new(
+                app,
+                OWNER,
+                tauri::WebviewUrl::External("about:blank".parse().unwrap()),
+            )
+            .title("WebKit capabilities fixture")
+            .data_directory(root.join("renderer"))
+            .on_page_load(|view, payload| {
+                if matches!(payload.event(), tauri::webview::PageLoadEvent::Started) {
+                    view.app_handle()
+                        .state::()
+                        .remove_owner(view.app_handle(), OWNER);
+                }
+            })
+            .inner_size(900.0, 740.0)
+            .build()?;
+            std::fs::write(&log, "primary ready\n").unwrap();
+            let views = app.state::();
+            let guest = views.create(
+                &window.as_ref().window(),
+                "browser-fixture",
+                root.join("browser"),
+                embedded_view::Bounds {
+                    x: 0,
+                    y: 0,
+                    width: 880,
+                    height: 700,
+                },
+                |_, _| {},
+                |_| true,
+            )?;
+            std::fs::write(&log, "guest ready\n").unwrap();
+            #[cfg(windows)]
+            {
+                let events = root.join("events.log");
+                guest.with_webview(move |platform| unsafe {
+                    use webview2_com::Microsoft::Web::WebView2::Win32::*;
+                    use webview2_com::{
+                        NavigationStartingEventHandler, PermissionRequestedEventHandler,
+                    };
+                    let core = platform.controller().CoreWebView2().unwrap();
+                    let permission_log = events.clone();
+                    core.add_PermissionRequested(
+                        &PermissionRequestedEventHandler::create(Box::new(move |_, args| {
+                            if let Some(args) = args {
+                                use std::io::Write;
+                                let mut kind = COREWEBVIEW2_PERMISSION_KIND::default();
+                                let mut state = COREWEBVIEW2_PERMISSION_STATE::default();
+                                args.PermissionKind(&mut kind)?;
+                                args.State(&mut state)?;
+                                let _ = writeln!(
+                                    std::fs::OpenOptions::new()
+                                        .create(true)
+                                        .append(true)
+                                        .open(&permission_log)
+                                        .unwrap(),
+                                    "permission {} state {}",
+                                    kind.0,
+                                    state.0
+                                );
+                            }
+                            Ok(())
+                        })),
+                        &mut 0,
+                    )
+                    .unwrap();
+                    core.add_NavigationStarting(
+                        &NavigationStartingEventHandler::create(Box::new(move |_, args| {
+                            if let Some(args) = args {
+                                use std::io::Write;
+                                let mut uri = windows_core::PWSTR::null();
+                                args.Uri(&mut uri)?;
+                                let mut cancelled = Default::default();
+                                args.Cancel(&mut cancelled)?;
+                                let uri = webview2_com::take_pwstr(uri);
+                                let _ = writeln!(
+                                    std::fs::OpenOptions::new()
+                                        .create(true)
+                                        .append(true)
+                                        .open(&events)
+                                        .unwrap(),
+                                    "navigation {} cancelled={:?}",
+                                    uri.chars().take(250).collect::(),
+                                    cancelled
+                                );
+                            }
+                            Ok(())
+                        })),
+                        &mut 0,
+                    )
+                    .unwrap();
+                })?;
+            }
+            guest.navigate(
+                if std::env::var_os("CODENOMAD_FIXTURE_CONTROLS").is_some() {
+                    "http://127.0.0.1:18741/controls"
+                } else {
+                    "http://127.0.0.1:18741/"
+                }
+                .parse()
+                .unwrap(),
+            )?;
+            guest.show()?;
+            #[cfg(any(target_os = "linux", target_os = "macos"))]
+            if std::env::var_os("CODENOMAD_FIXTURE_ZOOM_EVIDENCE").is_some() {
+                let primary: tauri::Webview = window.as_ref().clone();
+                let preview = guest.clone();
+                let output = root.join("native-zoom.log");
+                std::thread::spawn(move || {
+                    use std::io::Write;
+                    let mut previous = None;
+                    for _ in 0..3000 {
+                        let Ok((app, device)) = embedded_view::mobile::scale(&primary) else {
+                            break;
+                        };
+                        let Ok((guest, guest_device)) = embedded_view::mobile::scale(&preview)
+                        else {
+                            break;
+                        };
+                        let sample = (app / device, guest / guest_device);
+                        if previous != Some(sample) {
+                            writeln!(
+                                std::fs::OpenOptions::new()
+                                    .create(true)
+                                    .append(true)
+                                    .open(&output)
+                                    .unwrap(),
+                                "app={:.6} guest={:.6}",
+                                sample.0,
+                                sample.1
+                            )
+                            .unwrap();
+                            previous = Some(sample);
+                        }
+                        std::thread::sleep(std::time::Duration::from_millis(200));
+                    }
+                });
+            }
+            if let Ok(mode) = std::env::var("CODENOMAD_FIXTURE_LIFETIME") {
+                assert!([
+                    "opener-close",
+                    "opener-reload",
+                    "owner-destroy",
+                    "renderer-reload"
+                ]
+                .contains(&mode.as_str()));
+                // A hidden harness window keeps the event loop alive after owner destruction.
+                let _sentinel = tauri::WebviewWindowBuilder::new(
+                    app,
+                    "fixture-sentinel",
+                    tauri::WebviewUrl::External("about:blank".parse().unwrap()),
+                )
+                .visible(false)
+                .build()?;
+                let policy = views.inner().clone();
+                let handle = app.handle().clone();
+                let primary = window.clone();
+                let target = guest.clone();
+                let evidence = root.join(format!("lifetime-{mode}.txt"));
+                std::thread::spawn(move || {
+                    let trial = || -> Result<(), String> {
+                        // The page and its child are activated with native fixture input.
+                        let mut labels = Vec::new();
+                        for _ in 0..1200 {
+                            labels = handle
+                                .windows()
+                                .keys()
+                                .filter(|label| label.starts_with("browser-popup-"))
+                                .cloned()
+                                .collect();
+                            if labels.len() >= 2 {
+                                break;
+                            }
+                            std::thread::sleep(std::time::Duration::from_millis(50));
+                        }
+                        if labels.len() != 2 {
+                            return Err(format!(
+                                "expected two nested native popups, got {}",
+                                labels.len()
+                            ));
+                        }
+                        match mode.as_str() {
+                            "opener-close" => policy.close(&handle, OWNER, "browser-fixture")?,
+                            "opener-reload" => target.reload().map_err(|e| e.to_string())?,
+                            "owner-destroy" => primary.destroy().map_err(|e| e.to_string())?,
+                            "renderer-reload" => primary
+                                .navigate(
+                                    "http://127.0.0.1:18741/primary-replacement"
+                                        .parse()
+                                        .unwrap(),
+                                )
+                                .map_err(|e| e.to_string())?,
+                            _ => unreachable!(),
+                        }
+                        let retained = mode == "opener-reload";
+                        for _ in 0..200 {
+                            if labels.iter().all(|label| {
+                                handle.get_webview_window(label).is_none()
+                                    && policy.navigation_allowed(
+                                        label,
+                                        &"https://example.com".parse().unwrap(),
+                                    ) == Some(false)
+                            }) && policy.navigation_allowed(
+                                "browser-fixture",
+                                &"https://example.com".parse().unwrap(),
+                            ) == Some(retained)
+                            {
+                                break;
+                            }
+                            std::thread::sleep(std::time::Duration::from_millis(50));
+                        }
+                        for label in &labels {
+                            if handle.get_webview_window(label).is_some() {
+                                return Err(format!("orphan native window {label}"));
+                            }
+                            if policy
+                                .navigation_allowed(label, &"https://example.com".parse().unwrap())
+                                != Some(false)
+                            {
+                                return Err(format!("orphan registry {label}"));
+                            }
+                        }
+                        if policy.navigation_allowed(
+                            "browser-fixture",
+                            &"https://example.com".parse().unwrap(),
+                        ) != Some(retained)
+                        {
+                            return Err("root registry mismatch".into());
+                        }
+                        Ok(())
+                    };
+                    let result = trial();
+                    std::fs::write(evidence, format!("{mode}: {result:?}\n")).unwrap();
+                    handle.exit(if result.is_ok() { 0 } else { 1 });
+                });
+            }
+            if let Ok(seconds) = std::env::var("CODENOMAD_FIXTURE_CLOSE_AFTER")
+                .unwrap_or_default()
+                .parse::()
+            {
+                assert!((1..=60).contains(&seconds));
+                let policy = views.inner().clone();
+                let handle = app.handle().clone();
+                std::thread::spawn(move || {
+                    std::thread::sleep(std::time::Duration::from_secs(seconds));
+                    policy.close(&handle, OWNER, "browser-fixture").unwrap();
+                    for _ in 0..100 {
+                        if handle.get_webview("browser-fixture").is_none()
+                            && handle
+                                .windows()
+                                .keys()
+                                .all(|label| !label.starts_with("browser-popup-"))
+                        {
+                            eprintln!("opener and popup tree disposed");
+                            return;
+                        }
+                        std::thread::sleep(std::time::Duration::from_millis(50));
+                    }
+                    panic!("opener or popup tree survived closure");
+                });
+            }
+            let policy = views.inner().clone();
+            let handle = app.handle().clone();
+            window.on_window_event(move |event| {
+                if matches!(event, tauri::WindowEvent::Destroyed) {
+                    policy.remove_owner(&handle, OWNER);
+                }
+            });
+            Ok(())
+        })
+        .run(tauri::test::mock_context(tauri::test::noop_assets()))
+        .unwrap();
+}
diff --git a/packages/tauri-app/tests/webkit-capabilities/windows-beforeunload.ps1 b/packages/tauri-app/tests/webkit-capabilities/windows-beforeunload.ps1
new file mode 100644
index 0000000000..c827660375
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/windows-beforeunload.ps1
@@ -0,0 +1,109 @@
+# Run against a fresh isolated release fixture and its loopback acceptance page.
+param([Parameter(Mandatory=$true)][int]$FixtureProcessId,
+      [Parameter(Mandatory=$true)][string]$EvidenceDirectory,
+      [switch]$CloseOnly)
+$ErrorActionPreference = 'Stop'
+$driver = Join-Path $PSScriptRoot 'windows-ui.ps1'
+$null = New-Item -ItemType Directory -Path $EvidenceDirectory
+function Read-Fixture([switch]$Popup) { (& $driver -FixtureProcessId $FixtureProcessId -Popup:$Popup) -join "`n" }
+function Save-State([string]$Name,[switch]$Popup) { Read-Fixture -Popup:$Popup | Set-Content -Encoding UTF8 (Join-Path $EvidenceDirectory "$Name.txt") }
+function Wait-State([scriptblock]$Predicate,[switch]$Popup) {
+ $deadline = [DateTime]::UtcNow.AddSeconds(10)
+ do {
+  try { $text = Read-Fixture -Popup:$Popup }
+  catch {
+   if (!$Popup -or $_.Exception.Message -ne 'Expected one owned fixture popup') { throw }
+   [Threading.Thread]::Sleep(100)
+   continue
+  }
+  if (& $Predicate $text) { return }
+  [Threading.Thread]::Sleep(100)
+ } while ([DateTime]::UtcNow -lt $deadline)
+ throw 'Expected native fixture state did not appear'
+}
+function Page-Action([string]$Name) {
+ if($CloseOnly){ & $driver -FixtureProcessId $FixtureProcessId -Popup -Invoke $Name }
+ else { & $driver -FixtureProcessId $FixtureProcessId -Popup -Invoke $Name -NativePointer -Activate }
+}
+function Open-TestPopup {
+ if($CloseOnly){ & $driver -FixtureProcessId $FixtureProcessId -Invoke 'Close-test popup' }
+ else { & $driver -FixtureProcessId $FixtureProcessId -Invoke 'Close-test popup' -NativePointer -Activate }
+}
+function Dialog-Action([string]$Name) { & $driver -FixtureProcessId $FixtureProcessId -Invoke $Name }
+function Wait-LeaveDialog { Wait-State { param($t) $t.Contains('WINDOW | Quitter le site') } }
+function Wait-ReloadDialog { Wait-State { param($t) $t.Contains('WINDOW | Recharger le site') } }
+function Cancel-Dialog {
+ Dialog-Action 'Annuler'
+ Wait-State { param($t) !$t.Contains('WINDOW | Quitter le site') -and !$t.Contains('WINDOW | Recharger le site') }
+}
+function Wait-FreshPage { Wait-State -Popup { param($t) $t.Contains('isolation:') -and !$t.Contains('beforeunload: armed') } }
+function Close-Popup {
+ . $driver -FixtureProcessId $FixtureProcessId -Popup | Out-Null
+ $handle = [IntPtr]$roots[0].Current.NativeWindowHandle
+ if ($handle -eq [IntPtr]::Zero) { throw 'Owned fixture popup has no HWND' }
+ if (!('BeforeUnloadCloseInput' -as [type])) { Add-Type @'
+using System; using System.Runtime.InteropServices;
+public static class BeforeUnloadCloseInput { [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h,uint m,IntPtr w,IntPtr l); }
+'@ }
+ if (![BeforeUnloadCloseInput]::PostMessage($handle,16,[IntPtr]::Zero,[IntPtr]::Zero)) { throw 'Owned popup close input refused' }
+}
+function Wait-PopupGone { Wait-State { param($t) !$t.Contains('ControlType.Window | http://127.0.0.1:18741') -and !$t.Contains('WINDOW | http://127.0.0.1:18741') } }
+
+if ((Read-Fixture).Contains('beforeunload: armed')) { throw 'Use a fresh fixture' }
+Open-TestPopup
+Wait-FreshPage
+Page-Action 'Override window.close'
+Wait-State -Popup { param($t) $t.Contains('close-override: ()=>{}') }
+Save-State 'close-override-no-unload' -Popup
+Close-Popup
+Wait-PopupGone
+Save-State 'close-override-no-unload-complete'
+Open-TestPopup
+Wait-FreshPage
+if (!$CloseOnly) {
+Page-Action 'Arm beforeunload'
+Page-Action 'Navigate'
+Wait-LeaveDialog
+Save-State 'navigation-confirm'
+Cancel-Dialog
+Wait-State -Popup { param($t) $t.Contains('beforeunload: armed') }
+Save-State 'navigation-stay' -Popup
+
+Page-Action 'Reload page'
+Wait-ReloadDialog
+Save-State 'reload-confirm'
+Cancel-Dialog
+Save-State 'reload-stay' -Popup
+if (!(Read-Fixture -Popup).Contains('beforeunload: armed')) { throw 'Stay discarded the page' }
+Page-Action 'Reload page'
+Wait-ReloadDialog
+Dialog-Action 'Recharger'
+Wait-FreshPage
+Save-State 'reload-leave' -Popup
+
+Page-Action 'Arm beforeunload'
+Page-Action 'Navigate'
+Wait-LeaveDialog
+Dialog-Action 'Quitter'
+Wait-FreshPage
+Save-State 'navigation-leave' -Popup
+}
+
+Page-Action 'Override window.close'
+Wait-State -Popup { param($t) $t.Contains('close-override: ()=>{}') }
+Save-State 'close-override' -Popup
+Page-Action 'Arm beforeunload'
+Wait-State -Popup { param($t) $t.Contains('beforeunload: armed') -and $t.Contains('activation: true') }
+Close-Popup
+Wait-LeaveDialog
+Save-State 'close-confirm'
+Cancel-Dialog
+Wait-State -Popup { param($t) $t.Contains('beforeunload: armed') }
+Save-State 'close-stay' -Popup
+Close-Popup
+Wait-LeaveDialog
+Dialog-Action 'Quitter'
+Wait-PopupGone
+Save-State 'close-leave'
+$cases = if($CloseOnly){'popup-close'}else{'navigation/reload/popup-close'}
+Write-Output "PASS native beforeunload ${cases}: Stay preserves and Leave completes even after window.close redefinition; unarmed overridden popup closes too; evidence=$EvidenceDirectory"
diff --git a/packages/tauri-app/tests/webkit-capabilities/windows-file-drop.ps1 b/packages/tauri-app/tests/webkit-capabilities/windows-file-drop.ps1
new file mode 100644
index 0000000000..0c0c9fdd07
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/windows-file-drop.ps1
@@ -0,0 +1,39 @@
+# Native mouse input, fenced to the owned source and the isolated fixture.
+param([Parameter(Mandatory=$true)][int]$FixtureProcessId,
+      [Parameter(Mandatory=$true)][int]$SourceProcessId)
+$ErrorActionPreference = 'Stop'
+. "$PSScriptRoot/windows-ui.ps1" -FixtureProcessId $FixtureProcessId | Out-Null
+$source = Get-CimInstance Win32_Process -Filter "ProcessId=$SourceProcessId"
+$sourceScript = Join-Path $PSScriptRoot 'windows-file-source.ps1'
+if ($source.CommandLine.Replace('/', '\') -notlike "*$sourceScript*") { throw 'Expected the owned native file source' }
+$sourceProcess = Get-Process -Id $SourceProcessId
+$sourceRoot = [System.Windows.Automation.AutomationElement]::FromHandle($sourceProcess.MainWindowHandle)
+$button = $sourceRoot.FindFirst([System.Windows.Automation.TreeScope]::Descendants,
+  [System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::NameProperty, 'Drag fixture file'))
+$target = $roots | ForEach-Object { $_.FindAll([System.Windows.Automation.TreeScope]::Descendants,
+  [System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::NameProperty, 'Drop file')) } | Select-Object -First 1
+if (!$button -or !$target -or $target.Current.IsOffscreen) { throw 'Visible fixture drag endpoints unavailable' }
+Add-Type @'
+using System; using System.Runtime.InteropServices;
+public static class NativeFileDrag {
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y);
+ [DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint x,uint y,uint data,UIntPtr extra);
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
+ [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
+}
+'@
+$dpi = [NativeFileDrag]::SetThreadDpiAwarenessContext([IntPtr](-4))
+try {
+ $start=$button.Current.BoundingRectangle; $end=$target.Current.BoundingRectangle
+ $sx=[int]($start.X+$start.Width/2); $sy=[int]($start.Y+$start.Height/2)
+ $ex=[int]($end.X+[Math]::Min(30,$end.Width/2)); $ey=[int]($end.Y+$end.Height/2)
+ if(![NativeFileDrag]::SetForegroundWindow($sourceProcess.MainWindowHandle)){ throw 'Source cannot receive input' }
+ $null=[NativeFileDrag]::SetCursorPos($sx,$sy)
+ [NativeFileDrag]::mouse_event(2,0,0,0,[UIntPtr]::Zero)
+ try {
+  for($i=1;$i -le 40;$i++){
+   $null=[NativeFileDrag]::SetCursorPos([int]($sx+($ex-$sx)*$i/40),[int]($sy+($ey-$sy)*$i/40))
+   [Threading.Thread]::Sleep(25)
+  }
+ } finally { [NativeFileDrag]::mouse_event(4,0,0,0,[UIntPtr]::Zero) }
+} finally { $null=[NativeFileDrag]::SetThreadDpiAwarenessContext($dpi) }
diff --git a/packages/tauri-app/tests/webkit-capabilities/windows-file-source.ps1 b/packages/tauri-app/tests/webkit-capabilities/windows-file-source.ps1
new file mode 100644
index 0000000000..56b6b5d10a
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/windows-file-source.ps1
@@ -0,0 +1,32 @@
+# A real OLE FileDrop source for this checkout's isolated release fixture.
+param([Parameter(Mandatory=$true)][int]$FixtureProcessId)
+$ErrorActionPreference = 'Stop'
+$fixture = Get-Process -Id $FixtureProcessId
+$expected = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../target/release/codenomad-webkit-capabilities-fixture.exe'))
+if ($fixture.Path -ne $expected) { throw 'Expected this checkout''s isolated fixture' }
+Add-Type -AssemblyName System.Windows.Forms
+Add-Type -AssemblyName System.Drawing
+$file = (Resolve-Path (Join-Path $PSScriptRoot 'drop-fixture.txt')).Path
+$form = New-Object Windows.Forms.Form
+$form.Text = 'Capabilities file source'
+$form.Size = New-Object Drawing.Size 240,110
+$form.StartPosition = 'Manual'
+$form.Location = New-Object Drawing.Point ([Windows.Forms.Screen]::PrimaryScreen.WorkingArea.Right - 260),100
+$form.TopMost = $true
+$button = New-Object Windows.Forms.Button
+$button.Dock = 'Fill'
+$button.Text = 'Drag fixture file'
+$button.Add_MouseDown({
+  $data = New-Object Windows.Forms.DataObject
+  $data.SetData([Windows.Forms.DataFormats]::FileDrop, [string[]]@($file))
+  $effect = $button.DoDragDrop($data, [Windows.Forms.DragDropEffects]::Copy)
+  Write-Output "drag-end $effect"
+})
+$form.Controls.Add($button)
+Add-Type @'
+using System; using System.Runtime.InteropServices;
+public static class SourceWindow { [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h,int n); }
+'@
+$form.Show()
+$null = [SourceWindow]::ShowWindow($form.Handle, 5)
+[Windows.Forms.Application]::Run($form)
diff --git a/packages/tauri-app/tests/webkit-capabilities/windows-ui.ps1 b/packages/tauri-app/tests/webkit-capabilities/windows-ui.ps1
new file mode 100644
index 0000000000..831c51fb0e
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/windows-ui.ps1
@@ -0,0 +1,167 @@
+# Native accessibility driver for the isolated Windows release fixture only.
+param([Parameter(Mandatory=$true)][int]$FixtureProcessId, [string]$Invoke, [string]$Value, [switch]$NativePointer, [switch]$Activate, [switch]$Escape, [switch]$Popup, [switch]$RightClick)
+$ErrorActionPreference = 'Stop'
+Add-Type -AssemblyName UIAutomationClient
+Add-Type -AssemblyName UIAutomationTypes
+$process = Get-Process -Id $FixtureProcessId
+if ($process.ProcessName -ne 'codenomad-webkit-capabilities-fixture') { throw 'Expected the isolated fixture process' }
+$expected = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../target/release/codenomad-webkit-capabilities-fixture.exe'))
+if ($process.Path -ne $expected) { throw 'Fixture belongs to another checkout' }
+$root = [System.Windows.Automation.AutomationElement]::FromHandle($process.MainWindowHandle)
+if (!$root) { throw 'Fixture window unavailable' }
+$ids = New-Object 'System.Collections.Generic.HashSet[int]'
+$null = $ids.Add($FixtureProcessId)
+$birth = @{ $FixtureProcessId = $process.StartTime.ToUniversalTime() }
+$processes = Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CreationDate
+do {
+  $changed = $false
+  foreach ($candidate in $processes) {
+    if ($ids.Contains([int]$candidate.ParentProcessId) -and $candidate.CreationDate -and ($candidate.CreationDate.ToUniversalTime() -ge $birth[[int]$candidate.ParentProcessId]) -and $ids.Add([int]$candidate.ProcessId)) {
+      $birth[[int]$candidate.ProcessId] = $candidate.CreationDate.ToUniversalTime()
+      $changed = $true
+    }
+  }
+} while ($changed)
+$conditions = @($ids | ForEach-Object { New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$_) })
+$owned = if ($conditions.Count -eq 1) { $conditions[0] } else { [System.Windows.Automation.OrCondition]::new([System.Windows.Automation.Condition[]]$conditions) }
+$roots = @([System.Windows.Automation.AutomationElement]::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $owned))
+# WebView2 can present a browser-process dialog outside the native process tree.
+# Admit it only through its live HWND owner chain, never by executable name.
+if (!('FixtureWindowOwnership' -as [type])) { Add-Type @'
+using System; using System.Collections.Generic; using System.Runtime.InteropServices;
+public static class FixtureWindowOwnership {
+ delegate bool EnumCallback(IntPtr h,IntPtr p);
+ [DllImport("user32.dll")] static extern bool EnumWindows(EnumCallback c,IntPtr p);
+ [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h,uint command);
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h,out uint p);
+ public static int Process(IntPtr h){uint p;GetWindowThreadProcessId(h,out p);return (int)p;}
+ public static IntPtr[] Owned(uint pid) {
+  var result=new List();
+  EnumWindows((h,p)=>{
+   if(!IsWindowVisible(h))return true;
+   IntPtr owner=h;
+   for(int depth=0;owner!=IntPtr.Zero && depth<32;depth++,owner=GetWindow(owner,4)){
+    if(Process(owner)==pid){result.Add(h);break;}
+   }
+   return true;
+  },IntPtr.Zero);
+  return result.ToArray();
+ }
+}
+'@ }
+$seen = New-Object 'System.Collections.Generic.HashSet[long]'
+foreach ($r in $roots) { $null=$seen.Add([long]$r.Current.NativeWindowHandle) }
+foreach ($handle in [FixtureWindowOwnership]::Owned([uint32]$FixtureProcessId)) {
+  if ($seen.Add($handle.ToInt64())) {
+    $ownedElement=[System.Windows.Automation.AutomationElement]::FromHandle($handle)
+    $roots += $ownedElement
+    $null=$ids.Add([int]$ownedElement.Current.ProcessId)
+  }
+}
+if ($Popup) {
+  $condition=[System.Windows.Automation.AndCondition]::new(
+    [System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::ControlTypeProperty,[System.Windows.Automation.ControlType]::Window),
+    [System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::NameProperty,'http://127.0.0.1:18741'))
+  $popups=@($roots | ForEach-Object { $_.FindAll([System.Windows.Automation.TreeScope]::Subtree,$condition) })
+  $handles=@($popups | ForEach-Object { $_.Current.NativeWindowHandle } | Sort-Object -Unique)
+  if($handles.Count -ne 1){throw 'Expected one owned fixture popup'}
+  $roots=@($popups | Select-Object -First 1)
+}
+if ($Invoke) {
+  $condition = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::NameProperty, $Invoke)
+  $element = $null
+  foreach ($window in $roots) {
+    $element = $window.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $condition)
+    if ($element) { break }
+  }
+  if (!$element) { throw "Fixture control unavailable: $Invoke" }
+  if (!$NativePointer -or $element.Current.IsKeyboardFocusable) { $element.SetFocus() }
+  if ($NativePointer) {
+    if (!('FixturePointer' -as [type])) { Add-Type @'
+using System;
+using System.Runtime.InteropServices;
+public static class FixturePointer {
+  [StructLayout(LayoutKind.Sequential)] public struct Point { public int X,Y; }
+  [DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr hwnd, ref Point point);
+  [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr w, IntPtr l);
+  [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
+  [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
+  [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
+  [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid);
+  [DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y);
+  [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);
+  [DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint x,uint y,uint data,UIntPtr extra);
+  [DllImport("user32.dll")] public static extern void keybd_event(byte key,byte scan,uint flags,UIntPtr extra);
+  [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hwnd);
+  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd,int command);
+}
+'@ }
+    $native = $element
+    while ($native -and !$native.Current.NativeWindowHandle) { $native = [System.Windows.Automation.TreeWalker]::RawViewWalker.GetParent($native) }
+    if (!$native -or !$ids.Contains($native.Current.ProcessId)) { throw 'Native target outside the fixture' }
+    $bounds = $element.Current.BoundingRectangle
+    if ($bounds.IsEmpty -or $element.Current.IsOffscreen) { throw 'Fixture control is offscreen' }
+    $point = New-Object FixturePointer+Point
+    $point.X = [int]($bounds.X + $bounds.Width/2); $point.Y = [int]($bounds.Y + $bounds.Height/2)
+    $oldDpi = [FixturePointer]::SetThreadDpiAwarenessContext([IntPtr](-4))
+    try {
+      $hwnd = [IntPtr]$native.Current.NativeWindowHandle
+      if ($Activate) {
+        $top = [FixturePointer]::GetAncestor($hwnd, 2)
+        [uint32]$topProcess = 0
+        $null = [FixturePointer]::GetWindowThreadProcessId($top, [ref]$topProcess)
+        if (!$ids.Contains([int]$topProcess)) { throw 'Native target outside the fixture' }
+        if ([FixturePointer]::IsIconic($top)) { $null=[FixturePointer]::ShowWindow($top,9) }
+        if (![FixturePointer]::SetForegroundWindow($top)) { throw 'Owned fixture window cannot receive foreground input' }
+        if ($Escape) {
+          [FixturePointer]::keybd_event(27,0,0,[UIntPtr]::Zero)
+          [FixturePointer]::keybd_event(27,0,2,[UIntPtr]::Zero)
+          return
+        }
+        $hit = [IntPtr]::Zero
+        for ($attempt=0; $attempt -lt 20; $attempt++) {
+          $bounds=$element.Current.BoundingRectangle
+          $point.X=[int]($bounds.X+$bounds.Width/2); $point.Y=[int]($bounds.Y+$bounds.Height/2)
+          $hit=[FixturePointer]::GetAncestor([FixturePointer]::WindowFromPoint($point),2)
+          if ($hit -eq $top) { break }
+          [Threading.Thread]::Sleep(25)
+        }
+        if ($hit -ne $top) { throw 'Fixture control is covered' }
+        $null = [FixturePointer]::SetCursorPos($point.X,$point.Y)
+        $down=if($RightClick){8}else{2};$up=if($RightClick){16}else{4}
+        [FixturePointer]::mouse_event($down,0,0,0,[UIntPtr]::Zero)
+        [FixturePointer]::mouse_event($up,0,0,0,[UIntPtr]::Zero)
+        return
+      }
+      if ($Escape) {
+        if (![FixturePointer]::PostMessage($hwnd,0x100,[IntPtr]27,[IntPtr]0x10001)) { throw 'Fixture Escape refused' }
+        if (![FixturePointer]::PostMessage($hwnd,0x101,[IntPtr]27,[IntPtr](-1073676287))) { throw 'Fixture Escape release refused' }
+        return
+      }
+      if (![FixturePointer]::ScreenToClient($hwnd,[ref]$point)) { throw 'Invalid fixture coordinates' }
+      $position = [IntPtr](($point.Y -shl 16) -bor ($point.X -band 65535))
+      foreach ($message in @(0x200,0x201,0x202)) {
+        $button = if ($message -eq 0x201) { [IntPtr]1 } else { [IntPtr]0 }
+        if (![FixturePointer]::PostMessage($hwnd,$message,$button,$position)) { throw 'Native fixture input refused' }
+      }
+    } finally { $null = [FixturePointer]::SetThreadDpiAwarenessContext($oldDpi) }
+  } elseif ($PSBoundParameters.ContainsKey('Value')) {
+    $pattern = $element.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern)
+    $pattern.SetValue($Value)
+  } else {
+    $pattern = $null
+    if ($element.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern, [ref]$pattern)) { $pattern.Invoke() }
+    elseif ($element.TryGetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern, [ref]$pattern)) { $pattern.Expand() }
+    else { throw 'Fixture control has no native action' }
+  }
+} else {
+ foreach ($root in $roots) {
+  'WINDOW | ' + $root.Current.Name
+  $elements = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition)
+  for ($i=0; $i -lt [Math]::Min($elements.Count, 100); $i++) {
+    $item = $elements.Item($i)
+    '{0} | {1}' -f $item.Current.ControlType.ProgrammaticName, $item.Current.Name
+  }
+ }
+}
diff --git a/packages/tauri-app/tests/webkit-capabilities/zoom-policy.c b/packages/tauri-app/tests/webkit-capabilities/zoom-policy.c
new file mode 100644
index 0000000000..50520c78d9
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-capabilities/zoom-policy.c
@@ -0,0 +1,12 @@
+#include "../../src-tauri/src/embedded_view/zoom.h"
+#include 
+int main(void) {
+    assert(cn_preview_next_zoom(1, 1) == 1.2);
+    assert(cn_preview_next_zoom(1.2, -1) == 1);
+    assert(cn_preview_next_zoom(4, 0) == 1);
+    assert(cn_preview_next_zoom(5, 1) == 5);
+    assert(cn_preview_next_zoom(0.25, -1) == 0.25);
+    assert(cn_preview_next_zoom(NAN, 1) == 1.2);
+    assert(cn_preview_next_zoom(INFINITY, -1) == 0.8);
+    return 0;
+}
diff --git a/packages/tauri-app/tests/webkit-input/README.md b/packages/tauri-app/tests/webkit-input/README.md
new file mode 100644
index 0000000000..08d29f7d77
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-input/README.md
@@ -0,0 +1,53 @@
+# Native WebKit input qualification
+
+The harness compiles the native adapter sources in `src-tauri/src/embedded_view/input_{linux.c,macos.m}` directly. The application's target-gated native build uses the same sources; its private browser controller integrates visible PNG capture through the Rust read adapter. Public WebKit automation stays disabled, and input dispatch retains the qualification boundary below.
+
+Run on the graphical Linux desktop:
+
+```sh
+GDK_BACKEND=x11 python3 packages/tauri-app/scripts/test-webkit-input.py --output /path/to/artifacts/x11
+GDK_BACKEND=wayland python3 packages/tauri-app/scripts/test-webkit-input.py --output /path/to/artifacts/wayland
+```
+
+With an X11 desktop in use, `--nested-kde` starts a separate virtual KWin Wayland compositor, gives its keyboard focus to a sentinel window, and terminates only its own compositor. The WebKit widget uses `GdkWaylandDisplay`. This exercises native Wayland client routing while preserving the desktop session. A full Plasma Wayland login remains a separate qualification target.
+
+On macOS:
+
+```sh
+python3 packages/tauri-app/scripts/test-webkit-input.py --output /path/to/artifacts/macos
+```
+
+Requirements: a C compiler, Python 3, GTK 3 and WebKitGTK 4.1 development packages on Linux; Xcode command-line tools and AppKit/WebKit on macOS. `xdotool`, when present on the Linux desktop, observes pointer coordinates only. Synthetic input exclusively uses the adapter. The runner bounds compilation, compositor startup and execution. Each native executable checks background-window status throughout input dispatch.
+
+Artifacts: `checkpoint.json` contains the fixed isolated-world callback result and page event observations; `capture.png` is the visible native viewport; `native.log` records window and pointer state; `result.json` lists each acceptance check. Linux also records desktop-pointer observations when X11 observation is available. Wayland's GDK coordinates describe its own compositor, so the desktop observer supplies the external pointer check in nested runs.
+
+The fixture checks left/right click, hover, drag with a held button, wheel, key down/up, the platform select-all chord, Unicode insertion into input/contenteditable, and Enter in contenteditable. Every observed input must be trusted. A page-only global must be absent from the isolated world. The program is fixed in the adapter; callers supply neither script text nor an evaluation expression.
+
+## Qualification boundary
+
+The AppKit candidate uses targeted NSEvent/responder APIs. Its UI-thread dispatch scopes the native `pressedMouseButtons` implementation to the synthetic button state, delegates other threads to the original implementation, and restores it in `@finally`. The native self-check exercises nested dispatch, another thread and exception cleanup; the harness also verifies method restoration after every action. Its drag path must produce `pointermove.buttons == 1`; a trusted event alone is insufficient. Select-all must replace the entire input value, and Enter must reach contenteditable. Keep these assertions strict when investigating an alternative native path.
+
+`CN_INPUT_TRACE=1` records key-equivalent, native editing fallback and hover dispatch paths. Hover first checks for a public `mouseMoved:` implementation on the view and otherwise checks availability of the narrow `_simulateMouseMove:` WebKit SPI. An initial native snapshot establishes the paint callback before input starts. Keyboard delivery targets the exact view; an inactive native editing fallback remains subject to qualification of page cancellation and single execution before integration.
+
+The macOS harness primes hover at `(5,5)`, then targets `(30,160)` on the next timer tick, with tracking areas installed and mouse-moved events enabled. The trace records both CSS and native window coordinates. Chords send native `flagsChanged:` transitions for each modifier, the key equivalent, its matching key-up, and modifier release. Synthetic class modifier state is UI-thread scoped with exception-safe restoration; the native self-check covers nested modifier state and exception cleanup. Fresh key-event timestamps, window numbers and flags are recorded for sequence comparison.
+
+`CN_INPUT_NO_CHORD=1` is a diagnostic that omits only the chord down/up steps. The acceptance assertions remain enabled, so this diagnostic fails the chord criteria by design. Compare its contenteditable keyboard events against the complete sequence; use the complete sequence for acceptance.
+
+`CN_INPUT_DIRECT_HOVER=1` exercises public `mouseEntered:` then `mouseMoved:` directly on the exact WKWebView at the priming and target positions. This variant lives in the native self-test build. The trace includes each tracking area's options and key-window/always-active bits. Keep the window inactive throughout qualification.
+
+## macOS candidate limitations
+
+- A standalone Enter uses WebKit's native `keyDown:` text-input path and produces exactly one `insertParagraph` beforeinput/input pair. The harness counts both events independently to catch duplicate execution. Its DOM trace contains Enter key-down; Enter key-up is missing in this diagnostic.
+- In the complete Cmd+A sequence, the native select-all fallback replaces the input value. DOM delivery includes Meta key-down, while the Meta release and following Enter keyboard events are missing. The native trace records direct WKWebView `flagsChanged:` down/up, chord key-up and zero modifiers on the following Enter. After this chord, the agent's subsequent Enter also lacks its native paragraph edit. Keep keyboard actions following a Mod chord gated by this limitation.
+- The initial hover lacks `pointermove` at the requested target while the window is inactive, including after priming at a different in-view location. Public direct enter/move and the checked `_simulateMouseMove:` SPI are covered by separate harness variants. Mouse-enter/CSS hover observations occur with subsequent clicks. The agent's initial standalone hover consequently cannot establish the expected pointer-move behavior. The harness preserves background-window operation; tracking-area option logging is diagnostic evidence rather than a key-window positive control.
+
+The strict complete-sequence assertions retain these failures. The private transport integrates navigation and capture; pointer and keyboard dispatch retain the documented macOS limitations and their separate capability gate.
+
+WebKit's `WebEventFactory::createWebMouseEvent` obtains ordinary NSEvent button state from `WebCore::currentlyPressedMouseButtons`, which reads `[NSEvent pressedMouseButtons]`. The automation event path has distinct handling. Source references for investigation:
+
+- 
+- 
+- 
+- 
+
+An alternative based on WebKit automation SPI requires explicit contract qualification and runtime capability checks. Its background-window behavior must pass this harness before application integration. Never use global CGEvent posting, unscoped event-state overrides, XTest, DOM-event substitutes, or broad script evaluation to satisfy a failed assertion.
diff --git a/packages/tauri-app/tests/webkit-input/fixture.html b/packages/tauri-app/tests/webkit-input/fixture.html
new file mode 100644
index 0000000000..0c0043d37c
--- /dev/null
+++ b/packages/tauri-app/tests/webkit-input/fixture.html
@@ -0,0 +1,18 @@
+Native input qualification
+
+
pointer target
+ + diff --git a/packages/tauri-app/tests/webkit-input/linux.c b/packages/tauri-app/tests/webkit-input/linux.c new file mode 100644 index 0000000000..759cfff47d --- /dev/null +++ b/packages/tauri-app/tests/webkit-input/linux.c @@ -0,0 +1,61 @@ +#include +#include +#include "sequence.h" + +static GtkWidget *window, *view; +static int step = -4; +static gint initial_x, initial_y; +static GdkDevice *pointer; +static gboolean tick(gpointer unused) { + (void)unused; + if (step >= 0) assert(!gtk_window_is_active(GTK_WINDOW(window))); + if (step >= 0 && step <= 19) sequence(view, step); + if (step == 21) cn_checkpoint(view, write_result, "checkpoint.json"); + if (step == 22) cn_capture(view, write_result, "capture.png"); + if (step == 26) { + gint x, y; + gdk_device_get_position(pointer, NULL, &x, &y); + printf("window_active=%d pointer_before=%d,%d pointer_after=%d,%d backend=%s\n", + gtk_window_is_active(GTK_WINDOW(window)), initial_x, initial_y, x, y, + G_OBJECT_TYPE_NAME(gtk_widget_get_display(window))); + assert(!gtk_window_is_active(GTK_WINDOW(window))); + assert(x == initial_x && y == initial_y); + gtk_main_quit(); + return G_SOURCE_REMOVE; + } + step++; + return G_SOURCE_CONTINUE; +} +static void loaded(WebKitWebView *webview, WebKitLoadEvent event, gpointer unused) { + (void)webview; (void)unused; + if (event == WEBKIT_LOAD_FINISHED) g_timeout_add(250, tick, NULL); +} +int main(int argc, char **argv) { + assert(argc == 2); + gtk_init(&argc, &argv); + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window), "CodeNomad input qualification (no activation)"); + gtk_window_set_focus_on_map(GTK_WINDOW(window), FALSE); + gtk_window_set_default_size(GTK_WINDOW(window), 700, 600); + view = webkit_web_view_new(); + gtk_container_add(GTK_CONTAINER(window), view); + g_signal_connect(view, "load-changed", G_CALLBACK(loaded), NULL); + gtk_widget_show_all(window); + if (g_getenv("CN_NESTED_KDE")) { + /* A new private compositor initially focuses its first surface. Give + * keyboard focus to a sentinel before sending background guest input. */ + GtkWidget *sentinel = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(sentinel), "Qualification focus sentinel"); + gtk_window_set_default_size(GTK_WINDOW(sentinel), 200, 100); + gtk_widget_show_all(sentinel); + } + pointer = gdk_seat_get_pointer(gdk_display_get_default_seat(gtk_widget_get_display(window))); + gdk_device_get_position(pointer, NULL, &initial_x, &initial_y); + char *html = NULL; + assert(g_file_get_contents(argv[1], &html, NULL, NULL)); + webkit_web_view_load_html(WEBKIT_WEB_VIEW(view), html, "http://127.0.0.1/"); + g_free(html); + gtk_main(); + gtk_widget_destroy(window); + return 0; +} diff --git a/packages/tauri-app/tests/webkit-input/macos.m b/packages/tauri-app/tests/webkit-input/macos.m new file mode 100644 index 0000000000..fff5df6ecf --- /dev/null +++ b/packages/tauri-app/tests/webkit-input/macos.m @@ -0,0 +1,94 @@ +#import +#import +#include "sequence.h" +#include +extern void cn_test_scoped_buttons(void); +extern int cn_test_direct_hover(void *, double, double); +@interface WKWebView (CNInputDrain) +- (void)_doAfterProcessingAllPendingKeyEvents:(void (^)(void))completion; +- (void)_doAfterProcessingAllPendingMouseEvents:(void (^)(void))completion; +@end + +@interface Runner : NSObject +@property NSWindow *window; +@property WKWebView *view; +@property NSInteger step; +@property NSPoint pointer; +@end +static void painted(void *context, const unsigned char *bytes, size_t length, const char *error) { + (void)bytes; (void)length; + assert(!error); + Runner *runner = (__bridge Runner *)context; + [NSTimer scheduledTimerWithTimeInterval:0.25 target:runner selector:@selector(tick:) userInfo:nil repeats:YES]; +} +@implementation Runner +- (void)webView:(WKWebView *)view didFinishNavigation:(WKNavigation *)navigation { + (void)view; (void)navigation; + self.pointer = NSEvent.mouseLocation; + self.step = -4; + cn_capture((__bridge void *)self.view, painted, (__bridge void *)self); +} +- (void)tick:(NSTimer *)timer { + void *view = (__bridge void *)self.view; + if (self.step >= 0) assert(!self.window.isKeyWindow && !NSApp.active); + if (self.step == -1) { + self.window.acceptsMouseMovedEvents = YES; + [self.view updateTrackingAreas]; + fprintf(stderr, "hover variant=prime-5,5-then-target trackingAreas=%lu acceptsMouseMoved=%d\n", (unsigned long)self.view.trackingAreas.count, self.window.acceptsMouseMovedEvents); + for (NSTrackingArea *area in self.view.trackingAreas) { + fprintf(stderr, "tracking owner=%s options=0x%lx activeInKeyWindow=%d activeAlways=%d\n", NSStringFromClass([area.owner class]).UTF8String, (unsigned long)area.options, !!(area.options & NSTrackingActiveInKeyWindow), !!(area.options & NSTrackingActiveAlways)); + } + if (getenv("CN_INPUT_DIRECT_HOVER")) assert(cn_test_direct_hover(view, 5, 5)); + else assert(cn_pointer(view, CN_MOVE, 5, 5, 0)); + } + IMP buttons = class_getMethodImplementation(object_getClass(NSEvent.class), @selector(pressedMouseButtons)); + IMP modifiers = class_getMethodImplementation(object_getClass(NSEvent.class), @selector(modifierFlags)); + BOOL omit_chord = getenv("CN_INPUT_NO_CHORD") && (self.step == 12 || self.step == 13); + BOOL direct_hover = getenv("CN_INPUT_DIRECT_HOVER") && self.step == 0; + if (direct_hover) assert(cn_test_direct_hover(view, 30, 160)); + if (self.step >= 0 && self.step <= 19 && !omit_chord && !direct_hover) sequence(view, (int)self.step); + assert(class_getMethodImplementation(object_getClass(NSEvent.class), @selector(pressedMouseButtons)) == buttons); + assert(class_getMethodImplementation(object_getClass(NSEvent.class), @selector(modifierFlags)) == modifiers); + if (self.step >= 0 && self.step <= 19 && getenv("CN_INPUT_TRACE")) { + NSInteger current = self.step; + if ([self.view respondsToSelector:@selector(_doAfterProcessingAllPendingKeyEvents:)]) + [self.view _doAfterProcessingAllPendingKeyEvents:^{ fprintf(stderr, "key-drained step=%ld\n", (long)current); }]; + if ([self.view respondsToSelector:@selector(_doAfterProcessingAllPendingMouseEvents:)]) + [self.view _doAfterProcessingAllPendingMouseEvents:^{ fprintf(stderr, "mouse-drained step=%ld\n", (long)current); }]; + } + if (self.step == 21) cn_checkpoint(view, write_result, "checkpoint.json"); + if (self.step == 22) cn_capture(view, write_result, "capture.png"); + if (self.step == 26) { + NSPoint pointer = NSEvent.mouseLocation; + printf("window_key=%d app_active=%d pointer_before=%g,%g pointer_after=%g,%g\n", + self.window.isKeyWindow, NSApp.active, self.pointer.x, self.pointer.y, pointer.x, pointer.y); + assert(!self.window.isKeyWindow && !NSApp.active); + assert(NSEqualPoints(self.pointer, pointer)); + [timer invalidate]; + fflush(stdout); + exit(0); + } + self.step++; +} +@end +int main(int argc, char **argv) { + assert(argc == 2); + @autoreleasepool { + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory]; + cn_test_scoped_buttons(); + Runner *runner = [Runner new]; + runner.window = [[NSWindow alloc] initWithContentRect:NSMakeRect(30, 30, 700, 600) + styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; + runner.window.title = @"CodeNomad input qualification (no activation)"; + runner.view = [[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 700, 600)]; + runner.window.contentView = runner.view; + runner.view.navigationDelegate = runner; + [runner.window orderFront:nil]; + NSString *html = [NSString stringWithContentsOfFile:[NSString stringWithUTF8String:argv[1]] + encoding:NSUTF8StringEncoding error:nil]; + assert(html); + [runner.view loadHTMLString:html baseURL:[NSURL URLWithString:@"http://127.0.0.1/"]]; + [NSApp run]; + } +} diff --git a/packages/tauri-app/tests/webkit-input/sequence.h b/packages/tauri-app/tests/webkit-input/sequence.h new file mode 100644 index 0000000000..9225a118c1 --- /dev/null +++ b/packages/tauri-app/tests/webkit-input/sequence.h @@ -0,0 +1,55 @@ +#include "../../src-tauri/src/embedded_view/input.h" +#include +#include +#include +#include + +/* Deliberately space IPC deliveries across frames. No JS input substitutes. */ +static void sequence(void *view, int step) { + int ok = 1; + switch (step) { + case 0: ok = cn_pointer(view, CN_MOVE, 30, 160, 0); break; + case 1: ok = cn_pointer(view, CN_RIGHT_DOWN, 30, 160, 0); break; + case 2: ok = cn_pointer(view, CN_RIGHT_UP, 30, 160, 0); break; + case 3: ok = cn_pointer(view, CN_LEFT_DOWN, 30, 160, 0); break; + case 4: ok = cn_pointer(view, CN_DRAG, 90, 190, 0); break; + case 5: ok = cn_pointer(view, CN_LEFT_UP, 90, 190, 0); break; + case 6: ok = cn_wheel(view, 90, 190, 0, 100, 0); break; + case 7: ok = cn_pointer(view, CN_LEFT_DOWN, 30, 30, 0); break; + case 8: ok = cn_pointer(view, CN_LEFT_UP, 30, 30, 0); break; + case 9: ok = cn_key(view, "a", 0, 1); break; + case 10: ok = cn_key(view, "a", 0, 0); break; + case 11: ok = cn_text(view, "é漢🙂"); break; + case 12: ok = cn_key(view, "a", +#ifdef __APPLE__ + CN_META, +#else + CN_CONTROL, +#endif + 1); break; + case 13: ok = cn_key(view, "a", +#ifdef __APPLE__ + CN_META, +#else + CN_CONTROL, +#endif + 0); break; + case 14: ok = cn_text(view, "remplacé漢🙂"); break; + case 15: ok = cn_pointer(view, CN_LEFT_DOWN, 30, 90, 0); break; + case 16: ok = cn_pointer(view, CN_LEFT_UP, 30, 90, 0); break; + case 17: ok = cn_text(view, "éditeur漢🙂"); break; + case 18: ok = cn_key(view, "Return", 0, 1); break; + case 19: ok = cn_key(view, "Return", 0, 0); break; + } + if (!ok) { fprintf(stderr, "Native primitive refused at step %d\n", step); exit(2); } +} + +static void write_result(void *context, const unsigned char *bytes, size_t length, const char *error) { + if (error) { fprintf(stderr, "%s: %s\n", (char *)context, error); exit(3); } + FILE *file = fopen(context, "wb"); + assert(file); + assert(fwrite(bytes, 1, length, file) == length); + fclose(file); + printf("saved %s (%zu bytes)\n", (char *)context, length); + fflush(stdout); +} diff --git a/packages/tauri-app/vendor/README.md b/packages/tauri-app/vendor/README.md index be2305b0f0..5529837234 100644 --- a/packages/tauri-app/vendor/README.md +++ b/packages/tauri-app/vendor/README.md @@ -1,7 +1,78 @@ # Vendored Tauri crates +## Embedded WebKit views + +`tauri-runtime-wry-2.12.3/` and `wry-0.57.1/` are complete published +MIT/Apache-2.0 crates, including licenses, selected through `[patch.crates-io]`. + +- Crates: https://static.crates.io/crates/tauri-runtime-wry/tauri-runtime-wry-2.12.3.crate + and https://static.crates.io/crates/wry/wry-0.57.1.crate. +- Published SHA-256: runtime `e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f`; + Wry `759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9`. +- Local changes: `patches/tauri-runtime-wry-gtk.patch` and + `patches/wry-gtk.patch`, then `patches/wry-webkit-capabilities.patch`, + `patches/wry-browser-isolation.patch`, `patches/runtime-browser-isolation.patch` + `patches/wry-browser-print.patch` and `patches/wry-browser-download.patch`; + native trials ship beside the runtime examples. +- GTK: the runtime lazily installs a window-owned `GtkOverlay` inside Tao's + content box, below its menu bar. Primary content stays boxed; child webviews use + `GtkFixed`. The overlay passes uncovered input through to the primary view. + Primary-only windows keep their ordinary box. Reparenting uses the destination + window's own child container. +- Wry stores child positions in `GtkFixed` and sizes in GTK size requests, alongside + immediate allocation, so resize/menu/hide-show allocations keep the rectangle. + Bounds reads use that retained layout while hidden, preserving position across + Tauri's separate position and size updates before reveal. + Bounds follow the actual parent after reparenting. IPC callbacks keep weak + WebView references so destruction releases both the view and its IPC manager. +- WKWebView uses Tauri's per-webview `on_permission_request` callback, installed + on the embedded-view builder before construction. Wry's native delegate routes + media capture to it; file uploads retain user-driven selection. The application + renderer keeps its own permission policy. Requalify WebKit's engine-default + handling of location, notifications, display capture and storage access when + changing runtime or OS support. +- Browser previews' WKWebView delegate presents native JavaScript dialogs labeled + with the initiating host; the `browser-popup-` delegate closes its native window + on `window.close()`. WebKitGTK closes the corresponding popup window before + destroying its view, and scopes shared-context download callbacks to the + originating view with overwriting disabled and native file-URI destinations. + Rejected browser blob/data document requests become downloads, preserving the + preview's HTTP(S)-only document policy. + Browser pop-ups use Tauri's related-view/configuration API, retaining the native + opener and shared site state. The backend-free fixture in + `../tests/webkit-capabilities/` exercises these paths on both engines. +- Browser labels select a runtime fence around application initialization scripts, + IPC and app resource protocols. Native browser globals and synchronous dialogs + stay owned by the engine. Preview navigation gestures use Wry's native setting. + WebView2 popup script closure disposes the top-level popup instead of only its + child container; embedded roots remain host-owned. +- WKWebView preview printing and beforeunload use the native delegate selectors + in WebKit's `WKUIDelegatePrivate.h`: both printFrame variants and the + initiating-frame beforeunload completion. Printing uses the public + `printOperationWithPrintInfo:` operation and system panel. Qualify these + selectors on supported macOS/WebKit updates with the native fixture. +- WKWebView's `_webView:contextMenuDidCreateDownload:` callback, declared by + `WKNavigationDelegatePrivate.h`, attaches the same download delegate as native + navigation downloads. Both paths use the preview's Downloads-folder policy. + +Keep these overrides until the resolved upstream runtime supports the same child +layout, persistent geometry policy. Requalify both GTK +backends and macOS permission behavior before removing either override. + +The Linux native regression is +`python3 tauri-runtime-wry-2.12.3/examples/gtk-child-trial.py` from this directory, +with the desktop session environment, Cargo dependencies cached and `python3-dbus` +installed. KDE Wayland uses `GTK_TRIAL_UINPUT=1`, `python3-evdev` and a writable +`/dev/uinput`; an X11 desktop uses `GTK_TRIAL_X11=1` and `xdotool`. GNOME uses +Mutter's native seat. It compiles through a temporary manifest using the actual runtime layout +module and vendored Wry, then exercises Wayland and X11 with native input: +rectangles, relayout, menus, reparenting, hide/show, independent owning windows, +destruction, permission/download denial and distinct persistent data managers. +Full application checks additionally exercise Tauri's dispatch integration. + + The Tauri workspace's `[patch.crates-io]` (`packages/tauri-app/Cargo.toml`) -selects the published crates below, each with one local change. Never mutate the +selects the published crates below, with focused local changes. Never mutate the registry cache or patch at build time. Each directory is named after its crate version; `packages/tauri-app/scripts/vendored-patches.test.mjs` fails when `Cargo.lock` no longer resolves a vendored copy (for example after a dependency diff --git a/packages/tauri-app/vendor/patches/runtime-browser-isolation.patch b/packages/tauri-app/vendor/patches/runtime-browser-isolation.patch new file mode 100644 index 0000000000..6b97e18b25 --- /dev/null +++ b/packages/tauri-app/vendor/patches/runtime-browser-isolation.patch @@ -0,0 +1,51 @@ +diff --git a/src/lib.rs b/src/lib.rs +index 40330f716..0573fa5cf 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -4751,6 +4751,7 @@ You may have it installed on another user account, but it is not available for t + .with_incognito(webview_attributes.incognito) + .with_clipboard(webview_attributes.clipboard) + .with_hotkeys_zoom(webview_attributes.zoom_hotkeys_enabled) ++ .with_back_forward_navigation_gestures(label.starts_with("browser-")) + .with_general_autofill_enabled(webview_attributes.general_autofill_enabled); + + if url != "about:blank" { +@@ -5107,20 +5108,27 @@ You may have it installed on another user account, but it is not available for t + let window_id_for_ipc = window_id.clone(); + #[cfg(not(windows))] + let window_id_for_ipc = window_id; +- webview_builder = webview_builder.with_ipc_handler(create_ipc_handler( +- window_id_for_ipc, +- id, +- context.clone(), +- label.clone(), +- ipc_handler, +- )); +- +- for script in webview_attributes.initialization_scripts { +- webview_builder = webview_builder +- .with_initialization_script_for_main_only(script.script, script.for_main_frame_only); ++ let browser_guest = label.starts_with("browser-"); ++ if !browser_guest { ++ webview_builder = webview_builder.with_ipc_handler(create_ipc_handler( ++ window_id_for_ipc, ++ id, ++ context.clone(), ++ label.clone(), ++ ipc_handler, ++ )); ++ for script in webview_attributes.initialization_scripts { ++ webview_builder = webview_builder ++ .with_initialization_script_for_main_only(script.script, script.for_main_frame_only); ++ } + } + + for (scheme, protocol) in uri_scheme_protocols { ++ // Preview documents retain their browser globals (not app plugin overrides) ++ // and carry neither the application IPC bridge nor app resource protocols. ++ if browser_guest { ++ continue; ++ } + // on Linux the custom protocols are associated with the web context + // and you cannot register a scheme more than once + #[cfg(any( diff --git a/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch b/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch new file mode 100644 index 0000000000..3b9055f488 --- /dev/null +++ b/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch @@ -0,0 +1,108 @@ +--- /dev/null ++++ b/src/gtk_child_layout.rs +@@ -0,0 +1,56 @@ ++// Copyright 2026 CodeNomad contributors ++// SPDX-License-Identifier: Apache-2.0 OR MIT ++ ++use gtk::prelude::*; ++ ++const NAME: &str = "tauri-webview-overlay"; ++ ++pub(crate) fn content(vbox: >k::Box) -> gtk::Box { ++ vbox ++ .children() ++ .into_iter() ++ .find(|widget| widget.widget_name() == NAME) ++ .and_then(|widget| widget.downcast::().ok()) ++ .and_then(|overlay| overlay.child()) ++ .and_then(|widget| widget.downcast::().ok()) ++ .unwrap_or_else(|| vbox.clone()) ++} ++ ++// GTK owns the layout for exactly the lifetime of its window. Keeping the ++// overlay inside Tao's vbox leaves the menu bar outside content coordinates. ++pub(crate) fn containers(vbox: >k::Box) -> (gtk::Box, gtk::Fixed) { ++ if let Some(overlay) = vbox.children().into_iter().find_map(|widget| { ++ (widget.widget_name() == NAME) ++ .then(|| widget.downcast::().ok()) ++ .flatten() ++ }) { ++ let content = overlay.child().unwrap().downcast::().unwrap(); ++ let children = overlay ++ .children() ++ .into_iter() ++ .find_map(|widget| widget.downcast::().ok()) ++ .unwrap(); ++ return (content, children); ++ } ++ ++ let overlay = gtk::Overlay::new(); ++ overlay.set_widget_name(NAME); ++ let content = gtk::Box::new(gtk::Orientation::Vertical, 0); ++ let children = gtk::Fixed::new(); ++ overlay.add(&content); ++ // The primary-only path keeps Tao's original box. Install the overlay lazily ++ // on first child creation and move only its existing WebKit content. ++ for widget in vbox.children() { ++ if widget.is::() { ++ vbox.remove(&widget); ++ content.pack_start(&widget, true, true, 0); ++ } ++ } ++ overlay.add_overlay(&children); ++ // GtkFixed has no native input window; WebKit's child windows receive input ++ // inside their rectangles, while the uncovered area reaches the main view. ++ overlay.set_overlay_pass_through(&children, true); ++ vbox.pack_start(&overlay, true, true, 0); ++ overlay.show_all(); ++ (content, children) ++} +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -145,6 +145,14 @@ + + #[cfg(not(debug_assertions))] + mod dialog; ++#[cfg(any( ++ target_os = "linux", ++ target_os = "dragonfly", ++ target_os = "freebsd", ++ target_os = "netbsd", ++ target_os = "openbsd" ++))] ++mod gtk_child_layout; + mod monitor; + #[cfg(any( + windows, +@@ -3616,7 +3624,8 @@ + ))] + let reparent_result = { + if let Some(container) = new_parent_window.default_vbox() { +- webview.inner.reparent(container) ++ let (_, children) = gtk_child_layout::containers(container); ++ webview.inner.reparent(&children) + } else { + Err(wry::Error::MessageSender) + } +@@ -5169,9 +5178,9 @@ + target_os = "android" + )))] + WebviewKind::WindowChild => { +- // only way to account for menu bar height, and also works for multiwebviews :) + let vbox = window.default_vbox().unwrap(); +- webview_builder.build_gtk(vbox) ++ let (_, children) = gtk_child_layout::containers(vbox); ++ webview_builder.build_gtk(&children) + } + #[cfg(any( + target_os = "windows", +@@ -5196,7 +5205,8 @@ + )))] + let builder = { + let vbox = window.default_vbox().unwrap(); +- webview_builder.build_gtk(vbox) ++ let content = gtk_child_layout::content(vbox); ++ webview_builder.build_gtk(&content) + }; + builder + } diff --git a/packages/tauri-app/vendor/patches/wry-browser-download.patch b/packages/tauri-app/vendor/patches/wry-browser-download.patch new file mode 100644 index 0000000000..5c1ebdfc0f --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-browser-download.patch @@ -0,0 +1,59 @@ +diff --git a/src/wkwebview/class/wry_navigation_delegate.rs b/src/wkwebview/class/wry_navigation_delegate.rs +index be40aa62f..9a5c54c21 100644 +--- a/src/wkwebview/class/wry_navigation_delegate.rs ++++ b/src/wkwebview/class/wry_navigation_delegate.rs +@@ -19,7 +19,7 @@ use objc2_web_kit::WKWebView; + use crate::{ + PageLoadEvent, WryWebView, url_from_webview, + wkwebview::{ +- download::{navigation_download_action, navigation_download_response}, ++ download::{attach_download_delegate, navigation_download_action, navigation_download_response}, + navigation::{ + did_commit_navigation, did_finish_navigation, navigation_policy, navigation_policy_response, + web_content_process_did_terminate, +@@ -46,6 +46,15 @@ define_class!( + + unsafe impl NSObjectProtocol for WryNavigationDelegate {} + ++ impl WryNavigationDelegate { ++ // WKNavigationDelegatePrivate.h: native Download Image bypasses navigation policies. ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(_webView:contextMenuDidCreateDownload:))] ++ fn context_menu_download(&self, _webview: &WKWebView, download: &WKDownload) { ++ attach_download_delegate(self, download); ++ } ++ } ++ + unsafe impl WKNavigationDelegate for WryNavigationDelegate { + #[unsafe(method(webView:decidePolicyForNavigationAction:decisionHandler:))] + fn navigation_policy( +diff --git a/src/wkwebview/download.rs b/src/wkwebview/download.rs +index 6b94501a0..917ec4487 100644 +--- a/src/wkwebview/download.rs ++++ b/src/wkwebview/download.rs +@@ -20,12 +20,7 @@ pub(crate) fn navigation_download_action( + _action: &WKNavigationAction, + download: &WKDownload, + ) { +- unsafe { +- if let Some(delegate) = &this.ivars().download_delegate { +- let proto_delegate = ProtocolObject::from_ref(&**delegate); +- download.setDelegate(Some(proto_delegate)); +- } +- } ++ attach_download_delegate(this, download); + } + + // Download response handler +@@ -35,6 +30,11 @@ pub(crate) fn navigation_download_response( + _response: &WKNavigationResponse, + download: &WKDownload, + ) { ++ attach_download_delegate(this, download); ++} ++ ++// Navigation and native context-menu downloads share the same destination policy. ++pub(crate) fn attach_download_delegate(this: &WryNavigationDelegate, download: &WKDownload) { + unsafe { + if let Some(delegate) = &this.ivars().download_delegate { + let proto_delegate = ProtocolObject::from_ref(&**delegate); diff --git a/packages/tauri-app/vendor/patches/wry-browser-isolation.patch b/packages/tauri-app/vendor/patches/wry-browser-isolation.patch new file mode 100644 index 0000000000..936735fffc --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-browser-isolation.patch @@ -0,0 +1,71 @@ +diff --git a/src/webview2/mod.rs b/src/webview2/mod.rs +index 485bb4ed2..a5b978aeb 100644 +--- a/src/webview2/mod.rs ++++ b/src/webview2/mod.rs +@@ -692,10 +692,27 @@ impl InnerWebView { + ) -> Result<()> { + unsafe { + // Close container HWND when `window.close` is called in JS +- webview.add_WindowCloseRequested( +- &WindowCloseRequestedEventHandler::create(Box::new(move |_, _| DestroyWindow(hwnd))), +- token, +- )?; ++ if attributes ++ .id ++ .is_none_or(|id| !id.starts_with("browser-") || id.starts_with("browser-popup-")) ++ { ++ // Wry owns a child container even in a top-level Tauri window. A guest ++ // popup's script closure must dispose that top-level window as well. ++ let close_hwnd = if attributes ++ .id ++ .is_some_and(|id| id.starts_with("browser-popup-")) ++ { ++ GetAncestor(hwnd, GA_ROOT) ++ } else { ++ hwnd ++ }; ++ webview.add_WindowCloseRequested( ++ &WindowCloseRequestedEventHandler::create(Box::new(move |_, _| { ++ DestroyWindow(close_hwnd) ++ })), ++ token, ++ )?; ++ } + + // Document title changed handler + if let Some(document_title_changed_handler) = attributes.document_title_changed_handler.take() +diff --git a/src/wkwebview/class/wry_web_view_ui_delegate.rs b/src/wkwebview/class/wry_web_view_ui_delegate.rs +index 7c3af49e9..9280f1844 100644 +--- a/src/wkwebview/class/wry_web_view_ui_delegate.rs ++++ b/src/wkwebview/class/wry_web_view_ui_delegate.rs +@@ -96,6 +96,30 @@ define_class!( + unsafe impl NSObjectProtocol for WryWebViewUIDelegate {} + + unsafe impl WKUIDelegate for WryWebViewUIDelegate { ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(webView:requestDeviceOrientationAndMotionPermissionForOrigin:initiatedByFrame:decisionHandler:))] ++ fn request_orientation_permission( ++ &self, ++ _webview: &WryWebView, ++ _origin: &WKSecurityOrigin, ++ _frame: &WKFrameInfo, ++ completion: &Block, ++ ) { ++ let decision = if self.ivars().preview_dialogs { ++ match self ++ .ivars() ++ .permission_handler ++ .as_ref() ++ .map(|handler| handler(PermissionKind::Sensors)) ++ { ++ Some(PermissionResponse::Deny) => WKPermissionDecision::Deny, ++ _ => WKPermissionDecision::Prompt, ++ } ++ } else { ++ WKPermissionDecision::Prompt ++ }; ++ completion.call((decision,)); ++ } + #[cfg(target_os = "macos")] + #[unsafe(method(webViewDidClose:))] + fn web_view_did_close(&self, webview: &WryWebView) { diff --git a/packages/tauri-app/vendor/patches/wry-browser-print.patch b/packages/tauri-app/vendor/patches/wry-browser-print.patch new file mode 100644 index 0000000000..f26f52113a --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-browser-print.patch @@ -0,0 +1,51 @@ +diff --git a/src/wkwebview/class/wry_web_view_ui_delegate.rs b/src/wkwebview/class/wry_web_view_ui_delegate.rs +--- a/src/wkwebview/class/wry_web_view_ui_delegate.rs ++++ b/src/wkwebview/class/wry_web_view_ui_delegate.rs +@@ -98,1 +98,28 @@ define_class!( ++ // WebKit's native window.print/beforeunload hooks are declared in ++ // Source/WebKit/UIProcess/API/Cocoa/WKUIDelegatePrivate.h (macOS 12+). ++ // They are confined to preview delegates; the page receives no app bridge. ++ impl WryWebViewUIDelegate { ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(_webView:printFrame:))] ++ fn print_frame(&self, webview: &WryWebView, _frame: &NSObject) { ++ if self.ivars().preview_dialogs { preview_print(webview); } ++ } ++ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(_webView:printFrame:pdfFirstPageSize:completionHandler:))] ++ fn print_frame_with_completion(&self, webview: &WryWebView, _frame: &NSObject, ++ _size: objc2_foundation::NSSize, completion: &Block) { ++ if self.ivars().preview_dialogs { preview_print(webview); } ++ completion.call(()); ++ } ++ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(_webView:runBeforeUnloadConfirmPanelWithMessage:initiatedByFrame:completionHandler:))] ++ fn before_unload(&self, webview: &WryWebView, message: &objc2_foundation::NSString, ++ frame: &WKFrameInfo, completion: &Block) { ++ if !self.ivars().preview_dialogs { completion.call((true.into(),)); return; } ++ self.javascript_confirm(objc2::sel!(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:), webview, message, frame, completion); ++ } ++ } ++ + unsafe impl WKUIDelegate for WryWebViewUIDelegate { +@@ -436,1 +463,18 @@ impl WryWebViewUIDelegate { ++#[cfg(target_os = "macos")] ++fn preview_print(webview: &WryWebView) { ++ // Use the same public print operation as Wry's host-initiated printing. ++ unsafe { ++ if webview.window().is_none() ++ || objc2_app_kit::NSPrintOperation::currentOperation(MainThreadMarker::new().unwrap()) ++ .is_some() ++ { ++ return; ++ } ++ let info = objc2_app_kit::NSPrintInfo::sharedPrintInfo(); ++ let operation = webview.printOperationWithPrintInfo(&info); ++ operation.setCanSpawnSeparateThread(true); ++ operation.runOperation(); ++ } ++} ++ + #[cfg(target_os = "macos")] diff --git a/packages/tauri-app/vendor/patches/wry-gtk.patch b/packages/tauri-app/vendor/patches/wry-gtk.patch new file mode 100644 index 0000000000..8c9ec9e08a --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-gtk.patch @@ -0,0 +1,149 @@ +--- a/src/webkitgtk/mod.rs ++++ b/src/webkitgtk/mod.rs +@@ -2,7 +2,6 @@ + // SPDX-License-Identifier: Apache-2.0 + // SPDX-License-Identifier: MIT + +-#[cfg(feature = "x11")] + use dpi::LogicalPosition; + use dpi::LogicalSize; + use ffi::CookieManageExt; +@@ -91,7 +90,6 @@ + #[cfg(any(debug_assertions, feature = "devtools"))] + is_inspector_open: Arc, + pending_scripts: Arc>>>, +- is_in_fixed_parent: bool, + + #[cfg(feature = "x11")] + x11: Option, +@@ -323,7 +321,7 @@ + + web_context.register_automation(webview.clone()); + +- let is_in_fixed_parent = Self::add_to_container(&webview, container, &attributes); ++ Self::add_to_container(&webview, container, &attributes); + + #[cfg(any(debug_assertions, feature = "devtools"))] + let is_inspector_open = Self::attach_inspector_handlers(&webview); +@@ -339,7 +337,6 @@ + webview, + pending_scripts: Arc::new(Mutex::new(Some(Vec::new()))), + +- is_in_fixed_parent, + #[cfg(feature = "x11")] + x11: None, + +@@ -688,12 +685,10 @@ + } + } + +- fn add_to_container(webview: &WebView, container: &W, attributes: &WebViewAttributes) -> bool ++ fn add_to_container(webview: &WebView, container: &W, attributes: &WebViewAttributes) + where + W: IsA, + { +- let mut is_in_fixed_parent = false; +- + let container_type = container.type_().name(); + if container_type == "GtkBox" { + container +@@ -720,12 +715,10 @@ + .unwrap() + .put(webview, x, y); + +- is_in_fixed_parent = true; + } else { + container.add(webview); + } + +- is_in_fixed_parent + } + + fn attach_ipc_handler(webview: WebView, ipc_handler: Box)>) { +@@ -735,10 +728,14 @@ + .expect("WebView does not have UserContentManager"); + + // Connect before registering as recommended by the docs ++ let webview = webview.downgrade(); + manager.connect_script_message_received(None, move |_m, msg| { + #[cfg(feature = "tracing")] + let _span = tracing::info_span!(parent: None, "wry::ipc::handle").entered(); + ++ let Some(webview) = webview.upgrade() else { ++ return; ++ }; + if let Some(js) = msg.js_value() { + let uri = webview.uri().map(|u| u.to_string()).unwrap_or_default(); + match Request::builder().uri(uri).body(js.to_string()) { +@@ -968,6 +965,20 @@ + } + + let (size, _) = self.webview.allocated_size(); ++ if let Some(parent) = self ++ .webview ++ .parent() ++ .and_then(|p| p.downcast::().ok()) ++ { ++ // Hidden widgets can have a stale allocation. Read GtkFixed's retained ++ // layout so sequential position/size updates preserve both coordinates. ++ let x = parent.child_property::(&self.webview, "x"); ++ let y = parent.child_property::(&self.webview, "y"); ++ let (width, height) = self.webview.size_request(); ++ bounds.position = LogicalPosition::new(x, y).into(); ++ bounds.size = LogicalSize::new(width.max(1), height.max(1)).into(); ++ return Ok(bounds); ++ } + bounds.size = LogicalSize::new(size.width(), size.height()).into(); + + Ok(bounds) +@@ -988,7 +999,15 @@ + window.size_allocate(>k::Allocation::new(0, 0, width, height)); + } + +- if self.is_in_fixed_parent { ++ if let Some(parent) = self ++ .webview ++ .parent() ++ .and_then(|p| p.downcast::().ok()) ++ { ++ // Persist both properties in GtkFixed's layout state so the next parent ++ // allocation (resize, hide/show, menu changes) preserves the rectangle. ++ self.webview.set_size_request(width, height); ++ parent.move_(&self.webview, x, y); + self + .webview + .size_allocate(>k::Allocation::new(x, y, width, height)); +@@ -1237,6 +1256,7 @@ + .parent() + .and_then(|p| p.dynamic_cast::().ok()) + { ++ let bounds = self.bounds()?; + parent.remove(&self.webview); + + let container_type = container.type_().name(); +@@ -1246,10 +1266,21 @@ + .unwrap() + .pack_start(&self.webview, true, true, 0); + } else if container_type == "GtkFixed" { +- container +- .dynamic_cast_ref::() +- .unwrap() +- .put(&self.webview, 0, 0); ++ let size = bounds ++ .size ++ .to_logical::(self.webview.scale_factor() as f64); ++ self.webview.set_size_request(size.width, size.height); ++ container.dynamic_cast_ref::().unwrap().put( ++ &self.webview, ++ bounds ++ .position ++ .to_logical::(self.webview.scale_factor() as f64) ++ .x, ++ bounds ++ .position ++ .to_logical::(self.webview.scale_factor() as f64) ++ .y, ++ ); + } else { + container.add(&self.webview); + } diff --git a/packages/tauri-app/vendor/patches/wry-webkit-capabilities.patch b/packages/tauri-app/vendor/patches/wry-webkit-capabilities.patch new file mode 100644 index 0000000000..7e1f4fc51a --- /dev/null +++ b/packages/tauri-app/vendor/patches/wry-webkit-capabilities.patch @@ -0,0 +1,312 @@ +diff --git a/Cargo.toml b/Cargo.toml +index 16bd55ab8..9731746c0 100644 +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -278,9 +278,12 @@ default-features = false + version = "0.3.2" + features = [ + "std", ++ "block2", + "objc2-core-foundation", + "NSApplication", + "NSButton", ++ "NSAlert", ++ "NSTextField", + "NSControl", + "NSEvent", + "NSWindow", +diff --git a/src/webkitgtk/mod.rs b/src/webkitgtk/mod.rs +index d225c9648..bca5da85d 100644 +--- a/src/webkitgtk/mod.rs ++++ b/src/webkitgtk/mod.rs +@@ -46,7 +46,7 @@ use webkit2gtk::{ + }; + use webkit2gtk_sys::{ + webkit_get_major_version, webkit_get_micro_version, webkit_get_minor_version, +- webkit_policy_decision_ignore, webkit_policy_decision_use, ++ webkit_policy_decision_download, webkit_policy_decision_ignore, webkit_policy_decision_use, + }; + #[cfg(feature = "x11")] + use x11_dl::xlib::*; +@@ -468,7 +468,25 @@ impl InnerWebView { + attributes: &mut WebViewAttributes, + ) { + // window.close() +- webview.connect_close(move |webview| unsafe { webview.destroy() }); ++ let browser = attributes.id.is_some_and(|id| id.starts_with("browser-")); ++ let popup = attributes ++ .id ++ .is_some_and(|id| id.starts_with("browser-popup-")); ++ webview.connect_close(move |webview| unsafe { ++ if popup { ++ if let Some(window) = webview ++ .toplevel() ++ .and_then(|widget| widget.downcast::().ok()) ++ { ++ window.destroy(); ++ return; ++ } ++ } ++ // Embedded preview roots are closed by their host, like WKWebView roots. ++ if !browser { ++ webview.destroy(); ++ } ++ }); + + // Synthetic mouse events + synthetic_mouse_events::setup(webview); +@@ -556,6 +574,7 @@ impl InnerWebView { + } + + // Navigation handler ++ let browser_downloads = attributes.id.is_some_and(|id| id.starts_with("browser-")); + if let Some(navigation_handler) = attributes.navigation_handler.take() { + webview.connect_decide_policy(move |_webview, policy_decision, policy_type| { + let handler = match policy_type { +@@ -572,6 +591,12 @@ impl InnerWebView { + unsafe { + if allow { + webkit_policy_decision_use(pointer) ++ } else if browser_downloads ++ && (uri.starts_with("blob:") || uri.starts_with("data:")) ++ { ++ // Generated content can be saved, but never becomes a document ++ // in a browser preview whose navigation policy rejected it. ++ webkit_policy_decision_download(pointer) + } else { + webkit_policy_decision_ignore(pointer) + } +@@ -679,6 +704,7 @@ impl InnerWebView { + || attributes.download_completed_handler.is_some() + { + web_context.register_download_handler( ++ &webview, + attributes.download_started_handler.take(), + attributes.download_completed_handler.take(), + ) +@@ -714,11 +740,9 @@ impl InnerWebView { + .dynamic_cast_ref::() + .unwrap() + .put(webview, x, y); +- + } else { + container.add(webview); + } +- + } + + fn attach_ipc_handler(webview: WebView, ipc_handler: Box)>) { +diff --git a/src/webkitgtk/web_context.rs b/src/webkitgtk/web_context.rs +index 861046759..1be7136f4 100644 +--- a/src/webkitgtk/web_context.rs ++++ b/src/webkitgtk/web_context.rs +@@ -117,6 +117,7 @@ pub trait WebContextExt { + + fn register_download_handler( + &mut self, ++ webview: &WebView, + download_started_callback: Option bool>>, + download_completed_callback: Option, bool) + 'static>>, + ); +@@ -306,14 +307,23 @@ impl WebContextExt for super::WebContext { + + fn register_download_handler( + &mut self, ++ webview: &WebView, + download_started_handler: Option bool>>, + download_completed_handler: Option, bool) + 'static>>, + ) { + let context = &self.os.context; + + let download_started_handler = Rc::new(RefCell::new(download_started_handler)); ++ let webview = webview.downgrade(); + + context.connect_download_started(move |_context, download| { ++ let Some(webview) = webview.upgrade() else { ++ return; ++ }; ++ if download.web_view().as_ref() != Some(&webview) { ++ return; ++ } ++ download.set_allow_overwrite(false); + // Failure belongs to this download, not every download in the context. + let failed = Rc::new(RefCell::new(false)); + let download_started_handler = download_started_handler.clone(); +@@ -354,7 +364,9 @@ impl WebContextExt for super::WebContext { + } + + if download_started_handler(uri, &mut download_destination) { +- download.set_destination(&download_destination.to_string_lossy()); ++ use gtk::gio::prelude::FileExt; ++ let uri = gtk::gio::File::for_path(&download_destination).uri(); ++ download.set_destination(&uri); + } else { + download.cancel(); + } +diff --git a/src/wkwebview/class/wry_web_view_ui_delegate.rs b/src/wkwebview/class/wry_web_view_ui_delegate.rs +index 5ba4ddbb9..7c3af49e9 100644 +--- a/src/wkwebview/class/wry_web_view_ui_delegate.rs ++++ b/src/wkwebview/class/wry_web_view_ui_delegate.rs +@@ -83,6 +83,8 @@ pub struct WryWebViewUIDelegateIvars { + #[cfg(target_os = "macos")] + new_windows: Rc>>, + permission_handler: Option PermissionResponse + Send + Sync>>, ++ preview_dialogs: bool, ++ popup: bool, + } + + define_class!( +@@ -94,6 +96,95 @@ define_class!( + unsafe impl NSObjectProtocol for WryWebViewUIDelegate {} + + unsafe impl WKUIDelegate for WryWebViewUIDelegate { ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(webViewDidClose:))] ++ fn web_view_did_close(&self, webview: &WryWebView) { ++ if self.ivars().popup { ++ if let Some(window) = webview.window() { ++ window.close(); ++ } ++ } ++ } ++ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:))] ++ fn javascript_alert( ++ &self, ++ webview: &WryWebView, ++ message: &objc2_foundation::NSString, ++ frame: &WKFrameInfo, ++ completion: &Block, ++ ) { ++ let Some(window) = webview.window().filter(|_| self.ivars().preview_dialogs) else { ++ completion.call(()); ++ return; ++ }; ++ let alert = preview_alert(message, frame, false); ++ let completion = completion.copy(); ++ let callback = block2::RcBlock::new(move |_| completion.call(())); ++ alert.beginSheetModalForWindow_completionHandler(&window, Some(&callback)); ++ } ++ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:))] ++ fn javascript_confirm( ++ &self, ++ webview: &WryWebView, ++ message: &objc2_foundation::NSString, ++ frame: &WKFrameInfo, ++ completion: &Block, ++ ) { ++ let Some(window) = webview.window().filter(|_| self.ivars().preview_dialogs) else { ++ completion.call((false.into(),)); ++ return; ++ }; ++ let alert = preview_alert(message, frame, true); ++ let completion = completion.copy(); ++ let callback = block2::RcBlock::new(move |response| { ++ completion.call(((response == objc2_app_kit::NSAlertFirstButtonReturn).into(),)) ++ }); ++ alert.beginSheetModalForWindow_completionHandler(&window, Some(&callback)); ++ } ++ ++ #[cfg(target_os = "macos")] ++ #[unsafe(method(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:))] ++ fn javascript_prompt( ++ &self, ++ webview: &WryWebView, ++ message: &objc2_foundation::NSString, ++ default_text: Option<&objc2_foundation::NSString>, ++ frame: &WKFrameInfo, ++ completion: &Block, ++ ) { ++ let Some(window) = webview.window().filter(|_| self.ivars().preview_dialogs) else { ++ completion.call((std::ptr::null(),)); ++ return; ++ }; ++ let mtm = MainThreadMarker::new().unwrap(); ++ let alert = preview_alert(message, frame, true); ++ let input = objc2_app_kit::NSTextField::initWithFrame( ++ mtm.alloc(), ++ objc2_foundation::NSRect::new( ++ objc2_foundation::NSPoint::new(0.0, 0.0), ++ objc2_foundation::NSSize::new(320.0, 24.0), ++ ), ++ ); ++ if let Some(text) = default_text { ++ input.setStringValue(text); ++ } ++ alert.setAccessoryView(Some(&input)); ++ let completion = completion.copy(); ++ let callback = block2::RcBlock::new(move |response| { ++ if response == objc2_app_kit::NSAlertFirstButtonReturn { ++ let value = input.stringValue(); ++ completion.call((Retained::as_ptr(&value),)); ++ } else { ++ completion.call((std::ptr::null(),)); ++ } ++ }); ++ alert.beginSheetModalForWindow_completionHandler(&window, Some(&callback)); ++ } ++ + #[cfg(target_os = "macos")] + #[unsafe(method(webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:))] + fn run_file_upload_panel( +@@ -297,6 +388,8 @@ impl WryWebViewUIDelegate { + mtm: MainThreadMarker, + new_window_req_handler: Option NewWindowResponse>>, + permission_handler: Option PermissionResponse + Send + Sync>>, ++ preview_dialogs: bool, ++ popup: bool, + ) -> Retained { + #[cfg(target_os = "ios")] + let _new_window_req_handler = new_window_req_handler; +@@ -309,7 +402,33 @@ impl WryWebViewUIDelegate { + #[cfg(target_os = "macos")] + new_windows: Rc::new(RefCell::new(vec![])), + permission_handler, ++ preview_dialogs, ++ popup, + }); + unsafe { msg_send![super(delegate), init] } + } + } ++ ++#[cfg(target_os = "macos")] ++fn preview_alert( ++ message: &objc2_foundation::NSString, ++ frame: &WKFrameInfo, ++ cancel: bool, ++) -> Retained { ++ use objc2::ClassType; ++ use objc2_foundation::{NSBundle, NSString}; ++ let alert = objc2_app_kit::NSAlert::new(MainThreadMarker::new().unwrap()); ++ // Site-controlled text is always identified by the initiating frame's host. ++ let host = unsafe { frame.securityOrigin().host() }; ++ alert.setMessageText(&host); ++ alert.setInformativeText(message); ++ if cancel { ++ let bundle = unsafe { NSBundle::bundleForClass(objc2_app_kit::NSAlert::class()) }; ++ for key in ["OK", "Cancel"] { ++ let key = NSString::from_str(key); ++ let title = bundle.localizedStringForKey_value_table(&key, Some(&key), None); ++ alert.addButtonWithTitle(&title); ++ } ++ } ++ alert ++} +diff --git a/src/wkwebview/mod.rs b/src/wkwebview/mod.rs +index 25c7ce8e5..9b1db532b 100644 +--- a/src/wkwebview/mod.rs ++++ b/src/wkwebview/mod.rs +@@ -653,6 +653,10 @@ impl InnerWebView { + mtm, + attributes.new_window_req_handler, + attributes.permission_handler, ++ attributes.id.is_some_and(|id| id.starts_with("browser-")), ++ attributes ++ .id ++ .is_some_and(|id| id.starts_with("browser-popup-")), + ); + let proto_ui_delegate = ProtocolObject::from_ref(&*ui_delegate); + webview.setUIDelegate(Some(proto_ui_delegate)); diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/.cargo_vcs_info.json b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/.cargo_vcs_info.json new file mode 100644 index 0000000000..c8b9c928df --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "993038c49185307dfc895ab7657d77ca0d5ed7c7" + }, + "path_in_vcs": "crates/tauri-runtime-wry" +} \ No newline at end of file diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.lock b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.lock new file mode 100644 index 0000000000..68166ab1cd --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.lock @@ -0,0 +1,3622 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.4", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.0", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "cc" +version = "1.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a0aeaff4ff1a90589618835a598e545176939b97874f7abc7851caa0618f203" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-link 0.1.1", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.13.0", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.0", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.0", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a2a99df6e410a8ff4245aa2006499ea662245f967cc7c0a38c83ef8eb44dbf" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "ctor" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01334b89b69ff726750c5ce5073fc8bd860e99aa9a8fc5ca11b04730e3aee97a" + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dbus" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b3aa68d7e7abee336255bd7248ea965cc393f3e70411135a6f6a4b651345d4" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_more" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "libc", + "objc2 0.6.4", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dlopen2" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b54f373ccf864bf587a89e880fb7610f8d73f3045f13580948ccbcaff26febff" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b99bf03862d7f545ebc28ddd33a665b50865f4dfd84031a393823879bd4c54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set", + "cssparser", + "foldhash", + "html5ever", + "precomputed-hash", + "selectors", + "tendril", +] + +[[package]] +name = "dpi" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f25c0e292a7ca6d6498557ff1df68f32c99850012b6ea401cf8daf771f22ff53" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcbb2bf8e87535c23f7a8a321e364ce21462d0ff10cb6407820e8e96dfff6653" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "erased-serde" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645cbb3a84e60b7531617d5ae4e57f7e27308f6445f5abf653209ea76dec8dff" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.0", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.0", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever", +] + +[[package]] +name = "http" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core 0.52.0", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" +dependencies = [ + "cfb", +] + +[[package]] +name = "itoa" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "js-sys" +version = "0.3.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags 2.13.0", + "libc", +] + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.0", + "jni-sys", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" +dependencies = [ + "proc-macro-crate 3.2.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.0", + "dispatch2", + "objc2 0.6.4", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.0", + "dispatch2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.6", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" + +[[package]] +name = "plist" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85" +dependencies = [ + "base64", + "indexmap 2.11.4", + "quick-xml", + "serde", + "time", +] + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" +dependencies = [ + "toml_edit 0.20.7", +] + +[[package]] +name = "proc-macro-crate" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecf48c7ca261d60b74ab1a7b20da18bede46776b2e55535cb958eb595c5fa7b" +dependencies = [ + "toml_edit 0.22.24", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +dependencies = [ + "bitflags 2.13.0", +] + +[[package]] +name = "redox_users" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" +dependencies = [ + "getrandom", + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.0", + "cssparser", + "derive_more", + "log", + "new_debug_unreachable", + "phf", + "phf_codegen", + "precomputed-hash", + "rustc-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2676ba99bd82f75cae5cbd2c8eda6fa0b8760f18978ea840e980dd5567b5c5b6" +dependencies = [ + "erased-serde", + "serde", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_with" +version = "3.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.11.4", + "schemars 0.9.0", + "schemars 1.2.2", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "softbuffer" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08" +dependencies = [ + "bytemuck", + "cfg_aliases", + "core-graphics 0.24.0", + "foreign-types", + "js-sys", + "log", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", + "raw-window-handle", + "redox_syscall", + "wasm-bindgen", + "web-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.20", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d12c8607b01516c5d4a37e471a9cfb40b4a25cebce8fecbc6a559e125e51b6b" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "core-foundation", + "core-graphics 0.25.0", + "crossbeam-channel", + "dbus", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2 0.6.4", + "objc2-app-kit", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "once_cell", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core 0.62.0", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri-runtime" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni", + "objc2 0.6.4", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.12.3" +dependencies = [ + "gtk", + "http", + "jni", + "log", + "objc2 0.6.4", + "objc2-app-kit", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "tracing", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" +dependencies = [ + "anyhow", + "ctor", + "dunce", + "glob", + "http", + "infer", + "json-patch", + "log", + "memchr", + "phf", + "plist", + "regex", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "thiserror 2.0.21", + "toml 1.0.6+spec-1.1.0", + "url", + "urlpattern", + "uuid", +] + +[[package]] +name = "tendril" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4790fc369d5a530f4b544b094e31388b9b3a37c0f4652ade4505945f5660d24" +dependencies = [ + "new_debug_unreachable", + "utf-8", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "time" +version = "0.3.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcef1a61bdb119096e153208ec5cbec23944ce8bca13be5c7f60c634f7403935" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "022db8904dfa342efe721985167e9fcd16c29b226db4397ed752a761cfce81e8" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "toml" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" +dependencies = [ + "serde", + "serde_spanned 0.6.8", + "toml_datetime 0.6.8", + "toml_edit 0.22.24", +] + +[[package]] +name = "toml" +version = "1.0.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "399b1124a3c9e16766831c6bba21e50192572cdd98706ea114f9502509686ffc" +dependencies = [ + "indexmap 2.11.4", + "serde_core", + "serde_spanned 1.0.4", + "toml_datetime 1.0.0+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.14", +] + +[[package]] +name = "toml_datetime" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.0.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.11.4", + "toml_datetime 0.6.8", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" +dependencies = [ + "indexmap 2.11.4", + "toml_datetime 0.6.8", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.22.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" +dependencies = [ + "indexmap 2.11.4", + "serde", + "serde_spanned 0.6.8", + "toml_datetime 0.6.8", + "winnow 0.7.14", +] + +[[package]] +name = "toml_parser" +version = "1.0.9+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4" +dependencies = [ + "winnow 0.7.14", +] + +[[package]] +name = "toml_writer" +version = "1.0.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tracing-core" +version = "0.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typeid" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e13db2e0ccd5e14a544e8a246ba2312cd25223f616442d7f2cb0e3db614236e" + +[[package]] +name = "typenum" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" + +[[package]] +name = "unicode-ident" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" + +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlpattern" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" +dependencies = [ + "icu_properties", + "regex", + "serde", + "url", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" +dependencies = [ + "serde", +] + +[[package]] +name = "version-compare" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852e951cb7832cb45cb1169900d19760cfa39b82bc0ea9c0e5a14ae88411c98b" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.117", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webview2-com" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core 0.62.0", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "webview2-com-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core 0.62.0", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9579d0e6970fd5250aa29aba5994052385ff55cf7b28a059e484bb79ea842e42" +dependencies = [ + "windows-collections", + "windows-core 0.62.0", + "windows-future", + "windows-link 0.2.1", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a90dd7a7b86859ec4cdf864658b311545ef19dbcf17a672b52ab7cefe80c336f" +dependencies = [ + "windows-core 0.62.0", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.62.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57fe7168f7de578d2d8a05b07fd61870d2e73b4020e9f49aa00da8471723497c" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.1", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2194dee901458cb79e1148a4e9aac2b164cc95fa431891e7b296ff0b2f1d8a6" +dependencies = [ + "windows-core 0.62.0", + "windows-link 0.2.1", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.59.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-link" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ce3498fe0aba81e62e477408383196b4b0363db5e0c27646f932676283b43d8" +dependencies = [ + "windows-core 0.62.0", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-version" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c12476c23a74725c539b24eae8bfc0dac4029c39cdb561d9f23616accd4ae26d" +dependencies = [ + "windows-targets 0.53.2", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wry" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0" +dependencies = [ + "base64", + "block2 0.6.2", + "cookie", + "crossbeam-channel", + "dirs", + "dom_query", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni", + "libc", + "ndk", + "objc2 0.6.4", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "tracing", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core 0.62.0", + "windows-version", + "x11-dl", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml new file mode 100644 index 0000000000..c4001dc0e4 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml @@ -0,0 +1,153 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.90" +name = "tauri-runtime-wry" +version = "2.12.3" +authors = ["Tauri Programme within The Commons Conservancy"] +build = "build.rs" +exclude = [ + "CHANGELOG.md", + "/target", +] +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Wry bindings to the Tauri runtime" +homepage = "https://tauri.app/" +readme = "README.md" +categories = [ + "gui", + "web-programming", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/tauri-apps/tauri" + +[features] +common-controls-v6 = [ + "windows/Win32_UI_Controls", + "windows/Win32_UI_Shell", +] +dbus = ["tao/dbus"] +default = [ + "x11", + "dbus", +] +devtools = [ + "wry/devtools", + "tauri-runtime/devtools", +] +macos-private-api = ["tauri-runtime/macos-private-api"] +macos-proxy = ["wry/mac-proxy"] +objc-exception = [] +tracing = [ + "dep:tracing", + "wry/tracing", +] +unstable = [] +x11 = [ + "tao/x11", + "wry/x11", +] + +[lib] +name = "tauri_runtime_wry" +path = "src/lib.rs" + +[dependencies.http] +version = "1" + +[dependencies.log] +version = "0.4.21" + +[dependencies.raw-window-handle] +version = "0.6" + +[dependencies.tao] +version = "0.37.0" +features = ["rwh_06"] +default-features = false + +[dependencies.tauri-runtime] +version = "~2.12.2" + +[dependencies.tauri-utils] +version = "~2.10.2" + +[dependencies.tracing] +version = "0.1" +optional = true + +[dependencies.url] +version = "2" + +[dependencies.wry] +version = "0.57.0" +features = [ + "os-webview", + "linux-body", +] +default-features = false + +[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies.gtk] +version = "0.18" +features = ["v3_24"] + +[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies.percent-encoding] +version = "2" + +[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies.webkit2gtk] +version = "=2.0" +features = ["v2_40"] + +[target.'cfg(target_os = "android")'.dependencies.jni] +version = "0.21" + +[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit] +version = "0.3.2" +features = [ + "block2", + "NSApplication", + "NSResponder", + "NSView", + "NSWindow", + "NSScreen", + "NSGraphics", +] +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2] +version = "0.6" + +[target."cfg(windows)".dependencies.softbuffer] +version = "0.4" +default-features = false + +[target."cfg(windows)".dependencies.webview2-com] +version = "0.39" + +[target."cfg(windows)".dependencies.windows] +version = "0.62" +features = [ + "Win32_Foundation", + "Win32_Graphics_Dwm", + "Win32_UI_WindowsAndMessaging", +] + +[lints.clippy] +assigning_clones = "warn" +collapsible_if = "allow" +or_fun_call = "warn" +redundant_clone = "warn" diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml.orig b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml.orig new file mode 100644 index 0000000000..d1f8a9d053 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/Cargo.toml.orig @@ -0,0 +1,77 @@ +[package] +name = "tauri-runtime-wry" +version = "2.12.3" +description = "Wry bindings to the Tauri runtime" +exclude = ["CHANGELOG.md", "/target"] +authors.workspace = true +homepage.workspace = true +repository.workspace = true +categories.workspace = true +license.workspace = true +edition.workspace = true +rust-version.workspace = true + +[dependencies] +wry = { version = "0.57.0", default-features = false, features = [ + "os-webview", + "linux-body", +] } +tao = { version = "0.37.0", default-features = false, features = ["rwh_06"] } +tauri-runtime = { workspace = true } +tauri-utils = { workspace = true } +raw-window-handle = "0.6" +http = "1" +url = "2" +tracing = { version = "0.1", optional = true } +log = "0.4.21" + +[target."cfg(windows)".dependencies] +webview2-com = "0.39" +softbuffer = { version = "0.4", default-features = false } + +[target."cfg(windows)".dependencies.windows] +version = "0.62" +features = [ + "Win32_Foundation", + "Win32_Graphics_Dwm", + "Win32_UI_WindowsAndMessaging", +] + +[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies] +gtk = { version = "0.18", features = ["v3_24"] } +webkit2gtk = { version = "=2.0", features = ["v2_40"] } +percent-encoding = "2" + +[target.'cfg(target_vendor = "apple")'.dependencies] +objc2 = "0.6" + +[target.'cfg(target_os = "macos")'.dependencies] +objc2-app-kit = { version = "0.3.2", default-features = false, features = [ + "block2", + "NSApplication", + "NSResponder", + "NSView", + "NSWindow", + "NSScreen", + "NSGraphics", +] } + +[target."cfg(target_os = \"android\")".dependencies] +jni = "0.21" + +[features] +default = ["x11", "dbus"] +devtools = ["wry/devtools", "tauri-runtime/devtools"] +x11 = ["tao/x11", "wry/x11"] +# TODO: Remove in v3 - wry does not have this feature anymore +macos-private-api = ["tauri-runtime/macos-private-api"] +# TODO: Remove in v3 - wry does not have this feature anymore +objc-exception = [] +tracing = ["dep:tracing", "wry/tracing"] +macos-proxy = ["wry/mac-proxy"] +unstable = [] +common-controls-v6 = ["windows/Win32_UI_Controls", "windows/Win32_UI_Shell"] +dbus = ["tao/dbus"] + +[lints] +workspace = true diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-APACHE-2.0 b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-APACHE-2.0 new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-APACHE-2.0 @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-MIT b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-MIT new file mode 100644 index 0000000000..b08530d594 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 - Present Tauri Apps Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/README.md b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/README.md new file mode 100644 index 0000000000..a452527bc3 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/README.md @@ -0,0 +1,44 @@ +# tauri-runtime-wry + + + +[![status](https://img.shields.io/badge/Status-Beta-green.svg)](https://github.com/tauri-apps/tauri) +[![Chat Server](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/SpmNs4S) + +[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml) +[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app) + +[![https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg](https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg)](https://good-labs.github.io/greater-good-affirmation) +[![support](https://img.shields.io/badge/sponsor-Opencollective-blue.svg)](https://opencollective.com/tauri) + +| Component | Version | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------- | +| tauri-runtime-wry | [![](https://img.shields.io/crates/v/tauri-runtime-wry?style=flat-square)](https://crates.io/crates/tauri-runtime-wry) | + +## About Tauri + +Tauri is a polyglot and generic system that is very composable and allows engineers to make a wide variety of applications. It is used for building applications for Desktop Computers using a combination of Rust tools and HTML rendered in a Webview. Apps built with Tauri can ship with any number of pieces of an optional JS API / Rust API so that webviews can control the system via message passing. In fact, developers can extend the default API with their own functionality and bridge the Webview and Rust-based backend easily. + +Tauri apps can have custom menus and have tray-type interfaces. They can be updated, and are managed by the user's operating system as expected. They are very small, because they use the system's webview. They do not ship a runtime, since the final binary is compiled from rust. This makes the reversing of Tauri apps not a trivial task. + +## This module + +This crate opens up direct systems-level interactions specifically for WRY, such as printing, monitor detection, and other windowing related tasks. `tauri-runtime` implementation for WRY. +None of the exposed API of this crate is stable, and it may break semver +compatibility in the future. The major version only signifies the intended Tauri version. + +To learn more about the details of how all of these pieces fit together, please consult this [ARCHITECTURE.md](https://github.com/tauri-apps/tauri/blob/dev/ARCHITECTURE.md) document. + +## Semver + +**tauri** is following [Semantic Versioning 2.0](https://semver.org/). + +## Licenses + +Code: (c) 2021 - The Tauri Programme within The Commons Conservancy. + +MIT or MIT/Apache 2.0 where applicable. + +Logo: CC-BY-NC-ND + +- Original Tauri Logo Designs by [Daniel Thompson-Yvetot](https://github.com/nothingismagick) and [Guillaume Chau](https://github.com/akryum) diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/build.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/build.rs new file mode 100644 index 0000000000..9974c5040b --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/build.rs @@ -0,0 +1,19 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +// creates a cfg alias if `has_feature` is true. +// `alias` must be a snake case string. +fn alias(alias: &str, has_feature: bool) { + println!("cargo:rustc-check-cfg=cfg({alias})"); + if has_feature { + println!("cargo:rustc-cfg={alias}"); + } +} + +fn main() { + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap(); + let mobile = target_os == "ios" || target_os == "android"; + alias("desktop", !mobile); + alias("mobile", mobile); +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-layout.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-layout.rs new file mode 100644 index 0000000000..b6a93c4362 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-layout.rs @@ -0,0 +1,241 @@ +// Native Linux regression. Run in a graphical session with GDK_BACKEND=x11 and +// GDK_BACKEND=wayland. This example uses the runtime's actual layout helper. +use gtk::prelude::*; +use std::{cell::Cell, time::Duration}; +use webkit2gtk::{PermissionRequestExt, WebContextExt, WebViewExt, WebsiteDataManagerExt}; +use wry::{ + dpi::{LogicalPosition, LogicalSize}, + Rect, WebContext, WebViewBuilder, WebViewBuilderExtUnix, WebViewExtUnix, +}; +#[path = "../src/gtk_child_layout.rs"] +mod gtk_child_layout; + +fn main() { + gtk::init().unwrap(); + let data = std::path::PathBuf::from(std::env::var("XDG_DATA_HOME").unwrap()); + let app_data = data.join("config-A/app"); + let preview_data = data.join("config-A/browser/shared-v1"); + let other_data = data.join("config-B/browser/shared-v1"); + for path in [&app_data, &preview_data, &other_data] { + std::fs::create_dir_all(path).unwrap(); + } + let mut app_context = WebContext::new(Some(app_data.clone())); + let mut preview_context = WebContext::new(Some(preview_data.clone())); + let mut other_context = WebContext::new(Some(other_data.clone())); + let window = gtk::Window::new(gtk::WindowType::Toplevel); + window.set_title("CodeNomad GTK child trial"); + window.set_default_size(800, 600); + let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0); + let menu = gtk::Label::new(Some("Menu outside content")); + menu.set_size_request(-1, 40); + vbox.pack_start(&menu, false, false, 0); + window.add(&vbox); + let page = |name: &str| { + format!( + r#"

{name}

"#, + if name == "main" { "#ddeeff" } else { "#ffddaa" } + ) + }; + let main = WebViewBuilder::new_with_web_context(&mut app_context) + .with_html(page("main")) + .with_ipc_handler(|r| println!("{}", r.body())) + .build_gtk(>k_child_layout::content(&vbox)) + .unwrap(); + assert_eq!(vbox.children().len(), 2); + window.show_all(); + // Exercise installation after the primary view has been realized and loaded. + gtk::glib::timeout_add_local_once(Duration::from_secs(2), gtk::main_quit); + gtk::main(); + let (content, fixed) = gtk_child_layout::containers(&vbox); + assert_eq!(fixed, gtk_child_layout::containers(&vbox).1); + let child = WebViewBuilder::new_with_web_context(&mut preview_context) + .with_html(page("child")) + .with_bounds(Rect { + position: LogicalPosition::new(100, 80).into(), + size: LogicalSize::new(300, 200).into(), + }) + .with_ipc_handler(|r| println!("{}", r.body())) + .with_download_started_handler(|url, path| { + println!("DOWNLOAD_DENIED {url}"); + println!("DOWNLOAD_DESTINATION {}", path.display()); + false + }) + .build_gtk(&fixed) + .unwrap(); + // The application registers a fresh child hidden, then sends separate + // position/size updates before its first allocation or reveal. + child.set_visible(false).unwrap(); + let mut pending = child.bounds().unwrap(); + pending.position = LogicalPosition::new(100, 80).into(); + child.set_bounds(pending).unwrap(); + let mut pending = child.bounds().unwrap(); + pending.size = LogicalSize::new(300, 200).into(); + child.set_bounds(pending).unwrap(); + assert_eq!(child.bounds().unwrap().position.to_logical::(1.0), LogicalPosition::new(100, 80)); + child.webview().connect_permission_request(|_, request| { + println!("PERMISSION_DENIED {}", request.type_().name()); + request.deny(); + true + }); + let other_box = gtk::Box::new(gtk::Orientation::Vertical, 0); + let other = WebViewBuilder::new_with_web_context(&mut other_context) + .build_gtk(&other_box) + .unwrap(); + for (view, path) in [ + (&main, &app_data), + (&child, &preview_data), + (&other, &other_data), + ] { + let manager = view + .webview() + .context() + .unwrap() + .website_data_manager() + .unwrap(); + assert_eq!( + manager.base_data_directory().unwrap().as_str(), + path.to_str().unwrap() + ); + assert!(!manager.is_ephemeral()); + println!("PERSISTENT_STORE {}", path.display()); + } + if let Ok(url) = std::env::var("GTK_TRIAL_URL") { + child.load_url(&url).unwrap(); + } + window.show_all(); + let b_window = gtk::Window::new(gtk::WindowType::Toplevel); + b_window.set_title("CodeNomad GTK independent owner B"); + b_window.set_default_size(700, 500); + let b_vbox = gtk::Box::new(gtk::Orientation::Vertical, 0); + let b_menu = gtk::Label::new(Some("Owner B menu")); + b_menu.set_size_request(-1, 60); + b_vbox.pack_start(&b_menu, false, false, 0); + b_window.add(&b_vbox); + let b_main = WebViewBuilder::new_with_web_context(&mut app_context) + .with_html(page("main-B")) + .with_ipc_handler(|r| println!("{}", r.body())) + .build_gtk(>k_child_layout::content(&b_vbox)) + .unwrap(); + let (_, b_fixed) = gtk_child_layout::containers(&b_vbox); + assert_ne!(fixed, b_fixed); + let b_child = WebViewBuilder::new_with_web_context(&mut preview_context) + .with_bounds(Rect { + position: LogicalPosition::new(400, 200).into(), + size: LogicalSize::new(100, 80).into(), + }) + .with_html(page("child-B")) + .build_gtk(&b_fixed) + .unwrap(); + b_window.show_all(); + let weak_child = child.webview().downgrade(); + let weak_manager = child.webview().user_content_manager().unwrap().downgrade(); + let mut child = Some(child); + let step = Cell::new(0); + gtk::glib::timeout_add_local(Duration::from_secs(2), move || { + let n = step.get(); + let b_bounds = b_child.bounds().unwrap(); + assert_eq!( + b_bounds.position.to_logical::(1.0), + LogicalPosition::new(400, 200) + ); + assert_eq!( + b_bounds.size.to_logical::(1.0), + LogicalSize::new(100, 80) + ); + assert!(b_child.webview().is_visible()); + assert!(b_window.is_visible()); + println!("OWNER_B_STABLE phase={n} {b_bounds:?}"); + if let Some(child) = child.as_ref() { + let bounds = child.bounds().unwrap(); + println!( + "phase={n} child={bounds:?} content={:?} fixed={:?}", + content.allocation(), + fixed.allocation() + ); + if n < 6 { + let expected = if n == 0 { + (100, 80, 300, 200) + } else { + (140, 90, 280, 180) + }; + assert_eq!( + bounds.position.to_logical::(1.0), + LogicalPosition::new(expected.0, expected.1) + ); + assert_eq!( + bounds.size.to_logical::(1.0), + LogicalSize::new(expected.2, expected.3) + ); + } + match n { + 0 => { + child + .set_bounds(Rect { + position: LogicalPosition::new(140, 90).into(), + size: LogicalSize::new(280, 180).into(), + }) + .unwrap(); + assert_eq!( + child.bounds().unwrap().position.to_logical::(1.0), + LogicalPosition::new(140, 90) + ); + } + 1 => { + window.resize(900, 650); + child.set_visible(false).unwrap(); + // Match Tauri's separate SetPosition/SetSize round trips while hidden. + let mut retained = child.bounds().unwrap(); + retained.position = LogicalPosition::new(140, 90).into(); + child.set_bounds(retained).unwrap(); + let mut retained = child.bounds().unwrap(); + retained.size = LogicalSize::new(280, 180).into(); + child.set_bounds(retained).unwrap(); + assert_eq!(child.bounds().unwrap().position.to_logical::(1.0), LogicalPosition::new(140, 90)); + } + 2 => { + child.reparent(&fixed).unwrap(); + child.set_visible(true).unwrap(); + menu.set_size_request(-1, 60); + } + 3 => { + window.present(); + window.fullscreen(); + println!("DISPLAY_SCALE {}", child.webview().scale_factor()); + println!("READY_FOR_CLICKS: main=(20,100), child=(180,200)"); + } + 5 => { + child.set_visible(false).unwrap(); + println!("HIDDEN_FOR_CLICKS"); + } + _ => {} + } + } + if n == 6 { + drop(child.take()); + b_window.present(); + b_window.fullscreen(); + println!("WINDOW_B_READY_FOR_CLICKS"); + } + if n == 7 { + window.close(); + assert!( + weak_child.upgrade().is_none(), + "child WebView retained after destruction" + ); + assert!( + weak_manager.upgrade().is_none(), + "child IPC manager retained after destruction" + ); + println!("OWNER_A_CHILD_RELEASED"); + } + if n == 9 { + let _ = (&main, &b_main); + b_window.close(); + gtk::main_quit(); + return gtk::glib::ControlFlow::Break; + } + step.set(n + 1); + gtk::glib::ControlFlow::Continue + }); + gtk::main(); +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-trial.py b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-trial.py new file mode 100644 index 0000000000..a25d03aa5f --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/examples/gtk-child-trial.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Native input trial: python3 gtk-child-trial.py [prebuilt-binary]. + +Requires python3-dbus and a logged-in GNOME session. Runs X11 and Wayland; +keeps logs in the current directory. GTK_TRIAL_UINPUT=1 uses python3-evdev +and a writable /dev/uinput for KDE Wayland; GTK_TRIAL_X11=1 uses xdotool +in an X11 desktop session; otherwise uses Mutter's seat. +""" +import dbus +import http.server +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import time + +if len(sys.argv) > 1: + binary = sys.argv[1] +else: + build = tempfile.TemporaryDirectory(prefix="gtk-child-build-") + root = Path(__file__).resolve().parents[2] + manifest = Path(build.name) / "Cargo.toml" + manifest.write_text(f'''[package] +name = "gtk-native-trial" +version = "0.1.0" +edition = "2021" +[[bin]] +name = "gtk-native-trial" +path = "{Path(__file__).with_name('gtk-child-layout.rs').resolve()}" +[dependencies] +gtk = "0.18" +webkit2gtk = "2.0.2" +wry = {{ path = "{root / 'wry-0.57.1'}" }} +''') + target = Path(os.environ.get("CARGO_TARGET_DIR", str(Path(build.name) / "target"))) + subprocess.run(["cargo", "build", "--offline", "--manifest-path", str(manifest), + "--target-dir", str(target)], check=True) + binary = str(target / "debug" / "gtk-native-trial") + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + if self.path == "/download": + self.send_header("Content-Disposition", 'attachment; filename="denied.txt"') + body = b"must never be saved" + else: + body = b'''

child

+''' + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_): + pass + + +server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) +threading.Thread(target=server.serve_forever, daemon=True).start() +if os.environ.get("GTK_TRIAL_X11") == "1": + class Seat: + def NotifyPointerMotionRelative(self, x, y): + subprocess.run(["xdotool", "mousemove_relative", "--", str(int(x)), str(int(y))], check=True, timeout=5) + + def NotifyPointerButton(self, button, pressed): + assert button == 272 + subprocess.run(["xdotool", "mousedown" if pressed else "mouseup", "1"], check=True, timeout=5) + + def Stop(self): + pass + + seat = Seat() +elif os.environ.get("GTK_TRIAL_UINPUT") == "1": + from evdev import UInput, ecodes + + class Seat: + def __init__(self): + self.device = UInput({ecodes.EV_REL: [ecodes.REL_X, ecodes.REL_Y], + ecodes.EV_KEY: [ecodes.BTN_LEFT]}, name="CodeNomad GTK trial") + time.sleep(1) + # Match Mutter seat coordinates: bypass libinput pointer acceleration. + bus = dbus.SessionBus() + manager = dbus.Interface(bus.get_object("org.kde.KWin", "/org/kde/KWin/InputDevice"), "org.freedesktop.DBus.Properties") + devices = [dbus.Interface(bus.get_object("org.kde.KWin", "/org/kde/KWin/InputDevice/" + name), "org.freedesktop.DBus.Properties") + for name in manager.Get("org.kde.KWin.InputDeviceManager", "devicesSysNames")] + settings, = [device for device in devices if device.Get("org.kde.KWin.InputDevice", "name") == "CodeNomad GTK trial"] + settings.Set("org.kde.KWin.InputDevice", "pointerAccelerationProfileFlat", True) + settings.Set("org.kde.KWin.InputDevice", "pointerAcceleration", 0.) + + def NotifyPointerMotionRelative(self, x, y): + self.device.write(ecodes.EV_REL, ecodes.REL_X, int(x)) + self.device.write(ecodes.EV_REL, ecodes.REL_Y, int(y)) + self.device.syn() + + def NotifyPointerButton(self, button, pressed): + self.device.write(ecodes.EV_KEY, button, int(pressed)) + self.device.syn() + + def Stop(self): + self.device.close() + + seat = Seat() +else: + bus = dbus.SessionBus() + service = "org.gnome.Mutter.RemoteDesktop" + path = dbus.Interface(bus.get_object(service, "/org/gnome/Mutter/RemoteDesktop"), service).CreateSession() + seat = dbus.Interface(bus.get_object(service, path), service + ".Session") + seat.Start() +scale = 1 + + +def click(x, y): + seat.NotifyPointerMotionRelative(-10000., -10000.) + time.sleep(.1) + seat.NotifyPointerMotionRelative(float(x * scale), float(y * scale)) + time.sleep(.1) + # The first click can activate the new window; the second must reach HTML. + for _ in range(2): + seat.NotifyPointerButton(272, True) + seat.NotifyPointerButton(272, False) + time.sleep(.15) + + +try: + for backend in (("x11",) if os.environ.get("GTK_TRIAL_X11") == "1" else ("wayland", "x11")): + with tempfile.TemporaryDirectory(prefix="gtk-trial-") as storage: + env = dict(os.environ, GDK_BACKEND=backend, + WAYLAND_DISPLAY=os.environ.get("WAYLAND_DISPLAY", "wayland-0"), + DISPLAY=os.environ.get("DISPLAY", ":0"), + XDG_DATA_HOME=storage, XDG_CACHE_HOME=storage, + GTK_TRIAL_URL=f"http://127.0.0.1:{server.server_port}/") + # Use the current desktop's Xauthority instead of relying on a name. + authorities = list(Path(os.environ["XDG_RUNTIME_DIR"]).glob(".mutter-Xwaylandauth.*")) + if authorities: + env["XAUTHORITY"] = str(authorities[0]) + process = subprocess.Popen([binary], stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, env=env) + def kill_child(child=process): + try: + child.kill() + except ProcessLookupError: + pass + + watchdog = threading.Timer(60, kill_child) + watchdog.daemon = True + watchdog.start() + lines = [] + hidden_index = None + try: + for line in process.stdout: + print(backend, line, end="", flush=True) + lines.append(line) + if "DISPLAY_SCALE " in line: + scale = int(line.split("DISPLAY_SCALE ", 1)[1]) + if line.startswith("READY_FOR_CLICKS:"): + time.sleep(.8) + click(20, 100) + click(180, 200) + if "WINDOW_B_READY_FOR_CLICKS" in line: + time.sleep(.8) + click(20, 100) + if "HIDDEN_FOR_CLICKS" in line: + hidden_index = len(lines) + time.sleep(.3) + click(180, 200) + assert process.wait() == 0, backend + finally: + watchdog.cancel() + if process.poll() is None: + kill_child() + process.wait() + watchdog.join() + process.stdout.close() + text = "".join(lines) + Path(backend + ".log").write_text(text) + for expected in ("click main", "click child", "PERMISSION_DENIED", "geolocation denied 1", "DOWNLOAD_DENIED", "OWNER_A_CHILD_RELEASED", "OWNER_B_STABLE phase=9", "click main-B 20,40"): + assert expected in text, (backend, expected) + assert hidden_index is not None + assert "click main 180,140" in "".join(lines[hidden_index:]), backend + assert "UNEXPECTED_PERMISSION" not in text + stores = [line.split("PERSISTENT_STORE ", 1)[1].strip() + for line in lines if "PERSISTENT_STORE " in line] + assert len(stores) == len(set(stores)) == 3, (backend, stores) + destinations = [line.split("DOWNLOAD_DESTINATION ", 1)[1].strip() + for line in lines if "DOWNLOAD_DESTINATION " in line] + assert destinations and all(not Path(path).exists() for path in destinations), backend + assert not list(Path(storage).rglob("denied.txt")), backend + print(backend, "PASS: allocation, native input, hidden input, permission and download denial") +finally: + seat.Stop() + server.shutdown() diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/mod.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/mod.rs new file mode 100644 index 0000000000..83d89229f5 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +#[cfg(windows)] +mod windows; + +// Takes a `&'static str` here since we convert clickable hyperlinks, +// DO NOT pass in untrusted input +#[cfg_attr(not(windows), allow(unused))] +pub fn error(err: &'static str) { + #[cfg(windows)] + windows::error(err); + + #[cfg(not(windows))] + { + unimplemented!("Error dialog is not implemented for this platform"); + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/windows.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/windows.rs new file mode 100644 index 0000000000..26850eb6e5 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/dialog/windows.rs @@ -0,0 +1,124 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use windows::core::{HSTRING, w}; + +enum Level { + Error, + #[allow(unused)] + Warning, + #[allow(unused)] + Info, +} + +pub fn error(err: &'static str) { + dialog_inner(err, Level::Error); +} + +fn dialog_inner(err: &str, level: Level) { + let title = match level { + Level::Warning => w!("Warning"), + Level::Error => w!("Error"), + Level::Info => w!("Info"), + }; + + #[cfg(not(feature = "common-controls-v6"))] + { + use windows::Win32::UI::WindowsAndMessaging::*; + + let err = remove_hyperlink(err); + let err = HSTRING::from(err); + + unsafe { + MessageBoxW( + None, + &err, + title, + match level { + Level::Warning => MB_ICONWARNING, + Level::Error => MB_ICONERROR, + Level::Info => MB_ICONINFORMATION, + }, + ) + }; + } + + #[cfg(feature = "common-controls-v6")] + { + use windows::Win32::Foundation::*; + use windows::Win32::UI::Controls::*; + use windows::Win32::UI::Shell::*; + use windows::Win32::UI::WindowsAndMessaging::*; + use windows::core::{HRESULT, PCWSTR}; + + extern "system" fn task_dialog_callback( + _hwnd: HWND, + msg: TASKDIALOG_NOTIFICATIONS, + _wparam: WPARAM, + lparam: LPARAM, + _data: isize, + ) -> HRESULT { + if msg == TDN_HYPERLINK_CLICKED { + let link = PCWSTR(lparam.0 as _); + let _ = unsafe { ShellExecuteW(None, None, link, None, None, SW_SHOWNORMAL) }; + } + + S_OK + } + + let err = HSTRING::from(err); + let err = PCWSTR(err.as_ptr()); + + let task_dialog_config = TASKDIALOGCONFIG { + cbSize: std::mem::size_of::() as u32, + dwFlags: TDF_ALLOW_DIALOG_CANCELLATION | TDF_ENABLE_HYPERLINKS, + pszWindowTitle: title, + pszContent: err, + Anonymous1: TASKDIALOGCONFIG_0 { + pszMainIcon: match level { + Level::Warning => TD_WARNING_ICON, + Level::Error => TD_ERROR_ICON, + Level::Info => TD_INFORMATION_ICON, + }, + }, + dwCommonButtons: TDCBF_OK_BUTTON, + pfCallback: Some(task_dialog_callback), + ..Default::default() + }; + + let _ = unsafe { TaskDialogIndirect(&task_dialog_config, None, None, None) }; + } +} + +#[cfg(not(feature = "common-controls-v6"))] +fn remove_hyperlink(str: &str) -> String { + let mut result = String::new(); + let mut in_hyperlink = false; + + for c in str.chars() { + if c == '<' { + in_hyperlink = true; + } else if c == '>' { + in_hyperlink = false; + } else if !in_hyperlink { + result.push(c); + } + } + + result +} + +#[cfg(test)] +#[cfg(not(feature = "common-controls-v6"))] +mod tests { + use super::*; + + #[test] + fn test_remove_hyperlink() { + let input = "This is a test string."; + let expected = "This is a test string."; + let result = remove_hyperlink(input); + assert_eq!(result, expected); + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/gtk_child_layout.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/gtk_child_layout.rs new file mode 100644 index 0000000000..4a6985f422 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/gtk_child_layout.rs @@ -0,0 +1,56 @@ +// Copyright 2026 CodeNomad contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use gtk::prelude::*; + +const NAME: &str = "tauri-webview-overlay"; + +pub(crate) fn content(vbox: >k::Box) -> gtk::Box { + vbox + .children() + .into_iter() + .find(|widget| widget.widget_name() == NAME) + .and_then(|widget| widget.downcast::().ok()) + .and_then(|overlay| overlay.child()) + .and_then(|widget| widget.downcast::().ok()) + .unwrap_or_else(|| vbox.clone()) +} + +// GTK owns the layout for exactly the lifetime of its window. Keeping the +// overlay inside Tao's vbox leaves the menu bar outside content coordinates. +pub(crate) fn containers(vbox: >k::Box) -> (gtk::Box, gtk::Fixed) { + if let Some(overlay) = vbox.children().into_iter().find_map(|widget| { + (widget.widget_name() == NAME) + .then(|| widget.downcast::().ok()) + .flatten() + }) { + let content = overlay.child().unwrap().downcast::().unwrap(); + let children = overlay + .children() + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .unwrap(); + return (content, children); + } + + let overlay = gtk::Overlay::new(); + overlay.set_widget_name(NAME); + let content = gtk::Box::new(gtk::Orientation::Vertical, 0); + let children = gtk::Fixed::new(); + overlay.add(&content); + // The primary-only path keeps Tao's original box. Install the overlay lazily + // on first child creation and move only its existing WebKit content. + for widget in vbox.children() { + if widget.is::() { + vbox.remove(&widget); + content.pack_start(&widget, true, true, 0); + } + } + overlay.add_overlay(&children); + // GtkFixed has no native input window; WebKit's child windows receive input + // inside their rectangles, while the uncovered area reaches the main view. + overlay.set_overlay_pass_through(&children, true); + vbox.pack_start(&overlay, true, true, 0); + overlay.show_all(); + (content, children) +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs new file mode 100644 index 0000000000..0573fa5cfb --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs @@ -0,0 +1,5434 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! The [`wry`] Tauri [`Runtime`]. +//! +//! None of the exposed API of this crate is stable, and it may break semver +//! compatibility in the future. The major version only signifies the intended Tauri version. + +#![doc( + html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png", + html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png" +)] + +use self::monitor::MonitorExt; +use http::Request; +#[cfg(target_os = "macos")] +use objc2::ClassType; +use raw_window_handle::{DisplayHandle, HasDisplayHandle, HasWindowHandle}; + +#[cfg(windows)] +use tauri_runtime::webview::ScrollBarStyle; +use tauri_runtime::{ + Cookie, DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon, + ProgressBarState, ProgressBarStatus, Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs, + UserAttentionType, UserEvent, WebviewDispatch, WebviewEventId, WindowDispatch, WindowEventId, + dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, + monitor::Monitor, + webview::{DetachedWebview, DownloadEvent, PendingWebview, WebviewIpcHandler}, + window::{ + CursorIcon, DetachedWindow, DetachedWindowWebview, DragDropEvent, PendingWindow, RawWindow, + WebviewEvent, WindowBuilder, WindowBuilderBase, WindowEvent, WindowId, WindowSizeConstraints, + }, +}; + +#[cfg(target_vendor = "apple")] +use objc2::rc::Retained; +#[cfg(target_os = "android")] +use tao::platform::android::{WindowBuilderExtAndroid, WindowExtAndroid}; +#[cfg(target_os = "macos")] +use tao::platform::macos::{EventLoopWindowTargetExtMacOS, WindowBuilderExtMacOS}; +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +use tao::platform::unix::{WindowBuilderExtUnix, WindowExtUnix}; +#[cfg(windows)] +use tao::platform::windows::{WindowBuilderExtWindows, WindowExtWindows}; +#[cfg(windows)] +use webview2_com::{ + ContainsFullScreenElementChangedEventHandler, FocusChangedEventHandler, + Microsoft::Web::WebView2::Win32::ICoreWebView2Controller, +}; +#[cfg(windows)] +use windows::Win32::Foundation::HWND; +#[cfg(target_os = "ios")] +use wry::WebViewBuilderExtIos; +#[cfg(target_os = "macos")] +use wry::WebViewBuilderExtMacos; +#[cfg(windows)] +use wry::WebViewBuilderExtWindows; +#[cfg(target_vendor = "apple")] +use wry::{WebViewBuilderExtDarwin, WebViewExtDarwin}; + +use tao::{ + event::{Event, StartCause, WindowEvent as TaoWindowEvent}, + event_loop::{ + ControlFlow, DeviceEventFilter as TaoDeviceEventFilter, EventLoop, EventLoopBuilder, + EventLoopProxy as TaoEventLoopProxy, EventLoopWindowTarget, + }, + monitor::MonitorHandle, + window::{ + CursorIcon as TaoCursorIcon, Fullscreen, Icon as TaoWindowIcon, + ProgressBarState as TaoProgressBarState, ProgressState as TaoProgressState, Theme as TaoTheme, + UserAttentionType as TaoUserAttentionType, + }, +}; +#[cfg(target_os = "macos")] +use tauri_utils::TitleBarStyle; +use tauri_utils::config::PreventOverflowConfig; +use tauri_utils::{ + Theme, + config::{Color, WindowConfig}, +}; +use url::Url; +#[cfg(windows)] +use wry::ScrollBarStyle as WryScrollBarStyle; +use wry::{ + DragDropEvent as WryDragDropEvent, ProxyConfig, ProxyEndpoint, WebContext as WryWebContext, + WebView, WebViewBuilder, +}; + +pub use tao; +pub use tao::window::{Window, WindowBuilder as TaoWindowBuilder, WindowId as TaoWindowId}; +pub use wry; +pub use wry::webview_version; + +#[cfg(windows)] +use wry::WebViewExtWindows; +#[cfg(target_os = "android")] +use wry::{ + WebViewBuilderExtAndroid, WebViewExtAndroid, + prelude::{dispatch, find_class}, +}; +#[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" +)))] +use wry::{WebViewBuilderExtUnix, WebViewExtUnix}; + +#[cfg(target_os = "ios")] +pub use tao::platform::ios::{WindowBuilderExtIOS, WindowExtIOS}; +#[cfg(target_os = "macos")] +pub use tao::platform::macos::{ + ActivationPolicy as TaoActivationPolicy, EventLoopExtMacOS, WindowExtMacOS, +}; +#[cfg(target_os = "macos")] +use tauri_runtime::ActivationPolicy; + +use std::{ + cell::RefCell, + collections::{ + BTreeMap, HashMap, HashSet, + hash_map::Entry::{Occupied, Vacant}, + }, + fmt, + ops::Deref, + path::PathBuf, + rc::Rc, + sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicU32, Ordering}, + mpsc::{Sender, channel}, + }, + thread::{ThreadId, current as current_thread}, +}; + +pub type WebviewId = u32; +type IpcHandler = dyn Fn(Request) + 'static; + +#[cfg(not(debug_assertions))] +mod dialog; +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +mod gtk_child_layout; +mod monitor; +#[cfg(any( + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +mod undecorated_resizing; +mod util; +mod webview; +mod webview_permissions; +mod window; + +pub use webview::Webview; +use window::WindowExt as _; + +#[derive(Debug)] +pub struct WebContext { + pub inner: WryWebContext, + pub referenced_by_webviews: HashSet, + // on Linux the custom protocols are associated with the context + // and you cannot register a URI scheme more than once + pub registered_custom_protocols: HashSet, +} + +pub type WebContextStore = Arc, WebContext>>>; +// window +pub type WindowEventHandler = Box; +pub type WindowEventListeners = Arc>>; +pub type WebviewEventHandler = Box; +pub type WebviewEventListeners = Arc>>; + +#[derive(Debug, Clone, Default)] +pub struct WindowIdStore(Arc>>); + +impl WindowIdStore { + pub fn insert(&self, w: TaoWindowId, id: WindowId) { + self.0.lock().unwrap().insert(w, id); + } + + pub fn get(&self, w: &TaoWindowId) -> Option { + self.0.lock().unwrap().get(w).copied() + } +} + +#[macro_export] +macro_rules! getter { + ($self: ident, $rx: expr, $message: expr) => {{ + $self.context.send_user_message($message)?; + $rx + .recv() + .map_err(|_| $crate::Error::FailedToReceiveMessage) + }}; +} + +macro_rules! window_getter { + ($self: ident, $message: expr) => {{ + let (tx, rx) = channel(); + getter!($self, rx, Message::Window($self.window_id, $message(tx))) + }}; +} + +macro_rules! event_loop_window_getter { + ($self: ident, $message: expr) => {{ + let (tx, rx) = channel(); + getter!($self, rx, Message::EventLoopWindowTarget($message(tx))) + }}; +} + +macro_rules! webview_getter { + ($self: ident, $message: expr) => {{ + let (tx, rx) = channel(); + getter!( + $self, + rx, + Message::Webview( + *$self.window_id.lock().unwrap(), + $self.webview_id, + $message(tx) + ) + ) + }}; +} + +#[derive(Clone)] +pub struct Context { + pub window_id_map: WindowIdStore, + main_thread_id: ThreadId, + pub proxy: TaoEventLoopProxy>, + main_thread: DispatcherMainThreadContext, + plugins: Arc + Send>>>>, + next_window_id: Arc, + next_webview_id: Arc, + next_window_event_id: Arc, + next_webview_event_id: Arc, + webview_runtime_installed: bool, +} + +unsafe impl Send for Context {} +unsafe impl Sync for Context {} + +impl Context { + pub fn run_threaded(&self, f: F) -> R + where + F: FnOnce(Option<&DispatcherMainThreadContext>) -> R, + { + f(if current_thread().id() == self.main_thread_id { + Some(&self.main_thread) + } else { + None + }) + } + + fn send_user_message(&self, message: Message) -> Result<()> { + if current_thread().id() == self.main_thread_id { + handle_user_message( + &self.main_thread.window_target, + message, + UserMessageContext { + window_id_map: &self.window_id_map, + windows: &self.main_thread.windows, + }, + ); + Ok(()) + } else { + self + .proxy + .send_event(message) + .map_err(|_| Error::FailedToSendMessage) + } + } + + fn next_window_id(&self) -> WindowId { + self.next_window_id.fetch_add(1, Ordering::Relaxed).into() + } + + fn next_webview_id(&self) -> WebviewId { + self.next_webview_id.fetch_add(1, Ordering::Relaxed) + } + + fn next_window_event_id(&self) -> u32 { + self.next_window_event_id.fetch_add(1, Ordering::Relaxed) + } + + fn next_webview_event_id(&self) -> u32 { + self.next_webview_event_id.fetch_add(1, Ordering::Relaxed) + } +} + +impl Context { + fn create_window( + &self, + pending: PendingWindow>, + after_window_creation: Option, + ) -> Result>> { + let label = pending.label.clone(); + let context = self.clone(); + let window_id = self.next_window_id(); + let (webview_id, use_https_scheme) = pending + .webview + .as_ref() + .map(|w| { + ( + Some(context.next_webview_id()), + w.webview_attributes.use_https_scheme, + ) + }) + .unwrap_or((None, false)); + + let (tx, rx) = channel(); + self.send_user_message(Message::CreateWindow( + window_id, + Box::new(move |event_loop| { + create_window( + window_id, + webview_id.unwrap_or_default(), + event_loop, + &context, + pending, + after_window_creation, + ) + }), + tx, + ))?; + rx.recv() + .map_err(|_| crate::Error::FailedToReceiveMessage)??; + + let dispatcher = WryWindowDispatcher { + window_id, + context: self.clone(), + }; + + let detached_webview = webview_id.map(|id| { + let webview = DetachedWebview { + label: label.clone(), + dispatcher: WryWebviewDispatcher { + window_id: Arc::new(Mutex::new(window_id)), + webview_id: id, + context: self.clone(), + }, + }; + DetachedWindowWebview { + webview, + use_https_scheme, + } + }); + + Ok(DetachedWindow { + id: window_id, + label, + dispatcher, + webview: detached_webview, + }) + } + + fn create_webview( + &self, + window_id: WindowId, + pending: PendingWebview>, + ) -> Result>> { + let label = pending.label.clone(); + let context = self.clone(); + + let webview_id = self.next_webview_id(); + + let window_id_wrapper = Arc::new(Mutex::new(window_id)); + let window_id_wrapper_ = window_id_wrapper.clone(); + + let (tx, rx) = channel(); + self.send_user_message(Message::CreateWebview( + window_id, + Box::new(move |window, _options| { + create_webview( + WebviewKind::WindowChild, + window, + window_id_wrapper_, + webview_id, + &context, + pending, + #[cfg(windows)] + _options.focused_webview, + ) + }), + tx, + ))?; + rx.recv() + .map_err(|_| crate::Error::FailedToReceiveMessage)??; + + let dispatcher = WryWebviewDispatcher { + window_id: window_id_wrapper, + webview_id, + context: self.clone(), + }; + + Ok(DetachedWebview { label, dispatcher }) + } +} + +#[cfg(feature = "tracing")] +#[derive(Clone, Default)] +pub struct ActiveTraceSpanStore(Rc>>); + +// Deliberately does not borrow the inner `RefCell`: formatting can happen re-entrantly +// while the store is already borrowed (e.g. from an event loop callback), +// which would panic with "already borrowed". +#[cfg(feature = "tracing")] +impl fmt::Debug for ActiveTraceSpanStore { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ActiveTraceSpanStore") + .finish_non_exhaustive() + } +} + +#[cfg(feature = "tracing")] +impl ActiveTraceSpanStore { + pub fn remove_window_draw(&self) { + self + .0 + .borrow_mut() + .retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ })); + } +} + +#[cfg(feature = "tracing")] +#[derive(Debug)] +pub enum ActiveTracingSpan { + WindowDraw { + id: TaoWindowId, + span: tracing::span::EnteredSpan, + }, +} + +pub struct WindowsStore(pub RefCell>); + +// Deliberately does not borrow the inner `RefCell`: formatting can happen re-entrantly +// while the store is already borrowed (e.g. from an event loop callback), +// which would panic with "already borrowed". +impl fmt::Debug for WindowsStore { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WindowsStore").finish_non_exhaustive() + } +} + +#[derive(Debug, Clone)] +pub struct DispatcherMainThreadContext { + pub window_target: EventLoopWindowTarget>, + pub web_context: WebContextStore, + // changing this to an Rc will cause frequent app crashes. + pub windows: Arc, + #[cfg(feature = "tracing")] + pub active_tracing_spans: ActiveTraceSpanStore, +} + +impl fmt::Debug for Context { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Context") + .field("main_thread_id", &self.main_thread_id) + .field("proxy", &self.proxy) + .field("main_thread", &self.main_thread) + .finish() + } +} + +pub struct DeviceEventFilterWrapper(pub TaoDeviceEventFilter); + +impl From for DeviceEventFilterWrapper { + fn from(item: DeviceEventFilter) -> Self { + match item { + DeviceEventFilter::Always => Self(TaoDeviceEventFilter::Always), + DeviceEventFilter::Never => Self(TaoDeviceEventFilter::Never), + DeviceEventFilter::Unfocused => Self(TaoDeviceEventFilter::Unfocused), + } + } +} + +pub struct RectWrapper(pub wry::Rect); +impl From for RectWrapper { + fn from(value: tauri_runtime::dpi::Rect) -> Self { + RectWrapper(wry::Rect { + position: value.position, + size: value.size, + }) + } +} + +/// Wrapper around a [`tao::window::Icon`] that can be created from an [`Icon`]. +pub struct TaoIcon(pub TaoWindowIcon); + +impl TryFrom> for TaoIcon { + type Error = Error; + fn try_from(icon: Icon<'_>) -> std::result::Result { + TaoWindowIcon::from_rgba(icon.rgba.to_vec(), icon.width, icon.height) + .map(Self) + .map_err(|e| Error::InvalidIcon(Box::new(e))) + } +} + +pub struct WindowEventWrapper(pub Option); + +impl WindowEventWrapper { + fn map_from_tao(event: &TaoWindowEvent<'_>, #[cfg(windows)] window: &WindowWrapper) -> Self { + let event = match event { + TaoWindowEvent::Resized(size) => WindowEvent::Resized(*size), + TaoWindowEvent::Moved(position) => WindowEvent::Moved(*position), + TaoWindowEvent::Destroyed => WindowEvent::Destroyed, + TaoWindowEvent::ScaleFactorChanged { + scale_factor, + new_inner_size, + } => WindowEvent::ScaleFactorChanged { + scale_factor: *scale_factor, + new_inner_size: **new_inner_size, + }, + TaoWindowEvent::Focused(focused) => { + #[cfg(not(windows))] + return Self(Some(WindowEvent::Focused(*focused))); + // on multiwebview mode, if there's no focused webview, it means we're receiving a direct window focus change + // (without receiving a webview focus, such as when clicking the taskbar app icon or using Alt + Tab) + // in this case we must send the focus change event here + #[cfg(windows)] + if window.has_children.load(Ordering::Relaxed) { + if !*focused { + // Blur events are handled in the webview side (add_LostFocus) + return Self(None); + } + + let mut focused_webview = window.focused_webview.lock().unwrap(); + if let FocusState::Blured { + last_focused_webview_label, + } = &*focused_webview + { + let should_focus_webview = + last_focused_webview_label + .as_deref() + .and_then(|last_focused_webview_label| { + window + .webviews + .iter() + .find(|w| w.label == last_focused_webview_label) + }); + *focused_webview = FocusState::WindowFocused; + if let Some(should_focus_webview) = should_focus_webview { + drop(focused_webview); + let _ = should_focus_webview.focus(); + } + WindowEvent::Focused(true) + } else { + // Already focused + return Self(None); + } + } else if window.webviews.is_empty() { + // Raw tao window without webviews, forward the event + WindowEvent::Focused(*focused) + } else { + // when not on multiwebview mode, wry will set focus to the webview, + // and we will handle focus change events on the webview (add_GotFocus and add_LostFocus) + return Self(None); + } + } + TaoWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)), + #[cfg(mobile)] + TaoWindowEvent::Suspended => WindowEvent::Suspended, + #[cfg(mobile)] + TaoWindowEvent::Resumed => WindowEvent::Resumed, + _ => return Self(None), + }; + Self(Some(event)) + } + + fn parse(window: &WindowWrapper, event: &TaoWindowEvent<'_>) -> Self { + match event { + // resized event from tao doesn't include a reliable size on macOS + // because wry replaces the NSView + TaoWindowEvent::Resized(_) => { + if let Some(w) = &window.inner { + let size = inner_size( + w, + &window.webviews, + window.has_children.load(Ordering::Relaxed), + ); + Self(Some(WindowEvent::Resized(size))) + } else { + Self(None) + } + } + e => Self::map_from_tao( + e, + #[cfg(windows)] + window, + ), + } + } +} + +pub fn map_theme(theme: &TaoTheme) -> Theme { + match theme { + TaoTheme::Light => Theme::Light, + TaoTheme::Dark => Theme::Dark, + _ => Theme::Light, + } +} + +#[cfg(target_os = "macos")] +fn tao_activation_policy(activation_policy: ActivationPolicy) -> TaoActivationPolicy { + match activation_policy { + ActivationPolicy::Regular => TaoActivationPolicy::Regular, + ActivationPolicy::Accessory => TaoActivationPolicy::Accessory, + ActivationPolicy::Prohibited => TaoActivationPolicy::Prohibited, + _ => unimplemented!(), + } +} + +pub struct MonitorHandleWrapper(pub MonitorHandle); + +impl From for Monitor { + fn from(monitor: MonitorHandleWrapper) -> Monitor { + Self { + name: monitor.0.name(), + position: monitor.0.position(), + size: monitor.0.size(), + work_area: monitor.0.work_area(), + scale_factor: monitor.0.scale_factor(), + } + } +} + +fn find_monitor_for_position( + monitors: impl Iterator, + window_position: Position, +) -> Option { + monitors.into_iter().find(|m| { + let monitor_pos = m.position(); + let monitor_size = m.size(); + + // type annotations required for 32bit targets. + let window_position = window_position.to_physical::(m.scale_factor()); + + monitor_pos.x <= window_position.x + && window_position.x < monitor_pos.x + monitor_size.width as i32 + && monitor_pos.y <= window_position.y + && window_position.y < monitor_pos.y + monitor_size.height as i32 + }) +} + +#[derive(Debug, Clone)] +pub struct UserAttentionTypeWrapper(pub TaoUserAttentionType); + +impl From for UserAttentionTypeWrapper { + fn from(request_type: UserAttentionType) -> Self { + let o = match request_type { + UserAttentionType::Critical => TaoUserAttentionType::Critical, + UserAttentionType::Informational => TaoUserAttentionType::Informational, + }; + Self(o) + } +} + +#[derive(Debug)] +pub struct CursorIconWrapper(pub TaoCursorIcon); + +impl From for CursorIconWrapper { + fn from(icon: CursorIcon) -> Self { + use CursorIcon::*; + let i = match icon { + Default => TaoCursorIcon::Default, + Crosshair => TaoCursorIcon::Crosshair, + Hand => TaoCursorIcon::Hand, + Arrow => TaoCursorIcon::Arrow, + Move => TaoCursorIcon::Move, + Text => TaoCursorIcon::Text, + Wait => TaoCursorIcon::Wait, + Help => TaoCursorIcon::Help, + Progress => TaoCursorIcon::Progress, + NotAllowed => TaoCursorIcon::NotAllowed, + ContextMenu => TaoCursorIcon::ContextMenu, + Cell => TaoCursorIcon::Cell, + VerticalText => TaoCursorIcon::VerticalText, + Alias => TaoCursorIcon::Alias, + Copy => TaoCursorIcon::Copy, + NoDrop => TaoCursorIcon::NoDrop, + Grab => TaoCursorIcon::Grab, + Grabbing => TaoCursorIcon::Grabbing, + AllScroll => TaoCursorIcon::AllScroll, + ZoomIn => TaoCursorIcon::ZoomIn, + ZoomOut => TaoCursorIcon::ZoomOut, + EResize => TaoCursorIcon::EResize, + NResize => TaoCursorIcon::NResize, + NeResize => TaoCursorIcon::NeResize, + NwResize => TaoCursorIcon::NwResize, + SResize => TaoCursorIcon::SResize, + SeResize => TaoCursorIcon::SeResize, + SwResize => TaoCursorIcon::SwResize, + WResize => TaoCursorIcon::WResize, + EwResize => TaoCursorIcon::EwResize, + NsResize => TaoCursorIcon::NsResize, + NeswResize => TaoCursorIcon::NeswResize, + NwseResize => TaoCursorIcon::NwseResize, + ColResize => TaoCursorIcon::ColResize, + RowResize => TaoCursorIcon::RowResize, + _ => TaoCursorIcon::Default, + }; + Self(i) + } +} + +pub struct ProgressStateWrapper(pub TaoProgressState); + +impl From for ProgressStateWrapper { + fn from(status: ProgressBarStatus) -> Self { + let state = match status { + ProgressBarStatus::None => TaoProgressState::None, + ProgressBarStatus::Normal => TaoProgressState::Normal, + ProgressBarStatus::Indeterminate => TaoProgressState::Indeterminate, + ProgressBarStatus::Paused => TaoProgressState::Paused, + ProgressBarStatus::Error => TaoProgressState::Error, + }; + Self(state) + } +} + +pub struct ProgressBarStateWrapper(pub TaoProgressBarState); + +impl From for ProgressBarStateWrapper { + fn from(progress_state: ProgressBarState) -> Self { + Self(TaoProgressBarState { + progress: progress_state.progress, + state: progress_state + .status + .map(|state| ProgressStateWrapper::from(state).0), + desktop_filename: progress_state.desktop_filename, + }) + } +} + +#[derive(Clone, Default)] +pub struct WindowBuilderWrapper { + inner: TaoWindowBuilder, + center: bool, + prevent_overflow: Option, + #[cfg(target_os = "macos")] + tabbing_identifier: Option, +} + +impl std::fmt::Debug for WindowBuilderWrapper { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut s = f.debug_struct("WindowBuilderWrapper"); + s.field("inner", &self.inner) + .field("center", &self.center) + .field("prevent_overflow", &self.prevent_overflow); + #[cfg(target_os = "macos")] + { + s.field("tabbing_identifier", &self.tabbing_identifier); + } + s.finish() + } +} + +// SAFETY: this type is `Send` since `menu_items` are read only here +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Send for WindowBuilderWrapper {} + +impl WindowBuilderBase for WindowBuilderWrapper {} +impl WindowBuilder for WindowBuilderWrapper { + fn new() -> Self { + #[allow(unused_mut)] + let mut builder = Self::default().focused(true); + + #[cfg(target_os = "macos")] + { + // TODO: find a proper way to prevent webview being pushed out of the window. + // Workaround for issue: https://github.com/tauri-apps/tauri/issues/10225 + // The window requires `NSFullSizeContentViewWindowMask` flag to prevent devtools + // pushing the content view out of the window. + // By setting the default style to `TitleBarStyle::Visible` should fix the issue for most of the users. + builder = builder.title_bar_style(TitleBarStyle::Visible); + } + + builder = builder.title("Tauri App"); + + #[cfg(windows)] + { + builder = builder.window_classname("Tauri Window"); + } + + builder + } + + fn with_config(config: &WindowConfig) -> Self { + let mut window = WindowBuilderWrapper::new(); + + #[cfg(target_os = "macos")] + { + window = window + .hidden_title(config.hidden_title) + .title_bar_style(config.title_bar_style); + if let Some(identifier) = &config.tabbing_identifier { + window = window.tabbing_identifier(identifier); + } + if let Some(position) = &config.traffic_light_position { + window = window.traffic_light_position(tauri_runtime::dpi::LogicalPosition::new( + position.x, position.y, + )); + } + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + // Mouse event is disabled on Linux since sudden event bursts could block event loop. + window.inner = window.inner.with_cursor_moved_event(false); + } + + #[cfg(target_os = "android")] + { + if let Some(activity_name) = &config.activity_name { + window.inner = window.inner.with_activity_name(activity_name.clone()); + } + if let Some(activity_name) = &config.created_by_activity_name { + window.inner = window + .inner + .with_created_by_activity_name(activity_name.clone()); + } + } + + #[cfg(target_os = "ios")] + { + if let Some(scene_identifier) = &config.requested_by_scene_identifier { + window.inner = window + .inner + .with_requesting_scene_identifier(scene_identifier.clone()); + } + } + + // ignore size from config for mobile for backward compatibility + #[cfg(not(any(target_os = "ios", target_os = "android")))] + { + window = window.inner_size(config.width, config.height); + } + + window = window + .title(config.title.to_string()) + .focused(config.focus) + .focusable(config.focusable) + .visible(config.visible) + .resizable(config.resizable) + .fullscreen(config.fullscreen) + .decorations(config.decorations) + .maximized(config.maximized) + .always_on_bottom(config.always_on_bottom) + .always_on_top(config.always_on_top) + .visible_on_all_workspaces(config.visible_on_all_workspaces) + .content_protected(config.content_protected) + .skip_taskbar(config.skip_taskbar) + .theme(config.theme) + .no_redirection_bitmap(config.no_redirection_bitmap) + .closable(config.closable) + .maximizable(config.maximizable) + .minimizable(config.minimizable) + .shadow(config.shadow) + .transparent(config.transparent); + + let mut constraints = WindowSizeConstraints::default(); + + if let Some(min_width) = config.min_width { + constraints.min_width = Some(tao::dpi::LogicalUnit::new(min_width).into()); + } + if let Some(min_height) = config.min_height { + constraints.min_height = Some(tao::dpi::LogicalUnit::new(min_height).into()); + } + if let Some(max_width) = config.max_width { + constraints.max_width = Some(tao::dpi::LogicalUnit::new(max_width).into()); + } + if let Some(max_height) = config.max_height { + constraints.max_height = Some(tao::dpi::LogicalUnit::new(max_height).into()); + } + if let Some(color) = config.background_color { + window = window.background_color(color); + } + window = window.inner_size_constraints(constraints); + + if let (Some(x), Some(y)) = (config.x, config.y) { + window = window.position(x, y); + } + + if config.center { + window = window.center(); + } + + if let Some(window_classname) = &config.window_classname { + window = window.window_classname(window_classname); + } + + if let Some(prevent_overflow) = &config.prevent_overflow { + window = match prevent_overflow { + PreventOverflowConfig::Enable(true) => window.prevent_overflow(), + PreventOverflowConfig::Margin(margin) => { + window.prevent_overflow_with_margin(PhysicalSize::new(margin.width, margin.height).into()) + } + _ => window, + }; + } + + window + } + + fn center(mut self) -> Self { + self.center = true; + self + } + + fn position(mut self, x: f64, y: f64) -> Self { + self.inner = self.inner.with_position(LogicalPosition::new(x, y)); + self + } + + fn inner_size(mut self, width: f64, height: f64) -> Self { + self.inner = self.inner.with_inner_size(LogicalSize::new(width, height)); + self + } + + fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self { + self.inner = self + .inner + .with_min_inner_size(LogicalSize::new(min_width, min_height)); + self + } + + fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self { + self.inner = self + .inner + .with_max_inner_size(LogicalSize::new(max_width, max_height)); + self + } + + fn inner_size_constraints(mut self, constraints: WindowSizeConstraints) -> Self { + self.inner.window.inner_size_constraints = tao::window::WindowSizeConstraints { + min_width: constraints.min_width, + min_height: constraints.min_height, + max_width: constraints.max_width, + max_height: constraints.max_height, + }; + self + } + + /// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size) on creation + /// + /// ## Platform-specific + /// + /// - **iOS / Android:** Unsupported. + fn prevent_overflow(mut self) -> Self { + self + .prevent_overflow + .replace(PhysicalSize::new(0, 0).into()); + self + } + + /// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size) + /// on creation with a margin + /// + /// ## Platform-specific + /// + /// - **iOS / Android:** Unsupported. + fn prevent_overflow_with_margin(mut self, margin: Size) -> Self { + self.prevent_overflow.replace(margin); + self + } + + fn resizable(mut self, resizable: bool) -> Self { + self.inner = self.inner.with_resizable(resizable); + self + } + + fn maximizable(mut self, maximizable: bool) -> Self { + self.inner = self.inner.with_maximizable(maximizable); + self + } + + fn minimizable(mut self, minimizable: bool) -> Self { + self.inner = self.inner.with_minimizable(minimizable); + self + } + + fn closable(mut self, closable: bool) -> Self { + self.inner = self.inner.with_closable(closable); + self + } + + fn title>(mut self, title: S) -> Self { + self.inner = self.inner.with_title(title.into()); + self + } + + fn fullscreen(mut self, fullscreen: bool) -> Self { + self.inner = if fullscreen { + self + .inner + .with_fullscreen(Some(Fullscreen::Borderless(None))) + } else { + self.inner.with_fullscreen(None) + }; + self + } + + fn focused(mut self, focused: bool) -> Self { + self.inner = self.inner.with_focused(focused); + self + } + + fn focusable(mut self, focusable: bool) -> Self { + self.inner = self.inner.with_focusable(focusable); + self + } + + fn maximized(mut self, maximized: bool) -> Self { + self.inner = self.inner.with_maximized(maximized); + self + } + + fn visible(mut self, visible: bool) -> Self { + self.inner = self.inner.with_visible(visible); + self + } + + fn transparent(mut self, transparent: bool) -> Self { + self.inner = self.inner.with_transparent(transparent); + self + } + + fn decorations(mut self, decorations: bool) -> Self { + self.inner = self.inner.with_decorations(decorations); + self + } + + fn always_on_bottom(mut self, always_on_bottom: bool) -> Self { + self.inner = self.inner.with_always_on_bottom(always_on_bottom); + self + } + + fn always_on_top(mut self, always_on_top: bool) -> Self { + self.inner = self.inner.with_always_on_top(always_on_top); + self + } + + fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self { + self.inner = self + .inner + .with_visible_on_all_workspaces(visible_on_all_workspaces); + self + } + + fn content_protected(mut self, protected: bool) -> Self { + self.inner = self.inner.with_content_protection(protected); + self + } + + fn shadow(#[allow(unused_mut)] mut self, _enable: bool) -> Self { + #[cfg(windows)] + { + self.inner = self.inner.with_undecorated_shadow(_enable); + } + #[cfg(target_os = "macos")] + { + self.inner = self.inner.with_has_shadow(_enable); + } + self + } + + #[cfg(windows)] + fn owner(mut self, owner: HWND) -> Self { + self.inner = self.inner.with_owner_window(owner.0 as _); + self + } + + #[cfg(windows)] + fn parent(mut self, parent: HWND) -> Self { + self.inner = self.inner.with_parent_window(parent.0 as _); + self + } + + #[cfg(target_os = "macos")] + fn parent(mut self, parent: *mut std::ffi::c_void) -> Self { + self.inner = self.inner.with_parent_window(parent); + self + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + fn transient_for(mut self, parent: &impl gtk::glib::IsA) -> Self { + self.inner = self.inner.with_transient_for(parent); + self + } + + #[cfg(windows)] + fn drag_and_drop(mut self, enabled: bool) -> Self { + self.inner = self.inner.with_drag_and_drop(enabled); + self + } + + #[cfg(target_os = "macos")] + fn title_bar_style(mut self, style: TitleBarStyle) -> Self { + match style { + TitleBarStyle::Visible => { + self.inner = self.inner.with_titlebar_transparent(false); + // Fixes rendering issue when resizing window with devtools open (https://github.com/tauri-apps/tauri/issues/3914) + self.inner = self.inner.with_fullsize_content_view(true); + } + TitleBarStyle::Transparent => { + self.inner = self.inner.with_titlebar_transparent(true); + self.inner = self.inner.with_fullsize_content_view(false); + } + TitleBarStyle::Overlay => { + self.inner = self.inner.with_titlebar_transparent(true); + self.inner = self.inner.with_fullsize_content_view(true); + } + unknown => { + #[cfg(feature = "tracing")] + tracing::warn!("unknown title bar style applied: {unknown}"); + + #[cfg(not(feature = "tracing"))] + eprintln!("unknown title bar style applied: {unknown}"); + } + } + self + } + + #[cfg(target_os = "macos")] + fn traffic_light_position>(mut self, position: P) -> Self { + self.inner = self.inner.with_traffic_light_inset(position.into()); + self + } + + #[cfg(target_os = "macos")] + fn hidden_title(mut self, hidden: bool) -> Self { + self.inner = self.inner.with_title_hidden(hidden); + self + } + + #[cfg(target_os = "macos")] + fn tabbing_identifier(mut self, identifier: &str) -> Self { + self.inner = self.inner.with_tabbing_identifier(identifier); + self.tabbing_identifier.replace(identifier.into()); + self + } + + fn icon(mut self, icon: Icon) -> Result { + self.inner = self + .inner + .with_window_icon(Some(TaoIcon::try_from(icon)?.0)); + Ok(self) + } + + fn background_color(mut self, color: Color) -> Self { + self.inner = self.inner.with_background_color(color.into()); + self + } + + #[cfg(any( + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + fn skip_taskbar(mut self, skip: bool) -> Self { + self.inner = self.inner.with_skip_taskbar(skip); + self + } + + #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))] + fn skip_taskbar(self, _skip: bool) -> Self { + self + } + + fn theme(mut self, theme: Option) -> Self { + self.inner = self.inner.with_theme(if let Some(t) = theme { + match t { + Theme::Dark => Some(TaoTheme::Dark), + _ => Some(TaoTheme::Light), + } + } else { + None + }); + + self + } + + fn has_icon(&self) -> bool { + self.inner.window.window_icon.is_some() + } + + fn get_theme(&self) -> Option { + self.inner.window.preferred_theme.map(|theme| match theme { + TaoTheme::Dark => Theme::Dark, + _ => Theme::Light, + }) + } + + #[cfg(windows)] + fn window_classname>(mut self, window_classname: S) -> Self { + self.inner = self.inner.with_window_classname(window_classname); + self + } + #[cfg(not(windows))] + fn window_classname>(self, _window_classname: S) -> Self { + self + } + + fn no_redirection_bitmap(#[allow(unused_mut)] mut self, _enable: bool) -> Self { + #[cfg(windows)] + { + self.inner = self.inner.with_no_redirection_bitmap(_enable); + } + self + } + + #[cfg(target_os = "android")] + fn activity_name>(mut self, class_name: S) -> Self { + self.inner = self.inner.with_activity_name(class_name.into()); + self + } + + #[cfg(target_os = "android")] + fn created_by_activity_name>(mut self, class_name: S) -> Self { + self.inner = self.inner.with_created_by_activity_name(class_name.into()); + self + } + + #[cfg(target_os = "ios")] + fn requested_by_scene_identifier>(mut self, identifier: S) -> Self { + self.inner = self + .inner + .with_requesting_scene_identifier(identifier.into()); + self + } +} + +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +pub struct GtkWindow(pub gtk::ApplicationWindow); +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Send for GtkWindow {} + +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +pub struct GtkBox(pub gtk::Box); +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Send for GtkBox {} + +pub struct SendRawWindowHandle(pub raw_window_handle::RawWindowHandle); +unsafe impl Send for SendRawWindowHandle {} + +pub enum ApplicationMessage { + #[cfg(target_os = "macos")] + Show, + #[cfg(target_os = "macos")] + Hide, + #[cfg(any(target_os = "macos", target_os = "ios"))] + FetchDataStoreIdentifiers(Box) + Send + 'static>), + #[cfg(any(target_os = "macos", target_os = "ios"))] + RemoveDataStore([u8; 16], Box) + Send + 'static>), +} + +pub enum WindowMessage { + AddEventListener(WindowEventId, Box), + // Getters + ScaleFactor(Sender), + InnerPosition(Sender>>), + OuterPosition(Sender>>), + InnerSize(Sender>), + OuterSize(Sender>), + IsFullscreen(Sender), + IsMinimized(Sender), + IsMaximized(Sender), + IsFocused(Sender), + IsDecorated(Sender), + IsResizable(Sender), + IsMaximizable(Sender), + IsMinimizable(Sender), + IsClosable(Sender), + IsVisible(Sender), + Title(Sender), + // Monitors are converted on the main thread: on iOS tao's `MonitorHandle` + // can only be queried (and dropped) there. + CurrentMonitor(Sender>), + PrimaryMonitor(Sender>), + MonitorFromPoint(Sender>, (f64, f64)), + AvailableMonitors(Sender>), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + GtkWindow(Sender), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + GtkBox(Sender), + #[cfg(target_os = "android")] + ActivityName(Sender), + #[cfg(target_os = "ios")] + SceneIdentifier(Sender), + RawWindowHandle(Sender>), + Theme(Sender), + IsEnabled(Sender), + IsAlwaysOnTop(Sender), + // Setters + Center, + RequestUserAttention(Option), + SetEnabled(bool), + SetResizable(bool), + SetMaximizable(bool), + SetMinimizable(bool), + SetClosable(bool), + SetTitle(String), + Maximize, + Unmaximize, + Minimize, + Unminimize, + Show, + Hide, + Close, + Destroy, + SetDecorations(bool), + SetShadow(bool), + SetAlwaysOnBottom(bool), + SetAlwaysOnTop(bool), + SetVisibleOnAllWorkspaces(bool), + SetContentProtected(bool), + SetSize(Size), + SetMinSize(Option), + SetMaxSize(Option), + SetSizeConstraints(WindowSizeConstraints), + SetPosition(Position), + SetFullscreen(bool), + SetFullscreenOnMonitor(PhysicalPosition), + #[cfg(target_os = "macos")] + SetSimpleFullscreen(bool), + SetFocus, + SetFocusable(bool), + SetIcon(TaoWindowIcon), + SetSkipTaskbar(bool), + SetCursorGrab(bool), + SetCursorVisible(bool), + SetCursorIcon(CursorIcon), + SetCursorPosition(Position), + SetIgnoreCursorEvents(bool), + SetBadgeCount(Option, Option), + SetBadgeLabel(Option), + SetOverlayIcon(Option), + SetProgressBar(ProgressBarState), + SetTitleBarStyle(tauri_utils::TitleBarStyle), + SetTrafficLightPosition(Position), + SetTheme(Option), + SetBackgroundColor(Option), + DragWindow, + ResizeDragWindow(tauri_runtime::ResizeDirection), + RequestRedraw, +} + +#[derive(Debug, Clone)] +pub enum SynthesizedWindowEvent { + Focused(bool), + DragDrop(DragDropEvent), +} + +impl From for WindowEventWrapper { + fn from(event: SynthesizedWindowEvent) -> Self { + let event = match event { + SynthesizedWindowEvent::Focused(focused) => WindowEvent::Focused(focused), + SynthesizedWindowEvent::DragDrop(event) => WindowEvent::DragDrop(event), + }; + Self(Some(event)) + } +} + +pub enum WebviewMessage { + AddEventListener(WebviewEventId, Box), + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + EvaluateScript(String), + #[cfg(all(feature = "tracing", not(target_os = "android")))] + EvaluateScript(String, Sender<()>, tracing::Span), + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + EvaluateScriptWithCallback(String, Box), + #[cfg(all(feature = "tracing", not(target_os = "android")))] + EvaluateScriptWithCallback( + String, + Box, + Sender<()>, + tracing::Span, + ), + CookiesForUrl(Url, Sender>>>), + Cookies(Sender>>>), + SetCookie(tauri_runtime::Cookie<'static>), + DeleteCookie(tauri_runtime::Cookie<'static>), + WebviewEvent(WebviewEvent), + SynthesizedWindowEvent(SynthesizedWindowEvent), + Navigate(Url), + Reload, + Print, + Close, + Show, + Hide, + SetPosition(Position), + SetSize(Size), + SetBounds(tauri_runtime::dpi::Rect), + SetFocus, + Reparent(WindowId, Sender>), + SetAutoResize(bool), + SetZoom(f64), + SetBackgroundColor(Option), + ClearAllBrowsingData, + // Getters + Url(Sender>), + Bounds(Sender>), + Position(Sender>>), + Size(Sender>>), + WithWebview(Box), + // Devtools + #[cfg(any(debug_assertions, feature = "devtools"))] + OpenDevTools, + #[cfg(any(debug_assertions, feature = "devtools"))] + CloseDevTools, + #[cfg(any(debug_assertions, feature = "devtools"))] + IsDevToolsOpen(Sender), +} + +pub enum EventLoopWindowTargetMessage { + CursorPosition(Sender>>), + // See `WindowMessage::CurrentMonitor`. + PrimaryMonitor(Sender>), + MonitorFromPoint(Sender>, (f64, f64)), + AvailableMonitors(Sender>), + SetTheme(Option), + SetDeviceEventFilter(DeviceEventFilter), +} + +pub type CreateWindowClosure = + Box>) -> Result + Send>; + +pub type CreateWebviewClosure = + Box Result + Send>; + +pub struct CreateWebviewOptions { + #[cfg(windows)] + pub focused_webview: Arc>, +} + +pub enum Message { + Task(Box), + #[cfg(target_os = "macos")] + SetActivationPolicy(ActivationPolicy), + #[cfg(target_os = "macos")] + SetDockVisibility(bool), + RequestExit(i32), + Application(ApplicationMessage), + Window(WindowId, WindowMessage), + Webview(WindowId, WebviewId, WebviewMessage), + EventLoopWindowTarget(EventLoopWindowTargetMessage), + CreateWebview(WindowId, CreateWebviewClosure, Sender>), + CreateWindow(WindowId, CreateWindowClosure, Sender>), + CreateRawWindow( + WindowId, + Box (String, TaoWindowBuilder) + Send>, + Sender>>, + ), + UserEvent(T), +} + +impl Clone for Message { + fn clone(&self) -> Self { + match self { + Self::UserEvent(t) => Self::UserEvent(t.clone()), + _ => unimplemented!(), + } + } +} + +/// The Tauri [`WebviewDispatch`] for [`Wry`]. +#[derive(Debug, Clone)] +pub struct WryWebviewDispatcher { + window_id: Arc>, + webview_id: WebviewId, + context: Context, +} + +impl WebviewDispatch for WryWebviewDispatcher { + type Runtime = Wry; + + fn run_on_main_thread(&self, f: F) -> Result<()> { + self.context.send_user_message(Message::Task(Box::new(f))) + } + + fn on_webview_event(&self, f: F) -> WindowEventId { + let id = self.context.next_webview_event_id(); + let _ = self.context.proxy.send_event(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::AddEventListener(id, Box::new(f)), + )); + id + } + + fn with_webview) + Send + 'static>(&self, f: F) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::WithWebview(Box::new(move |webview| f(Box::new(webview)))), + )) + } + + #[cfg(any(debug_assertions, feature = "devtools"))] + fn open_devtools(&self) { + let _ = self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::OpenDevTools, + )); + } + + #[cfg(any(debug_assertions, feature = "devtools"))] + fn close_devtools(&self) { + let _ = self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::CloseDevTools, + )); + } + + /// Gets the devtools window's current open state. + #[cfg(any(debug_assertions, feature = "devtools"))] + fn is_devtools_open(&self) -> Result { + webview_getter!(self, WebviewMessage::IsDevToolsOpen) + } + + // Getters + + fn url(&self) -> Result { + webview_getter!(self, WebviewMessage::Url)? + } + + fn bounds(&self) -> Result { + webview_getter!(self, WebviewMessage::Bounds)? + } + + fn position(&self) -> Result> { + webview_getter!(self, WebviewMessage::Position)? + } + + fn size(&self) -> Result> { + webview_getter!(self, WebviewMessage::Size)? + } + + // Setters + + fn navigate(&self, url: Url) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Navigate(url), + )) + } + + fn reload(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Reload, + )) + } + + fn print(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Print, + )) + } + + fn close(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Close, + )) + } + + fn set_bounds(&self, bounds: tauri_runtime::dpi::Rect) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetBounds(bounds), + )) + } + + fn set_size(&self, size: Size) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetSize(size), + )) + } + + fn set_position(&self, position: Position) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetPosition(position), + )) + } + + fn set_focus(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetFocus, + )) + } + + fn reparent(&self, window_id: WindowId) -> Result<()> { + let mut current_window_id = self.window_id.lock().unwrap(); + let (tx, rx) = channel(); + self.context.send_user_message(Message::Webview( + *current_window_id, + self.webview_id, + WebviewMessage::Reparent(window_id, tx), + ))?; + + rx.recv().unwrap()?; + + *current_window_id = window_id; + Ok(()) + } + + fn cookies_for_url(&self, url: Url) -> Result>> { + let (tx, rx) = channel(); + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::CookiesForUrl(url, tx), + ))?; + + rx.recv().unwrap() + } + + fn cookies(&self) -> Result>> { + webview_getter!(self, WebviewMessage::Cookies)? + } + + fn set_cookie(&self, cookie: Cookie<'_>) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetCookie(cookie.into_owned()), + ))?; + Ok(()) + } + + fn delete_cookie(&self, cookie: Cookie<'_>) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::DeleteCookie(cookie.into_owned()), + ))?; + Ok(()) + } + + fn set_auto_resize(&self, auto_resize: bool) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetAutoResize(auto_resize), + )) + } + + #[cfg(all(feature = "tracing", not(target_os = "android")))] + fn eval_script>(&self, script: S) -> Result<()> { + // use a channel so the EvaluateScript task uses the current span as parent + let (tx, rx) = channel(); + getter!( + self, + rx, + Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::EvaluateScript(script.into(), tx, tracing::Span::current()), + ) + ) + } + + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + fn eval_script>(&self, script: S) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::EvaluateScript(script.into()), + )) + } + + #[cfg(all(feature = "tracing", not(target_os = "android")))] + fn eval_script_with_callback>( + &self, + script: S, + callback: impl Fn(String) + Send + 'static, + ) -> Result<()> { + // use a channel so the EvaluateScript task uses the current span as parent + let (tx, rx) = channel(); + getter!( + self, + rx, + Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::EvaluateScriptWithCallback( + script.into(), + Box::new(callback), + tx, + tracing::Span::current(), + ), + ) + ) + } + + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + fn eval_script_with_callback>( + &self, + script: S, + callback: impl Fn(String) + Send + 'static, + ) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::EvaluateScriptWithCallback(script.into(), Box::new(callback)), + )) + } + + fn set_zoom(&self, scale_factor: f64) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetZoom(scale_factor), + )) + } + + fn clear_all_browsing_data(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::ClearAllBrowsingData, + )) + } + + fn hide(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Hide, + )) + } + + fn show(&self) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::Show, + )) + } + + fn set_background_color(&self, color: Option) -> Result<()> { + self.context.send_user_message(Message::Webview( + *self.window_id.lock().unwrap(), + self.webview_id, + WebviewMessage::SetBackgroundColor(color), + )) + } +} + +/// The Tauri [`WindowDispatch`] for [`Wry`]. +#[derive(Debug, Clone)] +pub struct WryWindowDispatcher { + window_id: WindowId, + context: Context, +} + +// SAFETY: this is safe since the `Context` usage is guarded by `Context::send_user_message`. +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Sync for WryWindowDispatcher {} + +fn get_raw_window_handle( + dispatcher: &WryWindowDispatcher, +) -> Result> { + window_getter!(dispatcher, WindowMessage::RawWindowHandle) +} + +impl WindowDispatch for WryWindowDispatcher { + type Runtime = Wry; + type WindowBuilder = WindowBuilderWrapper; + + fn run_on_main_thread(&self, f: F) -> Result<()> { + self.context.send_user_message(Message::Task(Box::new(f))) + } + + fn on_window_event(&self, f: F) -> WindowEventId { + let id = self.context.next_window_event_id(); + let _ = self.context.proxy.send_event(Message::Window( + self.window_id, + WindowMessage::AddEventListener(id, Box::new(f)), + )); + id + } + + // Getters + + fn scale_factor(&self) -> Result { + window_getter!(self, WindowMessage::ScaleFactor) + } + + fn inner_position(&self) -> Result> { + window_getter!(self, WindowMessage::InnerPosition)? + } + + fn outer_position(&self) -> Result> { + window_getter!(self, WindowMessage::OuterPosition)? + } + + fn inner_size(&self) -> Result> { + window_getter!(self, WindowMessage::InnerSize) + } + + fn outer_size(&self) -> Result> { + window_getter!(self, WindowMessage::OuterSize) + } + + fn is_fullscreen(&self) -> Result { + window_getter!(self, WindowMessage::IsFullscreen) + } + + fn is_minimized(&self) -> Result { + window_getter!(self, WindowMessage::IsMinimized) + } + + fn is_maximized(&self) -> Result { + window_getter!(self, WindowMessage::IsMaximized) + } + + fn is_focused(&self) -> Result { + window_getter!(self, WindowMessage::IsFocused) + } + + /// Gets the window's current decoration state. + fn is_decorated(&self) -> Result { + window_getter!(self, WindowMessage::IsDecorated) + } + + /// Gets the window's current resizable state. + fn is_resizable(&self) -> Result { + window_getter!(self, WindowMessage::IsResizable) + } + + /// Gets the current native window's maximize button state + fn is_maximizable(&self) -> Result { + window_getter!(self, WindowMessage::IsMaximizable) + } + + /// Gets the current native window's minimize button state + fn is_minimizable(&self) -> Result { + window_getter!(self, WindowMessage::IsMinimizable) + } + + /// Gets the current native window's close button state + fn is_closable(&self) -> Result { + window_getter!(self, WindowMessage::IsClosable) + } + + fn is_visible(&self) -> Result { + window_getter!(self, WindowMessage::IsVisible) + } + + fn title(&self) -> Result { + window_getter!(self, WindowMessage::Title) + } + + fn current_monitor(&self) -> Result> { + window_getter!(self, WindowMessage::CurrentMonitor) + } + + fn primary_monitor(&self) -> Result> { + window_getter!(self, WindowMessage::PrimaryMonitor) + } + + fn monitor_from_point(&self, x: f64, y: f64) -> Result> { + let (tx, rx) = channel(); + + let _ = self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::MonitorFromPoint(tx, (x, y)), + )); + + rx.recv().map_err(|_| crate::Error::FailedToReceiveMessage) + } + + fn available_monitors(&self) -> Result> { + window_getter!(self, WindowMessage::AvailableMonitors) + } + + fn theme(&self) -> Result { + window_getter!(self, WindowMessage::Theme) + } + + fn is_enabled(&self) -> Result { + window_getter!(self, WindowMessage::IsEnabled) + } + + fn is_always_on_top(&self) -> Result { + window_getter!(self, WindowMessage::IsAlwaysOnTop) + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + fn gtk_window(&self) -> Result { + window_getter!(self, WindowMessage::GtkWindow).map(|w| w.0) + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + fn default_vbox(&self) -> Result { + window_getter!(self, WindowMessage::GtkBox).map(|w| w.0) + } + + /// Returns the name of the Android activity associated with this window. + #[cfg(target_os = "android")] + fn activity_name(&self) -> Result { + window_getter!(self, WindowMessage::ActivityName) + } + + /// Returns the identifier of the UIScene tied to this UIWindow. + #[cfg(target_os = "ios")] + fn scene_identifier(&self) -> Result { + window_getter!(self, WindowMessage::SceneIdentifier) + } + + fn window_handle( + &self, + ) -> std::result::Result, raw_window_handle::HandleError> { + get_raw_window_handle(self) + .map_err(|_| raw_window_handle::HandleError::Unavailable) + .and_then(|r| r.map(|h| unsafe { raw_window_handle::WindowHandle::borrow_raw(h.0) })) + } + + // Setters + + fn center(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Center)) + } + + fn request_user_attention(&self, request_type: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::RequestUserAttention(request_type.map(Into::into)), + )) + } + + // Creates a window by dispatching a message to the event loop. + // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock. + fn create_window( + &mut self, + pending: PendingWindow, + after_window_creation: Option, + ) -> Result> { + self.context.create_window(pending, after_window_creation) + } + + // Creates a webview by dispatching a message to the event loop. + // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock. + fn create_webview( + &mut self, + pending: PendingWebview, + ) -> Result> { + self.context.create_webview(self.window_id, pending) + } + + fn set_resizable(&self, resizable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetResizable(resizable), + )) + } + + fn set_enabled(&self, enabled: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetEnabled(enabled), + )) + } + + fn set_maximizable(&self, maximizable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetMaximizable(maximizable), + )) + } + + fn set_minimizable(&self, minimizable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetMinimizable(minimizable), + )) + } + + fn set_closable(&self, closable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetClosable(closable), + )) + } + + fn set_title>(&self, title: S) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetTitle(title.into()), + )) + } + + fn maximize(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Maximize)) + } + + fn unmaximize(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Unmaximize)) + } + + fn minimize(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Minimize)) + } + + fn unminimize(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Unminimize)) + } + + fn show(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Show)) + } + + fn hide(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::Hide)) + } + + fn close(&self) -> Result<()> { + // NOTE: close cannot use `Context::send_user_message` because it accesses the event loop callback + self + .context + .proxy + .send_event(Message::Window(self.window_id, WindowMessage::Close)) + .map_err(|_| Error::FailedToSendMessage) + } + + fn destroy(&self) -> Result<()> { + // NOTE: destroy cannot use `Context::send_user_message` because it accesses the event loop callback + self + .context + .proxy + .send_event(Message::Window(self.window_id, WindowMessage::Destroy)) + .map_err(|_| Error::FailedToSendMessage) + } + + fn set_decorations(&self, decorations: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetDecorations(decorations), + )) + } + + fn set_shadow(&self, enable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetShadow(enable), + )) + } + + fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetAlwaysOnBottom(always_on_bottom), + )) + } + + fn set_always_on_top(&self, always_on_top: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetAlwaysOnTop(always_on_top), + )) + } + + fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetVisibleOnAllWorkspaces(visible_on_all_workspaces), + )) + } + + fn set_content_protected(&self, protected: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetContentProtected(protected), + )) + } + + fn set_size(&self, size: Size) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetSize(size), + )) + } + + fn set_min_size(&self, size: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetMinSize(size), + )) + } + + fn set_max_size(&self, size: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetMaxSize(size), + )) + } + + fn set_size_constraints(&self, constraints: WindowSizeConstraints) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetSizeConstraints(constraints), + )) + } + + fn set_position(&self, position: Position) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetPosition(position), + )) + } + + fn set_fullscreen_on_monitor(&self, position: PhysicalPosition) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetFullscreenOnMonitor(position), + )) + } + + fn set_fullscreen(&self, fullscreen: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetFullscreen(fullscreen), + )) + } + + #[cfg(target_os = "macos")] + fn set_simple_fullscreen(&self, enable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetSimpleFullscreen(enable), + )) + } + + fn set_focus(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::SetFocus)) + } + + fn set_focusable(&self, focusable: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetFocusable(focusable), + )) + } + + fn set_icon(&self, icon: Icon) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetIcon(TaoIcon::try_from(icon)?.0), + )) + } + + fn set_skip_taskbar(&self, skip: bool) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetSkipTaskbar(skip), + )) + } + + fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetCursorGrab(grab), + )) + } + + fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetCursorVisible(visible), + )) + } + + fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetCursorIcon(icon), + )) + } + + fn set_cursor_position>(&self, position: Pos) -> crate::Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetCursorPosition(position.into()), + )) + } + + fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetIgnoreCursorEvents(ignore), + )) + } + + fn start_dragging(&self) -> Result<()> { + self + .context + .send_user_message(Message::Window(self.window_id, WindowMessage::DragWindow)) + } + + fn start_resize_dragging(&self, direction: tauri_runtime::ResizeDirection) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::ResizeDragWindow(direction), + )) + } + + fn set_badge_count(&self, count: Option, desktop_filename: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetBadgeCount(count, desktop_filename), + )) + } + + fn set_badge_label(&self, label: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetBadgeLabel(label), + )) + } + + fn set_overlay_icon(&self, icon: Option) -> Result<()> { + let icon: Result> = icon.map_or(Ok(None), |x| Ok(Some(TaoIcon::try_from(x)?))); + + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetOverlayIcon(icon?), + )) + } + + fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetProgressBar(progress_state), + )) + } + + fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetTitleBarStyle(style), + )) + } + + fn set_traffic_light_position(&self, position: Position) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetTrafficLightPosition(position), + )) + } + + fn set_theme(&self, theme: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetTheme(theme), + )) + } + + fn set_background_color(&self, color: Option) -> Result<()> { + self.context.send_user_message(Message::Window( + self.window_id, + WindowMessage::SetBackgroundColor(color), + )) + } +} + +#[derive(Clone)] +pub struct WebviewWrapper { + label: String, + id: WebviewId, + inner: Rc, + context_store: WebContextStore, + webview_event_listeners: WebviewEventListeners, + // the key of the WebContext if it's not shared + context_key: Option, + bounds: Arc>>, +} + +impl Deref for WebviewWrapper { + type Target = WebView; + + #[inline(always)] + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl Drop for WebviewWrapper { + fn drop(&mut self) { + if Rc::get_mut(&mut self.inner).is_some() { + let mut context_store = self.context_store.lock().unwrap(); + + if let Some(web_context) = context_store.get_mut(&self.context_key) { + web_context.referenced_by_webviews.remove(&self.label); + + // https://github.com/tauri-apps/tauri/issues/14626 + // Because WebKit does not close its network process even when no webviews are running, + // we need to ensure to re-use the existing process on Linux by keeping the WebContext + // alive for the lifetime of the app. + // WebKit on macOS handles this itself. + #[cfg(not(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )))] + if web_context.referenced_by_webviews.is_empty() { + context_store.remove(&self.context_key); + } + } + } + } +} + +#[cfg(windows)] +#[derive(Debug)] +pub enum FocusState { + WindowFocused, + WebviewFocused { + webview_label: String, + }, + Blured { + last_focused_webview_label: Option, + }, +} + +#[cfg(windows)] +impl Default for FocusState { + fn default() -> Self { + Self::Blured { + last_focused_webview_label: None, + } + } +} + +pub struct WindowWrapper { + label: String, + inner: Option>, + // whether this window has child webviews + // or it's just a container for a single webview + has_children: AtomicBool, + webviews: Vec, + window_event_listeners: WindowEventListeners, + #[cfg(windows)] + background_color: Option, + #[cfg(windows)] + is_window_transparent: bool, + #[cfg(windows)] + surface: Option, Arc>>, + #[cfg(windows)] + focused_webview: Arc>, +} + +impl WindowWrapper { + pub fn label(&self) -> &str { + &self.label + } +} + +impl fmt::Debug for WindowWrapper { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WindowWrapper") + .field("label", &self.label) + .field("inner", &self.inner) + .finish() + } +} + +#[derive(Debug, Clone)] +pub struct EventProxy(TaoEventLoopProxy>); + +#[cfg(target_os = "ios")] +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Sync for EventProxy {} + +impl EventLoopProxy for EventProxy { + fn send_event(&self, event: T) -> Result<()> { + self + .0 + .send_event(Message::UserEvent(event)) + .map_err(|_| Error::EventLoopClosed) + } +} + +pub trait PluginBuilder { + type Plugin: Plugin; + fn build(self, context: Context) -> Self::Plugin; +} + +pub trait Plugin { + fn on_event( + &mut self, + event: &Event>, + event_loop: &EventLoopWindowTarget>, + proxy: &TaoEventLoopProxy>, + control_flow: &mut ControlFlow, + context: EventLoopIterationContext<'_, T>, + web_context: &WebContextStore, + ) -> bool; +} + +/// A Tauri [`Runtime`] wrapper around wry. +pub struct Wry { + context: Context, + event_loop: EventLoop>, +} + +impl fmt::Debug for Wry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Wry") + .field("main_thread_id", &self.context.main_thread_id) + .field("event_loop", &self.event_loop) + .field("windows", &self.context.main_thread.windows) + .field("web_context", &self.context.main_thread.web_context) + .finish() + } +} + +/// A handle to the Wry runtime. +#[derive(Debug, Clone)] +pub struct WryHandle { + context: Context, +} + +// SAFETY: this is safe since the `Context` usage is guarded by `Context::send_user_message`. +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Sync for WryHandle {} + +impl WryHandle { + /// Creates a new tao window using a callback, and returns its window id. + pub fn create_tao_window (String, TaoWindowBuilder) + Send + 'static>( + &self, + f: F, + ) -> Result> { + let id = self.context.next_window_id(); + let (tx, rx) = channel(); + self + .context + .send_user_message(Message::CreateRawWindow(id, Box::new(f), tx))?; + rx.recv().unwrap() + } + + /// Gets the [`WindowId`] associated with the given [`TaoWindowId`]. + pub fn window_id(&self, window_id: TaoWindowId) -> WindowId { + self.context.window_id_map.get(&window_id).unwrap() + } + + /// Send a message to the event loop. + pub fn send_event(&self, message: Message) -> Result<()> { + self + .context + .proxy + .send_event(message) + .map_err(|_| Error::FailedToSendMessage)?; + Ok(()) + } + + pub fn plugin + 'static>(&mut self, plugin: P) + where +

>::Plugin: Send, + { + self + .context + .plugins + .lock() + .unwrap() + .push(Box::new(plugin.build(self.context.clone()))); + } +} + +impl RuntimeHandle for WryHandle { + type Runtime = Wry; + + fn create_proxy(&self) -> EventProxy { + EventProxy(self.context.proxy.clone()) + } + + #[cfg(target_os = "macos")] + fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> Result<()> { + self + .context + .send_user_message(Message::SetActivationPolicy(activation_policy)) + } + + #[cfg(target_os = "macos")] + fn set_dock_visibility(&self, visible: bool) -> Result<()> { + self + .context + .send_user_message(Message::SetDockVisibility(visible)) + } + + fn request_exit(&self, code: i32) -> Result<()> { + // NOTE: request_exit cannot use `Context::send_user_message` because it accesses the event loop callback + self + .context + .proxy + .send_event(Message::RequestExit(code)) + .map_err(|_| Error::FailedToSendMessage) + } + + // Creates a window by dispatching a message to the event loop. + // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock. + fn create_window( + &self, + pending: PendingWindow, + after_window_creation: Option, + ) -> Result> { + self.context.create_window(pending, after_window_creation) + } + + // Creates a webview by dispatching a message to the event loop. + // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock. + fn create_webview( + &self, + window_id: WindowId, + pending: PendingWebview, + ) -> Result> { + self.context.create_webview(window_id, pending) + } + + fn run_on_main_thread(&self, f: F) -> Result<()> { + self.context.send_user_message(Message::Task(Box::new(f))) + } + + fn display_handle( + &self, + ) -> std::result::Result, raw_window_handle::HandleError> { + self.context.main_thread.window_target.display_handle() + } + + fn primary_monitor(&self) -> Result> { + event_loop_window_getter!(self, EventLoopWindowTargetMessage::PrimaryMonitor) + } + + fn monitor_from_point(&self, x: f64, y: f64) -> Result> { + let (tx, rx) = channel(); + self + .context + .send_user_message(Message::EventLoopWindowTarget( + EventLoopWindowTargetMessage::MonitorFromPoint(tx, (x, y)), + ))?; + Ok(rx.recv().unwrap()) + } + + fn available_monitors(&self) -> Result> { + event_loop_window_getter!(self, EventLoopWindowTargetMessage::AvailableMonitors) + } + + fn cursor_position(&self) -> Result> { + event_loop_window_getter!(self, EventLoopWindowTargetMessage::CursorPosition)? + .map_err(|_| Error::FailedToGetCursorPosition) + } + + fn set_theme(&self, theme: Option) { + let _ = self + .context + .send_user_message(Message::EventLoopWindowTarget( + EventLoopWindowTargetMessage::SetTheme(theme), + )); + } + + #[cfg(target_os = "macos")] + fn show(&self) -> tauri_runtime::Result<()> { + self + .context + .send_user_message(Message::Application(ApplicationMessage::Show)) + } + + #[cfg(target_os = "macos")] + fn hide(&self) -> tauri_runtime::Result<()> { + self + .context + .send_user_message(Message::Application(ApplicationMessage::Hide)) + } + + fn set_device_event_filter(&self, filter: DeviceEventFilter) { + let _ = self + .context + .send_user_message(Message::EventLoopWindowTarget( + EventLoopWindowTargetMessage::SetDeviceEventFilter(filter), + )); + } + + #[cfg(target_os = "android")] + fn find_class<'a>( + &self, + env: &mut jni::JNIEnv<'a>, + activity: &jni::objects::JObject<'_>, + name: impl Into, + ) -> std::result::Result, jni::errors::Error> { + find_class(env, activity, name.into()) + } + + #[cfg(target_os = "android")] + fn run_on_android_context(&self, f: F) + where + F: FnOnce(&mut jni::JNIEnv<'_>, &jni::objects::JObject<'_>, &jni::objects::JObject<'_>) + + Send + + 'static, + { + dispatch(f) + } + + #[cfg(any(target_os = "macos", target_os = "ios"))] + fn fetch_data_store_identifiers) + Send + 'static>( + &self, + cb: F, + ) -> Result<()> { + self.context.send_user_message(Message::Application( + ApplicationMessage::FetchDataStoreIdentifiers(Box::new(cb)), + )) + } + + #[cfg(any(target_os = "macos", target_os = "ios"))] + fn remove_data_store) + Send + 'static>( + &self, + uuid: [u8; 16], + cb: F, + ) -> Result<()> { + self + .context + .send_user_message(Message::Application(ApplicationMessage::RemoveDataStore( + uuid, + Box::new(cb), + ))) + } +} + +impl Wry { + fn init_with_builder( + mut event_loop_builder: EventLoopBuilder>, + #[allow(unused_variables)] args: RuntimeInitArgs, + ) -> Result { + #[cfg(windows)] + if let Some(hook) = args.msg_hook { + use tao::platform::windows::EventLoopBuilderExtWindows; + event_loop_builder.with_msg_hook(hook); + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + if let Some(app_id) = args.app_id { + use tao::platform::unix::EventLoopBuilderExtUnix; + event_loop_builder.with_app_id(app_id); + } + Self::init(event_loop_builder.build()) + } + + fn init(event_loop: EventLoop>) -> Result { + let main_thread_id = current_thread().id(); + let web_context = WebContextStore::default(); + + #[allow(clippy::arc_with_non_send_sync)] + let windows = Arc::new(WindowsStore(RefCell::new(BTreeMap::default()))); + let window_id_map = WindowIdStore::default(); + + let context = Context { + window_id_map, + main_thread_id, + proxy: event_loop.create_proxy(), + main_thread: DispatcherMainThreadContext { + window_target: event_loop.deref().clone(), + web_context, + windows, + #[cfg(feature = "tracing")] + active_tracing_spans: Default::default(), + }, + plugins: Default::default(), + next_window_id: Default::default(), + next_webview_id: Default::default(), + next_window_event_id: Default::default(), + next_webview_event_id: Default::default(), + webview_runtime_installed: wry::webview_version().is_ok(), + }; + + Ok(Self { + context, + event_loop, + }) + } +} + +impl Runtime for Wry { + type WindowDispatcher = WryWindowDispatcher; + type WebviewDispatcher = WryWebviewDispatcher; + type Handle = WryHandle; + + type EventLoopProxy = EventProxy; + + fn new(args: RuntimeInitArgs) -> Result { + Self::init_with_builder(EventLoopBuilder::>::with_user_event(), args) + } + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + fn new_any_thread(args: RuntimeInitArgs) -> Result { + use tao::platform::unix::EventLoopBuilderExtUnix; + let mut event_loop_builder = EventLoopBuilder::>::with_user_event(); + event_loop_builder.with_any_thread(true); + Self::init_with_builder(event_loop_builder, args) + } + + #[cfg(windows)] + fn new_any_thread(args: RuntimeInitArgs) -> Result { + use tao::platform::windows::EventLoopBuilderExtWindows; + let mut event_loop_builder = EventLoopBuilder::>::with_user_event(); + event_loop_builder.with_any_thread(true); + Self::init_with_builder(event_loop_builder, args) + } + + fn create_proxy(&self) -> EventProxy { + EventProxy(self.event_loop.create_proxy()) + } + + fn handle(&self) -> Self::Handle { + WryHandle { + context: self.context.clone(), + } + } + + fn create_window( + &self, + pending: PendingWindow, + after_window_creation: Option, + ) -> Result> { + let label = pending.label.clone(); + let window_id = self.context.next_window_id(); + let (webview_id, use_https_scheme) = pending + .webview + .as_ref() + .map(|w| { + ( + Some(self.context.next_webview_id()), + w.webview_attributes.use_https_scheme, + ) + }) + .unwrap_or((None, false)); + + let window = create_window( + window_id, + webview_id.unwrap_or_default(), + &self.event_loop, + &self.context, + pending, + after_window_creation, + )?; + + let dispatcher = WryWindowDispatcher { + window_id, + context: self.context.clone(), + }; + + self + .context + .main_thread + .windows + .0 + .borrow_mut() + .insert(window_id, window); + + let detached_webview = webview_id.map(|id| { + let webview = DetachedWebview { + label: label.clone(), + dispatcher: WryWebviewDispatcher { + window_id: Arc::new(Mutex::new(window_id)), + webview_id: id, + context: self.context.clone(), + }, + }; + DetachedWindowWebview { + webview, + use_https_scheme, + } + }); + + Ok(DetachedWindow { + id: window_id, + label, + dispatcher, + webview: detached_webview, + }) + } + + fn create_webview( + &self, + window_id: WindowId, + pending: PendingWebview, + ) -> Result> { + let label = pending.label.clone(); + + let window = self + .context + .main_thread + .windows + .0 + .borrow() + .get(&window_id) + .map(|w| { + ( + w.inner.clone(), + CreateWebviewOptions { + #[cfg(windows)] + focused_webview: w.focused_webview.clone(), + }, + ) + }); + if let Some((Some(window), _options)) = window { + let window_id_wrapper = Arc::new(Mutex::new(window_id)); + + let webview_id = self.context.next_webview_id(); + + let webview = create_webview( + WebviewKind::WindowChild, + &window, + window_id_wrapper.clone(), + webview_id, + &self.context, + pending, + #[cfg(windows)] + _options.focused_webview, + )?; + + if let Some(w) = self + .context + .main_thread + .windows + .0 + .borrow_mut() + .get_mut(&window_id) + { + w.webviews.push(webview); + w.has_children.store(true, Ordering::Relaxed); + } + + let dispatcher = WryWebviewDispatcher { + window_id: window_id_wrapper, + webview_id, + context: self.context.clone(), + }; + + Ok(DetachedWebview { label, dispatcher }) + } else { + Err(Error::WindowNotFound) + } + } + + fn primary_monitor(&self) -> Option { + self + .context + .main_thread + .window_target + .primary_monitor() + .map(|m| MonitorHandleWrapper(m).into()) + } + + fn monitor_from_point(&self, x: f64, y: f64) -> Option { + self + .context + .main_thread + .window_target + .monitor_from_point(x, y) + .map(|m| MonitorHandleWrapper(m).into()) + } + + fn available_monitors(&self) -> Vec { + self + .context + .main_thread + .window_target + .available_monitors() + .map(|m| MonitorHandleWrapper(m).into()) + .collect() + } + + fn cursor_position(&self) -> Result> { + self + .context + .main_thread + .window_target + .cursor_position() + .map_err(|_| Error::FailedToGetCursorPosition) + } + + fn set_theme(&self, theme: Option) { + self.event_loop.set_theme(to_tao_theme(theme)); + } + + #[cfg(target_os = "macos")] + fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) { + self + .event_loop + .set_activation_policy(tao_activation_policy(activation_policy)); + } + + #[cfg(target_os = "macos")] + fn set_activate_ignoring_other_apps(&mut self, ignore: bool) { + self.event_loop.set_activate_ignoring_other_apps(ignore); + } + + #[cfg(target_os = "macos")] + fn set_dock_visibility(&mut self, visible: bool) { + self.event_loop.set_dock_visibility(visible); + } + + #[cfg(target_os = "macos")] + fn show(&self) { + self.event_loop.show_application(); + } + + #[cfg(target_os = "macos")] + fn hide(&self) { + self.event_loop.hide_application(); + } + + fn set_device_event_filter(&mut self, filter: DeviceEventFilter) { + self + .event_loop + .set_device_event_filter(DeviceEventFilterWrapper::from(filter).0); + } + + #[cfg(desktop)] + fn run_iteration) + 'static>(&mut self, mut callback: F) { + use tao::platform::run_return::EventLoopExtRunReturn; + let windows = &self.context.main_thread.windows; + let window_id_map = &self.context.window_id_map; + let web_context = &self.context.main_thread.web_context; + let plugins = &self.context.plugins; + + #[cfg(feature = "tracing")] + let active_tracing_spans = &self.context.main_thread.active_tracing_spans; + + let proxy = self.event_loop.create_proxy(); + + self + .event_loop + .run_return(|event, event_loop, control_flow| { + *control_flow = ControlFlow::Wait; + if let Event::MainEventsCleared = &event { + *control_flow = ControlFlow::Exit; + } + + for p in plugins.lock().unwrap().iter_mut() { + let prevent_default = p.on_event( + &event, + event_loop, + &proxy, + control_flow, + EventLoopIterationContext { + callback: &mut callback, + window_id_map, + windows, + #[cfg(feature = "tracing")] + active_tracing_spans, + }, + web_context, + ); + if prevent_default { + return; + } + } + + handle_event_loop( + event, + event_loop, + control_flow, + EventLoopIterationContext { + callback: &mut callback, + windows, + window_id_map, + #[cfg(feature = "tracing")] + active_tracing_spans, + }, + ); + }); + } + + fn run) + 'static>(self, callback: F) { + let event_handler = make_event_handler(self.context, callback); + self.event_loop.run(event_handler) + } + + #[cfg(not(target_os = "ios"))] + fn run_return) + 'static>(mut self, callback: F) -> i32 { + use tao::platform::run_return::EventLoopExtRunReturn; + + let event_handler = make_event_handler(self.context, callback); + self.event_loop.run_return(event_handler) + } + + #[cfg(target_os = "ios")] + fn run_return) + 'static>(self, callback: F) -> i32 { + self.run(callback); + 0 + } +} + +fn make_event_handler) + 'static>( + context: Context, + mut callback: F, +) -> impl FnMut(Event<'_, Message>, &EventLoopWindowTarget>, &mut ControlFlow) { + let windows = context.main_thread.windows; + let window_id_map = context.window_id_map; + let web_context = context.main_thread.web_context; + let plugins = context.plugins; + + #[cfg(feature = "tracing")] + let active_tracing_spans = context.main_thread.active_tracing_spans; + let proxy = context.proxy; + + move |event, event_loop, control_flow| { + for p in plugins.lock().unwrap().iter_mut() { + let prevent_default = p.on_event( + &event, + event_loop, + &proxy, + control_flow, + EventLoopIterationContext { + callback: &mut callback, + window_id_map: &window_id_map, + windows: &windows, + #[cfg(feature = "tracing")] + active_tracing_spans: &active_tracing_spans, + }, + &web_context, + ); + if prevent_default { + return; + } + } + handle_event_loop( + event, + event_loop, + control_flow, + EventLoopIterationContext { + callback: &mut callback, + window_id_map: &window_id_map, + windows: &windows, + #[cfg(feature = "tracing")] + active_tracing_spans: &active_tracing_spans, + }, + ); + } +} + +pub struct EventLoopIterationContext<'a, T: UserEvent> { + pub callback: &'a mut (dyn FnMut(RunEvent) + 'static), + pub window_id_map: &'a WindowIdStore, + pub windows: &'a WindowsStore, + #[cfg(feature = "tracing")] + pub active_tracing_spans: &'a ActiveTraceSpanStore, +} + +struct UserMessageContext<'a> { + windows: &'a WindowsStore, + window_id_map: &'a WindowIdStore, +} + +fn handle_user_message( + event_loop: &EventLoopWindowTarget>, + message: Message, + context: UserMessageContext, +) { + let UserMessageContext { + window_id_map, + windows, + } = context; + match message { + Message::Task(task) => task(), + #[cfg(target_os = "macos")] + Message::SetActivationPolicy(activation_policy) => { + event_loop.set_activation_policy_at_runtime(tao_activation_policy(activation_policy)) + } + #[cfg(target_os = "macos")] + Message::SetDockVisibility(visible) => event_loop.set_dock_visibility(visible), + Message::RequestExit(_code) => panic!("cannot handle RequestExit on the main thread"), + Message::Application(application_message) => match application_message { + #[cfg(target_os = "macos")] + ApplicationMessage::Show => { + event_loop.show_application(); + } + #[cfg(target_os = "macos")] + ApplicationMessage::Hide => { + event_loop.hide_application(); + } + #[cfg(any(target_os = "macos", target_os = "ios"))] + ApplicationMessage::FetchDataStoreIdentifiers(cb) => { + if let Err(e) = WebView::fetch_data_store_identifiers(cb) { + // this shouldn't ever happen because we're running on the main thread + // but let's be safe and warn here + log::error!("failed to fetch data store identifiers: {e}"); + } + } + #[cfg(any(target_os = "macos", target_os = "ios"))] + ApplicationMessage::RemoveDataStore(uuid, cb) => { + WebView::remove_data_store(&uuid, move |res| { + cb(res.map_err(|_| Error::FailedToRemoveDataStore)) + }) + } + }, + Message::Window(id, window_message) => { + let w = windows.0.borrow().get(&id).map(|w| { + #[cfg(windows)] + let focused_webview = w.focused_webview.clone(); + #[cfg(not(windows))] + let focused_webview = (); + ( + w.inner.clone(), + w.webviews.clone(), + w.has_children.load(Ordering::Relaxed), + w.window_event_listeners.clone(), + focused_webview, + ) + }); + if let Some(( + Some(window), + webviews, + has_children, + window_event_listeners, + _focused_webview, + )) = w + { + match window_message { + WindowMessage::AddEventListener(id, listener) => { + window_event_listeners.lock().unwrap().insert(id, listener); + } + + // Getters + WindowMessage::ScaleFactor(tx) => tx.send(window.scale_factor()).unwrap(), + WindowMessage::InnerPosition(tx) => tx + .send( + window + .inner_position() + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(), + WindowMessage::OuterPosition(tx) => tx + .send( + window + .outer_position() + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(), + WindowMessage::InnerSize(tx) => tx + .send(inner_size(&window, &webviews, has_children)) + .unwrap(), + WindowMessage::OuterSize(tx) => tx.send(window.outer_size()).unwrap(), + WindowMessage::IsFullscreen(tx) => tx.send(window.fullscreen().is_some()).unwrap(), + WindowMessage::IsMinimized(tx) => tx.send(window.is_minimized()).unwrap(), + WindowMessage::IsMaximized(tx) => tx.send(window.is_maximized()).unwrap(), + #[cfg(not(windows))] + WindowMessage::IsFocused(tx) => tx.send(window.is_focused()).unwrap(), + #[cfg(windows)] + WindowMessage::IsFocused(tx) => { + let focused = if has_children { + // on multiwebview mode, get the focused state from cache, + // as the window might not have direct focus + matches!( + *_focused_webview.lock().unwrap(), + FocusState::WindowFocused | FocusState::WebviewFocused { .. } + ) + } else { + window.is_focused() + }; + tx.send(focused).unwrap() + } + WindowMessage::IsDecorated(tx) => tx.send(window.is_decorated()).unwrap(), + WindowMessage::IsResizable(tx) => tx.send(window.is_resizable()).unwrap(), + WindowMessage::IsMaximizable(tx) => tx.send(window.is_maximizable()).unwrap(), + WindowMessage::IsMinimizable(tx) => tx.send(window.is_minimizable()).unwrap(), + WindowMessage::IsClosable(tx) => tx.send(window.is_closable()).unwrap(), + WindowMessage::IsVisible(tx) => tx.send(window.is_visible()).unwrap(), + WindowMessage::Title(tx) => tx.send(window.title()).unwrap(), + WindowMessage::CurrentMonitor(tx) => tx + .send( + window + .current_monitor() + .map(|m| MonitorHandleWrapper(m).into()), + ) + .unwrap(), + WindowMessage::PrimaryMonitor(tx) => tx + .send( + window + .primary_monitor() + .map(|m| MonitorHandleWrapper(m).into()), + ) + .unwrap(), + WindowMessage::MonitorFromPoint(tx, (x, y)) => tx + .send( + window + .monitor_from_point(x, y) + .map(|m| MonitorHandleWrapper(m).into()), + ) + .unwrap(), + WindowMessage::AvailableMonitors(tx) => tx + .send( + window + .available_monitors() + .map(|m| MonitorHandleWrapper(m).into()) + .collect(), + ) + .unwrap(), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + WindowMessage::GtkWindow(tx) => tx.send(GtkWindow(window.gtk_window().clone())).unwrap(), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + WindowMessage::GtkBox(tx) => tx + .send(GtkBox(window.default_vbox().unwrap().clone())) + .unwrap(), + #[cfg(target_os = "android")] + WindowMessage::ActivityName(tx) => { + tx.send(window.activity_name()).unwrap(); + } + #[cfg(target_os = "ios")] + WindowMessage::SceneIdentifier(tx) => { + tx.send(window.scene_identifier()).unwrap(); + } + WindowMessage::RawWindowHandle(tx) => tx + .send( + window + .window_handle() + .map(|h| SendRawWindowHandle(h.as_raw())), + ) + .unwrap(), + WindowMessage::Theme(tx) => { + tx.send(map_theme(&window.theme())).unwrap(); + } + WindowMessage::IsEnabled(tx) => tx.send(window.is_enabled()).unwrap(), + WindowMessage::IsAlwaysOnTop(tx) => tx.send(window.is_always_on_top()).unwrap(), + // Setters + WindowMessage::Center => window.center(), + WindowMessage::RequestUserAttention(request_type) => { + window.request_user_attention(request_type.map(|r| r.0)); + } + WindowMessage::SetResizable(resizable) => { + window.set_resizable(resizable); + #[cfg(windows)] + if !resizable { + undecorated_resizing::detach_resize_handler(window.hwnd()); + } else if !window.is_decorated() { + undecorated_resizing::attach_resize_handler( + window.hwnd(), + window.has_undecorated_shadow(), + ); + } + } + WindowMessage::SetMaximizable(maximizable) => window.set_maximizable(maximizable), + WindowMessage::SetMinimizable(minimizable) => window.set_minimizable(minimizable), + WindowMessage::SetClosable(closable) => window.set_closable(closable), + WindowMessage::SetTitle(title) => window.set_title(&title), + WindowMessage::Maximize => window.set_maximized(true), + WindowMessage::Unmaximize => window.set_maximized(false), + WindowMessage::Minimize => window.set_minimized(true), + WindowMessage::Unminimize => window.set_minimized(false), + WindowMessage::SetEnabled(enabled) => window.set_enabled(enabled), + WindowMessage::Show => window.set_visible(true), + WindowMessage::Hide => window.set_visible(false), + WindowMessage::Close => { + panic!("cannot handle `WindowMessage::Close` on the main thread") + } + WindowMessage::Destroy => { + panic!("cannot handle `WindowMessage::Destroy` on the main thread") + } + WindowMessage::SetDecorations(decorations) => { + window.set_decorations(decorations); + #[cfg(windows)] + if decorations { + undecorated_resizing::detach_resize_handler(window.hwnd()); + } else if window.is_resizable() { + undecorated_resizing::attach_resize_handler( + window.hwnd(), + window.has_undecorated_shadow(), + ); + } + } + WindowMessage::SetShadow(_enable) => { + #[cfg(windows)] + { + window.set_undecorated_shadow(_enable); + undecorated_resizing::update_drag_hwnd_rgn_for_undecorated(window.hwnd(), _enable); + } + #[cfg(target_os = "macos")] + window.set_has_shadow(_enable); + } + WindowMessage::SetAlwaysOnBottom(always_on_bottom) => { + window.set_always_on_bottom(always_on_bottom) + } + WindowMessage::SetAlwaysOnTop(always_on_top) => window.set_always_on_top(always_on_top), + WindowMessage::SetVisibleOnAllWorkspaces(visible_on_all_workspaces) => { + window.set_visible_on_all_workspaces(visible_on_all_workspaces) + } + WindowMessage::SetContentProtected(protected) => window.set_content_protection(protected), + WindowMessage::SetSize(size) => { + window.set_inner_size(size); + } + WindowMessage::SetMinSize(size) => { + window.set_min_inner_size(size); + } + WindowMessage::SetMaxSize(size) => { + window.set_max_inner_size(size); + } + WindowMessage::SetSizeConstraints(constraints) => { + window.set_inner_size_constraints(tao::window::WindowSizeConstraints { + min_width: constraints.min_width, + min_height: constraints.min_height, + max_width: constraints.max_width, + max_height: constraints.max_height, + }); + } + WindowMessage::SetPosition(position) => window.set_outer_position(position), + WindowMessage::SetFullscreen(fullscreen) => { + if fullscreen { + window.set_fullscreen(Some(Fullscreen::Borderless(None))) + } else { + window.set_fullscreen(None) + } + } + WindowMessage::SetFullscreenOnMonitor(position) => { + // Not `Window::monitor_from_point`: on macOS and Linux (GTK) it takes logical + // coordinates, while callers pass physical ones (e.g. `Monitor::position`). + if let Some(monitor) = + find_monitor_for_position(window.available_monitors(), position.into()) + { + window.set_fullscreen(Some(Fullscreen::Borderless(Some(monitor)))) + } + } + + #[cfg(target_os = "macos")] + WindowMessage::SetSimpleFullscreen(enable) => { + window.set_simple_fullscreen(enable); + } + + WindowMessage::SetFocus => { + window.set_focus(); + } + WindowMessage::SetFocusable(focusable) => { + window.set_focusable(focusable); + } + WindowMessage::SetIcon(icon) => { + window.set_window_icon(Some(icon)); + } + #[allow(unused_variables)] + WindowMessage::SetSkipTaskbar(skip) => { + #[cfg(any( + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + let _ = window.set_skip_taskbar(skip); + } + WindowMessage::SetCursorGrab(grab) => { + let _ = window.set_cursor_grab(grab); + } + WindowMessage::SetCursorVisible(visible) => { + window.set_cursor_visible(visible); + } + WindowMessage::SetCursorIcon(icon) => { + window.set_cursor_icon(CursorIconWrapper::from(icon).0); + } + WindowMessage::SetCursorPosition(position) => { + let _ = window.set_cursor_position(position); + } + WindowMessage::SetIgnoreCursorEvents(ignore) => { + let _ = window.set_ignore_cursor_events(ignore); + } + WindowMessage::DragWindow => { + let _ = window.drag_window(); + } + WindowMessage::ResizeDragWindow(direction) => { + let _ = window.drag_resize_window(match direction { + tauri_runtime::ResizeDirection::East => tao::window::ResizeDirection::East, + tauri_runtime::ResizeDirection::North => tao::window::ResizeDirection::North, + tauri_runtime::ResizeDirection::NorthEast => tao::window::ResizeDirection::NorthEast, + tauri_runtime::ResizeDirection::NorthWest => tao::window::ResizeDirection::NorthWest, + tauri_runtime::ResizeDirection::South => tao::window::ResizeDirection::South, + tauri_runtime::ResizeDirection::SouthEast => tao::window::ResizeDirection::SouthEast, + tauri_runtime::ResizeDirection::SouthWest => tao::window::ResizeDirection::SouthWest, + tauri_runtime::ResizeDirection::West => tao::window::ResizeDirection::West, + }); + } + WindowMessage::RequestRedraw => { + window.request_redraw(); + } + WindowMessage::SetBadgeCount(_count, _desktop_filename) => { + #[cfg(target_os = "ios")] + window.set_badge_count( + _count.map_or(0, |x| x.clamp(i32::MIN as i64, i32::MAX as i64) as i32), + ); + + #[cfg(target_os = "macos")] + window.set_badge_label(_count.map(|x| x.to_string())); + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + window.set_badge_count(_count, _desktop_filename); + } + WindowMessage::SetBadgeLabel(_label) => { + #[cfg(target_os = "macos")] + window.set_badge_label(_label); + } + WindowMessage::SetOverlayIcon(_icon) => { + #[cfg(windows)] + window.set_overlay_icon(_icon.map(|x| x.0).as_ref()); + } + WindowMessage::SetProgressBar(progress_state) => { + window.set_progress_bar(ProgressBarStateWrapper::from(progress_state).0); + } + WindowMessage::SetTitleBarStyle(_style) => { + #[cfg(target_os = "macos")] + match _style { + TitleBarStyle::Visible => { + window.set_titlebar_transparent(false); + window.set_fullsize_content_view(true); + } + TitleBarStyle::Transparent => { + window.set_titlebar_transparent(true); + window.set_fullsize_content_view(false); + } + TitleBarStyle::Overlay => { + window.set_titlebar_transparent(true); + window.set_fullsize_content_view(true); + } + unknown => { + #[cfg(feature = "tracing")] + tracing::warn!("unknown title bar style applied: {unknown}"); + + #[cfg(not(feature = "tracing"))] + eprintln!("unknown title bar style applied: {unknown}"); + } + }; + } + WindowMessage::SetTrafficLightPosition(_position) => { + #[cfg(target_os = "macos")] + window.set_traffic_light_inset(_position); + } + WindowMessage::SetTheme(theme) => { + window.set_theme(to_tao_theme(theme)); + } + WindowMessage::SetBackgroundColor(color) => { + window.set_background_color(color.map(Into::into)) + } + } + } + } + Message::Webview(window_id, webview_id, webview_message) => { + #[cfg(any( + target_os = "macos", + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + if let WebviewMessage::Reparent(new_parent_window_id, tx) = webview_message { + let webview_handle = windows.0.borrow_mut().get_mut(&window_id).and_then(|w| { + w.webviews + .iter() + .position(|w| w.id == webview_id) + .map(|webview_index| w.webviews.remove(webview_index)) + }); + + if let Some(webview) = webview_handle { + if let Some((Some(new_parent_window), new_parent_window_webviews)) = windows + .0 + .borrow_mut() + .get_mut(&new_parent_window_id) + .map(|w| (w.inner.clone(), &mut w.webviews)) + { + #[cfg(target_os = "macos")] + let reparent_result = { + use wry::WebViewExtMacOS; + webview.inner.reparent(new_parent_window.ns_window() as _) + }; + #[cfg(windows)] + let reparent_result = { webview.inner.reparent(new_parent_window.hwnd()) }; + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + let reparent_result = { + if let Some(container) = new_parent_window.default_vbox() { + let (_, children) = gtk_child_layout::containers(container); + webview.inner.reparent(&children) + } else { + Err(wry::Error::MessageSender) + } + }; + + match reparent_result { + Ok(_) => { + new_parent_window_webviews.push(webview); + tx.send(Ok(())).unwrap(); + } + Err(e) => { + log::error!("failed to reparent webview: {e}"); + tx.send(Err(Error::FailedToSendMessage)).unwrap(); + } + } + } + } else { + tx.send(Err(Error::FailedToSendMessage)).unwrap(); + } + + return; + } + + let webview_handle = windows.0.borrow().get(&window_id).map(|w| { + ( + w.inner.clone(), + w.webviews.iter().find(|w| w.id == webview_id).cloned(), + ) + }); + if let Some((Some(window), Some(webview))) = webview_handle { + match webview_message { + WebviewMessage::WebviewEvent(_) => { /* already handled */ } + WebviewMessage::SynthesizedWindowEvent(_) => { /* already handled */ } + WebviewMessage::Reparent(_window_id, _tx) => { /* already handled */ } + WebviewMessage::AddEventListener(id, listener) => { + webview + .webview_event_listeners + .lock() + .unwrap() + .insert(id, listener); + } + + #[cfg(all(feature = "tracing", not(target_os = "android")))] + WebviewMessage::EvaluateScript(script, tx, span) => { + let _span = span.entered(); + if let Err(e) = webview.evaluate_script(&script) { + log::error!("{e}"); + } + tx.send(()).unwrap(); + } + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + WebviewMessage::EvaluateScript(script) => { + if let Err(e) = webview.evaluate_script(&script) { + log::error!("{e}"); + } + } + #[cfg(all(feature = "tracing", not(target_os = "android")))] + WebviewMessage::EvaluateScriptWithCallback(script, callback, tx, span) => { + let _span = span.entered(); + if let Err(e) = webview.evaluate_script_with_callback(&script, callback) { + log::error!("{e}"); + } + tx.send(()).unwrap(); + } + #[cfg(not(all(feature = "tracing", not(target_os = "android"))))] + WebviewMessage::EvaluateScriptWithCallback(script, callback) => { + if let Err(e) = webview.evaluate_script_with_callback(&script, callback) { + log::error!("{e}"); + } + } + WebviewMessage::Navigate(url) => { + if let Err(e) = webview.load_url(url.as_str()) { + log::error!("failed to navigate to url {}: {}", url, e); + } + } + WebviewMessage::Reload => { + if let Err(e) = webview.reload() { + log::error!("failed to reload: {e}"); + } + } + WebviewMessage::Show => { + if let Err(e) = webview.set_visible(true) { + log::error!("failed to change webview visibility: {e}"); + } + } + WebviewMessage::Hide => { + if let Err(e) = webview.set_visible(false) { + log::error!("failed to change webview visibility: {e}"); + } + } + WebviewMessage::Print => { + let _ = webview.print(); + } + WebviewMessage::Close => { + #[allow(unknown_lints, clippy::manual_inspect)] + windows.0.borrow_mut().get_mut(&window_id).map(|window| { + if let Some(i) = window.webviews.iter().position(|w| w.id == webview.id) { + window.webviews.remove(i); + } + window + }); + } + WebviewMessage::SetBounds(bounds) => { + let bounds: RectWrapper = bounds.into(); + let bounds = bounds.0; + + if let Some(b) = &mut *webview.bounds.lock().unwrap() { + let scale_factor = window.scale_factor(); + let size = bounds.size.to_logical::(scale_factor); + let position = bounds.position.to_logical::(scale_factor); + let window_size = window.inner_size().to_logical::(scale_factor); + b.width_rate = size.width / window_size.width; + b.height_rate = size.height / window_size.height; + b.x_rate = position.x / window_size.width; + b.y_rate = position.y / window_size.height; + } + + if let Err(e) = webview.set_bounds(bounds) { + log::error!("failed to set webview size: {e}"); + } + } + WebviewMessage::SetSize(size) => match webview.bounds() { + Ok(mut bounds) => { + bounds.size = size; + + let scale_factor = window.scale_factor(); + let size = size.to_logical::(scale_factor); + + if let Some(b) = &mut *webview.bounds.lock().unwrap() { + let window_size = window.inner_size().to_logical::(scale_factor); + b.width_rate = size.width / window_size.width; + b.height_rate = size.height / window_size.height; + } + + if let Err(e) = webview.set_bounds(bounds) { + log::error!("failed to set webview size: {e}"); + } + } + Err(e) => { + log::error!("failed to get webview bounds: {e}"); + } + }, + WebviewMessage::SetPosition(position) => match webview.bounds() { + Ok(mut bounds) => { + bounds.position = position; + + let scale_factor = window.scale_factor(); + let position = position.to_logical::(scale_factor); + + if let Some(b) = &mut *webview.bounds.lock().unwrap() { + let window_size = window.inner_size().to_logical::(scale_factor); + b.x_rate = position.x / window_size.width; + b.y_rate = position.y / window_size.height; + } + + if let Err(e) = webview.set_bounds(bounds) { + log::error!("failed to set webview position: {e}"); + } + } + Err(e) => { + log::error!("failed to get webview bounds: {e}"); + } + }, + WebviewMessage::SetZoom(scale_factor) => { + if let Err(e) = webview.zoom(scale_factor) { + log::error!("failed to set webview zoom: {e}"); + } + } + WebviewMessage::SetBackgroundColor(color) => { + if let Err(e) = + webview.set_background_color(color.map(Into::into).unwrap_or((255, 255, 255, 255))) + { + log::error!("failed to set webview background color: {e}"); + } + } + WebviewMessage::ClearAllBrowsingData => { + if let Err(e) = webview.clear_all_browsing_data() { + log::error!("failed to clear webview browsing data: {e}"); + } + } + // Getters + WebviewMessage::Url(tx) => { + tx.send( + webview + .url() + .map(|u| u.parse().expect("invalid webview URL")) + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(); + } + + WebviewMessage::Cookies(tx) => { + tx.send(webview.cookies().map_err(|_| Error::FailedToSendMessage)) + .unwrap(); + } + + WebviewMessage::SetCookie(cookie) => { + if let Err(e) = webview.set_cookie(&cookie) { + log::error!("failed to set webview cookie: {e}"); + } + } + + WebviewMessage::DeleteCookie(cookie) => { + if let Err(e) = webview.delete_cookie(&cookie) { + log::error!("failed to delete webview cookie: {e}"); + } + } + + WebviewMessage::CookiesForUrl(url, tx) => { + let webview_cookies = webview + .cookies_for_url(url.as_str()) + .map_err(|_| Error::FailedToSendMessage); + tx.send(webview_cookies).unwrap(); + } + + WebviewMessage::Bounds(tx) => { + tx.send( + webview + .bounds() + .map(|bounds| tauri_runtime::dpi::Rect { + size: bounds.size, + position: bounds.position, + }) + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(); + } + WebviewMessage::Position(tx) => { + tx.send( + webview + .bounds() + .map(|bounds| bounds.position.to_physical(window.scale_factor())) + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(); + } + WebviewMessage::Size(tx) => { + tx.send( + webview + .bounds() + .map(|bounds| bounds.size.to_physical(window.scale_factor())) + .map_err(|_| Error::FailedToSendMessage), + ) + .unwrap(); + } + WebviewMessage::SetFocus => { + if let Err(e) = webview.focus() { + log::error!("failed to focus webview: {e}"); + } + } + WebviewMessage::SetAutoResize(auto_resize) => match webview.bounds() { + Ok(bounds) => { + let scale_factor = window.scale_factor(); + let window_size = window.inner_size().to_logical::(scale_factor); + *webview.bounds.lock().unwrap() = if auto_resize { + let size = bounds.size.to_logical::(scale_factor); + let position = bounds.position.to_logical::(scale_factor); + Some(WebviewBounds { + x_rate: position.x / window_size.width, + y_rate: position.y / window_size.height, + width_rate: size.width / window_size.width, + height_rate: size.height / window_size.height, + }) + } else { + None + }; + } + Err(e) => { + log::error!("failed to get webview bounds: {e}"); + } + }, + WebviewMessage::WithWebview(f) => { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + f(webview.webview()); + } + #[cfg(target_os = "macos")] + { + use wry::WebViewExtMacOS; + let platform_webview = webview.webview(); + let manager = webview.manager(); + let ns_window = webview.ns_window(); + f(Webview { + webview: Retained::as_ptr(&platform_webview).cast_mut() as *mut std::ffi::c_void, + manager: Retained::as_ptr(&manager).cast_mut() as *mut std::ffi::c_void, + ns_window: Retained::as_ptr(&ns_window).cast_mut() as *mut std::ffi::c_void, + }); + } + #[cfg(target_os = "ios")] + { + use wry::WebViewExtIOS; + let platform_webview = webview.inner.webview(); + let manager = webview.inner.manager(); + + f(Webview { + webview: Retained::as_ptr(&platform_webview).cast_mut() as *mut std::ffi::c_void, + manager: Retained::as_ptr(&manager).cast_mut() as *mut std::ffi::c_void, + view_controller: window.ui_view_controller(), + }); + } + #[cfg(windows)] + { + f(Webview { + controller: webview.controller(), + environment: webview.environment(), + }); + } + #[cfg(target_os = "android")] + { + f(webview.handle()) + } + } + #[cfg(any(debug_assertions, feature = "devtools"))] + WebviewMessage::OpenDevTools => { + webview.open_devtools(); + } + #[cfg(any(debug_assertions, feature = "devtools"))] + WebviewMessage::CloseDevTools => { + webview.close_devtools(); + } + #[cfg(any(debug_assertions, feature = "devtools"))] + WebviewMessage::IsDevToolsOpen(tx) => { + tx.send(webview.is_devtools_open()).unwrap(); + } + } + } + } + Message::CreateWebview(window_id, handler, sender) => { + let window = windows.0.borrow().get(&window_id).map(|w| { + ( + w.inner.clone(), + CreateWebviewOptions { + #[cfg(windows)] + focused_webview: w.focused_webview.clone(), + }, + ) + }); + if let Some((Some(window), options)) = window { + match handler(&window, options) { + Ok(webview) => { + if let Some(w) = windows.0.borrow_mut().get_mut(&window_id) { + w.webviews.push(webview); + w.has_children.store(true, Ordering::Relaxed); + } + // SAFETY: The caller calls blocking `rx.recv()` so the receiver will never be dropped before this + sender.send(Ok(())).unwrap(); + } + Err(e) => { + // SAFETY: The caller calls blocking `rx.recv()` so the receiver will never be dropped before this + sender.send(Err(e)).unwrap(); + } + } + } + } + Message::CreateWindow(window_id, handler, sender) => match handler(event_loop) { + Ok(webview) => { + windows.0.borrow_mut().insert(window_id, webview); + // SAFETY: The caller calls blocking `rx.recv()` so the receiver will never be dropped before this + sender.send(Ok(())).unwrap(); + } + Err(e) => { + // SAFETY: The caller calls blocking `rx.recv()` so the receiver will never be dropped before this + sender.send(Err(e)).unwrap(); + } + }, + Message::CreateRawWindow(window_id, handler, sender) => { + let (label, builder) = handler(); + + #[cfg(windows)] + let background_color = builder.window.background_color; + #[cfg(windows)] + let is_window_transparent = builder.window.transparent; + + if let Ok(window) = builder.build(event_loop) { + window_id_map.insert(window.id(), window_id); + + let window = Arc::new(window); + + #[cfg(windows)] + let surface = if is_window_transparent { + if let Ok(context) = softbuffer::Context::new(window.clone()) { + if let Ok(mut surface) = softbuffer::Surface::new(&context, window.clone()) { + window.draw_surface(&mut surface, background_color); + Some(surface) + } else { + None + } + } else { + None + } + } else { + None + }; + + windows.0.borrow_mut().insert( + window_id, + WindowWrapper { + label, + has_children: AtomicBool::new(false), + inner: Some(window.clone()), + window_event_listeners: Default::default(), + webviews: Vec::new(), + #[cfg(windows)] + background_color, + #[cfg(windows)] + is_window_transparent, + #[cfg(windows)] + surface, + #[cfg(windows)] + focused_webview: Default::default(), + }, + ); + sender.send(Ok(Arc::downgrade(&window))).unwrap(); + } else { + sender.send(Err(Error::CreateWindow)).unwrap(); + } + } + + Message::UserEvent(_) => (), + Message::EventLoopWindowTarget(message) => match message { + EventLoopWindowTargetMessage::CursorPosition(sender) => { + let pos = event_loop + .cursor_position() + .map_err(|_| Error::FailedToSendMessage); + sender.send(pos).unwrap(); + } + EventLoopWindowTargetMessage::PrimaryMonitor(sender) => { + sender + .send( + event_loop + .primary_monitor() + .map(|m| MonitorHandleWrapper(m).into()), + ) + .unwrap(); + } + EventLoopWindowTargetMessage::MonitorFromPoint(sender, (x, y)) => { + sender + .send( + event_loop + .monitor_from_point(x, y) + .map(|m| MonitorHandleWrapper(m).into()), + ) + .unwrap(); + } + EventLoopWindowTargetMessage::AvailableMonitors(sender) => { + sender + .send( + event_loop + .available_monitors() + .map(|m| MonitorHandleWrapper(m).into()) + .collect(), + ) + .unwrap(); + } + EventLoopWindowTargetMessage::SetTheme(theme) => { + event_loop.set_theme(to_tao_theme(theme)); + // On macOS tao caches each window's theme and only refreshes it from the + // system-wide appearance change notification, which the app-level + // `NSApp.setAppearance` call above never posts, so `Window::theme()` + // would keep reporting the previous value. tao's window-level setter + // does update the cache, so push the theme through it as well. + #[cfg(target_os = "macos")] + for window in windows.0.borrow().values() { + if let Some(inner) = &window.inner { + inner.set_theme(to_tao_theme(theme)); + } + } + } + EventLoopWindowTargetMessage::SetDeviceEventFilter(filter) => { + event_loop.set_device_event_filter(DeviceEventFilterWrapper::from(filter).0); + } + }, + } +} + +fn handle_event_loop( + event: Event<'_, Message>, + event_loop: &EventLoopWindowTarget>, + control_flow: &mut ControlFlow, + context: EventLoopIterationContext<'_, T>, +) { + let EventLoopIterationContext { + callback, + window_id_map, + windows, + #[cfg(feature = "tracing")] + active_tracing_spans, + } = context; + if *control_flow != ControlFlow::Exit { + *control_flow = ControlFlow::Wait; + } + + match event { + Event::NewEvents(StartCause::Init) => { + callback(RunEvent::Ready); + } + + Event::NewEvents(StartCause::Poll) => { + callback(RunEvent::Resumed); + } + + Event::MainEventsCleared => { + callback(RunEvent::MainEventsCleared); + } + + Event::LoopDestroyed => { + callback(RunEvent::Exit); + } + + #[cfg(windows)] + Event::RedrawRequested(id) => { + if let Some(window_id) = window_id_map.get(&id) { + let mut windows_ref = windows.0.borrow_mut(); + if let Some(window) = windows_ref.get_mut(&window_id) { + if window.is_window_transparent { + let background_color = window.background_color; + if let Some(surface) = &mut window.surface { + if let Some(window) = &window.inner { + window.draw_surface(surface, background_color); + } + } + } + } + } + } + + #[cfg(feature = "tracing")] + Event::RedrawEventsCleared => { + active_tracing_spans.remove_window_draw(); + } + + Event::UserEvent(Message::Webview( + window_id, + webview_id, + WebviewMessage::WebviewEvent(event), + )) => { + let windows_ref = windows.0.borrow(); + if let Some(window) = windows_ref.get(&window_id) { + if let Some(webview) = window.webviews.iter().find(|w| w.id == webview_id) { + let label = webview.label.clone(); + let webview_event_listeners = webview.webview_event_listeners.clone(); + + drop(windows_ref); + + callback(RunEvent::WebviewEvent { + label, + event: event.clone(), + }); + let listeners = webview_event_listeners.lock().unwrap(); + let handlers = listeners.values(); + for handler in handlers { + handler(&event); + } + } + } + } + + Event::UserEvent(Message::Webview( + window_id, + _webview_id, + WebviewMessage::SynthesizedWindowEvent(event), + )) => { + if let Some(event) = WindowEventWrapper::from(event).0 { + let windows_ref = windows.0.borrow(); + let window = windows_ref.get(&window_id); + if let Some(window) = window { + let label = window.label.clone(); + let window_event_listeners = window.window_event_listeners.clone(); + + drop(windows_ref); + + callback(RunEvent::WindowEvent { + label, + event: event.clone(), + }); + + let listeners = window_event_listeners.lock().unwrap(); + let handlers = listeners.values(); + for handler in handlers { + handler(&event); + } + } + } + } + + Event::WindowEvent { + event, window_id, .. + } => { + if let Some(window_id) = window_id_map.get(&window_id) { + { + let windows_ref = windows.0.borrow(); + if let Some(window) = windows_ref.get(&window_id) { + if let Some(event) = WindowEventWrapper::parse(window, &event).0 { + let label = window.label.clone(); + let window_event_listeners = window.window_event_listeners.clone(); + + drop(windows_ref); + + callback(RunEvent::WindowEvent { + label, + event: event.clone(), + }); + let listeners = window_event_listeners.lock().unwrap(); + let handlers = listeners.values(); + for handler in handlers { + handler(&event); + } + } + } + } + + match event { + #[cfg(windows)] + TaoWindowEvent::ThemeChanged(theme) => { + if let Some(window) = windows.0.borrow().get(&window_id) { + for webview in &window.webviews { + let theme = match theme { + TaoTheme::Dark => wry::Theme::Dark, + TaoTheme::Light => wry::Theme::Light, + _ => wry::Theme::Light, + }; + if let Err(e) = webview.set_theme(theme) { + log::error!("failed to set theme: {e}"); + } + } + } + } + TaoWindowEvent::CloseRequested => { + on_close_requested(callback, window_id, windows); + } + TaoWindowEvent::Destroyed => { + let removed = windows.0.borrow_mut().remove(&window_id).is_some(); + if removed { + let is_empty = windows.0.borrow().is_empty(); + if is_empty { + let (tx, rx) = channel(); + callback(RunEvent::ExitRequested { code: None, tx }); + + let recv = rx.try_recv(); + let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent)); + + if !should_prevent { + *control_flow = ControlFlow::Exit; + } + } + } + } + TaoWindowEvent::Resized(size) => { + if let Some((Some(window), webviews)) = windows + .0 + .borrow() + .get(&window_id) + .map(|w| (w.inner.clone(), w.webviews.clone())) + { + let size = size.to_logical::(window.scale_factor()); + for webview in webviews { + if let Some(b) = &*webview.bounds.lock().unwrap() { + if let Err(e) = webview.set_bounds(wry::Rect { + position: LogicalPosition::new(size.width * b.x_rate, size.height * b.y_rate) + .into(), + size: LogicalSize::new(size.width * b.width_rate, size.height * b.height_rate) + .into(), + }) { + log::error!("failed to autoresize webview: {e}"); + } + } + } + } + } + _ => {} + } + } + } + Event::UserEvent(message) => match message { + Message::RequestExit(code) => { + let (tx, rx) = channel(); + callback(RunEvent::ExitRequested { + code: Some(code), + tx, + }); + + let recv = rx.try_recv(); + let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent)); + + if !should_prevent { + *control_flow = ControlFlow::ExitWithCode(code); + } + } + Message::Window(id, WindowMessage::Close) => { + on_close_requested(callback, id, windows); + } + Message::Window(id, WindowMessage::Destroy) => { + on_window_close(id, windows); + } + Message::UserEvent(t) => callback(RunEvent::UserEvent(t)), + message => { + handle_user_message( + event_loop, + message, + UserMessageContext { + window_id_map, + windows, + }, + ); + } + }, + #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))] + Event::Opened { urls } => { + callback(RunEvent::Opened { urls }); + } + #[cfg(target_os = "macos")] + Event::Reopen { + has_visible_windows, + .. + } => callback(RunEvent::Reopen { + has_visible_windows, + }), + #[cfg(target_os = "ios")] + Event::SceneRequested { scene, options } => { + callback(RunEvent::SceneRequested { scene, options }); + } + _ => (), + } +} + +fn on_close_requested<'a, T: UserEvent>( + callback: &'a mut (dyn FnMut(RunEvent) + 'static), + window_id: WindowId, + windows: &WindowsStore, +) { + let (tx, rx) = channel(); + let windows_ref = windows.0.borrow(); + if let Some(w) = windows_ref.get(&window_id) { + let label = w.label.clone(); + let window_event_listeners = w.window_event_listeners.clone(); + + drop(windows_ref); + + let listeners = window_event_listeners.lock().unwrap(); + let handlers = listeners.values(); + for handler in handlers { + handler(&WindowEvent::CloseRequested { + signal_tx: tx.clone(), + }); + } + callback(RunEvent::WindowEvent { + label, + event: WindowEvent::CloseRequested { signal_tx: tx }, + }); + if let Ok(true) = rx.try_recv() { + } else { + on_window_close(window_id, windows); + } + } +} + +fn on_window_close(window_id: WindowId, windows: &WindowsStore) { + if let Some(window_wrapper) = windows.0.borrow_mut().get_mut(&window_id) { + window_wrapper.inner = None; + #[cfg(windows)] + window_wrapper.surface.take(); + } +} + +fn parse_proxy_url(url: &Url) -> Result { + let host = url.host().map(|h| h.to_string()).unwrap_or_default(); + let port = url.port().map(|p| p.to_string()).unwrap_or_default(); + + if url.scheme() == "http" { + let config = ProxyConfig::Http(ProxyEndpoint { host, port }); + + Ok(config) + } else if url.scheme() == "socks5" { + let config = ProxyConfig::Socks5(ProxyEndpoint { host, port }); + + Ok(config) + } else { + Err(Error::InvalidProxyUrl) + } +} + +fn create_window( + window_id: WindowId, + webview_id: u32, + event_loop: &EventLoopWindowTarget>, + context: &Context, + pending: PendingWindow>, + after_window_creation: Option, +) -> Result { + #[allow(unused_mut)] + let PendingWindow { + mut window_builder, + label, + webview, + } = pending; + + #[cfg(feature = "tracing")] + let _webview_create_span = tracing::debug_span!("wry::webview::create").entered(); + #[cfg(feature = "tracing")] + let window_draw_span = tracing::debug_span!("wry::window::draw").entered(); + #[cfg(feature = "tracing")] + let window_create_span = + tracing::debug_span!(parent: &window_draw_span, "wry::window::create").entered(); + + let window_event_listeners = WindowEventListeners::default(); + + #[cfg(windows)] + let background_color = window_builder.inner.window.background_color; + #[cfg(windows)] + let is_window_transparent = window_builder.inner.window.transparent; + + #[cfg(target_os = "macos")] + { + if window_builder.tabbing_identifier.is_none() + || window_builder.inner.window.transparent + || !window_builder.inner.window.decorations + { + window_builder.inner = window_builder.inner.with_automatic_window_tabbing(false); + } + } + + #[cfg(desktop)] + if window_builder.prevent_overflow.is_some() || window_builder.center { + let monitor = if let Some(window_position) = &window_builder.inner.window.position { + find_monitor_for_position(event_loop.available_monitors(), *window_position) + } else { + event_loop.primary_monitor() + }; + if let Some(monitor) = monitor { + let scale_factor = monitor.scale_factor(); + let desired_size = window_builder + .inner + .window + .inner_size + .unwrap_or_else(|| PhysicalSize::new(800, 600).into()); + let mut inner_size = window_builder + .inner + .window + .inner_size_constraints + .clamp(desired_size, scale_factor) + .to_physical::(scale_factor); + let mut window_size = inner_size; + #[allow(unused_mut)] + // Left and right window shadow counts as part of the window on Windows + // We need to include it when calculating positions, but not size + let mut shadow_width = 0; + #[cfg(windows)] + if window_builder.inner.window.decorations { + use windows::Win32::UI::WindowsAndMessaging::{AdjustWindowRect, WS_OVERLAPPEDWINDOW}; + let mut rect = windows::Win32::Foundation::RECT::default(); + let result = unsafe { AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false) }; + if result.is_ok() { + shadow_width = (rect.right - rect.left) as u32; + // rect.bottom is made out of shadow, and we don't care about it + window_size.height += -rect.top as u32; + } + } + + if let Some(margin) = window_builder.prevent_overflow { + let work_area = monitor.work_area(); + let margin = margin.to_physical::(scale_factor); + let constraint = PhysicalSize::new( + work_area.size.width - margin.width, + work_area.size.height - margin.height, + ); + if window_size.width > constraint.width || window_size.height > constraint.height { + if window_size.width > constraint.width { + inner_size.width = inner_size + .width + .saturating_sub(window_size.width - constraint.width); + window_size.width = constraint.width; + } + if window_size.height > constraint.height { + inner_size.height = inner_size + .height + .saturating_sub(window_size.height - constraint.height); + window_size.height = constraint.height; + } + window_builder.inner.window.inner_size = Some(inner_size.into()); + } + } + + if window_builder.center { + window_size.width += shadow_width; + let position = window::calculate_window_center_position(window_size, monitor); + let logical_position = position.to_logical::(scale_factor); + window_builder = window_builder.position(logical_position.x, logical_position.y); + } + } + }; + + #[cfg(any(target_os = "macos", target_os = "linux"))] + let (initial_position, is_fullscreen) = ( + window_builder.inner.window.position, + window_builder.inner.window.fullscreen.is_some(), + ); + + // If fullscreen is requested with an explicit position, resolve the target + // monitor up front so the window is created fullscreen on that display. + #[cfg(any(target_os = "macos", target_os = "linux"))] + if let (true, Some(position)) = (is_fullscreen, initial_position) { + if let Some(target_monitor) = + find_monitor_for_position(event_loop.available_monitors(), position) + { + window_builder.inner.window.fullscreen = Some(Fullscreen::Borderless(Some(target_monitor))); + } + } + + let window = window_builder + .inner + .build(event_loop) + .inspect_err(|e| log::error!("Error creating window: {e:?}")) + .map_err(|_| Error::CreateWindow)?; + + // On macOS, `with_position` uses the content origin; the title bar is added + // above it. `set_outer_position` is needed for precise window placement. + #[cfg(target_os = "macos")] + if !is_fullscreen { + if let Some(position) = initial_position { + window.set_outer_position(position); + } + } + + #[cfg(feature = "tracing")] + { + drop(window_create_span); + + context + .main_thread + .active_tracing_spans + .0 + .borrow_mut() + .push(ActiveTracingSpan::WindowDraw { + id: window.id(), + span: window_draw_span, + }); + } + + context.window_id_map.insert(window.id(), window_id); + + if let Some(handler) = after_window_creation { + let raw = RawWindow { + #[cfg(windows)] + hwnd: window.hwnd(), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + gtk_window: window.gtk_window(), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + default_vbox: window.default_vbox(), + _marker: &std::marker::PhantomData, + }; + handler(raw); + } + + let mut webviews = Vec::new(); + + #[cfg(windows)] + let focused_webview = Arc::new(Mutex::new(FocusState::default())); + + #[cfg(feature = "unstable")] + let has_children = webview.is_some(); + #[cfg(not(feature = "unstable"))] + let has_children = false; + + if let Some(webview) = webview { + webviews.push(create_webview( + #[cfg(feature = "unstable")] + WebviewKind::WindowChild, + #[cfg(not(feature = "unstable"))] + WebviewKind::WindowContent, + &window, + Arc::new(Mutex::new(window_id)), + webview_id, + context, + webview, + #[cfg(windows)] + focused_webview.clone(), + )?); + } + + let window = Arc::new(window); + + #[cfg(windows)] + let surface = if is_window_transparent { + if let Ok(context) = softbuffer::Context::new(window.clone()) { + if let Ok(mut surface) = softbuffer::Surface::new(&context, window.clone()) { + window.draw_surface(&mut surface, background_color); + Some(surface) + } else { + None + } + } else { + None + } + } else { + None + }; + + Ok(WindowWrapper { + label, + has_children: AtomicBool::new(has_children), + inner: Some(window), + webviews, + window_event_listeners, + #[cfg(windows)] + background_color, + #[cfg(windows)] + is_window_transparent, + #[cfg(windows)] + surface, + #[cfg(windows)] + focused_webview, + }) +} + +/// the kind of the webview +#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +enum WebviewKind { + /// webview is the entire window content + WindowContent, + /// webview is a child of the window, which can contain other webviews too + WindowChild, +} + +#[derive(Debug, Clone)] +struct WebviewBounds { + x_rate: f32, + y_rate: f32, + width_rate: f32, + height_rate: f32, +} + +fn create_webview( + kind: WebviewKind, + window: &Window, + window_id: Arc>, + id: WebviewId, + context: &Context, + pending: PendingWebview>, + #[cfg(windows)] focused_webview: Arc>, +) -> Result { + if !context.webview_runtime_installed { + #[cfg(all(not(debug_assertions), windows))] + dialog::error( + r#"Could not find the WebView2 Runtime. + +Make sure it is installed or download it from https://developer.microsoft.com/en-us/microsoft-edge/webview2 + +You may have it installed on another user account, but it is not available for this one. +"#, + ); + + if cfg!(target_os = "macos") { + log::warn!("WebKit webview runtime not found, attempting to create webview anyway."); + } else { + return Err(Error::WebviewRuntimeNotInstalled); + } + } + + #[allow(unused_mut)] + let PendingWebview { + webview_attributes, + uri_scheme_protocols, + label, + ipc_handler, + url, + .. + } = pending; + + let mut web_context = context + .main_thread + .web_context + .lock() + .expect("poisoned WebContext store"); + let is_first_context = web_context.is_empty(); + // the context must be stored on the HashMap because it must outlive the WebView on macOS + let automation_enabled = std::env::var("TAURI_WEBVIEW_AUTOMATION").as_deref() == Ok("true"); + let web_context_key = webview_attributes.data_directory; + let entry = web_context.entry(web_context_key.clone()); + let web_context = match entry { + Occupied(occupied) => { + let occupied = occupied.into_mut(); + occupied.referenced_by_webviews.insert(label.clone()); + occupied + } + Vacant(vacant) => { + let mut web_context = WryWebContext::new(web_context_key.clone()); + web_context.set_allows_automation(if automation_enabled { + is_first_context + } else { + false + }); + vacant.insert(WebContext { + inner: web_context, + referenced_by_webviews: [label.clone()].into(), + registered_custom_protocols: HashSet::new(), + }) + } + }; + + let mut webview_builder = WebViewBuilder::new_with_web_context(&mut web_context.inner) + .with_id(&label) + .with_focused(webview_attributes.focus) + .with_transparent(webview_attributes.transparent) + .with_accept_first_mouse(webview_attributes.accept_first_mouse) + .with_incognito(webview_attributes.incognito) + .with_clipboard(webview_attributes.clipboard) + .with_hotkeys_zoom(webview_attributes.zoom_hotkeys_enabled) + .with_back_forward_navigation_gestures(label.starts_with("browser-")) + .with_general_autofill_enabled(webview_attributes.general_autofill_enabled); + + if url != "about:blank" { + webview_builder = webview_builder.with_url(&url); + } + + #[cfg(target_os = "macos")] + if let Some(webview_configuration) = webview_attributes.webview_configuration { + webview_builder = webview_builder.with_webview_configuration(webview_configuration); + } + + #[cfg(any(target_os = "windows", target_os = "android"))] + { + webview_builder = webview_builder.with_https_scheme(webview_attributes.use_https_scheme); + } + + if let Some(background_throttling) = webview_attributes.background_throttling { + webview_builder = webview_builder.with_background_throttling(match background_throttling { + tauri_utils::config::BackgroundThrottlingPolicy::Disabled => { + wry::BackgroundThrottlingPolicy::Disabled + } + tauri_utils::config::BackgroundThrottlingPolicy::Suspend => { + wry::BackgroundThrottlingPolicy::Suspend + } + tauri_utils::config::BackgroundThrottlingPolicy::Throttle => { + wry::BackgroundThrottlingPolicy::Throttle + } + }); + } + + if webview_attributes.javascript_disabled { + webview_builder = webview_builder.with_javascript_disabled(); + } + + if let Some(color) = webview_attributes.background_color { + webview_builder = webview_builder.with_background_color(color.into()); + } + + if webview_attributes.drag_drop_handler_enabled { + let proxy = context.proxy.clone(); + let window_id_ = window_id.clone(); + webview_builder = webview_builder.with_drag_drop_handler(move |event| { + let event = match event { + WryDragDropEvent::Enter { + paths, + position: (x, y), + } => DragDropEvent::Enter { + paths, + position: PhysicalPosition::new(x as _, y as _), + }, + WryDragDropEvent::Over { position: (x, y) } => DragDropEvent::Over { + position: PhysicalPosition::new(x as _, y as _), + }, + WryDragDropEvent::Drop { + paths, + position: (x, y), + } => DragDropEvent::Drop { + paths, + position: PhysicalPosition::new(x as _, y as _), + }, + WryDragDropEvent::Leave => DragDropEvent::Leave, + _ => unimplemented!(), + }; + + let message = if kind == WebviewKind::WindowContent { + WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::DragDrop(event)) + } else { + WebviewMessage::WebviewEvent(WebviewEvent::DragDrop(event)) + }; + + let _ = proxy.send_event(Message::Webview(*window_id_.lock().unwrap(), id, message)); + true + }); + } + + if let Some(navigation_handler) = pending.navigation_handler { + webview_builder = webview_builder.with_navigation_handler(move |url| { + url + .parse() + .map(|url| navigation_handler(&url)) + .unwrap_or(true) + }); + } + + if let Some(new_window_handler) = pending.new_window_handler { + #[cfg(desktop)] + let context = context.clone(); + webview_builder = webview_builder.with_new_window_req_handler(move |url, features| { + let Ok(url) = url.parse() else { + return wry::NewWindowResponse::Deny; + }; + let response = new_window_handler( + url, + tauri_runtime::webview::NewWindowFeatures::new( + features.size, + features.position, + tauri_runtime::webview::NewWindowOpener { + #[cfg(desktop)] + webview: features.opener.webview, + #[cfg(windows)] + environment: features.opener.environment, + #[cfg(target_os = "macos")] + target_configuration: features.opener.target_configuration, + }, + ), + ); + match response { + tauri_runtime::webview::NewWindowResponse::Allow => wry::NewWindowResponse::Allow, + #[cfg(desktop)] + tauri_runtime::webview::NewWindowResponse::Create { window_id } => { + let windows = &context.main_thread.windows.0; + let webview = windows + .borrow() + .get(&window_id) + .unwrap() + .webviews + .first() + .unwrap() + .clone(); + + #[cfg(desktop)] + wry::NewWindowResponse::Create { + #[cfg(target_os = "macos")] + webview: wry::WebViewExtMacOS::webview(&*webview).as_super().into(), + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + webview: webview.webview(), + #[cfg(windows)] + webview: webview.webview(), + } + } + tauri_runtime::webview::NewWindowResponse::Deny => wry::NewWindowResponse::Deny, + } + }); + } + + if let Some(document_title_changed_handler) = pending.document_title_changed_handler { + webview_builder = + webview_builder.with_document_title_changed_handler(document_title_changed_handler) + } + + if let Some(permission_request_handler) = pending.permission_request_handler { + webview_builder = webview_builder.with_permission_handler(move |kind| { + let kind = webview_permissions::from_wry_permission_kind(kind); + let response = permission_request_handler(kind); + webview_permissions::to_wry_permission_response(response) + }); + } + + let webview_bounds = if let Some(bounds) = webview_attributes.bounds { + let bounds: RectWrapper = bounds.into(); + let bounds = bounds.0; + + let scale_factor = window.scale_factor(); + let position = bounds.position.to_logical::(scale_factor); + let size = bounds.size.to_logical::(scale_factor); + + webview_builder = webview_builder.with_bounds(bounds); + + let window_size = window.inner_size().to_logical::(scale_factor); + + if webview_attributes.auto_resize { + Some(WebviewBounds { + x_rate: position.x / window_size.width, + y_rate: position.y / window_size.height, + width_rate: size.width / window_size.width, + height_rate: size.height / window_size.height, + }) + } else { + None + } + } else { + #[cfg(feature = "unstable")] + { + webview_builder = webview_builder.with_bounds(wry::Rect { + position: LogicalPosition::new(0, 0).into(), + size: window.inner_size().into(), + }); + Some(WebviewBounds { + x_rate: 0., + y_rate: 0., + width_rate: 1., + height_rate: 1., + }) + } + #[cfg(not(feature = "unstable"))] + None + }; + + if let Some(download_handler) = pending.download_handler { + let download_handler_ = download_handler.clone(); + webview_builder = webview_builder.with_download_started_handler(move |url, path| { + if let Ok(url) = url.parse() { + download_handler_(DownloadEvent::Requested { + url, + destination: path, + }) + } else { + false + } + }); + webview_builder = webview_builder.with_download_completed_handler(move |url, path, success| { + if let Ok(url) = url.parse() { + download_handler(DownloadEvent::Finished { url, path, success }); + } + }); + } + + if let Some(page_load_handler) = pending.on_page_load_handler { + webview_builder = webview_builder.with_on_page_load_handler(move |event, url| { + if let Ok(url) = url.parse() { + page_load_handler( + url, + match event { + wry::PageLoadEvent::Started => tauri_runtime::webview::PageLoadEvent::Started, + wry::PageLoadEvent::Finished => tauri_runtime::webview::PageLoadEvent::Finished, + }, + ) + }; + }); + } + + if let Some(user_agent) = webview_attributes.user_agent { + webview_builder = webview_builder.with_user_agent(&user_agent); + } + + if let Some(proxy_url) = webview_attributes.proxy_url { + let config = parse_proxy_url(&proxy_url)?; + + webview_builder = webview_builder.with_proxy_config(config); + } + + #[cfg(windows)] + { + if let Some(additional_browser_args) = webview_attributes.additional_browser_args { + webview_builder = webview_builder.with_additional_browser_args(&additional_browser_args); + } + + if let Some(environment) = webview_attributes.environment { + webview_builder = webview_builder.with_environment(environment); + } + + webview_builder = webview_builder.with_theme(match window.theme() { + TaoTheme::Dark => wry::Theme::Dark, + TaoTheme::Light => wry::Theme::Light, + _ => wry::Theme::Light, + }); + + webview_builder = + webview_builder.with_scroll_bar_style(match webview_attributes.scroll_bar_style { + ScrollBarStyle::Default => WryScrollBarStyle::Default, + ScrollBarStyle::FluentOverlay => WryScrollBarStyle::FluentOverlay, + _ => unreachable!(), + }); + } + + #[cfg(windows)] + { + webview_builder = webview_builder + .with_browser_extensions_enabled(webview_attributes.browser_extensions_enabled); + } + + #[cfg(any( + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + if let Some(path) = &webview_attributes.extensions_path { + webview_builder = webview_builder.with_extensions_path(path); + } + } + + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + if let Some(related_view) = webview_attributes.related_view { + webview_builder = webview_builder.with_related_view(related_view); + } + } + + #[cfg(any(target_os = "macos", target_os = "ios"))] + { + if let Some(data_store_identifier) = &webview_attributes.data_store_identifier { + webview_builder = webview_builder.with_data_store_identifier(*data_store_identifier); + } + + webview_builder = + webview_builder.with_allow_link_preview(webview_attributes.allow_link_preview); + + if let Some(on_web_content_process_terminate_handler) = + pending.on_web_content_process_terminate_handler + { + webview_builder = webview_builder + .with_on_web_content_process_terminate_handler(on_web_content_process_terminate_handler); + } else { + log::debug!("web content process terminated"); + let context_ = context.clone(); + let window_id_ = window_id.clone(); + webview_builder = webview_builder.with_on_web_content_process_terminate_handler(move || { + if let Ok(windows) = &context_.main_thread.windows.0.try_borrow() { + if let Some(window) = windows.get(&*window_id_.lock().unwrap()) { + if let Some(webview) = window.webviews.iter().find(|w| w.id == id) { + match webview.reload() { + Ok(_) => log::debug!("webview reloaded"), + Err(e) => log::error!("failed to reload webview: {e}"), + } + } else { + log::error!("failed to find webview") + } + } else { + log::error!("failed to get window") + } + } else { + log::error!("failed to borrow windows") + } + }); + } + } + + #[cfg(target_os = "ios")] + { + webview_builder = webview_builder.with_limit_navigations_to_app_bound_domains( + webview_attributes.limit_navigations_to_app_bound_domains, + ); + + if let Some(input_accessory_view_builder) = webview_attributes.input_accessory_view_builder { + webview_builder = webview_builder + .with_input_accessory_view_builder(move |webview| input_accessory_view_builder.0(webview)); + } + } + + #[cfg(target_os = "macos")] + { + if let Some(position) = &webview_attributes.traffic_light_position { + webview_builder = webview_builder.with_traffic_light_inset(*position); + } + } + + #[cfg(windows)] + let window_id_for_ipc = window_id.clone(); + #[cfg(not(windows))] + let window_id_for_ipc = window_id; + let browser_guest = label.starts_with("browser-"); + if !browser_guest { + webview_builder = webview_builder.with_ipc_handler(create_ipc_handler( + window_id_for_ipc, + id, + context.clone(), + label.clone(), + ipc_handler, + )); + for script in webview_attributes.initialization_scripts { + webview_builder = webview_builder + .with_initialization_script_for_main_only(script.script, script.for_main_frame_only); + } + } + + for (scheme, protocol) in uri_scheme_protocols { + // Preview documents retain their browser globals (not app plugin overrides) + // and carry neither the application IPC bridge nor app resource protocols. + if browser_guest { + continue; + } + // on Linux the custom protocols are associated with the web context + // and you cannot register a scheme more than once + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + if web_context.registered_custom_protocols.contains(&scheme) { + continue; + } + + web_context + .registered_custom_protocols + .insert(scheme.clone()); + } + + webview_builder = webview_builder.with_asynchronous_custom_protocol( + scheme, + move |webview_id, request, responder| { + protocol( + webview_id, + request, + Box::new(move |response| responder.respond(response)), + ) + }, + ); + } + + #[cfg(any(debug_assertions, feature = "devtools"))] + { + webview_builder = webview_builder.with_devtools(webview_attributes.devtools.unwrap_or(true)); + } + + #[cfg(target_os = "android")] + { + if let Some(on_webview_created) = pending.on_webview_created { + webview_builder = webview_builder.on_webview_created(move |ctx| { + on_webview_created(tauri_runtime::webview::CreationContext { + env: ctx.env, + activity: ctx.activity, + webview: ctx.webview, + }) + }); + } + } + + let webview = match kind { + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + WebviewKind::WindowChild => { + let vbox = window.default_vbox().unwrap(); + let (_, children) = gtk_child_layout::containers(vbox); + webview_builder.build_gtk(&children) + } + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + WebviewKind::WindowChild => webview_builder.build_as_child(&window), + WebviewKind::WindowContent => { + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let builder = webview_builder.build(&window); + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let builder = { + let vbox = window.default_vbox().unwrap(); + let content = gtk_child_layout::content(vbox); + webview_builder.build_gtk(&content) + }; + builder + } + } + .map_err(|e| Error::CreateWebview(Box::new(e)))?; + + if kind == WebviewKind::WindowContent { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + undecorated_resizing::attach_resize_handler(&webview); + #[cfg(windows)] + if window.is_resizable() && !window.is_decorated() { + undecorated_resizing::attach_resize_handler(window.hwnd(), window.has_undecorated_shadow()); + } + } + + #[cfg(windows)] + { + let controller = webview.controller(); + let mut token = 0; + + add_focus_change_listeners( + window_id.clone(), + id, + context.proxy.clone(), + focused_webview, + label.clone(), + &controller, + &mut token, + ); + + if let Ok(webview) = unsafe { controller.CoreWebView2() } { + let proxy_clone = context.proxy.clone(); + unsafe { + let _ = webview.add_ContainsFullScreenElementChanged( + &ContainsFullScreenElementChangedEventHandler::create(Box::new(move |sender, _| { + let mut contains_fullscreen_element = windows::core::BOOL::default(); + sender + .ok_or_else(windows::core::Error::empty)? + .ContainsFullScreenElement(&mut contains_fullscreen_element)?; + let _ = proxy_clone.send_event(Message::Window( + *window_id.lock().unwrap(), + WindowMessage::SetFullscreen(contains_fullscreen_element.as_bool()), + )); + Ok(()) + })), + &mut token, + ); + } + } + } + + Ok(WebviewWrapper { + label, + id, + inner: Rc::new(webview), + context_store: context.main_thread.web_context.clone(), + webview_event_listeners: Default::default(), + context_key: if automation_enabled { + None + } else { + web_context_key + }, + bounds: Arc::new(Mutex::new(webview_bounds)), + }) +} + +/// Create a wry ipc handler from a tauri ipc handler. +fn create_ipc_handler( + window_id: Arc>, + webview_id: WebviewId, + context: Context, + label: String, + ipc_handler: Option>>, +) -> Box { + Box::new(move |request| { + if let Some(handler) = &ipc_handler { + handler( + DetachedWebview { + label: label.clone(), + dispatcher: WryWebviewDispatcher { + window_id: window_id.clone(), + webview_id, + context: context.clone(), + }, + }, + request, + ); + } + }) +} + +#[cfg(target_os = "macos")] +fn inner_size( + window: &Window, + webviews: &[WebviewWrapper], + has_children: bool, +) -> PhysicalSize { + if !has_children && !webviews.is_empty() { + use wry::WebViewExtMacOS; + let webview = webviews.first().unwrap(); + let view = unsafe { Retained::cast_unchecked::(webview.webview()) }; + let view_frame = view.frame(); + let logical: LogicalSize = (view_frame.size.width, view_frame.size.height).into(); + return logical.to_physical(window.scale_factor()); + } + + window.inner_size() +} + +#[cfg(not(target_os = "macos"))] +#[allow(unused_variables)] +fn inner_size( + window: &Window, + webviews: &[WebviewWrapper], + has_children: bool, +) -> PhysicalSize { + window.inner_size() +} + +fn to_tao_theme(theme: Option) -> Option { + match theme { + Some(Theme::Light) => Some(TaoTheme::Light), + Some(Theme::Dark) => Some(TaoTheme::Dark), + _ => None, + } +} + +/// Used to prevent duplicated [`WindowEvent::Focused`] events, +/// and to track last focused webview in multi-webview mode for us to restore webview focuses +#[cfg(windows)] +fn add_focus_change_listeners( + window_id: Arc>, + id: u32, + proxy: TaoEventLoopProxy>, + focused_webview: Arc>, + label: String, + controller: &ICoreWebView2Controller, + token: &mut i64, +) { + let label_ = label.clone(); + let window_id_ = window_id.clone(); + let proxy_clone = proxy.clone(); + let focused_webview_ = focused_webview.clone(); + if let Err(error) = unsafe { + controller.add_GotFocus( + &FocusChangedEventHandler::create(Box::new(move |_, _| { + let mut focused_webview = focused_webview_.lock().unwrap(); + // when using multiwebview mode, we should check if the focus change is actually a "webview focus change" + // instead of a window focus change (here we're patching window events, so we only care about the actual window changing focus) + let already_focused = matches!( + *focused_webview, + FocusState::WindowFocused | FocusState::WebviewFocused { .. } + ); + *focused_webview = FocusState::WebviewFocused { + webview_label: label_.clone(), + }; + + if !already_focused { + let _ = proxy_clone.send_event(Message::Webview( + *window_id_.lock().unwrap(), + id, + WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::Focused(true)), + )); + } + Ok(()) + })), + token, + ) + } { + log::error!( + "Failed to attach WebView2 `add_GotFocus` handler, `WindowEvent::Focused` will not be sent: {error}" + ); + return; + } + + if let Err(error) = unsafe { + controller.add_LostFocus( + &FocusChangedEventHandler::create(Box::new(move |_, _| { + let mut focused_webview = focused_webview.lock().unwrap(); + // when using multiwebview mode, we should handle webview focus changes + // so we check is the currently focused webview matches this webview's + // (in this case, it means we lost the window focus) + // + // on multiwebview mode if we change focus to a different webview + // we get the gotFocus event of the other webview before the lostFocus + // so this check makes sense + if let FocusState::WebviewFocused { ref webview_label } = *focused_webview { + let lost_window_focus = webview_label == &label; + if lost_window_focus { + // only reset when we lost window focus - otherwise some other webview is focused + *focused_webview = FocusState::Blured { + last_focused_webview_label: Some(label.clone()), + }; + let _ = proxy.send_event(Message::Webview( + *window_id.lock().unwrap(), + id, + WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::Focused(false)), + )); + } + } + + Ok(()) + })), + token, + ) + } { + log::error!( + "Failed to attach WebView2 `add_LostFocus` handler, `WindowEvent::Focused` will not be sent: {error}" + ); + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/linux.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/linux.rs new file mode 100644 index 0000000000..62f87eb05c --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/linux.rs @@ -0,0 +1,18 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use gtk::prelude::MonitorExt; +use tao::platform::unix::MonitorHandleExtUnix; +use tauri_runtime::dpi::{LogicalPosition, LogicalSize, PhysicalRect}; + +impl super::MonitorExt for tao::monitor::MonitorHandle { + fn work_area(&self) -> PhysicalRect { + let rect = self.gdk_monitor().workarea(); + let scale_factor = self.scale_factor(); + PhysicalRect { + size: LogicalSize::new(rect.width() as u32, rect.height() as u32).to_physical(scale_factor), + position: LogicalPosition::new(rect.x(), rect.y()).to_physical(scale_factor), + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/macos.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/macos.rs new file mode 100644 index 0000000000..aca8e334d0 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/macos.rs @@ -0,0 +1,36 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tauri_runtime::dpi::{LogicalSize, PhysicalRect}; + +impl super::MonitorExt for tao::monitor::MonitorHandle { + fn work_area(&self) -> PhysicalRect { + use objc2_app_kit::NSScreen; + use tao::platform::macos::MonitorHandleExtMacOS; + if let Some(ns_screen) = self.ns_screen() { + let ns_screen: &NSScreen = unsafe { &*ns_screen.cast() }; + let screen_frame = ns_screen.frame(); + let visible_frame = ns_screen.visibleFrame(); + + let scale_factor = self.scale_factor(); + + let mut position = self.position().to_logical::(scale_factor); + + position.x += visible_frame.origin.x - screen_frame.origin.x; + + position.y += (screen_frame.origin.y + screen_frame.size.height) + - (visible_frame.origin.y + visible_frame.size.height); + PhysicalRect { + size: LogicalSize::new(visible_frame.size.width, visible_frame.size.height) + .to_physical(scale_factor), + position: position.to_physical(scale_factor), + } + } else { + PhysicalRect { + size: self.size(), + position: self.position(), + } + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/mod.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/mod.rs new file mode 100644 index 0000000000..4322c3cadb --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/mod.rs @@ -0,0 +1,37 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tauri_runtime::dpi::PhysicalRect; + +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(windows)] +mod windows; + +pub trait MonitorExt { + /// Get the work area of this monitor + /// + /// ## Platform-specific: + /// + /// - **Android / iOS**: Unsupported. + fn work_area(&self) -> PhysicalRect; +} + +#[cfg(mobile)] +impl MonitorExt for tao::monitor::MonitorHandle { + fn work_area(&self) -> PhysicalRect { + PhysicalRect { + size: self.size(), + position: self.position(), + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/windows.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/windows.rs new file mode 100644 index 0000000000..8547ac9ddf --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/monitor/windows.rs @@ -0,0 +1,32 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::dpi::{PhysicalPosition, PhysicalSize}; +use tauri_runtime::dpi::PhysicalRect; + +impl super::MonitorExt for tao::monitor::MonitorHandle { + fn work_area(&self) -> PhysicalRect { + use tao::platform::windows::MonitorHandleExtWindows; + use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, HMONITOR, MONITORINFO}; + let mut monitor_info = MONITORINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let status = unsafe { GetMonitorInfoW(HMONITOR(self.hmonitor() as _), &mut monitor_info) }; + if status.as_bool() { + PhysicalRect { + size: PhysicalSize::new( + (monitor_info.rcWork.right - monitor_info.rcWork.left) as u32, + (monitor_info.rcWork.bottom - monitor_info.rcWork.top) as u32, + ), + position: PhysicalPosition::new(monitor_info.rcWork.left, monitor_info.rcWork.top), + } + } else { + PhysicalRect { + size: self.size(), + position: self.position(), + } + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/undecorated_resizing.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/undecorated_resizing.rs new file mode 100644 index 0000000000..f5aa8b5a9d --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/undecorated_resizing.rs @@ -0,0 +1,659 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +#![cfg(any( + windows, + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] + +const CLIENT: isize = 0b0000; +const LEFT: isize = 0b0001; +const RIGHT: isize = 0b0010; +const TOP: isize = 0b0100; +const BOTTOM: isize = 0b1000; +const TOPLEFT: isize = TOP | LEFT; +const TOPRIGHT: isize = TOP | RIGHT; +const BOTTOMLEFT: isize = BOTTOM | LEFT; +const BOTTOMRIGHT: isize = BOTTOM | RIGHT; + +#[cfg(not(windows))] +pub use self::gtk::*; +#[cfg(windows)] +pub use self::windows::*; + +#[cfg(windows)] +type WindowPositions = i32; +#[cfg(not(windows))] +type WindowPositions = f64; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum HitTestResult { + Client, + Left, + Right, + Top, + Bottom, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + NoWhere, +} + +#[allow(clippy::too_many_arguments)] +fn hit_test( + left: WindowPositions, + top: WindowPositions, + right: WindowPositions, + bottom: WindowPositions, + cx: WindowPositions, + cy: WindowPositions, + border_x: WindowPositions, + border_y: WindowPositions, +) -> HitTestResult { + #[rustfmt::skip] + let result = (LEFT * (cx < left + border_x) as isize) + | (RIGHT * (cx >= right - border_x) as isize) + | (TOP * (cy < top + border_y) as isize) + | (BOTTOM * (cy >= bottom - border_y) as isize); + + match result { + CLIENT => HitTestResult::Client, + LEFT => HitTestResult::Left, + RIGHT => HitTestResult::Right, + TOP => HitTestResult::Top, + BOTTOM => HitTestResult::Bottom, + TOPLEFT => HitTestResult::TopLeft, + TOPRIGHT => HitTestResult::TopRight, + BOTTOMLEFT => HitTestResult::BottomLeft, + BOTTOMRIGHT => HitTestResult::BottomRight, + _ => HitTestResult::NoWhere, + } +} + +#[cfg(windows)] +mod windows { + use crate::util; + + use super::{HitTestResult, hit_test}; + + use windows::Win32::System::LibraryLoader::*; + use windows::Win32::UI::WindowsAndMessaging::*; + use windows::Win32::{Foundation::*, UI::Shell::SetWindowSubclass}; + use windows::Win32::{Graphics::Gdi::*, UI::Shell::DefSubclassProc}; + use windows::core::*; + + impl HitTestResult { + fn to_win32(self) -> i32 { + match self { + HitTestResult::Left => HTLEFT as _, + HitTestResult::Right => HTRIGHT as _, + HitTestResult::Top => HTTOP as _, + HitTestResult::Bottom => HTBOTTOM as _, + HitTestResult::TopLeft => HTTOPLEFT as _, + HitTestResult::TopRight => HTTOPRIGHT as _, + HitTestResult::BottomLeft => HTBOTTOMLEFT as _, + HitTestResult::BottomRight => HTBOTTOMRIGHT as _, + _ => HTTRANSPARENT, + } + } + } + + const CLASS_NAME: PCWSTR = w!("TAURI_DRAG_RESIZE_BORDERS"); + const WINDOW_NAME: PCWSTR = w!("TAURI_DRAG_RESIZE_WINDOW"); + + const WM_UPDATE_UNDECORATED_SHADOWS: u32 = WM_USER + 100; + + struct UndecoratedResizingData { + child: HWND, + has_undecorated_shadows: bool, + } + + pub fn attach_resize_handler(hwnd: isize, has_undecorated_shadows: bool) { + let parent = HWND(hwnd as _); + + // return early if we already attached + if unsafe { FindWindowExW(Some(parent), None, CLASS_NAME, WINDOW_NAME) }.is_ok() { + return; + } + + let class = WNDCLASSEXW { + cbSize: std::mem::size_of::() as u32, + style: WNDCLASS_STYLES::default(), + lpfnWndProc: Some(drag_resize_window_proc), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: unsafe { HINSTANCE(GetModuleHandleW(PCWSTR::null()).unwrap_or_default().0) }, + hIcon: HICON::default(), + hCursor: HCURSOR::default(), + hbrBackground: HBRUSH::default(), + lpszMenuName: PCWSTR::null(), + lpszClassName: CLASS_NAME, + hIconSm: HICON::default(), + }; + + unsafe { RegisterClassExW(&class) }; + + let mut rect = RECT::default(); + unsafe { GetClientRect(parent, &mut rect).unwrap() }; + let width = rect.right - rect.left; + let height = rect.bottom - rect.top; + + let data = UndecoratedResizingData { + child: HWND::default(), + has_undecorated_shadows, + }; + + let Ok(drag_window) = (unsafe { + CreateWindowExW( + WINDOW_EX_STYLE::default(), + CLASS_NAME, + WINDOW_NAME, + WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, + 0, + 0, + width, + height, + Some(parent), + None, + GetModuleHandleW(None).ok().map(|h| HINSTANCE(h.0)), + Some(Box::into_raw(Box::new(data)) as _), + ) + }) else { + return; + }; + + unsafe { + set_drag_hwnd_rgn(drag_window, width, height, has_undecorated_shadows); + + let _ = SetWindowPos( + drag_window, + Some(HWND_TOP), + 0, + 0, + 0, + 0, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE, + ); + + let data = UndecoratedResizingData { + child: drag_window, + has_undecorated_shadows, + }; + + let _ = SetWindowSubclass( + parent, + Some(subclass_parent), + (WM_USER + 1) as _, + Box::into_raw(Box::new(data)) as _, + ); + } + } + + unsafe extern "system" fn subclass_parent( + parent: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, + _: usize, + data: usize, + ) -> LRESULT { + unsafe { + match msg { + WM_SIZE => { + let data = data as *mut UndecoratedResizingData; + let data = &*data; + let child = data.child; + let has_undecorated_shadows = data.has_undecorated_shadows; + + // when parent is maximized, remove the undecorated window drag resize region + if is_maximized(parent).unwrap_or(false) { + let _ = SetWindowPos( + child, + Some(HWND_TOP), + 0, + 0, + 0, + 0, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE, + ); + } else { + // otherwise update the cutout region + let mut rect = RECT::default(); + if GetClientRect(parent, &mut rect).is_ok() { + let width = rect.right - rect.left; + let height = rect.bottom - rect.top; + + let _ = SetWindowPos( + child, + Some(HWND_TOP), + 0, + 0, + width, + height, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOMOVE, + ); + + set_drag_hwnd_rgn(child, width, height, has_undecorated_shadows); + } + } + } + + WM_UPDATE_UNDECORATED_SHADOWS => { + let data = data as *mut UndecoratedResizingData; + let data = &mut *data; + data.has_undecorated_shadows = wparam.0 != 0; + } + + WM_NCDESTROY => { + let data = data as *mut UndecoratedResizingData; + drop(Box::from_raw(data)); + } + + _ => {} + } + + DefSubclassProc(parent, msg, wparam, lparam) + } + } + + unsafe extern "system" fn drag_resize_window_proc( + child: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> LRESULT { + unsafe { + match msg { + WM_CREATE => { + let data = lparam.0 as *mut CREATESTRUCTW; + let data = (*data).lpCreateParams as *mut UndecoratedResizingData; + (*data).child = child; + SetWindowLongPtrW(child, GWLP_USERDATA, data as _); + } + + WM_NCHITTEST => { + let data = GetWindowLongPtrW(child, GWLP_USERDATA); + let data = &*(data as *mut UndecoratedResizingData); + + let Ok(parent) = GetParent(child) else { + return DefWindowProcW(child, msg, wparam, lparam); + }; + let style = GetWindowLongPtrW(parent, GWL_STYLE); + let style = WINDOW_STYLE(style as u32); + + let is_resizable = (style & WS_SIZEBOX).0 != 0; + if !is_resizable { + return DefWindowProcW(child, msg, wparam, lparam); + } + + // if the window has undecorated shadows, + // it should always be the top border, + // ensured by the cutout drag window + if data.has_undecorated_shadows { + return LRESULT(HTTOP as _); + } + + let mut rect = RECT::default(); + if GetWindowRect(child, &mut rect).is_err() { + return DefWindowProcW(child, msg, wparam, lparam); + } + + let (cx, cy) = (GET_X_LPARAM(lparam) as i32, GET_Y_LPARAM(lparam) as i32); + + let dpi = util::hwnd_dpi(child); + let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi); + let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi); + + let res = hit_test( + rect.left, + rect.top, + rect.right, + rect.bottom, + cx, + cy, + border_x, + border_y, + ); + + return LRESULT(res.to_win32() as _); + } + + WM_NCLBUTTONDOWN => { + let data = GetWindowLongPtrW(child, GWLP_USERDATA); + let data = &*(data as *mut UndecoratedResizingData); + + let Ok(parent) = GetParent(child) else { + return DefWindowProcW(child, msg, wparam, lparam); + }; + let style = GetWindowLongPtrW(parent, GWL_STYLE); + let style = WINDOW_STYLE(style as u32); + + let is_resizable = (style & WS_SIZEBOX).0 != 0; + if !is_resizable { + return DefWindowProcW(child, msg, wparam, lparam); + } + + let (cx, cy) = (GET_X_LPARAM(lparam) as i32, GET_Y_LPARAM(lparam) as i32); + + // if the window has undecorated shadows, + // it should always be the top border, + // ensured by the cutout drag window + let res = if data.has_undecorated_shadows { + HitTestResult::Top + } else { + let mut rect = RECT::default(); + if GetWindowRect(child, &mut rect).is_err() { + return DefWindowProcW(child, msg, wparam, lparam); + } + + let dpi = util::hwnd_dpi(child); + let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi); + let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi); + + hit_test( + rect.left, + rect.top, + rect.right, + rect.bottom, + cx, + cy, + border_x, + border_y, + ) + }; + + if res != HitTestResult::NoWhere { + let points = POINTS { + x: cx as i16, + y: cy as i16, + }; + + let _ = PostMessageW( + Some(parent), + WM_NCLBUTTONDOWN, + WPARAM(res.to_win32() as _), + LPARAM(&points as *const _ as _), + ); + } + + return LRESULT(0); + } + + WM_UPDATE_UNDECORATED_SHADOWS => { + let data = GetWindowLongPtrW(child, GWLP_USERDATA); + let data = &mut *(data as *mut UndecoratedResizingData); + data.has_undecorated_shadows = wparam.0 != 0; + } + + WM_NCDESTROY => { + let data = GetWindowLongPtrW(child, GWLP_USERDATA); + let data = data as *mut UndecoratedResizingData; + drop(Box::from_raw(data)); + } + + _ => {} + } + + DefWindowProcW(child, msg, wparam, lparam) + } + } + + pub fn detach_resize_handler(hwnd: isize) { + let hwnd = HWND(hwnd as _); + + let Ok(child) = (unsafe { FindWindowExW(Some(hwnd), None, CLASS_NAME, WINDOW_NAME) }) else { + return; + }; + + let _ = unsafe { DestroyWindow(child) }; + } + + unsafe fn set_drag_hwnd_rgn(hwnd: HWND, width: i32, height: i32, only_top: bool) { + unsafe { + // The window used for drag resizing an undecorated window + // is a child HWND that covers the whole window + // and so we need create a cut out in the middle for the parent and other child + // windows like the webview can receive mouse events. + + let dpi = util::hwnd_dpi(hwnd); + let border_x = util::get_system_metrics_for_dpi(SM_CXFRAME, dpi); + let border_y = util::get_system_metrics_for_dpi(SM_CYFRAME, dpi); + + // hrgn1 must be mutable to call .free() later + let mut hrgn1 = CreateRectRgn(0, 0, width, height); + + let x1 = if only_top { 0 } else { border_x }; + let y1 = border_y; + let x2 = if only_top { width } else { width - border_x }; + let y2 = if only_top { height } else { height - border_y }; + + // Wrap hrgn2 in Owned so it is automatically freed when going out of scope + let hrgn2 = Owned::new(CreateRectRgn(x1, y1, x2, y2)); + + CombineRgn(Some(hrgn1), Some(hrgn1), Some(*hrgn2), RGN_DIFF); + + // Try to set the window region + if SetWindowRgn(hwnd, Some(hrgn1), true) == 0 { + // If it fails, we must free hrgn1 manually + hrgn1.free(); + } + } + } + + pub fn update_drag_hwnd_rgn_for_undecorated(hwnd: isize, has_undecorated_shadows: bool) { + let hwnd = HWND(hwnd as _); + + let mut rect = RECT::default(); + let Ok(_) = (unsafe { GetClientRect(hwnd, &mut rect) }) else { + return; + }; + + let width = rect.right - rect.left; + let height = rect.bottom - rect.top; + + let Ok(child) = (unsafe { FindWindowExW(Some(hwnd), None, CLASS_NAME, WINDOW_NAME) }) else { + return; + }; + + unsafe { set_drag_hwnd_rgn(child, width, height, has_undecorated_shadows) }; + + unsafe { + SendMessageW( + hwnd, + WM_UPDATE_UNDECORATED_SHADOWS, + None, + Some(LPARAM(has_undecorated_shadows as _)), + ) + }; + unsafe { + SendMessageW( + child, + WM_UPDATE_UNDECORATED_SHADOWS, + None, + Some(LPARAM(has_undecorated_shadows as _)), + ) + }; + } + + fn is_maximized(window: HWND) -> windows::core::Result { + let mut placement = WINDOWPLACEMENT { + length: std::mem::size_of::() as u32, + ..WINDOWPLACEMENT::default() + }; + unsafe { GetWindowPlacement(window, &mut placement)? }; + Ok(placement.showCmd == SW_MAXIMIZE.0 as u32) + } + + /// Implementation of the `GET_X_LPARAM` macro. + #[allow(non_snake_case)] + #[inline] + fn GET_X_LPARAM(lparam: LPARAM) -> i16 { + ((lparam.0 as usize) & 0xFFFF) as u16 as i16 + } + + /// Implementation of the `GET_Y_LPARAM` macro. + #[allow(non_snake_case)] + #[inline] + fn GET_Y_LPARAM(lparam: LPARAM) -> i16 { + (((lparam.0 as usize) & 0xFFFF_0000) >> 16) as u16 as i16 + } +} + +#[cfg(not(windows))] +mod gtk { + use super::{HitTestResult, hit_test}; + use gtk::prelude::*; + + const BORDERLESS_RESIZE_INSET: i32 = 5; + + impl HitTestResult { + fn to_gtk_edge(self) -> gtk::gdk::WindowEdge { + match self { + HitTestResult::Client | HitTestResult::NoWhere => gtk::gdk::WindowEdge::__Unknown(0), + HitTestResult::Left => gtk::gdk::WindowEdge::West, + HitTestResult::Right => gtk::gdk::WindowEdge::East, + HitTestResult::Top => gtk::gdk::WindowEdge::North, + HitTestResult::Bottom => gtk::gdk::WindowEdge::South, + HitTestResult::TopLeft => gtk::gdk::WindowEdge::NorthWest, + HitTestResult::TopRight => gtk::gdk::WindowEdge::NorthEast, + HitTestResult::BottomLeft => gtk::gdk::WindowEdge::SouthWest, + HitTestResult::BottomRight => gtk::gdk::WindowEdge::SouthEast, + } + } + + fn to_cursor(self, display: >k::gdk::Display) -> Option { + use gtk::gdk::CursorType; + + let cursor_type = match self { + HitTestResult::Left => CursorType::LeftSide, + HitTestResult::Right => CursorType::RightSide, + HitTestResult::Top => CursorType::TopSide, + HitTestResult::Bottom => CursorType::BottomSide, + HitTestResult::TopLeft => CursorType::TopLeftCorner, + HitTestResult::TopRight => CursorType::TopRightCorner, + HitTestResult::BottomLeft => CursorType::BottomLeftCorner, + HitTestResult::BottomRight => CursorType::BottomRightCorner, + HitTestResult::Client | HitTestResult::NoWhere => return None, + }; + + gtk::gdk::Cursor::for_display(display, cursor_type) + } + } + + fn resizable_window(webview: &webkit2gtk::WebView) -> Option { + // The webview may be nested at any depth (e.g. reparented into a GtkPaned), so resolve its toplevel + let window = webview.toplevel()?.downcast::().ok()?; + (!window.is_decorated() && window.is_resizable() && !window.is_maximized()).then_some(window) + } + + fn hit_test_window(window: >k::gdk::Window, x: f64, y: f64) -> HitTestResult { + let border = window.scale_factor() * BORDERLESS_RESIZE_INSET; + hit_test( + 0.0, + 0.0, + window.width() as f64, + window.height() as f64, + x, + y, + border as _, + border as _, + ) + } + + fn hit_test_window_root(window: >k::gdk::Window, root_x: f64, root_y: f64) -> HitTestResult { + let (window_x, window_y) = window.position(); + hit_test_window(window, root_x - window_x as f64, root_y - window_y as f64) + } + + pub fn attach_resize_handler(webview: &wry::WebView) { + use gtk::{gdk::WindowEdge, glib::Propagation}; + use wry::WebViewExtUnix; + + let webview = webview.webview(); + + webview.add_events( + gtk::gdk::EventMask::POINTER_MOTION_MASK + | gtk::gdk::EventMask::BUTTON1_MOTION_MASK + | gtk::gdk::EventMask::BUTTON_PRESS_MASK + | gtk::gdk::EventMask::TOUCH_MASK, + ); + + webview.connect_motion_notify_event( + move |webview: &webkit2gtk::WebView, event: >k::gdk::EventMotion| { + let Some(window) = resizable_window(webview).and_then(|w| w.window()) else { + return Propagation::Proceed; + }; + let Some(webview_window) = webview.window() else { + return Propagation::Proceed; + }; + + // hit test against the toplevel like the button press handler, the webview may not fill it + let (root_x, root_y) = event.root(); + let result = hit_test_window_root(&window, root_x, root_y); + if matches!(result, HitTestResult::Client | HitTestResult::NoWhere) { + return Propagation::Proceed; + } + + let cursor = result.to_cursor(&webview_window.display()); + webview_window.set_cursor(cursor.as_ref()); + Propagation::Stop + }, + ); + + webview.connect_button_press_event( + move |webview: &webkit2gtk::WebView, event: >k::gdk::EventButton| { + if event.button() != 1 { + return Propagation::Proceed; + } + let Some(window) = resizable_window(webview).and_then(|w| w.window()) else { + return Propagation::Proceed; + }; + + let (root_x, root_y) = event.root(); + let edge = hit_test_window_root(&window, root_x, root_y).to_gtk_edge(); + if matches!(&edge, WindowEdge::__Unknown(_)) { + return Propagation::Proceed; + } + + window.begin_resize_drag(edge, 1, root_x as i32, root_y as i32, event.time()); + // Prevent the webview from handling an event claimed by the resize inset + Propagation::Stop + }, + ); + + webview.connect_touch_event( + move |webview: &webkit2gtk::WebView, event: >k::gdk::Event| { + let Some(window) = resizable_window(webview).and_then(|w| w.window()) else { + return Propagation::Proceed; + }; + let Some((root_x, root_y)) = event.root_coords() else { + return Propagation::Proceed; + }; + let Some(device) = event.device() else { + return Propagation::Proceed; + }; + + let edge = hit_test_window_root(&window, root_x, root_y).to_gtk_edge(); + if matches!(&edge, WindowEdge::__Unknown(_)) { + return Propagation::Proceed; + } + + window.begin_resize_drag_for_device( + edge, + &device, + 0, + root_x as i32, + root_y as i32, + event.time(), + ); + Propagation::Proceed + }, + ); + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/util.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/util.rs new file mode 100644 index 0000000000..fa8dec0fc8 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/util.rs @@ -0,0 +1,123 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +#[cfg_attr(not(windows), allow(unused_imports))] +pub use imp::*; + +#[cfg(not(windows))] +mod imp {} + +#[cfg(windows)] +mod imp { + use std::{iter::once, os::windows::ffi::OsStrExt, sync::LazyLock}; + + use windows::{ + Win32::{ + Foundation::*, + Graphics::Gdi::*, + System::LibraryLoader::{GetProcAddress, LoadLibraryW}, + UI::{HiDpi::*, WindowsAndMessaging::*}, + }, + core::{HRESULT, PCSTR, PCWSTR}, + }; + + pub fn encode_wide(string: impl AsRef) -> Vec { + string.as_ref().encode_wide().chain(once(0)).collect() + } + + // Helper function to dynamically load function pointer. + // `library` and `function` must be zero-terminated. + pub(super) fn get_function_impl(library: &str, function: &str) -> FARPROC { + let library = encode_wide(library); + assert_eq!(function.chars().last(), Some('\0')); + + // Library names we will use are ASCII so we can use the A version to avoid string conversion. + let module = unsafe { LoadLibraryW(PCWSTR::from_raw(library.as_ptr())) }.unwrap_or_default(); + if module.is_invalid() { + return None; + } + + unsafe { GetProcAddress(module, PCSTR::from_raw(function.as_ptr())) } + } + + macro_rules! get_function { + ($lib:expr, $func:ident) => { + $crate::util::get_function_impl($lib, concat!(stringify!($func), '\0')) + .map(|f| unsafe { std::mem::transmute::<_, $func>(f) }) + }; + } + + type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32; + type GetDpiForMonitor = unsafe extern "system" fn( + hmonitor: HMONITOR, + dpi_type: MONITOR_DPI_TYPE, + dpi_x: *mut u32, + dpi_y: *mut u32, + ) -> HRESULT; + type GetSystemMetricsForDpi = + unsafe extern "system" fn(nindex: SYSTEM_METRICS_INDEX, dpi: u32) -> i32; + + static GET_DPI_FOR_WINDOW: LazyLock> = + LazyLock::new(|| get_function!("user32.dll", GetDpiForWindow)); + static GET_DPI_FOR_MONITOR: LazyLock> = + LazyLock::new(|| get_function!("shcore.dll", GetDpiForMonitor)); + static GET_SYSTEM_METRICS_FOR_DPI: LazyLock> = + LazyLock::new(|| get_function!("user32.dll", GetSystemMetricsForDpi)); + + #[allow(non_snake_case)] + pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 { + unsafe { + if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { + // We are on Windows 10 Anniversary Update (1607) or later. + match GetDpiForWindow(hwnd) { + 0 => USER_DEFAULT_SCREEN_DPI, // 0 is returned if hwnd is invalid + dpi => dpi, + } + } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { + // We are on Windows 8.1 or later. + let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + if monitor.is_invalid() { + return USER_DEFAULT_SCREEN_DPI; + } + + let mut dpi_x = 0; + let mut dpi_y = 0; + if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y).is_ok() { + dpi_x + } else { + USER_DEFAULT_SCREEN_DPI + } + } else { + // We are on Vista or later. + if IsProcessDPIAware().as_bool() { + let hdc = GetDC(Some(hwnd)); + if hdc.is_invalid() { + return USER_DEFAULT_SCREEN_DPI; + } + // If the process is DPI aware, then scaling must be handled by the application using + // this DPI value. + let dpi = GetDeviceCaps(Some(hdc), LOGPIXELSX) as u32; + ReleaseDC(Some(hwnd), hdc); + dpi + } else { + // If the process is DPI unaware, then scaling is performed by the OS; we thus return + // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the + // application and the WM. + USER_DEFAULT_SCREEN_DPI + } + } + } + } + + #[allow(non_snake_case)] + pub unsafe fn get_system_metrics_for_dpi(nindex: SYSTEM_METRICS_INDEX, dpi: u32) -> i32 { + unsafe { + if let Some(GetSystemMetricsForDpi) = *GET_SYSTEM_METRICS_FOR_DPI { + GetSystemMetricsForDpi(nindex, dpi) + } else { + GetSystemMetrics(nindex) + } + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview.rs new file mode 100644 index 0000000000..69a7863a4f --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview.rs @@ -0,0 +1,49 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +mod imp { + pub type Webview = webkit2gtk::WebView; +} + +#[cfg(target_vendor = "apple")] +mod imp { + use std::ffi::c_void; + + // These pointers are borrowed from ObjC `Retained` handles owned elsewhere and must + // not be mutated through. TODO: change these to `*const c_void` in v3 (breaking change). + pub struct Webview { + pub webview: *mut c_void, + pub manager: *mut c_void, + #[cfg(target_os = "macos")] + pub ns_window: *mut c_void, + #[cfg(target_os = "ios")] + pub view_controller: *mut c_void, + } +} + +#[cfg(windows)] +mod imp { + use webview2_com::Microsoft::Web::WebView2::Win32::{ + ICoreWebView2Controller, ICoreWebView2Environment, + }; + pub struct Webview { + pub controller: ICoreWebView2Controller, + pub environment: ICoreWebView2Environment, + } +} + +#[cfg(target_os = "android")] +mod imp { + use wry::JniHandle; + pub type Webview = JniHandle; +} + +pub use imp::*; diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview_permissions.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview_permissions.rs new file mode 100644 index 0000000000..98e1f57b57 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/webview_permissions.rs @@ -0,0 +1,35 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tauri_runtime::webview::{PermissionKind, PermissionResponse}; + +pub(super) fn from_wry_permission_kind(kind: wry::PermissionKind) -> PermissionKind { + match kind { + wry::PermissionKind::Microphone => PermissionKind::Microphone, + wry::PermissionKind::Camera => PermissionKind::Camera, + wry::PermissionKind::Geolocation => PermissionKind::Geolocation, + wry::PermissionKind::Notifications => PermissionKind::Notifications, + wry::PermissionKind::ClipboardRead => PermissionKind::ClipboardRead, + wry::PermissionKind::DisplayCapture => PermissionKind::DisplayCapture, + wry::PermissionKind::Midi => PermissionKind::Midi, + wry::PermissionKind::Sensors => PermissionKind::Sensors, + wry::PermissionKind::MediaKeySystemAccess => PermissionKind::MediaKeySystemAccess, + wry::PermissionKind::LocalFonts => PermissionKind::LocalFonts, + wry::PermissionKind::WindowManagement => PermissionKind::WindowManagement, + wry::PermissionKind::PointerLock => PermissionKind::PointerLock, + wry::PermissionKind::AutomaticDownloads => PermissionKind::AutomaticDownloads, + wry::PermissionKind::FileSystemAccess => PermissionKind::FileSystemAccess, + wry::PermissionKind::Autoplay => PermissionKind::Autoplay, + wry::PermissionKind::Other => PermissionKind::Other, + _ => PermissionKind::Other, + } +} + +pub(super) fn to_wry_permission_response(response: PermissionResponse) -> wry::PermissionResponse { + match response { + PermissionResponse::Allow => wry::PermissionResponse::Allow, + PermissionResponse::Deny => wry::PermissionResponse::Deny, + PermissionResponse::Default => wry::PermissionResponse::Default, + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/linux.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/linux.rs new file mode 100644 index 0000000000..e7ee9276bd --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/linux.rs @@ -0,0 +1,31 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use gtk::prelude::*; +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +use tao::platform::unix::WindowExtUnix; + +impl super::WindowExt for tao::window::Window { + fn set_enabled(&self, enabled: bool) { + self.gtk_window().set_sensitive(enabled); + } + + fn is_enabled(&self) -> bool { + self.gtk_window().is_sensitive() + } + + fn center(&self) { + if let Some(monitor) = self.current_monitor() { + let window_size = self.outer_size(); + let new_pos = super::calculate_window_center_position(window_size, monitor); + self.set_outer_position(new_pos); + } + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/macos.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/macos.rs new file mode 100644 index 0000000000..4a1d9a3605 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/macos.rs @@ -0,0 +1,43 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use objc2::MainThreadMarker; +use objc2_app_kit::{NSBackingStoreType, NSWindow, NSWindowStyleMask}; +use tao::platform::macos::WindowExtMacOS; + +impl super::WindowExt for tao::window::Window { + // based on electron implementation + // https://github.com/electron/electron/blob/15db63e26df3e3d59ce6281f030624f746518511/shell/browser/native_window_mac.mm#L474 + fn set_enabled(&self, enabled: bool) { + let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() }; + if !enabled { + let frame = ns_window.frame(); + let mtm = MainThreadMarker::new() + .expect("`Window::set_enabled` can only be called on the main thread"); + let sheet = unsafe { + NSWindow::initWithContentRect_styleMask_backing_defer( + mtm.alloc(), + frame, + NSWindowStyleMask::Titled, + NSBackingStoreType::Buffered, + false, + ) + }; + sheet.setAlphaValue(0.5); + ns_window.beginSheet_completionHandler(&sheet, None); + } else if let Some(attached) = ns_window.attachedSheet() { + ns_window.endSheet(&attached); + } + } + + fn is_enabled(&self) -> bool { + let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() }; + ns_window.attachedSheet().is_none() + } + + fn center(&self) { + let ns_window: &NSWindow = unsafe { &*self.ns_window().cast() }; + ns_window.center(); + } +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/mod.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/mod.rs new file mode 100644 index 0000000000..56384f4b75 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/mod.rs @@ -0,0 +1,74 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(windows)] +mod windows; + +#[cfg(desktop)] +use crate::monitor::MonitorExt; + +pub trait WindowExt { + /// Enable or disable the window + /// + /// ## Platform-specific: + /// + /// - **Android / iOS**: Unsupported. + fn set_enabled(&self, enabled: bool); + + /// Whether the window is enabled or disabled. + /// + /// ## Platform-specific: + /// + /// - **Android / iOS**: Unsupported, always returns `true`. + fn is_enabled(&self) -> bool; + + /// Center the window + /// + /// ## Platform-specific: + /// + /// - **Android / iOS**: Unsupported. + fn center(&self) {} + + /// Clears the window surface. i.e make it transparent. + #[cfg(windows)] + fn draw_surface( + &self, + surface: &mut softbuffer::Surface< + std::sync::Arc, + std::sync::Arc, + >, + background_color: Option, + ); +} + +#[cfg(mobile)] +impl WindowExt for tao::window::Window { + fn set_enabled(&self, _: bool) {} + fn is_enabled(&self) -> bool { + true + } +} + +#[cfg(desktop)] +pub fn calculate_window_center_position( + window_size: tao::dpi::PhysicalSize, + target_monitor: tao::monitor::MonitorHandle, +) -> tao::dpi::PhysicalPosition { + let work_area = target_monitor.work_area(); + + tao::dpi::PhysicalPosition::new( + (work_area.size.width as i32 - window_size.width as i32) / 2 + work_area.position.x, + (work_area.size.height as i32 - window_size.height as i32) / 2 + work_area.position.y, + ) +} diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/windows.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/windows.rs new file mode 100644 index 0000000000..1bfff48618 --- /dev/null +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/window/windows.rs @@ -0,0 +1,68 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use windows::Win32::{ + Foundation::{HWND, RECT}, + Graphics::Dwm::{DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute}, + UI::Input::KeyboardAndMouse::{EnableWindow, IsWindowEnabled}, +}; + +use tao::platform::windows::WindowExtWindows; + +impl super::WindowExt for tao::window::Window { + fn set_enabled(&self, enabled: bool) { + let _ = unsafe { EnableWindow(HWND(self.hwnd() as _), enabled) }; + } + + fn is_enabled(&self) -> bool { + unsafe { IsWindowEnabled(HWND(self.hwnd() as _)) }.as_bool() + } + + fn center(&self) { + if let Some(monitor) = self.current_monitor() { + let mut window_size = self.outer_size(); + + if self.is_decorated() { + let mut rect = RECT::default(); + let result = unsafe { + DwmGetWindowAttribute( + HWND(self.hwnd() as _), + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut rect as *mut _ as *mut _, + std::mem::size_of::() as u32, + ) + }; + if result.is_ok() { + window_size.height = (rect.bottom - rect.top) as u32; + } + } + + let new_pos = super::calculate_window_center_position(window_size, monitor); + self.set_outer_position(new_pos); + } + } + + fn draw_surface( + &self, + surface: &mut softbuffer::Surface< + std::sync::Arc, + std::sync::Arc, + >, + background_color: Option, + ) { + let size = self.inner_size(); + if let (Some(width), Some(height)) = ( + std::num::NonZeroU32::new(size.width), + std::num::NonZeroU32::new(size.height), + ) { + surface.resize(width, height).unwrap(); + let mut buffer = surface.buffer_mut().unwrap(); + let color = background_color + .map(|(r, g, b, _)| (b as u32) | ((g as u32) << 8) | ((r as u32) << 16)) + .unwrap_or(0); + buffer.fill(color); + let _ = buffer.present(); + } + } +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/.cargo/audit.toml b/packages/tauri-app/vendor/wry-0.57.1/.cargo/audit.toml new file mode 100644 index 0000000000..b4e01b462d --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/.cargo/audit.toml @@ -0,0 +1,9 @@ +[advisories] +ignore = [ + # time crate can't be updated in the repo because of MSRV, users are unaffected + "RUSTSEC-2026-0009", + # quick-xml, pulled in by dev-dependency wayland-scanner > winit + "RUSTSEC-2026-0194", + # quick-xml, pulled in by dev-dependency wayland-scanner > winit + "RUSTSEC-2026-0195", +] diff --git a/packages/tauri-app/vendor/wry-0.57.1/.cargo/config.toml b/packages/tauri-app/vendor/wry-0.57.1/.cargo/config.toml new file mode 100644 index 0000000000..3f6a4c76b1 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/.cargo/config.toml @@ -0,0 +1,4 @@ +# [build] +# target = "aarch64-linux-android" +[target.x86_64-apple-darwin] +rustflags = ["-C", "link-arg=-mmacosx-version-min=10.12"] diff --git a/packages/tauri-app/vendor/wry-0.57.1/.cargo_vcs_info.json b/packages/tauri-app/vendor/wry-0.57.1/.cargo_vcs_info.json new file mode 100644 index 0000000000..19c0fa14c9 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/.cargo_vcs_info.json @@ -0,0 +1,7 @@ +{ + "git": { + "sha1": "2446feadae623d6f2ac8d2136e3ccef3d7197e0e", + "dirty": true + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/packages/tauri-app/vendor/wry-0.57.1/.gitignore b/packages/tauri-app/vendor/wry-0.57.1/.gitignore new file mode 100644 index 0000000000..0a01592710 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/.gitignore @@ -0,0 +1,9 @@ +# Copyright 2020-2023 Tauri Programme within The Commons Conservancy +# SPDX-License-Identifier: Apache-2.0 +# SPDX-License-Identifier: MIT + +target +gh-pages +.DS_Store +examples/test_video.mp4 +.vscode/ diff --git a/packages/tauri-app/vendor/wry-0.57.1/.license_template b/packages/tauri-app/vendor/wry-0.57.1/.license_template new file mode 100644 index 0000000000..9601f8a1b4 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/.license_template @@ -0,0 +1,3 @@ +// Copyright {20\d{2}(-20\d{2})?} Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT \ No newline at end of file diff --git a/packages/tauri-app/vendor/wry-0.57.1/CHANGELOG.md b/packages/tauri-app/vendor/wry-0.57.1/CHANGELOG.md new file mode 100644 index 0000000000..2fba1b8432 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/CHANGELOG.md @@ -0,0 +1,1344 @@ +# Changelog + +## [0.57.1] + +- [`f9b8bee`](https://github.com/tauri-apps/wry/commit/f9b8bee1de7cfa68d1ee17000c630abeb551b66e) ([#1885](https://github.com/tauri-apps/wry/pull/1885) by [@LucaCappelletti94](https://github.com/tauri-apps/wry/../../LucaCappelletti94)) On Android, read `__wryActivityId` only when the intent or saved state contains it. +- [`1f86475`](https://github.com/tauri-apps/wry/commit/1f86475c0154aeb14af7ad5710fdc72be4c139be) ([#1895](https://github.com/tauri-apps/wry/pull/1895) by [@Arthurmtro](https://github.com/tauri-apps/wry/../../Arthurmtro)) On Android, run initialization scripts once on URLs that are not intercepted by a custom protocol when the WebView supports `DOCUMENT_START_SCRIPT`, instead of a second time from `onPageStarted`. +- [`b6bef41`](https://github.com/tauri-apps/wry/commit/b6bef4124469d0525f604961c187123ae8a2e469) ([#1865](https://github.com/tauri-apps/wry/pull/1865) by [@velocitysystems](https://github.com/tauri-apps/wry/../../velocitysystems)) On Android, stop the WebView from applying the `Range` header a second time to a custom protocol `206` response, and serve ranges past 2 GiB. +- [`d8fe88d`](https://github.com/tauri-apps/wry/commit/d8fe88dc7be2f6ff00c671f823e985335a14f7ad) ([#1847](https://github.com/tauri-apps/wry/pull/1847) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) Moved to edition 2024 +- [`75f2b48`](https://github.com/tauri-apps/wry/commit/75f2b480177db9871dad7df69885d182d3328946) ([#1893](https://github.com/tauri-apps/wry/pull/1893) by [@TimeToBuildBob](https://github.com/tauri-apps/wry/../../TimeToBuildBob)) On Linux, isolate download failure state per download so a canceled or failed download does not make later successful downloads report failure. +- [`9a5f3aa`](https://github.com/tauri-apps/wry/commit/9a5f3aad86d610037f9afc8c22412691f59153da) ([#1868](https://github.com/tauri-apps/wry/pull/1868) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) Log `eval` exceptions when `tracing` feature's enabled at `debug` level. (thanks [#1849](https://github.com/tauri-apps/wry/pull/1849) for bring this up) +- [`66cdfa1`](https://github.com/tauri-apps/wry/commit/66cdfa1d76265cd9a5b1773087d7eec98918adc5) ([#1866](https://github.com/tauri-apps/wry/pull/1866) by [@steipete](https://github.com/tauri-apps/wry/../../steipete)) On macOS, only activate the application and request initial keyboard focus when the new webview is both visible and focused. Creating hidden or unfocused webviews no longer steals focus. +- [`d93a812`](https://github.com/tauri-apps/wry/commit/d93a81272bd7ea0ae51a972e1b7cdaf045cfbe0a) ([#1844](https://github.com/tauri-apps/wry/pull/1844) by [@cpruijsen](https://github.com/tauri-apps/wry/../../cpruijsen)) On macOS, collect dragged file paths via `NSPasteboard.readObjectsForClasses:options:` instead of the deprecated `NSFilenamesPboardType`, fixing a panic in `drag_drop::collect_paths` when the drag source only publishes per-item `public.file-url` types or file reference URLs that AppKit cannot map to `NSFilenamesPboardType`. The legacy type is kept as a fallback. +- [`926dd15`](https://github.com/tauri-apps/wry/commit/926dd150b13beff4dc5d2647d577aedf910affb2) ([#1876](https://github.com/tauri-apps/wry/pull/1876) by [@rterence](https://github.com/tauri-apps/wry/../../rterence)) On macOS, a webview built on its opener's configuration (`NewWindowResponse::Create` with `WebViewBuilderExtMacos::with_webview_configuration`) shares the opener's `WKUserContentController`, so it no longer adds its own initialization scripts and IPC handler to it: the opener's scripts and `ipc` handler already serve it. This stops every opened window from growing the opener's script set, and stops dropping the new webview from removing the opener's `ipc` handler. + +### bug + +- [`78a7056`](https://github.com/tauri-apps/wry/commit/78a705644fd9b59fb47f12a8c8105c48be403332) ([#1883](https://github.com/tauri-apps/wry/pull/1883) by [@LucaCappelletti94](https://github.com/tauri-apps/wry/../../LucaCappelletti94)) On Android, load `with_html` and `load_html` content at `about:blank` so IPC messages reach the handler. +- [`cab3eac`](https://github.com/tauri-apps/wry/commit/cab3eace983007a16f132c14a34d0a220c707bea) ([#1839](https://github.com/tauri-apps/wry/pull/1839) by [@zackees](https://github.com/tauri-apps/wry/../../zackees)) Only inject the Linux WebKitGTK `window.ipc` bridge when an IPC handler is configured. + +## [0.57.0] + +- [`105ca17`](https://github.com/tauri-apps/wry/commit/105ca17188a4d590a364c4e9e2d0845eeccc491c) ([#1834](https://github.com/tauri-apps/wry/pull/1834) by [@renovate](https://github.com/tauri-apps/wry/../../renovate)) Updated dependency `dirs` from v6 to v7 +- [`f701e13`](https://github.com/tauri-apps/wry/commit/f701e13af8426f7775737f5283a9c386521d4dbf) ([#1824](https://github.com/tauri-apps/wry/pull/1824) by [@IntellyCode](https://github.com/tauri-apps/wry/../../IntellyCode)) On iOS, follow the system background color when no `background_color` is set, so the webview no longer flashes its opaque white default before the page paints. +- [`bb69d62`](https://github.com/tauri-apps/wry/commit/bb69d628a905d65042c71a95e85f6921ec9b3264) ([#1809](https://github.com/tauri-apps/wry/pull/1809) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) Bumped MSRV to 1.85 +- [`d293751`](https://github.com/tauri-apps/wry/commit/d2937514ee5b01f4b52b6132f895180e90dd0fc7) ([#1816](https://github.com/tauri-apps/wry/pull/1816) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) Only inject `window.ipc` if the webview is built with `WebViewBuilder::with_ipc_handler` +- [`bb69d62`](https://github.com/tauri-apps/wry/commit/bb69d628a905d65042c71a95e85f6921ec9b3264) ([#1809](https://github.com/tauri-apps/wry/pull/1809) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) Updated `windows` and `windows-core` to 0.62, `webview2-com` to 0.39, this drops Windows 7 support, see https://github.com/microsoft/windows-rs/issues/3808 + +## [0.56.1] + +- [`62080fa`](https://github.com/tauri-apps/wry/commit/62080fabeb154e7951a1d42d1e77e5146a984a9a) ([#1811](https://github.com/tauri-apps/wry/pull/1811) by [@gimenete](https://github.com/tauri-apps/wry/../../gimenete)) On Android, cache the asset-loader setting in `RustWebViewClient` so intercepted requests avoid repeated JNI calls into Rust state. +- [`a5612a8`](https://github.com/tauri-apps/wry/commit/a5612a8475ec2c3072b4cc302b6ea1aa01a4f670) ([#1812](https://github.com/tauri-apps/wry/pull/1812) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) On Android, removed unused `withAssetLoader` binding and `assetLoaderDomain` can now return `null`. +- [`5ce72b0`](https://github.com/tauri-apps/wry/commit/5ce72b0a9b9a8f72111aef10fb4d9242469cfda4) ([#1772](https://github.com/tauri-apps/wry/pull/1772) by [@degant](https://github.com/tauri-apps/wry/../../degant)) Don't panic in the IPC handler when the webview's current document URL is not a valid `http::Uri` (for example a `file://` URL, or one containing a raw space or non-ASCII characters). Such invalid IPC requests are now logged (under the `tracing` feature) and dropped instead of aborting the process, matching the existing behavior of the WKWebView backend. +- [`b95a7f8`](https://github.com/tauri-apps/wry/commit/b95a7f81cbdaab80b13dff2f79472ea28589f210) ([#1799](https://github.com/tauri-apps/wry/pull/1799) by [@Legend-Master](https://github.com/tauri-apps/wry/../../Legend-Master)) On Windows, ignore set webview focus error on create as it fails if the hosting window is minimized. +- [`aff28ef`](https://github.com/tauri-apps/wry/commit/aff28ef5a48e717e1b14b716e452124663cc4df1) ([#1781](https://github.com/tauri-apps/wry/pull/1781) by [@FabianLars](https://github.com/tauri-apps/wry/../../FabianLars)) On macOS in debug mode, don't register `requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:` delegate method on macOS 11 or older to prevent a debug_assertion startup panic. +- [`be729e3`](https://github.com/tauri-apps/wry/commit/be729e302c7cd5a504038cabc9aa2610fb36a3d9) ([#1804](https://github.com/tauri-apps/wry/pull/1804) by [@velocitysystems](https://github.com/tauri-apps/wry/../../velocitysystems)) Override `getDefaultVideoPoster()` on Android to return a transparent bitmap instead of null, preventing Chromium from painting its default gray play-button placeholder on `

WRY Webview Rendering library

+ +[![](https://img.shields.io/crates/v/wry?style=flat-square)](https://crates.io/crates/wry) [![](https://img.shields.io/docsrs/wry?style=flat-square)](https://docs.rs/wry/) +[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri) +[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S) +[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app) +[![https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg](https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg)](https://good-labs.github.io/greater-good-affirmation) +[![support](https://img.shields.io/badge/sponsor-Open%20Collective-blue.svg)](https://opencollective.com/tauri) + +Wry is a cross-platform WebView rendering library. + +The webview requires a running event loop and a window type that implements [`HasWindowHandle`], +or a gtk container widget if you need to support X11 and Wayland. +You can use a windowing library like [`tao`] or [`winit`]. + +### Examples + +This example leverages the [`HasWindowHandle`] and supports Windows, macOS, iOS, Android and Linux (X11 Only). +See the following example using [`winit`]: + +```rust +#[derive(Default)] +struct App { + window: Option, + webview: Option, +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let webview = WebViewBuilder::new() + .with_url("https://tauri.app") + .build(&window) + .unwrap(); + + self.window = Some(window); + self.webview = Some(webview); + } + + fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {} +} + +let event_loop = EventLoop::new().unwrap(); +let mut app = App::default(); +event_loop.run_app(&mut app).unwrap(); +``` + +If you also want to support Wayland too, then we recommend you use [`WebViewBuilderExtUnix::build_gtk`] on Linux. +See the following example using [`tao`]: + +```rust +let event_loop = EventLoop::new(); +let window = WindowBuilder::new().build(&event_loop).unwrap(); + +let builder = WebViewBuilder::new().with_url("https://tauri.app"); + +#[cfg(not(target_os = "linux"))] +let webview = builder.build(&window).unwrap(); +#[cfg(target_os = "linux")] +let webview = builder.build_gtk(window.gtk_window()).unwrap(); +``` + +### Child webviews + +You can use [`WebViewBuilder::build_as_child`] to create the webview as a child inside another window. This is supported on +macOS, Windows and Linux (X11 Only). + +```rust +#[derive(Default)] +struct App { + window: Option, + webview: Option, +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let webview = WebViewBuilder::new() + .with_url("https://tauri.app") + .with_bounds(Rect { + position: LogicalPosition::new(100, 100).into(), + size: LogicalSize::new(200, 200).into(), + }) + .build_as_child(&window) + .unwrap(); + + self.window = Some(window); + self.webview = Some(webview); + } + + fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {} +} + +let event_loop = EventLoop::new().unwrap(); +let mut app = App::default(); +event_loop.run_app(&mut app).unwrap(); +``` + +If you want to support X11 and Wayland at the same time, we recommend using +[`WebViewExtUnix::new_gtk`] or [`WebViewBuilderExtUnix::build_gtk`] with [`gtk::Fixed`]. + +```rust +let event_loop = EventLoop::new(); +let window = WindowBuilder::new().build(&event_loop).unwrap(); + +let builder = WebViewBuilder::new() + .with_url("https://tauri.app") + .with_bounds(Rect { + position: LogicalPosition::new(100, 100).into(), + size: LogicalSize::new(200, 200).into(), + }); + +#[cfg(not(target_os = "linux"))] +let webview = builder.build_as_child(&window).unwrap(); +#[cfg(target_os = "linux")] +let webview = { + let vbox = window.default_vbox().unwrap(); // tao adds a gtk::Box by default + let fixed = gtk::Fixed::new(); + fixed.show_all(); + vbox.pack_start(&fixed, true, true, 0); + builder.build_gtk(&fixed).unwrap() +}; +``` + +### Platform Considerations + +Here is the underlying web engine each platform uses, and some dependencies you might need to install. + +#### Linux + +[WebKitGTK](https://webkitgtk.org/) is used to provide webviews on Linux which requires GTK, +so if the windowing library doesn't support GTK (as in [`winit`]) +you'll need to call [`gtk::init`] before creating the webview and then call [`gtk::main_iteration_do`] alongside +your windowing library event loop. + +```rust +#[derive(Default)] +struct App { + webview_window: Option<(Window, WebView)>, +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let webview = WebViewBuilder::new() + .with_url("https://tauri.app") + .build(&window) + .unwrap(); + + self.webview_window = Some((window, webview)); + } + + fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {} + + // Advance GTK event loop + + + + + + + + + + +

Welcome to WRY!

+

Page 1

+ +

+ Link + + + + diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/script.js b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/script.js new file mode 100644 index 0000000000..f6f257dcb3 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/script.js @@ -0,0 +1,22 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT +if (window.location.pathname.startsWith("/page2")) { + console.log("hello from javascript in page2"); +} else { + console.log("hello from javascript in page1"); + + if (typeof WebAssembly.instantiateStreaming !== "undefined") { + WebAssembly.instantiateStreaming(fetch("/wasm.wasm")).then((wasm) => { + console.log(wasm.instance.exports.main()); // should log 42 + }); + } else { + // Older WKWebView may not support `WebAssembly.instantiateStreaming` yet. + fetch("/wasm.wasm") + .then((response) => response.arrayBuffer()) + .then((bytes) => WebAssembly.instantiate(bytes)) + .then((wasm) => { + console.log(wasm.instance.exports.main()); // should log 42 + }); + } +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/subpage.html b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/subpage.html new file mode 100644 index 0000000000..db373d554a --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/subpage.html @@ -0,0 +1,20 @@ + + + + + + + + + + + + +

Page 2

+ Back home + + + + \ No newline at end of file diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/wasm.wasm b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/wasm.wasm new file mode 100644 index 0000000000..8ffac94b9f Binary files /dev/null and b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_protocol/wasm.wasm differ diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/custom_titlebar.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_titlebar.rs new file mode 100644 index 0000000000..3e4c373a2d --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/custom_titlebar.rs @@ -0,0 +1,304 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + dpi::PhysicalSize, + event::{Event, StartCause, WindowEvent}, + event_loop::{ControlFlow, EventLoopBuilder}, + window::{CursorIcon, ResizeDirection, Window, WindowBuilder}, +}; +use wry::{WebViewBuilder, http::Request}; + +#[derive(Debug)] +enum HitTestResult { + Client, + Left, + Right, + Top, + Bottom, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + NoWhere, +} + +impl HitTestResult { + fn drag_resize_window(&self, window: &Window) { + let _ = window.drag_resize_window(match self { + HitTestResult::Left => ResizeDirection::West, + HitTestResult::Right => ResizeDirection::East, + HitTestResult::Top => ResizeDirection::North, + HitTestResult::Bottom => ResizeDirection::South, + HitTestResult::TopLeft => ResizeDirection::NorthWest, + HitTestResult::TopRight => ResizeDirection::NorthEast, + HitTestResult::BottomLeft => ResizeDirection::SouthWest, + HitTestResult::BottomRight => ResizeDirection::SouthEast, + _ => unreachable!(), + }); + } + + fn change_cursor(&self, window: &Window) { + window.set_cursor_icon(match self { + HitTestResult::Left => CursorIcon::WResize, + HitTestResult::Right => CursorIcon::EResize, + HitTestResult::Top => CursorIcon::NResize, + HitTestResult::Bottom => CursorIcon::SResize, + HitTestResult::TopLeft => CursorIcon::NwResize, + HitTestResult::TopRight => CursorIcon::NeResize, + HitTestResult::BottomLeft => CursorIcon::SwResize, + HitTestResult::BottomRight => CursorIcon::SeResize, + _ => CursorIcon::Default, + }); + } +} + +fn hit_test(window_size: PhysicalSize, x: i32, y: i32, scale: f64) -> HitTestResult { + const BORDERLESS_RESIZE_INSET: f64 = 5.0; + + const CLIENT: isize = 0b0000; + const LEFT: isize = 0b0001; + const RIGHT: isize = 0b0010; + const TOP: isize = 0b0100; + const BOTTOM: isize = 0b1000; + const TOPLEFT: isize = TOP | LEFT; + const TOPRIGHT: isize = TOP | RIGHT; + const BOTTOMLEFT: isize = BOTTOM | LEFT; + const BOTTOMRIGHT: isize = BOTTOM | RIGHT; + + let top = 0; + let left = 0; + let bottom = top + window_size.height as i32; + let right = left + window_size.width as i32; + + let inset = (BORDERLESS_RESIZE_INSET * scale) as i32; + + #[rustfmt::skip] + let result = + (LEFT * (if x < (left + inset) { 1 } else { 0 })) + | (RIGHT * (if x >= (right - inset) { 1 } else { 0 })) + | (TOP * (if y < (top + inset) { 1 } else { 0 })) + | (BOTTOM * (if y >= (bottom - inset) { 1 } else { 0 })); + + match result { + CLIENT => HitTestResult::Client, + LEFT => HitTestResult::Left, + RIGHT => HitTestResult::Right, + TOP => HitTestResult::Top, + BOTTOM => HitTestResult::Bottom, + TOPLEFT => HitTestResult::TopLeft, + TOPRIGHT => HitTestResult::TopRight, + BOTTOMLEFT => HitTestResult::BottomLeft, + BOTTOMRIGHT => HitTestResult::BottomRight, + _ => HitTestResult::NoWhere, + } +} + +enum UserEvent { + Minimize, + Maximize, + DragWindow, + CloseWindow, + MouseDown(i32, i32), + MouseMove(i32, i32), +} + +fn main() -> wry::Result<()> { + let event_loop = EventLoopBuilder::::with_user_event().build(); + let window = WindowBuilder::new() + .with_decorations(false) + .build(&event_loop) + .unwrap(); + + const HTML: &str = r#" + + + + + + + +
+
Custom Titlebar
+
+
+ +
+
+ +
+
+ +
+
+
+
+

WRYYYYYYYYYYYYYYYYYYYYYY!

+
+ + + + +"#; + + let proxy = event_loop.create_proxy(); + let handler = move |req: Request| { + let body = req.body(); + let mut req = body.split([':', ',']); + match req.next().unwrap() { + "minimize" => { + let _ = proxy.send_event(UserEvent::Minimize); + } + "maximize" => { + let _ = proxy.send_event(UserEvent::Maximize); + } + "drag_window" => { + let _ = proxy.send_event(UserEvent::DragWindow); + } + "close" => { + let _ = proxy.send_event(UserEvent::CloseWindow); + } + "mousedown" => { + let x = req.next().unwrap().parse().unwrap(); + let y = req.next().unwrap().parse().unwrap(); + let _ = proxy.send_event(UserEvent::MouseDown(x, y)); + } + "mousemove" => { + let x = req.next().unwrap().parse().unwrap(); + let y = req.next().unwrap().parse().unwrap(); + let _ = proxy.send_event(UserEvent::MouseMove(x, y)); + } + _ => {} + } + }; + + let builder = WebViewBuilder::new() + .with_html(HTML) + .with_ipc_handler(handler) + .with_accept_first_mouse(true); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + let mut webview = Some(webview); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::NewEvents(StartCause::Init) => println!("Wry application started!"), + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } + | Event::UserEvent(UserEvent::CloseWindow) => { + let _ = webview.take(); + *control_flow = ControlFlow::Exit + } + + Event::UserEvent(e) => match e { + UserEvent::Minimize => window.set_minimized(true), + UserEvent::Maximize => window.set_maximized(!window.is_maximized()), + UserEvent::DragWindow => window.drag_window().unwrap(), + UserEvent::MouseDown(x, y) => { + let res = hit_test(window.inner_size(), x, y, window.scale_factor()); + match res { + HitTestResult::Client | HitTestResult::NoWhere => {} + _ => res.drag_resize_window(&window), + } + } + UserEvent::MouseMove(x, y) => { + hit_test(window.inner_size(), x, y, window.scale_factor()).change_cursor(&window); + } + UserEvent::CloseWindow => { /* handled above */ } + }, + _ => (), + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_multiwebview.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_multiwebview.rs new file mode 100644 index 0000000000..1c6eb0d2d9 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_multiwebview.rs @@ -0,0 +1,133 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; +use wry::{ + Rect, WebViewBuilder, + dpi::{LogicalPosition, LogicalSize}, +}; + +fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let fixed = { + use gtk::prelude::*; + use tao::platform::unix::WindowExtUnix; + let fixed = gtk::Fixed::new(); + let vbox = window.default_vbox().unwrap(); + vbox.pack_start(&fixed, true, true, 0); + fixed.show_all(); + fixed + }; + + let build_webview = |builder: WebViewBuilder<'_>| -> wry::Result { + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window)?; + + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use wry::WebViewBuilderExtUnix; + builder.build_gtk(&fixed)? + }; + + Ok(webview) + }; + + let size = window.inner_size().to_logical::(window.scale_factor()); + + let builder = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(0, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://tauri.app"); + let webview = build_webview(builder)?; + + let builder2 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(size.width / 2, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://github.com/tauri-apps/wry"); + let webview2 = build_webview(builder2)?; + + let builder3 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(0, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://twitter.com/TauriApps"); + let webview3 = build_webview(builder3)?; + + let builder4 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(size.width / 2, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://google.com"); + let webview4 = build_webview(builder4)?; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::Resized(size), + .. + } => { + let size = size.to_logical::(window.scale_factor()); + webview + .set_bounds(Rect { + position: LogicalPosition::new(0, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + webview2 + .set_bounds(Rect { + position: LogicalPosition::new(size.width / 2, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + webview3 + .set_bounds(Rect { + position: LogicalPosition::new(0, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + webview4 + .set_bounds(Rect { + position: LogicalPosition::new(size.width / 2, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + } + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => {} + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_opengl.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_opengl.rs new file mode 100644 index 0000000000..b20f1e431e --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/gtk_opengl.rs @@ -0,0 +1,240 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; +use wry::{ + Rect, WebViewBuilder, + dpi::{LogicalPosition, LogicalSize}, +}; + +fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new() + .with_title("GTK OpenGL with Webview") + .with_inner_size(LogicalSize::new(800, 600)) + .build(&event_loop) + .unwrap(); + + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let (fixed, _) = { + use gtk::prelude::*; + use std::{cell::RefCell, rc::Rc}; + use tao::platform::unix::WindowExtUnix; + + let overlay = gtk::Overlay::new(); + let vbox = window.default_vbox().unwrap(); + vbox.pack_start(&overlay, true, true, 0); + + let gl_area = gtk::GLArea::new(); + gl_area.set_has_alpha(true); + gl_area.set_auto_render(true); + + struct AppState { + gl: glow::Context, + program: glow::Program, + vertex_array: glow::VertexArray, + } + + let state: Rc>> = Rc::new(RefCell::new(None)); + let state_realize = state.clone(); + + gl_area.connect_realize(move |gl_area| { + gl_area.make_current(); + if gl_area.error().is_some() { + println!("Error creating GLArea context"); + return; + } + + let gl = unsafe { + glow::Context::from_loader_function(|s| { + let mut ptr = std::ptr::null(); + let name = std::ffi::CString::new(s).unwrap(); + + if let Ok(lib) = libloading::Library::new("libGL.so.1") { + if let Ok(sym) = lib.get:: *const std::ffi::c_void>( + b"glXGetProcAddress\0", + ) { + ptr = sym(name.as_ptr()); + } + } + if ptr.is_null() { + if let Ok(lib) = libloading::Library::new("libEGL.so.1") { + if let Ok(sym) = lib + .get:: *const std::ffi::c_void>( + b"eglGetProcAddress\0", + ) + { + ptr = sym(name.as_ptr()); + } + } + } + ptr + }) + }; + + unsafe { + use glow::HasContext as _; + + let vertex_array = gl.create_vertex_array().unwrap(); + gl.bind_vertex_array(Some(vertex_array)); + + let program = gl.create_program().expect("Cannot create program"); + + let vertex_shader_source = r#" + #version 330 core + void main() { + if (gl_VertexID == 0) gl_Position = vec4(-0.5, -0.5, 0.0, 1.0); + else if (gl_VertexID == 1) gl_Position = vec4(0.5, -0.5, 0.0, 1.0); + else gl_Position = vec4(0.0, 0.5, 0.0, 1.0); + } + "#; + + let fragment_shader_source = r#" + #version 330 core + out vec4 FragColor; + void main() { + FragColor = vec4(1.0, 0.5, 0.2, 1.0); + } + "#; + + let vs = gl.create_shader(glow::VERTEX_SHADER).unwrap(); + gl.shader_source(vs, vertex_shader_source); + gl.compile_shader(vs); + if !gl.get_shader_compile_status(vs) { + panic!("{}", gl.get_shader_info_log(vs)); + } + + let fs = gl.create_shader(glow::FRAGMENT_SHADER).unwrap(); + gl.shader_source(fs, fragment_shader_source); + gl.compile_shader(fs); + if !gl.get_shader_compile_status(fs) { + panic!("{}", gl.get_shader_info_log(fs)); + } + + gl.attach_shader(program, vs); + gl.attach_shader(program, fs); + gl.link_program(program); + if !gl.get_program_link_status(program) { + panic!("{}", gl.get_program_info_log(program)); + } + + gl.detach_shader(program, vs); + gl.delete_shader(vs); + gl.detach_shader(program, fs); + gl.delete_shader(fs); + + *state_realize.borrow_mut() = Some(AppState { + gl, + program, + vertex_array, + }); + } + }); + + let state_render = state.clone(); + gl_area.connect_render(move |_gl_area, _gl_context| { + if let Some(state) = state_render.borrow().as_ref() { + unsafe { + use glow::HasContext as _; + state.gl.clear_color(0.1, 0.2, 0.3, 1.0); + state.gl.clear(glow::COLOR_BUFFER_BIT); + + state.gl.use_program(Some(state.program)); + state.gl.bind_vertex_array(Some(state.vertex_array)); + state.gl.draw_arrays(glow::TRIANGLES, 0, 3); + } + } + gtk::glib::Propagation::Proceed + }); + + gl_area.connect_unrealize(move |gl_area| { + gl_area.make_current(); + if let Some(state) = state.borrow_mut().take() { + unsafe { + use glow::HasContext as _; + state.gl.delete_program(state.program); + state.gl.delete_vertex_array(state.vertex_array); + } + } + }); + + overlay.add(&gl_area); + + let fixed = gtk::Fixed::new(); + overlay.add_overlay(&fixed); + + overlay.show_all(); + (fixed, gl_area) + }; + + let builder = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(100, 100).into(), + size: LogicalSize::new(400, 300).into(), + }) + .with_transparent(true) + .with_html( + r#" + +

Hello World!

+ + "#, + ); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window)?; + + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use wry::WebViewBuilderExtUnix; + builder.build_gtk(&fixed)? + }; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::Resized(size), + .. + } => { + let size = size.to_logical::(window.scale_factor()); + webview + .set_bounds(Rect { + position: LogicalPosition::new(100, 100).into(), + size: LogicalSize::new( + size.width.saturating_sub(200).max(100), + size.height.saturating_sub(200).max(100), + ) + .into(), + }) + .unwrap(); + } + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => {} + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/multiwebview.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/multiwebview.rs new file mode 100644 index 0000000000..fba6733f58 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/multiwebview.rs @@ -0,0 +1,168 @@ +use winit::{ + application::ApplicationHandler, + event::WindowEvent, + event_loop::{ActiveEventLoop, EventLoop}, + window::{Window, WindowId}, +}; +use wry::{ + Rect, WebViewBuilder, + dpi::{LogicalPosition, LogicalSize}, +}; + +#[derive(Default)] +struct State { + window: Option, + webview1: Option, + webview2: Option, + webview3: Option, + webview4: Option, +} + +impl ApplicationHandler for State { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let mut attributes = Window::default_attributes(); + attributes.inner_size = Some(LogicalSize::new(800, 800).into()); + let window = event_loop.create_window(attributes).unwrap(); + + let size = window.inner_size().to_logical::(window.scale_factor()); + + let webview1 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(0, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://tauri.app") + .build_as_child(&window) + .unwrap(); + + let webview2 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(size.width / 2, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://github.com/tauri-apps/wry") + .build_as_child(&window) + .unwrap(); + + let webview3 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(0, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://twitter.com/TauriApps") + .build_as_child(&window) + .unwrap(); + + let webview4 = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(size.width / 2, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .with_url("https://google.com") + .build_as_child(&window) + .unwrap(); + + self.window = Some(window); + self.webview1 = Some(webview1); + self.webview2 = Some(webview2); + self.webview3 = Some(webview3); + self.webview4 = Some(webview4); + } + + fn window_event( + &mut self, + _event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + WindowEvent::Resized(size) => { + if let (Some(window), Some(webview1), Some(webview2), Some(webview3), Some(webview4)) = ( + &self.window, + &self.webview1, + &self.webview2, + &self.webview3, + &self.webview4, + ) { + let size = size.to_logical::(window.scale_factor()); + + webview1 + .set_bounds(Rect { + position: LogicalPosition::new(0, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + + webview2 + .set_bounds(Rect { + position: LogicalPosition::new(size.width / 2, 0).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + + webview3 + .set_bounds(Rect { + position: LogicalPosition::new(0, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + + webview4 + .set_bounds(Rect { + position: LogicalPosition::new(size.width / 2, size.height / 2).into(), + size: LogicalSize::new(size.width / 2, size.height / 2).into(), + }) + .unwrap(); + } + } + WindowEvent::CloseRequested => { + std::process::exit(0); + } + _ => {} + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + while gtk::events_pending() { + gtk::main_iteration_do(false); + } + } + } +} + +fn main() -> wry::Result<()> { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + use gtk::prelude::DisplayExtManual; + + gtk::init()?; + if gtk::gdk::Display::default().unwrap().backend().is_wayland() { + panic!("This example doesn't support wayland!"); + } + + winit::platform::x11::register_xlib_error_hook(Box::new(|_display, error| { + let error = error as *mut x11_dl::xlib::XErrorEvent; + (unsafe { (*error).error_code }) == 170 + })); + } + + let event_loop = EventLoop::new().unwrap(); + let mut state = State::default(); + event_loop.run_app(&mut state).unwrap(); + + Ok(()) +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/multiwindow.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/multiwindow.rs new file mode 100644 index 0000000000..a7e63383bb --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/multiwindow.rs @@ -0,0 +1,125 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use std::collections::HashMap; +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget}, + window::{Window, WindowBuilder, WindowId}, +}; +use wry::{WebView, WebViewBuilder, http::Request}; + +enum UserEvent { + CloseWindow(WindowId), + NewTitle(WindowId, String), + NewWindow, +} + +fn main() -> wry::Result<()> { + let event_loop = EventLoopBuilder::::with_user_event().build(); + let mut webviews = HashMap::new(); + let proxy = event_loop.create_proxy(); + + let (window, webview) = create_new_window( + format!("Window {}", webviews.len() + 1), + &event_loop, + proxy.clone(), + ); + webviews.insert(window.id(), (window, webview)); + + event_loop.run(move |event, event_loop, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + .. + } => { + webviews.remove(&window_id); + if webviews.is_empty() { + *control_flow = ControlFlow::Exit + } + } + Event::UserEvent(UserEvent::NewWindow) => { + let (window, webview) = create_new_window( + format!("Window {}", webviews.len() + 1), + event_loop, + proxy.clone(), + ); + webviews.insert(window.id(), (window, webview)); + } + Event::UserEvent(UserEvent::CloseWindow(id)) => { + webviews.remove(&id); + if webviews.is_empty() { + *control_flow = ControlFlow::Exit + } + } + + Event::UserEvent(UserEvent::NewTitle(id, title)) => { + webviews.get(&id).unwrap().0.set_title(&title); + } + _ => (), + } + }); +} + +fn create_new_window( + title: String, + event_loop: &EventLoopWindowTarget, + proxy: EventLoopProxy, +) -> (Window, WebView) { + let window = WindowBuilder::new() + .with_title(title) + .build(event_loop) + .unwrap(); + let window_id = window.id(); + let handler = move |req: Request| { + let body = req.body(); + match body.as_str() { + "new-window" => { + let _ = proxy.send_event(UserEvent::NewWindow); + } + "close" => { + let _ = proxy.send_event(UserEvent::CloseWindow(window_id)); + } + _ if body.starts_with("change-title") => { + let title = body.replace("change-title:", ""); + let _ = proxy.send_event(UserEvent::NewTitle(window_id, title)); + } + _ => {} + } + }; + + let builder = WebViewBuilder::new() + .with_html( + r#" + + + + "#, + ) + .with_ipc_handler(handler); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window).unwrap(); + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox).unwrap() + }; + (window, webview) +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/permission_handler.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/permission_handler.rs new file mode 100644 index 0000000000..08e5f8a05d --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/permission_handler.rs @@ -0,0 +1,66 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! Example demonstrating the permission handler API. +//! +//! Run: cargo run --example permission_handler +//! Then click the buttons and watch the terminal output. + +fn main() -> wry::Result<()> { + use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, + }; + use wry::{PermissionKind, PermissionResponse, WebViewBuilder}; + + let event_loop = EventLoop::new(); + let window = WindowBuilder::new() + .with_title("Permission Handler Example") + .with_inner_size(tao::dpi::LogicalSize::new(800, 600)) + .build(&event_loop) + .unwrap(); + + let builder = WebViewBuilder::new() + .with_url("https://permission.site/") + .with_permission_handler(|kind| { + let response = match kind { + PermissionKind::Geolocation => PermissionResponse::Default, + _ => PermissionResponse::Allow, + }; + println!("[permission] {kind} → {response}"); + response + }); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let _webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let _webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + if let Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } = event + { + *control_flow = ControlFlow::Exit; + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/reparent.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/reparent.rs new file mode 100644 index 0000000000..1b5476508d --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/reparent.rs @@ -0,0 +1,111 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + event::{ElementState, Event, KeyEvent, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + keyboard::Key, + window::WindowBuilder, +}; +use wry::WebViewBuilder; + +#[cfg(target_os = "macos")] +use {objc2_app_kit::NSWindow, tao::platform::macos::WindowExtMacOS, wry::WebViewExtMacOS}; +#[cfg(target_os = "windows")] +use {tao::platform::windows::WindowExtWindows, wry::WebViewExtWindows}; + +#[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" +)))] +#[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" +)))] +use { + tao::platform::unix::WindowExtUnix, + wry::{WebViewBuilderExtUnix, WebViewExtUnix}, +}; + +fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + let window2 = WindowBuilder::new().build(&event_loop).unwrap(); + + let builder = WebViewBuilder::new().with_url("https://tauri.app"); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use tao::platform::unix::WindowExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + let mut webview_container = window.id(); + + event_loop.run(move |event, _event_loop, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + + Event::WindowEvent { + event: + WindowEvent::KeyboardInput { + event: + KeyEvent { + logical_key: Key::Character("x"), + state: ElementState::Pressed, + .. + }, + .. + }, + .. + } => { + let new_parent = if webview_container == window.id() { + &window2 + } else { + &window + }; + webview_container = new_parent.id(); + + #[cfg(target_os = "macos")] + webview + .reparent(new_parent.ns_window() as *mut NSWindow) + .unwrap(); + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + webview + .reparent(new_parent.default_vbox().unwrap()) + .unwrap(); + #[cfg(target_os = "windows")] + webview.reparent(new_parent.hwnd()).unwrap(); + } + _ => {} + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/simple.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/simple.rs new file mode 100644 index 0000000000..e9c53569f3 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/simple.rs @@ -0,0 +1,70 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; +use wry::WebViewBuilder; + +fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + let builder = WebViewBuilder::new() + .with_url("http://tauri.app") + .with_new_window_req_handler(|url, features| { + println!("new window req: {url} {features:?}"); + wry::NewWindowResponse::Allow + }); + + let builder = builder.with_drag_drop_handler(|e| { + match e { + wry::DragDropEvent::Enter { paths, position } => { + println!("DragEnter: {position:?} {paths:?} ") + } + wry::DragDropEvent::Over { position } => println!("DragOver: {position:?} "), + wry::DragDropEvent::Drop { paths, position } => { + println!("DragDrop: {position:?} {paths:?} ") + } + wry::DragDropEvent::Leave => println!("DragLeave"), + _ => {} + } + + true + }); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let _webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let _webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + if let Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } = event + { + *control_flow = ControlFlow::Exit; + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/streaming.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/streaming.rs new file mode 100644 index 0000000000..5a2048d034 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/streaming.rs @@ -0,0 +1,262 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use std::{ + io::{Read, Seek, SeekFrom, Write}, + path::PathBuf, +}; + +use http::{StatusCode, header}; +use http_range::HttpRange; +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; +use wry::{ + WebViewBuilder, + http::{Request, Response, header::*}, +}; + +pub fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + let builder = WebViewBuilder::new() + .with_custom_protocol( + "wry".into(), + move |_webview_id, request| match wry_protocol(request) { + Ok(r) => r.map(Into::into), + Err(e) => http::Response::builder() + .header(CONTENT_TYPE, "text/plain") + .status(500) + .body(e.to_string().as_bytes().to_vec()) + .unwrap() + .map(Into::into), + }, + ) + .with_custom_protocol( + "stream".into(), + move |_webview_id, request| match stream_protocol(request) { + Ok(r) => r.map(Into::into), + Err(e) => http::Response::builder() + .header(CONTENT_TYPE, "text/plain") + .status(500) + .body(e.to_string().as_bytes().to_vec()) + .unwrap() + .map(Into::into), + }, + ) + // tell the webview to load the custom protocol + .with_url("wry://localhost"); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let _webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let _webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + if let Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } = event + { + *control_flow = ControlFlow::Exit + } + }); +} + +fn wry_protocol( + request: Request>, +) -> Result>, Box> { + let path = request.uri().path(); + // Read the file content from file path + let root = PathBuf::from("examples/streaming"); + let path = if path == "/" { + "index.html" + } else { + // removing leading slash + &path[1..] + }; + let content = std::fs::read(std::fs::canonicalize(root.join(path))?)?; + + // Return asset contents and mime types based on file extentions + // If you don't want to do this manually, there are some crates for you. + // Such as `infer` and `mime_guess`. + let mimetype = if path.ends_with(".html") || path == "/" { + "text/html" + } else if path.ends_with(".js") { + "text/javascript" + } else { + unimplemented!(); + }; + + Response::builder() + .header(CONTENT_TYPE, mimetype) + .body(content) + .map_err(Into::into) +} + +fn stream_protocol( + request: http::Request>, +) -> Result>, Box> { + // skip leading `/` + let path = percent_encoding::percent_decode(&request.uri().path().as_bytes()[1..]) + .decode_utf8_lossy() + .to_string(); + + let mut file = std::fs::File::open(path)?; + + // get file length + let len = { + let old_pos = file.stream_position()?; + let len = file.seek(SeekFrom::End(0))?; + file.seek(SeekFrom::Start(old_pos))?; + len + }; + + let mut resp = Response::builder().header(CONTENT_TYPE, "video/mp4"); + + // if the webview sent a range header, we need to send a 206 in return + // Actually only macOS and Windows are supported. Linux will ALWAYS return empty headers. + let http_response = if let Some(range_header) = request.headers().get("range") { + let not_satisfiable = || { + Response::builder() + .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(header::CONTENT_RANGE, format!("bytes */{len}")) + .body(vec![]) + }; + + // parse range header + let ranges = if let Ok(ranges) = HttpRange::parse(range_header.to_str()?, len) { + ranges + .iter() + // map the output back to spec range , example: 0-499 + .map(|r| (r.start, r.start + r.length - 1)) + .collect::>() + } else { + return Ok(not_satisfiable()?); + }; + + /// The Maximum bytes we send in one range + const MAX_LEN: u64 = 1000 * 1024; + + if ranges.len() == 1 { + let &(start, mut end) = ranges.first().unwrap(); + + // check if a range is not satisfiable + // + // this should be already taken care of by HttpRange::parse + // but checking here again for extra assurance + if start >= len || end >= len || end < start { + return Ok(not_satisfiable()?); + } + + // adjust end byte for MAX_LEN + end = start + (end - start).min(len - start).min(MAX_LEN - 1); + + // calculate number of bytes needed to be read + let bytes_to_read = end + 1 - start; + + // allocate a buf with a suitable capacity + let mut buf = Vec::with_capacity(bytes_to_read as usize); + // seek the file to the starting byte + file.seek(SeekFrom::Start(start))?; + // read the needed bytes + file.take(bytes_to_read).read_to_end(&mut buf)?; + + resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}")); + resp = resp.header(CONTENT_LENGTH, end + 1 - start); + resp = resp.status(StatusCode::PARTIAL_CONTENT); + resp.body(buf) + } else { + let mut buf = Vec::new(); + let ranges = ranges + .iter() + .filter_map(|&(start, mut end)| { + // filter out unsatisfiable ranges + // + // this should be already taken care of by HttpRange::parse + // but checking here again for extra assurance + if start >= len || end >= len || end < start { + None + } else { + // adjust end byte for MAX_LEN + end = start + (end - start).min(len - start).min(MAX_LEN - 1); + Some((start, end)) + } + }) + .collect::>(); + + let boundary = random_boundary(); + let boundary_sep = format!("\r\n--{boundary}\r\n"); + let boundary_closer = format!("\r\n--{boundary}\r\n"); + + resp = resp.header( + CONTENT_TYPE, + format!("multipart/byteranges; boundary={boundary}"), + ); + + for (end, start) in ranges { + // a new range is being written, write the range boundary + buf.write_all(boundary_sep.as_bytes())?; + + // write the needed headers `Content-Type` and `Content-Range` + buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())?; + buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())?; + + // write the separator to indicate the start of the range body + buf.write_all("\r\n".as_bytes())?; + + // calculate number of bytes needed to be read + let bytes_to_read = end + 1 - start; + + let mut local_buf = vec![0_u8; bytes_to_read as usize]; + file.seek(SeekFrom::Start(start))?; + file.read_exact(&mut local_buf)?; + buf.extend_from_slice(&local_buf); + } + // all ranges have been written, write the closing boundary + buf.write_all(boundary_closer.as_bytes())?; + + resp.body(buf) + } + } else { + resp = resp.header(CONTENT_LENGTH, len); + let mut buf = Vec::with_capacity(len as usize); + file.read_to_end(&mut buf)?; + resp.body(buf) + }; + + http_response.map_err(Into::into) +} + +fn random_boundary() -> String { + let mut x = [0_u8; 30]; + getrandom::fill(&mut x).expect("failed to get random bytes"); + (x[..]) + .iter() + .map(|&x| format!("{x:x}")) + .fold(String::new(), |mut a, x| { + a.push_str(x.as_str()); + a + }) +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/streaming/index.html b/packages/tauri-app/vendor/wry-0.57.1/examples/streaming/index.html new file mode 100644 index 0000000000..547cef0d82 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/streaming/index.html @@ -0,0 +1,38 @@ + + + + + + Document + + +

Enter a path to a video to play, then hit Enter or click Start

+
+ + +
+ + + + + diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/transparent.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/transparent.rs new file mode 100644 index 0000000000..6f78282ec3 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/transparent.rs @@ -0,0 +1,79 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use tao::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; +use wry::WebViewBuilder; + +fn main() -> wry::Result<()> { + let event_loop = EventLoop::new(); + #[allow(unused_mut)] + let mut builder = WindowBuilder::new() + .with_decorations(false) + // There are actually three layer of background color when creating webview window. + // The first is window background... + .with_transparent(true); + #[cfg(target_os = "windows")] + { + use tao::platform::windows::WindowBuilderExtWindows; + builder = builder.with_undecorated_shadow(false); + } + let window = builder.build(&event_loop).unwrap(); + + #[cfg(target_os = "windows")] + { + use tao::platform::windows::WindowExtWindows; + window.set_undecorated_shadow(true); + } + + let builder = WebViewBuilder::new() + // The second is on webview... + .with_transparent(true) + // And the last is in html. + .with_html( + r#" + + + "#, + ); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let _webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let _webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + if let Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } = event + { + *control_flow = ControlFlow::Exit + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/wgpu.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/wgpu.rs new file mode 100644 index 0000000000..a64d99dfb8 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/wgpu.rs @@ -0,0 +1,273 @@ +use std::{borrow::Cow, sync::Arc}; +use winit::{ + application::ApplicationHandler, + event::WindowEvent, + event_loop::{ActiveEventLoop, EventLoop}, + window::{Window, WindowId}, +}; +use wry::{ + Rect, WebViewBuilder, + dpi::{LogicalPosition, LogicalSize}, +}; + +#[derive(Default)] +struct State { + window: Option>, + webview: Option, + gfx_state: Option, +} + +struct GfxState { + surface: wgpu::Surface<'static>, + device: wgpu::Device, + queue: wgpu::Queue, + config: wgpu::SurfaceConfiguration, + render_pipeline: wgpu::RenderPipeline, +} + +impl GfxState { + fn new(window: Arc) -> Self { + let instance = wgpu::Instance::default(); + let window_size = window.inner_size(); + let surface = instance.create_surface(window).unwrap(); + + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + force_fallback_adapter: false, + compatible_surface: Some(&surface), + })) + .expect("Failed to find an appropriate adapter"); + + let (device, queue) = pollster::block_on(adapter.request_device( + &wgpu::DeviceDescriptor { + label: None, + required_features: wgpu::Features::empty(), + required_limits: + wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits()), + memory_hints: wgpu::MemoryHints::Performance, + }, + None, + )) + .expect("Failed to create device"); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed( + r#" + @vertex + fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4 { + let x = f32(i32(in_vertex_index) - 1); + let y = f32(i32(in_vertex_index & 1u) * 2 - 1); + return vec4(x, y, 0.0, 1.0); + } + + @fragment + fn fs_main() -> @location(0) vec4 { + return vec4(1.0, 0.0, 0.0, 1.0); + } + "#, + )), + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[], + push_constant_ranges: &[], + }); + + let swapchain_capabilities = surface.get_capabilities(&adapter); + let swapchain_format = swapchain_capabilities.formats[0]; + + let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(swapchain_format.into())], + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview: None, + cache: None, + }); + + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: swapchain_format, + width: window_size.width, + height: window_size.height, + present_mode: wgpu::PresentMode::Fifo, + desired_maximum_frame_latency: 2, + alpha_mode: swapchain_capabilities.alpha_modes[0], + view_formats: vec![], + }; + + surface.configure(&device, &config); + + Self { + surface, + device, + queue, + config, + render_pipeline, + } + } + + fn render(&mut self) { + let frame = self + .surface + .get_current_texture() + .expect("Failed to acquire next swap chain texture"); + let view = frame + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); + { + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + }); + render_pass.set_pipeline(&self.render_pipeline); + render_pass.draw(0..3, 0..1); + } + + self.queue.submit(Some(encoder.finish())); + frame.present(); + } +} + +impl ApplicationHandler for State { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let mut attributes = Window::default_attributes(); + attributes.transparent = true; + #[cfg(windows)] + { + use winit::platform::windows::WindowAttributesExtWindows; + attributes = attributes.with_clip_children(false); + } + + let window = Arc::new(event_loop.create_window(attributes).unwrap()); + + let gfx_state = GfxState::new(Arc::clone(&window)); + + let webview = WebViewBuilder::new() + .with_bounds(Rect { + position: LogicalPosition::new(100, 100).into(), + size: LogicalSize::new(200, 200).into(), + }) + .with_transparent(true) + .with_html( + r#" + + + "#, + ) + .build_as_child(&window) + .unwrap(); + + window.request_redraw(); + + self.window = Some(window); + self.webview = Some(webview); + self.gfx_state = Some(gfx_state); + } + + fn window_event( + &mut self, + _event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + WindowEvent::Resized(size) => { + if let Some(gfx_state) = &mut self.gfx_state { + gfx_state.config.width = size.width; + gfx_state.config.height = size.height; + gfx_state + .surface + .configure(&gfx_state.device, &gfx_state.config); + + if let Some(window) = &self.window { + window.request_redraw(); + } + } + } + WindowEvent::RedrawRequested => { + if let Some(gfx_state) = &mut self.gfx_state { + gfx_state.render(); + } + } + WindowEvent::CloseRequested => { + std::process::exit(0); + } + _ => {} + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + while gtk::events_pending() { + gtk::main_iteration_do(false); + } + } + } +} + +fn main() { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + use gtk::prelude::DisplayExtManual; + + gtk::init().unwrap(); + if gtk::gdk::Display::default().unwrap().backend().is_wayland() { + panic!("This example doesn't support wayland!"); + } + + winit::platform::x11::register_xlib_error_hook(Box::new(|_display, error| { + let error = error as *mut x11_dl::xlib::XErrorEvent; + (unsafe { (*error).error_code }) == 170 + })); + } + + let event_loop = EventLoop::new().unwrap(); + let mut state = State::default(); + event_loop.run_app(&mut state).unwrap(); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/window_border.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/window_border.rs new file mode 100644 index 0000000000..8dd230c8cc --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/window_border.rs @@ -0,0 +1,122 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use dpi::LogicalSize; +use tao::{ + event::{Event, StartCause, WindowEvent}, + event_loop::{ControlFlow, EventLoopBuilder}, + window::WindowBuilder, +}; +use wry::{WebViewBuilder, http::Request}; + +#[derive(Debug)] +enum UserEvent { + TogglShadows, +} + +fn main() -> wry::Result<()> { + let event_loop = EventLoopBuilder::::with_user_event().build(); + let window = WindowBuilder::new() + .with_inner_size(LogicalSize::new(500, 500)) + .with_decorations(false) + .build(&event_loop) + .unwrap(); + + const HTML: &str = r#" + + + + + + + +

+ Click the window to toggle shadows. +

+ + + + + +"#; + + let proxy = event_loop.create_proxy(); + let handler = move |req: Request| { + if req.body().as_str() == "toggleShadows" { + proxy.send_event(UserEvent::TogglShadows).unwrap(); + } + }; + + let builder = WebViewBuilder::new() + .with_html(HTML) + .with_ipc_handler(handler) + .with_accept_first_mouse(true); + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + ))] + let webview = builder.build(&window)?; + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let webview = { + use tao::platform::unix::WindowExtUnix; + use wry::WebViewBuilderExtUnix; + let vbox = window.default_vbox().unwrap(); + builder.build_gtk(vbox)? + }; + + let mut webview = Some(webview); + + let mut shadow = true; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::NewEvents(StartCause::Init) => println!("Wry application started!"), + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => { + let _ = webview.take(); + *control_flow = ControlFlow::Exit + } + + Event::UserEvent(e) => match e { + UserEvent::TogglShadows => { + shadow = !shadow; + #[cfg(windows)] + { + use tao::platform::windows::WindowExtWindows; + window.set_undecorated_shadow(shadow); + } + } + }, + _ => (), + } + }); +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/examples/winit.rs b/packages/tauri-app/vendor/wry-0.57.1/examples/winit.rs new file mode 100644 index 0000000000..7299487009 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/examples/winit.rs @@ -0,0 +1,100 @@ +use dpi::{LogicalPosition, LogicalSize}; +use winit::{ + application::ApplicationHandler, + event::WindowEvent, + event_loop::{ActiveEventLoop, EventLoop}, + window::{Window, WindowId}, +}; +use wry::{Rect, WebViewBuilder}; + +#[derive(Default)] +struct State { + window: Option, + webview: Option, +} + +impl ApplicationHandler for State { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let mut attributes = Window::default_attributes(); + attributes.inner_size = Some(LogicalSize::new(800, 800).into()); + let window = event_loop.create_window(attributes).unwrap(); + + let webview = WebViewBuilder::new() + .with_url("https://tauri.app") + .build_as_child(&window) + .unwrap(); + + self.window = Some(window); + self.webview = Some(webview); + } + + fn window_event( + &mut self, + _event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + match event { + WindowEvent::Resized(size) => { + let window = self.window.as_ref().unwrap(); + let webview = self.webview.as_ref().unwrap(); + + let size = size.to_logical::(window.scale_factor()); + webview + .set_bounds(Rect { + position: LogicalPosition::new(0, 0).into(), + size: LogicalSize::new(size.width, size.height).into(), + }) + .unwrap(); + } + WindowEvent::CloseRequested => { + std::process::exit(0); + } + _ => {} + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + while gtk::events_pending() { + gtk::main_iteration_do(false); + } + } + } +} + +fn main() -> wry::Result<()> { + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + ))] + { + use gtk::prelude::DisplayExtManual; + + gtk::init().unwrap(); + if gtk::gdk::Display::default().unwrap().backend().is_wayland() { + panic!("This example doesn't support wayland!"); + } + + winit::platform::x11::register_xlib_error_hook(Box::new(|_display, error| { + let error = error as *mut x11_dl::xlib::XErrorEvent; + (unsafe { (*error).error_code }) == 170 + })); + } + + let event_loop = EventLoop::new().unwrap(); + let mut state = State::default(); + event_loop.run_app(&mut state).unwrap(); + + Ok(()) +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/renovate.json b/packages/tauri-app/vendor/wry-0.57.1/renovate.json new file mode 100644 index 0000000000..e0493a29a7 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/renovate.json @@ -0,0 +1,10 @@ +{ + "extends": ["config:recommended"], + "rangeStrategy": "replace", + "packageRules": [ + { + "semanticCommitType": "chore", + "matchPackageNames": ["*"] + } + ] +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/rustfmt.toml b/packages/tauri-app/vendor/wry-0.57.1/rustfmt.toml new file mode 100644 index 0000000000..a90653d108 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/rustfmt.toml @@ -0,0 +1,15 @@ +max_width = 100 +hard_tabs = false +tab_spaces = 2 +newline_style = "Unix" +use_small_heuristics = "Default" +reorder_imports = true +reorder_modules = true +remove_nested_parens = true +edition = "2018" +merge_derives = true +use_try_shorthand = false +use_field_init_shorthand = false +force_explicit_abi = true +imports_granularity = "Crate" +#license_template_path = ".license_template" diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/binding.rs b/packages/tauri-app/vendor/wry-0.57.1/src/android/binding.rs new file mode 100644 index 0000000000..e2952fb498 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/binding.rs @@ -0,0 +1,558 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use http::{ + Request, + header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderName, HeaderValue}, +}; +use jni::errors::Result as JniResult; +pub use jni::{ + self, JNIEnv, + objects::{GlobalRef, JClass, JMap, JObject, JString}, + sys::{jboolean, jint, jobject, jstring}, +}; +pub use ndk; +use ndk::looper::{FdEvent, ThreadLooper}; +use std::os::fd::{AsFd, AsRawFd}; + +use super::{ + ASSET_LOADER_DOMAIN, EVAL_CALLBACKS, IPC, ON_LOAD_HANDLER, PERMISSION_HANDLER, REQUEST_HANDLER, + TITLE_CHANGE_HANDLER, URL_LOADING_OVERRIDE, + main_pipe::{MAIN_PIPE, MainPipe}, +}; + +use crate::{PageLoadEvent, PermissionKind, PermissionResponse}; + +#[macro_export] +macro_rules! android_binding { + ($domain:ident, $package:ident) => { + ::wry::android_binding!($domain, $package, ::wry) + }; + // use imported `android_setup` just to force the import path to use `wry::{}` + // as the macro breaks without braces + ($domain:ident, $package:ident, $wry:path) => {{ + use $wry::{android_setup as _, prelude::*}; + + android_fn!($domain, $package, Rust, onFirstActivityCreateWry, []); + android_fn!( + $domain, + $package, + Rust, + onWebviewDestroy, + [JObject, JString] + ); + + android_fn!( + $domain, + $package, + Rust, + handleRequest, + [JString, JObject, jboolean], + jobject + ); + android_fn!( + $domain, + $package, + Rust, + assetLoaderDomain, + [JString], + jstring + ); + android_fn!( + $domain, + $package, + Rust, + shouldOverride, + [JString, JString], + jboolean + ); + android_fn!($domain, $package, Rust, onEval, [JString, jint, JString]); + android_fn!($domain, $package, Rust, onPageLoading, [JString, JString]); + android_fn!($domain, $package, Rust, onPageLoaded, [JString, JString]); + android_fn!($domain, $package, Rust, ipc, [JString, JString, JString]); + android_fn!( + $domain, + $package, + Rust, + handleReceivedTitle, + [JString, JString], + ); + android_fn!( + $domain, + $package, + RustWebChromeClient, + onPermissionRequestNative, + [JString, JString], + jint + ); + android_fn!( + $domain, + $package, + RustWebChromeClient, + onGeolocationPermissionRequestNative, + [JString, JString], + jboolean + ); + }}; +} + +fn handle_request( + env: &mut JNIEnv, + webview_id: JString, + request: JObject, + is_document_start_script_enabled: jboolean, +) -> JniResult { + let webview_id = env.get_string(&webview_id)?; + let webview_id = webview_id.to_str().unwrap_or_default(); + + let Some(handler) = REQUEST_HANDLER + .lock() + .unwrap() + .get(webview_id) + .map(|handler| handler.handler.clone()) + else { + return Ok(*JObject::null()); + }; + + #[cfg(feature = "tracing")] + let span = + tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty) + .entered(); + + let mut request_builder = Request::builder(); + + let uri = env + .call_method(&request, "getUrl", "()Landroid/net/Uri;", &[])? + .l()?; + let url: JString = env + .call_method(&uri, "toString", "()Ljava/lang/String;", &[])? + .l()? + .into(); + let url = env.get_string(&url)?.to_string_lossy().to_string(); + + #[cfg(feature = "tracing")] + span.record("uri", &url); + + request_builder = request_builder.uri(&url); + + let method = env + .call_method(&request, "getMethod", "()Ljava/lang/String;", &[])? + .l() + .map(JString::from)?; + request_builder = request_builder.method( + env + .get_string(&method)? + .to_string_lossy() + .to_string() + .as_str(), + ); + + let request_headers = env + .call_method(request, "getRequestHeaders", "()Ljava/util/Map;", &[])? + .l()?; + let request_headers = JMap::from_env(env, &request_headers)?; + let mut iter = request_headers.iter(env)?; + while let Some((header, value)) = iter.next(env)? { + let header = JString::from(header); + let value = JString::from(value); + let header = env.get_string(&header)?; + let value = env.get_string(&value)?; + if let (Ok(header), Ok(value)) = ( + HeaderName::from_bytes(header.to_bytes()), + HeaderValue::from_bytes(value.to_bytes()), + ) { + request_builder = request_builder.header(header, value); + } + } + + let final_request = match request_builder.body(Vec::new()) { + Ok(req) => req, + Err(_e) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to build response: {_e}"); + return Ok(*JObject::null()); + } + }; + + let response = { + #[cfg(feature = "tracing")] + let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered(); + handler( + webview_id, + final_request, + is_document_start_script_enabled != 0, + ) + }; + let Some(response) = response else { + return Ok(*JObject::null()); + }; + let status = response.status(); + let status_code = status.as_u16() as i32; + let status_err = if status_code < 100 { + Some("Status code can't be less than 100") + } else if status_code > 599 { + Some("statusCode can't be greater than 599.") + } else if status_code > 299 && status_code < 400 { + Some("statusCode can't be in the [300, 399] range.") + } else { + None + }; + if let Some(_err) = status_err { + #[cfg(feature = "tracing")] + tracing::warn!("{_err}"); + return Ok(*JObject::null()); + } + + let reason_phrase = status.canonical_reason().unwrap_or("OK"); + let (mime_type, encoding) = if let Some(content_type) = response.headers().get(CONTENT_TYPE) { + let content_type = content_type.to_str().unwrap().trim(); + let mut s = content_type.split(';'); + let mime_type = s.next().unwrap().trim(); + let mut encoding = None; + for token in s { + let token = token.trim(); + if token.starts_with("charset=") { + encoding.replace(token.split('=').nth(1).unwrap()); + break; + } + } + ( + env.new_string(mime_type)?, + if let Some(encoding) = encoding { + env.new_string(encoding)? + } else { + JString::default() + }, + ) + } else { + (JString::default(), JString::default()) + }; + + let headers = response.headers(); + let obj = env.new_object("java/util/HashMap", "()V", &[])?; + let response_headers = { + let headers_map = JMap::from_env(env, &obj)?; + for (name, value) in headers.iter() { + // WebResourceResponse will automatically generate Content-Type and + // Content-Length headers so we should skip them to avoid duplication. + if name == CONTENT_TYPE || name == CONTENT_LENGTH { + continue; + } + let key = env.new_string(name)?; + let value = env.new_string(value.to_str().unwrap_or_default())?; + headers_map.put(env, &key, &value)?; + } + headers_map + }; + + let bytes = response.body(); + + let byte_array_input_stream = env.find_class("java/io/ByteArrayInputStream")?; + let byte_array = env.byte_array_from_slice(bytes)?; + let stream = env.new_object(byte_array_input_stream, "([B)V", &[(&byte_array).into()])?; + + let reason_phrase = env.new_string(reason_phrase)?; + + let web_resource_response_class = env.find_class("android/webkit/WebResourceResponse")?; + let web_resource_response = env.new_object( + web_resource_response_class, + "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/util/Map;Ljava/io/InputStream;)V", + &[(&mime_type).into(), (&encoding).into(), status_code.into(), (&reason_phrase).into(), (&response_headers).into(), (&stream).into()], + )?; + + Ok(*web_resource_response) +} + +#[allow(non_snake_case)] +pub unsafe fn onFirstActivityCreateWry(env: JNIEnv, _: JClass) { + unsafe { + let mut main_pipe = MainPipe { env }; + + let looper = ThreadLooper::for_thread().unwrap(); + + looper + .add_fd_with_callback(MAIN_PIPE[0].as_fd(), FdEvent::INPUT, move |fd, _event| { + let mut buf = [0u8]; + if libc::read(fd.as_raw_fd(), buf.as_mut_ptr() as *mut _, buf.len()) + == buf.len() as libc::ssize_t + { + // unregister itself on errors + main_pipe.recv().is_ok() + } else { + // unregister itself + false + } + }) + .unwrap(); + } +} + +#[allow(non_snake_case)] +pub unsafe fn onWebviewDestroy(mut env: JNIEnv, _: JClass, activity: JObject, webview_id: JString) { + let activity_id = env + .call_method(&activity, "getId", "()I", &[]) + .unwrap() + .i() + .unwrap(); + + let webview_id = env + .get_string(&webview_id) + .unwrap() + .to_string_lossy() + .to_string(); + + let is_changing_configurations = env + .call_method(&activity, "isChangingConfigurations", "()Z", &[]) + .unwrap() + .z() + .unwrap(); + + super::MainPipe::send( + activity_id, + super::WebViewMessage::OnDestroy { + activity_id, + webview_id, + is_changing_configurations, + }, + ); +} + +#[allow(non_snake_case)] +pub unsafe fn handleRequest( + mut env: JNIEnv, + _: JClass, + webview_id: JString, + request: JObject, + is_document_start_script_enabled: jboolean, +) -> jobject { + match handle_request( + &mut env, + webview_id, + request, + is_document_start_script_enabled, + ) { + Ok(response) => response, + Err(_e) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to handle request: {_e}"); + JObject::null().as_raw() + } + } +} + +#[allow(non_snake_case)] +pub unsafe fn shouldOverride( + mut env: JNIEnv, + _: JClass, + webview_id: JString, + url: JString, +) -> jboolean { + match env.get_string(&url) { + Ok(url) => { + let url = url.to_string_lossy().to_string(); + + let Ok(webview_id) = env.get_string(&webview_id) else { + return false.into(); + }; + let webview_id = webview_id.to_str().unwrap_or_default(); + + URL_LOADING_OVERRIDE + .lock() + .unwrap() + .get(webview_id) + // We negate the result of the function because the logic for the android + // client is different from how the navigation_handler is defined. + // + // https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20android.webkit.WebResourceRequest) + .map(|f| !(f.handler)(url)) + .unwrap_or_default() + } + Err(_e) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}"); + false + } + } + .into() +} + +#[allow(non_snake_case)] +pub unsafe fn onEval(mut env: JNIEnv, _: JClass, _webview_id: JString, id: jint, result: JString) { + match env.get_string(&result) { + Ok(result) => { + if let Some(cb) = EVAL_CALLBACKS + .get_or_init(Default::default) + .lock() + .unwrap() + .get(&id) + { + cb(result.into()); + } + } + Err(_e) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}"); + } + } +} + +pub unsafe fn ipc(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString, body: JString) { + match ( + env.get_string(&url), + env.get_string(&body), + env.get_string(&webview_id), + ) { + (Ok(url), Ok(body), Ok(webview_id)) => { + #[cfg(feature = "tracing")] + let _span = tracing::info_span!(parent: None, "wry::ipc::handle").entered(); + + let url = url.to_string_lossy().to_string(); + let body = body.to_string_lossy().to_string(); + let webview_id = webview_id.to_string_lossy().to_string(); + if let Some(ipc) = IPC.lock().unwrap().get(&webview_id) { + match Request::builder().uri(url).body(body) { + Ok(request) => (ipc.handler)(request), + Err(_error) => { + #[cfg(feature = "tracing")] + tracing::warn!("WebView received invalid IPC request: {_error}") + } + } + } + } + (Err(_e), _, _) | (_, Err(_e), _) | (_, _, Err(_e)) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}") + } + } +} + +#[allow(non_snake_case)] +pub unsafe fn handleReceivedTitle(mut env: JNIEnv, _: JClass, webview_id: JString, title: JString) { + match (env.get_string(&title), env.get_string(&webview_id)) { + (Ok(title), Ok(webview_id)) => { + let title = title.to_string_lossy().to_string(); + let webview_id = webview_id.to_string_lossy().to_string(); + if let Some(title_handler) = TITLE_CHANGE_HANDLER.lock().unwrap().get(&webview_id) { + (title_handler.handler)(title) + } + } + (Err(_e), _) | (_, Err(_e)) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}") + } + } +} + +#[allow(non_snake_case)] +pub unsafe fn assetLoaderDomain(env: JNIEnv, _: JClass, webview_id: JString) -> jstring { + fn asset_loader_domain_inner(mut env: JNIEnv, webview_id: JString) -> Option { + let webview_id = env.get_string(&webview_id).ok()?; + let webview_id = webview_id.to_str().ok()?; + let asset_loader_domain = ASSET_LOADER_DOMAIN.lock().unwrap(); + let domain = asset_loader_domain.get(webview_id)?; + Some(env.new_string(domain).unwrap().as_raw()) + } + asset_loader_domain_inner(env, webview_id).unwrap_or_else(|| (*JObject::null()).into()) +} + +#[allow(non_snake_case)] +pub unsafe fn onPageLoading(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString) { + match (env.get_string(&url), env.get_string(&webview_id)) { + (Ok(url), Ok(webview_id)) => { + let url = url.to_string_lossy().to_string(); + let webview_id = webview_id.to_string_lossy().to_string(); + if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().get(&webview_id) { + (on_load.handler)(PageLoadEvent::Started, url) + } + } + (Err(_e), _) | (_, Err(_e)) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}") + } + } +} + +#[allow(non_snake_case)] +pub unsafe fn onPageLoaded(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString) { + match (env.get_string(&url), env.get_string(&webview_id)) { + (Ok(url), Ok(webview_id)) => { + let url = url.to_string_lossy().to_string(); + let webview_id = webview_id.to_string_lossy().to_string(); + if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().get(&webview_id) { + (on_load.handler)(PageLoadEvent::Finished, url) + } + } + (Err(_e), _) | (_, Err(_e)) => { + #[cfg(feature = "tracing")] + tracing::warn!("Failed to parse JString: {_e}") + } + } +} + +const ANDROID_PERMISSION_REQUEST_DEFAULT: jint = 0; +const ANDROID_PERMISSION_REQUEST_ALLOW: jint = 1; +const ANDROID_PERMISSION_REQUEST_DENY: jint = 2; + +/// Returns `ANDROID_PERMISSION_REQUEST_DEFAULT | ANDROID_PERMISSION_REQUEST_ALLOW | ANDROID_PERMISSION_REQUEST_DENY` +#[allow(non_snake_case)] +pub unsafe fn onPermissionRequestNative( + mut env: JNIEnv, + _: JClass, + webview_id: JString, + resource: JString, +) -> jint { + let Ok(webview_id) = env.get_string(&webview_id) else { + return ANDROID_PERMISSION_REQUEST_DEFAULT; + }; + let webview_id = webview_id.to_str().ok().unwrap_or_default(); + let permission_handlers = PERMISSION_HANDLER.lock().unwrap(); + let Some(handler) = permission_handlers.get(webview_id) else { + return ANDROID_PERMISSION_REQUEST_DEFAULT; + }; + + let Ok(resource_str) = env.get_string(&resource) else { + return ANDROID_PERMISSION_REQUEST_DEFAULT; + }; + let resource_str = resource_str.to_string_lossy(); + + let kind = match resource_str.as_ref() { + "android.webkit.resource.AUDIO_CAPTURE" => PermissionKind::Microphone, + "android.webkit.resource.VIDEO_CAPTURE" => PermissionKind::Camera, + "android.webkit.resource.PROTECTED_MEDIA_ID" => PermissionKind::MediaKeySystemAccess, + "android.webkit.resource.MIDI_SYSEX" => PermissionKind::Midi, + _ => PermissionKind::Other, + }; + + match (handler.handler)(kind) { + PermissionResponse::Default => ANDROID_PERMISSION_REQUEST_DEFAULT, + PermissionResponse::Allow => ANDROID_PERMISSION_REQUEST_ALLOW, + PermissionResponse::Deny => ANDROID_PERMISSION_REQUEST_DENY, + } +} + +/// Returns true to deny geolocation. +/// +/// Returns false to let Kotlin continue with Android's normal runtime permission flow. +#[allow(non_snake_case)] +pub unsafe fn onGeolocationPermissionRequestNative( + mut env: JNIEnv, + _: JClass, + webview_id: JString, + _origin: JString, +) -> jboolean { + let Ok(webview_id) = env.get_string(&webview_id) else { + return false.into(); + }; + let webview_id = webview_id.to_str().ok().unwrap_or_default(); + let permission_handlers = PERMISSION_HANDLER.lock().unwrap(); + let Some(handler) = permission_handlers.get(webview_id) else { + return false.into(); + }; + + matches!( + (handler.handler)(PermissionKind::Geolocation), + PermissionResponse::Deny + ) + .into() +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Ipc.kt b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Ipc.kt new file mode 100644 index 0000000000..c760375064 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Ipc.kt @@ -0,0 +1,23 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +@file:Suppress("unused") + +package {{package}} + +import android.webkit.* + +class Ipc(val webView: RustWebView, val webViewClient: RustWebViewClient) { + @JavascriptInterface + fun postMessage(message: String?) { + message?.let {m -> + // we're not using WebView::getUrl() here because it needs to be executed on the main thread + // and it would slow down the Ipc + // so instead we track the current URL on the webview client + Rust.ipc(webView.id, webViewClient.currentUrl, m) + } + } + + {{class-extension}} +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Logger.kt b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Logger.kt new file mode 100644 index 0000000000..3666ad2aac --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Logger.kt @@ -0,0 +1,87 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +@file:Suppress("unused", "MemberVisibilityCanBePrivate") + +package {{package}} + +// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/Logger.java + +import android.text.TextUtils +import android.util.Log + +class Logger { + companion object { + private const val LOG_TAG_CORE = "Tauri" + + fun tags(vararg subtags: String): String { + return if (subtags.isNotEmpty()) { + LOG_TAG_CORE + "/" + TextUtils.join("/", subtags) + } else LOG_TAG_CORE + } + + fun verbose(message: String) { + verbose(LOG_TAG_CORE, message) + } + + private fun verbose(tag: String, message: String) { + if (!shouldLog()) { + return + } + Log.v(tag, message) + } + + fun debug(message: String) { + debug(LOG_TAG_CORE, message) + } + + fun debug(tag: String, message: String) { + if (!shouldLog()) { + return + } + Log.d(tag, message) + } + + fun info(message: String) { + info(LOG_TAG_CORE, message) + } + + fun info(tag: String, message: String) { + if (!shouldLog()) { + return + } + Log.i(tag, message) + } + + fun warn(message: String) { + warn(LOG_TAG_CORE, message) + } + + fun warn(tag: String, message: String) { + if (!shouldLog()) { + return + } + Log.w(tag, message) + } + + fun error(message: String) { + error(LOG_TAG_CORE, message, null) + } + + fun error(message: String, e: Throwable?) { + error(LOG_TAG_CORE, message, e) + } + + fun error(tag: String, message: String, e: Throwable?) { + if (!shouldLog()) { + return + } + Log.e(tag, message, e) + } + + private fun shouldLog(): Boolean { + return BuildConfig.DEBUG + } + } +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/PermissionHelper.kt b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/PermissionHelper.kt new file mode 100644 index 0000000000..b2471e515e --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/PermissionHelper.kt @@ -0,0 +1,115 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +package {{package}} + +// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/PermissionHelper.java + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.ActivityCompat +import java.util.ArrayList + +object PermissionHelper { + /** + * Checks if a list of given permissions are all granted by the user + * + * @param permissions Permissions to check. + * @return True if all permissions are granted, false if at least one is not. + */ + fun hasPermissions(context: Context?, permissions: Array): Boolean { + for (perm in permissions) { + if (ActivityCompat.checkSelfPermission( + context!!, + perm + ) != PackageManager.PERMISSION_GRANTED + ) { + return false + } + } + return true + } + + /** + * Check whether the given permission has been defined in the AndroidManifest.xml + * + * @param permission A permission to check. + * @return True if the permission has been defined in the Manifest, false if not. + */ + fun hasDefinedPermission(context: Context, permission: String): Boolean { + var hasPermission = false + val requestedPermissions = getManifestPermissions(context) + if (!requestedPermissions.isNullOrEmpty()) { + val requestedPermissionsList = listOf(*requestedPermissions) + val requestedPermissionsArrayList = ArrayList(requestedPermissionsList) + if (requestedPermissionsArrayList.contains(permission)) { + hasPermission = true + } + } + return hasPermission + } + + /** + * Check whether all of the given permissions have been defined in the AndroidManifest.xml + * @param context the app context + * @param permissions a list of permissions + * @return true only if all permissions are defined in the AndroidManifest.xml + */ + fun hasDefinedPermissions(context: Context, permissions: Array): Boolean { + for (permission in permissions) { + if (!hasDefinedPermission(context, permission)) { + return false + } + } + return true + } + + /** + * Get the permissions defined in AndroidManifest.xml + * + * @return The permissions defined in AndroidManifest.xml + */ + private fun getManifestPermissions(context: Context): Array? { + var requestedPermissions: Array? = null + try { + val pm = context.packageManager + val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong())) + } else { + @Suppress("DEPRECATION") + pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS) + } + if (packageInfo != null) { + requestedPermissions = packageInfo.requestedPermissions + } + } catch (_: Exception) { + } + return requestedPermissions + } + + /** + * Given a list of permissions, return a new list with the ones not present in AndroidManifest.xml + * + * @param neededPermissions The permissions needed. + * @return The permissions not present in AndroidManifest.xml + */ + fun getUndefinedPermissions(context: Context, neededPermissions: Array): Array { + val undefinedPermissions = ArrayList() + val requestedPermissions = getManifestPermissions(context) + if (!requestedPermissions.isNullOrEmpty()) { + val requestedPermissionsList = listOf(*requestedPermissions) + val requestedPermissionsArrayList = ArrayList(requestedPermissionsList) + for (permission in neededPermissions) { + if (!requestedPermissionsArrayList.contains(permission)) { + undefinedPermissions.add(permission) + } + } + var undefinedPermissionArray = arrayOfNulls(undefinedPermissions.size) + undefinedPermissionArray = undefinedPermissions.toArray(undefinedPermissionArray) + return undefinedPermissionArray + } + return neededPermissions + } +} diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Rust.kt b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Rust.kt new file mode 100644 index 0000000000..6b2d9a3de1 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/Rust.kt @@ -0,0 +1,44 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +@file:Suppress("unused") + +package {{package}} + +import android.content.Intent +import android.webkit.WebView +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse + +object Rust { + init { + System.loadLibrary("{{library}}") + } + + // Tao bindings + @JvmStatic external fun onFirstActivityCreate() + @JvmStatic external fun onCreate(activity: WryActivity) + @JvmStatic external fun onStart(activity: WryActivity) + @JvmStatic external fun onResume(activity: WryActivity) + @JvmStatic external fun onPause(activity: WryActivity) + @JvmStatic external fun onStop(activity: WryActivity) + @JvmStatic external fun onDestroy(activity: WryActivity) + @JvmStatic external fun onWindowFocusChanged(activity: WryActivity, focus: Boolean) + @JvmStatic external fun onLowMemory() + @JvmStatic external fun onNewIntent(intent: Intent) + + @JvmStatic external fun onFirstActivityCreateWry() + @JvmStatic external fun onWebviewDestroy(activity: WryActivity, webviewId: String) + + @JvmStatic external fun ipc(webviewId: String, url: String, message: String) + + @JvmStatic external fun assetLoaderDomain(webviewId: String): String? + @JvmStatic external fun handleRequest(webviewId: String, request: WebResourceRequest, isDocumentStartScriptEnabled: Boolean): WebResourceResponse? + @JvmStatic external fun shouldOverride(webviewId: String, url: String): Boolean + @JvmStatic external fun onPageLoading(webviewId: String, url: String) + @JvmStatic external fun onPageLoaded(webviewId: String, url: String) + @JvmStatic external fun onEval(webviewId: String, id: Int, result: String) + + @JvmStatic external fun handleReceivedTitle(webviewId: String, title: String) +} \ No newline at end of file diff --git a/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/RustWebChromeClient.kt b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/RustWebChromeClient.kt new file mode 100644 index 0000000000..0a8aee15c2 --- /dev/null +++ b/packages/tauri-app/vendor/wry-0.57.1/src/android/kotlin/RustWebChromeClient.kt @@ -0,0 +1,517 @@ +// Copyright 2020-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +@file:Suppress("ObsoleteSdkInt", "RedundantOverride", "QueryPermissionsNeeded", "SimpleDateFormat") + +package {{package}} + +// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java + +import android.Manifest +import android.app.Activity +import android.app.AlertDialog +import android.content.ActivityNotFoundException +import android.content.DialogInterface +import android.content.Intent +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.view.View +import android.webkit.* +import android.widget.EditText +import androidx.core.content.FileProvider +import java.io.File +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.* + +class RustWebChromeClient(private val activity: WryActivity, private val webViewId: String) : WebChromeClient() { + private companion object { + const val PERMISSION_REQUEST_DEFAULT = 0 + const val PERMISSION_REQUEST_ALLOW = 1 + const val PERMISSION_REQUEST_DENY = 2 + } + + /** + * Render web content in `view`. + * + * Both this method and [.onHideCustomView] are required for + * rendering web content in full screen. + * + * @see [](https://developer.android.com/reference/android/webkit/WebChromeClient.onShowCustomView + ) */ + override fun onShowCustomView(view: View, callback: CustomViewCallback) { + callback.onCustomViewHidden() + super.onShowCustomView(view, callback) + } + + /** + * Render web content in the original Web View again. + * + * Do not remove this method--@see #onShowCustomView(View, CustomViewCallback). + */ + override fun onHideCustomView() { + super.onHideCustomView() + } + + override fun onPermissionRequest(request: PermissionRequest) { + val requestedResources = request.resources + if (requestedResources.isEmpty()) { + request.deny() + return + } + + val allowedResources = ArrayList() + val defaultResources = ArrayList() + + for (resource in requestedResources) { + when (onPermissionRequestNative(webViewId, resource)) { + PERMISSION_REQUEST_DENY -> {} + PERMISSION_REQUEST_ALLOW -> allowedResources.add(resource) + PERMISSION_REQUEST_DEFAULT -> defaultResources.add(resource) + } + } + + val resources = + allowedResources.plus(filterKnownPermissions(defaultResources)).toList().toTypedArray() + grantPermissionRequest(request, resources) + } + + private fun grantPermissionRequest(request: PermissionRequest, resources: Array) { + if (resources.isEmpty()) { + request.deny() + return + } + + val isRequestPermissionRequired = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M + val permissionList = androidPermissionsForResources(resources) + if (permissionList.isNotEmpty() && isRequestPermissionRequired) { + val permissions = permissionList.toTypedArray() + activity.requestPermissions(permissions) { isGranted -> + if (isGranted == true) { + request.grant(resources) + } else { + request.deny() + } + } + } else { + request.grant(resources) + } + } + + private fun androidPermissionsForResources(resources: Array): MutableList { + val permissionList: MutableList = ArrayList() + if (resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) { + permissionList.add(Manifest.permission.CAMERA) + } + if (resources.contains(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) { + permissionList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS) + permissionList.add(Manifest.permission.RECORD_AUDIO) + } + return permissionList + } + + /** + * @return one of the PERMISSION_REQUEST_* constants. + */ + private external fun onPermissionRequestNative(webviewId: String, resource: String): Int + + override fun getDefaultVideoPoster(): Bitmap { + // Return a transparent bitmap so Chromium doesn't paint its default gray play-button placeholder on