From 0966c6de175d54c560cf749ec9b2a2357c851921 Mon Sep 17 00:00:00 2001 From: yc Date: Sat, 7 Nov 2026 19:49:09 +0100 Subject: [PATCH] browser export --- CHANGELOG.md | 9 + CLAUDE.md | 19 +- README.md | 41 +++- .../cesiumjs/CesiumjsPlugin.kt | 43 +++- lib/cesiumjs.dart | 5 +- lib/src/cesium_viewer.dart | 175 ++------------ lib/src/native_channel.dart | 21 +- lib/src/native_web_view.dart | 217 ++++++++++++++++++ lib/src/web_browser.dart | 112 +++++++++ linux/cesiumjs_plugin.cc | 59 ++++- pubspec.yaml | 4 +- test/native_web_view_test.dart | 69 ++++++ windows/cesiumjs_plugin.cpp | 73 ++++-- 13 files changed, 640 insertions(+), 207 deletions(-) create mode 100644 lib/src/native_web_view.dart create mode 100644 lib/src/web_browser.dart create mode 100644 test/native_web_view_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d02579..ce092b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## 0.3.0 + +* `WebBrowserView` / `WebBrowserController`: a web page (URL) in the same + native web view as the globe. The native `create` call accepts `url` + instead of `html`; new `loadUrl` and `reload` methods. +* Linux/Windows: native views also hide while a dialog or popup menu route + covers their own route. +* `CesiumViewer` now builds on the shared `NativeWebViewHost`. + ## 0.2.0 * Android support: system `WebView` shown as a platform view (Flutter widgets diff --git a/CLAUDE.md b/CLAUDE.md index b405dd0..e8e1b7f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,7 @@ # CLAUDE.md -Flutter **plugin** (Linux, Android, Windows) embedding a CesiumJS globe. The +Flutter **plugin** (Linux, Android, Windows) embedding a CesiumJS globe, and +a plain web page (`WebBrowserView`) in the same native web views. The package is meant to be imported by other apps: keep the public API in `lib/cesiumjs.dart` small and stable; everything else stays in `lib/src/`. `example/` is the test/demo app, not part of the package. @@ -30,13 +31,19 @@ Android test emulator: AVD `cesium_test` (API 35, x86_64), lives in All platforms share the `cesiumjs/webview` channel protocol (`create` eagerly builds the web view keyed by a Dart id; other calls address it by id). -- `CesiumViewer` (Dart) renders a black placeholder and reports its global - rect after each paint (`_RenderRectReporter`) → `setRect` over the - `cesiumjs/webview` method channel. +- `NativeWebViewHost` (`native_web_view.dart`, internal) owns one native + view: renders a placeholder, reports its global rect after each paint + (`_RenderRectReporter`) → `setRect` over the `cesiumjs/webview` method + channel, and hides the view (desktop) when `visible` is false, tickers are + muted or its route isn't current (dialog/menu on top). `CesiumViewer` and + `WebBrowserView` are thin wrappers around it. +- `create` takes either `html` (Cesium page, served from the virtual origin) + or `url` (browser view: network page, links opening a window load in place + instead of going to the system browser, no black background). - `linux/cesiumjs_plugin.cc` creates one `WebKitWebView` per viewer inside a `GtkOverlay` that holds the `FlView`; `get-child-position` places it at the - reported rect. Methods: `create`, `setRect`, `runJavaScript`, - `openInspector`, `dispose`, `disposeAll` (called once per isolate so hot + reported rect. Methods: `create`, `setRect`, `runJavaScript`, `loadUrl`, + `reload`, `openInspector`, `dispose`, `disposeAll` (called once per isolate so hot restart doesn't leave orphan views). Events back to Dart: `onMessage`, `onError`. - Android (`android/…/CesiumjsPlugin.kt`): `create` builds an diff --git a/README.md b/README.md index bbf67a7..818d7e9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # cesiumjs A Flutter plugin that embeds a [CesiumJS](https://cesium.com/platform/cesiumjs/) -3D globe in Flutter apps on **Linux, Windows and Android**. +3D globe in Flutter apps on **Linux, Windows and Android**. It also +provides `WebBrowserView`, a plain web page shown by the same engines. | Platform | Web engine | Integration | Status | |---|---|---|---| @@ -107,6 +108,35 @@ class _GlobePageState extends State { Controller calls are only valid after `onReady` (or `isReady == true`). +### `WebBrowserView` + +A web page in the same native web view as the globe (WebKitGTK, WebView2, +Android WebView), with the same layering rules (see Limitations). + +```dart +WebBrowserView(url: 'https://example.com', controller: browserController) +``` + +| Parameter | Description | +|---|---| +| `url` | Page to load; changing it navigates the view | +| `controller` | A `WebBrowserController` | +| `onError` | Page load failures and web process crashes | +| `visible` | Hides the web view without destroying it | + +Links that would open a new window load in the view itself. + +| `WebBrowserController` | Description | +|---|---| +| `loadUrl(url)` | Navigates to `url` | +| `reload()` | Reloads the page | +| `runJavaScript(script)` | Runs JS in the page, returns the result as a string | +| `openInspector()` | Dev tools (no-op on Android) | +| `isAttached` | Whether the controller drives a live view | + +`nativeWebViewSupported` tells whether the current platform has native web +views. + ### Messages from JavaScript The page calls `CesiumChannel.postMessage(obj)`; objects are sent as JSON and @@ -125,9 +155,9 @@ Your own scripts (via `runJavaScript`) can post custom types the same way. - **Linux and Windows: Flutter widgets cannot be drawn over the globe**: the web view is a native window above the Flutter surface. Put controls around - it, or set `visible: false` while a dialog, menu or drawer overlaps it. The - view is hidden automatically when another route is pushed on top. (Android - has no such restriction.) + it, or set `visible: false` while a drawer or overlay overlaps it. The + view is hidden automatically when another route is pushed on top, including + dialogs and popup menus. (Android has no such restriction.) - Linux and Windows: the widget is positioned in window coordinates; don't place it inside a scroll view that clips it. - One Flutter view per app (the default) is supported. @@ -170,6 +200,9 @@ lib/ src/cesium_controller.dart CesiumController, CesiumMessage, CesiumImagery src/cesium_html.dart HTML page hosting Cesium (CDN version pinned here) src/native_channel.dart `cesiumjs/webview` method channel wrapper + src/native_web_view.dart NativeWebViewHost: creates/places/hides one + native view (shared by both widgets) + src/web_browser.dart WebBrowserView, WebBrowserController linux/ cesiumjs_plugin.cc WebKitGTK views in a GtkOverlay over the FlView android/src/main/kotlin/…/CesiumjsPlugin.kt diff --git a/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt b/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt index af565c9..d748160 100644 --- a/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt +++ b/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt @@ -79,13 +79,16 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA when (call.method) { "create" -> { val html = call.argument("html") - if (id == null || html == null) { - result.error("bad_args", "create requires id and html", null) + // A url makes a browser view: loaded from the network, links + // stay in the view. + val url = call.argument("url") + if (id == null || (html == null && url == null)) { + result.error("bad_args", "create requires id and html or url", null) } else if (views.containsKey(id)) { result.error("exists", "a view with this id already exists", null) } else { val baseUrl = call.argument("baseUrl") ?: BASE_URL - views[id] = createWebView(id, html, baseUrl) + views[id] = createWebView(id, html, baseUrl, url) result.success(null) } } @@ -101,6 +104,27 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA } } } + "loadUrl" -> { + val view = views[id] + val url = call.argument("url") + when { + view == null -> result.error("not_found", "unknown view id", null) + url == null -> result.error("bad_args", "url missing", null) + else -> { + view.loadUrl(url) + result.success(null) + } + } + } + "reload" -> { + val view = views[id] + if (view == null) { + result.error("not_found", "unknown view id", null) + } else { + view.reload() + result.success(null) + } + } // No in-app inspector on Android: use chrome://inspect (debug builds). "openInspector" -> result.success(null) "dispose" -> { @@ -116,9 +140,10 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA } @SuppressLint("SetJavaScriptEnabled") - private fun createWebView(id: Int, html: String, baseUrl: String): WebView { + private fun createWebView(id: Int, html: String?, baseUrl: String, url: String?): WebView { + val browser = url != null val view = WebView(activityContext ?: appContext) - view.setBackgroundColor(Color.BLACK) + if (!browser) view.setBackgroundColor(Color.BLACK) view.settings.apply { javaScriptEnabled = true domStorageEnabled = true @@ -138,7 +163,7 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA v: WebView, request: WebResourceRequest, ): Boolean { - if (!request.isForMainFrame) return false + if (browser || !request.isForMainFrame) return false try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(request.url.toString())) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) @@ -168,7 +193,11 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA return true // keep the app alive } } - view.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null) + if (url != null) { + view.loadUrl(url) + } else { + view.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null) + } return view } diff --git a/lib/cesiumjs.dart b/lib/cesiumjs.dart index a2d5dd3..7a7760a 100644 --- a/lib/cesiumjs.dart +++ b/lib/cesiumjs.dart @@ -1,7 +1,10 @@ -/// CesiumJS globe for Flutter (Linux desktop, via WebKitGTK). +/// CesiumJS globe and web browser views for Flutter (Linux: WebKitGTK, +/// Windows: WebView2, Android: system WebView). library; export 'src/cesium_controller.dart' show CesiumController, CesiumImagery, CesiumMessage; export 'src/cesium_html.dart' show cesiumVersion; export 'src/cesium_viewer.dart' show CesiumViewer; +export 'src/native_web_view.dart' show nativeWebViewSupported; +export 'src/web_browser.dart' show WebBrowserController, WebBrowserView; diff --git a/lib/src/cesium_viewer.dart b/lib/src/cesium_viewer.dart index d8bbab5..1862c7f 100644 --- a/lib/src/cesium_viewer.dart +++ b/lib/src/cesium_viewer.dart @@ -1,12 +1,9 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; import 'cesium_controller.dart'; import 'cesium_html.dart'; import 'native_channel.dart'; +import 'native_web_view.dart'; /// Displays a CesiumJS globe. /// @@ -20,7 +17,8 @@ import 'native_channel.dart'; /// Flutter surface and kept aligned with this widget's rectangle. /// Consequences: /// * Flutter widgets cannot be drawn on top of the globe (put overlays -/// around it, or set [visible] to false while a dialog/menu is open). +/// around it, or set [visible] to false). The view hides itself while +/// another route (dialog, popup menu) covers its own. /// * The rectangle is in window coordinates, so the widget should not be /// clipped by a scroll view. class CesiumViewer extends StatefulWidget { @@ -52,44 +50,6 @@ class CesiumViewer extends StatefulWidget { class _CesiumViewerState extends State { late final CesiumController _controller = widget.controller ?? CesiumController(); - int? _viewId; - bool _disposed = false; - Rect? _sentRect; - bool? _sentVisible; - double? _sentScale; - Rect _currentRect = Rect.zero; - - static bool get _supported => - !kIsWeb && - (defaultTargetPlatform == TargetPlatform.linux || - defaultTargetPlatform == TargetPlatform.windows || - defaultTargetPlatform == TargetPlatform.android); - - /// Android composes the web view as a platform view; the desktop - /// platforms place a native view over the reported rectangle. - static bool get _isPlatformView => - defaultTargetPlatform == TargetPlatform.android; - - @override - void initState() { - super.initState(); - if (_supported) _create(); - } - - Future _create() async { - final id = await CesiumNativeChannel.instance.create( - buildCesiumHtml(ionToken: widget.ionToken), - _onNativeEvent, - ); - if (_disposed) { - await CesiumNativeChannel.instance.dispose(id); - return; - } - _controller.attach(id); - // Rebuild: on Android the platform view can be created now. - setState(() => _viewId = id); - _sync(); - } void _onNativeEvent(String event, String message) { if (event == 'onError') { @@ -103,132 +63,25 @@ class _CesiumViewerState extends State { widget.onMessage?.call(msg); } - void _onRectChanged(Rect rect) { - _currentRect = rect; - _sync(); - } - - bool get _effectiveVisible => - widget.visible && TickerMode.valuesOf(context).enabled; - - void _sync() { - final id = _viewId; - if (id == null || _disposed || _isPlatformView) return; - final visible = _effectiveVisible; - final scale = MediaQuery.devicePixelRatioOf(context); - if (_sentRect == _currentRect && - _sentVisible == visible && - _sentScale == scale) { - return; - } - _sentRect = _currentRect; - _sentVisible = visible; - _sentScale = scale; - CesiumNativeChannel.instance.setRect( - id, - _currentRect, - visible: visible, - scale: scale, - ); - } - - @override - void didUpdateWidget(CesiumViewer oldWidget) { - super.didUpdateWidget(oldWidget); - _sync(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - // TickerMode changes when a route is pushed on top of this one. - if (_viewId != null) _sync(); - } - @override void dispose() { - _disposed = true; - final id = _viewId; - if (id != null) CesiumNativeChannel.instance.dispose(id); - _controller.detach(); if (widget.controller == null) _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - if (!_supported) { - return const ColoredBox( - color: Colors.black, - child: Center( - child: Text( - 'CesiumViewer supports Linux, Windows and Android only.', - style: TextStyle(color: Colors.white70), - ), - ), - ); - } - if (_isPlatformView) { - final id = _viewId; - if (id == null) { - return const SizedBox.expand(child: ColoredBox(color: Colors.black)); - } - return Visibility( - visible: _effectiveVisible, - maintainState: true, - child: AndroidView( - viewType: CesiumNativeChannel.viewType, - creationParams: {'id': id}, - creationParamsCodec: const StandardMessageCodec(), - // The globe handles every gesture that starts on it. - gestureRecognizers: { - Factory(EagerGestureRecognizer.new), - }, - ), - ); - } - // SizedBox.expand: a childless ColoredBox would size to 0x0 under loose - // constraints, which hides the native view. - return _RectReporter( - onRectChanged: _onRectChanged, - child: const SizedBox.expand(child: ColoredBox(color: Colors.black)), + return NativeWebViewHost( + create: (onEvent) => CesiumNativeChannel.instance.create( + onEvent, + html: buildCesiumHtml(ionToken: widget.ionToken), + ), + onEvent: _onNativeEvent, + onCreated: _controller.attach, + onDisposed: _controller.detach, + visible: widget.visible, + unsupportedMessage: + 'CesiumViewer supports Linux, Windows and Android only.', ); } } - -/// Reports its global (window) rectangle after every paint. -class _RectReporter extends SingleChildRenderObjectWidget { - const _RectReporter({required this.onRectChanged, super.child}); - - final ValueChanged onRectChanged; - - @override - RenderObject createRenderObject(BuildContext context) => - _RenderRectReporter(onRectChanged); - - @override - void updateRenderObject( - BuildContext context, - _RenderRectReporter renderObject, - ) => renderObject.onRectChanged = onRectChanged; -} - -class _RenderRectReporter extends RenderProxyBox { - _RenderRectReporter(this.onRectChanged); - - ValueChanged onRectChanged; - Rect? _last; - - @override - void paint(PaintingContext context, Offset offset) { - super.paint(context, offset); - final rect = localToGlobal(Offset.zero) & size; - if (rect != _last) { - _last = rect; - // Can't call out to the platform mid-paint; do it after the frame. - WidgetsBinding.instance.addPostFrameCallback((_) { - if (attached) onRectChanged(rect); - }); - } - } -} diff --git a/lib/src/native_channel.dart b/lib/src/native_channel.dart index 2964236..9574d2e 100644 --- a/lib/src/native_channel.dart +++ b/lib/src/native_channel.dart @@ -29,14 +29,31 @@ class CesiumNativeChannel { Future _ensureReset() => _reset ??= _channel.invokeMethod('disposeAll'); - Future create(String html, NativeEventHandler onEvent) async { + /// Creates a view showing [html] (served from `https://cesium.localhost/`) + /// or, for a browser view, loading [url]. Exactly one must be given. + Future create( + NativeEventHandler onEvent, { + String? html, + String? url, + }) async { + assert((html == null) != (url == null), 'give either html or url'); await _ensureReset(); final id = _nextId++; _handlers[id] = onEvent; - await _channel.invokeMethod('create', {'id': id, 'html': html}); + await _channel.invokeMethod('create', { + 'id': id, + 'html': ?html, + 'url': ?url, + }); return id; } + Future loadUrl(int id, String url) => + _channel.invokeMethod('loadUrl', {'id': id, 'url': url}); + + Future reload(int id) => + _channel.invokeMethod('reload', {'id': id}); + /// [rect] is in logical pixels relative to the Flutter view; [scale] is /// its device pixel ratio (used by Windows, where windows use physical /// pixels). diff --git a/lib/src/native_web_view.dart b/lib/src/native_web_view.dart new file mode 100644 index 0000000..768a625 --- /dev/null +++ b/lib/src/native_web_view.dart @@ -0,0 +1,217 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; + +import 'native_channel.dart'; + +/// Whether native web views are available on this platform. +bool get nativeWebViewSupported => + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.android); + +/// Android composes the web view as a platform view; the desktop platforms +/// place a native view over the reported rectangle. +bool get _isPlatformView => defaultTargetPlatform == TargetPlatform.android; + +/// Hosts one native web view (shared by `CesiumViewer` and `WebBrowserView`). +/// +/// [create] builds the native view and returns its id; [onCreated] and +/// [onDisposed] bracket its life, [onEvent] receives the native events +/// (`onMessage`, `onError`). +/// +/// On Linux and Windows the native view is stacked above the Flutter surface, +/// so it is hidden while [visible] is false, while tickers are muted (route +/// pushed on top) and while another route (dialog, popup menu) covers this +/// one: Flutter could not draw it over the web view. +class NativeWebViewHost extends StatefulWidget { + const NativeWebViewHost({ + super.key, + required this.create, + required this.onEvent, + this.onCreated, + this.onDisposed, + this.visible = true, + this.background = Colors.black, + this.unsupportedMessage = 'Web views are supported on Linux, Windows and ' + 'Android only.', + }); + + final Future Function(NativeEventHandler onEvent) create; + final NativeEventHandler onEvent; + final ValueChanged? onCreated; + final VoidCallback? onDisposed; + final bool visible; + + /// Color shown before the view exists and where it is not supported. + final Color background; + final String unsupportedMessage; + + @override + State createState() => _NativeWebViewHostState(); +} + +class _NativeWebViewHostState extends State { + int? _viewId; + bool _disposed = false; + Rect? _sentRect; + bool? _sentVisible; + double? _sentScale; + Rect _currentRect = Rect.zero; + + @override + void initState() { + super.initState(); + if (nativeWebViewSupported) _create(); + } + + Future _create() async { + final id = await widget.create((event, message) { + if (!_disposed) widget.onEvent(event, message); + }); + if (_disposed) { + await CesiumNativeChannel.instance.dispose(id); + return; + } + widget.onCreated?.call(id); + // Rebuild: on Android the platform view can be created now. + setState(() => _viewId = id); + _sync(); + } + + void _onRectChanged(Rect rect) { + _currentRect = rect; + _sync(); + } + + bool get _effectiveVisible => + widget.visible && + TickerMode.valuesOf(context).enabled && + // Desktop: a dialog or menu over this route would be hidden by the + // native view. Android composes it, so it can stay. + (_isPlatformView || (ModalRoute.isCurrentOf(context) ?? true)); + + void _sync() { + final id = _viewId; + if (id == null || _disposed || _isPlatformView || !mounted) return; + final visible = _effectiveVisible; + final scale = MediaQuery.devicePixelRatioOf(context); + if (_sentRect == _currentRect && + _sentVisible == visible && + _sentScale == scale) { + return; + } + _sentRect = _currentRect; + _sentVisible = visible; + _sentScale = scale; + CesiumNativeChannel.instance.setRect( + id, + _currentRect, + visible: visible, + scale: scale, + ); + } + + @override + void didUpdateWidget(NativeWebViewHost oldWidget) { + super.didUpdateWidget(oldWidget); + _sync(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // TickerMode and ModalRoute.isCurrent change when a route is pushed. + if (_viewId != null) _sync(); + } + + @override + void dispose() { + _disposed = true; + final id = _viewId; + if (id != null) { + CesiumNativeChannel.instance.dispose(id); + widget.onDisposed?.call(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final background = SizedBox.expand( + child: ColoredBox(color: widget.background), + ); + if (!nativeWebViewSupported) { + return ColoredBox( + color: widget.background, + child: Center( + child: Text( + widget.unsupportedMessage, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.grey), + ), + ), + ); + } + if (_isPlatformView) { + final id = _viewId; + if (id == null) return background; + return Visibility( + visible: _effectiveVisible, + maintainState: true, + child: AndroidView( + viewType: CesiumNativeChannel.viewType, + creationParams: {'id': id}, + creationParamsCodec: const StandardMessageCodec(), + // The page handles every gesture that starts on it. + gestureRecognizers: { + Factory(EagerGestureRecognizer.new), + }, + ), + ); + } + // SizedBox.expand: a childless ColoredBox would size to 0x0 under loose + // constraints, which hides the native view. + return _RectReporter(onRectChanged: _onRectChanged, child: background); + } +} + +/// Reports its global (window) rectangle after every paint. +class _RectReporter extends SingleChildRenderObjectWidget { + const _RectReporter({required this.onRectChanged, super.child}); + + final ValueChanged onRectChanged; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderRectReporter(onRectChanged); + + @override + void updateRenderObject( + BuildContext context, + _RenderRectReporter renderObject, + ) => renderObject.onRectChanged = onRectChanged; +} + +class _RenderRectReporter extends RenderProxyBox { + _RenderRectReporter(this.onRectChanged); + + ValueChanged onRectChanged; + Rect? _last; + + @override + void paint(PaintingContext context, Offset offset) { + super.paint(context, offset); + final rect = localToGlobal(Offset.zero) & size; + if (rect != _last) { + _last = rect; + // Can't call out to the platform mid-paint; do it after the frame. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (attached) onRectChanged(rect); + }); + } + } +} diff --git a/lib/src/web_browser.dart b/lib/src/web_browser.dart new file mode 100644 index 0000000..5c6f4f7 --- /dev/null +++ b/lib/src/web_browser.dart @@ -0,0 +1,112 @@ +import 'package:flutter/material.dart'; + +import 'native_channel.dart'; +import 'native_web_view.dart'; + +/// Drives a [WebBrowserView] from Dart. +class WebBrowserController { + int? _viewId; + + /// Whether the controller is attached to a live web view. + bool get isAttached => _viewId != null; + + int get _id { + final id = _viewId; + if (id == null) { + throw StateError('WebBrowserController is not attached to a view'); + } + return id; + } + + /// Navigates to [url]. + Future loadUrl(String url) => + CesiumNativeChannel.instance.loadUrl(_id, url); + + /// Reloads the current page. + Future reload() => CesiumNativeChannel.instance.reload(_id); + + /// Runs [script] in the current page and returns the result as a string + /// (null for undefined/null). The last expression must not be a Promise. + Future runJavaScript(String script) => + CesiumNativeChannel.instance.runJavaScript(_id, script); + + /// Opens the dev tools (no-op on Android, use chrome://inspect). + Future openInspector() async { + final id = _viewId; + if (id != null) await CesiumNativeChannel.instance.openInspector(id); + } +} + +/// A web page, rendered by the same engine as `CesiumViewer`: WebKitGTK on +/// Linux, the system WebView on Android, WebView2 on Windows. +/// +/// Changing [url] navigates the view; links that would open a new window +/// load in place. The same layering rules as `CesiumViewer` apply on Linux +/// and Windows (nothing can be drawn over the page). +class WebBrowserView extends StatefulWidget { + const WebBrowserView({ + super.key, + required this.url, + this.controller, + this.onError, + this.visible = true, + }); + + final String url; + final WebBrowserController? controller; + + /// Page load failures and web process crashes. + final ValueChanged? onError; + + /// Hides the web view without destroying it (keeps the page). + final bool visible; + + @override + State createState() => _WebBrowserViewState(); +} + +class _WebBrowserViewState extends State { + late WebBrowserController _controller = + widget.controller ?? WebBrowserController(); + String? _createdUrl; + + @override + void didUpdateWidget(WebBrowserView oldWidget) { + super.didUpdateWidget(oldWidget); + final newController = widget.controller ?? _controller; + if (newController != _controller) { + newController._viewId = _controller._viewId; + _controller._viewId = null; + _controller = newController; + } + if (widget.url != oldWidget.url && _controller.isAttached) { + _controller.loadUrl(widget.url); + } + } + + void _onNativeEvent(String event, String message) { + if (event == 'onError') widget.onError?.call(message); + } + + @override + Widget build(BuildContext context) { + return NativeWebViewHost( + create: (onEvent) { + _createdUrl = widget.url; + return CesiumNativeChannel.instance.create(onEvent, url: widget.url); + }, + onEvent: _onNativeEvent, + onCreated: (id) { + _controller._viewId = id; + // The url may have changed while the view was being created. + if (!mounted) return; + if (widget.url != _createdUrl) _controller.loadUrl(widget.url); + }, + onDisposed: () => _controller._viewId = null, + visible: widget.visible, + background: Colors.white, + unsupportedMessage: 'WebBrowserView supports Linux, Windows and ' + 'Android only.', + ); + } +} diff --git a/linux/cesiumjs_plugin.cc b/linux/cesiumjs_plugin.cc index ad6dad4..2803f20 100644 --- a/linux/cesiumjs_plugin.cc +++ b/linux/cesiumjs_plugin.cc @@ -10,6 +10,7 @@ namespace { constexpr char kChannelName[] = "cesiumjs/webview"; constexpr char kMessageHandlerName[] = "cesium"; constexpr char kRectKey[] = "cesium-rect"; +constexpr char kBrowserKey[] = "cesium-browser"; struct Plugin { GtkOverlay* overlay = nullptr; @@ -112,9 +113,10 @@ void on_web_process_terminated(WebKitWebView* view, send_event("onError", view_id(view), msg); } -// Keep the web view from opening a new window when CesiumJS links are clicked -// (credits, help...): open them in the user's browser instead. -gboolean on_decide_policy(WebKitWebView*, WebKitPolicyDecision* decision, +// Keep the web view from opening a new window. Cesium pages (credits, +// help...) send the link to the user's browser; browser views (created with a +// url) load it in place. +gboolean on_decide_policy(WebKitWebView* view, WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer) { if (type != WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) return FALSE; auto* nav = WEBKIT_NAVIGATION_POLICY_DECISION(decision); @@ -123,7 +125,11 @@ gboolean on_decide_policy(WebKitWebView*, WebKitPolicyDecision* decision, WebKitURIRequest* request = webkit_navigation_action_get_request(action); const gchar* uri = webkit_uri_request_get_uri(request); if (uri != nullptr) { - g_app_info_launch_default_for_uri(uri, nullptr, nullptr); + if (g_object_get_data(G_OBJECT(view), kBrowserKey) != nullptr) { + webkit_web_view_load_uri(view, uri); + } else { + g_app_info_launch_default_for_uri(uri, nullptr, nullptr); + } } webkit_policy_decision_ignore(decision); return TRUE; @@ -145,9 +151,12 @@ FlMethodResponse* create_view(FlValue* args) { int64_t id = get_int(args, "id"); const gchar* html = get_string(args, "html"); const gchar* base_url = get_string(args, "baseUrl"); - if (id < 0 || html == nullptr) { + // A url makes a browser view: the page is loaded from the network, links + // opening a window stay in the view. + const gchar* url = get_string(args, "url"); + if (id < 0 || (html == nullptr && url == nullptr)) { return FL_METHOD_RESPONSE(fl_method_error_response_new( - "bad_args", "create requires id and html", nullptr)); + "bad_args", "create requires id and html or url", nullptr)); } if (g_plugin->views.count(id)) { return FL_METHOD_RESPONSE(fl_method_error_response_new( @@ -183,17 +192,25 @@ FlMethodResponse* create_view(FlValue* args) { nullptr); g_signal_connect(view, "realize", G_CALLBACK(on_view_realize), nullptr); - // Black background so there is no white flash before CesiumJS draws. - GdkRGBA black = {0, 0, 0, 1}; - webkit_web_view_set_background_color(view, &black); + if (url != nullptr) { + g_object_set_data(G_OBJECT(view), kBrowserKey, GINT_TO_POINTER(1)); + } else { + // Black background so there is no white flash before CesiumJS draws. + GdkRGBA black = {0, 0, 0, 1}; + webkit_web_view_set_background_color(view, &black); + } gtk_overlay_add_overlay(g_plugin->overlay, GTK_WIDGET(view)); // Hidden until Dart reports a non-empty rectangle. gtk_widget_set_no_show_all(GTK_WIDGET(view), TRUE); gtk_widget_hide(GTK_WIDGET(view)); - webkit_web_view_load_html(view, html, - base_url ? base_url : "https://cesium.localhost/"); + if (url != nullptr) { + webkit_web_view_load_uri(view, url); + } else { + webkit_web_view_load_html( + view, html, base_url ? base_url : "https://cesium.localhost/"); + } g_plugin->views[id] = view; return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } @@ -288,6 +305,26 @@ void method_call_cb(FlMethodChannel*, FlMethodCall* call, gpointer) { g_object_ref(call)); return; // answered asynchronously } + } else if (strcmp(method, "loadUrl") == 0) { + WebKitWebView* view = find_view(args); + const gchar* url = get_string(args, "url"); + if (view == nullptr) { + response = not_found(); + } else if (url == nullptr) { + response = FL_METHOD_RESPONSE( + fl_method_error_response_new("bad_args", "url missing", nullptr)); + } else { + webkit_web_view_load_uri(view, url); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } + } else if (strcmp(method, "reload") == 0) { + WebKitWebView* view = find_view(args); + if (view == nullptr) { + response = not_found(); + } else { + webkit_web_view_reload(view); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } } else if (strcmp(method, "openInspector") == 0) { WebKitWebView* view = find_view(args); if (view == nullptr) { diff --git a/pubspec.yaml b/pubspec.yaml index f4bdb53..2fb10d9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: cesiumjs -description: "CesiumJS 3D globe for Flutter (Linux, Windows, Android), rendered in a native web view." -version: 0.2.0 +description: "CesiumJS 3D globe and web browser view for Flutter (Linux, Windows, Android), rendered in a native web view." +version: 0.3.0 publish_to: 'none' environment: diff --git a/test/native_web_view_test.dart b/test/native_web_view_test.dart new file mode 100644 index 0000000..38279d5 --- /dev/null +++ b/test/native_web_view_test.dart @@ -0,0 +1,69 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:cesiumjs/cesiumjs.dart'; + +void main() { + const channel = MethodChannel('cesiumjs/webview'); + late List calls; + + setUp(() { + calls = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return null; + }); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + bool? lastVisible() => calls + .lastWhere((c) => c.method == 'setRect') + .arguments['visible'] as bool?; + + // One test: the channel singleton memoizes its first call's future, which + // does not complete in a later test's fake-async zone. + testWidgets('browser view: url, url changes, hidden under dialogs', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + final controller = WebBrowserController(); + Widget app(String url) => MaterialApp( + home: WebBrowserView(url: url, controller: controller), + ); + await tester.pumpWidget(app('https://a.example')); + await tester.pumpAndSettle(); + final create = calls.firstWhere((c) => c.method == 'create'); + expect(create.arguments['url'], 'https://a.example'); + expect((create.arguments as Map).containsKey('html'), isFalse); + expect(controller.isAttached, isTrue); + expect(lastVisible(), isTrue); + + await tester.pumpWidget(app('https://b.example')); + await tester.pumpAndSettle(); + final load = calls.lastWhere((c) => c.method == 'loadUrl'); + expect(load.arguments['url'], 'https://b.example'); + + // Linux: a dialog over the route hides the native view + showDialog( + context: tester.element(find.byType(WebBrowserView)), + builder: (_) => const AlertDialog(content: Text('hi')), + ); + await tester.pumpAndSettle(); + expect(lastVisible(), isFalse); + + Navigator.of(tester.element(find.text('hi'))).pop(); + await tester.pumpAndSettle(); + expect(lastVisible(), isTrue); + + await tester.pumpWidget(const SizedBox()); + expect(calls.last.method, 'dispose'); + expect(controller.isAttached, isFalse); + debugDefaultTargetPlatformOverride = null; + }); +} diff --git a/windows/cesiumjs_plugin.cpp b/windows/cesiumjs_plugin.cpp index 226decd..12af736 100644 --- a/windows/cesiumjs_plugin.cpp +++ b/windows/cesiumjs_plugin.cpp @@ -178,6 +178,10 @@ struct View { ComPtr webview; std::string html; std::wstring base_url; + // Browser view (created with a url): loaded from the network, links that + // open a window stay in the view. + bool browser = false; + std::wstring url; RECT bounds{}; // physical pixels, in host parent's client coordinates bool visible = false; // Run once WebView2 is ready; called with false if the view is disposed @@ -276,7 +280,7 @@ class CesiumjsPlugin : public flutter::Plugin { // --- create --------------------------------------------------------------- void Create(int64_t id, const std::string& html, const std::string& base, - MethodResultPtr result) { + const std::string* url, MethodResultPtr result) { HWND parent = HostParent(); if (parent == nullptr) { result->Error("no_window", "Flutter view has no native window"); @@ -292,6 +296,10 @@ class CesiumjsPlugin : public flutter::Plugin { auto view = std::make_unique(); view->html = html; view->base_url = Utf8ToWide(base); + if (url != nullptr) { + view->browser = true; + view->url = Utf8ToWide(*url); + } view->host = CreateWindowExW( 0, kHostClass, L"", WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 0, 0, parent, nullptr, GetModuleHandleW(nullptr), nullptr); @@ -348,7 +356,8 @@ class CesiumjsPlugin : public flutter::Plugin { ICoreWebView2* wv = v->webview.Get(); ComPtr controller2; - if (SUCCEEDED(controller->QueryInterface(IID_PPV_ARGS(&controller2)))) { + if (!v->browser && + SUCCEEDED(controller->QueryInterface(IID_PPV_ARGS(&controller2)))) { controller2->put_DefaultBackgroundColor({255, 0, 0, 0}); // opaque black } ComPtr settings; @@ -376,10 +385,12 @@ class CesiumjsPlugin : public flutter::Plugin { &token); // Serve the page from the virtual origin, like load_html on Linux. - std::wstring filter = v->base_url + L"*"; - wv->AddWebResourceRequestedFilter(filter.c_str(), - COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT); ComPtr environment(env); + if (!v->browser) { + std::wstring filter = v->base_url + L"*"; + wv->AddWebResourceRequestedFilter( + filter.c_str(), COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT); + } wv->add_WebResourceRequested( Callback( [this, id, environment]( @@ -401,14 +412,21 @@ class CesiumjsPlugin : public flutter::Plugin { .Get(), &token); - // Links opening a new window (Cesium credits...) go to the browser. + // Links opening a new window: Cesium pages (credits...) send them to the + // user's browser, browser views load them in place. wv->add_NewWindowRequested( Callback( - [](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) { + [this, id](ICoreWebView2* sender, + ICoreWebView2NewWindowRequestedEventArgs* args) { CoStr uri; if (SUCCEEDED(args->get_Uri(&uri.p)) && uri.p) { - ShellExecuteW(nullptr, L"open", uri.p, nullptr, nullptr, - SW_SHOWNORMAL); + View* target = Find(id); + if (target != nullptr && target->browser) { + sender->Navigate(uri.p); + } else { + ShellExecuteW(nullptr, L"open", uri.p, nullptr, nullptr, + SW_SHOWNORMAL); + } } args->put_Handled(TRUE); return S_OK; @@ -450,7 +468,7 @@ class CesiumjsPlugin : public flutter::Plugin { &token); ApplyBounds(v); - wv->Navigate(v->base_url.c_str()); + wv->Navigate(v->browser ? v->url.c_str() : v->base_url.c_str()); auto pending = std::move(v->pending); for (auto& fn : pending) fn(true); @@ -512,6 +530,16 @@ class CesiumjsPlugin : public flutter::Plugin { } } + // Runs [fn] now if WebView2 is ready, else once it is (or with false if the + // view is disposed first). + static void WhenReady(View* v, std::function fn) { + if (v->webview) { + fn(true); + } else { + v->pending.push_back(std::move(fn)); + } + } + void Dispose(int64_t id) { auto it = views_.find(id); if (it == views_.end()) return; @@ -545,19 +573,22 @@ class CesiumjsPlugin : public flutter::Plugin { } if (method == "create") { const std::string* html = GetString(args, "html"); - if (!id || html == nullptr) { - result->Error("bad_args", "create requires id and html"); + const std::string* url = GetString(args, "url"); + if (!id || (html == nullptr && url == nullptr)) { + result->Error("bad_args", "create requires id and html or url"); } else if (Find(*id)) { result->Error("exists", "a view with this id already exists"); } else { const std::string* base = GetString(args, "baseUrl"); - Create(*id, *html, base ? *base : kDefaultBaseUrl, std::move(result)); + Create(*id, html ? *html : std::string(), + base ? *base : kDefaultBaseUrl, url, std::move(result)); } return; } View* v = id ? Find(*id) : nullptr; if (method != "setRect" && method != "runJavaScript" && + method != "loadUrl" && method != "reload" && method != "openInspector") { result->NotImplemented(); return; @@ -576,6 +607,22 @@ class CesiumjsPlugin : public flutter::Plugin { } else { RunJavaScript(v, *script, std::move(result)); } + } else if (method == "loadUrl") { + const std::string* url = GetString(args, "url"); + if (url == nullptr) { + result->Error("bad_args", "url missing"); + } else { + std::wstring wurl = Utf8ToWide(*url); + WhenReady(v, [v, wurl](bool ready) { + if (ready) v->webview->Navigate(wurl.c_str()); + }); + result->Success(); + } + } else if (method == "reload") { + WhenReady(v, [v](bool ready) { + if (ready) v->webview->Reload(); + }); + result->Success(); } else { // openInspector if (v->webview) v->webview->OpenDevToolsWindow(); result->Success();