Bimba.git

ref: 28e71396b2ed6cee7c88b62de6788b39344689ff

app/src/main/java/ml/adamsprogs/bimba/api/Structs.kt


  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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package ml.adamsprogs.bimba.api

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.text.format.DateUtils
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.ColorUtils.HSLToColor
import androidx.core.graphics.drawable.toBitmap
import ml.adamsprogs.bimba.R
import ml.adamsprogs.bimba.dpToPixel
import ml.adamsprogs.bimba.dpToPixelI
import xyz.apiote.fruchtfleisch.Reader
import java.io.InputStream
import java.util.*
import java.util.zip.Adler32
import kotlin.math.abs
import kotlin.math.pow

data class Position(
	val latitude: Double,
	val longitude: Double
) {
	fun isZero(): Boolean {
		return latitude == 0.0 && longitude == 0.0
	}

	override fun toString(): String = "$latitude,$longitude"

	companion object {
		fun unmarshal(stream: InputStream): Position {
			val reader = Reader(stream)
			return Position(
				reader.readFloat64(),
				reader.readFloat64()
			)
		}
	}
}

data class DateTime(
	val year: Int,
	val month: Int,
	val day: Int,
	val hour: Int,
	val minute: Int,
	val second: Int,
	val offsetSign: Int,
	val offsetH: Int,
	val offsetM: Int
) {
	companion object {
		fun of(s: String): DateTime {
			val (oH, oM) = if (s[19] == 'Z') {
				arrayOf(0, 0)
			} else {
				arrayOf(Integer.parseInt(s.substring(20, 22)), Integer.parseInt(s.substring(23, 25)))
			}
			val oS = when (s[19]) {
				'Z' -> 0
				'+' -> 1
				'-' -> -1
				else -> TODO("Throw invalid")
			}
			return DateTime(
				Integer.parseInt(s.substring(0, 4)),
				Integer.parseInt(s.substring(5, 7)),
				Integer.parseInt(s.substring(8, 10)),
				Integer.parseInt(s.substring(11, 13)),
				Integer.parseInt(s.substring(14, 16)),
				Integer.parseInt(s.substring(17, 19)),
				oS, oH, oM
			)
		}
	}
}

data class FeedInfo(
	val name: String,
	val id: String,
	val attribution: String,
	val description: String,
	val lastUpdate: DateTime
) {
	companion object {
		fun unmarshal(stream: InputStream): FeedInfo {
			val reader = Reader(stream)
			return FeedInfo(
				reader.readString(),
				reader.readString(),
				reader.readString(),
				reader.readString(),
				DateTime.of(reader.readString())
			)
		}
	}
}

data class Alert(
	val header: String,
	val Description: String,
	val Url: String,
	val Cause: UInt,
	val Effect: UInt
) {
	companion object {
		fun unmarshal(stream: InputStream): Alert {
			val reader = Reader(stream)
			val header = reader.readString()
			val description = reader.readString()
			val url = reader.readString()
			val cause = reader.readU32()
			val effect = reader.readU32()
			return Alert(header, description, url, cause, effect)
		}
	}
}

data class Time(
	val Hour: UInt,
	val Minute: UInt,
	val Second: UInt,
	val DayOffset: Byte,
	val Zone: String
) {
	companion object {
		fun unmarshal(stream: InputStream): Time {
			val reader = Reader(stream)
			return Time(
				reader.readUInt().toUInt(),
				reader.readUInt().toUInt(),
				reader.readUInt().toUInt(),
				reader.readI8(),
				reader.readString()
			)
		}
	}
}

data class Colour(val R: UByte, val G: UByte, val B: UByte) {
	companion object {
		fun unmarshal(stream: InputStream): Colour {
			val reader = Reader(stream)
			return Colour(
				reader.readU8(),
				reader.readU8(),
				reader.readU8()
			)
		}
	}

	fun toInt(): Int {
		var rgb = 0xff
		rgb = (rgb shl 8) + R.toInt()
		rgb = (rgb shl 8) + G.toInt()
		rgb = (rgb shl 8) + B.toInt()
		return rgb
	}
}

