Skip to content

Linux WPE WebKit Backend

The Linux package is the only ZikZak backend that renders through WPE WebKit, the WebKit port built for embedded and offscreen use. Every other platform in the federated plugin family binds a widget-hierarchy toolkit (Android WebView, Apple WKWebView, Windows WebView2); Linux instead creates a WebKitWebView with no GTK widget ancestry, exports each frame as a DMA-BUF buffer, and hands it to Flutter as a texture. That single architectural decision — offscreen rendering plus zero-copy texture sharing — drives the package’s build system, its dual backend API, its frame-path state machine, and its documented gaps. This page covers the native C++ layer under zikzak_inappwebview_linux/linux, the Dart platform implementation under lib/src, and the contract tooling that keeps the two wire-compatible with the upstream code the native layer was imported from.

Sources: README.md, in_app_webview.h

zikzak_inappwebview_linux is an endorsed implementation package: it declares implements: zikzak_inappwebview and registers both a native pluginClass (InAppWebViewFlutterPlugin) and a dartPluginClass (LinuxInAppWebViewPlatform), so an application that depends only on the umbrella package gets Linux support automatically. The Dart entry point is a thin factory table — every createPlatform* override returns a Linux-specific class, and unsupported Apple-only concepts return static stubs so isClassSupported probes do not throw.

graph TD
App["Flutter application"] --> Umbrella["zikzak_inappwebview (umbrella)"]
Umbrella --> PI["zikzak_inappwebview_platform_interface"]
Umbrella --> Linux["zikzak_inappwebview_linux"]
Linux -->|Dart| Factory["LinuxInAppWebViewPlatform"]
Factory --> Widget["LinuxInAppWebViewWidget"]
Factory --> Ctl["LinuxInAppWebViewController"]
Factory --> Cookie["LinuxCookieManager / WebStorage / Proxy"]
Widget -->|FlTextureRegistrar| Tex["EGL or pixel-buffer texture"]
Ctl -->|FlMethodChannel| Delegate["WebViewChannelDelegate"]
Cookie -->|FlMethodChannel| NativeMgr["Native managers"]
Delegate --> WebView["InAppWebView (C++)"]
Tex --> WebView
WebView -->|DMA-BUF / SHM| WPE["WPE WebKit WebProcess"]

The native side mirrors the Windows package’s manager pattern rather than a global singleton: a PluginInstance object is constructed with the FlPluginRegistrar* and then populated with pointers to each manager, which the plugin GObject owns. Cached GtkWindow* and FlView* are captured at registration time so headless webviews can exist without a window.

Sources: pubspec.yaml, inappwebview_platform.dart, plugin_instance.h, zikzak_inappwebview_linux_plugin.cc

WPE exposes two mutually exclusive host APIs, and the plugin resolves between them at CMake configure time using pkg-config plus a compile probe. wpe-platform-2.0 together with wpe-platform-headless-2.0 is the modern default (WPE WebKit 2.40+); wpebackend-fdo-1.0 is the legacy fallback. The critical subtlety is that a present pkg-config file does not prove WebKit was built with WPEPlatform support, so the build compiles and links a tiny program calling webkit_web_view_get_wpe_view() before defining HAVE_WPE_PLATFORM. If neither backend resolves, configuration fails with an explanatory FATAL_ERROR.

Detection outcome Compile definition Effect
wpe-platform-2.0 + headless found, probe links HAVE_WPE_PLATFORM=1 Modern API; FDO ignored even if installed
Probe fails or platform missing, wpebackend-fdo-1.0 found HAVE_WPE_BACKEND_LEGACY=1 Legacy loader path with wpe_loader_init
Neither found — Configuration aborts
wpe-webkit-2.0 missing (falls back 1.1 → 1.0) — Configuration aborts

The link set is completed by epoxy (GL/EGL without direct headers), gtk+-3.0 (GDK display access and event handling only), libwpe, wayland-server (SHM buffers), libsecret-1 (credential storage), and nlohmann/json 3.11.3 fetched via FetchContent. When WPE lives in a non-system prefix, that prefix’s lib directory is appended to BUILD_RPATH/INSTALL_RPATH and passed to the app link as -rpath-link, so flutter run works with no LD_LIBRARY_PATH. WPE itself is deliberately not bundled — the plugin’s bundled-library list is intentionally empty.

