first commit

This commit is contained in:
yves committed 2026-11-07 14:39:59 +01:00
commit c069b8945d
34 files changed
+2424

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
/// CesiumJS globe for Flutter (Linux desktop, via WebKitGTK).
library;
export 'src/cesium_controller.dart'
show CesiumController, CesiumImagery, CesiumMessage;
export 'src/cesium_html.dart' show cesiumVersion;
export 'src/cesium_viewer.dart' show CesiumViewer;
+175
View File
@@ -0,0 +1,175 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'native_channel.dart';
/// Base imagery sources available in the viewer.
enum CesiumImagery {
/// OpenStreetMap map tiles (no key).
osm('osm', 'OpenStreetMap'),
/// Bing Maps aerial orthophotos via Cesium ion (worldwide, needs token).
ionAerial('ion-aerial', 'Ortho monde (Bing / ion)'),
/// IGN BD ORTHO via Géoplateforme WMTS (France, ~20 cm, no key).
ignOrtho('ign-ortho', 'Ortho IGN (France)');
const CesiumImagery(this.jsName, this.label);
final String jsName;
final String label;
}
/// A message posted from JavaScript with `CesiumChannel.postMessage(...)`.
///
/// Messages are expected to be JSON objects with a `type` field; anything
/// else is delivered with type `raw`.
class CesiumMessage {
CesiumMessage(this.type, this.data);
factory CesiumMessage.parse(String raw) {
try {
final decoded = jsonDecode(raw);
if (decoded is Map<String, dynamic>) {
return CesiumMessage(decoded['type']?.toString() ?? 'raw', decoded);
}
} on FormatException {
// fall through
}
return CesiumMessage('raw', {'value': raw});
}
final String type;
final Map<String, dynamic> data;
@override
String toString() => 'CesiumMessage($type, $data)';
}
/// Controls a [CesiumViewer] from Dart.
///
/// The controller becomes usable once the viewer reports `ready`
/// (see [CesiumViewer.onReady] or [isReady]).
class CesiumController {
int? _viewId;
bool _ready = false;
final _messages = StreamController<CesiumMessage>.broadcast();
/// Whether the Cesium viewer has finished initialising.
bool get isReady => _ready;
/// All messages posted from JavaScript (including `ready`, `camera`,
/// `error`).
Stream<CesiumMessage> get messages => _messages.stream;
/// Runs [script] in the page. `window.cesiumViewer` is the `Cesium.Viewer`.
/// Returns the result converted to a string, or null for undefined/null.
/// The last expression must not be a Promise (WebKit cannot return it).
Future<String?> runJavaScript(String script) {
final id = _viewId;
if (id == null) {
throw StateError('CesiumController is not attached to a CesiumViewer');
}
return CesiumNativeChannel.instance.runJavaScript(id, script);
}
/// Flies the camera to [longitude]/[latitude] (degrees) at [height] metres.
Future<void> flyTo(
double longitude,
double latitude,
double height, {
double durationSeconds = 3,
double headingDegrees = 0,
double pitchDegrees = -90,
}) => runJavaScript('''
cesiumViewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees($longitude, $latitude, $height),
orientation: {
heading: Cesium.Math.toRadians($headingDegrees),
pitch: Cesium.Math.toRadians($pitchDegrees),
roll: 0
},
duration: $durationSeconds
});''');
/// Adds a labelled point entity and returns its id.
Future<String?> addPoint(
double longitude,
double latitude, {
String? label,
String cssColor = '#ffcc00',
double pixelSize = 12,
}) => runJavaScript('''
(function () {
const e = cesiumViewer.entities.add({
position: Cesium.Cartesian3.fromDegrees($longitude, $latitude),
point: {
pixelSize: $pixelSize,
color: Cesium.Color.fromCssColorString(${jsonEncode(cssColor)}),
outlineColor: Cesium.Color.BLACK,
outlineWidth: 1,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
},
label: ${label == null ? 'undefined' : '''{
text: ${jsonEncode(label)},
font: '14px sans-serif',
pixelOffset: new Cesium.Cartesian2(0, -20),
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
style: Cesium.LabelStyle.FILL_AND_OUTLINE
}'''}
});
return e.id;
})()''');
/// Switches the base imagery (orthophoto). `ionAerial` needs an ion token;
/// `ignOrtho` covers France and sits on top of a worldwide layer.
Future<void> setImagery(CesiumImagery imagery) => runJavaScript(
'cesiumLayers.setImagery(${jsonEncode(imagery.jsName)}); undefined;',
);
/// Turns the terrain model (MNT, Cesium World Terrain) on or off.
/// Needs an ion token.
Future<void> setTerrain(bool enabled) =>
runJavaScript('cesiumLayers.setTerrain($enabled); undefined;');
/// Shows Cesium's frames-per-second overlay.
Future<void> showFps(bool enabled) => runJavaScript(
'cesiumViewer.scene.debugShowFramesPerSecond = $enabled; undefined;',
);
/// Removes every entity from the viewer.
Future<void> clearEntities() =>
runJavaScript('cesiumViewer.entities.removeAll();');
/// Opens the WebKit inspector (devtools) for this page.
Future<void> openInspector() async {
final id = _viewId;
if (id != null) await CesiumNativeChannel.instance.openInspector(id);
}
// --- Internal: used by CesiumViewer --------------------------------------
@internal
void attach(int viewId) {
_viewId = viewId;
_ready = false;
}
@internal
void detach() {
_viewId = null;
_ready = false;
}
@internal
void handleMessage(CesiumMessage message) {
if (message.type == 'ready') _ready = true;
if (!_messages.isClosed) _messages.add(message);
}
/// Releases resources. Call when the controller is no longer needed.
void dispose() => _messages.close();
}
+160
View File
@@ -0,0 +1,160 @@
import 'dart:convert';
/// CesiumJS version loaded from the jsDelivr CDN.
const String cesiumVersion = '1.122.0';
/// Builds the HTML page hosting the Cesium viewer.
///
/// When [ionToken] is null or empty, the globe uses OpenStreetMap imagery and
/// no Cesium ion services, so it works without an account.
String buildCesiumHtml({String? ionToken}) {
final base =
'https://cdn.jsdelivr.net/npm/cesium@$cesiumVersion/Build/Cesium';
final token = jsonEncode(ionToken ?? '');
return '''
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="$base/Cesium.js"></script>
<link href="$base/Widgets/widgets.css" rel="stylesheet">
<style>
html, body, #cesiumContainer {
margin: 0; padding: 0; width: 100%; height: 100%;
overflow: hidden; background: #000;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
// JS -> Dart bridge (WebKitGTK script message handler).
window.CesiumChannel = {
postMessage: function (msg) {
if (typeof msg !== 'string') msg = JSON.stringify(msg);
window.webkit.messageHandlers.cesium.postMessage(msg);
}
};
window.addEventListener('error', function (e) {
CesiumChannel.postMessage({type: 'error', message: String(e.message)});
});
try {
const token = $token;
const options = {
geocoder: false,
baseLayerPicker: false,
timeline: false,
animation: false,
sceneModePicker: true,
navigationHelpButton: false,
fullscreenButton: false,
};
if (token) Cesium.Ion.defaultAccessToken = token;
options.baseLayer = false; // imagery is managed by cesiumLayers below
const viewer = new Cesium.Viewer('cesiumContainer', options);
window.cesiumViewer = viewer;
// Hide entities/markers behind mountains once terrain is on.
viewer.scene.globe.depthTestAgainstTerrain = true;
function reportError(what, e) {
CesiumChannel.postMessage({type: 'error', message: what + ': ' + e});
}
// ---- Imagery (orthophoto) and terrain (MNT) management --------------
const imagerySources = {
// OpenStreetMap, no key needed.
osm: function () {
return new Cesium.OpenStreetMapImageryProvider({
url: 'https://tile.openstreetmap.org/'
});
},
// Bing Maps aerial orthophotos, worldwide (Cesium ion asset 2).
'ion-aerial': function () {
return Cesium.IonImageryProvider.fromAssetId(2);
},
// IGN BD ORTHO (France, ~20 cm), Géoplateforme WMTS, no key needed.
'ign-ortho': function () {
return new Cesium.WebMapTileServiceImageryProvider({
url: 'https://data.geopf.fr/wmts',
layer: 'ORTHOIMAGERY.ORTHOPHOTOS',
style: 'normal',
format: 'image/jpeg',
tileMatrixSetID: 'PM',
maximumLevel: 19,
rectangle: Cesium.Rectangle.fromDegrees(-5.5, 41.0, 10.0, 51.5),
credit: new Cesium.Credit('© IGN – BD ORTHO®'),
});
},
};
let imageryRequest = 0;
window.cesiumLayers = {
imagery: null,
terrain: false,
// name: 'osm' | 'ion-aerial' | 'ign-ortho'.
// 'ign-ortho' only covers France, so a worldwide layer is kept below it.
setImagery: async function (name) {
if (!imagerySources[name]) throw new Error('unknown imagery ' + name);
const req = ++imageryRequest;
const stack = name === 'ign-ortho'
? [token ? 'ion-aerial' : 'osm', 'ign-ortho']
: [name];
try {
const providers = await Promise.all(
stack.map(function (n) { return imagerySources[n](); }));
if (req !== imageryRequest) return; // superseded
viewer.imageryLayers.removeAll();
providers.forEach(function (p) {
viewer.imageryLayers.addImageryProvider(p);
});
this.imagery = name;
CesiumChannel.postMessage({type: 'layers', imagery: name,
terrain: this.terrain});
} catch (e) { reportError('imagery ' + name, e); }
},
// MNT: Cesium World Terrain (ion asset 1); false = WGS84 ellipsoid.
setTerrain: async function (enabled) {
try {
viewer.terrainProvider = enabled
? await Cesium.createWorldTerrainAsync({requestVertexNormals: true})
: new Cesium.EllipsoidTerrainProvider();
this.terrain = !!enabled;
CesiumChannel.postMessage({type: 'layers', imagery: this.imagery,
terrain: this.terrain});
} catch (e) { reportError('terrain', e); }
},
};
cesiumLayers.setImagery(token ? 'ion-aerial' : 'osm');
if (token) cesiumLayers.setTerrain(true);
// Report camera position to Dart after each movement.
viewer.camera.moveEnd.addEventListener(function () {
const c = viewer.camera.positionCartographic;
CesiumChannel.postMessage({
type: 'camera',
longitude: Cesium.Math.toDegrees(c.longitude),
latitude: Cesium.Math.toDegrees(c.latitude),
height: c.height,
});
});
const gl = viewer.scene.context._gl;
CesiumChannel.postMessage({
type: 'ready',
webgl: (typeof WebGL2RenderingContext !== 'undefined' &&
gl instanceof WebGL2RenderingContext) ? 2 : 1,
cesium: Cesium.VERSION,
});
} catch (e) {
CesiumChannel.postMessage({type: 'error', message: String(e)});
}
</script>
</body>
</html>
''';
}
+182
View File
@@ -0,0 +1,182 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'cesium_controller.dart';
import 'cesium_html.dart';
import 'native_channel.dart';
/// Displays a CesiumJS globe.
///
/// On Linux the globe is a native WebKitGTK view stacked *above* the 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).
/// * The rectangle is in window coordinates, so the widget should not be
/// clipped by a scroll view.
class CesiumViewer extends StatefulWidget {
const CesiumViewer({
super.key,
this.ionToken,
this.controller,
this.onReady,
this.onMessage,
this.onError,
this.visible = true,
});
/// Cesium ion token (https://ion.cesium.com/tokens). Optional: without it
/// OpenStreetMap imagery and an ellipsoid globe are used.
final String? ionToken;
final CesiumController? controller;
final VoidCallback? onReady;
final ValueChanged<CesiumMessage>? onMessage;
final ValueChanged<String>? onError;
/// Hides the native view without destroying it (keeps camera state).
final bool visible;
@override
State<CesiumViewer> createState() => _CesiumViewerState();
}
class _CesiumViewerState extends State<CesiumViewer> {
late final CesiumController _controller =
widget.controller ?? CesiumController();
int? _viewId;
bool _disposed = false;
Rect? _sentRect;
bool? _sentVisible;
Rect _currentRect = Rect.zero;
bool get _supported =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.linux;
@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;
}
_viewId = id;
_controller.attach(id);
_sync();
}
void _onNativeEvent(String event, String message) {
if (event == 'onError') {
widget.onError?.call(message);
return;
}
final msg = CesiumMessage.parse(message);
_controller.handleMessage(msg);
if (msg.type == 'ready') widget.onReady?.call();
if (msg.type == 'error') widget.onError?.call('${msg.data['message']}');
widget.onMessage?.call(msg);
}
void _onRectChanged(Rect rect) {
_currentRect = rect;
_sync();
}
void _sync() {
final id = _viewId;
if (id == null || _disposed) return;
final visible = widget.visible && TickerMode.valuesOf(context).enabled;
if (_sentRect == _currentRect && _sentVisible == visible) return;
_sentRect = _currentRect;
_sentVisible = visible;
CesiumNativeChannel.instance.setRect(id, _currentRect, visible: visible);
}
@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 currently supports Linux desktop only.',
style: TextStyle(color: Colors.white70),
),
),
);
}
// 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);
});
}
}
}
+57
View File
@@ -0,0 +1,57 @@
import 'package:flutter/services.dart';
typedef NativeEventHandler = void Function(String event, String message);
/// Thin wrapper over the `cesiumjs/webview` method channel implemented in
/// `linux/cesiumjs_plugin.cc`.
class CesiumNativeChannel {
CesiumNativeChannel._() {
_channel.setMethodCallHandler(_onCall);
}
static final CesiumNativeChannel instance = CesiumNativeChannel._();
final MethodChannel _channel = const MethodChannel('cesiumjs/webview');
final Map<int, NativeEventHandler> _handlers = {};
int _nextId = 0;
Future<void>? _reset;
Future<dynamic> _onCall(MethodCall call) async {
final args = Map<String, dynamic>.from(call.arguments as Map);
final handler = _handlers[args['id'] as int];
handler?.call(call.method, args['message'] as String? ?? '');
}
/// Native views survive a Dart hot restart; wipe them once per isolate.
Future<void> _ensureReset() =>
_reset ??= _channel.invokeMethod<void>('disposeAll');
Future<int> create(String html, NativeEventHandler onEvent) async {
await _ensureReset();
final id = _nextId++;
_handlers[id] = onEvent;
await _channel.invokeMethod<void>('create', {'id': id, 'html': html});
return id;
}
Future<void> setRect(int id, Rect rect, {required bool visible}) =>
_channel.invokeMethod<void>('setRect', {
'id': id,
'x': rect.left,
'y': rect.top,
'width': rect.width,
'height': rect.height,
'visible': visible,
});
Future<String?> runJavaScript(int id, String script) => _channel
.invokeMethod<String>('runJavaScript', {'id': id, 'script': script});
Future<void> openInspector(int id) =>
_channel.invokeMethod<void>('openInspector', {'id': id});
Future<void> dispose(int id) {
_handlers.remove(id);
return _channel.invokeMethod<void>('dispose', {'id': id});
}
}