data class Vehicle(
	val ID: String,
	val Position: Position,
	val Capabilities: UShort,
	val Speed: Float,
	val Line: LineStub,
	val Headsign: String,
	val CongestionLevel: UByte,
	val OccupancyStatus: UByte
) : Locatable {
	enum class Capability(val bit: UShort) {
		RAMP(0b0001u),
		LOW_FLOOR(0b0010u),
		LOW_ENTRY(0b0001_0000_0000u),
		AC(0b0100u),
		BIKE(0b1000u),
		VOICE(0b0001_0000u),
		TICKET_MACHINE(0b0010_0000u),
		TICKET_DRIVER(0b0100_0000u),
		USB_CHARGING(0b1000_0000u)
	}

	override fun id(): String = ID

	override fun icon(context: Context, scale: Float): Drawable {
		return BitmapDrawable(context.resources, Line.icon(context, scale))
	}

	override fun location(): Position = Position

	fun congestion(context: Context): String {
		return when (CongestionLevel.toUInt()) { // todo enum
			0u -> context.getString(R.string.congestion_unknown)
			1u -> context.getString(R.string.congestion_smooth)
			2u -> context.getString(R.string.congestion_stop_and_go)
			3u -> context.getString(R.string.congestion_congestion)
			4u -> context.getString(R.string.congestion_jams)
			else -> TODO("throw invalid congestion")
		}
	}

	fun occupancy(context: Context): String {
		return when (OccupancyStatus.toUInt()) { // todo enum
			0u -> context.getString(R.string.occupancy_unknown)
			1u -> context.getString(R.string.occupancy_empty)
			2u -> context.getString(R.string.occupancy_many_seats)
			3u -> context.getString(R.string.occupancy_few_seats)
			4u -> context.getString(R.string.occupancy_standing_only)
			5u -> context.getString(R.string.occupancy_crowded)
			6u -> context.getString(R.string.occupancy_full)
			7u -> context.getString(R.string.occupancy_wont_let)
			else -> TODO("throw invalid occupancy")
		}
	}

	companion object {
		fun unmarshal(stream: InputStream): Vehicle {
			val reader = Reader(stream)
			return Vehicle(
				reader.readString(),
				Position.unmarshal(stream),
				reader.readU16(),
				reader.readFloat32(),
				LineStub.unmarshal(stream),
				reader.readString(),
				reader.readU8(),
				reader.readU8()
			)
		}
	}

	fun getCapability(field: Capability): Boolean {
		return Capabilities.and(field.bit) != (0).toUShort()
	}
}

data class LineStub(
	val colour: Colour,
	val type: LineType,
	val name: String
) : LineAbstract {
	companion object {
		fun unmarshal(stream: InputStream): LineStub {
			val reader = Reader(stream)
			val colour = Colour.unmarshal(stream)
			val type = reader.readUInt()
			val name = reader.readString()
			return LineStub(name = name, colour = colour, type = LineType.of(type.toUInt()))
		}
	}

	fun icon(context: Context, scale: Float = 1f): Bitmap {
		return super.icon(context, type, colour, scale)
	}
}