Sources: CMakeLists.txt, CMakeLists.txt, WPE_BACKEND.md

Frame delivery is the heart of the backend, and it is governed by one pure function. FramePathFor takes four booleans — EGL display available, buffer is DMA-BUF, a previous import failed, pixel readback required — and returns either kZeroCopyEgl or kPixelBuffer. The two paths are mutually exclusive per frame, and the header documents why: mixing them was the cause of a blank visible view (issue #442), because while an EGL image was imported no callback filled the CPU pixel buffer, leaving any texture that could not sample the image with nothing to draw.

stateDiagram-v2
[*] --> Evaluate
Evaluate --> PixelBuffer: pixel_readback_required
Evaluate --> PixelBuffer: no EGL display
Evaluate --> PixelBuffer: SHM buffer
Evaluate --> PixelBuffer: egl_import_failed
Evaluate --> ZeroCopy: DMA-BUF + display + clean
ZeroCopy --> Evaluate: next frame
PixelBuffer --> Evaluate: next frame
ZeroCopy --> PixelBuffer: texture import rejected (latch)

The modern arm lives in OnWpePlatformBufferRendered: it classifies the buffer with WPE_IS_BUFFER_DMA_BUF / WPE_IS_BUFFER_SHM, consults FramePathFor, and on the zero-copy branch calls wpe_buffer_import_to_egl_image. A failed import sets egl_import_failed_ per instance (a process-wide latch would disable zero-copy for every webview after one transient failure) and is cleared on web-process termination, since a restart recreates the EGL context. The SHM branch copies wpe_buffer_shm_get_data into a double-buffered pixel buffer and converts ARGB32→RGBA in place. The legacy arm makes the same keep-or-copy decision independently in OnExportDmaBuf, gated on IsPixelReadbackRequired() — the source comments are explicit that changing one arm does not change the other.

Sources: render_path.h, in_app_webview.cc, in_app_webview.cc, render_path_test.cc

Flutter receives frames through one of two FlTexture implementations, chosen by CustomPlatformView. InAppWebViewEGLTexture subclasses FlTextureGL and binds WPE’s EGL image with glEGLImageTargetTexture2DOES, eliminating the glReadPixels round-trip entirely. InAppWebViewTexture subclasses FlPixelBufferTexture and uploads the CPU copy. Because an EGL image only imports into a context that can reach the display it was created on, a rejected import is invisible to Flutter — the driver either raises a GL error or leaves the texture without storage, and the widget area simply stays black. The EGL texture therefore verifies the import two ways before accepting a frame: it reads glGetError() and it queries glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH/HEIGHT, …), caching the verified image pointer alongside the dimensions so a later same-size image that fails to bind cannot be accepted on an earlier success. On rejection, disable_zero_copy() latches zero_copy_disabled = TRUE, resets the texture dimensions to force reallocation, and calls SetPixelReadbackRequired(true) so the buffer callbacks start filling the pixel buffer.

Texture GL base type Source of pixels Requests CPU copy
InAppWebViewEGLTexture FlTextureGL EGL image bound to GL texture No (until latch trips)
InAppWebViewTexture FlPixelBufferTexture CPU pixel buffer Yes, always
InAppBrowser GL area GtkGLArea + shader Uploaded pixels Yes, always

Three environment variables, each read once at start-up, select the mode: ZIKZAK_INAPPWEBVIEW_LINUX_DISABLE_GL=1 selects the pixel-buffer texture, ZIKZAK_INAPPWEBVIEW_LINUX_DISABLE_ZERO_COPY=1 keeps the GL texture but uploads pixels from frame one, and LIBGL_ALWAYS_SOFTWARE=1 makes WPE render into SHM buffers. All GL entry is guarded by HasCurrentGLContext(), which resolves eglGetCurrentContext/glXGetCurrentContext through dlsym precisely because libepoxy’s wrappers assert a context is current.

Sources: inappwebview_egl_texture.h, inappwebview_egl_texture.cc, custom_platform_view.h, gl_context.h, README.md

