android and windows targets

This commit is contained in:
yves committed 2026-11-07 15:48:01 +01:00
1 parent c069b8945d
commit 1d974b42a1
58 files changed
+2596 -106

No files matched your search

+24 -1
View File
@@ -8,7 +8,30 @@
"cwd": "example",
"program": "lib/main.dart",
"deviceId": "linux",
"toolArgs": ["--dart-define-from-file=cesium_ion.json"]
"toolArgs": [
"--dart-define-from-file=cesium_ion.json"
]
},
{
"name": "example (android)",
"request": "launch",
"type": "dart",
"cwd": "example",
"program": "lib/main.dart",
"toolArgs": [
"--dart-define-from-file=cesium_ion.json"
]
},
{
"name": "example (windows)",
"request": "launch",
"type": "dart",
"cwd": "example",
"program": "lib/main.dart",
"deviceId": "windows",
"toolArgs": [
"--dart-define-from-file=cesium_ion.json"
]
}
]
}
+8
View File
@@ -1,3 +1,11 @@
## 0.2.0
* Android support: system `WebView` shown as a platform view (Flutter widgets
can be drawn over the globe on Android).
* Windows support: WebView2 in a native child window over the Flutter view
(WebView2 SDK fetched from NuGet at build time).
* JS bridge (`CesiumChannel.postMessage`) works on all three platforms.
## 0.1.0
* First packaged version: `CesiumViewer` widget + `CesiumController` for
+26 -5
View File
@@ -1,6 +1,6 @@
# CLAUDE.md
Flutter **plugin** (Linux desktop only) embedding a CesiumJS globe. The
Flutter **plugin** (Linux, Android, Windows) 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.
@@ -10,15 +10,26 @@ package is meant to be imported by other apps: keep the public API in
```sh
flutter pub get && flutter analyze && flutter test # package (root)
cd example && flutter build linux --debug # compiles the native plugin
cd example && flutter build apk --debug # compiles the Kotlin 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/`.
through the example app — after changing `linux/cesiumjs_plugin.cc` or
`android/`, always run the matching `flutter build` in `example/`.
`windows/cesiumjs_plugin.cpp` cannot be built from Linux (needs MSVC); it
compiles with `/W4 /WX`, so avoid unused parameters, shadowed names and
narrowing.
Android test emulator: AVD `cesium_test` (API 35, x86_64), lives in
`~/.config/.android/avd` → start with
`ANDROID_AVD_HOME=~/.config/.android/avd ~/Android/Sdk/emulator/emulator -avd cesium_test`.
## Architecture
All platforms share the `cesiumjs/webview` channel protocol (`create`
eagerly builds the web view keyed by a Dart id; other calls address it by id).
- `CesiumViewer` (Dart) renders a black placeholder and reports its global
rect after each paint (`_RenderRectReporter`) → `setRect` over the
`cesiumjs/webview` method channel.
@@ -28,7 +39,17 @@ run `flutter build linux` in `example/`.
`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`.
- Android (`android/…/CesiumjsPlugin.kt`): `create` builds an
`android.webkit.WebView`; the widget then shows it with an `AndroidView`
(view type `cesiumjs/webview`, creation param `id`). `setRect` is a no-op.
Flutter widgets *can* paint over the globe here.
- Windows (`windows/cesiumjs_plugin.cpp`): WebView2 in a host child window,
sibling of the Flutter view, placed at `rect * scale` (Dart sends
`devicePixelRatio` as `scale`). Page served from `https://cesium.localhost/`
via `WebResourceRequested`. WebView2 SDK downloaded from NuGet by CMake.
- JS → Dart: `CesiumChannel.postMessage` → `window.webkit.messageHandlers.cesium`
(Linux), `window.CesiumAndroid.postMessage` (Android),
`window.chrome.webview.postMessage` (Windows).
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
@@ -46,7 +67,7 @@ run `flutter build linux` in `example/`.
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`.
- Linux/Windows: 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`.
+47 -27
View File
@@ -1,27 +1,35 @@
# cesiumjs
A Flutter plugin that embeds a [CesiumJS](https://cesium.com/platform/cesiumjs/)
3D globe in Flutter **Linux desktop** apps.
3D globe in Flutter apps on **Linux, Windows and Android**.
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 | Web engine | Integration | Status |
|---|---|---|---|
| Linux (X11) | WebKitGTK 4.1 | Native view stacked above the Flutter surface | Tested |
| Android 7+ | System WebView (Chromium) | Platform view (`AndroidView`) | Tested (emulator, API 35) |
| Windows 10/11 | WebView2 (Edge) | Native child window stacked above the Flutter view | Not yet tested |
| Other platforms | — | The widget shows a "not supported" placeholder | — |
| Platform | Status |
|---|---|
| Linux (X11) | Supported |
| Other platforms | The widget shows a "not supported" placeholder |
On Linux and Windows the globe is a native web view kept aligned with the
`CesiumViewer` widget's rectangle (Flutter has no platform views there). On
Android it is a regular platform view, composed with the rest of the UI.
All three engines render WebGL2 on the GPU.
## Requirements
- Flutter ≥ 3.32 / Dart ≥ 3.13
- WebKitGTK 4.1 development files at build time:
- **Linux**: 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.
- **Android**: `minSdk` 24. The plugin declares the `INTERNET` permission.
- **Windows**: the WebView2 SDK is downloaded from NuGet by CMake on the
first build (needs network access; SHA-256 pinned in
`windows/CMakeLists.txt`). End users need the
[WebView2 Runtime](https://developer.microsoft.com/microsoft-edge/webview2/),
preinstalled on Windows 11 and up-to-date Windows 10.
- 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
@@ -35,9 +43,10 @@ dependencies:
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.
No runner changes are needed on any platform. On Linux the plugin wraps the
app's `FlView` in a `GtkOverlay` at registration (an existing `GtkOverlay`
parent is reused). On Windows the web views are created as siblings of the
Flutter view inside the runner's top-level window.
## Usage
@@ -80,7 +89,7 @@ class _GlobePageState extends State<GlobePage> {
| `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) |
| `visible` | Hides the web view without destroying it (keeps camera state) |
### `CesiumController`
@@ -93,7 +102,7 @@ class _GlobePageState extends State<GlobePage> {
| `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 |
| `openInspector()` | Opens the dev tools (WebKit inspector on Linux, Edge DevTools on Windows). On Android, debug builds can be inspected from `chrome://inspect` instead; this call does nothing |
| `isReady`, `messages` | Ready flag and broadcast stream of `CesiumMessage`s |
Controller calls are only valid after `onReady` (or `isReady == true`).
@@ -114,35 +123,41 @@ 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.
- **Linux and Windows: Flutter widgets cannot be drawn over the globe**: the
web view is a native window above the Flutter surface. Put controls around
it, or set `visible: false` while a dialog, menu or drawer overlaps it. The
view is hidden automatically when another route is pushed on top. (Android
has no such restriction.)
- Linux and Windows: the widget is positioned in window coordinates; don't
place it inside a scroll view that clips it.
- One Flutter view per app (the default) is supported.
- Tested on X11. Wayland is untested.
- Linux: tested on X11. Wayland is untested.
- Windows: written against WebView2 SDK 1.0.4314.35 but not yet compiled or
run on a Windows machine.
## Example app
`example/` is a test app with places, imagery and terrain switches, markers
and a camera readout.
and a camera readout. On narrow screens (phones) the side panel becomes a drawer.
```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
flutter run -d windows --dart-define-from-file=cesium_ion.json
flutter run -d <android-device-id> --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`.
`cesium_ion.json` is git-ignored. VS Code launch configurations
("example (linux)", "example (android)", "example (windows)") are provided in
`.vscode/launch.json`.
## Development
```sh
flutter analyze
flutter test
cd example && flutter build linux
cd example && flutter build linux # or: flutter build apk / flutter build windows
```
Layout:
@@ -150,11 +165,16 @@ Layout:
```
lib/
cesiumjs.dart public API (barrel)
src/cesium_viewer.dart CesiumViewer widget, reports its rect to native
src/cesium_viewer.dart CesiumViewer widget (AndroidView on Android,
reports its rect to native on desktop)
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
android/src/main/kotlin/…/CesiumjsPlugin.kt
android.webkit.WebView + platform view factory
windows/
cesiumjs_plugin.cpp WebView2 in child windows over the Flutter view
example/ test / demo app
```
+2
View File
@@ -13,6 +13,8 @@ analyzer:
exclude:
- build/**
- linux/**
- android/**
- windows/**
linter:
# The lint rules applied to this project can be customized in the
+9
View File
@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.cxx
+53
View File
@@ -0,0 +1,53 @@
group = "fr.irt_saintexupery.cesiumjs"
version = "1.0-SNAPSHOT"
buildscript {
val kotlinVersion = "2.4.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:9.1.0")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
plugins {
id("com.android.library")
}
android {
namespace = "fr.irt_saintexupery.cesiumjs"
compileSdk = 36
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
sourceSets {
getByName("main") {
java.srcDirs("src/main/kotlin")
}
}
defaultConfig {
minSdk = 24
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
+1
View File
@@ -0,0 +1 @@
rootProject.name = "cesiumjs"
+4
View File
@@ -0,0 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- CesiumJS, imagery and terrain are loaded from the network. -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,221 @@
package fr.irt_saintexupery.cesiumjs
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.graphics.Color
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
import org.json.JSONTokener
/**
* Android side of the `cesiumjs/webview` channel.
*
* Same protocol as the Linux plugin: `create` builds an [android.webkit.WebView]
* keyed by a Dart-side id, the other methods address it by id. The view is
* shown by an `AndroidView` (platform view type `cesiumjs/webview`) whose
* creation params carry that id; `setRect` is a no-op because Flutter lays the
* platform view out itself.
*/
class CesiumjsPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
private lateinit var appContext: Context
private var activityContext: Context? = null
private val views = HashMap<Int, WebView>()
private val mainHandler = Handler(Looper.getMainLooper())
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
appContext = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, CHANNEL)
channel.setMethodCallHandler(this)
binding.platformViewRegistry.registerViewFactory(CHANNEL, Factory())
val debuggable =
appContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
// Debug builds: inspect the page from chrome://inspect on the host.
if (debuggable) WebView.setWebContentsDebuggingEnabled(true)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
disposeAll()
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activityContext = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
activityContext = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activityContext = binding.activity
}
override fun onDetachedFromActivity() {
activityContext = null
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
val id = call.argument<Number>("id")?.toInt()
when (call.method) {
"create" -> {
val html = call.argument<String>("html")
if (id == null || html == null) {
result.error("bad_args", "create requires id and html", null)
} else if (views.containsKey(id)) {
result.error("exists", "a view with this id already exists", null)
} else {
val baseUrl = call.argument<String>("baseUrl") ?: BASE_URL
views[id] = createWebView(id, html, baseUrl)
result.success(null)
}
}
"setRect" -> result.success(null) // laid out by the platform view
"runJavaScript" -> {
val view = views[id]
val script = call.argument<String>("script")
when {
view == null -> result.error("not_found", "unknown view id", null)
script == null -> result.error("bad_args", "script missing", null)
else -> view.evaluateJavascript(script) { json ->
result.success(jsonToString(json))
}
}
}
// No in-app inspector on Android: use chrome://inspect (debug builds).
"openInspector" -> result.success(null)
"dispose" -> {
id?.let { destroy(it) }
result.success(null)
}
"disposeAll" -> {
disposeAll()
result.success(null)
}
else -> result.notImplemented()
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun createWebView(id: Int, html: String, baseUrl: String): WebView {
val view = WebView(activityContext ?: appContext)
view.setBackgroundColor(Color.BLACK)
view.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
mediaPlaybackRequiresUserGesture = true
setSupportMultipleWindows(false)
}
// JS -> Dart. Called on a WebView binder thread.
view.addJavascriptInterface(object {
@JavascriptInterface
fun postMessage(message: String) {
mainHandler.post { sendEvent("onMessage", id, message) }
}
}, JS_INTERFACE)
view.webViewClient = object : WebViewClient() {
// Links clicked in the page (Cesium credits...) open in the browser.
override fun shouldOverrideUrlLoading(
v: WebView,
request: WebResourceRequest,
): Boolean {
if (!request.isForMainFrame) return false
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(request.url.toString()))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
v.context.startActivity(intent)
} catch (_: Exception) {
}
return true
}
override fun onReceivedError(
v: WebView,
request: WebResourceRequest,
error: WebResourceError,
) {
if (request.isForMainFrame || request.url.toString().contains("Cesium.js")) {
sendEvent("onError", id, "Load failed (${request.url}): ${error.description}")
}
}
override fun onRenderProcessGone(v: WebView, detail: RenderProcessGoneDetail): Boolean {
sendEvent(
"onError", id,
if (detail.didCrash()) "Web process crashed"
else "Web process terminated (memory pressure)",
)
destroy(id)
return true // keep the app alive
}
}
view.loadDataWithBaseURL(baseUrl, html, "text/html", "utf-8", null)
return view
}
private fun sendEvent(method: String, id: Int, message: String) {
channel.invokeMethod(method, mapOf("id" to id, "message" to message))
}
private fun destroy(id: Int) {
val view = views.remove(id) ?: return
(view.parent as? ViewGroup)?.removeView(view)
view.destroy()
}
private fun disposeAll() {
views.keys.toList().forEach { destroy(it) }
}
/** Hands the already-created WebView to Flutter's platform view machinery. */
private inner class Factory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
val id = ((args as? Map<*, *>)?.get("id") as? Number)?.toInt()
val webView = id?.let { views[it] }
val view: View = webView ?: View(context).apply { setBackgroundColor(Color.BLACK) }
// The platform view may be recreated (e.g. widget reparented).
(view.parent as? ViewGroup)?.removeView(view)
return object : PlatformView {
override fun getView(): View = view
// The WebView's lifetime is driven by the `dispose` method.
override fun dispose() {}
}
}
}
companion object {
private const val CHANNEL = "cesiumjs/webview"
private const val JS_INTERFACE = "CesiumAndroid"
private const val BASE_URL = "https://cesium.localhost/"
/** evaluateJavascript returns JSON; mimic the Linux "toString" result. */
private fun jsonToString(json: String?): String? {
if (json == null || json == "null" || json == "undefined") return null
if (!json.startsWith("\"")) return json
return try {
JSONTokener(json).nextValue() as? String ?: json
} catch (_: Exception) {
json
}
}
}
}
+2
View File
@@ -13,6 +13,8 @@ analyzer:
exclude:
- build/**
- linux/**
- android/**
- windows/**
linter:
# The lint rules applied to this project can be customized in the
+14
View File
@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks
+49
View File
@@ -0,0 +1,49 @@
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "fr.irt_saintexupery.cesiumjs_example"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "fr.irt_saintexupery.cesiumjs_example"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
// flag during build.
versionCode = flutter.versionCode
versionName = flutter.versionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
@@ -0,0 +1,45 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="cesiumjs_example"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
@@ -0,0 +1,5 @@
package fr.irt_saintexupery.cesiumjs_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+24
View File
@@ -0,0 +1,24 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}
+6
View File
@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
+26
View File
@@ -0,0 +1,26 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.1.0" apply false
id("org.jetbrains.kotlin.android") version "2.4.0" apply false
}
include(":app")
+59 -53
View File
@@ -4,7 +4,7 @@ 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
/// flutter run --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');
@@ -138,9 +138,58 @@ class _DemoPageState extends State<DemoPage> {
Widget build(BuildContext context) {
final ready = _controller.isReady;
const hasToken = ionToken != '';
// Phones: the side panel becomes a drawer.
final narrow = MediaQuery.sizeOf(context).width < 700;
final panel = ListView(
children: [
for (final p in _places)
ListTile(
dense: true,
leading: const Icon(Icons.place_outlined),
title: Text(p.name),
enabled: ready,
onTap: () {
if (narrow) Navigator.of(context).pop(); // close the drawer
_goTo(p);
},
),
const Divider(),
const ListTile(dense: true, title: Text('Orthophoto / fond')),
RadioGroup<CesiumImagery>(
groupValue: _imagery,
onChanged: (v) {
if (ready && v != null) _controller.setImagery(v);
},
child: Column(
children: [
for (final i in CesiumImagery.values)
RadioListTile<CesiumImagery>(
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,
),
],
);
final viewer = CesiumViewer(
ionToken: hasToken ? ionToken : null,
controller: _controller,
onMessage: _onMessage,
onError: (e) => setState(() => _status = 'Error: $e'),
);
return Scaffold(
drawer: narrow ? Drawer(child: SafeArea(child: panel)) : null,
appBar: AppBar(
title: const Text('CesiumJS in Flutter (Linux / WebKitGTK)'),
title: const Text('CesiumJS in Flutter'),
actions: [
IconButton(
tooltip: 'Clear markers',
@@ -164,68 +213,25 @@ class _DemoPageState extends State<DemoPage> {
),
],
),
body: Row(
body: narrow
? viewer
: 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<CesiumImagery>(
groupValue: _imagery,
onChanged: (v) {
if (ready && v != null) _controller.setImagery(v);
},
child: Column(
children: [
for (final i in CesiumImagery.values)
RadioListTile<CesiumImagery>(
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'),
),
),
SizedBox(width: 230, child: panel),
Expanded(child: viewer),
],
),
bottomNavigationBar: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
color: Theme.of(context).colorScheme.surfaceContainer,
child: SafeArea(
top: false,
child: Text(
'$_status $_camera',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
);
}
}
+4 -4
View File
@@ -126,10 +126,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d
url: "https://pub.dev"
source: hosted
version: "1.19.0"
version: "1.18.3"
path:
dependency: transitive
description:
@@ -195,10 +195,10 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc
sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188"
url: "https://pub.dev"
source: hosted
version: "2.4.4"
version: "2.4.0"
vm_service:
dependency: transitive
description:
+17
View File
@@ -0,0 +1,17 @@
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
+108
View File
@@ -0,0 +1,108 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.14)
project(cesiumjs_example 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")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# Define build configuration option.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
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()
endif()
# Define settings for the Profile build mode.
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# 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_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
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)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
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.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)
+109
View File
@@ -0,0 +1,109 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.14)
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.
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
# Set fallback configurations for older versions of the flutter tool.
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
set(FLUTTER_TARGET_PLATFORM "windows-x64")
endif()
# === Flutter Library ===
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
# 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/windows/app.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"flutter_export.h"
"flutter_windows.h"
"flutter_messenger.h"
"flutter_plugin_registrar.h"
"flutter_texture_registrar.h"
)
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
add_dependencies(flutter flutter_assemble)
# === Wrapper ===
list(APPEND CPP_WRAPPER_SOURCES_CORE
"core_implementations.cc"
"standard_codec.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
"plugin_registrar.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_APP
"flutter_engine.cc"
"flutter_view_controller.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
# Wrapper sources needed for a plugin.
add_library(flutter_wrapper_plugin STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
)
apply_standard_settings(flutter_wrapper_plugin)
set_target_properties(flutter_wrapper_plugin PROPERTIES
POSITION_INDEPENDENT_CODE ON)
set_target_properties(flutter_wrapper_plugin PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
target_include_directories(flutter_wrapper_plugin PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_plugin flutter_assemble)
# Wrapper sources needed for the runner.
add_library(flutter_wrapper_app STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_APP}
)
apply_standard_settings(flutter_wrapper_app)
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
target_include_directories(flutter_wrapper_app PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_app 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.
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
${PHONY_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
)
@@ -0,0 +1,14 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <cesiumjs/cesiumjs_plugin_c_api.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
CesiumjsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("CesiumjsPluginCApi"));
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
@@ -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}/windows plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
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}/windows plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
+40
View File
@@ -0,0 +1,40 @@
cmake_minimum_required(VERSION 3.14)
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} WIN32
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
"win32_window.cpp"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
"Runner.rc"
"runner.exe.manifest"
)
# 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 build version.
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
# Disable Windows macros that collide with C++ standard library functions.
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
# Add dependency libraries and include directories. Add any application-specific
# dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
+121
View File
@@ -0,0 +1,121 @@
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
#else
#define VERSION_AS_NUMBER 1,0,0,0
#endif
#if defined(FLUTTER_VERSION)
#define VERSION_AS_STRING FLUTTER_VERSION
#else
#define VERSION_AS_STRING "1.0.0"
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VERSION_AS_NUMBER
PRODUCTVERSION VERSION_AS_NUMBER
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "fr.irt_saintexupery" "\0"
VALUE "FileDescription", "cesiumjs_example" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "cesiumjs_example" "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 fr.irt_saintexupery. All rights reserved." "\0"
VALUE "OriginalFilename", "cesiumjs_example.exe" "\0"
VALUE "ProductName", "cesiumjs_example" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
+71
View File
@@ -0,0 +1,71 @@
#include "flutter_window.h"
#include <optional>
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window {
public:
// Creates a new FlutterWindow hosting a Flutter view running |project|.
explicit FlutterWindow(const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
private:
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_
+43
View File
@@ -0,0 +1,43 @@
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.Create(L"cesiumjs_example", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
+16
View File
@@ -0,0 +1,16 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>
+69
View File
@@ -0,0 +1,69 @@
#include "utils.h"
#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
void CreateAndAttachConsole() {
if (::AllocConsole()) {
FILE *unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
FlutterDesktopResyncOutputStreams();
}
}
std::vector<std::string> GetCommandLineArguments() {
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argv == nullptr) {
return std::vector<std::string>();
}
std::vector<std::string> command_line_arguments;
// Skip the first argument as it's the binary name.
for (int i = 1; i < argc; i++) {
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
}
::LocalFree(argv);
return command_line_arguments;
}
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
// First, find the length of the string with a safe upper bound (CWE-126).
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
// Now use that bounded length to determine the required buffer size.
// When an explicit length is passed, WideCharToMultiByte does not include
// the null terminator in its returned size.
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, nullptr, 0, nullptr, nullptr);
std::string utf8_string;
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
return utf8_string;
}
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, utf8_string.data(), target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
+288
View File
@@ -0,0 +1,288 @@
#include "win32_window.h"
#include <dwmapi.h>
#include <flutter_windows.h>
#include "resource.h"
namespace {
/// Window attribute that enables dark mode window decorations.
///
/// Redefined in case the developer's machine has a Windows SDK older than
/// version 10.0.22000.0.
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
/// Registry key for app theme preference.
///
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
/// value indicates apps should use light mode.
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
// The number of Win32Window objects that currently exist.
static int g_active_window_count = 0;
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in
// scale factor
int Scale(int source, double scale_factor) {
return static_cast<int>(source * scale_factor);
}
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
// This API is only needed for PerMonitor V1 awareness mode.
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
HMODULE user32_module = LoadLibraryA("User32.dll");
if (!user32_module) {
return;
}
auto enable_non_client_dpi_scaling =
reinterpret_cast<EnableNonClientDpiScaling*>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) {
enable_non_client_dpi_scaling(hwnd);
}
FreeLibrary(user32_module);
}
} // namespace
// Manages the Win32Window's window class registration.
class WindowClassRegistrar {
public:
~WindowClassRegistrar() = default;
// Returns the singleton registrar instance.
static WindowClassRegistrar* GetInstance() {
if (!instance_) {
instance_ = new WindowClassRegistrar();
}
return instance_;
}
// Returns the name of the window class, registering the class if it hasn't
// previously been registered.
const wchar_t* GetWindowClass();
// Unregisters the window class. Should only be called if there are no
// instances of the window.
void UnregisterWindowClass();
private:
WindowClassRegistrar() = default;
static WindowClassRegistrar* instance_;
bool class_registered_ = false;
};
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() {
if (!class_registered_) {
WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.hIcon =
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
window_class.hbrBackground = 0;
window_class.lpszMenuName = nullptr;
window_class.lpfnWndProc = Win32Window::WndProc;
RegisterClass(&window_class);
class_registered_ = true;
}
return kWindowClassName;
}
void WindowClassRegistrar::UnregisterWindowClass() {
UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false;
}
Win32Window::Win32Window() {
++g_active_window_count;
}
Win32Window::~Win32Window() {
--g_active_window_count;
Destroy();
}
bool Win32Window::Create(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(origin.x),
static_cast<LONG>(origin.y)};
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
UpdateTheme(window);
return OnCreate();
}
bool Win32Window::Show() {
return ShowWindow(window_handle_, SW_SHOWNORMAL);
}
// static
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
if (message == WM_NCCREATE) {
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
EnableFullDpiSupportIfAvailable(window);
that->window_handle_ = window;
} else if (Win32Window* that = GetThisFromHandle(window)) {
return that->MessageHandler(window, message, wparam, lparam);
}
return DefWindowProc(window, message, wparam, lparam);
}
LRESULT
Win32Window::MessageHandler(HWND hwnd,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
switch (message) {
case WM_DESTROY:
window_handle_ = nullptr;
Destroy();
if (quit_on_close_) {
PostQuitMessage(0);
}
return 0;
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_SIZE: {
RECT rect = GetClientArea();
if (child_content_ != nullptr) {
// Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE);
}
return 0;
}
case WM_ACTIVATE:
if (child_content_ != nullptr) {
SetFocus(child_content_);
}
return 0;
case WM_DWMCOLORIZATIONCOLORCHANGED:
UpdateTheme(hwnd);
return 0;
}
return DefWindowProc(window_handle_, message, wparam, lparam);
}
void Win32Window::Destroy() {
OnDestroy();
if (window_handle_) {
DestroyWindow(window_handle_);
window_handle_ = nullptr;
}
if (g_active_window_count == 0) {
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
}
}
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
return reinterpret_cast<Win32Window*>(
GetWindowLongPtr(window, GWLP_USERDATA));
}
void Win32Window::SetChildContent(HWND content) {
child_content_ = content;
SetParent(content, window_handle_);
RECT frame = GetClientArea();
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
frame.bottom - frame.top, true);
SetFocus(child_content_);
}
RECT Win32Window::GetClientArea() {
RECT frame;
GetClientRect(window_handle_, &frame);
return frame;
}
HWND Win32Window::GetHandle() {
return window_handle_;
}
void Win32Window::SetQuitOnClose(bool quit_on_close) {
quit_on_close_ = quit_on_close;
}
bool Win32Window::OnCreate() {
// No-op; provided for subclasses.
return true;
}
void Win32Window::OnDestroy() {
// No-op; provided for subclasses.
}
void Win32Window::UpdateTheme(HWND const window) {
DWORD light_mode;
DWORD light_mode_size = sizeof(light_mode);
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
kGetPreferredBrightnessRegValue,
RRF_RT_REG_DWORD, nullptr, &light_mode,
&light_mode_size);
if (result == ERROR_SUCCESS) {
BOOL enable_dark_mode = light_mode == 0;
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
&enable_dark_mode, sizeof(enable_dark_mode));
}
}
+102
View File
@@ -0,0 +1,102 @@
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates a win32 window with |title| that is positioned and sized using
// |origin| and |size|. New windows are created on the default monitor. Window
// sizes are specified to the OS in physical pixels, hence to ensure a
// consistent size this function will scale the inputted width and height as
// as appropriate for the default monitor. The window is invisible until
// |Show| is called. Returns true if the window was created successfully.
bool Create(const std::wstring& title, const Point& origin, const Size& size);
// Show the current window. Returns true if the window was successfully shown.
bool Show();
// Release OS resources associated with window.
void Destroy();
// Inserts |content| into the window tree.
void SetChildContent(HWND content);
// Returns the backing Window handle to enable clients to set icon and other
// window properties. Returns nullptr if the window has been destroyed.
HWND GetHandle();
// If true, closing this window will quit the application.
void SetQuitOnClose(bool quit_on_close);
// Return a RECT representing the bounds of the current client area.
RECT GetClientArea();
protected:
// Processes and route salient window messages for mouse handling,
// size change and DPI. Delegates handling of these to member overloads that
// inheriting classes can handle.
virtual LRESULT MessageHandler(HWND window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Called when CreateAndShow is called, allowing subclass window-related
// setup. Subclasses should return false if setup fails.
virtual bool OnCreate();
// Called when Destroy is called.
virtual void OnDestroy();
private:
friend class WindowClassRegistrar;
// OS callback called by message pump. Handles the WM_NCCREATE message which
// is passed when the non-client area is being created and enables automatic
// non-client DPI scaling so that the non-client area automatically
// responds to changes in DPI. All other messages are handled by
// MessageHandler.
static LRESULT CALLBACK WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Retrieves a class instance pointer for |window|
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
// Update the window frame's theme to match the system theme.
static void UpdateTheme(HWND const window);
bool quit_on_close_ = false;
// window handle for top level window.
HWND window_handle_ = nullptr;
// window handle for hosted content.
HWND child_content_ = nullptr;
};
#endif // RUNNER_WIN32_WINDOW_H_
+9 -1
View File
@@ -28,11 +28,19 @@ String buildCesiumHtml({String? ionToken}) {
<body>
<div id="cesiumContainer"></div>
<script>
// JS -> Dart bridge (WebKitGTK script message handler).
// JS -> Dart bridge: WebKitGTK script message handler (Linux), Java
// interface (Android) or WebView2 web messages (Windows).
window.CesiumChannel = {
postMessage: function (msg) {
if (typeof msg !== 'string') msg = JSON.stringify(msg);
if (window.webkit && window.webkit.messageHandlers &&
window.webkit.messageHandlers.cesium) {
window.webkit.messageHandlers.cesium.postMessage(msg);
} else if (window.CesiumAndroid) {
window.CesiumAndroid.postMessage(msg);
} else if (window.chrome && window.chrome.webview) {
window.chrome.webview.postMessage(msg);
}
}
};
window.addEventListener('error', function (e) {
+62 -10
View File
@@ -1,6 +1,8 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'cesium_controller.dart';
import 'cesium_html.dart';
@@ -8,8 +10,15 @@ 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:
/// Supported on Linux (WebKitGTK), Windows (WebView2) and Android (system
/// WebView).
///
/// On Android the web view is a regular platform view: it is composed with
/// the Flutter UI like any other widget.
///
/// On Linux and Windows the globe is a native 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
@@ -47,10 +56,19 @@ class _CesiumViewerState extends State<CesiumViewer> {
bool _disposed = false;
Rect? _sentRect;
bool? _sentVisible;
double? _sentScale;
Rect _currentRect = Rect.zero;
bool get _supported =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.linux;
static bool get _supported =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.linux ||
defaultTargetPlatform == TargetPlatform.windows ||
defaultTargetPlatform == TargetPlatform.android);
/// Android composes the web view as a platform view; the desktop
/// platforms place a native view over the reported rectangle.
static bool get _isPlatformView =>
defaultTargetPlatform == TargetPlatform.android;
@override
void initState() {
@@ -67,8 +85,9 @@ class _CesiumViewerState extends State<CesiumViewer> {
await CesiumNativeChannel.instance.dispose(id);
return;
}
_viewId = id;
_controller.attach(id);
// Rebuild: on Android the platform view can be created now.
setState(() => _viewId = id);
_sync();
}
@@ -89,14 +108,28 @@ class _CesiumViewerState extends State<CesiumViewer> {
_sync();
}
bool get _effectiveVisible =>
widget.visible && TickerMode.valuesOf(context).enabled;
void _sync() {
final id = _viewId;
if (id == null || _disposed) return;
final visible = widget.visible && TickerMode.valuesOf(context).enabled;
if (_sentRect == _currentRect && _sentVisible == visible) return;
if (id == null || _disposed || _isPlatformView) return;
final visible = _effectiveVisible;
final scale = MediaQuery.devicePixelRatioOf(context);
if (_sentRect == _currentRect &&
_sentVisible == visible &&
_sentScale == scale) {
return;
}
_sentRect = _currentRect;
_sentVisible = visible;
CesiumNativeChannel.instance.setRect(id, _currentRect, visible: visible);
_sentScale = scale;
CesiumNativeChannel.instance.setRect(
id,
_currentRect,
visible: visible,
scale: scale,
);
}
@override
@@ -129,12 +162,31 @@ class _CesiumViewerState extends State<CesiumViewer> {
color: Colors.black,
child: Center(
child: Text(
'CesiumViewer currently supports Linux desktop only.',
'CesiumViewer supports Linux, Windows and Android only.',
style: TextStyle(color: Colors.white70),
),
),
);
}
if (_isPlatformView) {
final id = _viewId;
if (id == null) {
return const SizedBox.expand(child: ColoredBox(color: Colors.black));
}
return Visibility(
visible: _effectiveVisible,
maintainState: true,
child: AndroidView(
viewType: CesiumNativeChannel.viewType,
creationParams: {'id': id},
creationParamsCodec: const StandardMessageCodec(),
// The globe handles every gesture that starts on it.
gestureRecognizers: {
Factory<OneSequenceGestureRecognizer>(EagerGestureRecognizer.new),
},
),
);
}
// SizedBox.expand: a childless ColoredBox would size to 0x0 under loose
// constraints, which hides the native view.
return _RectReporter(
+15 -3
View File
@@ -2,8 +2,8 @@ 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`.
/// Thin wrapper over the `cesiumjs/webview` method channel implemented by
/// the native plugins (`linux/`, `windows/`, `android/`).
class CesiumNativeChannel {
CesiumNativeChannel._() {
_channel.setMethodCallHandler(_onCall);
@@ -11,6 +11,9 @@ class CesiumNativeChannel {
static final CesiumNativeChannel instance = CesiumNativeChannel._();
/// Android platform view type (same name as the channel).
static const String viewType = 'cesiumjs/webview';
final MethodChannel _channel = const MethodChannel('cesiumjs/webview');
final Map<int, NativeEventHandler> _handlers = {};
int _nextId = 0;
@@ -34,7 +37,15 @@ class CesiumNativeChannel {
return id;
}
Future<void> setRect(int id, Rect rect, {required bool visible}) =>
/// [rect] is in logical pixels relative to the Flutter view; [scale] is
/// its device pixel ratio (used by Windows, where windows use physical
/// pixels).
Future<void> setRect(
int id,
Rect rect, {
required bool visible,
required double scale,
}) =>
_channel.invokeMethod<void>('setRect', {
'id': id,
'x': rect.left,
@@ -42,6 +53,7 @@ class CesiumNativeChannel {
'width': rect.width,
'height': rect.height,
'visible': visible,
'scale': scale,
});
Future<String?> runJavaScript(int id, String script) => _channel
+7 -2
View File
@@ -1,6 +1,6 @@
name: cesiumjs
description: "CesiumJS 3D globe for Flutter Linux desktop, rendered in a native WebKitGTK view."
version: 0.1.0
description: "CesiumJS 3D globe for Flutter (Linux, Windows, Android), rendered in a native web view."
version: 0.2.0
publish_to: 'none'
environment:
@@ -19,5 +19,10 @@ dev_dependencies:
flutter:
plugin:
platforms:
android:
package: fr.irt_saintexupery.cesiumjs
pluginClass: CesiumjsPlugin
linux:
pluginClass: CesiumjsPlugin
windows:
pluginClass: CesiumjsPluginCApi
+17
View File
@@ -0,0 +1,17 @@
flutter/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
+53
View File
@@ -0,0 +1,53 @@
cmake_minimum_required(VERSION 3.14)
set(PROJECT_NAME "cesiumjs")
project(${PROJECT_NAME} LANGUAGES CXX)
cmake_policy(VERSION 3.14...3.25)
set(PLUGIN_NAME "cesiumjs_plugin")
# --- WebView2 SDK (headers + static loader), fetched from NuGet ------------
set(WEBVIEW2_VERSION "1.0.4314.35")
set(WEBVIEW2_SHA256
"90778deb1b77e36292828b4b5833c9255c27533f40e0ddd55891ae718944edc4")
set(WEBVIEW2_DIR "${CMAKE_BINARY_DIR}/webview2-${WEBVIEW2_VERSION}")
if(NOT EXISTS "${WEBVIEW2_DIR}/build/native/include/WebView2.h")
set(_wv2_pkg "${CMAKE_BINARY_DIR}/webview2-${WEBVIEW2_VERSION}.nupkg")
file(DOWNLOAD
"https://api.nuget.org/v3-flatcontainer/microsoft.web.webview2/${WEBVIEW2_VERSION}/microsoft.web.webview2.${WEBVIEW2_VERSION}.nupkg"
"${_wv2_pkg}"
EXPECTED_HASH SHA256=${WEBVIEW2_SHA256}
TLS_VERIFY ON)
file(ARCHIVE_EXTRACT INPUT "${_wv2_pkg}" DESTINATION "${WEBVIEW2_DIR}")
endif()
if(CMAKE_GENERATOR_PLATFORM STREQUAL "ARM64" OR
CMAKE_SYSTEM_PROCESSOR MATCHES "ARM64")
set(WEBVIEW2_ARCH "arm64")
else()
set(WEBVIEW2_ARCH "x64")
endif()
add_library(${PLUGIN_NAME} SHARED
"include/cesiumjs/cesiumjs_plugin_c_api.h"
"cesiumjs_plugin.cpp"
)
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_include_directories(${PLUGIN_NAME} PRIVATE
"${WEBVIEW2_DIR}/build/native/include")
target_link_libraries(${PLUGIN_NAME} PRIVATE
flutter flutter_wrapper_plugin
"${WEBVIEW2_DIR}/build/native/${WEBVIEW2_ARCH}/WebView2LoaderStatic.lib"
shlwapi version)
# The loader is linked statically: nothing to bundle. End users need the
# WebView2 Runtime (preinstalled on Windows 10 21H2+ and Windows 11).
set(cesiumjs_bundled_libraries
""
PARENT_SCOPE
)
+599
View File
@@ -0,0 +1,599 @@
// Windows side of the `cesiumjs/webview` channel.
//
// Same protocol and approach as linux/cesiumjs_plugin.cc: each viewer is a
// WebView2 hosted in a native child window placed *above* the Flutter view,
// at the rectangle reported by Dart (setRect, logical pixels * scale).
#include "include/cesiumjs/cesiumjs_plugin_c_api.h"
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <wrl.h>
#include <WebView2.h>
#include <flutter/encodable_value.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <cmath>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace {
using flutter::EncodableMap;
using flutter::EncodableValue;
using Microsoft::WRL::Callback;
using Microsoft::WRL::ComPtr;
using MethodResultPtr = std::unique_ptr<flutter::MethodResult<EncodableValue>>;
constexpr char kChannelName[] = "cesiumjs/webview";
constexpr wchar_t kHostClass[] = L"CesiumjsWebViewHost";
constexpr char kDefaultBaseUrl[] = "https://cesium.localhost/";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
std::wstring Utf8ToWide(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
std::wstring out(n, L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), out.data(), n);
return out;
}
std::string WideToUtf8(const wchar_t* s) {
if (s == nullptr || *s == 0) return {};
int n = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, nullptr, nullptr);
std::string out(n > 0 ? n - 1 : 0, '\0');
WideCharToMultiByte(CP_UTF8, 0, s, -1, out.data(), n, nullptr, nullptr);
return out;
}
// Frees a WebView2 out-string on scope exit.
struct CoStr {
LPWSTR p = nullptr;
~CoStr() { CoTaskMemFree(p); }
};
const EncodableValue* Lookup(const EncodableValue* args, const char* key) {
const auto* map = args ? std::get_if<EncodableMap>(args) : nullptr;
if (map == nullptr) return nullptr;
auto it = map->find(EncodableValue(key));
return it == map->end() ? nullptr : &it->second;
}
std::optional<int64_t> GetInt(const EncodableValue* args, const char* key) {
const EncodableValue* v = Lookup(args, key);
if (v == nullptr) return std::nullopt;
if (auto i = std::get_if<int32_t>(v)) return *i;
if (auto i = std::get_if<int64_t>(v)) return *i;
if (auto d = std::get_if<double>(v)) return (int64_t)*d;
return std::nullopt;
}
double GetDouble(const EncodableValue* args, const char* key, double fb = 0) {
const EncodableValue* v = Lookup(args, key);
if (v == nullptr) return fb;
if (auto d = std::get_if<double>(v)) return *d;
if (auto i = std::get_if<int32_t>(v)) return *i;
if (auto i = std::get_if<int64_t>(v)) return (double)*i;
return fb;
}
const std::string* GetString(const EncodableValue* args, const char* key) {
const EncodableValue* v = Lookup(args, key);
return v ? std::get_if<std::string>(v) : nullptr;
}
void AppendUtf8(std::string& out, uint32_t cp) {
if (cp < 0x80) {
out += (char)cp;
} else if (cp < 0x800) {
out += (char)(0xC0 | (cp >> 6));
out += (char)(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += (char)(0xE0 | (cp >> 12));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
} else {
out += (char)(0xF0 | (cp >> 18));
out += (char)(0x80 | ((cp >> 12) & 0x3F));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
}
}
// ExecuteScript returns JSON. Mimic the Linux result: null for
// undefined/null, the plain text for strings, the JSON text otherwise.
std::optional<std::string> JsonResultToString(const std::string& json) {
if (json.empty() || json == "null") return std::nullopt;
if (json.size() < 2 || json.front() != '"' || json.back() != '"') {
return json;
}
std::string out;
for (size_t i = 1; i + 1 < json.size(); ++i) {
char c = json[i];
if (c != '\\' || i + 2 >= json.size()) {
out += c;
continue;
}
char e = json[++i];
switch (e) {
case 'n': out += '\n'; break;
case 't': out += '\t'; break;
case 'r': out += '\r'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'u': {
if (i + 4 >= json.size()) return json;
uint32_t cp = std::stoul(json.substr(i + 1, 4), nullptr, 16);
i += 4;
if (cp >= 0xD800 && cp < 0xDC00 && i + 6 < json.size() &&
json[i + 1] == '\\' && json[i + 2] == 'u') {
uint32_t lo = std::stoul(json.substr(i + 3, 4), nullptr, 16);
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
i += 6;
}
AppendUtf8(out, cp);
break;
}
default: out += e; // \" \\ \/
}
}
return out;
}
std::wstring UserDataFolder() {
std::wstring base;
PWSTR local = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr,
&local))) {
base = local;
}
CoTaskMemFree(local);
wchar_t exe[MAX_PATH];
GetModuleFileNameW(nullptr, exe, MAX_PATH);
std::wstring name = PathFindFileNameW(exe);
if (auto dot = name.rfind(L'.'); dot != std::wstring::npos) {
name.resize(dot);
}
return base + L"\\" + name + L"\\CesiumWebView2";
}
// ---------------------------------------------------------------------------
// Plugin
// ---------------------------------------------------------------------------
struct View {
HWND host = nullptr;
ComPtr<ICoreWebView2Controller> controller;
ComPtr<ICoreWebView2> webview;
std::string html;
std::wstring base_url;
RECT bounds{}; // physical pixels, in host parent's client coordinates
bool visible = false;
// Run once WebView2 is ready; called with false if the view is disposed
// first (so queued Dart futures still complete).
std::vector<std::function<void(bool)>> pending;
};
class CesiumjsPlugin : public flutter::Plugin {
public:
explicit CesiumjsPlugin(flutter::PluginRegistrarWindows* registrar)
: registrar_(registrar) {
channel_ = std::make_unique<flutter::MethodChannel<EncodableValue>>(
registrar->messenger(), kChannelName,
&flutter::StandardMethodCodec::GetInstance());
channel_->SetMethodCallHandler([this](const auto& call, auto result) {
HandleMethodCall(call, std::move(result));
});
// WebView2 wants to know when the top-level window moves (popups,
// IME and drop-down positions).
proc_id_ = registrar->RegisterTopLevelWindowProcDelegate(
[this](HWND, UINT msg, WPARAM, LPARAM) -> std::optional<LRESULT> {
if (msg == WM_MOVE || msg == WM_MOVING) {
for (auto& [id, v] : views_) {
if (v->controller) v->controller->NotifyParentWindowPositionChanged();
}
}
return std::nullopt;
});
}
~CesiumjsPlugin() override {
registrar_->UnregisterTopLevelWindowProcDelegate(proc_id_);
DisposeAll();
}
private:
HWND FlutterHwnd() const {
auto* view = registrar_->GetView();
return view ? view->GetNativeWindow() : nullptr;
}
// The runner makes the Flutter view a child of its top-level window; web
// views are siblings stacked above it.
HWND HostParent() const {
HWND fv = FlutterHwnd();
HWND parent = fv ? GetParent(fv) : nullptr;
return parent ? parent : fv;
}
static void EnsureHostClass() {
static bool registered = false;
if (registered) return;
WNDCLASSEXW wc{};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = DefWindowProcW;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = kHostClass;
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
RegisterClassExW(&wc);
registered = true;
}
void SendEvent(const char* method, int64_t id, const std::string& message) {
channel_->InvokeMethod(
method, std::make_unique<EncodableValue>(EncodableMap{
{EncodableValue("id"), EncodableValue(id)},
{EncodableValue("message"), EncodableValue(message)},
}));
}
View* Find(int64_t id) {
auto it = views_.find(id);
return it == views_.end() ? nullptr : it->second.get();
}
void ApplyBounds(View* v) {
bool show = v->visible && v->bounds.right > v->bounds.left &&
v->bounds.bottom > v->bounds.top;
if (show) {
SetWindowPos(v->host, HWND_TOP, v->bounds.left, v->bounds.top,
v->bounds.right - v->bounds.left,
v->bounds.bottom - v->bounds.top,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
} else {
ShowWindow(v->host, SW_HIDE);
}
if (v->controller) {
RECT inner{0, 0, v->bounds.right - v->bounds.left,
v->bounds.bottom - v->bounds.top};
v->controller->put_Bounds(inner);
v->controller->put_IsVisible(show ? TRUE : FALSE);
}
}
// --- create ---------------------------------------------------------------
void Create(int64_t id, const std::string& html, const std::string& base,
MethodResultPtr result) {
HWND parent = HostParent();
if (parent == nullptr) {
result->Error("no_window", "Flutter view has no native window");
return;
}
// Keep the Flutter view from painting over its sibling web views.
HWND fv = FlutterHwnd();
if (fv && fv != parent) {
SetWindowLongPtrW(fv, GWL_STYLE,
GetWindowLongPtrW(fv, GWL_STYLE) | WS_CLIPSIBLINGS);
}
EnsureHostClass();
auto view = std::make_unique<View>();
view->html = html;
view->base_url = Utf8ToWide(base);
view->host = CreateWindowExW(
0, kHostClass, L"", WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0,
0, 0, parent, nullptr, GetModuleHandleW(nullptr), nullptr);
views_[id] = std::move(view);
HRESULT create_hr = CreateCoreWebView2EnvironmentWithOptions(
nullptr, UserDataFolder().c_str(), nullptr,
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[this, id](HRESULT env_hr, ICoreWebView2Environment* env) -> HRESULT {
View* view = Find(id);
if (view == nullptr) return S_OK; // disposed meanwhile
if (FAILED(env_hr) || env == nullptr) {
SendEvent("onError", id,
"WebView2 runtime not available (install the "
"Microsoft Edge WebView2 Runtime)");
return S_OK;
}
ComPtr<ICoreWebView2Environment> environment(env);
return env->CreateCoreWebView2Controller(
view->host,
Callback<
ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
[this, id, environment](
HRESULT,
ICoreWebView2Controller* controller) -> HRESULT {
View* v = Find(id);
if (controller == nullptr) {
if (v) SendEvent("onError", id,
"WebView2 controller creation failed");
return S_OK;
}
if (v == nullptr) {
controller->Close();
return S_OK;
}
OnControllerReady(id, v, environment.Get(), controller);
return S_OK;
})
.Get());
})
.Get());
if (FAILED(create_hr)) {
SendEvent("onError", id,
"WebView2 runtime not available (install the Microsoft Edge "
"WebView2 Runtime)");
}
result->Success();
}
void OnControllerReady(int64_t id, View* v, ICoreWebView2Environment* env,
ICoreWebView2Controller* controller) {
v->controller = controller;
controller->get_CoreWebView2(&v->webview);
ICoreWebView2* wv = v->webview.Get();
ComPtr<ICoreWebView2Controller2> controller2;
if (SUCCEEDED(controller->QueryInterface(IID_PPV_ARGS(&controller2)))) {
controller2->put_DefaultBackgroundColor({255, 0, 0, 0}); // opaque black
}
ComPtr<ICoreWebView2Settings> settings;
if (SUCCEEDED(wv->get_Settings(&settings))) {
settings->put_IsScriptEnabled(TRUE);
settings->put_IsWebMessageEnabled(TRUE);
settings->put_AreDevToolsEnabled(TRUE);
settings->put_IsStatusBarEnabled(FALSE);
settings->put_AreDefaultContextMenusEnabled(FALSE);
}
EventRegistrationToken token;
// JS -> Dart: window.chrome.webview.postMessage("...")
wv->add_WebMessageReceived(
Callback<ICoreWebView2WebMessageReceivedEventHandler>(
[this, id](ICoreWebView2*,
ICoreWebView2WebMessageReceivedEventArgs* args) {
CoStr msg;
if (SUCCEEDED(args->TryGetWebMessageAsString(&msg.p))) {
SendEvent("onMessage", id, WideToUtf8(msg.p));
}
return S_OK;
})
.Get(),
&token);
// Serve the page from the virtual origin, like load_html on Linux.
std::wstring filter = v->base_url + L"*";
wv->AddWebResourceRequestedFilter(filter.c_str(),
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT);
ComPtr<ICoreWebView2Environment> environment(env);
wv->add_WebResourceRequested(
Callback<ICoreWebView2WebResourceRequestedEventHandler>(
[this, id, environment](
ICoreWebView2*,
ICoreWebView2WebResourceRequestedEventArgs* args) {
View* target = Find(id);
if (target == nullptr) return S_OK;
ComPtr<IStream> stream;
stream.Attach(SHCreateMemStream(
reinterpret_cast<const BYTE*>(target->html.data()),
(UINT)target->html.size()));
ComPtr<ICoreWebView2WebResourceResponse> response;
environment->CreateWebResourceResponse(
stream.Get(), 200, L"OK",
L"Content-Type: text/html; charset=utf-8", &response);
args->put_Response(response.Get());
return S_OK;
})
.Get(),
&token);
// Links opening a new window (Cesium credits...) go to the browser.
wv->add_NewWindowRequested(
Callback<ICoreWebView2NewWindowRequestedEventHandler>(
[](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) {
CoStr uri;
if (SUCCEEDED(args->get_Uri(&uri.p)) && uri.p) {
ShellExecuteW(nullptr, L"open", uri.p, nullptr, nullptr,
SW_SHOWNORMAL);
}
args->put_Handled(TRUE);
return S_OK;
})
.Get(),
&token);
wv->add_NavigationCompleted(
Callback<ICoreWebView2NavigationCompletedEventHandler>(
[this, id](ICoreWebView2*,
ICoreWebView2NavigationCompletedEventArgs* args) {
BOOL ok = TRUE;
args->get_IsSuccess(&ok);
if (!ok) {
COREWEBVIEW2_WEB_ERROR_STATUS status;
args->get_WebErrorStatus(&status);
SendEvent("onError", id,
"Load failed (WebView2 error " +
std::to_string((int)status) + ")");
}
return S_OK;
})
.Get(),
&token);
wv->add_ProcessFailed(
Callback<ICoreWebView2ProcessFailedEventHandler>(
[this, id](ICoreWebView2*,
ICoreWebView2ProcessFailedEventArgs* args) {
COREWEBVIEW2_PROCESS_FAILED_KIND kind;
args->get_ProcessFailedKind(&kind);
SendEvent("onError", id,
kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED
? "Web browser process exited"
: "Web process crashed");
return S_OK;
})
.Get(),
&token);
ApplyBounds(v);
wv->Navigate(v->base_url.c_str());
auto pending = std::move(v->pending);
for (auto& fn : pending) fn(true);
}
// --- other methods --------------------------------------------------------
void SetRect(View* v, const EncodableValue* args) {
double scale = GetDouble(args, "scale", 1.0);
if (scale <= 0) scale = 1.0;
POINT origin{(LONG)std::lround(GetDouble(args, "x") * scale),
(LONG)std::lround(GetDouble(args, "y") * scale)};
// Dart reports coordinates relative to the Flutter view.
HWND fv = FlutterHwnd();
HWND parent = GetParent(v->host);
if (fv && parent && fv != parent) MapWindowPoints(fv, parent, &origin, 1);
v->bounds = {origin.x, origin.y,
origin.x + (LONG)std::lround(GetDouble(args, "width") * scale),
origin.y + (LONG)std::lround(GetDouble(args, "height") * scale)};
const EncodableValue* vis = Lookup(args, "visible");
const bool* b = vis ? std::get_if<bool>(vis) : nullptr;
v->visible = b == nullptr || *b;
ApplyBounds(v);
}
void RunJavaScript(View* v, const std::string& script,
MethodResultPtr result) {
std::shared_ptr<flutter::MethodResult<EncodableValue>> shared(
result.release());
std::wstring wscript = Utf8ToWide(script);
auto run = [v, wscript, shared](bool ready) {
if (!ready) {
shared->Error("disposed", "the view was disposed");
return;
}
HRESULT hr = v->webview->ExecuteScript(
wscript.c_str(),
Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[shared](HRESULT exec_hr, LPCWSTR json) {
if (FAILED(exec_hr)) {
shared->Error("js_error", "ExecuteScript failed");
return S_OK;
}
auto value = JsonResultToString(WideToUtf8(json));
if (value) {
shared->Success(EncodableValue(*value));
} else {
shared->Success();
}
return S_OK;
})
.Get());
if (FAILED(hr)) shared->Error("js_error", "ExecuteScript failed");
};
if (v->webview) {
run(true);
} else {
v->pending.push_back(run);
}
}
void Dispose(int64_t id) {
auto it = views_.find(id);
if (it == views_.end()) return;
std::unique_ptr<View> v = std::move(it->second);
views_.erase(it);
for (auto& fn : v->pending) fn(false);
if (v->controller) v->controller->Close();
if (v->host) DestroyWindow(v->host);
}
void DisposeAll() {
while (!views_.empty()) Dispose(views_.begin()->first);
}
void HandleMethodCall(const flutter::MethodCall<EncodableValue>& call,
MethodResultPtr result) {
const std::string& method = call.method_name();
const EncodableValue* args = call.arguments();
auto id = GetInt(args, "id");
if (method == "disposeAll") {
// Called once per Dart isolate start (hot restart).
DisposeAll();
result->Success();
return;
}
if (method == "dispose") {
if (id) Dispose(*id);
result->Success();
return;
}
if (method == "create") {
const std::string* html = GetString(args, "html");
if (!id || html == nullptr) {
result->Error("bad_args", "create requires id and html");
} else if (Find(*id)) {
result->Error("exists", "a view with this id already exists");
} else {
const std::string* base = GetString(args, "baseUrl");
Create(*id, *html, base ? *base : kDefaultBaseUrl, std::move(result));
}
return;
}
View* v = id ? Find(*id) : nullptr;
if (method != "setRect" && method != "runJavaScript" &&
method != "openInspector") {
result->NotImplemented();
return;
}
if (v == nullptr) {
result->Error("not_found", "unknown view id");
return;
}
if (method == "setRect") {
SetRect(v, args);
result->Success();
} else if (method == "runJavaScript") {
const std::string* script = GetString(args, "script");
if (script == nullptr) {
result->Error("bad_args", "script missing");
} else {
RunJavaScript(v, *script, std::move(result));
}
} else { // openInspector
if (v->webview) v->webview->OpenDevToolsWindow();
result->Success();
}
}
flutter::PluginRegistrarWindows* registrar_;
std::unique_ptr<flutter::MethodChannel<EncodableValue>> channel_;
std::map<int64_t, std::unique_ptr<View>> views_;
int proc_id_ = 0;
};
} // namespace
void CesiumjsPluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar_ref) {
auto* registrar =
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar_ref);
registrar->AddPlugin(std::make_unique<CesiumjsPlugin>(registrar));
}
@@ -0,0 +1,23 @@
#ifndef FLUTTER_PLUGIN_CESIUMJS_PLUGIN_C_API_H_
#define FLUTTER_PLUGIN_CESIUMJS_PLUGIN_C_API_H_
#include <flutter_plugin_registrar.h>
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)
#else
#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
FLUTTER_PLUGIN_EXPORT void CesiumjsPluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_PLUGIN_CESIUMJS_PLUGIN_C_API_H_