aboutsummaryrefslogtreecommitdiff
path: root/androidApp/src/main/java/mx/trackermap/TrackerMap/android/map/MapFragment.kt
blob: b04bfbc500e0000e07f01a7dc4ca9b92ca79b4f3 (plain)
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
/**
 * TrackerMap
 * Copyright (C) 2021-2022  Iván Ávalos <avalos@disroot.org>, Henoch Ojeda <imhenoch@protonmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package mx.trackermap.TrackerMap.android.map

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import com.mousebird.maply.*
import com.soywiz.krypto.md5
import mil.nga.sf.Polygon
import mil.nga.sf.util.SFException
import mil.nga.sf.wkt.GeometryReader
import java.io.File
import mx.trackermap.TrackerMap.android.R
import mx.trackermap.TrackerMap.android.shared.MarkerTransformations
import mx.trackermap.TrackerMap.client.models.Geofence
import mx.trackermap.TrackerMap.client.models.MapLayer
import mx.trackermap.TrackerMap.client.models.Marker
import mx.trackermap.TrackerMap.utils.MapCalculus

typealias SetupCallback = () -> Unit
typealias MarkerCallback = (Int?) -> Unit

open class MapFragment : GlobeMapFragment() {

    private var loader: QuadImageLoader? = null

    var hasStarted: Boolean = false
    val setupCallbacks = mutableListOf<SetupCallback>()
    var markerCallback: MarkerCallback? = null

    private val objects = mutableListOf<ComponentObject>()
    private val geofenceObjects = mutableListOf<ComponentObject>()

    private var tileInfo: TileInfoNew? = null

    override fun chooseDisplayType(): MapDisplayType {
        return MapDisplayType.Map
    }

    override fun preControlCreated() {
        super.preControlCreated()
        mapSettings.clearColor = Color.WHITE
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        super.onCreateView(inflater, container, savedInstanceState)
        return baseControl.contentView!!
    }

    override fun controlHasStarted() {
        Log.d("MapFragment", "controlHasStarted")

        if (tileInfo == null) {
            val layer = MapLayer.defaultLayer
            // Load default map layer
            val info = RemoteTileInfoNew(layer.url, layer.minZoom, layer.maxZoom)
            tileInfo = tileInfoSetCacheDir(layer.url, info)
            tileInfo?.let {
                setZoomLimits(layer.minZoom, layer.maxZoom)
            }
        }

        val params = SamplingParams()
        params.coordSystem = SphericalMercatorCoordSystem()
        params.coverPoles = true
        params.edgeMatching = true
        params.minZoom = tileInfo!!.minZoom
        params.maxZoom = tileInfo!!.maxZoom
        params.singleLevel = true
        params.maxTiles = 25

        loader = QuadImageLoader(params, tileInfo, baseControl)
        loader?.setImageFormat(RenderController.ImageFormat.MaplyImageUShort565)

        val latitude = 23.191 * Math.PI / 180
        val longitude = -100.36 * Math.PI / 180
        mapControl.setPositionGeo(longitude, latitude, 0.4)

        hasStarted = true
        setupCallbacks.forEach { it() }
        setupCallbacks.clear()
    }

    override fun onStop() {
        super.onStop()
        hasStarted = false
    }

    override fun mapDidStopMoving(
        mapControl: MapController?,
        corners: Array<out Point3d>?,
        userMotion: Boolean
    ) {
        super.mapDidStopMoving(mapControl, corners, userMotion)
        Log.d("MapFragment", "Height: %7.7f".format(mapControl?.height))
    }

    override fun userDidSelect(
        mapControl: MapController?,
        selObjs: Array<out SelectedObject>?,
        loc: Point2d?,
        screenLoc: Point2d?
    ) {
        super.userDidSelect(mapControl, selObjs, loc, screenLoc)
        selObjs?.forEach { selectedObject ->
            if (selectedObject.selObj is ScreenMarker) {
                val screenMarker = selectedObject.selObj as ScreenMarker
                val markerId = screenMarker.userObject as Int
                Log.d("MapFragment", "Selected marker with id: $markerId")

                markerCallback?.let { it(markerId) }
            }
        }
    }

    override fun userDidTap(mapControl: MapController?, loc: Point2d?, screenLoc: Point2d?) {
        super.userDidTap(mapControl, loc, screenLoc)

        markerCallback?.let { it(null) }
    }

    private fun clear(geofences: Boolean = false) {
        if (mapControl == null) {
            return
        }

        if (geofences) {
            mapControl.removeObjects(
                geofenceObjects,
                ThreadMode.ThreadAny
            )
            geofenceObjects.clear()
        } else {
            mapControl.removeObjects(
                objects,
                ThreadMode.ThreadAny
            )
            objects.clear()
        }
    }

    fun display(markers: Array<Marker>, isReport: Boolean, center: Boolean = true) {
        Log.d("MapFragment", "Displaying markers")

        clear()

        val points = markers.map { marker ->
            Point2d.FromDegrees(marker.longitude, marker.latitude)
        }.toTypedArray()

        val fontSize = context?.resources?.getDimensionPixelSize(R.dimen.marker_label_text_size)
        val colorReport = ContextCompat.getColor(requireContext(), R.color.colorReport)
        val colorLabel = ContextCompat.getColor(requireContext(), R.color.colorMarkerLabel)
        val colorLabelOutline = ContextCompat.getColor(requireContext(), R.color.colorMarkerLabelOutline)
        val vectorWidth = context?.resources?.getDimensionPixelSize(R.dimen.report_label_width)?.toFloat()

        val vectorInfo = VectorInfo()
        vectorInfo.setColor(colorReport)
        vectorInfo.setLineWidth(vectorWidth ?: 20f)

        val labelInfo = LabelInfo()
        labelInfo.typeface = Typeface.DEFAULT_BOLD
        labelInfo.textColor = colorLabel
        labelInfo.outlineColor = colorLabelOutline
        labelInfo.outlineSize = 3.0f
        fontSize?.let {
            labelInfo.fontSize = it.toFloat()
        }

        /* Draw markers for positions */
        val screenMarkers = markers.mapIndexed { i, marker ->
            val screenMarker = ScreenMarker()
            screenMarker.loc = Point2d.FromDegrees(marker.longitude, marker.latitude)
            screenMarker.image = if (isReport) {
                // For reports, position, start and end, icons must be different
                when (i) {
                    0 -> getIcon(Marker.Type.REPORT_START)
                    markers.size - 1 -> getIcon(Marker.Type.REPORT_END)
                    else -> getIcon(Marker.Type.REPORT_POSITION)
                }
            } else getIcon(marker.type)
            screenMarker.size = if (isReport) {
                // For reports, position, start and end, size must be different
                when (i) {
                    0 -> Point2d(144.0, 144.0)
                    markers.size - 1 -> Point2d(144.0, 144.0)
                    else -> Point2d(82.0, 82.0)
                }
            } else Point2d(144.0, 144.0)
            screenMarker.userObject = marker.id
            screenMarker.selectable = true

            screenMarker
        }

        objects.add(mapControl.addScreenMarkers(
            screenMarkers,
            MarkerInfo(),
            ThreadMode.ThreadAny
        ))

        /* Add labels for markers */
        if (!isReport && markers.isNotEmpty()) {
            val screenLabels = markers.map { marker ->
                val label = ScreenLabel()
                label.layoutImportance = Float.MAX_VALUE
                label.text = if (marker.name.length >= 20) {
                    marker.name.substring(0 until 20) + "..."
                } else marker.name
                label.loc = Point2d.FromDegrees(marker.longitude, marker.latitude)
                label.offset = Point2d(0.0, 92.0)
                label
            }

            objects.add(mapControl.addScreenLabels(
                screenLabels,
                labelInfo,
                ThreadMode.ThreadAny
            ))
        }

        /* Draw polyline for report */
        if (isReport && markers.isNotEmpty()) {
            val vector = VectorObject()
            vector.addLinear(points)

            objects.add(mapControl.addVector(
                vector,
                vectorInfo,
                ThreadMode.ThreadAny
            ))
        }

        // Center map to bounds
        if (center && markers.isNotEmpty()) {
            val mbr = Mbr()
            points.forEach {
                mbr.addPoint(it)
            }
            mbr.expandByFraction(0.1)

            mapControl?.addPostSurfaceRunnable {
                mapControl?.let {
                    val zoom = it.findHeightToViewBounds(mbr, mbr.middle())
                        .coerceAtLeast(mapControl.zoomLimitMin)
                    it.setPositionGeo(mbr.middle(), zoom)
                }
            }
        }
    }

    fun displayGeofences(geofences: Array<Geofence>) {
        Log.d("MapFragment", "Displaying geofences")

        clear(true)

        val fontSize = context?.resources?.getDimensionPixelSize(R.dimen.marker_label_text_size)
        val colorFill = ContextCompat.getColor(requireContext(), R.color.colorGeofence)
        val colorLabel = ContextCompat.getColor(requireContext(), R.color.colorGeofenceLabel)
        val colorLabelOutline = ContextCompat.getColor(requireContext(), R.color.colorMarkerLabelOutline)
        val vectorWidth = context?.resources?.getDimensionPixelSize(R.dimen.geofence_label_width)?.toFloat()

        val vectorInfo = VectorInfo()
        vectorInfo.setColor(colorFill)
        vectorInfo.setLineWidth(vectorWidth ?: 4f)

        val labelInfo = LabelInfo()
        labelInfo.typeface = Typeface.DEFAULT_BOLD
        labelInfo.textColor = colorLabel
        labelInfo.outlineColor = colorLabelOutline
        labelInfo.outlineSize = 3.0f
        fontSize?.let {
            labelInfo.fontSize = it.toFloat()
        }

        val shapes = mutableListOf<Shape>()
        val vectors = mutableListOf<VectorObject>()
        val labels = mutableListOf<ScreenLabel>()

        geofences.forEach { geofence ->
            geofence.area?.let { area ->
                try {
                    val geometry = GeometryReader.readGeometry(area)
                    if (!geometry.isEmpty) {
                        when (geometry) {
                            is Polygon -> {
                                val vector = VectorObject()
                                vector.addAreal(geometry.exteriorRing.points.map {
                                    Point2d.FromDegrees(it.y, it.x)
                                }.toTypedArray())

                                vectors.add(vector)

                                val label = ScreenLabel()
                                label.text = geofence.name
                                label.loc = Point2d.FromDegrees(geometry.centroid.y, geometry.centroid.x)
                                label.layoutImportance = Float.MAX_VALUE

                                labels.add(label)
                            }
                        }
                    }
                } catch (e: SFException) {}
            }
        }

        geofenceObjects.add(mapControl.addShapes(
            shapes,
            ShapeInfo(),
            ThreadMode.ThreadAny
        ))

        geofenceObjects.add(mapControl.addVectors(
            vectors,
            vectorInfo,
            ThreadMode.ThreadAny
        ))

        geofenceObjects.add(mapControl.addScreenLabels(
            labels,
            labelInfo,
            ThreadMode.ThreadAny
        ))
    }

    fun focusOn(
        latitude: Double,
        longitude: Double,
        height: Double = 0.0000264,
        animated: Boolean = true
    ) {
        val lat = latitude * Math.PI / 180
        val lon = longitude * Math.PI / 180
        // Ensure height is equal or higher than bottom limit
        val z = height.coerceAtLeast(mapControl.zoomLimitMin)
        if (animated) {
            mapControl.animatePositionGeo(lon, lat, z, 0.2)
        } else {
            mapControl.setPositionGeo(lon, lat, z)
        }
    }

    fun zoomIn() {
        val pos = mapControl.positionGeo.toPoint2d().toDegrees()
        val zoom = mapControl.currentMapScale() / 2
        focusOn(pos.y, pos.x, mapControl.heightForMapScale(zoom))
    }

    fun zoomOut() {
        val pos = mapControl.positionGeo.toPoint2d().toDegrees()
        val zoom = mapControl.currentMapScale() * 2
        focusOn(pos.y, pos.x, mapControl.heightForMapScale(zoom))
    }

    private fun tileInfoSetCacheDir(url: String, tileInfo: TileInfoNew): TileInfoNew? {
        return context?.let {
            val cacheDirName = url.toByteArray(Charsets.UTF_8).md5().hex
            val cacheDirMap = File(it.cacheDir, cacheDirName)
            cacheDirMap.mkdir()
            Log.d("MapFragment", "Cache dir for $url = ${cacheDirMap.absolutePath}")
            (tileInfo as? RemoteTileInfoNew)?.cacheDir = cacheDirMap
            tileInfo
        }
    }

    fun updateLayer(layer: MapLayer.Type) {
        MapLayer.layers[layer]?.let {
            val tileInfo = RemoteTileInfoNew(it.url, it.minZoom, it.maxZoom)
            this.tileInfo = tileInfoSetCacheDir(it.url, tileInfo)
            this.tileInfo?.let { t ->
                loader?.changeTileInfo(t)
                setZoomLimits(tileInfo.minZoom, tileInfo.maxZoom)

                val pos = mapControl.positionGeo.toPoint2d().toDegrees()
                focusOn(pos.y, pos.x, mapControl.positionGeo.z, animated = true)
            }
        }
    }

    private fun setZoomLimits(minZoom: Int, maxZoom: Int) {
        mapControl?.let {
            it.setZoomLimits(
                it.heightForMapScale(
                    MapCalculus.zoomLevelToScale(maxZoom)
                        ?: MapCalculus.zoomLevelToScale(21)!!
                ),
                it.heightForMapScale(
                    MapCalculus.zoomLevelToScale(minZoom)
                        ?: MapCalculus.zoomLevelToScale(1)!!
                )
            )
        }
    }

    private fun getIcon(markerType: Marker.Type): Bitmap {
        return ResourcesCompat.getDrawable(
            requireActivity().resources,
            MarkerTransformations.markerTypeToResourceId(markerType),
            requireActivity().theme)!!.toBitmap(144, 144)
    }
}