browser export

This commit is contained in:
yves committed 2026-11-07 19:49:09 +01:00
1 parent 1d974b42a1
commit 0966c6de17
13 files changed
+640 -207

No files matched your search

+4 -1
View File
@@ -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;
+14 -161
View File
@@ -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(
'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)),
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<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);
});
}
}
}
+19 -2
View File
@@ -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).
+217
View File
@@ -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);
});
}
}
}
+112
View File
@@ -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.',
);
}
}