diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..671a084 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79f872f..f0d3bb0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -38,8 +38,29 @@ jobs: cache: 'gradle' - name: Build core and compose locally + env: + HEAD_REF: ${{ github.head_ref }} run: | - git clone --depth 1 https://github.com/MapConductor/android-sdk-core.git _core + # コア側に PR と同名のブランチがあるなら、そちらを組む。 + # + # ここを default ブランチ固定にしていると、**コアの未マージな変更に追随する + # PR は永久に赤いまま**になる。実際 CameraBearing をコアへ足したとき、 + # プロバイダ側の PR が 10 本まとめて Unresolved reference で落ちた。 + # コアが先にマージされるまで待つ、という運用は取り込み順の事故を呼ぶので、 + # 同名ブランチがあれば拾う形にしてある(無ければ従来どおり default)。 + clone_matching() { + repo="$1"; dir="$2" + url="https://github.com/MapConductor/$repo.git" + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads "$url" "$HEAD_REF" >/dev/null 2>&1; then + echo "$repo: matching branch $HEAD_REF" + git clone --depth 1 --branch "$HEAD_REF" "$url" "$dir" + else + echo "$repo: default branch" + git clone --depth 1 "$url" "$dir" + fi + } + + clone_matching android-sdk-core _core cd _core ./gradlew --no-daemon publishToMavenLocal cd .. @@ -53,7 +74,7 @@ jobs: } EOF - git clone --depth 1 https://github.com/MapConductor/android-sdk-compose.git _compose + clone_matching android-sdk-compose _compose cd _compose ./gradlew --no-daemon publishToMavenLocal cd .. diff --git a/api/android-for-googlemaps.api b/api/android-for-googlemaps.api index 40a1ff6..338c043 100644 --- a/api/android-for-googlemaps.api +++ b/api/android-for-googlemaps.api @@ -99,6 +99,8 @@ public final class com.mapconductor.googlemaps.GoogleMapViewController extends c public final class com.mapconductor.googlemaps.GoogleMapViewController$Companion { } public final class com.mapconductor.googlemaps.GoogleMapViewControllerCameraKt { + public static final double viewportHeightDp(com.mapconductor.googlemaps.GoogleMapViewController); + public static final com.mapconductor.core.map.MapCameraPosition toNativeCamera(com.mapconductor.googlemaps.GoogleMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleMoveCamera(com.mapconductor.googlemaps.GoogleMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleAnimateCamera(com.mapconductor.googlemaps.GoogleMapViewController, com.mapconductor.core.map.MapCameraPosition, long); public static final void handleFitBounds(com.mapconductor.googlemaps.GoogleMapViewController, com.mapconductor.core.features.GeoRectBounds, int); @@ -136,11 +138,14 @@ public final class com.mapconductor.googlemaps.GoogleMapViewHolder implements co public androidx.compose.ui.geometry.Offset toScreenOffset-x-9fifI(com.mapconductor.core.features.GeoPointInterface); public java.lang.Object fromScreenOffset-3MmeM6k(long, kotlin.coroutines.Continuation); public com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); + public com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.projection.ProjectedPoint); + public com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(); public java.lang.Object getMapView(); public java.lang.Object getMap(); } public final class com.mapconductor.googlemaps.GoogleMapViewKt { - public static final void GoogleMapView(com.mapconductor.googlemaps.GoogleMapViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void GoogleMapView(com.mapconductor.googlemaps.GoogleMapViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); public static final com.mapconductor.googlemaps.GoogleMapViewController createGoogleMapViewController(com.mapconductor.googlemaps.GoogleMapViewHolder, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.MutableMapServiceRegistry); } public final class com.mapconductor.googlemaps.GoogleMapViewSaver extends com.mapconductor.compose.map.BaseMapViewSaver { @@ -178,6 +183,7 @@ public final class com.mapconductor.googlemaps.LatLngInterpolationCache { public final void put(java.lang.String, java.util.List); } public final class com.mapconductor.googlemaps.MapCameraPositionKt { + public static final double GOOGLE_VERTICAL_FOV; public static final com.google.android.gms.maps.model.CameraPosition toCameraPosition(com.mapconductor.core.map.MapCameraPosition); public static final com.mapconductor.core.map.MapCameraPosition from(com.mapconductor.core.map.MapCameraPosition$Companion, com.mapconductor.core.map.MapCameraPositionInterface); public static final com.mapconductor.core.map.MapCameraPosition toMapCameraPosition(com.google.android.gms.maps.model.CameraPosition, com.mapconductor.core.map.MapPaddingsInterface); @@ -252,6 +258,7 @@ public final class com.mapconductor.googlemaps.marker.GoogleMapMarkerControllerI public final class com.mapconductor.googlemaps.marker.GoogleMapMarkerRenderer extends com.mapconductor.core.marker.AbstractMarkerOverlayRenderer { public com.mapconductor.googlemaps.marker.GoogleMapMarkerRenderer(com.mapconductor.googlemaps.GoogleMapViewHolder, kotlinx.coroutines.CoroutineScope); public com.mapconductor.googlemaps.marker.GoogleMapMarkerRenderer(com.mapconductor.googlemaps.GoogleMapViewHolder, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + protected java.lang.Object applyDrawOrder(java.util.List>, kotlin.coroutines.Continuation); public boolean getSupportsAnimationOverlay(); public void setMarkerVisible(com.mapconductor.core.marker.MarkerEntityInterface, boolean); public void setMarkerPosition(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.features.GeoPoint); @@ -308,6 +315,8 @@ public final class com.mapconductor.googlemaps.polyline.GoogleMapPolylineOverlay public final class com.mapconductor.googlemaps.raster.GoogleMapRasterLayerController extends com.mapconductor.core.raster.RasterLayerController implements com.mapconductor.googlemaps.raster.GoogleMapRasterLayerControllerInterface { public com.mapconductor.googlemaps.raster.GoogleMapRasterLayerController(com.mapconductor.core.raster.RasterLayerManagerInterface, com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer); public com.mapconductor.googlemaps.raster.GoogleMapRasterLayerController(com.mapconductor.core.raster.RasterLayerManagerInterface, com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer, int, kotlin.jvm.internal.DefaultConstructorMarker); + public java.lang.Object onCameraChanged(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); + public void destroy(); } public interface com.mapconductor.googlemaps.raster.GoogleMapRasterLayerControllerInterface extends com.mapconductor.core.controller.OverlayControllerInterface> { } @@ -327,6 +336,10 @@ public final class com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverla } final class com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer$Companion { } +final class com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer$DetachableTileProvider implements com.google.android.gms.maps.model.TileProvider { + public com.google.android.gms.maps.model.Tile getTile(int, int, int); + public final void detach(); +} final class com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer$TileSpec { public final java.lang.String getTemplate(); public final int getTileSize(); diff --git a/gradle.properties b/gradle.properties index 26d9949..8b1a332 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ android.useAndroidX=true kotlin.code.style=official android.nonTransitiveRClass=true -compileSdk=35 +compileSdk=37 minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5e2b5b2..5abc420 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,15 +1,18 @@ [versions] -composeLibs = "1.7.8" -coroutines = "1.9.0" -agp = "9.2.1" -kotlin = "2.0.21" - -composeBom = "2025.02.00" -coreKtx = "1.16.0" -lifecycleRuntimeKtx = "2.8.7" -okhttp = "5.3.2" -playServicesMaps = "20.0.0" -activityCompose = "1.9.3" +composeLibs = "1.12.1" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" +coroutines = "1.11.0" +agp = "9.4.1" +kotlin = "2.4.20" + +composeBom = "2026.09.00" +coreKtx = "1.19.1" +lifecycleRuntimeKtx = "2.11.0" +okhttp = "5.5.1" +playServicesMaps = "20.1.0" +activityCompose = "1.13.0" ktLint = "14.2.0" junit = "4.13.2" @@ -35,7 +38,10 @@ play-services-maps = { module = "com.google.android.gms:play-services-maps", ver # Sample app androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } -androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeLibs" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } +# sample-app が Icons.AutoMirrored を使う。material3 は material-icons を推移的に持ってこないので +# 明示的に足す。版は compose BOM 任せ(集約ビルドの catalog と同じ形)。 +androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" } androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "composeLibs" } # Test diff --git a/sample-app/build.gradle.kts b/sample-app/build.gradle.kts index bd12482..55a8249 100644 --- a/sample-app/build.gradle.kts +++ b/sample-app/build.gradle.kts @@ -57,6 +57,7 @@ dependencies { implementation(libs.androidx.ui) implementation(libs.androidx.ui.tooling.preview) implementation(libs.androidx.material3) + implementation(libs.androidx.material.icons.core) debugImplementation(platform(libs.androidx.compose.bom)) debugImplementation(libs.androidx.ui.tooling) } diff --git a/src/androidTest/java/com/mapconductor/googlemaps/GoogleMapViewSaverTest.kt b/src/androidTest/java/com/mapconductor/googlemaps/GoogleMapViewSaverTest.kt new file mode 100644 index 0000000..f183fe7 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/googlemaps/GoogleMapViewSaverTest.kt @@ -0,0 +1,86 @@ +package com.mapconductor.googlemaps + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.android.gms.maps.GoogleMap +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapUISettings +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が [GoogleMapViewSaver] を通って作り直されても、デザイン(id・ + * attributionRules ほか)と uiSettings・カメラが落ちないこと。Bundle は実機の Parcel を一度通す。 + */ +@RunWith(AndroidJUnit4::class) +class GoogleMapViewSaverTest { + private val rules = + listOf(AttributionRule("© test"), AttributionRule("© ranged", minZoom = 3, maxZoom = 15)) + + private val camera = + MapCameraPosition( + position = GeoPoint(21.38, -157.93), + zoom = 12.0, + bearing = 20.0, + tilt = 10.0, + ) + + @Test + fun keepsCustomDesignWithAttributionRules() { + val design = GoogleMapDesign.Custom(GoogleMap.MAP_TYPE_SATELLITE, rules) + val state = GoogleMapViewState(id = "google-1", mapDesignType = design, cameraPosition = camera) + state.uiSettings = MapUISettings(rotateGesture = false, tiltGesture = false) + + val restored = roundTrip(GoogleMapViewSaver().createSaver(), state) + + // 以前は id だけを保存して Create(id) で戻しており、Satellite(規則なし)になっていた。 + val actual = restored.mapDesignType + assertTrue(actual is GoogleMapDesign.Custom) + assertEquals(GoogleMap.MAP_TYPE_SATELLITE, actual.id) + assertEquals(rules, actual.attributionRules) + assertCommon(restored, "google-1") + } + + @Test + fun keepsPresetDesignAsTheSameObject() { + val state = GoogleMapViewState(id = "google-2", mapDesignType = GoogleMapDesign.Hybrid) + assertSame(GoogleMapDesign.Hybrid, roundTrip(GoogleMapViewSaver().createSaver(), state).mapDesignType) + } + + private fun assertCommon( + restored: com.mapconductor.core.map.MapViewStateInterface<*>, + id: String, + ) { + assertEquals(id, restored.id) + assertEquals(false, restored.uiSettings.rotateGesture) + assertEquals(false, restored.uiSettings.tiltGesture) + assertEquals(true, restored.uiSettings.scrollGesture) + assertEquals(12.0, restored.cameraPosition.zoom, 1e-9) + assertEquals(20.0, restored.cameraPosition.bearing, 1e-9) + assertEquals(21.38, restored.cameraPosition.position.latitude, 1e-9) + } + + private fun roundTrip( + saver: Saver, + value: T, + ): T { + val saved = with(saver) { SaverScope { true }.save(value) }!! + // 一度 Parcel に書いて読み戻す(プロセスが落ちたあとの復元と同じ経路)。 + val parcel = Parcel.obtain() + try { + parcel.writeBundle(saved) + parcel.setDataPosition(0) + return saver.restore(parcel.readBundle(javaClass.classLoader)!!)!! + } finally { + parcel.recycle() + } + } +} diff --git a/src/main/java/com/mapconductor/googlemaps/GoogleMapView.kt b/src/main/java/com/mapconductor/googlemaps/GoogleMapView.kt index 8320de9..22f98e1 100644 --- a/src/main/java/com/mapconductor/googlemaps/GoogleMapView.kt +++ b/src/main/java/com/mapconductor/googlemaps/GoogleMapView.kt @@ -20,6 +20,7 @@ import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapCapability import com.mapconductor.core.map.MapCapabilityStatus +import com.mapconductor.core.map.MapViewStyle import com.mapconductor.core.map.MutableMapServiceRegistry import com.mapconductor.core.marker.MarkerEventControllerInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface @@ -28,6 +29,8 @@ import com.mapconductor.core.marker.MarkerRenderingSupport import com.mapconductor.core.marker.MarkerRenderingSupportKey import com.mapconductor.core.marker.MarkerTilingOptions import com.mapconductor.core.marker.StrategyMarkerController +import com.mapconductor.core.raster.RasterTilePreference +import com.mapconductor.core.raster.RasterTilePreferenceKey import com.mapconductor.googlemaps.circle.GoogleMapCircleController import com.mapconductor.googlemaps.circle.GoogleMapCircleOverlayRenderer import com.mapconductor.googlemaps.groundimage.GoogleMapGroundImageController @@ -40,7 +43,6 @@ import com.mapconductor.googlemaps.polyline.GoogleMapPolylineOverlayRenderer import com.mapconductor.googlemaps.raster.GoogleMapRasterLayerController import com.mapconductor.googlemaps.raster.GoogleMapRasterLayerOverlayRenderer import okhttp3.OkHttpClient -import android.view.ViewGroup import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @@ -58,6 +60,15 @@ fun GoogleMapView( onCameraMoveStart: OnCameraMoveHandler? = null, onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, + /** + * How the map looks, when the app states it rather than naming a design. + * + * A vector style *is* the basemap. `com.mapconductor:vectorstyle` builds + * one; what happens underneath depends on this backend and the app does + * not have to know. + */ + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable GoogleMapViewScope.() -> Unit)? = null, ) { val scope = remember { GoogleMapViewScope() } // Use specific scope @@ -130,7 +141,6 @@ fun GoogleMapView( // Specific Google Maps DisposableEffect logic val lifecycle = LocalLifecycleOwner.current.lifecycle // Get lifecycle here DisposableEffect(lifecycle) { - val stateId = state.id val observer = object : DefaultLifecycleObserver { override fun onResume(owner: LifecycleOwner) { @@ -140,22 +150,6 @@ fun GoogleMapView( override fun onPause(owner: LifecycleOwner) { holderRef.value?.mapView?.onPause() } - - override fun onDestroy(owner: LifecycleOwner) { - val activity = context.findActivity() - if (activity?.isChangingConfigurations == true) { - holderRef.value?.mapView?.let { - (it.parent as? ViewGroup)?.removeView(it) - it.onDestroy() - } - } else { - // Real teardown (not a configuration change): free the - // controller's overlay controllers (tile-server routes, - // marker managers) and cancel its coroutine scope. - GoogleMapViewControllerStore.get(stateId)?.destroy() - GoogleMapViewControllerStore.remove(stateId) - } - } } lifecycle.addObserver(observer) onDispose { @@ -163,12 +157,18 @@ fun GoogleMapView( } } }, + // The MapView keeps an SDK thread whose listeners reach the controller, + // so it has to be destroyed when the map leaves -- a provider switch as + // much as an Activity going away. + onDestroyMapView = { mapView -> mapView.onDestroy() }, sdkInitialize = { sdkInitialize?.invoke(context) ?: true }, // Pass content if it needs to be rendered within the overlay providers in MapViewBase, // or handle it here if it's specific to GoogleMapView structure before calling MapViewBase. // For now, assuming content relates to overlay definitions. + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, // This might need adjustment based on how overlays are handled ) } @@ -199,6 +199,14 @@ fun createGoogleMapViewController( ) serviceRegistry?.let { registry -> + // Google displays each overlay tile across 256 dp regardless of its + // encoded pixel dimensions. Rasterisers must size style paint for that slot. + registry.put( + RasterTilePreferenceKey, + object : RasterTilePreference { + override val preferredTileSize: Int = 256 + }, + ) // オーバーレイをタップに対して透過させられるか(実測 2026-08-09)。 // Polygon / Polyline / Circle / GroundOverlay は clickable(false) で透過し、 // OnMapClickListener が発火するのでコアのカスケードへ寄せてある。 diff --git a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewController.kt b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewController.kt index 1fd28b6..afe741b 100644 --- a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewController.kt +++ b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewController.kt @@ -1,5 +1,8 @@ package com.mapconductor.googlemaps +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.circle.CircleTiler +import com.mapconductor.core.circle.circleTileRasterLayerState import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.GoogleMap.OnCameraIdleListener import com.google.android.gms.maps.GoogleMap.OnCameraMoveCanceledListener @@ -18,6 +21,9 @@ import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.groundimage.OnGroundImageEventHandler import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.CameraPaddingEmulation +import com.mapconductor.core.map.MapPaddings +import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.map.MapUISettings import com.mapconductor.core.marker.DefaultMarkerEventController import com.mapconductor.core.marker.MarkerAnimationOverlayHost @@ -28,8 +34,14 @@ import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.marker.dispatchGeoMarkerClick import com.mapconductor.core.marker.dispatchNativeMarkerClick import com.mapconductor.core.polygon.OnPolygonEventHandler +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.polygonTileRasterLayerState import com.mapconductor.core.polyline.OnPolylineEventHandler +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTiler +import com.mapconductor.core.polyline.polylineTileRasterLayerState import com.mapconductor.googlemaps.circle.GoogleMapCircleController import com.mapconductor.googlemaps.groundimage.GoogleMapGroundImageController import com.mapconductor.googlemaps.marker.GoogleMapMarkerController @@ -66,6 +78,16 @@ class GoogleMapViewController internal constructor( internal val markerEventControllers = mutableListOf>() private val _mapLoadedState = MutableStateFlow(false) val mapLoadedState: StateFlow = _mapLoadedState + + /** + * 今カメラに付いているパディング(dp)。 + * + * `GoogleMap.setPadding` は使わない。付けた瞬間に画面がずれてアニメーションの始まりが + * 跳ぶうえ、ロゴやコントロールまで動くため。代わりにカメラ中心をずらして再現し + * ([CameraPaddingEmulation])、読むときに元へ戻すためにここで覚えておく。 + */ + internal var cameraPaddings: MapPaddingsInterface = MapPaddings.Zeros + internal var markerClickListener: OnMarkerEventHandler? = null internal var markerDragStartListener: OnMarkerEventHandler? = null internal var markerDragListener: OnMarkerEventHandler? = null @@ -79,6 +101,7 @@ class GoogleMapViewController internal constructor( registerOverlayController(polygonController) registerOverlayController(polylineController) registerOverlayController(circleController) + registerOverlayController(groundImageController) registerOverlayController(rasterLayerController) registerMarkerEventController(DefaultMarkerEventController(markerController)) @@ -95,6 +118,41 @@ class GoogleMapViewController internal constructor( markerTileLayers.forEach { entity -> rasterLayerController.removeById(entity.state.id) } } } + + // Many polygons are drawn as raster tiles, shown through the same RasterLayer + // controller as the marker tiles (upsert / removeById, never the app's layers). + polygonController.tiler = + PolygonTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polygonTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYGON_TILE_LAYER_ID) + } + } + } + + // Many polylines too: the same raster layer path, in the polyline band. + polylineController.tiler = + PolylineTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polylineTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYLINE_TILE_LAYER_ID) + } + } + } + circleController.tiler = + CircleTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(circleTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(CIRCLE_TILE_LAYER_ID) + } + } + } } override fun moveCamera(position: MapCameraPosition) = handleMoveCamera(position) @@ -178,6 +236,8 @@ class GoogleMapViewController internal constructor( polygonController.clear() circleController.clear() rasterLayerController.clear() + // 拡張モジュール(クラスタリングなど)が登録した Strategy のマーカーも消す。 + clearStrategyMarkerControllers() } override fun setMarkerAnimationOverlayHost(host: MarkerAnimationOverlayHost?) { diff --git a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewControllerCamera.kt b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewControllerCamera.kt index b98bc8c..c1a3287 100644 --- a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewControllerCamera.kt +++ b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewControllerCamera.kt @@ -3,6 +3,7 @@ package com.mapconductor.googlemaps import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap.CancelableCallback import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.VisibleRegion @@ -11,9 +12,26 @@ import kotlinx.coroutines.launch // カメラの適用と、Google Maps からのカメライベントの受け口。 // Google Maps だけは範囲制限もズーム制限もネイティブ API があるので、 // 他プロバイダのような停止時クランプは要らない。 + +/** 地図の高さ(dp)。パディングのエミュレーションで遠近を解くのに使う。 */ +internal fun GoogleMapViewController.viewportHeightDp(): Double { + val density = holder.mapView.resources.displayMetrics.density + return holder.mapView.height / density.toDouble() +} + +/** パディングを中心のずらしに置き換えたカメラ。paddings が null なら今のパディングを使い続ける。 */ +internal fun GoogleMapViewController.toNativeCamera(position: MapCameraPosition): MapCameraPosition { + position.paddings?.let { cameraPaddings = it } + return CameraPaddingEmulation.toNativeCamera( + position.copy(paddings = cameraPaddings), + GOOGLE_VERTICAL_FOV, + viewportHeightDp(), + ) +} + internal fun GoogleMapViewController.handleMoveCamera(position: MapCameraPosition) { mainCoroutine.launch { - val dstCameraPosition = position.toCameraPosition() + val dstCameraPosition = toNativeCamera(position).toCameraPosition() val cameraUpdate = CameraUpdateFactory.newCameraPosition(dstCameraPosition) holder.map.moveCamera(cameraUpdate) } @@ -23,8 +41,8 @@ internal fun GoogleMapViewController.handleAnimateCamera( position: MapCameraPosition, duration: Long, ) { - val dstCameraPosition = position.toCameraPosition() mainCoroutine.launch { + val dstCameraPosition = toNativeCamera(position).toCameraPosition() val cameraUpdate = CameraUpdateFactory.newCameraPosition(dstCameraPosition) holder.map.animateCamera( cameraUpdate, @@ -74,6 +92,7 @@ internal fun GoogleMapViewController.handleCameraMove() { } internal fun GoogleMapViewController.handleCameraIdle() { + rasterLayerController.onCameraIdle() val mapCameraPosition = getMapCameraPosition() defaultCoroutine.launch { markerController.onCameraChanged(mapCameraPosition) } emitCameraMoveEnd(getMapCameraPosition()) @@ -88,7 +107,13 @@ internal fun GoogleMapViewController.handleCameraMoveCanceled() { } internal fun GoogleMapViewController.getMapCameraPosition(): MapCameraPosition { - val camera = holder.map.cameraPosition.toMapCameraPosition() + val camera = + CameraPaddingEmulation.fromNativeCamera( + holder.map.cameraPosition.toMapCameraPosition(), + cameraPaddings, + GOOGLE_VERTICAL_FOV, + viewportHeightDp(), + ) holder.map.projection.visibleRegion.let { val visibleRegion = VisibleRegion( diff --git a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewStateImpl.kt b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewStateImpl.kt index c86fb25..5df8c95 100644 --- a/src/main/java/com/mapconductor/googlemaps/GoogleMapViewStateImpl.kt +++ b/src/main/java/com/mapconductor/googlemaps/GoogleMapViewStateImpl.kt @@ -9,6 +9,7 @@ import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapPaddings import com.mapconductor.core.map.MapViewState +import com.mapconductor.core.map.MapViewStateBundle import com.mapconductor.core.map.MapViewStateInterface import java.util.UUID import android.os.Bundle @@ -36,17 +37,24 @@ class GoogleMapViewState( this.controller?.setMapDesignType(value) } get() = _mapDesignType - private var controller: GoogleMapViewControllerInterface? = null + + // Read through the base so that letting go of the controller there (MapViewBase + // does it when the map is torn down) leaves nothing behind here. + private val controller: GoogleMapViewControllerInterface? + get() = attachedMapController as? GoogleMapViewControllerInterface internal fun setController(controller: GoogleMapViewControllerInterface) { - this.controller = controller -// _mapDesignType.let { -// controller.setMapDesignType(it) -// } + // コントローラが覚えているデザインを state のものにしておく。既定の None のままだと、 + // 変更リスナーを繋いだ時点で None が state へ返ってきて、復元したデザインを潰す。 + // 地図は state の mapType で作られているので、地図の見た目は変わらない。 + controller.setMapDesignType(_mapDesignType) attachController(controller) } internal fun onMapDesignTypeChange(value: GoogleMapDesignType) { + // 地図から読み戻した値は mapType(Int)から作った定義済みデザインで、attributionRules を + // 持たない。同じ mapType なら、アプリが渡した(あるいは復元した)デザインを残す。 + if (value.getValue() == _mapDesignType.getValue()) return _mapDesignType = value } @@ -64,26 +72,42 @@ class GoogleMapViewSaver : BaseMapViewSaver() { state: GoogleMapViewState, bundle: Bundle, ) { - bundle.putInt("id", state.mapDesignType.id) + val design = state.mapDesignType + bundle.putInt("id", design.id) + // 定義済み(Normal など)以外は Custom として戻す。id だけだと Custom の + // attributionRules が落ち、定義に無い id は None になってしまう。 + bundle.putBoolean(KEY_CUSTOM, design !== GoogleMapDesign.toMapDesignType(design.id)) + MapViewStateBundle.putAttributionRules(bundle, design.attributionRules) } override fun createState( stateId: String, mapDesignBundle: Bundle?, cameraPosition: MapCameraPosition, - ): GoogleMapViewState = - GoogleMapViewState( + ): GoogleMapViewState { + val id = mapDesignBundle?.getInt("id", GoogleMapDesign.Normal.id) ?: GoogleMapDesign.Normal.id + val design = + if (mapDesignBundle?.getBoolean(KEY_CUSTOM) == true) { + GoogleMapDesign.Custom( + id = id, + attributionRules = MapViewStateBundle.getAttributionRules(mapDesignBundle), + ) + } else { + GoogleMapDesign.Create(id) + } + return GoogleMapViewState( id = stateId, - mapDesignType = - GoogleMapDesign.Create( - id = mapDesignBundle?.getInt("id") ?: GoogleMapDesign.Normal.id, - ), + mapDesignType = design, cameraPosition = cameraPosition, ) + } override fun getStateId(state: GoogleMapViewState): String = state.id } +// 公開 API の門番(javap)にコンパニオンの定数が載らないよう、ファイル private にする。 +private const val KEY_CUSTOM = "custom" + @Composable fun rememberGoogleMapViewState( mapDesign: GoogleMapDesign = GoogleMapDesign.Normal, diff --git a/src/main/java/com/mapconductor/googlemaps/MapCameraPosition.kt b/src/main/java/com/mapconductor/googlemaps/MapCameraPosition.kt index 2f867cc..e5e2cd6 100644 --- a/src/main/java/com/mapconductor/googlemaps/MapCameraPosition.kt +++ b/src/main/java/com/mapconductor/googlemaps/MapCameraPosition.kt @@ -2,6 +2,7 @@ package com.mapconductor.googlemaps import com.google.android.gms.maps.model.CameraPosition import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.CameraBearing import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapPaddings @@ -15,6 +16,13 @@ import kotlin.math.tan private val converter = ZoomAltitudeConverter(AbstractZoomAltitudeConverter.DEFAULT_ZOOM0_ALTITUDE) +/** + * Google Maps(Android)のカメラの縦方向の視野角(度)。SDK に取得 API は無い。 + * 地図の大きさによらず一定で、TB520FU の縦・横・半分の大きさで 30° を実測した + * (焦点距離 ≈ 地図の高さ × 1.86)。web の Google Maps JS(ベクター地図)の約 25° とは違う。 + */ +internal const val GOOGLE_VERTICAL_FOV = 30.0 + fun MapCameraPosition.toCameraPosition(): CameraPosition { if (this.tilt >= 0) { return CameraPosition @@ -22,7 +30,7 @@ fun MapCameraPosition.toCameraPosition(): CameraPosition { .target(GeoPoint.from(position).toLatLng()) .zoom(zoom.toFloat()) .tilt(tilt.coerceIn(0.0, 60.0).toFloat()) - .bearing(bearing.toFloat()) + .bearing(CameraBearing.toNativeHeading(bearing).toFloat()) .build() } else { // tilt < 0: 水平線より abs(tilt) 度上方を向く(仰角ビュー) @@ -33,7 +41,7 @@ fun MapCameraPosition.toCameraPosition(): CameraPosition { val tiltAbsRad = Math.toRadians(tiltAbsDeg) val altitude = converter.zoomLevelToAltitude(zoom, position.latitude, 0.0) val distanceForward = altitude * tan(tiltAbsRad) - val target = Spherical.computeOffset(position, distanceForward, bearing) + val target = Spherical.computeOffset(position, distanceForward, CameraBearing.toNativeHeading(bearing)) val adjustedZoom = converter.altitudeToZoomLevel(altitude / cos(tiltAbsRad), target.latitude, 0.0) return CameraPosition @@ -41,7 +49,7 @@ fun MapCameraPosition.toCameraPosition(): CameraPosition { .target(target.toLatLng()) .zoom(adjustedZoom.toFloat()) .tilt(tiltAbsDeg.toFloat()) - .bearing(bearing.toFloat()) + .bearing(CameraBearing.toNativeHeading(bearing).toFloat()) .build() } } @@ -57,6 +65,7 @@ fun MapCameraPosition.Companion.from(position: MapCameraPositionInterface): MapC tilt = position.tilt, paddings = position.paddings, visibleRegion = position.visibleRegion, + fov = position.fov, ) } @@ -71,9 +80,10 @@ fun CameraPosition.toMapCameraPosition(paddings: MapPaddingsInterface = MapPaddi return MapCameraPosition( position = position, zoom = zoom.toDouble(), - bearing = bearing.toDouble(), + bearing = CameraBearing.bearingFromNativeHeading(bearing.toDouble()), tilt = tilt.toDouble(), paddings = paddings, visibleRegion = null, + fov = GOOGLE_VERTICAL_FOV, ) } diff --git a/src/main/java/com/mapconductor/googlemaps/circle/GoogleMapCircleOverlayRenderer.kt b/src/main/java/com/mapconductor/googlemaps/circle/GoogleMapCircleOverlayRenderer.kt index aef70b5..33f116f 100644 --- a/src/main/java/com/mapconductor/googlemaps/circle/GoogleMapCircleOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/circle/GoogleMapCircleOverlayRenderer.kt @@ -7,6 +7,8 @@ import com.mapconductor.core.calculateZIndex import com.mapconductor.core.circle.AbstractCircleOverlayRenderer import com.mapconductor.core.circle.CircleEntityInterface import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.geometry.circleToRing import com.mapconductor.core.geometry.closeRing @@ -37,7 +39,7 @@ class GoogleMapCircleOverlayRenderer( .fillColor(state.fillColor.toArgb()) .clickable(false) .geodesic(state.geodesic) - .zIndex((state.zIndex ?: calculateZIndex(state.center)).toFloat()) + .zIndex(OverlayStacking.flatZIndex(OverlayKind.Circle, state.zIndex ?: calculateZIndex(state.center))) holder.map.addPolygon(options).also { it.tag = state.id } @@ -82,7 +84,11 @@ class GoogleMapCircleOverlayRenderer( circle.fillColor = current.state.fillColor.toArgb() } if (finger.zIndex != prevFinger.zIndex) { - circle.zIndex = (current.state.zIndex ?: calculateZIndex(current.state.center)).toFloat() + circle.zIndex = + OverlayStacking.flatZIndex( + OverlayKind.Circle, + current.state.zIndex ?: calculateZIndex(current.state.center), + ) } circle } diff --git a/src/main/java/com/mapconductor/googlemaps/groundimage/GoogleMapGroundImageOverlayRenderer.kt b/src/main/java/com/mapconductor/googlemaps/groundimage/GoogleMapGroundImageOverlayRenderer.kt index 67c71cf..3c262d8 100644 --- a/src/main/java/com/mapconductor/googlemaps/groundimage/GoogleMapGroundImageOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/groundimage/GoogleMapGroundImageOverlayRenderer.kt @@ -3,6 +3,8 @@ package com.mapconductor.googlemaps.groundimage import androidx.core.graphics.drawable.toBitmap import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.GroundOverlayOptions +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking import com.mapconductor.core.groundimage.AbstractGroundImageOverlayRenderer import com.mapconductor.core.groundimage.GroundImageEntityInterface import com.mapconductor.core.groundimage.GroundImageState @@ -28,6 +30,8 @@ class GoogleMapGroundImageOverlayRenderer( .image(image) .positionFromBounds(bounds) .transparency(1.0f - opacity) + // GroundImage の帯(タイルの上、ポリゴンの下)。Google は種類をまたいで zIndex で重ねる。 + .zIndex(OverlayStacking.flatZIndex(OverlayKind.GroundImage, 0)) holder.map.addGroundOverlay(options)?.also { it.tag = state.id } diff --git a/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerController.kt b/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerController.kt index 373d7c6..99d0c2f 100644 --- a/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerController.kt +++ b/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerController.kt @@ -1,404 +1,453 @@ -package com.mapconductor.googlemaps.marker - -import com.mapconductor.core.controller.OnCameraChangeReceiverInterface -import com.mapconductor.core.controller.OverlayControllerInterface -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.marker.AbstractMarkerController -import com.mapconductor.core.marker.BitmapIcon -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerEntity -import com.mapconductor.core.marker.MarkerEntityInterface -import com.mapconductor.core.marker.MarkerIngestionEngine -import com.mapconductor.core.marker.MarkerManager -import com.mapconductor.core.marker.MarkerOverlayRendererInterface -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.MarkerTileRenderer -import com.mapconductor.core.marker.MarkerTilingOptions -import com.mapconductor.core.marker.MarkerViewportSwitch -import com.mapconductor.core.raster.RasterLayerSource -import com.mapconductor.core.raster.RasterLayerState -import com.mapconductor.core.raster.TileScheme -import com.mapconductor.core.tileserver.TileServerRegistry -import com.mapconductor.googlemaps.GoogleMapActualMarker -import com.mapconductor.googlemaps.GoogleMapViewHolder -import java.util.UUID -import android.util.Log -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.withPermit -import kotlinx.coroutines.withContext - -/** - * Callback interface for managing RasterLayer from MarkerController. - * This is used to decouple the MarkerController from the RasterLayerController. - */ -fun interface MarkerTileRasterLayerCallback { - /** - * Called when the marker tile RasterLayer needs to be added, updated, or removed. - * @param state The RasterLayerState to add/update, or null to remove - */ - suspend fun onRasterLayerUpdate(state: RasterLayerState?) -} - -interface GoogleMapMarkerControllerInterface : - OverlayControllerInterface> - -internal class GoogleMapMarkerController private constructor( - renderer: GoogleMapMarkerRenderer, - markerManager: MarkerManager, - private val markerTiling: MarkerTilingOptions, -) : AbstractMarkerController( - markerManager = markerManager, - renderer = renderer, - ), - GoogleMapMarkerControllerInterface, - OnCameraChangeReceiverInterface { - private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() - private val tiledMarkerIds = LinkedHashSet() - - private var lastKnownZoom: Double = 0.0 - - // Tile rendering via RasterLayer - private val tileServer = TileServerRegistry.get() - private var markerTileRenderer: MarkerTileRenderer? = null - private var markerTileGroupId: String? = null - private var markerTileRasterLayerState: RasterLayerState? = null - private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null - private var cacheVersion: Int = 0 - - /** - * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 - * - * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 - */ - private val viewportSwitch = - MarkerViewportSwitch( - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - semaphore = semaphore, - policy = markerTiling.viewport, - setTileLayerVisible = ::setTileLayerVisible, - invalidateTiles = ::updateRasterLayerSource, - ) - - /** - * Sets the callback for RasterLayer operations. - * This must be called before using tiled marker rendering. - */ - internal fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { - rasterLayerCallback = callback - } - - override suspend fun add(data: List) { - // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 - // semaphore は再入不可なので withPermit の外で呼ぶこと。 - viewportSwitch.retract() - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && data.size >= markerManager.minMarkerCount - - val result = - withContext(Dispatchers.Default) { - MarkerIngestionEngine.ingest( - data = data, - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - tilingEnabled = tilingEnabled, - tiledMarkerIds = tiledMarkerIds, - shouldTile = { state -> !state.draggable && state.getAnimation() == null }, - ) - } - - if (result.tiledDataChanged) { - syncTiledOverlay() - } else if (result.hasTiledMarkers) { - // Keep existing tile overlay if present. - // (No per-zoom indexing needed; renderTile queries MarkerManager directly.) - if (markerTileRenderer == null || markerTileRasterLayerState == null) { - syncTiledOverlay() - } - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun update(state: MarkerState) { - if (!markerManager.hasEntity(state.id)) return - - // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 - // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 - if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) - - val prevEntity = markerManager.getEntity(state.id) ?: return - val currentFinger = state.fingerPrint() - val prevFinger = prevEntity.fingerPrint - if (currentFinger == prevFinger) return - - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount - val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null - val wasTiled = tiledMarkerIds.contains(state.id) - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon - - if (wantsTiled) { - if (!wasTiled) { - prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } - tiledMarkerIds.add(state.id) - } - markerManager.updateEntity( - MarkerEntity( - marker = null, - state = state, - visible = prevEntity.visible, - isRendered = true, - // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 - // タイル昇格したのにタイルへ描かれないマーカーになる。 - tiling = true, - ), - ) - syncTiledOverlay() - return - } - - if (wasTiled) { - tiledMarkerIds.remove(state.id) - } - - val renderEntity = - MarkerEntity( - marker = prevEntity.marker, - state = state, - visible = prevEntity.visible, - isRendered = true, - ) - - val markerParams = - object : MarkerOverlayRendererInterface.ChangeParamsInterface { - override val current: MarkerEntityInterface = renderEntity - override val bitmapIcon: BitmapIcon = markerIcon - override val prev: MarkerEntityInterface = prevEntity - } - val markers = renderer.onChange(listOf(markerParams)) - - markers.firstOrNull()?.let { actualMarker -> - markerManager.updateEntity( - MarkerEntity( - marker = actualMarker, - state = state, - visible = prevEntity.visible, - isRendered = true, - ), - ) - - if (prevFinger.animation != currentFinger.animation) { - state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } - } - } - - renderer.onPostProcess() - - if (tiledMarkerIds.isNotEmpty()) { - syncTiledOverlay() - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun clear() { - viewportSwitch.destroy() - semaphore.withPermit { - val entities = markerManager.allEntities() - val toRemove = entities.filter { it.marker != null } - if (toRemove.isNotEmpty()) { - renderer.onRemove(toRemove) - } - markerManager.clear() - tiledMarkerIds.clear() - removeTileOverlay() - } - } - - override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { - // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 - viewportSwitch.onCameraChanged(mapCameraPosition) - lastKnownZoom = mapCameraPosition.zoom - - // Also update the MarkerTileRenderer's camera zoom for fractional zoom support - } - - /** - * マーカータイルのラスターレイヤの表示だけを切り替える。 - * - * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに - * タイルキャッシュを捨てるのと同じになる。 - */ - private suspend fun setTileLayerVisible(visible: Boolean) { - val current = markerTileRasterLayerState ?: return - if (current.visible == visible) return - val newState = current.copy(visible = visible) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - override fun destroy() { - viewportSwitch.destroy() - // Clean up tile server registration - // Unregister this map's route only. Never stop the server here: it is - // a process-wide singleton shared by all map controllers and overlay - // modules; stopping it breaks tile loading for every other live map. - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - // Remove RasterLayer via callback - (renderer as GoogleMapMarkerRenderer).coroutine.launch { - rasterLayerCallback?.onRasterLayerUpdate(null) - } - markerTileRasterLayerState = null - super.destroy() - } - - /** - * Updates the RasterLayer source URL to trigger a cache refresh. - * Creates a new RasterLayerState to ensure proper change detection. - */ - private suspend fun updateRasterLayerSource() { - val groupId = - markerTileGroupId ?: run { - Log.w(TAG, "updateRasterLayerSource: groupId is null, skip") - return - } - val tileRenderer = - markerTileRenderer ?: run { - Log.w(TAG, "updateRasterLayerSource: tileRenderer is null, skip") - return - } - val oldState = - markerTileRasterLayerState - ?: run { - Log.w(TAG, "updateRasterLayerSource: rasterLayerState is null, skip") - return - } - cacheVersion = (cacheVersion + 1) and 0x7fffffff - tileRenderer.invalidate() - - // Create a new state object so RasterLayerController can detect the change - val newState = - oldState.copy( - source = - RasterLayerSource.UrlTemplate( - template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?v=$cacheVersion", - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - id = oldState.id, - ) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - private suspend fun syncTiledOverlay() { - if (tiledMarkerIds.isEmpty()) { - removeTileOverlay() - return - } - if (!markerTiling.enabled) { - removeTileOverlay() - tiledMarkerIds.clear() - return - } - - // Ensure tile renderer + RasterLayer are created before updating the source. - getOrCreateTileRenderer() - updateRasterLayerSource() - } - - private fun getOrCreateTileRenderer(): MarkerTileRenderer { - markerTileRenderer?.let { - return it - } - - val groupId = UUID.randomUUID().toString() - markerTileGroupId = groupId - - val tileRenderer = - MarkerTileRenderer( - markerManager = markerManager, - tileSize = 256, - cacheSizeBytes = markerTiling.cacheSize, - debugTileOverlay = markerTiling.debugTileOverlay, - iconScaleCallback = markerTiling.iconScaleCallback, - ) - markerTileRenderer = tileRenderer - - // Register with tile server - tileServer.register(groupId, tileRenderer) - - // Create RasterLayerState - markerTileRasterLayerState = - RasterLayerState( - id = "marker-tile-$groupId", - source = - RasterLayerSource.UrlTemplate( - template = tileServer.urlTemplate(groupId, tileRenderer.tileSize), - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - opacity = 1.0f, - visible = true, - ) - - return tileRenderer - } - - private suspend fun removeTileOverlay() { - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - // Remove RasterLayer - rasterLayerCallback?.onRasterLayerUpdate(null) - markerTileRasterLayerState = null - } - - companion object { - private const val TAG = "GoogleMapMarkerController" - - fun create( - holder: GoogleMapViewHolder, - markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, - ): GoogleMapMarkerController { - val markerManager = - MarkerManager.defaultManager( - minMarkerCount = markerTiling.minMarkerCount, - ) - val renderer = - GoogleMapMarkerRenderer( - holder = holder, - ) - val controller = - GoogleMapMarkerController( - renderer = renderer, - markerManager = markerManager, - markerTiling = markerTiling, - ) - controller.lastKnownZoom = - holder.map.cameraPosition.zoom - .toDouble() - return controller - } - } -} +package com.mapconductor.googlemaps.marker + +import com.mapconductor.core.controller.OnCameraChangeReceiverInterface +import com.mapconductor.core.controller.OverlayControllerInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.marker.AbstractMarkerController +import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerEntityInterface +import com.mapconductor.core.marker.MarkerIngestionEngine +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.core.marker.MarkerViewportSwitch +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.TileScheme +import com.mapconductor.core.tileserver.TileServerRegistry +import com.mapconductor.googlemaps.GoogleMapActualMarker +import com.mapconductor.googlemaps.GoogleMapViewHolder +import java.util.UUID +import kotlin.math.floor +import kotlin.time.Duration.Companion.milliseconds +import android.util.Log +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext + +/** + * Callback interface for managing RasterLayer from MarkerController. + * This is used to decouple the MarkerController from the RasterLayerController. + */ +fun interface MarkerTileRasterLayerCallback { + /** + * Called when the marker tile RasterLayer needs to be added, updated, or removed. + * @param state The RasterLayerState to add/update, or null to remove + */ + suspend fun onRasterLayerUpdate(state: RasterLayerState?) +} + +interface GoogleMapMarkerControllerInterface : + OverlayControllerInterface> + +internal class GoogleMapMarkerController private constructor( + renderer: GoogleMapMarkerRenderer, + markerManager: MarkerManager, + private val markerTiling: MarkerTilingOptions, +) : AbstractMarkerController( + markerManager = markerManager, + renderer = renderer, + ), + GoogleMapMarkerControllerInterface, + OnCameraChangeReceiverInterface { + private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() + private val tiledMarkerIds = LinkedHashSet() + + // タイルを描くスレッドからも読む([displayTileZoom])。 + @Volatile + private var lastKnownZoom: Double = 0.0 + + /** 前回タイルを描き直したときの [displayTileZoom]。 */ + private var lastDisplayTileZoom: Int? = null + + // Tile rendering via RasterLayer + private val tileServer = TileServerRegistry.get() + private var markerTileRenderer: MarkerTileRenderer? = null + private var markerTileGroupId: String? = null + private var markerTileRasterLayerState: RasterLayerState? = null + private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null + private var cacheVersion: Int = 0 + + /** + * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 + * + * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 + */ + private val viewportSwitch = + MarkerViewportSwitch( + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + semaphore = semaphore, + policy = markerTiling.viewport, + setTileLayerVisible = ::setTileLayerVisible, + invalidateTiles = ::updateRasterLayerSource, + ) + + /** + * Sets the callback for RasterLayer operations. + * This must be called before using tiled marker rendering. + */ + internal fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { + rasterLayerCallback = callback + } + + override suspend fun add(data: List) { + // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 + // semaphore は再入不可なので withPermit の外で呼ぶこと。 + viewportSwitch.retract() + semaphore.withPermit { + val tilingEnabled = + markerTiling.enabled && data.size >= markerManager.minMarkerCount + + val result = + withContext(Dispatchers.Default) { + MarkerIngestionEngine.ingest( + data = data, + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + tilingEnabled = tilingEnabled, + tiledMarkerIds = tiledMarkerIds, + shouldTile = { state -> !state.draggable && state.getAnimation() == null }, + ) + } + + if (result.tiledDataChanged) { + syncTiledOverlay() + } else if (result.hasTiledMarkers) { + // Keep existing tile overlay if present. + // (No per-zoom indexing needed; renderTile queries MarkerManager directly.) + if (markerTileRenderer == null || markerTileRasterLayerState == null) { + syncTiledOverlay() + } + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + override suspend fun update(state: MarkerState) { + if (!markerManager.hasEntity(state.id)) return + + // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 + // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 + if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) + + val prevEntity = markerManager.getEntity(state.id) ?: return + val currentFinger = state.fingerPrint() + val prevFinger = prevEntity.fingerPrint + if (currentFinger == prevFinger) return + + semaphore.withPermit { + // 件数だけが要る。allEntities() は全件の写しを作るので、ラベルの付け替えのように + // 数十本が続けて変わると、そのたびに 14 万件を写すことになる。 + val tilingEnabled = + markerTiling.enabled && markerManager.getMemoryStats().entityCount >= markerManager.minMarkerCount + val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null + val wasTiled = tiledMarkerIds.contains(state.id) + + if (wantsTiled) { + if (!wasTiled) { + prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } + tiledMarkerIds.add(state.id) + } + markerManager.updateEntity( + MarkerEntity( + marker = null, + state = state, + visible = prevEntity.visible, + isRendered = true, + // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 + // タイル昇格したのにタイルへ描かれないマーカーになる。 + tiling = true, + ), + ) + scheduleTileRefresh() + return + } + + if (wasTiled) { + tiledMarkerIds.remove(state.id) + } + // ネイティブマーカーとして描くときだけ焼き込む。タイル担当なら要らない。 + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon + + val renderEntity = + MarkerEntity( + marker = prevEntity.marker, + state = state, + visible = prevEntity.visible, + isRendered = true, + ) + + val markerParams = + object : MarkerOverlayRendererInterface.ChangeParamsInterface { + override val current: MarkerEntityInterface = renderEntity + override val bitmapIcon: BitmapIcon = markerIcon + override val prev: MarkerEntityInterface = prevEntity + } + val markers = renderer.onChange(listOf(markerParams)) + + markers.firstOrNull()?.let { actualMarker -> + markerManager.updateEntity( + MarkerEntity( + marker = actualMarker, + state = state, + visible = prevEntity.visible, + isRendered = true, + ), + ) + + if (prevFinger.animation != currentFinger.animation) { + state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } + } + } + + renderer.onPostProcess() + + if (tiledMarkerIds.isNotEmpty()) { + scheduleTileRefresh() + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + private var tileRefreshJob: Job? = null + + /** + * 1 本ずつの変更からの描き直しを 1 回にまとめる。 + * + * ラベルの付け替えのように数十本が続けて変わると、1 本ごとにラスターソースを差し替え、 + * そのたびに地図が見えているタイルを全部取り直していた(MapLibre・Pixel 5a で 45 回、 + * 描き直したタイル 494 枚、最後のタイルまで 6 秒)。続けて来た変更は + * [TILE_REFRESH_COALESCE] の間に受けて、まとめて 1 回だけ差し替える。 + */ + private fun scheduleTileRefresh() { + if (tileRefreshJob?.isActive == true) return + tileRefreshJob = + (renderer as GoogleMapMarkerRenderer).coroutine.launch { + delay(TILE_REFRESH_COALESCE) + semaphore.withPermit { syncTiledOverlay() } + } + } + + override suspend fun clear() { + viewportSwitch.destroy() + semaphore.withPermit { + val entities = markerManager.allEntities() + val toRemove = entities.filter { it.marker != null } + if (toRemove.isNotEmpty()) { + renderer.onRemove(toRemove) + } + markerManager.clear() + tiledMarkerIds.clear() + removeTileOverlay() + } + } + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 + viewportSwitch.onCameraChanged(mapCameraPosition) + lastKnownZoom = mapCameraPosition.zoom + + // Google Maps は切り捨てたズームのタイルを出す。マーカーとラベルを MapLibre 系と + // 同じ大きさに見せるため、タイルは四捨五入したズームに合わせて描いている + // ([MarkerTileRenderer] の displayTileZoom)。それが変わったら、地図が持っている + // タイルは大きさが合わなくなるので取り直させる。 + val displayZoom = displayTileZoom() + if (displayZoom != lastDisplayTileZoom) { + lastDisplayTileZoom = displayZoom + if (markerTileRenderer != null) scheduleTileRefresh() + } + } + + /** カメラのズームを四捨五入したズーム(MapLibre 系がタイルに使うズーム)。 */ + private fun displayTileZoom(): Int = floor(lastKnownZoom + 0.5).toInt() + + /** + * マーカータイルのラスターレイヤの表示だけを切り替える。 + * + * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに + * タイルキャッシュを捨てるのと同じになる。 + */ + private suspend fun setTileLayerVisible(visible: Boolean) { + val current = markerTileRasterLayerState ?: return + if (current.visible == visible) return + val newState = current.copy(visible = visible) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + override fun destroy() { + viewportSwitch.destroy() + // 待っている描き直しが後から走ると、外したタイル経路をまた登録してしまう。 + tileRefreshJob?.cancel() + // Clean up tile server registration + // Unregister this map's route only. Never stop the server here: it is + // a process-wide singleton shared by all map controllers and overlay + // modules; stopping it breaks tile loading for every other live map. + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + // Remove RasterLayer via callback + (renderer as GoogleMapMarkerRenderer).coroutine.launch { + rasterLayerCallback?.onRasterLayerUpdate(null) + } + markerTileRasterLayerState = null + super.destroy() + } + + /** + * Updates the RasterLayer source URL to trigger a cache refresh. + * Creates a new RasterLayerState to ensure proper change detection. + */ + private suspend fun updateRasterLayerSource() { + val groupId = + markerTileGroupId ?: run { + Log.w(TAG, "updateRasterLayerSource: groupId is null, skip") + return + } + val tileRenderer = + markerTileRenderer ?: run { + Log.w(TAG, "updateRasterLayerSource: tileRenderer is null, skip") + return + } + val oldState = + markerTileRasterLayerState + ?: run { + Log.w(TAG, "updateRasterLayerSource: rasterLayerState is null, skip") + return + } + cacheVersion = (cacheVersion + 1) and 0x7fffffff + tileRenderer.invalidate() + + // Create a new state object so RasterLayerController can detect the change + val newState = + oldState.copy( + source = + RasterLayerSource.UrlTemplate( + template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?v=$cacheVersion", + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + id = oldState.id, + ) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + private suspend fun syncTiledOverlay() { + if (tiledMarkerIds.isEmpty()) { + removeTileOverlay() + return + } + if (!markerTiling.enabled) { + removeTileOverlay() + tiledMarkerIds.clear() + return + } + + // Ensure tile renderer + RasterLayer are created before updating the source. + getOrCreateTileRenderer() + updateRasterLayerSource() + } + + private fun getOrCreateTileRenderer(): MarkerTileRenderer { + markerTileRenderer?.let { + return it + } + + val groupId = UUID.randomUUID().toString() + markerTileGroupId = groupId + + val tileRenderer = + MarkerTileRenderer( + markerManager = markerManager, + tileSize = 256, + cacheSizeBytes = markerTiling.cacheSize, + debugTileOverlay = markerTiling.debugTileOverlay, + iconScaleCallback = markerTiling.iconScaleCallback, + declutterPx = markerTiling.declutterPx, + displayTileZoom = ::displayTileZoom, + ) + markerTileRenderer = tileRenderer + + // Register with tile server + tileServer.register(groupId, tileRenderer) + + // Create RasterLayerState + markerTileRasterLayerState = + RasterLayerState( + id = "marker-tile-$groupId", + source = + RasterLayerSource.UrlTemplate( + template = tileServer.urlTemplate(groupId, tileRenderer.tileSize), + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + opacity = 1.0f, + visible = true, + ) + + return tileRenderer + } + + private suspend fun removeTileOverlay() { + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + // Remove RasterLayer + rasterLayerCallback?.onRasterLayerUpdate(null) + markerTileRasterLayerState = null + } + + companion object { + /** 続けて来る変更を 1 回の描き直しにまとめる窓。1 フレーム分。 */ + private val TILE_REFRESH_COALESCE = 16.milliseconds + + private const val TAG = "GoogleMapMarkerController" + + fun create( + holder: GoogleMapViewHolder, + markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, + ): GoogleMapMarkerController { + val markerManager = + MarkerManager.defaultManager( + minMarkerCount = markerTiling.minMarkerCount, + ) + val renderer = + GoogleMapMarkerRenderer( + holder = holder, + ) + val controller = + GoogleMapMarkerController( + renderer = renderer, + markerManager = markerManager, + markerTiling = markerTiling, + ) + controller.lastKnownZoom = + holder.map.cameraPosition.zoom + .toDouble() + return controller + } + } +} diff --git a/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerRenderer.kt b/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerRenderer.kt index aa7e098..7ecbd7a 100644 --- a/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/marker/GoogleMapMarkerRenderer.kt @@ -2,11 +2,11 @@ package com.mapconductor.googlemaps.marker import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions -import com.mapconductor.core.calculateZIndex import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.marker.AbstractMarkerOverlayRenderer import com.mapconductor.core.marker.MarkerEntityInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState import com.mapconductor.googlemaps.GoogleMapActualMarker import com.mapconductor.googlemaps.GoogleMapViewHolder import com.mapconductor.googlemaps.toLatLng @@ -22,8 +22,16 @@ class GoogleMapMarkerRenderer( holder = holder, coroutine = coroutine, ) { - private fun resolveZIndex(params: MarkerOverlayRendererInterface.AddParamsInterface): Float = - (params.state.zIndex ?: calculateZIndex(params.state.position)).toFloat() + // zIndex が第 1 キー、同じなら画面で下(北が上なら南、さらに西)が手前。値を小さく保つのは、 + // Google が大きな値(以前の -緯度 × 10^6)を明示の小さな zIndex と正しく比べないため。 + private fun resolveZIndex(state: MarkerState): Float = drawOrderOf(state).toFloat() + + // 地図が回ったら、今ある全マーカーの zIndex を付け直す。 + override suspend fun applyDrawOrder(entities: List>) { + withContext(coroutine.coroutineContext) { + entities.forEach { entity -> entity.marker?.zIndex = resolveZIndex(entity.state) } + } + } override val supportsAnimationOverlay: Boolean = true @@ -59,7 +67,7 @@ class GoogleMapMarkerRenderer( params.bitmapIcon.anchor.y, ).icon(bitmapDescriptor) .draggable(params.state.draggable) - .zIndex(resolveZIndex(params)) + .zIndex(resolveZIndex(params.state)) val marker = holder.map.addMarker(options)?.also { it.tag = params.state.id @@ -118,8 +126,7 @@ class GoogleMapMarkerRenderer( marker.position = GeoPoint.from(params.current.state.position).toLatLng() marker.isVisible = params.current.visible - marker.zIndex = - (params.current.state.zIndex ?: calculateZIndex(params.current.state.position)).toFloat() + marker.zIndex = resolveZIndex(params.current.state) // Google Mapsはマーカーを再作成しなくてよいので、同じマーカーのインスタンスを返す marker diff --git a/src/main/java/com/mapconductor/googlemaps/polygon/GoogleMapPolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/googlemaps/polygon/GoogleMapPolygonOverlayRenderer.kt index d579143..92cee63 100644 --- a/src/main/java/com/mapconductor/googlemaps/polygon/GoogleMapPolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/polygon/GoogleMapPolygonOverlayRenderer.kt @@ -4,14 +4,15 @@ import androidx.compose.ui.graphics.toArgb import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.PolygonOptions import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.geometry.densifyPolygonRing import com.mapconductor.core.polygon.AbstractPolygonOverlayRenderer import com.mapconductor.core.polygon.PolygonEntityInterface import com.mapconductor.core.polygon.PolygonState import com.mapconductor.core.polygon.unionHoles -import com.mapconductor.core.spherical.Planar -import com.mapconductor.core.spherical.WGS84Geodesic import com.mapconductor.googlemaps.AdaptiveInterpolation import com.mapconductor.googlemaps.GoogleMapActualPolygon import com.mapconductor.googlemaps.GoogleMapViewHolder @@ -42,7 +43,9 @@ internal class GoogleMapPolygonOverlayRenderer( val key = AdaptiveInterpolation.cacheKey(AdaptiveInterpolation.pointsHash(statePoints), maxSegmentLength) interpolationCache.get(key)?.let { return it } - val geoPoints = WGS84Geodesic.createInterpolatePoints(statePoints, maxSegmentLength = maxSegmentLength) + // リングの閉じる辺(末尾 → 先頭)も大圏で補間する。隣り合う点の間だけを補間すると、閉じる辺が + // 直線の弦になり、塗りも輪郭(同じネイティブポリゴンの stroke)もそこだけ直線になる。 + val geoPoints = densifyPolygonRing(statePoints, geodesic = true, maxSegmentLength = maxSegmentLength) val points = geoPoints.map { GeoPoint.from(it).toLatLng() } interpolationCache.put(key, points) return points @@ -54,7 +57,9 @@ internal class GoogleMapPolygonOverlayRenderer( ): List = when (geodesic) { true -> geodesicPoints(statePoints) - false -> Planar.createInterpolatePoints(statePoints).map { GeoPoint.from(it).toLatLng() } + // geodesic=false も閉じる辺を緯度経度で線形補間する(輪郭のポリラインと同じ線。補間しないと + // 閉じる辺だけメルカトルの直線になる)。 + false -> densifyPolygonRing(statePoints, geodesic = false).map { GeoPoint.from(it).toLatLng() } } private fun toLatLngHoles( @@ -88,7 +93,7 @@ internal class GoogleMapPolygonOverlayRenderer( .strokeColor(resolved.strokeColor.toArgb()) .strokeWidth(ResourceProvider.dpToPx(resolved.strokeWidth).toFloat()) .fillColor(resolved.fillColor.toArgb()) - .zIndex(resolved.zIndex.toFloat()) + .zIndex(OverlayStacking.flatZIndex(OverlayKind.Polygon, resolved.zIndex)) .clickable(false) holder.map.addPolygon(options).also { it.tag = state.id @@ -123,7 +128,7 @@ internal class GoogleMapPolygonOverlayRenderer( polygon.fillColor = current.state.fillColor.toArgb() } if (finger.zIndex != prevFinger.zIndex) { - polygon.zIndex = current.state.zIndex.toFloat() + polygon.zIndex = OverlayStacking.flatZIndex(OverlayKind.Polygon, current.state.zIndex) } polygon } diff --git a/src/main/java/com/mapconductor/googlemaps/polyline/GoogleMapPolylineOverlayRenderer.kt b/src/main/java/com/mapconductor/googlemaps/polyline/GoogleMapPolylineOverlayRenderer.kt index 38c220f..43ad344 100644 --- a/src/main/java/com/mapconductor/googlemaps/polyline/GoogleMapPolylineOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/polyline/GoogleMapPolylineOverlayRenderer.kt @@ -5,6 +5,8 @@ import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Polyline import com.google.android.gms.maps.model.PolylineOptions import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.polyline.AbstractPolylineOverlayRenderer @@ -57,7 +59,7 @@ class GoogleMapPolylineOverlayRenderer( .color(state.strokeColor.toArgb()) .width(ResourceProvider.dpToPx(state.strokeWidth).toFloat()) .geodesic(state.geodesic) - .zIndex(state.zIndex.toFloat()) + .zIndex(OverlayStacking.flatZIndex(OverlayKind.Polyline, state.zIndex)) .clickable(false) holder.map.addPolyline(options).also { @@ -95,7 +97,7 @@ class GoogleMapPolylineOverlayRenderer( } if (finger.zIndex != prevFinger.zIndex) { - polyline.zIndex = current.state.zIndex.toFloat() + polyline.zIndex = OverlayStacking.flatZIndex(OverlayKind.Polyline, current.state.zIndex) } polyline diff --git a/src/main/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueue.kt b/src/main/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueue.kt new file mode 100644 index 0000000..f7dccf2 --- /dev/null +++ b/src/main/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueue.kt @@ -0,0 +1,99 @@ +package com.mapconductor.googlemaps.raster + +import com.mapconductor.core.InternalMapConductorApi +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock +import kotlin.math.abs + +/** Bounds local renders and discards obsolete zooms before they occupy a worker. */ +@InternalMapConductorApi +internal class GoogleLocalTileRequestQueue( + private val width: Int = 4, + private val render: (String, () -> Boolean) -> ByteArray?, +) { + @InternalMapConductorApi + private class Job(val zoom: Int) { + val cancelled = AtomicBoolean(false) + } + + private val lock = ReentrantLock() + private val changed = lock.newCondition() + private val pending = mutableListOf() + private val active = mutableSetOf() + private val retryAfterZoom = AtomicBoolean(false) + private var zoom: Double? = null + private var closed = false + + init { + require(width > 0) + } + + fun updateZoom(next: Double) { + if (!next.isFinite()) return + lock.withLock { + zoom = next + for (job in pending + active) { + if (abs(job.zoom - next) > 1.5 && job.cancelled.compareAndSet(false, true)) retryAfterZoom.set(true) + } + pending.removeAll { it.cancelled.get() } + changed.signalAll() + } + } + + fun consumeRetryAfterZoom(): Boolean = retryAfterZoom.getAndSet(false) + + fun close() { + lock.withLock { + closed = true + for (job in pending + active) job.cancelled.set(true) + pending.clear() + changed.signalAll() + } + } + + fun renderTile(url: String, tileZoom: Int): ByteArray? { + val job = Job(tileZoom) + lock.withLock { + if (closed || zoom?.let { abs(tileZoom - it) > 1.5 } == true) return null + pending.add(job) + try { + while (!job.cancelled.get()) { + val current = zoom + val next = pending.minByOrNull { abs(it.zoom - (current ?: it.zoom.toDouble())) } + if (active.size < width && next === job) { + pending.remove(job) + active.add(job) + break + } + if (current != null && next != null) { + val closest = abs(next.zoom - current) + for (running in active) { + if (abs(running.zoom - current) > closest + 0.25 && running.cancelled.compareAndSet(false, true)) { + retryAfterZoom.set(true) + } + } + } + changed.await() + } + if (job.cancelled.get()) return null + } catch (_: InterruptedException) { + job.cancelled.set(true) + Thread.currentThread().interrupt() + return null + } finally { + pending.remove(job) + changed.signalAll() + } + } + return try { + val bytes = render(url) { job.cancelled.get() } + if (job.cancelled.get()) null else bytes + } finally { + lock.withLock { + active.remove(job) + changed.signalAll() + } + } + } +} diff --git a/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerController.kt b/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerController.kt index 34cdf79..9f73fef 100644 --- a/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerController.kt +++ b/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerController.kt @@ -2,6 +2,8 @@ package com.mapconductor.googlemaps.raster import com.google.android.gms.maps.model.TileOverlay import com.mapconductor.core.controller.OverlayControllerInterface +import com.mapconductor.core.map.MapCameraPosition +import kotlinx.coroutines.withContext import com.mapconductor.core.raster.RasterLayerController import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerManager @@ -18,4 +20,19 @@ internal class GoogleMapRasterLayerController( rasterLayerManager: RasterLayerManagerInterface = RasterLayerManager(), renderer: GoogleMapRasterLayerOverlayRenderer, ) : RasterLayerController(rasterLayerManager, renderer), - GoogleMapRasterLayerControllerInterface + GoogleMapRasterLayerControllerInterface { + private val tileRenderer = renderer + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + withContext(tileRenderer.coroutine.coroutineContext) { + tileRenderer.updateLocalZoom(mapCameraPosition.zoom) + } + } + + internal fun onCameraIdle() { tileRenderer.refreshLocalTilesAfterZoom() } + + override fun destroy() { + tileRenderer.removeAllLayers() + super.destroy() + } +} diff --git a/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerOverlayRenderer.kt index 43239bd..e0685b4 100644 --- a/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/googlemaps/raster/GoogleMapRasterLayerOverlayRenderer.kt @@ -5,26 +5,36 @@ import com.google.android.gms.maps.model.TileOverlay import com.google.android.gms.maps.model.TileOverlayOptions import com.google.android.gms.maps.model.TileProvider import com.google.android.gms.maps.model.TileProvider.NO_TILE +import com.mapconductor.core.controller.OverlayKind +import com.mapconductor.core.controller.OverlayStacking +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface import com.mapconductor.core.raster.RasterLayerSource import com.mapconductor.core.raster.RasterLayerState import com.mapconductor.core.raster.TileScheme +import com.mapconductor.core.tileserver.TileServerRegistry import com.mapconductor.googlemaps.GoogleMapViewHolder import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import java.io.ByteArrayOutputStream import java.io.IOException +import java.util.concurrent.atomic.AtomicLong import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Typeface +import android.os.SystemClock import android.util.Log import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class GoogleMapRasterLayerOverlayRenderer( @@ -32,14 +42,77 @@ class GoogleMapRasterLayerOverlayRenderer( private val okHttpClient: OkHttpClient, override val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Main), ) : RasterLayerOverlayRendererInterface { + private val localRequests = mutableMapOf() + + /** 各オーバーレイがタイルを最後に返した時刻。差し替えた古い方を外す時機に使う。 */ + private val tileActivity = mutableMapOf() + + /** 差し替え済みで、新しい方のタイルが揃うのを待って外す古いオーバーレイ。 */ + private val retiring = mutableSetOf() + + /** + * 各オーバーレイに渡したタイルプロバイダ。SDK はオーバーレイを外しても、地図を + * 破棄しても、渡されたプロバイダをプロセス共有の表に残す(実測)。そこから + * このレンダラ・ホルダー・MapView まで辿れてしまうので、外すときに中身を切り離す。 + */ + private val providers = mutableMapOf() + + internal fun updateLocalZoom(zoom: Double) { + localRequests.values.forEach { it.updateZoom(zoom) } + } + + internal fun refreshLocalTilesAfterZoom() { + // Google backs off retryable null tiles. Reset that backoff after a + // zoom settles, so returning to a cancelled zoom does not wait seconds. + localRequests.forEach { (overlay, requests) -> + if (requests.consumeRetryAfterZoom()) overlay.clearTileCache() + } + } + + internal fun cancelLocalRequests() { + localRequests.values.forEach { it.close() } + localRequests.clear() + } + + /** + * Takes every overlay this renderer added off the map. Called when the map + * goes away: the SDK keeps a tile overlay's provider in a process-wide + * table until the overlay is removed, and the provider reaches this + * renderer and through it the map view. Must run on the main thread, before + * the MapView is destroyed. + */ + internal fun removeAllLayers() { + cancelLocalRequests() + (tileActivity.keys + retiring).forEach { overlay -> runCatching { overlay.remove() } } + tileActivity.clear() + retiring.clear() + providers.values.forEach { it.detach() } + providers.clear() + } + + private fun forget(overlay: TileOverlay) { + tileActivity.remove(overlay) + providers.remove(overlay)?.detach() + } + private fun isMarkerTileRaster(state: RasterLayerState): Boolean = state.id.startsWith(MARKER_TILE_RASTER_ID_PREFIX) + // Google は TileOverlay・GroundOverlay・Polygon・Circle・Polyline を 1 本の zIndex で重ねる + // (Marker は常にその上)。帯の順(OverlayStacking)に沿って値を割り当てる。 private fun resolveOverlayZIndex(state: RasterLayerState): Float = if (isMarkerTileRaster(state)) { - // Backward-compatible behavior: marker tiles stay above most overlays. - 999f + // マーカーのタイルはマーカーの帯(ポリラインより上)。 + OverlayStacking.flatZIndex(OverlayKind.Marker, Int.MIN_VALUE) + } else if (state.id == POLYGON_TILE_LAYER_ID) { + // ポリゴンのタイルはポリゴンの帯の一番下(GroundImage より上、ネイティブのポリゴンより下)。 + OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MIN_VALUE) + } else if (state.id == CIRCLE_TILE_LAYER_ID) { + OverlayStacking.flatZIndex(OverlayKind.Circle, Int.MIN_VALUE) + } else if (state.id == POLYLINE_TILE_LAYER_ID) { + // ポリラインのタイルはポリラインの帯の一番下(サークルより上、ネイティブのポリラインより下)。 + OverlayStacking.flatZIndex(OverlayKind.Polyline, Int.MIN_VALUE) } else { - state.zIndex.toFloat() + OverlayStacking.flatZIndex(OverlayKind.RasterLayer, state.zIndex) } override suspend fun onAdd(data: List): List = @@ -57,8 +130,12 @@ class GoogleMapRasterLayerOverlayRenderer( val prev = params.prev val next = params.current.state if (prev.state.source != next.source || prev.state.debug != next.debug) { - prev.layer.remove() - addLayer(next) + // 先に外すと、新しいタイルが届くまでの間(マーカータイルで 0.3 秒ほど) + // レイヤーが丸ごと消えて点滅する。新しい方を足してから古い方を外す。 + localRequests.remove(prev.layer)?.close() + val added = addLayer(next) + retireWhenReplaced(prev.layer, added) + added } else { updateLayer(prev.layer, next) prev.layer @@ -69,8 +146,45 @@ class GoogleMapRasterLayerOverlayRenderer( override suspend fun onRemove(data: List>) { withContext(coroutine.coroutineContext) { data.forEach { entity -> + localRequests.remove(entity.layer)?.close() + forget(entity.layer) entity.layer.remove() } + retiring.forEach { + forget(it) + it.remove() + } + retiring.clear() + } + } + + /** + * [old] を、[replacement] がタイルを返し終えたころに外す。 + * + * Google Maps にはタイルを描き終えた通知が無いので、新しい方がタイルを 1 枚以上返し、 + * そのあと [RETIRE_QUIET_MS] のあいだ頼まれなくなったら揃ったとみなす。地図が + * 何も頼まない(見えている範囲にタイルが無い)こともあるので、[RETIRE_TIMEOUT_MS] で + * 打ち切って外す。 + */ + private fun retireWhenReplaced( + old: TileOverlay, + replacement: TileOverlay?, + ) { + retiring.add(old) + val activity = replacement?.let { tileActivity[it] } + coroutine.launch { + val start = SystemClock.elapsedRealtime() + while (true) { + val now = SystemClock.elapsedRealtime() + if (now - start >= RETIRE_TIMEOUT_MS) break + val last = activity?.get() ?: 0L + if (last > 0L && now - last >= RETIRE_QUIET_MS) break + delay(RETIRE_POLL_MS) + } + if (retiring.remove(old)) { + forget(old) + old.remove() + } } } @@ -98,6 +212,17 @@ class GoogleMapRasterLayerOverlayRenderer( } val requestHeaders = headerBuilder.build() + // Only this registry's local routes bypass HTTP. Remote raster + // sources retain their headers, user agent and OkHttp behaviour. + val server = if (tileSpec.template.startsWith("http://127.0.0.1:")) TileServerRegistry.get() else null + val requests = if (server != null && tileSpec.template.startsWith("${server.baseUrl}/tiles/")) { + GoogleLocalTileRequestQueue { url, cancelled -> server.renderLocalTile(url, cancelled) }.also { + it.updateZoom(holder.map.cameraPosition.zoom.toDouble()) + } + } else { + null + } + val activity = AtomicLong(0L) val provider = object : TileProvider { private var firstTileLogged = false @@ -106,7 +231,7 @@ class GoogleMapRasterLayerOverlayRenderer( x: Int, y: Int, zoom: Int, - ): Tile { + ): Tile? { if (!firstTileLogged) { firstTileLogged = true } @@ -123,6 +248,19 @@ class GoogleMapRasterLayerOverlayRenderer( .replace("{y}", schemeY.toString()) .replace("{z}", zoom.toString()) + if (requests != null) { + // A cancelled/failed tile is retryable. NO_TILE would + // cache a permanent hole when this zoom is revisited. + val bytes = runCatching { requests.renderTile(url, zoom) }.getOrNull() ?: return null + activity.set(SystemClock.elapsedRealtime()) + val rendered = if (state.debug) { + addDebugOverlay(bytes, tileSpec.tileSize, x, schemeY, zoom, tileSpec.scheme) + } else { + bytes + } + return Tile(tileSpec.tileSize, tileSpec.tileSize, rendered) + } + val request: Request = Request .Builder() @@ -153,6 +291,7 @@ class GoogleMapRasterLayerOverlayRenderer( imageBytes } + activity.set(SystemClock.elapsedRealtime()) // Return a new Tile with the image data return Tile(tileSpec.tileSize, tileSpec.tileSize, renderedBytes) } @@ -163,13 +302,21 @@ class GoogleMapRasterLayerOverlayRenderer( } } } + val detachable = DetachableTileProvider(provider) val options = TileOverlayOptions() - .tileProvider(provider) + .tileProvider(detachable) .zIndex(resolveOverlayZIndex(state)) .transparency(opacityToTransparency(state.opacity)) .visible(state.visible) val overlay = holder.map.addTileOverlay(options) + if (overlay != null) { + tileActivity[overlay] = activity + providers[overlay] = detachable + } + if (requests != null) { + if (overlay != null) localRequests[overlay] = requests else requests.close() + } return overlay } @@ -207,6 +354,21 @@ class GoogleMapRasterLayerOverlayRenderer( private fun opacityToTransparency(opacity: Float): Float = (1.0f - opacity.coerceIn(0.0f, 1.0f)).coerceIn(0.0f, 1.0f) + /** SDK に渡すのはこれ。[detach] したあとは何も返さず、元のプロバイダも掴まない。 */ + private class DetachableTileProvider( + @Volatile private var delegate: TileProvider?, + ) : TileProvider { + override fun getTile( + x: Int, + y: Int, + zoom: Int, + ): Tile? = delegate?.getTile(x, y, zoom) ?: NO_TILE + + fun detach() { + delegate = null + } + } + private data class TileSpec( val template: String, val tileSize: Int, @@ -215,6 +377,14 @@ class GoogleMapRasterLayerOverlayRenderer( private companion object { private const val TAG = "GoogleMapRasterLayerOverlayRenderer" + + /** 新しいオーバーレイへの依頼がこれだけ途切れたら、古い方を外す。 */ + private const val RETIRE_QUIET_MS = 150L + + /** 新しい方が何も頼まれなくても、古い方はこれだけ待って外す。 */ + private const val RETIRE_TIMEOUT_MS = 1_500L + + private const val RETIRE_POLL_MS = 30L private const val MARKER_TILE_RASTER_ID_PREFIX = "marker-tile-" } diff --git a/src/test/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueueTest.kt b/src/test/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueueTest.kt new file mode 100644 index 0000000..67c0f49 --- /dev/null +++ b/src/test/java/com/mapconductor/googlemaps/raster/GoogleLocalTileRequestQueueTest.kt @@ -0,0 +1,100 @@ +package com.mapconductor.googlemaps.raster + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +class GoogleLocalTileRequestQueueTest { + @Test + fun obsoletePendingRequestsReturnBeforeTheActiveRenderFinishes() { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val queue = GoogleLocalTileRequestQueue(width = 1) { _, _ -> entered.countDown(); release.await(); byteArrayOf(1) } + val workers = Executors.newFixedThreadPool(2) + try { + queue.updateZoom(12.0) + val owner = workers.submit { queue.renderTile("owner", 12) } + assertTrue(entered.await(1, TimeUnit.SECONDS)) + val pending = workers.submit { queue.renderTile("pending", 12) } + queue.updateZoom(16.0) + assertNull(pending.get(1, TimeUnit.SECONDS)) + assertFalse(owner.isDone) + assertTrue(queue.consumeRetryAfterZoom()) + assertFalse(queue.consumeRetryAfterZoom()) + assertNull(queue.renderTile("obsolete-arrival", 12)) + release.countDown() + assertNull(owner.get(1, TimeUnit.SECONDS)) + } finally { + release.countDown(); queue.close(); workers.shutdownNow() + } + } + + @Test + fun currentZoomPreemptsAnAdjacentFallbackWhenEverySlotIsOccupied() { + val entered = CountDownLatch(1) + val queue = GoogleLocalTileRequestQueue(width = 1) { url, cancelled -> + if (url == "fallback") { + entered.countDown() + while (!cancelled()) Thread.sleep(1) + } + url.toByteArray() + } + val workers = Executors.newFixedThreadPool(2) + try { + queue.updateZoom(12.0) + val fallback = workers.submit { queue.renderTile("fallback", 11) } + assertTrue(entered.await(1, TimeUnit.SECONDS)) + val current = workers.submit { queue.renderTile("current", 12) } + assertEquals("current", current.get(1, TimeUnit.SECONDS)!!.decodeToString()) + assertNull(fallback.get(1, TimeUnit.SECONDS)) + } finally { + queue.close(); workers.shutdownNow() + } + } + + @Test + fun concurrentSdkCallbacksRemainBoundedAndKeepTheirCoordinates() { + val active = AtomicInteger() + val peak = AtomicInteger() + val queue = GoogleLocalTileRequestQueue(width = 3) { url, _ -> + peak.accumulateAndGet(active.incrementAndGet(), ::maxOf) + try { Thread.sleep(2); url.toByteArray() } finally { active.decrementAndGet() } + } + val workers = Executors.newFixedThreadPool(16) + try { + queue.updateZoom(12.0) + val results = (0 until 200).map { id -> workers.submit { queue.renderTile("12/$id/1612", 12) } } + results.forEachIndexed { id, result -> assertEquals("12/$id/1612", result.get(5, TimeUnit.SECONDS)!!.decodeToString()) } + assertTrue(peak.get() in 1..3) + assertEquals(0, active.get()) + } finally { + queue.close(); workers.shutdownNow() + } + } + + @Test + fun removingTheLayerRejectsNewRequestsAndCancelsTheActiveOne() { + val entered = CountDownLatch(1) + val queue = GoogleLocalTileRequestQueue { _, cancelled -> + entered.countDown() + while (!cancelled()) Thread.sleep(1) + byteArrayOf(1) + } + val worker = Executors.newSingleThreadExecutor() + try { + val running = worker.submit { queue.renderTile("active", 12) } + assertTrue(entered.await(1, TimeUnit.SECONDS)) + queue.close() + assertNull(running.get(1, TimeUnit.SECONDS)) + assertNull(queue.renderTile("after-close", 12)) + } finally { + queue.close(); worker.shutdownNow() + } + } +}