Because WebKit’s WebProcess inherits environment variables at spawn time, software-rendering decisions must be made before any WPEDisplay exists. zikzak_inappwebview_linux_plugin_register_with_registrar calls ApplySoftwareRenderingIfNeeded() as its very first statement, before constructing the plugin object. The detector reads /sys/class/dmi/id/product_name and sys_vendor against a table of VM indicators (QEMU, KVM, VMware, VirtualBox, Parallels, Xen, Hyper-V, UTM, Bochs, …), checks /proc/cpuinfo for the hypervisor flag, and inspects /sys/class/drm/card0/device/driver — treating nvidia, nouveau, amdgpu, radeon, i915 and xe as known-good, and virtio/vmwgfx as problematic inside a VM. Two escape hatches exist: ZIKZAK_INAPPWEBVIEW_SKIP_DMABUF_CHECK=1 bypasses detection, and an already-set LIBGL_ALWAYS_SOFTWARE is never overridden.

Sources: zikzak_inappwebview_linux_plugin.cc, software_rendering.cc, software_rendering.h

The native layer separates one manager per channel domain from one instance per live object, with a shared ChannelDelegate base providing invokeMethod in both directions. InAppWebViewManager owns platform_views_ keyed by texture ID, keepAliveWebViews_ keyed by keep-alive ID, and windowWebViews_ keyed by window ID for popups created via onCreateWindow.

Native type Channel name Responsibility
InAppWebViewManager wtf.zikzak/zikzak_inappwebview_manager Create/dispose webviews, keep-alive store, popup transports
InAppWebView wtf.zikzak/zikzak_inappwebview_<id> The WebKitWebView itself, ~8.3k lines
HeadlessInAppWebViewManager wtf.zikzak/flutter_headless_inappwebview Offscreen instances keyed by string ID
InAppBrowserManager — GTK windows with embedded WPE view
CookieManager wtf.zikzak/zikzak_inappwebview_cookiemanager WebKitCookieManager + libsoup SoupCookie
CredentialDatabase wtf.zikzak/zikzak_inappwebview_credential_database HTTP auth secrets in libsecret keyring
ProxyManager wtf.zikzak/zikzak_inappwebview_proxycontroller WebKitNetworkProxySettings overrides
WebStorageManager — WebKitWebsiteDataManager records
WebViewEnvironment wtf.zikzak/flutter_webview_environment Per-ID WebKitWebContext (unsupported on Linux)
FindInteractionController wtf.zikzak/zikzak_inappwebview_find_interaction_<id> WebKitFindController sessions

HeadlessInAppWebView is explicitly a thin wrapper: the header states it is “essentially InAppWebView without texture registration,” which is possible only because WPE is inherently offscreen. CustomPlatformView additionally carries the keep-alive ID, the method channel for pointer/size events, and an FlEventChannel for cursor changes.

Sources: types/channel_delegate.h, in_app_webview_manager.h, headless_in_app_webview.h, cookie_manager.h, credential_database.h, proxy_manager.h

Disposal, Lifetime Fencing, and Custom Schemes

Section titled “Disposal, Lifetime Fencing, and Custom Schemes”

Destruction is ordered around a lifetime_flag_ shared pointer plus an atomic is_disposing_. The destructor first sets both, so any evaluate_javascript, timer, or content-blocker compile callback that fires afterwards bails out on its captured guard instead of touching freed memory. Content-blocker application in the constructor demonstrates the pattern: the initial load is deferred into the setContentBlockers completion callback, guarded by lifetime_flag_, and skipped entirely if the webview was disposed while filters compiled. A separate pending_compiles_ set nulls each context’s handler pointer in the ContentBlockerHandler destructor so the async onFilterCompiled can never reach a freed handler.

Custom URI schemes need special handling because WebKit has no unregister API and schemes are registered on the shared WebKitWebContext, which outlives individual webviews. A process-wide mutex-guarded registry maps (WebKitWebContext*, scheme) to the owning InAppWebView*, and the destructor removes the entry so the static handler never resolves a dangling owner.

Sources: in_app_webview.cc, in_app_webview.cc, in_app_webview.cc, content_blocker_handler.h

The native C++ was imported from flutter_inappwebview_linux 0.1.0-beta.1 and mechanically renamed, so its wire shapes are upstream’s rather than ZikZak’s generated types. lib/src/util/wire.dart is the adapter seam that reconciles them, and tool/wire_parity is a dev-only package that proves the reconciliation is complete. It compares upstream’s toMap()/toNativeValue() against ZikZak’s toJson()/xxxToWire() in both directions with strict comparison (2 vs "2", true vs "true", 4 vs 4.0, List<int> vs Uint8List all differ); every differing path must be explained by a knownDifferences entry naming the adapter that resolves it, and an unlisted difference fails the test. tool/rename_upstream.sh is the idempotent re-application of ZikZak’s names after a fresh upstream import, including the JS bridge global rename to window.zikzak_inappwebview.

