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
+2601 -111

No files matched your search

+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
}
}
}
}