data class Departure(
	val ID: String,
	val line: LineStub,
	val headsign: String,
	val time: Time,
	val status: UByte,
	val isRealtime: Boolean,
	val stopOrder: String,
	val vehicle: Vehicle,
	val boarding: UByte
) {

	fun statusText(context: Context?): String {
		val now = Calendar.getInstance()
		val departureTime = Calendar.getInstance().apply {
			set(Calendar.HOUR_OF_DAY, this@Departure.time.Hour.toInt())
			set(Calendar.MINUTE, this@Departure.time.Minute.toInt())
			set(Calendar.SECOND, this@Departure.time.Second.toInt())
			set(
				Calendar.ZONE_OFFSET,
				TimeZone.getTimeZone(this@Departure.time.Zone).getOffset(now.timeInMillis)
			)
			roll(Calendar.DAY_OF_MONTH, this@Departure.time.DayOffset.toInt())
		}
		return when (status.toInt()) {
			0 -> DateUtils.getRelativeTimeSpanString(
				departureTime.timeInMillis,
				now.timeInMillis,
				DateUtils.MINUTE_IN_MILLIS,
				DateUtils.FORMAT_ABBREV_RELATIVE
			)
				.toString()
			1 -> context?.getString(R.string.departure_momentarily) ?: "momentarily"
			2 -> context?.getString(R.string.departure_now) ?: "now"
			3 -> context?.getString(R.string.departure_departed) ?: "departed"
			else -> TODO("throw invalid")
		}
	}

	fun timeString(context: Context): String {
		return if (isRealtime) {
			context.getString(
				R.string.at_time_realtime,
				time.Hour.toInt(),
				time.Minute.toInt(),
				time.Second.toInt()
			)
		} else {
			context.getString(R.string.at_time, time.Hour.toInt(), time.Minute.toInt())
		}
	}

	fun boardingText(context: Context): String {
		// todo [3.x] probably should take into account (on|off)-boarding only, on demand
		return when {
			(boarding.and(0b1010u) != (0b0).toUByte()) -> context.getString(R.string.on_demand)
			(boarding.and(0b0101u) == (0b0101).toUByte()) -> context.getString(R.string.no_boarding)
			(boarding.and(0b0100u) == (0b0100).toUByte()) -> context.getString(R.string.on_boarding)
			(boarding.and(0b0001u) == (0b0001).toUByte()) -> context.getString(R.string.off_boarding)
			else -> context.getString(R.string.boarding)
		}
	}

	companion object {
		fun unmarshal(stream: InputStream): Departure {
			val reader = Reader(stream)
			val id = reader.readString()
			val line = LineStub.unmarshal(stream)
			val headsign = reader.readString()
			val time = Time.unmarshal(stream)
			val status = reader.readU8()
			val isRealtime = reader.readBoolean()
			val stopOrder = reader.readString()
			val vehicle = Vehicle.unmarshal(stream)
			val boarding = reader.readU8()
			return Departure(id, line, headsign, time, status, isRealtime, stopOrder, vehicle, boarding)
		}
	}
}

interface Item
interface Locatable {
	fun icon(context: Context, scale: Float = 1f): Drawable
	fun location(): Position
	fun id(): String
}

data class Stop(
	val code: String,
	val zone: String,
	val position: Position,
	val changeOptions: List<ChangeOption>,
	val name: String
) : Item, Locatable {
	override fun icon(context: Context, scale: Float): Drawable {
		val saturationArray = arrayOf(0.5f, 0.65f, 0.8f)
		val sal = saturationArray.size
		val lightnessArray = arrayOf(.5f)
		val lal = lightnessArray.size
		val md = Adler32().let {
			it.update(name.toByteArray())
			it.value
		}
		val h = md % 359f
		val s = saturationArray[(md / 360 % sal).toInt()]
		val l = lightnessArray[(md / 360 / sal % lal).toInt()]
		val fg = AppCompatResources.getDrawable(context, R.drawable.stop)
		val bg =
			AppCompatResources.getDrawable(context, R.drawable.stop_bg)!!.mutate()
				.apply {
					setTint(HSLToColor(arrayOf(h, s, l).toFloatArray()))
				}
		return BitmapDrawable(
			context.resources,
			LayerDrawable(arrayOf(bg, fg)).mutate()
				.toBitmap(dpToPixelI(24f / scale), dpToPixelI(24f / scale), Bitmap.Config.ARGB_8888)
		)
	}

	override fun id(): String = code

	override fun location(): Position = position

	override fun toString(): String {
		var result = "$name ($code) [$zone] $position\n"
		for (chOpt in changeOptions)
			result += "${chOpt.line}${chOpt.headsign}\n"
		return result
	}

	fun changeOptions(context: Context): Pair<String,String> {
		return Pair(changeOptions.groupBy { it.line }
			.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }
			.joinToString {
				context.getString(
					R.string.vehicle_headsign,
					it.first,
					it.second
				)
			},
			changeOptions.groupBy { it.line }
				.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }
				.joinToString {
					context.getString(
						R.string.vehicle_headsign_content_description,
						it.first,
						it.second
					)
				})
	}

	companion object {
		fun unmarshal(stream: InputStream): Stop {
			val reader = Reader(stream)
			val code = reader.readString()
			val zone = reader.readString()
			val position = Position.unmarshal(stream)
			val chOptionsNum = reader.readUInt()
			val changeOptions = mutableListOf<ChangeOption>()
			for (i in 0UL until chOptionsNum) {
				changeOptions.add(ChangeOption.unmarshal(stream))
			}
			val name = reader.readString()
			return Stop(
				name = name,
				code = code,
				zone = zone,
				position = position,
				changeOptions = changeOptions
			)
		}
	}
}

