browser export
This commit is contained in:
1 parent
1d974b42a1
commit
0966c6de17
13 files changed
+632
-199
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<GlobePage> {
|
||||
|
||||
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
|
||||
|
||||
@@ -79,13 +79,16 @@ class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityA
|
||||
when (call.method) {
|
||||
"create" -> {
|
||||
val html = call.argument<String>("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<String>("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<String>("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<String>("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
|
||||
}
|
||||
}
|
||||
if (url != null) {
|
||||
view.loadUrl(url)
|
||||
} else {
|
||||
view.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -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;
|
||||
+13
-160
@@ -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<CesiumViewer> {
|
||||
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<void> _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<CesiumViewer> {
|
||||
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(
|
||||
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.',
|
||||
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<OneSequenceGestureRecognizer>(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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports its global (window) rectangle after every paint.
|
||||
class _RectReporter extends SingleChildRenderObjectWidget {
|
||||
const _RectReporter({required this.onRectChanged, super.child});
|
||||
|
||||
final ValueChanged<Rect> 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<Rect> 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,14 +29,31 @@ class CesiumNativeChannel {
|
||||
Future<void> _ensureReset() =>
|
||||
_reset ??= _channel.invokeMethod<void>('disposeAll');
|
||||
|
||||
Future<int> 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<int> 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<void>('create', {'id': id, 'html': html});
|
||||
await _channel.invokeMethod<void>('create', {
|
||||
'id': id,
|
||||
'html': ?html,
|
||||
'url': ?url,
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
Future<void> loadUrl(int id, String url) =>
|
||||
_channel.invokeMethod<void>('loadUrl', {'id': id, 'url': url});
|
||||
|
||||
Future<void> reload(int id) =>
|
||||
_channel.invokeMethod<void>('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).
|
||||
|
||||
@@ -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<int> Function(NativeEventHandler onEvent) create;
|
||||
final NativeEventHandler onEvent;
|
||||
final ValueChanged<int>? 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<NativeWebViewHost> createState() => _NativeWebViewHostState();
|
||||
}
|
||||
|
||||
class _NativeWebViewHostState extends State<NativeWebViewHost> {
|
||||
int? _viewId;
|
||||
bool _disposed = false;
|
||||
Rect? _sentRect;
|
||||
bool? _sentVisible;
|
||||
double? _sentScale;
|
||||
Rect _currentRect = Rect.zero;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (nativeWebViewSupported) _create();
|
||||
}
|
||||
|
||||
Future<void> _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<OneSequenceGestureRecognizer>(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<Rect> 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<Rect> 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> loadUrl(String url) =>
|
||||
CesiumNativeChannel.instance.loadUrl(_id, url);
|
||||
|
||||
/// Reloads the current page.
|
||||
Future<void> 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<String?> runJavaScript(String script) =>
|
||||
CesiumNativeChannel.instance.runJavaScript(_id, script);
|
||||
|
||||
/// Opens the dev tools (no-op on Android, use chrome://inspect).
|
||||
Future<void> 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<String>? onError;
|
||||
|
||||
/// Hides the web view without destroying it (keeps the page).
|
||||
final bool visible;
|
||||
|
||||
@override
|
||||
State<WebBrowserView> createState() => _WebBrowserViewState();
|
||||
}
|
||||
|
||||
class _WebBrowserViewState extends State<WebBrowserView> {
|
||||
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.',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,8 +125,12 @@ 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) {
|
||||
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);
|
||||
|
||||
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) {
|
||||
|
||||
+2
-2
@@ -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:
|
||||
|
||||
@@ -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<MethodCall> 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<void>(
|
||||
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;
|
||||
});
|
||||
}
|
||||
+58
-11
@@ -178,6 +178,10 @@ struct View {
|
||||
ComPtr<ICoreWebView2> 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>();
|
||||
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<ICoreWebView2Controller2> 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<ICoreWebView2Settings> 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<ICoreWebView2Environment> 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<ICoreWebView2WebResourceRequestedEventHandler>(
|
||||
[this, id, environment](
|
||||
@@ -401,15 +412,22 @@ 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<ICoreWebView2NewWindowRequestedEventHandler>(
|
||||
[](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) {
|
||||
[this, id](ICoreWebView2* sender,
|
||||
ICoreWebView2NewWindowRequestedEventArgs* args) {
|
||||
CoStr uri;
|
||||
if (SUCCEEDED(args->get_Uri(&uri.p)) && uri.p) {
|
||||
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<void(bool)> 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();
|
||||
|
||||
Reference in new issue
Block a user