commit c069b8945dcf4708a63db6fd31fe7bd45907b690 Author: yc Date: Sat Nov 7 14:39:59 2026 +0100 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9d7f25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..f9bdd57 --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "c197ca5199e9ee5661e865596c9c07294dfab51c" + channel: "stable" + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c + base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c + - platform: linux + create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c + base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..210f163 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,14 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "example (linux)", + "request": "launch", + "type": "dart", + "cwd": "example", + "program": "lib/main.dart", + "deviceId": "linux", + "toolArgs": ["--dart-define-from-file=cesium_ion.json"] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..64eefb8 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "${workspaceFolder}/example/linux" +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ed1278f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## 0.1.0 + +* First packaged version: `CesiumViewer` widget + `CesiumController` for + Linux desktop, backed by a native WebKitGTK view (Flutter plugin). +* Demo moved to `example/`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..d89b8bc --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,61 @@ +# CLAUDE.md + +Flutter **plugin** (Linux desktop only) embedding a CesiumJS globe. 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. + +## Commands + +```sh +flutter pub get && flutter analyze && flutter test # package (root) +cd example && flutter build linux --debug # compiles the native plugin +cd example && flutter run -d linux --dart-define-from-file=cesium_ion.json +``` + +Native build needs `libwebkit2gtk-4.1-dev`. Native code is only compiled +through the example app — after changing `linux/cesiumjs_plugin.cc`, always +run `flutter build linux` in `example/`. + +## Architecture + +- `CesiumViewer` (Dart) renders a black placeholder and reports its global + rect after each paint (`_RenderRectReporter`) → `setRect` over the + `cesiumjs/webview` method channel. +- `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 + restart doesn't leave orphan views). Events back to Dart: `onMessage`, + `onError`. +- JS → Dart: `CesiumChannel.postMessage` → `window.webkit.messageHandlers.cesium`. + Messages are JSON with a `type` field → `CesiumMessage`. +- HTML is generated in `lib/src/cesium_html.dart` and loaded with + `load_html` + base URI `https://cesium.localhost/`; CesiumJS comes from + jsDelivr (`cesiumVersion`). JS helpers `cesiumViewer` / `cesiumLayers` live + on `window`. + +## Gotchas — do not regress + +- **Overlay creation**: the stock runner realizes the `FlView` (starting the + engine's GL surface) *before* plugins register. A plain + `gtk_container_remove`/`add` unrealizes it and Flutter fails with + "Could not determine GL version". `ensure_overlay()` uses the deprecated + `gtk_widget_reparent()` via a temporary realized window to keep it realized. +- **`on_view_realize` → `gdk_window_ensure_native()`** must stay: without a + native child window, GTK3 composites WebKit with the FlView GL surface and + only ~0.2 frames/s reach the screen (Cesium's own FPS counter still says + 60 — measure presented frames with ffmpeg x11grab + mpdecimate instead). +- Flutter widgets cannot paint over the globe; use `visible: false`. +- `runJavaScript` cannot return a Promise as the last expression; scripts that + return nothing should end with `undefined;`. +- Controller internals (`attach`, `detach`, `handleMessage`) are `@internal`. + +## Conventions + +- Never commit a Cesium ion token. The example reads `CESIUM_ION_TOKEN` via + `--dart-define-from-file=cesium_ion.json` (git-ignored). +- New controller features: add a Dart method in `cesium_controller.dart` + that calls `runJavaScript` (JSON-encode string arguments with `jsonEncode`), + plus a JS helper in `cesium_html.dart` if it is more than a few lines. +- Update `README.md` API tables and `CHANGELOG.md` when the public API changes. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ec46501 --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# cesiumjs + +A Flutter plugin that embeds a [CesiumJS](https://cesium.com/platform/cesiumjs/) +3D globe in Flutter **Linux desktop** apps. + +Flutter on Linux has no platform views, so the globe is a native WebKitGTK +web view stacked above the Flutter surface and kept aligned with the +`CesiumViewer` widget. WebKitGTK renders WebGL2 on the GPU, so Cesium runs at +full frame rate. + +| Platform | Status | +|---|---| +| Linux (X11) | Supported | +| Other platforms | The widget shows a "not supported" placeholder | + +## Requirements + +- Flutter ≥ 3.32 / Dart ≥ 3.13 +- WebKitGTK 4.1 development files at build time: + ```sh + sudo apt install libwebkit2gtk-4.1-dev + ``` + End users need the runtime library (`libwebkit2gtk-4.1-0`), which ships with + most GTK desktops. +- Network access: CesiumJS is loaded from the jsDelivr CDN. +- Optional: a [Cesium ion token](https://ion.cesium.com/tokens) for Bing + aerial imagery and Cesium World Terrain. Without one the globe uses + OpenStreetMap and a smooth ellipsoid. + +## Installation + +```yaml +dependencies: + cesiumjs: + path: ../cesiumjs # or a git: dependency +``` + +No changes to your Linux runner are needed: on registration the plugin wraps +the app's `FlView` in a `GtkOverlay`. If your runner already places the +`FlView` inside a `GtkOverlay`, that overlay is used as is. + +## Usage + +```dart +import 'package:cesiumjs/cesiumjs.dart'; + +class GlobePage extends StatefulWidget { + const GlobePage({super.key}); + @override + State createState() => _GlobePageState(); +} + +class _GlobePageState extends State { + final _controller = CesiumController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return CesiumViewer( + ionToken: const String.fromEnvironment('CESIUM_ION_TOKEN'), + controller: _controller, + onReady: () => _controller.flyTo(1.4442, 43.6047, 15000), // Toulouse + onError: (e) => debugPrint('Cesium error: $e'), + ); + } +} +``` + +### `CesiumViewer` + +| Parameter | Description | +|---|---| +| `ionToken` | Cesium ion token, optional | +| `controller` | A `CesiumController` to drive the globe from Dart | +| `onReady` | Called once the Cesium viewer is initialised | +| `onMessage` | Every message posted from JavaScript (`CesiumMessage`) | +| `onError` | Page load failures, web process crashes and JS errors | +| `visible` | Hides the native view without destroying it (keeps camera state) | + +### `CesiumController` + +| Method | Description | +|---|---| +| `flyTo(lon, lat, height, {durationSeconds, headingDegrees, pitchDegrees})` | Animated camera move | +| `addPoint(lon, lat, {label, cssColor, pixelSize})` | Adds a ground-clamped point entity, returns its id | +| `clearEntities()` | Removes all entities | +| `setImagery(CesiumImagery)` | `osm`, `ionAerial` (needs a token) or `ignOrtho` (IGN, France) | +| `setTerrain(bool)` | Cesium World Terrain on/off (needs a token) | +| `showFps(bool)` | Cesium's FPS overlay | +| `runJavaScript(script)` | Runs arbitrary JS; `window.cesiumViewer` is the `Cesium.Viewer`. Returns the result as a string | +| `openInspector()` | Opens the WebKit dev tools | +| `isReady`, `messages` | Ready flag and broadcast stream of `CesiumMessage`s | + +Controller calls are only valid after `onReady` (or `isReady == true`). + +### Messages from JavaScript + +The page calls `CesiumChannel.postMessage(obj)`; objects are sent as JSON and +arrive as `CesiumMessage(type, data)`. Built-in types: + +| `type` | `data` | +|---|---| +| `ready` | `cesium` (version), `webgl` (1 or 2) | +| `camera` | `longitude`, `latitude`, `height` (sent when the camera stops moving) | +| `layers` | `imagery`, `terrain` | +| `error` | `message` | + +Your own scripts (via `runJavaScript`) can post custom types the same way. + +## Limitations + +- **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. +- 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. +- Tested on X11. Wayland is untested. + +## Example app + +`example/` is a test app with places, imagery and terrain switches, markers +and a camera readout. + +```sh +cd example +cp cesium_ion.example.json cesium_ion.json # then paste your token (optional) +flutter run -d linux --dart-define-from-file=cesium_ion.json +``` + +`cesium_ion.json` is git-ignored. A VS Code launch configuration +("example (linux)") is provided in `.vscode/launch.json`. + +## Development + +```sh +flutter analyze +flutter test +cd example && flutter build linux +``` + +Layout: + +``` +lib/ + cesiumjs.dart public API (barrel) + src/cesium_viewer.dart CesiumViewer widget, reports its rect to native + 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 +linux/ + cesiumjs_plugin.cc WebKitGTK views in a GtkOverlay over the FlView +example/ test / demo app +``` diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..6087fad --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,33 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - linux/** + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..a458fbb --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,51 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ + +# Local Cesium ion token (see cesium_ion.example.json) +cesium_ion.json diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..6087fad --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1,33 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - linux/** + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/example/cesium_ion.example.json b/example/cesium_ion.example.json new file mode 100644 index 0000000..153170b --- /dev/null +++ b/example/cesium_ion.example.json @@ -0,0 +1 @@ +{ "CESIUM_ION_TOKEN": "paste-your-ion-token-here" } diff --git a/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 0000000..802e8e5 --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,231 @@ +import 'package:flutter/material.dart'; + +import 'package:cesiumjs/cesiumjs.dart'; + +/// Optional Cesium ion token (https://ion.cesium.com/tokens), injected at +/// build time so it never lands in source control: +/// flutter run -d linux --dart-define-from-file=cesium_ion.json +/// (see cesium_ion.example.json). Without it the demo uses OpenStreetMap +/// imagery and an ellipsoid globe. +const String ionToken = String.fromEnvironment('CESIUM_ION_TOKEN'); + +void main() => runApp(const DemoApp()); + +class DemoApp extends StatelessWidget { + const DemoApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'CesiumJS demo', + debugShowCheckedModeBanner: false, + theme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.teal, + brightness: Brightness.dark, + ), + ), + home: const DemoPage(), + ); + } +} + +class DemoPage extends StatefulWidget { + const DemoPage({super.key}); + + @override + State createState() => _DemoPageState(); +} + +class _Place { + /// Marker at [lon]/[lat]. The camera is placed at [camLon]/[camLat]/[height] + /// (defaults to straight above the marker) looking with [heading]/[pitch]. + const _Place( + this.name, + this.lon, + this.lat, + this.height, { + double? camLon, + double? camLat, + this.heading = 0, + this.pitch = -90, + }) : camLon = camLon ?? lon, + camLat = camLat ?? lat; + final String name; + final double lon, lat, height, camLon, camLat, heading, pitch; +} + +const _places = [ + _Place('Toulouse', 1.4442, 43.6047, 15000), + _Place('Capitole (zoom ortho)', 1.4433, 43.6045, 900), + _Place('Paris', 2.3522, 48.8566, 20000), + // Oblique views to show the terrain model (MNT). + _Place( + 'Mont Blanc (3D)', + 6.8652, + 45.8326, + 7500, + camLon: 6.80, + camLat: 45.73, + heading: 25, + pitch: -18, + ), + _Place( + 'Pic du Midi (3D)', + 0.1424, + 42.9369, + 5500, + camLon: 0.10, + camLat: 42.86, + heading: 20, + pitch: -18, + ), + _Place('New York', -74.0060, 40.7128, 25000), + _Place('Tokyo', 139.6917, 35.6895, 30000), +]; + +class _DemoPageState extends State { + final _controller = CesiumController(); + String _status = 'Loading CesiumJS…'; + String _camera = ''; + CesiumImagery? _imagery; + bool _terrain = false; + bool _fps = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _onMessage(CesiumMessage msg) { + switch (msg.type) { + case 'ready': + setState( + () => _status = + 'Ready — Cesium ${msg.data['cesium']}, WebGL ${msg.data['webgl']}', + ); + case 'layers': + setState(() { + _imagery = CesiumImagery.values + .where((i) => i.jsName == msg.data['imagery']) + .firstOrNull; + _terrain = msg.data['terrain'] == true; + }); + case 'camera': + final d = msg.data; + setState( + () => _camera = + 'lon ${(d['longitude'] as num).toStringAsFixed(4)} ' + 'lat ${(d['latitude'] as num).toStringAsFixed(4)} ' + 'h ${((d['height'] as num) / 1000).toStringAsFixed(1)} km', + ); + } + } + + Future _goTo(_Place p) async { + await _controller.flyTo( + p.camLon, + p.camLat, + p.height, + headingDegrees: p.heading, + pitchDegrees: p.pitch, + ); + await _controller.addPoint(p.lon, p.lat, label: p.name); + } + + @override + Widget build(BuildContext context) { + final ready = _controller.isReady; + const hasToken = ionToken != ''; + return Scaffold( + appBar: AppBar( + title: const Text('CesiumJS in Flutter (Linux / WebKitGTK)'), + actions: [ + IconButton( + tooltip: 'Clear markers', + icon: const Icon(Icons.layers_clear), + onPressed: ready ? _controller.clearEntities : null, + ), + IconButton( + tooltip: 'Show FPS', + icon: Icon(_fps ? Icons.speed : Icons.speed_outlined), + onPressed: ready + ? () { + setState(() => _fps = !_fps); + _controller.showFps(_fps); + } + : null, + ), + IconButton( + tooltip: 'Open web inspector', + icon: const Icon(Icons.bug_report_outlined), + onPressed: _controller.openInspector, + ), + ], + ), + body: Row( + children: [ + SizedBox( + width: 230, + child: ListView( + children: [ + for (final p in _places) + ListTile( + dense: true, + leading: const Icon(Icons.place_outlined), + title: Text(p.name), + enabled: ready, + onTap: () => _goTo(p), + ), + const Divider(), + const ListTile(dense: true, title: Text('Orthophoto / fond')), + RadioGroup( + groupValue: _imagery, + onChanged: (v) { + if (ready && v != null) _controller.setImagery(v); + }, + child: Column( + children: [ + for (final i in CesiumImagery.values) + RadioListTile( + dense: true, + value: i, + enabled: + ready && + (i != CesiumImagery.ionAerial || hasToken), + title: Text(i.label), + ), + ], + ), + ), + SwitchListTile( + dense: true, + title: const Text('MNT (Cesium World Terrain)'), + value: _terrain, + onChanged: ready && hasToken ? _controller.setTerrain : null, + ), + ], + ), + ), + Expanded( + child: CesiumViewer( + ionToken: hasToken ? ionToken : null, + controller: _controller, + onMessage: _onMessage, + onError: (e) => setState(() => _status = 'Error: $e'), + ), + ), + ], + ), + bottomNavigationBar: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + color: Theme.of(context).colorScheme.surfaceContainer, + child: Text( + '$_status $_camera', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ); + } +} diff --git a/example/linux/.gitignore b/example/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/example/linux/CMakeLists.txt b/example/linux/CMakeLists.txt new file mode 100644 index 0000000..d1b2bbc --- /dev/null +++ b/example/linux/CMakeLists.txt @@ -0,0 +1,130 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "cesiumjs_example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "fr.irt_saintexupery.cesiumjs_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Enable the test target. +set(include_cesiumjs_tests TRUE) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/example/linux/flutter/CMakeLists.txt b/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/example/linux/flutter/generated_plugin_registrant.cc b/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..d828924 --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) cesiumjs_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "CesiumjsPlugin"); + cesiumjs_plugin_register_with_registrar(cesiumjs_registrar); +} diff --git a/example/linux/flutter/generated_plugin_registrant.h b/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/linux/flutter/generated_plugins.cmake b/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..59cdbee --- /dev/null +++ b/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + cesiumjs +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/linux/runner/CMakeLists.txt b/example/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/example/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/example/linux/runner/main.cc b/example/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/example/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/example/linux/runner/my_application.cc b/example/linux/runner/my_application.cc new file mode 100644 index 0000000..6e8f32a --- /dev/null +++ b/example/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "cesiumjs_example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "cesiumjs_example"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/example/linux/runner/my_application.h b/example/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/example/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/example/pubspec.lock b/example/pubspec.lock new file mode 100644 index 0000000..d5627ff --- /dev/null +++ b/example/pubspec.lock @@ -0,0 +1,212 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + cesiumjs: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "0.1.0" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc + url: "https://pub.dev" + source: hosted + version: "2.4.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.dev" + source: hosted + version: "15.4.0" +sdks: + dart: ">=3.13.7 <4.0.0" + flutter: ">=3.32.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml new file mode 100644 index 0000000..3e2b5c4 --- /dev/null +++ b/example/pubspec.yaml @@ -0,0 +1,20 @@ +name: cesiumjs_example +description: "Test / demo app for the cesiumjs plugin." +publish_to: 'none' + +environment: + sdk: ^3.13.7 + +dependencies: + flutter: + sdk: flutter + cesiumjs: + path: ../ + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + uses-material-design: true diff --git a/lib/cesiumjs.dart b/lib/cesiumjs.dart new file mode 100644 index 0000000..a2d5dd3 --- /dev/null +++ b/lib/cesiumjs.dart @@ -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; diff --git a/lib/src/cesium_controller.dart b/lib/src/cesium_controller.dart new file mode 100644 index 0000000..b6e84c6 --- /dev/null +++ b/lib/src/cesium_controller.dart @@ -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) { + return CesiumMessage(decoded['type']?.toString() ?? 'raw', decoded); + } + } on FormatException { + // fall through + } + return CesiumMessage('raw', {'value': raw}); + } + + final String type; + final Map 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.broadcast(); + + /// Whether the Cesium viewer has finished initialising. + bool get isReady => _ready; + + /// All messages posted from JavaScript (including `ready`, `camera`, + /// `error`). + Stream 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 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 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 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 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 setTerrain(bool enabled) => + runJavaScript('cesiumLayers.setTerrain($enabled); undefined;'); + + /// Shows Cesium's frames-per-second overlay. + Future showFps(bool enabled) => runJavaScript( + 'cesiumViewer.scene.debugShowFramesPerSecond = $enabled; undefined;', + ); + + /// Removes every entity from the viewer. + Future clearEntities() => + runJavaScript('cesiumViewer.entities.removeAll();'); + + /// Opens the WebKit inspector (devtools) for this page. + Future 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(); +} diff --git a/lib/src/cesium_html.dart b/lib/src/cesium_html.dart new file mode 100644 index 0000000..84b5a14 --- /dev/null +++ b/lib/src/cesium_html.dart @@ -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 ''' + + + + + + + + + +
+ + + +'''; +} diff --git a/lib/src/cesium_viewer.dart b/lib/src/cesium_viewer.dart new file mode 100644 index 0000000..7daecf8 --- /dev/null +++ b/lib/src/cesium_viewer.dart @@ -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? onMessage; + final ValueChanged? onError; + + /// Hides the native view without destroying it (keeps camera state). + final bool visible; + + @override + State createState() => _CesiumViewerState(); +} + +class _CesiumViewerState extends State { + 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 _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 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 new file mode 100644 index 0000000..10e475c --- /dev/null +++ b/lib/src/native_channel.dart @@ -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 _handlers = {}; + int _nextId = 0; + Future? _reset; + + Future _onCall(MethodCall call) async { + final args = Map.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 _ensureReset() => + _reset ??= _channel.invokeMethod('disposeAll'); + + Future create(String html, NativeEventHandler onEvent) async { + await _ensureReset(); + final id = _nextId++; + _handlers[id] = onEvent; + await _channel.invokeMethod('create', {'id': id, 'html': html}); + return id; + } + + Future setRect(int id, Rect rect, {required bool visible}) => + _channel.invokeMethod('setRect', { + 'id': id, + 'x': rect.left, + 'y': rect.top, + 'width': rect.width, + 'height': rect.height, + 'visible': visible, + }); + + Future runJavaScript(int id, String script) => _channel + .invokeMethod('runJavaScript', {'id': id, 'script': script}); + + Future openInspector(int id) => + _channel.invokeMethod('openInspector', {'id': id}); + + Future dispose(int id) { + _handlers.remove(id); + return _channel.invokeMethod('dispose', {'id': id}); + } +} diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..5121ad8 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,31 @@ +# Linux build of the cesiumjs Flutter plugin. +cmake_minimum_required(VERSION 3.10) + +set(PROJECT_NAME "cesiumjs") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Must match the pluginClass in pubspec.yaml (CesiumjsPlugin -> cesiumjs_plugin). +set(PLUGIN_NAME "cesiumjs_plugin") + +add_library(${PLUGIN_NAME} SHARED + "cesiumjs_plugin.cc" +) + +apply_standard_settings(${PLUGIN_NAME}) +set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) +target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) + +# WebKitGTK hosts CesiumJS (GPU-accelerated WebGL2). +# Debian/Ubuntu: sudo apt install libwebkit2gtk-4.1-dev +pkg_check_modules(WEBKIT REQUIRED IMPORTED_TARGET webkit2gtk-4.1) +target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::WEBKIT) + +# Libraries to bundle with the app (none: WebKitGTK is a system library). +set(cesiumjs_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/linux/cesiumjs_plugin.cc b/linux/cesiumjs_plugin.cc new file mode 100644 index 0000000..ad6dad4 --- /dev/null +++ b/linux/cesiumjs_plugin.cc @@ -0,0 +1,383 @@ +#include "include/cesiumjs/cesiumjs_plugin.h" + +#include + +#include +#include + +namespace { + +constexpr char kChannelName[] = "cesiumjs/webview"; +constexpr char kMessageHandlerName[] = "cesium"; +constexpr char kRectKey[] = "cesium-rect"; + +struct Plugin { + GtkOverlay* overlay = nullptr; + FlMethodChannel* channel = nullptr; + std::map views; +}; + +Plugin* g_plugin = nullptr; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +FlValue* lookup(FlValue* args, const char* key) { + if (args == nullptr || fl_value_get_type(args) != FL_VALUE_TYPE_MAP) { + return nullptr; + } + return fl_value_lookup_string(args, key); +} + +int64_t get_int(FlValue* args, const char* key, int64_t fallback = -1) { + FlValue* v = lookup(args, key); + if (v == nullptr) return fallback; + if (fl_value_get_type(v) == FL_VALUE_TYPE_INT) return fl_value_get_int(v); + if (fl_value_get_type(v) == FL_VALUE_TYPE_FLOAT) { + return static_cast(fl_value_get_float(v)); + } + return fallback; +} + +double get_double(FlValue* args, const char* key) { + FlValue* v = lookup(args, key); + if (v == nullptr) return 0; + if (fl_value_get_type(v) == FL_VALUE_TYPE_FLOAT) return fl_value_get_float(v); + if (fl_value_get_type(v) == FL_VALUE_TYPE_INT) return fl_value_get_int(v); + return 0; +} + +const gchar* get_string(FlValue* args, const char* key) { + FlValue* v = lookup(args, key); + if (v == nullptr || fl_value_get_type(v) != FL_VALUE_TYPE_STRING) { + return nullptr; + } + return fl_value_get_string(v); +} + +void send_event(const char* method, int64_t id, const gchar* message) { + if (g_plugin == nullptr) return; + g_autoptr(FlValue) args = fl_value_new_map(); + fl_value_set_string_take(args, "id", fl_value_new_int(id)); + fl_value_set_string_take(args, "message", + fl_value_new_string(message ? message : "")); + fl_method_channel_invoke_method(g_plugin->channel, method, args, nullptr, + nullptr, nullptr); +} + +int64_t view_id(gpointer widget) { + return GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "cesium-id")); +} + +// --------------------------------------------------------------------------- +// Layout: place each web view at the rectangle reported by Dart. +// --------------------------------------------------------------------------- + +gboolean on_get_child_position(GtkOverlay* overlay, GtkWidget* widget, + GdkRectangle* allocation, gpointer) { + auto* rect = + static_cast(g_object_get_data(G_OBJECT(widget), kRectKey)); + if (rect == nullptr) return FALSE; + *allocation = *rect; + return TRUE; +} + +// --------------------------------------------------------------------------- +// WebKit signal handlers +// --------------------------------------------------------------------------- + +// JS -> Dart: window.webkit.messageHandlers.cesium.postMessage("...") +void on_script_message(WebKitUserContentManager*, WebKitJavascriptResult* result, + gpointer view) { + JSCValue* value = webkit_javascript_result_get_js_value(result); + g_autofree gchar* str = jsc_value_to_string(value); + send_event("onMessage", view_id(view), str); +} + +gboolean on_load_failed(WebKitWebView* view, WebKitLoadEvent, gchar* uri, + GError* error, gpointer) { + g_autofree gchar* msg = g_strdup_printf("Load failed (%s): %s", uri, + error ? error->message : "?"); + send_event("onError", view_id(view), msg); + return FALSE; +} + +void on_web_process_terminated(WebKitWebView* view, + WebKitWebProcessTerminationReason reason, + gpointer) { + const char* msg = reason == WEBKIT_WEB_PROCESS_CRASHED + ? "Web process crashed" + : "Web process terminated (memory limit or request)"; + 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, + WebKitPolicyDecisionType type, gpointer) { + if (type != WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) return FALSE; + auto* nav = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + WebKitNavigationAction* action = + webkit_navigation_policy_decision_get_navigation_action(nav); + 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); + } + webkit_policy_decision_ignore(decision); + return TRUE; +} + +// Give the web view its own native (X11) child window. Without this, the view +// is composited by GTK3 into the toplevel together with the FlView's GL +// surface, and WebKit frames reach the screen only sporadically. +void on_view_realize(GtkWidget* widget, gpointer) { + GdkWindow* window = gtk_widget_get_window(widget); + if (window != nullptr) gdk_window_ensure_native(window); +} + +// --------------------------------------------------------------------------- +// Method implementations +// --------------------------------------------------------------------------- + +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) { + return FL_METHOD_RESPONSE(fl_method_error_response_new( + "bad_args", "create requires id and html", nullptr)); + } + if (g_plugin->views.count(id)) { + return FL_METHOD_RESPONSE(fl_method_error_response_new( + "exists", "a view with this id already exists", nullptr)); + } + + WebKitUserContentManager* ucm = webkit_user_content_manager_new(); + webkit_user_content_manager_register_script_message_handler( + ucm, kMessageHandlerName); + + auto* view = WEBKIT_WEB_VIEW( + g_object_new(WEBKIT_TYPE_WEB_VIEW, "user-content-manager", ucm, nullptr)); + g_object_unref(ucm); // owned by the view now + g_object_ref_sink(view); + g_object_set_data(G_OBJECT(view), "cesium-id", GINT_TO_POINTER(id)); + g_object_set_data_full(G_OBJECT(view), kRectKey, g_new0(GdkRectangle, 1), + g_free); + + WebKitSettings* settings = webkit_web_view_get_settings(view); + webkit_settings_set_enable_webgl(settings, TRUE); + webkit_settings_set_enable_javascript(settings, TRUE); + webkit_settings_set_enable_developer_extras(settings, TRUE); + webkit_settings_set_javascript_can_open_windows_automatically(settings, + FALSE); + + g_autofree gchar* signal = + g_strdup_printf("script-message-received::%s", kMessageHandlerName); + g_signal_connect(ucm, signal, G_CALLBACK(on_script_message), view); + g_signal_connect(view, "load-failed", G_CALLBACK(on_load_failed), nullptr); + g_signal_connect(view, "web-process-terminated", + G_CALLBACK(on_web_process_terminated), nullptr); + g_signal_connect(view, "decide-policy", G_CALLBACK(on_decide_policy), + 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); + + 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/"); + g_plugin->views[id] = view; + return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); +} + +WebKitWebView* find_view(FlValue* args) { + auto it = g_plugin->views.find(get_int(args, "id")); + return it == g_plugin->views.end() ? nullptr : it->second; +} + +FlMethodResponse* not_found() { + return FL_METHOD_RESPONSE( + fl_method_error_response_new("not_found", "unknown view id", nullptr)); +} + +FlMethodResponse* set_rect(FlValue* args) { + WebKitWebView* view = find_view(args); + if (view == nullptr) return not_found(); + auto* rect = + static_cast(g_object_get_data(G_OBJECT(view), kRectKey)); + rect->x = static_cast(get_double(args, "x") + 0.5); + rect->y = static_cast(get_double(args, "y") + 0.5); + rect->width = static_cast(get_double(args, "width") + 0.5); + rect->height = static_cast(get_double(args, "height") + 0.5); + + FlValue* visible_v = lookup(args, "visible"); + bool visible = visible_v == nullptr || + fl_value_get_type(visible_v) != FL_VALUE_TYPE_BOOL || + fl_value_get_bool(visible_v); + visible = visible && rect->width > 0 && rect->height > 0; + + if (visible) { + gtk_widget_show(GTK_WIDGET(view)); + gtk_widget_queue_resize(GTK_WIDGET(view)); + } else { + gtk_widget_hide(GTK_WIDGET(view)); + } + return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); +} + +void on_js_finished(GObject* object, GAsyncResult* res, gpointer user_data) { + g_autoptr(FlMethodCall) call = FL_METHOD_CALL(user_data); + g_autoptr(GError) error = nullptr; + JSCValue* value = webkit_web_view_evaluate_javascript_finish( + WEBKIT_WEB_VIEW(object), res, &error); + if (value == nullptr) { + fl_method_call_respond_error(call, "js_error", + error ? error->message : "unknown", nullptr, + nullptr); + return; + } + g_autoptr(FlValue) result = nullptr; + if (jsc_value_is_undefined(value) || jsc_value_is_null(value)) { + result = fl_value_new_null(); + } else { + g_autofree gchar* str = jsc_value_to_string(value); + result = fl_value_new_string(str); + } + g_object_unref(value); + fl_method_call_respond_success(call, result, nullptr); +} + +void dispose_view(int64_t id) { + auto it = g_plugin->views.find(id); + if (it == g_plugin->views.end()) return; + WebKitWebView* view = it->second; + g_plugin->views.erase(it); + gtk_container_remove(GTK_CONTAINER(g_plugin->overlay), GTK_WIDGET(view)); + gtk_widget_destroy(GTK_WIDGET(view)); + g_object_unref(view); +} + +void method_call_cb(FlMethodChannel*, FlMethodCall* call, gpointer) { + const gchar* method = fl_method_call_get_name(call); + FlValue* args = fl_method_call_get_args(call); + g_autoptr(FlMethodResponse) response = nullptr; + + if (strcmp(method, "create") == 0) { + response = create_view(args); + } else if (strcmp(method, "setRect") == 0) { + response = set_rect(args); + } else if (strcmp(method, "runJavaScript") == 0) { + WebKitWebView* view = find_view(args); + const gchar* script = get_string(args, "script"); + if (view == nullptr) { + response = not_found(); + } else if (script == nullptr) { + response = FL_METHOD_RESPONSE( + fl_method_error_response_new("bad_args", "script missing", nullptr)); + } else { + webkit_web_view_evaluate_javascript(view, script, -1, nullptr, nullptr, + nullptr, on_js_finished, + g_object_ref(call)); + return; // answered asynchronously + } + } else if (strcmp(method, "openInspector") == 0) { + WebKitWebView* view = find_view(args); + if (view == nullptr) { + response = not_found(); + } else { + webkit_web_inspector_show(webkit_web_view_get_inspector(view)); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } + } else if (strcmp(method, "dispose") == 0) { + dispose_view(get_int(args, "id")); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } else if (strcmp(method, "disposeAll") == 0) { + // Called once per Dart isolate start, so a hot restart does not leave + // orphaned web views stacked over the new UI. + while (!g_plugin->views.empty()) { + dispose_view(g_plugin->views.begin()->first); + } + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } else { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + fl_method_call_respond(call, response, nullptr); +} + + +// Returns the GtkOverlay hosting [view], creating one around it if needed. +// +// The default Flutter runner puts the FlView directly in the GtkWindow and +// realizes it (starting the engine and its GL surface) before plugins are +// registered. A plain remove/add would unrealize the FlView and break its GL +// context, so the move uses gtk_widget_reparent(), which keeps a widget +// realized when the destination is realized too: +// 1. realize a new overlay inside a temporary (never shown) window, +// 2. move the FlView into it (the GtkWindow is now empty), +// 3. move the overlay into the GtkWindow. +GtkOverlay* ensure_overlay(FlView* view) { + GtkWidget* view_widget = GTK_WIDGET(view); + GtkWidget* parent = gtk_widget_get_parent(view_widget); + if (parent != nullptr && GTK_IS_OVERLAY(parent)) return GTK_OVERLAY(parent); + + GtkWidget* overlay = gtk_overlay_new(); + gtk_widget_show(overlay); + if (parent == nullptr) { + // Not in a window yet: the host app will add it later, which would fail + // if we parented it here. Ask for the runner change instead. + g_warning( + "cesiumjs: the FlView has no parent at plugin registration; wrap it " + "in a GtkOverlay in the runner (see README)."); + return GTK_OVERLAY(overlay); + } + + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + if (gtk_widget_get_realized(view_widget)) { + GtkWidget* temp = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_container_add(GTK_CONTAINER(temp), overlay); + gtk_widget_realize(overlay); + gtk_widget_reparent(view_widget, overlay); + gtk_widget_reparent(overlay, parent); + gtk_widget_destroy(temp); + } else { + g_object_ref(view_widget); + gtk_container_remove(GTK_CONTAINER(parent), view_widget); + gtk_container_add(GTK_CONTAINER(overlay), view_widget); + gtk_container_add(GTK_CONTAINER(parent), overlay); + g_object_unref(view_widget); + } + G_GNUC_END_IGNORE_DEPRECATIONS + return GTK_OVERLAY(overlay); +} + +} // namespace + +void cesiumjs_plugin_register_with_registrar(FlPluginRegistrar* registrar) { + if (g_plugin != nullptr) return; // one FlView per app is supported + FlView* view = fl_plugin_registrar_get_view(registrar); + if (view == nullptr) { + g_warning("cesiumjs: no FlView available (headless?); plugin disabled."); + return; + } + + g_plugin = new Plugin(); + g_plugin->overlay = ensure_overlay(view); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_plugin->channel = fl_method_channel_new( + fl_plugin_registrar_get_messenger(registrar), kChannelName, + FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(g_plugin->channel, method_call_cb, + nullptr, nullptr); + + g_signal_connect(g_plugin->overlay, "get-child-position", + G_CALLBACK(on_get_child_position), nullptr); +} diff --git a/linux/include/cesiumjs/cesiumjs_plugin.h b/linux/include/cesiumjs/cesiumjs_plugin.h new file mode 100644 index 0000000..8af0cfb --- /dev/null +++ b/linux/include/cesiumjs/cesiumjs_plugin.h @@ -0,0 +1,28 @@ +#ifndef FLUTTER_PLUGIN_CESIUMJS_PLUGIN_H_ +#define FLUTTER_PLUGIN_CESIUMJS_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +// Native side of the `cesiumjs/webview` method channel. +// +// Flutter on Linux has no platform-view support, so each CesiumJS web view is +// a real WebKitGTK widget stacked on top of the FlView inside a GtkOverlay. +// The Dart `CesiumViewer` widget reports its on-screen rectangle and the +// native widget is positioned to match. +// +// If the FlView is not already inside a GtkOverlay, registration wraps it in +// one, so host apps need no runner changes. +FLUTTER_PLUGIN_EXPORT void cesiumjs_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_CESIUMJS_PLUGIN_H_ diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..bd0119d --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,23 @@ +name: cesiumjs +description: "CesiumJS 3D globe for Flutter Linux desktop, rendered in a native WebKitGTK view." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.13.7 + flutter: '>=3.32.0' + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + plugin: + platforms: + linux: + pluginClass: CesiumjsPlugin diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..c845519 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,17 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:cesiumjs/cesiumjs.dart'; + +void main() { + test('CesiumMessage parses JSON messages', () { + final m = CesiumMessage.parse('{"type":"ready","webgl":2}'); + expect(m.type, 'ready'); + expect(m.data['webgl'], 2); + }); + + test('CesiumMessage falls back to raw for non-JSON', () { + final m = CesiumMessage.parse('hello'); + expect(m.type, 'raw'); + expect(m.data['value'], 'hello'); + }); +}