interface LineAbstract {
	fun textColour(c: Colour): Int {
		val black = relativeLuminance(Colour(0u, 0u, 0u)) + .05
		val white = relativeLuminance(Colour(255u, 255u, 255u)) + .05
		val colour = relativeLuminance(c) + .05
		return if ((white / colour) > (colour / black)) {
			Color.WHITE
		} else {
			Color.BLACK
		}
	}

	private fun relativeLuminance(colour: Colour): Double {
		val r = fromSRGB(colour.R.toDouble() / 0xff)
		val g = fromSRGB(colour.G.toDouble() / 0xff)
		val b = fromSRGB(colour.B.toDouble() / 0xff)
		return 0.2126 * r + 0.7152 * g + 0.0722 * b
	}

	private fun fromSRGB(part: Double): Double {
		return if (part <= 0.03928) {
			part / 12.92
		} else {
			((part + 0.055) / 1.055).pow(2.4)
		}
	}

	fun icon(context: Context, type: LineType, colour: Colour, scale: Float): Bitmap {
		val drawingBitmap = Bitmap.createBitmap(
			dpToPixelI(24f / scale),
			dpToPixelI(24f / scale),
			Bitmap.Config.ARGB_8888
		)
		val canvas = Canvas(drawingBitmap)

		canvas.drawPath(
			getSquirclePath(
				dpToPixel(.8f / scale),
				dpToPixel(.8f / scale),
				dpToPixelI(11.2f / scale)
			), Paint().apply { color = textColour(colour) })
		canvas.drawPath(
			getSquirclePath(
				dpToPixel(1.6f / scale),
				dpToPixel(1.6f / scale),
				dpToPixelI(10.4f / scale)
			), Paint().apply { color = colour.toInt() })

		val iconID = when (type) {
			LineType.BUS -> R.drawable.bus_black
			LineType.TRAM -> R.drawable.tram_black
			LineType.UNKNOWN -> R.drawable.vehicle_black
		}
		val icon =
			AppCompatResources.getDrawable(context, iconID)?.mutate()
				?.apply {
					setTint(textColour(colour))
				}?.toBitmap(dpToPixelI(19.2f / scale), dpToPixelI(19.2f / scale), Bitmap.Config.ARGB_8888)
		canvas.drawBitmap(
			icon!!,
			dpToPixel(2.4f / scale),
			dpToPixel(2.4f / scale),
			Paint()
		)
		return drawingBitmap
	}

	private fun getSquirclePath(
		left: Float,
		top: Float,
		radius: Int
	): Path {
		val radiusToPow = (radius * radius * radius).toDouble()
		val path = Path()
		path.moveTo(-radius.toFloat(), 0f)
		for (x in -radius..radius) path.lineTo(
			x.toFloat(),
			Math.cbrt(radiusToPow - abs(x * x * x)).toFloat()
		)
		for (x in radius downTo -radius) path.lineTo(
			x.toFloat(),
			-Math.cbrt(radiusToPow - abs(x * x * x)).toFloat()
		)
		path.close()
		val matrix = Matrix()
		matrix.postTranslate((left + radius), (top + radius))
		path.transform(matrix)
		return path
	}
}

