-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMapViewModel.kt
More file actions
469 lines (425 loc) · 17.7 KB
/
MapViewModel.kt
File metadata and controls
469 lines (425 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/**
* DepNav -- department navigator.
* Copyright (C) 2022 Timofei Pushkin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ru.spbu.depnav.ui.viewmodel
import android.util.Log
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.text.intl.Locale
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.getAndUpdate
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import ovh.plrapps.mapcompose.api.addLayer
import ovh.plrapps.mapcompose.api.addMarker
import ovh.plrapps.mapcompose.api.centerOnMarker
import ovh.plrapps.mapcompose.api.disableRotation
import ovh.plrapps.mapcompose.api.enableRotation
import ovh.plrapps.mapcompose.api.maxScale
import ovh.plrapps.mapcompose.api.minScale
import ovh.plrapps.mapcompose.api.onMarkerClick
import ovh.plrapps.mapcompose.api.onTap
import ovh.plrapps.mapcompose.api.removeAllLayers
import ovh.plrapps.mapcompose.api.removeAllMarkers
import ovh.plrapps.mapcompose.api.removeMarker
import ovh.plrapps.mapcompose.api.rotateTo
import ovh.plrapps.mapcompose.api.scale
import ovh.plrapps.mapcompose.api.setColorFilterProvider
import ovh.plrapps.mapcompose.api.setScrollOffsetRatio
import ovh.plrapps.mapcompose.api.shouldLoopScale
import ovh.plrapps.mapcompose.ui.state.MapState
import ru.spbu.depnav.data.composite.MarkerWithText
import ru.spbu.depnav.data.model.Language
import ru.spbu.depnav.data.model.MapInfo
import ru.spbu.depnav.data.model.Marker
import ru.spbu.depnav.data.model.toLanguage
import ru.spbu.depnav.data.preferences.PreferencesManager
import ru.spbu.depnav.data.repository.MapRepo
import ru.spbu.depnav.data.repository.MarkerWithTextRepo
import ru.spbu.depnav.ui.component.Pin
import ru.spbu.depnav.utils.map.Floor
import ru.spbu.depnav.utils.map.TileStreamProviderFactory
import ru.spbu.depnav.utils.map.addClusterers
import ru.spbu.depnav.utils.map.addMarker
import ru.spbu.depnav.utils.map.getMarkerAlpha
import javax.inject.Inject
private const val TAG = "MapViewModel"
private const val PIN_ID = "Pin" // Real IDs start with integers
/** View model for [MapState]-related parts of [MapScreen][ru.spbu.depnav.ui.screen.MapScreen]. */
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class MapViewModel @Inject constructor(
private val tileStreamProviderFactory: TileStreamProviderFactory,
private val mapRepo: MapRepo,
private val markerRepo: MarkerWithTextRepo,
prefs: PreferencesManager
) : ViewModel() {
// Updated only on the main thread
private val state = MutableStateFlow(PrivateState())
/** UI-visible state. */
val uiState = state.map { it.toMapUiState() }.stateIn(
viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = state.value.toMapUiState()
)
private data class PrivateState(
val language: Language = Locale.current.toLanguage(),
val availableMaps: List<AvailableMap> = emptyList(),
val displayedMap: DisplayedMap? = null,
val mapColor: Color = Color.Unspecified,
val pinnedMarker: MarkerWithText? = null,
val showOnMapUi: Boolean = false
) {
data class DisplayedMap(
val id: Int,
val internalName: String,
val mapState: MapState,
val title: String,
val floorsNum: Int,
val floor: Floor
) {
constructor(mapInfo: MapInfo, mapState: MapState, title: String, floor: Floor) :
this(mapInfo.id, mapInfo.internalName, mapState, title, mapInfo.floorsNum, floor)
}
fun toMapUiState() = if (displayedMap == null) {
MapUiState.Loading(availableMaps)
} else {
MapUiState.Ready(
availableMaps,
displayedMap.mapState,
displayedMap.title,
displayedMap.floorsNum,
displayedMap.floor.number,
pinnedMarker,
showOnMapUi
)
}
}
private var _markerAlpha = MutableStateFlow(0f)
/** Alpha of marker views and clusters. */
val markerAlpha = _markerAlpha.asStateFlow()
private var markerAlphaUpdater: Job = Job().apply { complete() }
init {
viewModelScope.launch {
state.update {
val availableMaps = withContext(Dispatchers.IO) {
mapRepo.loadAll(it.language).map { (info, title) ->
AvailableMap(info.id, info.internalName, title)
}
}
it.copy(availableMaps = availableMaps)
}
}
prefs.selectedMapIdFlow
.filterNotNull() // Can only be null initially, but not set to null by the user
.onEach(::initMap)
.launchIn(viewModelScope)
state
.mapNotNull { it.displayedMap?.mapState }
.distinctUntilChanged() // State can change for other reasons
.combine(prefs.enableRotationFlow) { a, b -> a to b }
.mapLatest { (mapState, enableRotation) ->
with(mapState) {
if (enableRotation) {
enableRotation()
} else {
disableRotation()
rotateTo(0f)
}
}
}
.launchIn(viewModelScope)
state
.mapNotNull {
val (mapState, color) = with(it) { displayedMap?.mapState to mapColor }
if (mapState != null && color != Color.Unspecified) mapState to color else null
}
.distinctUntilChanged() // State can change for other reasons
.onEach { (mapState, color) ->
mapState.setColorFilterProvider { _, _, _ -> ColorFilter.tint(color) }
}
.launchIn(viewModelScope)
}
private suspend fun initMap(mapId: Int) {
Log.d(TAG, "Initializing map $mapId")
val mapInfo = withContext(Dispatchers.IO) { mapRepo.loadInfoById(mapId) }
var mapTitle: String
var firstFloor: Floor
do {
val language = state.value.language
mapTitle = mapRepo.loadTitleById(mapId, language)
firstFloor = loadFloor(mapInfo.id, mapInfo.internalName, 1, language)
} while (state.value.language != language)
val mapState = with(mapInfo) {
MapState(levelsNum, floorWidth, floorHeight, tileSize) { scale(0.0) }
}.apply {
setScrollOffsetRatio(0.5f, 0.5f)
addClusterers(markerAlpha)
shouldLoopScale = true
onTap { _, _ ->
state.update {
if (it.pinnedMarker != null) {
removeMarker(PIN_ID)
it.copy(pinnedMarker = null)
} else {
it.copy(showOnMapUi = !it.showOnMapUi)
}
}
}
onMarkerClick { id, _, _ ->
val floor = checkNotNull(state.value.displayedMap) {
"Marker can be clicked only when a map is displayed"
}.floor
val markerWithText = checkNotNull(floor.markers[id]) {
"Marker outside of the current floor got clicked"
}
pinMarker(markerWithText.marker)
state.update { it.copy(pinnedMarker = markerWithText, showOnMapUi = true) }
}
for (layer in firstFloor.layers) {
addLayer(layer)
}
for (markerWithText in firstFloor.markers.values) {
with(markerWithText) { addMarker(extendedId, marker, text, markerAlpha) }
}
markerAlphaUpdater.cancel("New map state arrived")
markerAlphaUpdater = snapshotFlow { getMarkerAlpha(minScale, scale, maxScale) }
.onEach { _markerAlpha.value = it }
.launchIn(viewModelScope)
}
state.getAndUpdate {
PrivateState(
availableMaps = it.availableMaps,
displayedMap = PrivateState.DisplayedMap(mapInfo, mapState, mapTitle, firstFloor),
mapColor = it.mapColor,
pinnedMarker = null,
showOnMapUi = true
)
}.displayedMap?.mapState?.shutdown() // Shutdown the previous map state, if any
Log.i(TAG, "Initialized map $mapInfo titled $mapTitle")
}
private suspend fun loadFloor(
mapId: Int,
internalMapName: String,
floorNo: Int,
language: Language
) = Floor(
number = floorNo,
layers = listOf(tileStreamProviderFactory.makeTileStreamProvider(internalMapName, floorNo)),
markers = withContext(Dispatchers.IO) { markerRepo.loadByFloor(mapId, floorNo, language) }
.associateBy { it.extendedId }
)
private fun MapState.pinMarker(marker: Marker) {
removeMarker(PIN_ID)
addMarker(
id = PIN_ID,
x = marker.x,
y = marker.y,
zIndex = 1f,
clickable = false
) { Pin() }
}
/** Asynchronously sets the color of map tiles. */
fun setMapColor(color: Color) {
if (state.value.mapColor != color) {
state.update { it.copy(mapColor = color) }
Log.i(TAG, "Updated map color to $color")
}
}
/** Asynchronously sets the map floor to be displayed. */
fun setFloor(floorNo: Int) {
Log.d(TAG, "Switching to floor $floorNo")
val mapState = checkNotNull(state.value.displayedMap?.mapState) { "No map to set floors" }
viewModelScope.launch { mapState.setFloor(floorNo) }
}
private suspend fun MapState.setFloor(floorNo: Int) {
var displayedMap = state.value.displayedMap.takeIf { it?.mapState == this } ?: return
var floor: Floor
do {
val language = state.value.language
floor = with(displayedMap) { loadFloor(id, internalName, floorNo, language) }
displayedMap = state.value.displayedMap.takeIf { it?.mapState == this } ?: return
} while (state.value.language != language)
with(displayedMap.mapState) {
removeAllMarkers()
if (displayedMap.floor.number != floorNo) {
removeAllLayers()
for (layer in floor.layers) {
addLayer(layer)
}
}
for (markerWithText in floor.markers.values) {
with(markerWithText) { addMarker(extendedId, marker, text, markerAlpha) }
}
}
state.update {
it.copy(
displayedMap = displayedMap.copy(floor = floor),
pinnedMarker = it.pinnedMarker?.takeIf { displayedMap.floor.number == floorNo }
)
}
Log.i(
TAG,
with(state.value) {
"Changed floor of map ${displayedMap.internalName} to $floorNo on $language"
}
)
}
/** Asynchronously centers on the specified marker and pins it. */
fun focusOnMarker(markerId: Int) {
Log.d(TAG, "Focusing on marker $markerId")
val mapState = checkNotNull(state.value.displayedMap?.mapState) { "No map to do focusing" }
viewModelScope.launch {
var markerWithText: MarkerWithText
do {
val language = state.value.language
markerWithText = withContext(Dispatchers.IO) {
markerRepo.loadById(markerId, language)
}
mapState.setFloor(markerWithText.marker.floor)
if (
state.value.displayedMap?.let {
it.mapState == mapState && it.floor.number == markerWithText.marker.floor
} != true
) {
return@launch // Map or floor got switched
}
} while (state.value.language != language)
state.update { it.copy(pinnedMarker = markerWithText, showOnMapUi = true) }
with(mapState) {
pinMarker(markerWithText.marker)
centerOnMarker(markerWithText.extendedId, maxScale)
}
Log.i(TAG, "Finished focusing on marker with text ${markerWithText.text}")
}
}
/**
* Asynchronously updates language of the map-related UI parts that come from the persisted
* storage and thus are not updated automatically by Android.
*/
fun onLocaleChange(locale: Locale) {
val language = locale.toLanguage()
if (state.value.language == language) {
return
}
Log.d(TAG, "Updating language to $language")
viewModelScope.launch {
val newAvailableMaps = withContext(Dispatchers.IO) {
mapRepo.loadAll(language).map { (info, title) ->
AvailableMap(info.id, info.internalName, title)
}
}
while (true) {
val stateSnapshot = state.value
val (newDisplayedMap, newPinnedMarker) = stateSnapshot.displayedMap?.run {
val newMapTitle = mapRepo.loadTitleById(id, language)
val newFloor = loadFloor(id, internalName, floor.number, language)
val newPinnedMarker = stateSnapshot.pinnedMarker?.let { (marker) ->
newFloor.markers.values.first { it.marker.id == marker.id }
}
copy(title = newMapTitle, floor = newFloor) to newPinnedMarker
} ?: (null to null)
val currentState = state.value
if (currentState.language == language) {
return@launch // The language has already been set
}
if (currentState.displayedMap?.let { it != stateSnapshot.displayedMap } == true ||
currentState.pinnedMarker?.let { it != stateSnapshot.pinnedMarker } == true) {
continue // State got changed significantly, need to try again
}
val newState = stateSnapshot.copy(
language = language,
availableMaps = newAvailableMaps,
displayedMap = newDisplayedMap.takeIf { currentState.displayedMap != null },
pinnedMarker = newPinnedMarker.takeIf { currentState.pinnedMarker != null }
)
state.value = newState
newState.displayedMap?.run {
mapState.removeAllMarkers()
for (markerWithText in floor.markers.values) {
mapState.addMarker(
markerWithText.extendedId,
markerWithText.marker,
markerWithText.text,
markerAlpha
)
}
newPinnedMarker?.run { mapState.pinMarker(marker) }
}
Log.i(TAG, "Updated language to $language")
return@launch
}
}
}
}
/** Describes states of map UI. */
sealed interface MapUiState {
/** State that has a list of available maps. */
sealed interface WithAvailableMaps : MapUiState {
/** Maps available in the app. */
val availableMaps: List<AvailableMap>
}
/** State in which a map has not yet been loaded. */
data class Loading(
override val availableMaps: List<AvailableMap> = emptyList()
) : WithAvailableMaps
/** State in which a map has been loaded. */
data class Ready(
override val availableMaps: List<AvailableMap>,
/** State of the map. */
val mapState: MapState,
/** Localized title of the map. */
val mapTitle: String,
/** Number of floors the current map has. */
val floorsNum: Int,
/** The floor currently displayed. */
val currentFloor: Int,
/** Latest pinned marker. */
val pinnedMarker: MarkerWithText?,
/** Whether any UI is displayed above the map. */
val showOnMapUi: Boolean
) : WithAvailableMaps
}
/** Map description for the UI. */
data class AvailableMap(
/** ID of the map. */
val id: Int,
/** Name needed to retrieve resources and assets for the map. */
val internalName: String,
/** Localized title of the map. */
val title: String
)