diff --git a/.vscode/launch.json b/.vscode/launch.json index 210f163..85e985a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -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" + ] } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index ed1278f..4d02579 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index d89b8bc..b405dd0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/README.md b/README.md index ec46501..bbf67a7 100644 --- a/README.md +++ b/README.md @@ -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 { | `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 { | `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 linux --dart-define-from-file=cesium_ion.json +flutter run -d windows --dart-define-from-file=cesium_ion.json +flutter run -d --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 ``` diff --git a/analysis_options.yaml b/analysis_options.yaml index 6087fad..9689dc9 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,6 +13,8 @@ analyzer: exclude: - build/** - linux/** + - android/** + - windows/** linter: # The lint rules applied to this project can be customized in the diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..d875fd7 --- /dev/null +++ b/android/build.gradle.kts @@ -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 + } +} diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..685e478 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "cesiumjs" diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9db353f --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt b/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt new file mode 100644 index 0000000..af565c9 --- /dev/null +++ b/android/src/main/kotlin/fr/irt_saintexupery/cesiumjs/CesiumjsPlugin.kt @@ -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() + 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("id")?.toInt() + when (call.method) { + "create" -> { + val html = call.argument("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("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("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 + } + } + } +} diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 6087fad..9689dc9 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -13,6 +13,8 @@ analyzer: exclude: - build/** - linux/** + - android/** + - windows/** linter: # The lint rules applied to this project can be customized in the diff --git a/example/android/.gitignore b/example/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/example/android/.gitignore @@ -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 diff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts new file mode 100644 index 0000000..fe38338 --- /dev/null +++ b/example/android/app/build.gradle.kts @@ -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 = "../.." +} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..37f7db9 --- /dev/null +++ b/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/example/android/app/src/main/kotlin/fr/irt_saintexupery/cesiumjs_example/MainActivity.kt b/example/android/app/src/main/kotlin/fr/irt_saintexupery/cesiumjs_example/MainActivity.kt new file mode 100644 index 0000000..eea7357 --- /dev/null +++ b/example/android/app/src/main/kotlin/fr/irt_saintexupery/cesiumjs_example/MainActivity.kt @@ -0,0 +1,5 @@ +package fr.irt_saintexupery.cesiumjs_example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/example/android/build.gradle.kts @@ -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("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/example/android/gradle.properties b/example/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/example/android/gradle.properties @@ -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 diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a20f2c4 --- /dev/null +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/example/android/settings.gradle.kts b/example/android/settings.gradle.kts new file mode 100644 index 0000000..b28021a --- /dev/null +++ b/example/android/settings.gradle.kts @@ -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") diff --git a/example/lib/main.dart b/example/lib/main.dart index 802e8e5..d93cc54 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -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 { 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( + groupValue: _imagery, + onChanged: (v) { + if (ready && v != null) _controller.setImagery(v); + }, + child: Column( + children: [ + for (final i in CesiumImagery.values) + RadioListTile( + dense: true, + value: i, + enabled: ready && (i != CesiumImagery.ionAerial || hasToken), + title: Text(i.label), + ), + ], + ), + ), + SwitchListTile( + dense: true, + title: const Text('MNT (Cesium World Terrain)'), + value: _terrain, + onChanged: ready && hasToken ? _controller.setTerrain : null, + ), + ], + ); + 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,66 +213,23 @@ class _DemoPageState extends State { ), ], ), - body: Row( - children: [ - SizedBox( - width: 230, - child: ListView( + body: narrow + ? viewer + : Row( children: [ - for (final p in _places) - ListTile( - dense: true, - leading: const Icon(Icons.place_outlined), - title: Text(p.name), - enabled: ready, - onTap: () => _goTo(p), - ), - const Divider(), - const ListTile(dense: true, title: Text('Orthophoto / fond')), - RadioGroup( - groupValue: _imagery, - onChanged: (v) { - if (ready && v != null) _controller.setImagery(v); - }, - child: Column( - children: [ - for (final i in CesiumImagery.values) - RadioListTile( - dense: true, - value: i, - enabled: - ready && - (i != CesiumImagery.ionAerial || hasToken), - title: Text(i.label), - ), - ], - ), - ), - SwitchListTile( - dense: true, - title: const Text('MNT (Cesium World Terrain)'), - value: _terrain, - onChanged: ready && hasToken ? _controller.setTerrain : null, - ), + SizedBox(width: 230, child: panel), + Expanded(child: viewer), ], ), - ), - Expanded( - child: CesiumViewer( - ionToken: hasToken ? ionToken : null, - controller: _controller, - onMessage: _onMessage, - onError: (e) => setState(() => _status = 'Error: $e'), - ), - ), - ], - ), bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), color: Theme.of(context).colorScheme.surfaceContainer, - child: Text( - '$_status $_camera', - style: Theme.of(context).textTheme.bodySmall, + child: SafeArea( + top: false, + child: Text( + '$_status $_camera', + style: Theme.of(context).textTheme.bodySmall, + ), ), ), ); diff --git a/example/pubspec.lock b/example/pubspec.lock index d5627ff..470e024 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -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: diff --git a/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/example/windows/.gitignore @@ -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/ diff --git a/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..07ef12c --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -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 "$<$:_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 "$") +# 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) diff --git a/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/example/windows/flutter/CMakeLists.txt @@ -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} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..282600e --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + CesiumjsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CesiumjsPluginCApi")); +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..128588a --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + cesiumjs +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -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) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..abf5180 --- /dev/null +++ b/example/windows/runner/Runner.rc @@ -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 diff --git a/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#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( + 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 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); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#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_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..dbedc73 --- /dev/null +++ b/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#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 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; +} diff --git a/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/example/windows/runner/resource.h @@ -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 diff --git a/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/windows/runner/resources/app_icon.ico differ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +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 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::vector 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(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(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; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// 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, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#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(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( + 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(origin.x), + static_cast(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(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(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(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( + 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)); + } +} diff --git a/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// 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_ diff --git a/lib/src/cesium_html.dart b/lib/src/cesium_html.dart index 84b5a14..e39cca2 100644 --- a/lib/src/cesium_html.dart +++ b/lib/src/cesium_html.dart @@ -28,11 +28,19 @@ String buildCesiumHtml({String? ionToken}) {