Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 143 additions & 30 deletions src/main/java/com/mapconductor/compose/AddProgress.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.mapconductor.compose
import android.os.SystemClock
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
Expand All @@ -12,6 +13,9 @@ import com.mapconductor.core.OverlayAddedListeners
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch

/**
Expand All @@ -20,20 +24,25 @@ import kotlinx.coroutines.launch
* nothing until they are drawn, and these say that work is going on.
*
* "On the map" is what each state's `onAdded` means: drawn natively, or, for a
* state drawn in tiles, its tiles handed to the map (their images may still be
* loading).
* state drawn in tiles, its tiles handed to the map. The work does not end
* there for tiles, so the collection also counts as busy while its tiles are
* being drawn ([drawingChanged]): after a filter change, and while the camera
* moves to where tiles are not drawn yet.
*
* - `onAddStart(total)`: a list brought states that are not on the map yet;
* `total` is how many.
* - `onAddStart(total)`: a list was handed over, or tiles have been drawn for
* [DRAW_START_DELAY_MS] without one; `total` is how many states the list
* brought that are not on the map yet (0 when it only removed or updated
* states, or for tiles alone).
* - `onAddProgress(added, total)`: how many of them are on the map so far, at
* most every 100 ms, and once more with `added == total` before the end.
* - `onAddEnd(total)`: all of them are on the map. A state taken out of the
* list before it got there no longer counts against the end.
* most every 100 ms, and once more with `added == total` before the end
* when `total` is not 0.
* - `onAddEnd(total)`: all of them are on the map and nothing has been drawn
* for [SETTLE_MS]. A state taken out of the list before it got there no
* longer counts against the end.
*
* A list that brings new states while an earlier one is still being added
* starts over: a new `onAddStart` with only the new states, and no `onAddEnd`
* for the earlier list. A list that only updates or removes states calls
* nothing. All three run on the main thread.
* for the earlier list. All three run on the main thread.
*/
@InternalMapConductorApi
internal class AddProgressTracker(
Expand All @@ -57,6 +66,20 @@ internal class AddProgressTracker(
private var lastProgressAt = Long.MIN_VALUE / 2
private var timer: Job? = null

/** Between an onAddStart and its onAddEnd. */
private var started = false

/** The last list had states: an empty list after an empty one hands nothing over. */
private var hadStates = false

/** The collection's tiles are being drawn (or its tiler is taking a list). */
private var drawing = false

/** When the last reason to be busy ended: a hand-over, the last arrival, drawing stopping. */
private var quietSince = Long.MIN_VALUE / 2
private var settle: Job? = null
private var drawStart: Job? = null

/**
* The states of [states] whose id is not in [prevIds], or none when no one
* listens. Call it off the main thread; it walks the whole list.
Expand All @@ -77,6 +100,9 @@ internal class AddProgressTracker(
nextIds: Set<String>,
newStates: List<ComponentState>,
) {
val hadStates = this.hadStates
this.hadStates = states.isNotEmpty()
if (states.isEmpty() && !hadStates) return
if (pending.isNotEmpty()) {
val before = pending.size
pending.keys.retainAll(nextIds)
Expand All @@ -86,20 +112,26 @@ internal class AddProgressTracker(
if (pending.isNotEmpty() && newStates.isEmpty()) {
for (state in states) if (state.id in pending) pending[state.id] = state
}
if (newStates.isEmpty()) finishIfDone()
}
if (newStates.isEmpty()) return
timer?.cancel()
timer = null
// Room for every state without a resize at the 0.75 load factor, and no more.
pending =
HashMap<String, ComponentState>((newStates.size / 0.75f).toInt() + 1).apply {
for (s in newStates) put(s.id, s)
}
total = newStates.size
added = 0
lastProgressAt = Long.MIN_VALUE / 2
onAddStart?.invoke(total)
quietSince = now()
if (newStates.isNotEmpty()) {
timer?.cancel()
timer = null
// Room for every state without a resize at the 0.75 load factor, and no more.
pending =
HashMap<String, ComponentState>((newStates.size / 0.75f).toInt() + 1).apply {
for (s in newStates) put(s.id, s)
}
total = newStates.size
added = 0
lastProgressAt = Long.MIN_VALUE / 2
begin(total)
} else if (!started) {
total = 0
added = 0
begin(0)
}
scheduleSettle()
}

/** States reached the map (any collection's, any map's: only ours count). */
Expand All @@ -114,22 +146,86 @@ internal class AddProgressTracker(
}
}
if (!hit) return
if (pending.isEmpty()) finishIfDone() else reportProgress()
if (pending.isEmpty()) {
// A HashMap keeps its table at the largest size it reached.
pending = HashMap()
quietSince = now()
scheduleSettle()
} else {
reportProgress()
}
}