Adapter Reconciles
wireMap / fromWire Deep Map<Object?,Object?> → Map<String,dynamic>
userScriptToWire Fills default contentWorld: {name: page}
inAppWebViewSettingsToWire Drops iOS/web-only keys native never reads
withAjaxEventFlags Adds useOnAjaxReadyStateChange / useOnAjaxProgress
proxySettingsToWire ZikZak’s ProxySettings → {bypassRules, proxyRules}
permissionRequestFromWire Native int resource types → enum subset

Three upstream-only settings silently take WPE’s native defaults because ZikZak cannot send them: allowModalDialogs (native true vs upstream Dart false), enable2DCanvasAcceleration (native true vs false), and enableEncryptedMedia (native false vs true).

Sources: wire.dart, wire_parity/README.md, wire_parity/README.md, rename_upstream.sh

InAppWebViewSettings exists as a hand-written C++ class separate from the shared interface, mapping Dart settings onto WebKitSettings plus a WPEPlatform block (darkMode, disableAnimations, font hinting/subpixel/DPI, cursor blink, double-click thresholds, drag threshold, key repeat) applied via applyWpePlatformSettings only when HAVE_WPE_PLATFORM is defined. Missing keys are safe by construction: every parse uses get_fl_map_value or a fl_map_contains_not_null guard, so a key ZikZak never sends leaves the member at its native default.

Keyboard input is translated in Dart, not C++: key_mappings.dart maps USB HID usage codes to Linux evdev scancodes (X11 keycode = evdev + 8) and produces X11 keysyms, using the Unicode code point directly for printable characters and a 0xFF00+ table for special keys. Native logging follows a process-wide atomic flag set from PlatformInAppWebViewController.debugLoggingSettings.enabled on every webview, headless webview and browser creation; info logs are suppressed unless the flag is on, while errors always print in release builds too. The few start-up lines (GPU detection) run before any setting can arrive and therefore follow the build default.

Sources: in_app_webview_settings.h, key_mappings.dart, log.h, debug_logging.dart

Testing is layered. The frame-path decision is unit-tested in C++ as a truth table plus an exhaustive 16-case mask over all four booleans; the wiring around that decision is asserted by Dart source-contract tests that read the .cc files as text (the test file itself is candid that a green run is evidence about shape, never about behaviour). Dart unit tests cover the controller, cookies, debug logging, headless lifecycle, Linux-only methods and the wire adapters, and the example app ships an integration test that drives a real loopback HTTP server to verify header preservation, HttpOnly cookie survival across navigation, document-start script ordering, JS bridge round-trip and navigation cancellation.

The documented gaps all trace back to WPE or interface limits: createPdf returns null (no print-to-PDF API), onShowFileChooser is not exposed so <input type="file"> opens the native GTK chooser, WebViewEnvironment throws UnimplementedError, geolocation/notification/device-info/pointer-lock permission resources arrive as an empty list, URLProtectionSpace authentication-method strings and ClientCertChallenge.isProxy are dropped, and setCookie’s maxAge is converted in Dart to an absolute expiresDate because native never reads it. Manual verification of the visual behaviours automated tests cannot see follows a 14-row checklist in the package README, run at both 1x and 2x scaling.

Sources: README.md, linux_frame_path_contract_test.dart, native_navigation_test.dart, CMakeLists.txt

Continue with Windows WebView2 Facade and the DevTools Fork for the contrasting texture-and-GPU story on a second desktop backend, or Web and OpenHarmony (ArkWeb) Implementations for the two non-native ends of the matrix. For the shared contract this package adapts against, read The Platform Interface: The Contract Seam; for the lifecycle semantics that lifetime_flag_ implements, read Disposal Lifecycle and KeepAlive Patterns. The offscreen capability that makes HeadlessInAppWebView trivial here is generalised in Headless WebView and the Live-Instance Cap, and the filter compilation deferred in the constructor is covered comparatively in Content Blockers, Proxy, and Tracing.