data class Line(
	val colour: Colour,
	val type: LineType,
	val headsignsThere: List<String>,
	val headsignsBack: List<String>,
	val graphThere: LineGraph,
	val graphBack: LineGraph,
	val name: String
) : Item, LineAbstract {
	override fun toString(): String {
		return "$name ($type) [$colour]\n→ [${headsignsThere.joinToString()}]\n→ [${headsignsBack.joinToString()}]\n"
	}

	fun icon(context: Context, scale: Float = 1f): Bitmap {
		return super.icon(context, type, colour, scale)
	}

	companion object {
		fun unmarshal(stream: InputStream): Line {
			val reader = Reader(stream)
			val colour = Colour.unmarshal(stream)
			val type = reader.readUInt()
			val headsignsThereNum = reader.readUInt()
			val headsignsThere = mutableListOf<String>()
			for (i in 0UL until headsignsThereNum) {
				headsignsThere.add(reader.readString())
			}
			val headsignsBackNum = reader.readUInt()
			val headsignsBack = mutableListOf<String>()
			for (i in 0UL until headsignsBackNum) {
				headsignsBack.add(reader.readString())
			}
			val graphThere = LineGraph.unmarshal(stream)
			val graphBack = LineGraph.unmarshal(stream)
			val name = reader.readString()
			return Line(
				name = name, colour = colour, type = LineType.of(type.toUInt()),
				headsignsThere = headsignsThere, headsignsBack = headsignsBack, graphThere = graphThere,
				graphBack = graphBack
			)
		}
	}
}

enum class LineType {
	TRAM, BUS, UNKNOWN;

	companion object {
		fun of(type: UInt): LineType {
			return when (type) {
				0U -> valueOf("TRAM")
				3U -> valueOf("BUS")
				else -> valueOf("UNKNOWN")
			}
		}
	}
}

data class ChangeOption(val line: String, val headsign: String) {
	companion object {
		fun unmarshal(stream: InputStream): ChangeOption {
			val reader = Reader(stream)
			return ChangeOption(line = reader.readString(), headsign = reader.readString())
		}
	}
}

data class LineGraph(
	val stops: List<StopStub>,
	val nextNodes: Map<Long, List<Long>>,
	val prevNodes: Map<Long, List<Long>>
) {
	companion object {
		fun unmarshal(stream: InputStream): LineGraph {
			val reader = Reader(stream)
			val stopsNum = reader.readUInt()
			val stops = mutableListOf<StopStub>()
			for (i in 0UL until stopsNum) {
				stops.add(StopStub.unmarshal(stream))
			}
			val nextNodesNum = reader.readUInt()
			val nextNodes = mutableMapOf<Long, List<Long>>()
			for (i in 0UL until nextNodesNum) {
				val from = reader.readInt()
				val toNum = reader.readUInt()
				val to = mutableListOf<Long>()
				for (j in 0UL until toNum) {
					to.add(reader.readInt())
				}
				nextNodes[from] = to
			}
			val prevNodesNum = reader.readUInt()
			val prevNodes = mutableMapOf<Long, List<Long>>()
			for (i in 0UL until prevNodesNum) {
				val from = reader.readInt()
				val toNum = reader.readUInt()
				val to = mutableListOf<Long>()
				for (j in 0UL until toNum) {
					to.add(reader.readInt())
				}
				prevNodes[from] = to
			}

			return LineGraph(stops = stops, nextNodes = nextNodes, prevNodes = prevNodes)
		}
	}
}

data class StopStub(val name: String, val code: String, val zone: String, val onDemand: Boolean) {
	companion object {
		fun unmarshal(stream: InputStream): StopStub {
			val reader = Reader(stream)
			return StopStub(
				code = reader.readString(),
				name = reader.readString(),
				zone = reader.readString(),
				onDemand = reader.readBoolean()
			)
		}
	}
}