/** Whether the collection's tiles are being drawn now. */
fun drawingChanged(drawing: Boolean) {
if (drawing == this.drawing) return
this.drawing = drawing
if (drawing) {
settle?.cancel()
settle = null
if (!started && drawStart == null) {
drawStart =
scope.launch {
delay(DRAW_START_DELAY_MS)
drawStart = null
if (this@AddProgressTracker.drawing && !started) {
total = 0
added = 0
begin(0)
}
}
}
} else {
drawStart?.cancel()
drawStart = null
quietSince = now()
scheduleSettle()
}
}

fun dispose() {
timer?.cancel()
timer = null
settle?.cancel()
settle = null
drawStart?.cancel()
drawStart = null
pending = HashMap()
}

private fun finishIfDone() {
if (pending.isNotEmpty()) return
pending = HashMap()
private fun begin(total: Int) {
started = true
drawStart?.cancel()
drawStart = null
onAddStart?.invoke(total)
}

private fun scheduleSettle() {
if (!started) return
settle?.cancel()
settle =
scope.launch {
delay(SETTLE_MS)
settle = null
finishIfIdle()
}
}

private fun finishIfIdle() {
if (!started || drawing || pending.isNotEmpty()) return
val wait = quietSince + SETTLE_MS - now()
if (wait > 0) {
scheduleSettle()
return
}
timer?.cancel()
timer = null
onAddProgress?.invoke(total, total)
onAddEnd?.invoke(total)
started = false
val count = total
total = 0
added = 0
if (count > 0) onAddProgress?.invoke(count, count)
onAddEnd?.invoke(count)
}

private fun reportProgress() {
Expand All @@ -154,18 +250,29 @@ internal class AddProgressTracker(
}

@InternalMapConductorApi
private companion object {
companion object {
const val PROGRESS_INTERVAL_MS = 100L

/** Drawing alone counts as work only once it has lasted this long: a camera move over cached tiles does not. */
const val DRAW_START_DELAY_MS = 200L

/** Quiet this long -- nothing handed over, arriving or drawn -- before onAddEnd. */
const val SETTLE_MS = 400L
}
}

/** The tracker for one collection, listening only while one of the callbacks is set. */
/**
* The tracker for one collection, listening only while one of the callbacks
* is set. [activity] says whether the map's tilers for this kind of overlay
* are drawing (see `BaseMapViewController.tileActivity`).
*/
@InternalMapConductorApi
@Composable
internal fun rememberAddProgress(
onAddStart: ((total: Int) -> Unit)?,
onAddProgress: ((added: Int, total: Int) -> Unit)?,
onAddEnd: ((total: Int) -> Unit)?,
activity: List<StateFlow<Boolean>> = emptyList(),
): AddProgressTracker {
val scope = rememberCoroutineScope()
val tracker = remember { AddProgressTracker(scope) }
Expand All @@ -179,6 +286,12 @@ internal fun rememberAddProgress(
val remove = if (wanted) OverlayAddedListeners.add(tracker::arrived) else null
onDispose { remove?.invoke() }
}
LaunchedEffect(tracker, wanted, activity) {
if (!wanted || activity.isEmpty()) return@LaunchedEffect
combine(activity) { busy -> busy.any { it } }
.distinctUntilChanged()
.collect { tracker.drawingChanged(it) }
}
DisposableEffect(tracker) { onDispose { tracker.dispose() } }
return tracker
}
15 changes: 15 additions & 0 deletions src/main/java/com/mapconductor/compose/OverlayTileActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.mapconductor.compose

import androidx.compose.runtime.compositionLocalOf
import com.mapconductor.core.InternalMapConductorApi
import com.mapconductor.core.controller.OverlayKind
import kotlinx.coroutines.flow.StateFlow

/**
* Whether this map's tilers of each overlay kind are busy, for the collections'
* onAddStart / onAddEnd (see [AddProgressTracker]). Nothing outside a map view
* that provides it: the collections then go by their hand-overs alone.
*/
@InternalMapConductorApi
val LocalOverlayTileActivity =
compositionLocalOf<(OverlayKind) -> List<StateFlow<Boolean>>> { { emptyList() } }
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mapconductor.compose.circle

import com.mapconductor.compose.LocalOverlayTileActivity
import com.mapconductor.core.controller.OverlayKind
import com.mapconductor.compose.rememberAddProgress
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
Expand Down Expand Up @@ -66,7 +68,9 @@ fun MapViewScope.Circles(
val prevIdsState = remember { mutableStateOf<Set<String>>(emptySet()) }
// The membership this Circles() last published as its own list, while it is still the published one.
val ownList = remember { arrayOfNulls<OverlayStateList<CircleState>>(1) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd)
val activityOf = LocalOverlayTileActivity.current
val tileActivity = remember(activityOf) { activityOf(OverlayKind.Circle) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd, tileActivity)
val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null

LaunchedEffect(states) {
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/com/mapconductor/compose/map/MapViewBase.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.mapconductor.compose.map

import com.mapconductor.core.controller.overlayTileActivity
import com.mapconductor.core.controller.OverlayKind
import com.mapconductor.compose.LocalOverlayTileActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
Expand Down Expand Up @@ -297,13 +300,18 @@ fun <
subcompose("slotid") {
@Suppress("UNUSED_VARIABLE") // KtLint: backing property rule workaround
val localController = controllerRef.value ?: return@subcompose
val tileActivityOf =
remember(localController) {
{ kind: OverlayKind -> (localController as? BaseMapViewController)?.overlayTileActivity(kind).orEmpty() }
}

// 子コンポーネントを収集する
// **ここで初めて CompositionLocalProvider を差し込む**
CompositionLocalProvider(
LocalMapOverlayRegistry provides registry,
LocalMapServiceRegistry provides state.serviceRegistry,
LocalMapViewController provides localController,
LocalOverlayTileActivity provides tileActivityOf,
LocalMarkerCollector provides scope.markerCollector,
LocalInfoBubbleCollector provides scope.bubbleFlow,
LocalCircleCollector provides scope.circleCollector,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mapconductor.compose.polygon

import com.mapconductor.compose.LocalOverlayTileActivity
import com.mapconductor.core.controller.OverlayKind
import com.mapconductor.compose.rememberAddProgress
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
Expand Down Expand Up @@ -64,7 +66,9 @@ fun MapViewScope.Polygons(
) {
val collector = LocalPolygonCollector.current
val prevIdsState = remember { mutableStateOf<Set<String>>(emptySet()) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd)
val activityOf = LocalOverlayTileActivity.current
val tileActivity = remember(activityOf) { activityOf(OverlayKind.Polygon) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd, tileActivity)
val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null

LaunchedEffect(states) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mapconductor.compose.polyline

import com.mapconductor.compose.LocalOverlayTileActivity
import com.mapconductor.core.controller.OverlayKind
import com.mapconductor.compose.rememberAddProgress
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
Expand Down Expand Up @@ -63,7 +65,9 @@ fun MapViewScope.Polylines(
) {
val collector = LocalPolylineCollector.current
val prevIdsState = remember { mutableStateOf<Set<String>>(emptySet()) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd)
val activityOf = LocalOverlayTileActivity.current
val tileActivity = remember(activityOf) { activityOf(OverlayKind.Polyline) }
val progress = rememberAddProgress(onAddStart, onAddProgress, onAddEnd, tileActivity)
val tracking = onAddStart != null || onAddProgress != null || onAddEnd != null

LaunchedEffect(states) {
Expand Down
Loading
Loading