diff --git a/app/build.gradle b/app/build.gradle index 045f25f..79abbd8 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -24,6 +24,7 @@ dependencies { implementation(libs.kotlin.stdlib) testImplementation(libs.junit) + testImplementation(libs.androidx.car.app.testing) androidTestImplementation(libs.androidx.test.junit) androidTestImplementation(libs.androidx.test.runner) @@ -31,6 +32,7 @@ dependencies { androidTestImplementation(libs.espresso.core) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.car.app.testing) debugImplementation(platform(libs.androidx.compose.bom)) debugImplementation(libs.androidx.compose.ui.test.manifest) @@ -54,6 +56,7 @@ dependencies { implementation(libs.androidx.compose.foundation) implementation(libs.androidx.compose.material3) implementation(libs.androidx.compose.material.icons) + implementation(libs.androidx.car.app) implementation('com.google.android.gms:play-services-oss-licenses:17.5.1') } diff --git a/app/src/androidTest/kotlin/in/izyum/bart/presentation/DepartureTextFormatterTest.kt b/app/src/androidTest/kotlin/in/izyum/bart/presentation/DepartureTextFormatterTest.kt new file mode 100644 index 0000000..2b93c2d --- /dev/null +++ b/app/src/androidTest/kotlin/in/izyum/bart/presentation/DepartureTextFormatterTest.kt @@ -0,0 +1,72 @@ +package `in`.izyum.bart.presentation + +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import `in`.izyum.bart.model.Departure +import `in`.izyum.bart.model.Line +import `in`.izyum.bart.model.Station +import `in`.izyum.bart.model.TripLeg +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class DepartureTextFormatterTest { + + @Test + fun countdownFormatsMinutesAndSecondsUnderOneHour() { + val context = ApplicationProvider.getApplicationContext() + val now = 1_000_000L + val minEstimate = now + (15 * 60 + 30) * 1000L + val maxEstimate = minEstimate + + val departure = createDeparture(minEstimate, maxEstimate) + val result = DepartureTextFormatter.countdown(context, departure, now) + + assertEquals("15m 30s", result) + } + + @Test + fun countdownFormatsHoursMinutesAndSecondsOverOneHour() { + val context = ApplicationProvider.getApplicationContext() + val now = 1_000_000L + // 1 hour 52 minutes 0 seconds = 6720 seconds = 6,720,000 ms + val minEstimate = now + (1 * 3600 + 52 * 60 + 0) * 1000L + val maxEstimate = minEstimate + + val departure = createDeparture(minEstimate, maxEstimate) + val result = DepartureTextFormatter.countdown(context, departure, now) + + assertEquals("1h 52m 0s", result) + } + + @Test + fun countdownFormatsExactlyOneHour() { + val context = ApplicationProvider.getApplicationContext() + val now = 1_000_000L + // 1 hour = 3600 seconds = 3,600,000 ms + val minEstimate = now + 3600 * 1000L + val maxEstimate = minEstimate + + val departure = createDeparture(minEstimate, maxEstimate) + val result = DepartureTextFormatter.countdown(context, departure, now) + + assertEquals("1h 0m 0s", result) + } + + private fun createDeparture(minEstimate: Long, maxEstimate: Long): Departure = + Departure.builder() + .setOrigin(Station.CAST) + .setTrainDestination(Station.MLPT) + .setPassengerDestination(Station.MLPT) + .setLine(Line.ORANGE) + .setDirection("north") + .setPlatform("1") + .setListedInETDs(true) + .setMinEstimate(minEstimate) + .setMaxEstimate(maxEstimate) + .setTripLegs(listOf(TripLeg( + Line.ORANGE, Station.CAST, Station.MLPT, Station.MLPT, + "trip-1", minEstimate, maxEstimate, emptyList(), + ))).build() +} diff --git a/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt b/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt index 9b3d225..26324b5 100644 --- a/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt +++ b/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt @@ -280,6 +280,89 @@ class BartRunnerUiTest { composeRule.onNodeWithText("Set departure alarm").assertIsDisplayed() } + @Test + fun followedTripCardOnHomeScreenOpensFullScreenView() { + val departure = testDeparture() + setTestContent { + BartRunnerTheme { + HomeScreen( + state = RoutesUiState(isLoading = false), + followedTrip = departure, + timeSource = timeSource, + onRouteSelected = {}, + onAddFavorite = {}, + onRemoveFavorite = {}, + onMoveFavorite = { _, _ -> }, + onInsertFavorite = { _, _ -> }, + onViewTrip = {}, + onViewMap = {}, + ) + } + } + + composeRule.onNodeWithContentDescription("Full screen").assertIsDisplayed() + composeRule.onNodeWithContentDescription("Full screen").performClick() + composeRule.onNodeWithContentDescription("Exit full screen").assertIsDisplayed() + composeRule.onNodeWithContentDescription("Keep screen active").assertIsDisplayed() + composeRule.onAllNodesWithText("Castro Valley → Milpitas").onFirst().assertIsDisplayed() + } + + @Test + fun homeScreenSettingsIncludesHomeStationOption() { + setTestContent { + BartRunnerTheme { + HomeScreen( + state = RoutesUiState(isLoading = false), + followedTrip = null, + timeSource = timeSource, + onRouteSelected = {}, + onAddFavorite = {}, + onRemoveFavorite = {}, + onMoveFavorite = { _, _ -> }, + onInsertFavorite = { _, _ -> }, + onViewTrip = {}, + onViewMap = {}, + ) + } + } + + composeRule.onNodeWithContentDescription("More options").performClick() + composeRule.onNodeWithText("Settings").performClick() + composeRule.onNodeWithText("Home station").assertIsDisplayed() + composeRule.onNodeWithText("Keep screen active").assertIsDisplayed() + } + + @Test + fun tripScreenHeroShowsFullScreenButtonWhenFollowing() { + val departure = testDeparture() + setTestContent { + BartRunnerTheme { + TripScreen( + departure = departure, + route = `in`.izyum.bart.model.StationPair(Station.CAST, Station.MLPT), + isFollowingInitially = true, + alarmVisible = false, + timeSource = timeSource, + alarmPending = false, + alarmLeadTimeMinutes = 0, + onBack = {}, + onFollow = {}, + onSetAlarm = {}, + onCancelAlarm = {}, + onClear = {}, + onShare = {}, + onSilenceAlarm = {}, + ) + } + } + + composeRule.onNodeWithContentDescription("Full screen").assertIsDisplayed() + composeRule.onNodeWithContentDescription("Full screen").performClick() + composeRule.onNodeWithContentDescription("Exit full screen").assertIsDisplayed() + composeRule.onNodeWithContentDescription("Exit full screen").performClick() + composeRule.onNodeWithContentDescription("Exit full screen").assertDoesNotExist() + } + @Test fun systemMapExposesZoomControls() { setTestContent { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 43dde24..144306b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -10,6 +10,14 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt b/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt index 25aabf8..4d155a2 100644 --- a/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt +++ b/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt @@ -60,13 +60,13 @@ class BartRunnerApplication : Application() { override fun onActivityStarted(activity: Activity) { startedActivityCount++ - transitRepository.setAppInForeground(true) + transitRepository.setAppInForeground(inForeground = true) } override fun onActivityStopped(activity: Activity) { startedActivityCount = (startedActivityCount - 1).coerceAtLeast(0) if (startedActivityCount == 0) { - transitRepository.setAppInForeground(false) + transitRepository.setAppInForeground(inForeground = false) } } diff --git a/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt index 5801bc8..6a5b9d4 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt @@ -1,11 +1,11 @@ package `in`.izyum.bart.activities import android.content.Intent -import android.net.Uri import android.os.Bundle import android.os.Build import androidx.activity.ComponentActivity import androidx.activity.compose.setContent +import androidx.core.net.toUri import `in`.izyum.bart.BuildConfig import `in`.izyum.bart.R import `in`.izyum.bart.ui.AboutScreen @@ -25,16 +25,16 @@ class AboutActivity : ComponentActivity() { startActivity( Intent( Intent.ACTION_VIEW, - Uri.parse(getString(R.string.github_url)), - ) + getString(R.string.github_url).toUri(), + ), ) }, onOpenApacheLicense = { startActivity( Intent( Intent.ACTION_VIEW, - Uri.parse(getString(R.string.apache_license_url)), - ) + getString(R.string.apache_license_url).toUri(), + ), ) }, onOpenLicenses = { diff --git a/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt index 17b4fdd..3b9f7c9 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt @@ -36,23 +36,40 @@ class DeparturesViewModel @JvmOverloads constructor( val status: Status, val departures: List, val error: Exception?, + val showTransfers: Boolean = true, ) { companion object { - fun loading() = State(Status.LOADING, emptyList(), null) - fun content(departures: List) = - State(Status.CONTENT, departures, null) - fun empty() = State(Status.EMPTY, emptyList(), null) - fun error(exception: Exception, departures: List) = - State(Status.ERROR, departures, exception) + fun loading(showTransfers: Boolean = true) = + State(Status.LOADING, emptyList(), null, showTransfers) + fun content(departures: List, showTransfers: Boolean = true) = + State(Status.CONTENT, departures, null, showTransfers) + fun empty(showTransfers: Boolean = true) = + State(Status.EMPTY, emptyList(), null, showTransfers) + fun error(exception: Exception, departures: List, showTransfers: Boolean = true) = + State(Status.ERROR, departures, exception, showTransfers) } } - private val _uiState = MutableStateFlow(State.loading()) + private var showTransfers: Boolean = true + private var departures: List = emptyList() + + private val _uiState = MutableStateFlow(State.loading(showTransfers)) val uiState: StateFlow = _uiState.asStateFlow() - private var departures: List = emptyList() private var collectionJob: Job? = null + fun toggleShowTransfers() { + setShowTransfers(!showTransfers) + } + + @Synchronized + fun setShowTransfers(show: Boolean) { + if (showTransfers != show) { + showTransfers = show + updateState() + } + } + /** Configures the query; the ViewModel owns collection until it is cleared. */ fun setQuery( repository: TransitRepository, @@ -63,7 +80,7 @@ class DeparturesViewModel @JvmOverloads constructor( collectionJob?.cancel() collectionJob = null departures = emptyList() - _uiState.value = State.loading() + _uiState.value = State.loading(showTransfers) if (stationPair == null) { return } @@ -98,25 +115,27 @@ class DeparturesViewModel @JvmOverloads constructor( @Synchronized fun replace(incoming: List): List { departures = immutableCopy(Departure.replaceFeed(departures, incoming, timeSource)) - _uiState.value = if (departures.isEmpty()) { - State.empty() - } else { - State.content(departures) - } - return departures + updateState() + return getDepartures() } @Synchronized fun clear(): List { departures = emptyList() - _uiState.value = State.empty() - return departures + updateState() + return emptyList() } fun getState(): State = uiState.value @Synchronized - fun getDepartures(): List = departures + fun getDepartures(): List { + return if (showTransfers) { + departures + } else { + departures.filter { !it.requiresTransfer && !it.hasTransfers() } + } + } @Synchronized private fun updateFromFeed(incoming: List) { @@ -125,12 +144,33 @@ class DeparturesViewModel @JvmOverloads constructor( @Synchronized private fun updateError(exception: Exception) { - _uiState.value = State.error(exception, departures) + val visible = getDepartures() + _uiState.value = State.error(exception, visible, showTransfers) + } + + @Synchronized + private fun updateState() { + val visible = getDepartures() + val currentStatus = _uiState.value.status + _uiState.value = when { + (currentStatus == Status.LOADING) && departures.isEmpty() -> { + State.loading(showTransfers) + } + currentStatus == Status.ERROR -> { + State.error(_uiState.value.error ?: RuntimeException(), visible, showTransfers) + } + visible.isEmpty() -> { + State.empty(showTransfers) + } + else -> { + State.content(visible, showTransfers) + } + } } private fun immutableCopy(values: List): List = Collections.unmodifiableList(ArrayList(values)) private fun asException(error: Throwable): Exception = - error as? Exception ?: RuntimeException(error) + (error as? Exception) ?: RuntimeException(error) } diff --git a/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt index 8da3695..60acf92 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt @@ -31,6 +31,10 @@ import `in`.izyum.bart.BartRunnerApplication import `in`.izyum.bart.R import `in`.izyum.bart.performance.PerformanceTrace import `in`.izyum.bart.data.BackgroundPollingPreferences +import `in`.izyum.bart.data.HomeStationPreferences +import `in`.izyum.bart.data.KeepScreenOnPreferences +import `in`.izyum.bart.data.TransferPreferences +import `in`.izyum.bart.model.Station import `in`.izyum.bart.platform.DeparturePollingWork import `in`.izyum.bart.networktasks.RiderCategory import `in`.izyum.bart.ui.BartRunnerTheme @@ -41,10 +45,13 @@ import kotlinx.coroutines.withContext class RoutesListActivity : ComponentActivity() { private val routesViewModel: RoutesViewModel by viewModels() - private var staticDataReady by mutableStateOf(false) + private var staticDataReady by mutableStateOf(value = false) private var riderCategories by mutableStateOf>(emptyList()) private var riderCategoryId by mutableStateOf(null) - private var backgroundPollingEnabled by mutableStateOf(true) + private var backgroundPollingEnabled by mutableStateOf(value = true) + private var defaultTransferViewEnabled by mutableStateOf(value = true) + private var homeStation by mutableStateOf(null) + private var keepScreenOnEnabled by mutableStateOf(value = false) fun addFavorite(route: `in`.izyum.bart.model.StationPair) { routesViewModel.addFavorite(route) @@ -56,6 +63,9 @@ class RoutesListActivity : ComponentActivity() { riderCategoryId = `in`.izyum.bart.data.FareDiscountPreferences .getRiderCategoryId(this) backgroundPollingEnabled = BackgroundPollingPreferences.isEnabled(this) + defaultTransferViewEnabled = TransferPreferences.getDefaultShowTransfers(this) + homeStation = HomeStationPreferences.getHomeStation(this) + keepScreenOnEnabled = KeepScreenOnPreferences.isKeepScreenOn(this) val needsInitialStaticLoad = !application.gtfsStaticData.hasDatabaseCache() staticDataReady = !needsInitialStaticLoad lifecycleScope.launch(Dispatchers.IO) { @@ -69,7 +79,7 @@ class RoutesListActivity : ComponentActivity() { }.getOrDefault(emptyList()) withContext(Dispatchers.Main.immediate) { riderCategories = categories - if (riderCategoryId != null && categories.none { it.id == riderCategoryId }) { + if ((riderCategoryId != null) && categories.none { it.id == riderCategoryId }) { riderCategoryId = null routesViewModel.setRiderCategoryId(null) } @@ -146,6 +156,21 @@ class RoutesListActivity : ComponentActivity() { BackgroundPollingPreferences.setEnabled(this, enabled) DeparturePollingWork.refresh(this, application.followedTripRepository) }, + defaultTransferViewEnabled = defaultTransferViewEnabled, + onDefaultTransferViewChanged = { enabled -> + defaultTransferViewEnabled = enabled + TransferPreferences.setDefaultShowTransfers(this, enabled) + }, + homeStation = homeStation, + onHomeStationChanged = { station -> + homeStation = station + HomeStationPreferences.setHomeStation(this, station) + }, + keepScreenActive = keepScreenOnEnabled, + onKeepScreenActiveChanged = { enabled -> + keepScreenOnEnabled = enabled + KeepScreenOnPreferences.setKeepScreenOn(this, enabled) + }, ) } } diff --git a/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt index 290fe59..3bed342 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt @@ -141,7 +141,7 @@ class RoutesViewModel(application: Application) : AndroidViewModel(application) private fun syncRouteJobs(favorites: List) { PerformanceTrace.counter("BART favorite count", favorites.size) val desired = favorites.toSet() - routeJobs.keys.toList() + routeJobs.keys.asSequence() .filter { it !in desired } .forEach { route -> routeJobs.remove(route)?.cancel() @@ -250,5 +250,5 @@ class RoutesViewModel(application: Application) : AndroidViewModel(application) Collections.unmodifiableMap(HashMap(values)) private fun asException(error: Throwable): Exception = - error as? Exception ?: RuntimeException(error) + (error as? Exception) ?: RuntimeException(error) } diff --git a/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt index a79685f..e8a606f 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt @@ -12,7 +12,6 @@ import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.annotation.RequiresApi import androidx.core.app.NotificationManagerCompat -import androidx.core.content.edit import androidx.core.net.toUri import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue @@ -42,7 +41,7 @@ class TripInProgressActivity : ComponentActivity() { private const val POST_NOTIFICATIONS_REQUEST_CODE = 1002 internal fun shouldReturnToRoutes(screenMode: String?, followed: Departure?): Boolean = - screenMode == RouteArguments.MODE_FOLLOWED && followed == null + (screenMode == RouteArguments.MODE_FOLLOWED) && (followed == null) } private val tripProgressViewModel: TripProgressViewModel by viewModels() @@ -54,13 +53,13 @@ class TripInProgressActivity : ComponentActivity() { private var fareEligible = false private var fareLookupKey: String? = null private var pendingAlarmLeadTimeMinutes: Int? = null - private var alarmVisible by mutableStateOf(false) + private var alarmVisible by mutableStateOf(value = false) override fun onResume() { super.onResume() tripActionsViewModel.refreshAlarmState() val pendingLeadTime = pendingAlarmLeadTimeMinutes - if (pendingLeadTime != null && hasExactAlarmPermission()) { + if ((pendingLeadTime != null) && hasExactAlarmPermission()) { pendingAlarmLeadTimeMinutes = null enableAlarm(pendingLeadTime) } @@ -92,7 +91,7 @@ class TripInProgressActivity : ComponentActivity() { finish() return } - if (route == null && followed != null && (screenMode == null || screenMode == RouteArguments.MODE_FOLLOWED)) { + if ((route == null) && (followed != null) && ((screenMode == null) || (screenMode == RouteArguments.MODE_FOLLOWED))) { identity = followed.identity route = followed.getStationPair() } @@ -287,7 +286,7 @@ class TripInProgressActivity : ComponentActivity() { val message = getString( R.string.arrival_message, destination.getName(), - DepartureTextFormatter.estimatedArrivalTime(this, departure, false), + DepartureTextFormatter.estimatedArrivalTime(this, departure, compact = false), ) startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "text/plain" @@ -305,7 +304,7 @@ class TripInProgressActivity : ComponentActivity() { } private fun requestNotificationPermissionIfNeeded() { - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU && + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED ) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), POST_NOTIFICATIONS_REQUEST_CODE) diff --git a/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt index dd21d77..97e220c 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt @@ -69,14 +69,14 @@ class TripProgressViewModel(application: Application) : } ?: incoming val current = departureState.value val updated = current?.let { - Departure.merge(it, normalizedIncoming, true, timeSource) + Departure.merge(it, normalizedIncoming, updateTripLegs = true, timeSource = timeSource) } ?: normalizedIncoming publish(updated) startTripProgress(updated) } private fun startTripProgress(departure: Departure) { - if (tripProgressCollectionJob?.isActive == true + if ((tripProgressCollectionJob?.isActive == true) || departure.tripLegs.isEmpty() ) { return diff --git a/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt index ba71b40..5100caa 100644 --- a/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt +++ b/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt @@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue import androidx.lifecycle.lifecycleScope import `in`.izyum.bart.BartRunnerApplication import `in`.izyum.bart.data.FareDiscountPreferences +import `in`.izyum.bart.data.TransferPreferences import `in`.izyum.bart.model.Departure import `in`.izyum.bart.model.StationPair import `in`.izyum.bart.ui.BartRunnerTheme @@ -46,6 +47,8 @@ class ViewDeparturesActivity : ComponentActivity() { } } } + val initialShowTransfers = TransferPreferences.getShowTransfersForRoute(this, stationPair) + departuresViewModel.setShowTransfers(initialShowTransfers) departuresViewModel.setQuery( app.transitRepository, app.bartGtfsNetworkSupplier, @@ -65,6 +68,14 @@ class ViewDeparturesActivity : ComponentActivity() { onBack = { finish() }, onOpenTrip = ::openTripSchedule, onMap = { startActivity(Intent(this, ViewMapActivity::class.java)) }, + onToggleShowTransfers = { + departuresViewModel.toggleShowTransfers() + TransferPreferences.setShowTransfersForRoute( + this@ViewDeparturesActivity, + stationPair, + departuresViewModel.uiState.value.showTransfers, + ) + }, ) } } diff --git a/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt index 82aeabf..b03f982 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt @@ -50,9 +50,9 @@ class AlertProjection { if (previous === current) { return true } - if (previous == null || current == null - || previous.areNoDelaysReported() != current.areNoDelaysReported() - || previous.getAlerts().size != current.getAlerts().size + if ((previous == null) || (current == null) + || (previous.areNoDelaysReported() != current.areNoDelaysReported()) + || (previous.getAlerts().size != current.getAlerts().size) ) { return false } diff --git a/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt b/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt index 35aa722..3ea43fb 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt @@ -41,16 +41,17 @@ object EtdCorroborator { val feedIds = snapshot.getTripUpdateIndex().tripUpdatesById.keys val feedTime = snapshot.getTripUpdatesTimestampMillis() return departures + .asSequence() .flatMap { it.tripLegs } .filter { leg -> val tripId = leg.tripId - tripId != null - && tripId !in feedIds - && leg.origin != null - && leg.scheduledDepartureTime in - feedTime..(feedTime + SUSPICIOUS_WINDOW_MILLIS) + (tripId != null) + && (tripId !in feedIds) + && (leg.origin != null) + && (leg.scheduledDepartureTime in feedTime..(feedTime + SUSPICIOUS_WINDOW_MILLIS)) } .distinctBy(::key) + .toList() } fun applyBoards( diff --git a/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt index 1690c7e..331095f 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt @@ -8,7 +8,6 @@ import `in`.izyum.bart.networktasks.GtfsRealtimeContentHandler import `in`.izyum.bart.networktasks.GtfsRealtimeFeedIndex import `in`.izyum.bart.performance.PerformanceTrace import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork -import com.google.transit.realtime.GtfsRealtime import java.util.function.Supplier /** Builds departures for one route from the already-downloaded feed. */ @@ -82,7 +81,7 @@ class RouteDepartureProjection private constructor( routes, network, feedIndex, feedTime, schedule, excludedTripIds ) - if (result.getDepartures().isEmpty() && query.destination != null) { + if (result.getDepartures().isEmpty() && (query.destination != null)) { val lateNightRoutes = if (schedule.isLateNightSfoMillbraeService()) { schedule.lateNightSfoMillbraeRoutes( query.origin, diff --git a/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt b/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt index dd69899..a274c63 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt @@ -49,7 +49,7 @@ class Schedule private constructor( fun departureDelaySeconds(): Int? = delaySeconds(departureTime, scheduledDepartureTime) private fun delaySeconds(actual: Long, scheduled: Long): Int? = - if (actual > 0L && scheduled > 0L) { + if ((actual > 0L) && (scheduled > 0L)) { ((actual - scheduled) / 1000L).toInt() } else { null @@ -469,7 +469,7 @@ class Schedule private constructor( ) return route return Route.transfer( route.origin!!, - destination!!, + destination, route.lines + Line.YELLOW_DMU, route.transferStations + Station.PITT, route.direction, @@ -518,7 +518,7 @@ class Schedule private constructor( // The DMU is a terminal continuation, not a normal transfer line. // Its topology is added explicitly after a Yellow route reaches // Pittsburg. - val lines = Line.values().filter { + val lines = Line.entries.filter { it != Line.YELLOW_DMU && network.routePatternsForLine(it).isNotEmpty() } for (first in lines) { @@ -728,7 +728,7 @@ class Schedule private constructor( fun fromStatic( network: BartGtfsNetwork, feedTime: Long, - lines: Set = Line.values().toSet(), + lines: Set = Line.entries.toSet(), ): Schedule { if (feedTime <= 0L) { return create(emptyList(), emptyMap(), network::stationForStopId, network, feedTime) diff --git a/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt b/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt index be9e991..2a68b23 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt @@ -59,7 +59,7 @@ class TransitFeedSnapshot( return correctedSchedules[network] ?: Schedule.fromStatic( network, getTripUpdatesTimestampMillis(), - Line.values().toSet(), + Line.entries.toSet(), ).applyRealtime(getTripUpdateIndex()).also { correctedSchedules[network] = it } diff --git a/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt b/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt index a53c47a..4af7489 100644 --- a/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt +++ b/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt @@ -40,14 +40,14 @@ data class TransitFeedState( class TransitRepository( private val feedClient: TransitFeedClient, private val refreshIntervalMillis: Long, - private val backgroundPollingNeeded: StateFlow = MutableStateFlow(false), + private val backgroundPollingNeeded: StateFlow = MutableStateFlow(value = false), private val offlineSnapshotProvider: (() -> TransitFeedSnapshot)? = null, private val backgroundPollingIntervalMillis: StateFlow = MutableStateFlow(refreshIntervalMillis), ) : AutoCloseable { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val lock = Any() - private val appInForeground = MutableStateFlow(false) + private val appInForeground = MutableStateFlow(value = false) private val _state = MutableStateFlow(TransitFeedState()) private val feedUpdates = MutableSharedFlow( replay = 1, @@ -81,7 +81,7 @@ class TransitRepository( } .distinctUntilChanged() .collectLatest { pollingIntervalMillis -> - while (isActive && pollingIntervalMillis != null) { + while (isActive && (pollingIntervalMillis != null)) { refreshIfStaleCancellable() delay(pollingIntervalMillis) } @@ -131,7 +131,7 @@ class TransitRepository( .mapLatest { feedState -> if (feedState.snapshot == null) { feedState.error?.let { - return@mapLatest Result.failure(it) + return@mapLatest Result.failure(it) } return@mapLatest Result.failure( IllegalStateException("Transit feed is unavailable"), diff --git a/app/src/main/kotlin/in/izyum/bart/car/ActiveDepartureScreen.kt b/app/src/main/kotlin/in/izyum/bart/car/ActiveDepartureScreen.kt new file mode 100644 index 0000000..764ce19 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/ActiveDepartureScreen.kt @@ -0,0 +1,265 @@ +package `in`.izyum.bart.car + +import android.os.Handler +import android.os.Looper +import androidx.car.app.CarContext +import androidx.car.app.Screen +import androidx.car.app.model.Action +import androidx.car.app.model.Header +import androidx.car.app.model.Pane +import androidx.car.app.model.PaneTemplate +import androidx.car.app.model.Row +import androidx.car.app.model.Template +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import `in`.izyum.bart.BartRunnerApplication +import `in`.izyum.bart.backend.RouteDepartureProjection +import `in`.izyum.bart.model.Departure +import `in`.izyum.bart.model.StationPair + +/** + * Screen rendering live train departure countdowns in Android Auto. + * Uses PaneTemplate to fit cleanly into split-screen (Coolwalk) dashboard layouts + * alongside media players. + * + * Updates via invalidate() on a 30-second ticker to adhere to Car App Quality Guidelines + * and avoid driver distraction lockouts. + */ +class ActiveDepartureScreen( + carContext: CarContext, + private val stationPair: StationPair, +) : Screen(carContext), DefaultLifecycleObserver { + + private val mainHandler = Handler(Looper.getMainLooper()) + private val notifiedMilestones = mutableSetOf() + + private var _audioGuidanceManager: AudioGuidanceManager? = null + private fun getAudioGuidanceManager(): AudioGuidanceManager { + if (_audioGuidanceManager == null) { + _audioGuidanceManager = AudioGuidanceManager(carContext) + } + return _audioGuidanceManager!! + } + + private val tickerRunnable = object : Runnable { + override fun run() { + runCatching { invalidate() } + mainHandler.postDelayed(this, TICKER_INTERVAL_MILLIS) + } + } + + init { + lifecycle.addObserver(this) + } + + override fun onResume(owner: LifecycleOwner) { + val app = carContext.applicationContext as? BartRunnerApplication + if (app != null && app.transitRepository.getLatestSnapshot() == null) { + runCatching { app.transitRepository.refreshNow() } + } + mainHandler.removeCallbacks(tickerRunnable) + mainHandler.postDelayed(tickerRunnable, TICKER_INTERVAL_MILLIS) + } + + override fun onPause(owner: LifecycleOwner) { + mainHandler.removeCallbacks(tickerRunnable) + } + + override fun onDestroy(owner: LifecycleOwner) { + mainHandler.removeCallbacks(tickerRunnable) + _audioGuidanceManager?.shutdown() + _audioGuidanceManager = null + } + + override fun onGetTemplate(): Template { + return runCatching { buildTemplate() }.getOrElse { buildFallbackTemplate() } + } + + private fun buildTemplate(): Template { + val app = carContext.applicationContext as? BartRunnerApplication + ?: return buildFallbackTemplate() + + if (stationPair.origin == null) { + return buildErrorTemplate("Invalid Route", "Selected route has no origin station.") + } + + var snapshot = app.transitRepository.getLatestSnapshot() + if (snapshot == null) { + runCatching { app.transitRepository.refreshNow() } + snapshot = app.transitRepository.getLatestSnapshot() + } + + val showTransfers = CarPreferences.getShowTransfersForRoute(carContext, stationPair) + val isAudioGuidanceEnabled = CarPreferences.getDefaultAudioGuidance(carContext) + + val allDepartures = if (snapshot != null) { + runCatching { + val projection = RouteDepartureProjection(stationPair, app.bartGtfsNetworkSupplier) + projection.project(snapshot).getDepartures() + }.getOrDefault(emptyList()) + } else { + emptyList() + } + + val departures = if (showTransfers) { + allDepartures + } else { + allDepartures.filter { !it.requiresTransfer && !it.hasTransfers() } + } + + val paneBuilder = Pane.Builder() + + if (departures.isEmpty()) { + val emptyMessage = if (allDepartures.isNotEmpty()) { + "No direct trains found. Toggle 'Include Transfers' to see connecting routes." + } else { + "Connecting to BART realtime feeds..." + } + paneBuilder.addRow( + Row.Builder() + .setTitle("No Matching Departures") + .addText(emptyMessage) + .build(), + ) + } else { + val primaryDeparture = departures.first() + val minutesLeft = getMinutesLeft(primaryDeparture, app.timeSource.nowMillis()) + + val titleText = "${primaryDeparture.line?.name ?: "Train"} to ${primaryDeparture.getTrainDestinationName() ?: "Destination"}" + val subtitleText = buildString { + append(formatCountdownText(minutesLeft)) + if (primaryDeparture.requiresTransfer || primaryDeparture.hasTransfers()) { + append(" • Transfer Req") + } + primaryDeparture.platform?.let { append(" • Platform $it") } + primaryDeparture.trainLength?.let { append(" • $it cars") } + } + + paneBuilder.addRow( + Row.Builder() + .setTitle(titleText) + .addText(subtitleText) + .build(), + ) + + if (departures.size > 1) { + val nextDeparture = departures[1] + val nextMinutes = getMinutesLeft(nextDeparture, app.timeSource.nowMillis()) + val transferSuffix = if (nextDeparture.requiresTransfer || nextDeparture.hasTransfers()) " (Transfer)" else "" + paneBuilder.addRow( + Row.Builder() + .setTitle("Next Train") + .addText("${nextDeparture.getTrainDestinationName() ?: "Train"}$transferSuffix: ${formatCountdownText(nextMinutes)}") + .build(), + ) + } + + runCatching { + checkMilestoneAlerts(primaryDeparture, minutesLeft, isAudioGuidanceEnabled) + } + } + + val transferToggleTitle = if (showTransfers) "Direct Only" else "Include Transfers" + paneBuilder.addAction( + Action.Builder() + .setTitle(transferToggleTitle) + .setOnClickListener { + CarPreferences.setShowTransfersForRoute(carContext, stationPair, !showTransfers) + runCatching { invalidate() } + } + .build(), + ) + + paneBuilder.addAction( + Action.Builder() + .setTitle(if (isAudioGuidanceEnabled) "Mute Guidance" else "Unmute Guidance") + .setOnClickListener { + CarPreferences.setDefaultAudioGuidance(carContext, !isAudioGuidanceEnabled) + runCatching { invalidate() } + } + .build(), + ) + + val routeTitle = "${stationPair.origin.getName()} → ${stationPair.destination?.getName() ?: "All"}" + + val header = Header.Builder() + .setTitle(routeTitle) + .setStartHeaderAction(Action.BACK) + .addEndHeaderAction( + Action.Builder() + .setTitle("Refresh") + .setOnClickListener { + runCatching { app.transitRepository.refreshNow() } + runCatching { invalidate() } + } + .build(), + ) + .build() + + return PaneTemplate.Builder(paneBuilder.build()) + .setHeader(header) + .build() + } + + private fun buildErrorTemplate(title: String, message: String): Template { + val header = Header.Builder() + .setTitle(title) + .setStartHeaderAction(Action.BACK) + .build() + + val pane = Pane.Builder().addRow( + Row.Builder() + .setTitle(title) + .addText(message) + .build(), + ).build() + + return PaneTemplate.Builder(pane).setHeader(header).build() + } + + private fun buildFallbackTemplate(): Template { + return buildErrorTemplate("Live Departures", "Unable to load departure times. Tap Refresh to try again.") + } + + private fun checkMilestoneAlerts(departure: Departure, minutesLeft: Int, isAudioGuidanceEnabled: Boolean) { + val trainKey = departure.identity + val milestoneKey = "${trainKey}_$minutesLeft" + + if ((minutesLeft in listOf(5, 2, 0)) && !notifiedMilestones.contains(milestoneKey)) { + notifiedMilestones.add(milestoneKey) + + val destinationName = departure.getTrainDestinationName() ?: "Destination" + val platformText = departure.platform?.let { " on platform $it" } ?: "" + + val announcement = when (minutesLeft) { + 0 -> "Train to $destinationName is boarding now$platformText" + else -> "Train to $destinationName departs in $minutesLeft minutes" + } + + CarNotificationHelper.postDepartureMilestoneNotification( + carContext, + "${stationPair.origin?.abbreviation ?: "BART"} Departure Alert", + announcement, + ) + + getAudioGuidanceManager().speakAnnouncement(announcement, isAudioGuidanceEnabled) + } + } + + private fun getMinutesLeft(departure: Departure, nowMillis: Long): Int { + val seconds = departure.getMeanSecondsLeft(nowMillis) + return (seconds / 60).coerceAtLeast(0) + } + + private fun formatCountdownText(minutesLeft: Int): String { + return when { + minutesLeft <= 0 -> "Boarding Now" + minutesLeft == 1 -> "Departs in 1 min" + else -> "Departs in $minutesLeft mins" + } + } + + companion object { + private const val TICKER_INTERVAL_MILLIS = 30_000L + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/AudioGuidanceManager.kt b/app/src/main/kotlin/in/izyum/bart/car/AudioGuidanceManager.kt new file mode 100644 index 0000000..5e4b63b --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/AudioGuidanceManager.kt @@ -0,0 +1,125 @@ +package `in`.izyum.bart.car + +import android.content.Context +import android.media.AudioAttributes +import android.media.AudioFocusRequest +import android.media.AudioManager +import android.os.Build +import android.speech.tts.TextToSpeech +import android.speech.tts.UtteranceProgressListener +import java.util.Locale + +/** + * Manages audio focus requests with AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK + * and USAGE_ASSISTANCE_NAVIGATION_GUIDANCE to duck background media playback + * during voice announcements of departure milestones. + */ +class AudioGuidanceManager(context: Context) : TextToSpeech.OnInitListener { + + private val appContext = context.applicationContext + private val audioManager = + appContext.getSystemService(Context.AUDIO_SERVICE) as? AudioManager + private var textToSpeech: TextToSpeech? = null + @Volatile + private var isTtsReady = false + + private val focusLock = Any() + private var focusRequest: AudioFocusRequest? = null + + init { + runCatching { + textToSpeech = TextToSpeech(appContext, this) + } + } + + override fun onInit(status: Int) { + if (status == TextToSpeech.SUCCESS) { + runCatching { + val result = textToSpeech?.setLanguage(Locale.US) + if ((result != TextToSpeech.LANG_MISSING_DATA) && (result != TextToSpeech.LANG_NOT_SUPPORTED)) { + isTtsReady = true + textToSpeech?.setOnUtteranceProgressListener( + object : UtteranceProgressListener() { + override fun onStart(utteranceId: String?) {} + + override fun onDone(utteranceId: String?) { + abandonAudioFocus() + } + + @Deprecated("Deprecated in Java") + override fun onError(utteranceId: String?) { + abandonAudioFocus() + } + }, + ) + } + } + } + } + + fun speakAnnouncement(message: String, enabled: Boolean) { + if (!enabled || !isTtsReady) return + + runCatching { + if (requestAudioFocus()) { + val utteranceId = "bart_guidance_${System.currentTimeMillis()}" + val result = textToSpeech?.speak(message, TextToSpeech.QUEUE_FLUSH, null, utteranceId) + if (result != TextToSpeech.SUCCESS) { + abandonAudioFocus() + } + } + } + } + + private fun requestAudioFocus(): Boolean { + synchronized(focusLock) { + val am = audioManager ?: return false + return runCatching { + val audioAttributes = AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE) + .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) + .build() + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val request = + AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK) + .setAudioAttributes(audioAttributes) + .setWillPauseWhenDucked(false) + .build() + focusRequest = request + am.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED + } else { + @Suppress("DEPRECATION") + am.requestAudioFocus( + null, + AudioManager.STREAM_NOTIFICATION, + AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK, + ) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED + } + }.getOrDefault(false) + } + } + + private fun abandonAudioFocus() { + synchronized(focusLock) { + val am = audioManager ?: return + runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + focusRequest?.let { am.abandonAudioFocusRequest(it) } + focusRequest = null + } else { + @Suppress("DEPRECATION") + am.abandonAudioFocus(null) + } + } + } + } + + fun shutdown() { + runCatching { + textToSpeech?.stop() + textToSpeech?.shutdown() + abandonAudioFocus() + } + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/BartCarAppService.kt b/app/src/main/kotlin/in/izyum/bart/car/BartCarAppService.kt new file mode 100644 index 0000000..6008af3 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/BartCarAppService.kt @@ -0,0 +1,22 @@ +package `in`.izyum.bart.car + +import androidx.car.app.CarAppService +import androidx.car.app.Session +import androidx.car.app.SessionInfo +import androidx.car.app.validation.HostValidator + +/** + * Entry point for Android Auto / Android for Cars App Library. + * Connects the car head unit to the BartRunner app session. + */ +class BartCarAppService : CarAppService() { + + override fun createHostValidator(): HostValidator { + // Allows connection from Android Auto / Desktop Head Unit (DHU) during testing and production hosts + return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR + } + + override fun onCreateSession(sessionInfo: SessionInfo): Session { + return BartCarSession() + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/BartCarSession.kt b/app/src/main/kotlin/in/izyum/bart/car/BartCarSession.kt new file mode 100644 index 0000000..f3209cd --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/BartCarSession.kt @@ -0,0 +1,16 @@ +package `in`.izyum.bart.car + +import android.content.Intent +import androidx.car.app.Screen +import androidx.car.app.Session + +/** + * Manages the lifecycle of the Android Auto session. + * Instantiates the initial Saved Route Picker screen when launched. + */ +class BartCarSession : Session() { + + override fun onCreateScreen(intent: Intent): Screen { + return SavedRoutePickerScreen(carContext) + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/CarNotificationHelper.kt b/app/src/main/kotlin/in/izyum/bart/car/CarNotificationHelper.kt new file mode 100644 index 0000000..ec0766c --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/CarNotificationHelper.kt @@ -0,0 +1,79 @@ +package `in`.izyum.bart.car + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.car.app.notification.CarAppExtender +import androidx.core.app.ActivityCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import `in`.izyum.bart.R + +/** + * Helper utility for posting Android Auto-compliant Heads-Up Notifications (HUN) + * with CarAppExtender to notify drivers of upcoming train departure milestones. + */ +object CarNotificationHelper { + const val CHANNEL_ID = "bart_transit_milestones" + private const val CHANNEL_NAME = "Commute & Transit Milestones" + private const val CHANNEL_DESC = "Heads-Up Notifications for upcoming train departures" + + fun createNotificationChannel(context: Context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + runCatching { + val importance = NotificationManager.IMPORTANCE_HIGH + val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance).apply { + description = CHANNEL_DESC + enableVibration(true) + } + val notificationManager = + context.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager + notificationManager?.createNotificationChannel(channel) + } + } + } + + fun postDepartureMilestoneNotification( + context: Context, + routeTitle: String, + contentText: String, + notificationId: Int = 1001, + ) { + val appContext = context.applicationContext + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ActivityCompat.checkSelfPermission( + appContext, + android.Manifest.permission.POST_NOTIFICATIONS, + ) != PackageManager.PERMISSION_GRANTED + ) { + return + } + } + + try { + createNotificationChannel(appContext) + + val carExtender = CarAppExtender.Builder() + .setImportance(NotificationManager.IMPORTANCE_HIGH) + .build() + + val builder = NotificationCompat.Builder(appContext, CHANNEL_ID) + .setSmallIcon(R.mipmap.ic_launcher) + .setContentTitle(routeTitle) + .setContentText(contentText) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setCategory(NotificationCompat.CATEGORY_NAVIGATION) + .setAutoCancel(true) + .extend(carExtender) + + val notificationManager = NotificationManagerCompat.from(appContext) + notificationManager.notify(notificationId, builder.build()) + } catch (_: SecurityException) { + // Permission for POST_NOTIFICATIONS may not be granted + } catch (_: Throwable) { + // Avoid crashing on notification errors + } + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/CarPreferences.kt b/app/src/main/kotlin/in/izyum/bart/car/CarPreferences.kt new file mode 100644 index 0000000..0b9248f --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/CarPreferences.kt @@ -0,0 +1,88 @@ +package `in`.izyum.bart.car + +import android.content.Context +import androidx.core.content.edit +import `in`.izyum.bart.model.StationPair + +/** + * Persists Android Auto settings, including global default transfer view preferences + * and per-route override states. + */ +object CarPreferences { + private const val PREFS_NAME = "car_app_preferences" + + private const val KEY_DEFAULT_SHOW_TRANSFERS = "default_show_transfers" + private const val KEY_DEFAULT_AUDIO_GUIDANCE = "default_audio_guidance" + private const val PREFIX_ROUTE_SHOW_TRANSFERS = "route_show_transfers_" + + fun getDefaultShowTransfers(context: Context): Boolean { + return runCatching { + context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getBoolean(KEY_DEFAULT_SHOW_TRANSFERS, true) + }.getOrDefault(true) + } + + fun setDefaultShowTransfers(context: Context, showTransfers: Boolean) { + runCatching { + context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(KEY_DEFAULT_SHOW_TRANSFERS, showTransfers) } + } + } + + fun getDefaultAudioGuidance(context: Context): Boolean { + return runCatching { + context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .getBoolean(KEY_DEFAULT_AUDIO_GUIDANCE, true) + }.getOrDefault(true) + } + + fun setDefaultAudioGuidance(context: Context, enabled: Boolean) { + runCatching { + context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(KEY_DEFAULT_AUDIO_GUIDANCE, enabled) } + } + } + + fun getShowTransfersForRoute(context: Context, stationPair: StationPair): Boolean { + return runCatching { + val prefs = context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + val key = getRouteKey(stationPair) + if (prefs.contains(key)) { + prefs.getBoolean(key, true) + } else { + getDefaultShowTransfers(context) + } + }.getOrDefault(true) + } + + fun setShowTransfersForRoute(context: Context, stationPair: StationPair, showTransfers: Boolean) { + runCatching { + val key = getRouteKey(stationPair) + context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(key, showTransfers) } + } + } + + fun clearRouteOverrides(context: Context) { + runCatching { + val prefs = context.applicationContext + .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + val keysToRemove = prefs.all.keys.filter { it.startsWith(PREFIX_ROUTE_SHOW_TRANSFERS) } + prefs.edit { + keysToRemove.forEach { remove(it) } + } + } + } + + private fun getRouteKey(stationPair: StationPair): String { + val origin = stationPair.origin?.abbreviation ?: "ORIGIN" + val destination = stationPair.destination?.abbreviation ?: "ALL" + return "$PREFIX_ROUTE_SHOW_TRANSFERS${origin}_$destination" + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/CarSettingsScreen.kt b/app/src/main/kotlin/in/izyum/bart/car/CarSettingsScreen.kt new file mode 100644 index 0000000..ade7f09 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/CarSettingsScreen.kt @@ -0,0 +1,105 @@ +package `in`.izyum.bart.car + +import androidx.car.app.CarContext +import androidx.car.app.Screen +import androidx.car.app.model.Action +import androidx.car.app.model.Header +import androidx.car.app.model.ItemList +import androidx.car.app.model.ListTemplate +import androidx.car.app.model.Row +import androidx.car.app.model.Template + +/** + * Android Auto Screen providing settings for Android Auto options. + * Allows configuring the default transfer view setting, default audio guidance, + * and clearing per-route preference overrides. + */ +class CarSettingsScreen(carContext: CarContext) : Screen(carContext) { + + override fun onGetTemplate(): Template { + return runCatching { buildTemplate() }.getOrElse { buildFallbackTemplate() } + } + + private fun buildTemplate(): Template { + val listBuilder = ItemList.Builder() + + // 1. Default Transfer View Setting + val defaultShowTransfers = CarPreferences.getDefaultShowTransfers(carContext) + val transferSubtitle = if (defaultShowTransfers) { + "Showing all trains (Direct & Transfers)" + } else { + "Direct trains only (Filtering out transfer routes)" + } + + listBuilder.addItem( + Row.Builder() + .setTitle("Default Transfer View Setting") + .addText(transferSubtitle) + .setOnClickListener { + CarPreferences.setDefaultShowTransfers(carContext, !defaultShowTransfers) + runCatching { invalidate() } + } + .build(), + ) + + // 2. Default Audio Guidance Setting + val defaultAudioGuidance = CarPreferences.getDefaultAudioGuidance(carContext) + val audioSubtitle = if (defaultAudioGuidance) { + "Enabled (Media ducking and voice alerts on)" + } else { + "Disabled (Muted)" + } + + listBuilder.addItem( + Row.Builder() + .setTitle("Default Audio Guidance") + .addText(audioSubtitle) + .setOnClickListener { + CarPreferences.setDefaultAudioGuidance(carContext, !defaultAudioGuidance) + runCatching { invalidate() } + } + .build(), + ) + + // 3. Clear Per-Route Overrides + listBuilder.addItem( + Row.Builder() + .setTitle("Reset Per-Route Transfer Settings") + .addText("Clear saved route-specific transfer view overrides and revert all routes to default.") + .setOnClickListener { + CarPreferences.clearRouteOverrides(carContext) + runCatching { invalidate() } + } + .build(), + ) + + val header = Header.Builder() + .setTitle("Android Auto Settings") + .setStartHeaderAction(Action.BACK) + .build() + + return ListTemplate.Builder() + .setHeader(header) + .setSingleList(listBuilder.build()) + .build() + } + + private fun buildFallbackTemplate(): Template { + val header = Header.Builder() + .setTitle("Android Auto Settings") + .setStartHeaderAction(Action.BACK) + .build() + + val listBuilder = ItemList.Builder().addItem( + Row.Builder() + .setTitle("Error loading settings") + .addText("Tap Back and try again.") + .build(), + ) + + return ListTemplate.Builder() + .setHeader(header) + .setSingleList(listBuilder.build()) + .build() + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/car/SavedRoutePickerScreen.kt b/app/src/main/kotlin/in/izyum/bart/car/SavedRoutePickerScreen.kt new file mode 100644 index 0000000..5099c76 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/car/SavedRoutePickerScreen.kt @@ -0,0 +1,145 @@ +package `in`.izyum.bart.car + +import androidx.car.app.CarContext +import androidx.car.app.Screen +import androidx.car.app.model.Action +import androidx.car.app.model.Header +import androidx.car.app.model.ItemList +import androidx.car.app.model.ListTemplate +import androidx.car.app.model.Row +import androidx.car.app.model.Template +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.lifecycleScope +import `in`.izyum.bart.BartRunnerApplication +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch + +/** + * Android Auto Screen providing a Saved Route Picker. + * Displays user's favorite stations / commutes for fast 1-tap access while driving. + */ +class SavedRoutePickerScreen(carContext: CarContext) : Screen(carContext), DefaultLifecycleObserver { + + private var observerJob: Job? = null + + init { + lifecycle.addObserver(this) + } + + override fun onResume(owner: LifecycleOwner) { + val app = carContext.applicationContext as? BartRunnerApplication ?: return + observerJob?.cancel() + observerJob = lifecycleScope.launch { + app.favoritesRepository.uiState.collectLatest { + runCatching { invalidate() } + } + } + } + + override fun onPause(owner: LifecycleOwner) { + observerJob?.cancel() + observerJob = null + } + + override fun onGetTemplate(): Template { + return runCatching { buildTemplate() }.getOrElse { buildFallbackTemplate() } + } + + private fun buildTemplate(): Template { + val app = carContext.applicationContext as? BartRunnerApplication + val favoritesState = app?.favoritesRepository?.uiState?.value + val favorites = favoritesState?.favorites.orEmpty() + + val listBuilder = ItemList.Builder() + + if (favorites.isEmpty()) { + val emptyTitle = if (favoritesState?.isLoading == true) "Loading Saved Commutes..." else "No Favorite Commutes Saved" + val emptySubtitle = if (favoritesState?.isLoading == true) { + "Fetching saved favorites from storage..." + } else { + "Add favorite routes on your phone to quickly access them in Android Auto." + } + listBuilder.addItem( + Row.Builder() + .setTitle(emptyTitle) + .addText(emptySubtitle) + .build(), + ) + } else { + // Android Auto ListTemplate caps list to 6 items max per template guidelines + val displayFavorites = favorites.take(MAX_DISPLAY_FAVORITES) + for (favorite in displayFavorites) { + val origin = favorite.origin ?: continue + + val originName = origin.getName() + val destName = favorite.destination?.getName() ?: "All Destinations" + val subtitle = "${origin.abbreviation} → ${favorite.destination?.abbreviation ?: "ALL"}" + + listBuilder.addItem( + Row.Builder() + .setTitle("$originName → $destName") + .addText(subtitle) + .setOnClickListener { + screenManager.push(ActiveDepartureScreen(carContext, favorite)) + } + .build(), + ) + } + } + + val header = Header.Builder() + .setTitle("Saved Route Picker") + .setStartHeaderAction(Action.APP_ICON) + .addEndHeaderAction( + Action.Builder() + .setTitle("Refresh") + .setOnClickListener { runCatching { invalidate() } } + .build(), + ) + .addEndHeaderAction( + Action.Builder() + .setTitle("Settings") + .setOnClickListener { + screenManager.push(CarSettingsScreen(carContext)) + } + .build(), + ) + .build() + + return ListTemplate.Builder() + .setHeader(header) + .setSingleList(listBuilder.build()) + .build() + } + + private fun buildFallbackTemplate(): Template { + val header = Header.Builder() + .setTitle("Saved Route Picker") + .setStartHeaderAction(Action.APP_ICON) + .addEndHeaderAction( + Action.Builder() + .setTitle("Refresh") + .setOnClickListener { runCatching { invalidate() } } + .build(), + ) + .build() + + val listBuilder = ItemList.Builder().addItem( + Row.Builder() + .setTitle("Unable to load saved routes") + .addText("Tap Refresh to try again.") + .build(), + ) + + return ListTemplate.Builder() + .setHeader(header) + .setSingleList(listBuilder.build()) + .build() + } + + companion object { + private const val MAX_DISPLAY_FAVORITES = 6 + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/data/FavoritesRepository.kt b/app/src/main/kotlin/in/izyum/bart/data/FavoritesRepository.kt index bef3161..5111abc 100644 --- a/app/src/main/kotlin/in/izyum/bart/data/FavoritesRepository.kt +++ b/app/src/main/kotlin/in/izyum/bart/data/FavoritesRepository.kt @@ -55,7 +55,7 @@ class FavoritesRepository(context: Context) : AutoCloseable { fun moveFavorite(from: Int, to: Int) { updateFavorites { favorites -> - if (from in favorites.indices && to in favorites.indices && from != to) { + if ((from in favorites.indices) && (to in favorites.indices) && (from != to)) { val favorite = favorites.removeAt(from) favorites.add(to, favorite) } @@ -98,7 +98,7 @@ class FavoritesRepository(context: Context) : AutoCloseable { object : TypeReference>() {} ) } - } catch (exception: java.io.FileNotFoundException) { + } catch (_: java.io.FileNotFoundException) { emptyList() } catch (exception: Exception) { Log.e(TAG, "Could not read favorite routes", exception) diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt index a2e73f0..8a51b5b 100644 --- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt +++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt @@ -8,7 +8,7 @@ import `in`.izyum.bart.model.TripLeg import `in`.izyum.bart.model.TripStop /** Versioned JSON schema for the durable followed-trip state. */ -class FollowedTripRecord constructor() { +class FollowedTripRecord { @JvmField var version: Int = CURRENT_VERSION @JvmField var origin: String? = null @JvmField var trainDestination: String? = null @@ -97,7 +97,7 @@ class FollowedTripRecord constructor() { abbreviation?.let(Station::getByAbbreviation) } - class TripLegRecord constructor() { + class TripLegRecord { @JvmField var line: String? = null @JvmField var origin: String? = null @JvmField var destination: String? = null @@ -148,7 +148,7 @@ class FollowedTripRecord constructor() { } } - class TripStopRecord constructor() { + class TripStopRecord { @JvmField var station: String? = null @JvmField var arrivalTime = 0L @JvmField var departureTime = 0L diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt index 56fc690..4d2668b 100644 --- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt +++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt @@ -185,7 +185,7 @@ class FollowedTripRepository @JvmOverloads constructor( } try { store.save(nextDeparture) - } catch (exception: Exception) { + } catch (_: Exception) { // Persistence is best effort; the in-memory state remains authoritative. } } diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt index a4e318c..0d2a02e 100644 --- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt +++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt @@ -20,7 +20,7 @@ class FollowedTripStore @JvmOverloads constructor( objectMapper.readValue(input, FollowedTripRecord::class.java) .toDeparture() } - } catch (exception: Exception) { + } catch (_: Exception) { delete() null } diff --git a/app/src/main/kotlin/in/izyum/bart/data/HomeStationPreferences.kt b/app/src/main/kotlin/in/izyum/bart/data/HomeStationPreferences.kt new file mode 100644 index 0000000..9bb2dd8 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/data/HomeStationPreferences.kt @@ -0,0 +1,35 @@ +package `in`.izyum.bart.data + +import android.content.Context +import androidx.core.content.edit +import `in`.izyum.bart.model.Station + +/** Stores the home station used as default origin in Trip Planner and Add Route. */ +object HomeStationPreferences { + private const val PREFERENCES_NAME = "home_station_preferences" + private const val HOME_STATION_ABBR_KEY = "home_station_abbr" + + fun getHomeStationAbbreviation(context: Context): String? = + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .getString(HOME_STATION_ABBR_KEY, null) + ?.takeIf { it.isNotEmpty() } + + fun getHomeStation(context: Context): Station? { + val abbr = getHomeStationAbbreviation(context) ?: return null + return Station.getStationList().firstOrNull { it.abbreviation.equals(abbr, ignoreCase = true) } + } + + fun setHomeStation(context: Context, station: Station?) { + setHomeStationAbbreviation(context, station?.abbreviation) + } + + fun setHomeStationAbbreviation(context: Context, abbreviation: String?) { + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .edit { + if (abbreviation.isNullOrEmpty()) remove(HOME_STATION_ABBR_KEY) + else putString(HOME_STATION_ABBR_KEY, abbreviation) + } + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/data/KeepScreenOnPreferences.kt b/app/src/main/kotlin/in/izyum/bart/data/KeepScreenOnPreferences.kt new file mode 100644 index 0000000..f230ebf --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/data/KeepScreenOnPreferences.kt @@ -0,0 +1,21 @@ +package `in`.izyum.bart.data + +import android.content.Context +import androidx.core.content.edit + +/** Manages persistent preference for keeping screen active during full-screen ride follow. */ +object KeepScreenOnPreferences { + private const val PREFERENCES_NAME = "keep_screen_on_preferences" + private const val KEEP_SCREEN_ON_KEY = "keep_screen_on" + + fun isKeepScreenOn(context: Context): Boolean = + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .getBoolean(KEEP_SCREEN_ON_KEY, false) + + fun setKeepScreenOn(context: Context, keepOn: Boolean) { + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(KEEP_SCREEN_ON_KEY, keepOn) } + } +} diff --git a/app/src/main/kotlin/in/izyum/bart/data/TransferPreferences.kt b/app/src/main/kotlin/in/izyum/bart/data/TransferPreferences.kt new file mode 100644 index 0000000..e347866 --- /dev/null +++ b/app/src/main/kotlin/in/izyum/bart/data/TransferPreferences.kt @@ -0,0 +1,44 @@ +package `in`.izyum.bart.data + +import android.content.Context +import androidx.core.content.edit +import `in`.izyum.bart.model.StationPair + +/** Manages persistent preferences for route transfer filtering and defaults. */ +object TransferPreferences { + private const val PREFERENCES_NAME = "transfer_preferences" + private const val DEFAULT_SHOW_TRANSFERS_KEY = "default_show_transfers" + private const val ROUTE_PREF_PREFIX = "route_show_transfers_" + + fun getDefaultShowTransfers(context: Context): Boolean = + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .getBoolean(DEFAULT_SHOW_TRANSFERS_KEY, true) + + fun setDefaultShowTransfers(context: Context, show: Boolean) { + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(DEFAULT_SHOW_TRANSFERS_KEY, show) } + } + + fun getShowTransfersForRoute(context: Context, route: StationPair?): Boolean { + if (route == null) return getDefaultShowTransfers(context) + val prefs = context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + val key = routeKey(route) + return if (prefs.contains(key)) { + prefs.getBoolean(key, true) + } else { + getDefaultShowTransfers(context) + } + } + + fun setShowTransfersForRoute(context: Context, route: StationPair?, show: Boolean) { + if (route == null) return + context.applicationContext + .getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + .edit { putBoolean(routeKey(route), show) } + } + + private fun routeKey(route: StationPair): String = + "$ROUTE_PREF_PREFIX${route.origin?.abbreviation.orEmpty()}_${route.destination?.abbreviation.orEmpty()}" +} diff --git a/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt b/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt index c5b85f0..15766e8 100644 --- a/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt +++ b/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt @@ -19,9 +19,7 @@ class RealTimeDepartures internal constructor( private val unfilteredDepartures = immutableList(unfilteredDepartures) private val departures = immutableList(departures) - init { - requireNotNull(schedule) { "A schedule is required" } - } + fun getOrigin(): Station? = origin @@ -121,8 +119,8 @@ class RealTimeDepartures internal constructor( val line = departure.line ?: return null return routes.firstOrNull { route -> route.trainDestinationIsApplicable(trainDestination, line) - && (route.destination == null - || route.destination!!.includedInLimitedService + && ((route.destination == null) + || route.destination.includedInLimitedService || !departure.limited) } } diff --git a/app/src/main/kotlin/in/izyum/bart/model/StationPair.kt b/app/src/main/kotlin/in/izyum/bart/model/StationPair.kt index a32499d..9d73508 100644 --- a/app/src/main/kotlin/in/izyum/bart/model/StationPair.kt +++ b/app/src/main/kotlin/in/izyum/bart/model/StationPair.kt @@ -10,13 +10,13 @@ class StationPair @JsonCreator constructor( @param:JsonProperty("destination") val destination: Station?, ) { @JsonIgnore - fun isStationOnly(): Boolean = origin != null && destination == null + fun isStationOnly(): Boolean = (origin != null) && (destination == null) fun isBetweenStations(station1: Station?, station2: Station?): Boolean = - origin != null - && destination != null - && ((origin == station1 && destination == station2) - || (origin == station2 && destination == station1)) + (origin != null) + && (destination != null) + && (((origin == station1) && (destination == station2)) + || ((origin == station2) && (destination == station1))) override fun hashCode(): Int = 31 * (31 + (destination?.hashCode() ?: 0)) + (origin?.hashCode() ?: 0) diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/ElevatorStatusClient.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/ElevatorStatusClient.kt index 9cf5960..dd3d903 100644 --- a/app/src/main/kotlin/in/izyum/bart/networktasks/ElevatorStatusClient.kt +++ b/app/src/main/kotlin/in/izyum/bart/networktasks/ElevatorStatusClient.kt @@ -20,7 +20,6 @@ class ElevatorStatusClient @JvmOverloads constructor( throw IOException("Elevator status returned ${response.code}") } val body = response.body - ?: throw IOException("Elevator status returned an empty body") parseDescription(body.string()).ifBlank { throw IOException("Elevator status response did not contain a description") } diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt index 0a10800..ea4e573 100644 --- a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt +++ b/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt @@ -27,8 +27,8 @@ data class EtdStationBoard( ) { fun departuresFor(line: Line?, destination: Station?): List = departures.filter { departure -> - normalizeLine(departure.line) == normalizeLine(line) - && departure.destination == destination + (normalizeLine(departure.line) == normalizeLine(line)) + && (departure.destination == destination) } private fun normalizeLine(line: Line?): Line? = when (line) { @@ -55,7 +55,6 @@ class HttpEtdClient @JvmOverloads constructor( throw IOException("ETD status returned ${response.code}") } val body = response.body - ?: throw IOException("ETD status returned an empty body") parseBoard(station, receivedAtMillis, body.string()) } } diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt index 97eff76..f6f311b 100644 --- a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt +++ b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt @@ -29,9 +29,7 @@ class GtfsRealtimeContentHandler @JvmOverloads constructor( private val bartGtfsNetwork: BartGtfsNetwork, private val timeSource: TimeSource = SystemTimeSource, ) { - init { - requireNotNull(bartGtfsNetwork) { "A validated GTFS network is required" } - } + fun getRealTimeDepartures(feed: GtfsRealtime.FeedMessage): RealTimeDepartures { val feedIndex = GtfsRealtimeFeedIndex.from(feed) @@ -381,7 +379,7 @@ class GtfsRealtimeContentHandler @JvmOverloads constructor( ): Schedule = Schedule.fromStatic( bartGtfsNetwork, feedTime, - Line.values().toSet(), + Line.entries.toSet(), ).applyRealtime(feedIndex) private fun snapshotFromSchedule(trip: Schedule.Trip): TripSnapshot { diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt index 2bba9fc..11adf59 100644 --- a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt +++ b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt @@ -93,7 +93,7 @@ class GtfsStaticData @JvmOverloads constructor( private fun loadLocked(refreshStale: Boolean): LoadedData { synchronized(lock) { val now = timeSource.nowMillis() - if (cachedData != null && now - cachedAt < CACHE_MILLIS) { + if (cachedData != null && (now - cachedAt < CACHE_MILLIS)) { return cachedData!! } @@ -185,7 +185,7 @@ class GtfsStaticData @JvmOverloads constructor( cachedData = it cachedAt = if (lastSuccess > 0) lastSuccess else now } - } catch (exception: Exception) { + } catch (_: Exception) { invalidateDatabase() null } @@ -389,11 +389,12 @@ class GtfsStaticData @JvmOverloads constructor( .header("Accept", "application/zip") .build() CLIENT.newCall(request).execute().use { response -> - if (!response.isSuccessful || response.body == null) { + val body = response.body + if (!response.isSuccessful || body == null) { throw IOException("Static GTFS returned ${response.code}") } FileOutputStream(destination, false).use { output -> - response.body!!.byteStream().use { input -> + body.byteStream().use { input -> input.copyTo(output, 8192) } } diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt index fa55c83..1b9472d 100644 --- a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt +++ b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt @@ -158,7 +158,7 @@ class DepartureAlarmScheduler @JvmOverloads constructor( try { manager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, alarmTime, intent) - } catch (exception: SecurityException) { + } catch (_: SecurityException) { manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, intent) Log.w(Constants.TAG, "Exact alarm permission is unavailable; using an inexact alarm") diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingWorker.kt b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingWorker.kt index 85b0ce9..ecdcf21 100644 --- a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingWorker.kt +++ b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingWorker.kt @@ -5,7 +5,6 @@ import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import `in`.izyum.bart.BartRunnerApplication import `in`.izyum.bart.data.BackgroundPollingPreferences -import `in`.izyum.bart.data.FollowedTripRepository import `in`.izyum.bart.model.Departure import `in`.izyum.bart.backend.RouteDepartureProjection import `in`.izyum.bart.presentation.DepartureNotificationFactory diff --git a/app/src/main/kotlin/in/izyum/bart/platform/OfflineStatusController.kt b/app/src/main/kotlin/in/izyum/bart/platform/OfflineStatusController.kt index 6db6b73..f1ee068 100644 --- a/app/src/main/kotlin/in/izyum/bart/platform/OfflineStatusController.kt +++ b/app/src/main/kotlin/in/izyum/bart/platform/OfflineStatusController.kt @@ -40,7 +40,7 @@ class OfflineStatusController( private val notificationManager = NotificationManagerCompat.from(applicationContext) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val lock = Any() - private val _isOffline = MutableStateFlow(false) + private val _isOffline = MutableStateFlow(value = false) private var networkAvailable: Boolean? = null private var downloadFailed = false private var retryJob: Job? = null diff --git a/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt b/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt index 65003ed..80c71b7 100644 --- a/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt +++ b/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt @@ -25,10 +25,10 @@ object DepartureTextFormatter { val predictionLabel: String? = null, val isPositiveDelay: Boolean = false, ) { - fun isNotBlank(): Boolean = scheduledTime != null - || actualTime != null - || actualLabel != null - || predictionLabel != null + fun isNotBlank(): Boolean = (scheduledTime != null) + || (actualTime != null) + || (actualLabel != null) + || (predictionLabel != null) } @JvmStatic @@ -330,6 +330,12 @@ object DepartureTextFormatter { } else { context.getString(if (departure.isListedInETDs()) R.string.leaving else R.string.departed) } + secondsLeft >= 3600 -> context.getString( + R.string.departure_countdown_hours, + secondsLeft / 3600, + (secondsLeft % 3600) / 60, + secondsLeft % 60, + ) else -> context.getString(R.string.departure_countdown, secondsLeft / 60, secondsLeft % 60) } } diff --git a/app/src/main/kotlin/in/izyum/bart/ui/BartRunnerUi.kt b/app/src/main/kotlin/in/izyum/bart/ui/BartRunnerUi.kt index 127b92a..970de9f 100644 --- a/app/src/main/kotlin/in/izyum/bart/ui/BartRunnerUi.kt +++ b/app/src/main/kotlin/in/izyum/bart/ui/BartRunnerUi.kt @@ -22,7 +22,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.size @@ -32,12 +31,12 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.automirrored.filled.CompareArrows import androidx.compose.material.icons.filled.AccessTime import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Alarm @@ -48,6 +47,9 @@ import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.DirectionsSubway import androidx.compose.material.icons.filled.Done import androidx.compose.material.icons.filled.Elevator +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.material.icons.filled.Fullscreen +import androidx.compose.material.icons.filled.FullscreenExit import androidx.compose.material.icons.filled.Map import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Refresh @@ -70,6 +72,7 @@ import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedCard @@ -107,8 +110,11 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.text.rememberTextMeasurer @@ -118,9 +124,16 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import android.widget.ImageView +import `in`.izyum.bart.BartRunnerApplication import `in`.izyum.bart.R import `in`.izyum.bart.activities.DeparturesViewModel import `in`.izyum.bart.activities.RoutesUiState +import `in`.izyum.bart.backend.RouteDepartureProjection +import `in`.izyum.bart.data.HomeStationPreferences +import `in`.izyum.bart.data.KeepScreenOnPreferences +import androidx.compose.material.icons.filled.WbSunny +import androidx.compose.runtime.DisposableEffect +import androidx.compose.ui.platform.LocalView import `in`.izyum.bart.model.Departure import `in`.izyum.bart.model.Line import `in`.izyum.bart.model.Station @@ -232,6 +245,12 @@ fun HomeScreen( onFareDiscountChanged: (String?) -> Unit = {}, backgroundPollingEnabled: Boolean = true, onBackgroundPollingChanged: (Boolean) -> Unit = {}, + defaultTransferViewEnabled: Boolean = true, + onDefaultTransferViewChanged: (Boolean) -> Unit = {}, + homeStation: Station? = null, + onHomeStationChanged: (Station?) -> Unit = {}, + keepScreenActive: Boolean = false, + onKeepScreenActiveChanged: (Boolean) -> Unit = {}, ) { var showPicker by remember { mutableStateOf(false) } var pickerAddsFavorite by remember { mutableStateOf(false) } @@ -240,6 +259,7 @@ fun HomeScreen( var showOverflowMenu by remember { mutableStateOf(false) } var showSettingsDialog by remember { mutableStateOf(false) } var showElevatorDialog by remember { mutableStateOf(false) } + var showFullScreenTrip by remember { mutableStateOf(false) } var draggedRoute by remember { mutableStateOf(null) } var draggedOffset by remember { mutableFloatStateOf(0f) } val favoriteListState = rememberLazyListState() @@ -324,30 +344,77 @@ fun HomeScreen( if (followedTrip != null) { item { Card( - modifier = Modifier.fillMaxWidth().clickable { onViewTrip(followedTrip) }, + modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer), shape = RoundedCornerShape(20.dp), ) { - Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { - Box(Modifier.size(44.dp).clip(RoundedCornerShape(12.dp)).background(MaterialTheme.colorScheme.primary), contentAlignment = Alignment.Center) { - Icon(Icons.Filled.Train, stringResource(R.string.trip_in_progress), tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(25.dp)) + Box(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onViewTrip(followedTrip) } + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(44.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.primary), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.Train, + stringResource(R.string.trip_in_progress), + tint = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier.size(25.dp), + ) + } + Column( + modifier = Modifier + .weight(1f) + .padding(start = 12.dp, end = 36.dp), + ) { + Text( + stringResource(R.string.trip_in_progress), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + ) + Text( + stringResource( + R.string.route_arrow, + followedTrip.origin?.getName().orEmpty(), + (followedTrip.passengerDestination ?: followedTrip.trainDestination)?.getName().orEmpty(), + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Icon( + Icons.AutoMirrored.Filled.ArrowForward, + null, + tint = MaterialTheme.colorScheme.primary, + ) } - Column(Modifier.weight(1f).padding(start = 12.dp)) { - Text(stringResource(R.string.trip_in_progress), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) - Text( - stringResource(R.string.route_arrow, followedTrip.origin?.getName().orEmpty(), (followedTrip.passengerDestination ?: followedTrip.trainDestination)?.getName().orEmpty()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onPrimaryContainer, - maxLines = 1, - overflow = TextOverflow.Ellipsis, + IconButton( + onClick = { showFullScreenTrip = true }, + modifier = Modifier + .align(Alignment.TopEnd) + .padding(4.dp), + ) { + Icon( + Icons.Filled.Fullscreen, + contentDescription = stringResource(R.string.full_screen), + tint = MaterialTheme.colorScheme.primary, ) } - Icon(Icons.AutoMirrored.Filled.ArrowForward, null, tint = MaterialTheme.colorScheme.primary) } } } } - if (!state.isOffline && state.alertKind != RoutesUiState.AlertKind.HIDDEN) { + if (!state.isOffline && (state.alertKind != RoutesUiState.AlertKind.HIDDEN)) { item { ServiceAlert(state, context) } } item { @@ -398,7 +465,6 @@ fun HomeScreen( route = route, departure = state.firstDepartures[route], fare = state.fares[route], - timeSource = timeSource, tick = tick, isEditing = isEditing, modifier = Modifier @@ -422,7 +488,7 @@ fun HomeScreen( draggedRoute = null draggedOffset = 0f }, - onDrag = { change, dragAmount -> + onDrag = { _, dragAmount -> if (draggedRoute != route) return@detectDragGestures draggedOffset += dragAmount.y val source = favoriteListState.layoutInfo.visibleItemsInfo @@ -508,6 +574,12 @@ fun HomeScreen( onFareDiscountChanged = onFareDiscountChanged, backgroundPollingEnabled = backgroundPollingEnabled, onBackgroundPollingChanged = onBackgroundPollingChanged, + defaultTransferViewEnabled = defaultTransferViewEnabled, + onDefaultTransferViewChanged = onDefaultTransferViewChanged, + homeStation = homeStation, + onHomeStationChanged = onHomeStationChanged, + keepScreenActive = keepScreenActive, + onKeepScreenActiveChanged = onKeepScreenActiveChanged, onDismiss = { showSettingsDialog = false }, ) } @@ -520,6 +592,15 @@ fun HomeScreen( onDismiss = { showElevatorDialog = false }, ) } + + if (showFullScreenTrip && followedTrip != null) { + FullScreenTripDialog( + departure = followedTrip, + pair = followedTrip.getStationPair(), + timeSource = timeSource, + onDismiss = { showFullScreenTrip = false }, + ) + } } @Composable @@ -573,9 +654,17 @@ private fun SettingsDialog( onFareDiscountChanged: (String?) -> Unit, backgroundPollingEnabled: Boolean, onBackgroundPollingChanged: (Boolean) -> Unit, + defaultTransferViewEnabled: Boolean, + onDefaultTransferViewChanged: (Boolean) -> Unit, + homeStation: Station? = null, + onHomeStationChanged: (Station?) -> Unit = {}, + keepScreenActive: Boolean = false, + onKeepScreenActiveChanged: (Boolean) -> Unit = {}, onDismiss: () -> Unit, ) { var showFareDiscountMenu by remember { mutableStateOf(false) } + var showHomeStationMenu by remember { mutableStateOf(false) } + val stations = remember { Station.getStationList() } val selectedDescription = fareDiscountOptions .firstOrNull { it.id == fareDiscountId } ?.description @@ -585,7 +674,52 @@ private fun SettingsDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.settings)) }, text = { - Column { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + Text( + text = stringResource(R.string.home_station), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = stringResource(R.string.home_station_description), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(8.dp)) + Box { + OutlinedButton( + onClick = { showHomeStationMenu = true }, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = homeStation?.getName() ?: stringResource(R.string.none), + modifier = Modifier.weight(1f), + ) + Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null) + } + DropdownMenu( + expanded = showHomeStationMenu, + onDismissRequest = { showHomeStationMenu = false }, + modifier = Modifier.heightIn(max = 280.dp), + ) { + DropdownMenuItem( + text = { Text(stringResource(R.string.none)) }, + onClick = { + onHomeStationChanged(null) + showHomeStationMenu = false + }, + ) + stations.forEach { station -> + DropdownMenuItem( + text = { Text(station.getName()) }, + onClick = { + onHomeStationChanged(station) + showHomeStationMenu = false + }, + ) + } + } + } + Spacer(Modifier.height(16.dp)) Text( text = stringResource(R.string.fare_discount), style = MaterialTheme.typography.titleMedium, @@ -597,7 +731,7 @@ private fun SettingsDialog( modifier = Modifier.fillMaxWidth(), ) { Text(selectedDescription, modifier = Modifier.weight(1f)) - Icon(Icons.Filled.ArrowForward, contentDescription = null) + Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null) } DropdownMenu( expanded = showFareDiscountMenu, @@ -641,6 +775,46 @@ private fun SettingsDialog( onCheckedChange = onBackgroundPollingChanged, ) } + Spacer(Modifier.height(16.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + text = stringResource(R.string.default_transfer_view), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = stringResource(R.string.default_transfer_view_description), + style = MaterialTheme.typography.bodySmall, + ) + } + Switch( + checked = defaultTransferViewEnabled, + onCheckedChange = onDefaultTransferViewChanged, + ) + } + Spacer(Modifier.height(16.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + text = stringResource(R.string.keep_screen_active), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = stringResource(R.string.keep_screen_active_description), + style = MaterialTheme.typography.bodySmall, + ) + } + Switch( + checked = keepScreenActive, + onCheckedChange = onKeepScreenActiveChanged, + ) + } } }, confirmButton = { @@ -732,15 +906,13 @@ fun AboutScreen( append(" ") append(stringResource(R.string.about_license_suffix)) } - ClickableText( + Text( text = apacheLicenseText, style = MaterialTheme.typography.bodyLarge.copy( color = MaterialTheme.colorScheme.onSurface, ), - onClick = { offset -> - if (apacheLicenseText.getStringAnnotations("URL", offset, offset).isNotEmpty()) { - onOpenApacheLicense() - } + modifier = Modifier.clickable { + onOpenApacheLicense() }, ) TextButton(onClick = onOpenGithub) { @@ -825,7 +997,6 @@ private fun FavoriteRouteCard( route: StationPair, departure: Departure?, fare: String?, - timeSource: TimeSource, tick: Long, isEditing: Boolean, modifier: Modifier = Modifier, @@ -903,9 +1074,10 @@ fun RoutePickerDialog( (context as? Activity)?.getPreferences(Context.MODE_PRIVATE) ?: context.getSharedPreferences("route_picker_preferences", Context.MODE_PRIVATE) } + val homeStation = remember(context) { HomeStationPreferences.getHomeStation(context) } val lastOriginPosition = preferences.getInt(LAST_SELECTED_ORIGIN, 0) var origin by remember(initialRoute) { - mutableStateOf(initialRoute?.origin ?: stations.getOrNull(lastOriginPosition) ?: stations.firstOrNull()) + mutableStateOf(initialRoute?.origin ?: homeStation ?: stations.getOrNull(lastOriginPosition) ?: stations.firstOrNull()) } var destination by remember(initialRoute) { mutableStateOf(initialRoute?.destination) @@ -982,6 +1154,7 @@ fun DeparturesScreen( onBack: () -> Unit, onOpenTrip: (Departure) -> Unit, onMap: () -> Unit, + onToggleShowTransfers: () -> Unit = {}, ) { val context = androidx.compose.ui.platform.LocalContext.current val tick = rememberSecondTick(timeSource) @@ -1006,9 +1179,9 @@ fun DeparturesScreen( val density = LocalDensity.current BoxWithConstraints(Modifier.fillMaxWidth()) { val requiredWidth = with(density) { - textMeasurer.measure(AnnotatedString(originName), style = titleStyle).size.width - + textMeasurer.measure(AnnotatedString(destinationName), style = titleStyle).size.width - + 22.dp.toPx() + textMeasurer.measure(AnnotatedString(originName), style = titleStyle).size.width + + textMeasurer.measure(AnnotatedString(destinationName), style = titleStyle).size.width + + 22.dp.toPx() } if (requiredWidth <= with(density) { maxWidth.toPx() }) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -1048,7 +1221,22 @@ fun DeparturesScreen( } } }, - actions = { IconButton(onClick = onMap) { Icon(Icons.Filled.Map, stringResource(R.string.system_map)) } }, + actions = { + IconButton(onClick = onToggleShowTransfers) { + Icon( + Icons.AutoMirrored.Filled.CompareArrows, + contentDescription = stringResource(R.string.show_transfers), + tint = if (state.showTransfers) { + LocalContentColor.current + } else { + MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + }, + ) + } + IconButton(onClick = onMap) { + Icon(Icons.Filled.Map, stringResource(R.string.system_map)) + } + }, ) }, contentWindowInsets = WindowInsets.safeDrawing, @@ -1073,7 +1261,6 @@ fun DeparturesScreen( DepartureCard( departure = departure, context = context, - timeSource = timeSource, tick = tick, onClick = { onOpenTrip(departure) }, ) @@ -1084,7 +1271,7 @@ fun DeparturesScreen( } @Composable -private fun DepartureCard(departure: Departure, context: Context, timeSource: TimeSource, tick: Long, onClick: () -> Unit) { +private fun DepartureCard(departure: Departure, context: Context, tick: Long, onClick: () -> Unit) { val primary = if (departure.isCanceled()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary val scheduleDetails = DepartureTextFormatter.departureSchedulePresentation(context, departure) val arrivalTime = if (departure.isCanceled()) { @@ -1188,56 +1375,62 @@ fun TripScreen( onShare: (Departure) -> Unit, onSilenceAlarm: () -> Unit, ) { - val context = androidx.compose.ui.platform.LocalContext.current val tick = rememberSecondTick(timeSource) var following by remember(isFollowingInitially) { mutableStateOf(isFollowingInitially) } var showAlarm by remember { mutableStateOf(false) } var showClear by remember { mutableStateOf(false) } - val current = departure + var showFullScreenTrip by remember { mutableStateOf(false) } Scaffold( topBar = { TopAppBar( navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) } }, title = { Text(stringResource(if (following) R.string.trip_in_progress else R.string.trip_details), fontWeight = FontWeight.Bold) }, actions = { - if (current != null) IconButton(onClick = { onShare(current) }) { Icon(Icons.Filled.Share, stringResource(R.string.share_arrival)) } - if (following && current != null) IconButton(onClick = { showClear = true }) { Icon(Icons.Filled.Close, stringResource(R.string.stop_following)) } + if (departure != null) IconButton(onClick = { onShare(departure) }) { Icon(Icons.Filled.Share, stringResource(R.string.share_arrival)) } + if (following && departure != null) IconButton(onClick = { showClear = true }) { Icon(Icons.Filled.Close, stringResource(R.string.stop_following)) } }, ) }, contentWindowInsets = WindowInsets.safeDrawing, ) { padding -> - if (current == null) { + if (departure == null) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } else { - val pair = current.getStationPair() + val pair = departure.getStationPair() LazyColumn(Modifier.fillMaxSize().padding(padding), contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp, 12.dp, 16.dp, 32.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { if (isOffline) { item { OfflineBanner() } } item { - TripHero(current, route ?: pair, fare, timeSource, tick) + TripHero( + departure = departure, + pair = route ?: pair, + fare = fare, + timeSource = timeSource, + tick = tick, + onFullScreen = if (following) { { showFullScreenTrip = true } } else null, + ) } if (!following) { - item { Button(onClick = { following = true; onFollow(current) }, modifier = Modifier.fillMaxWidth()) { Icon(Icons.Filled.Train, null); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.follow_this_trip)) } } + item { Button(onClick = { following = true; onFollow(departure) }, modifier = Modifier.fillMaxWidth()) { Icon(Icons.Filled.Train, null); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.follow_this_trip)) } } } else { item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { if (alarmPending) { FilledTonalButton(onClick = onCancelAlarm, modifier = Modifier.weight(1f)) { Icon(Icons.Filled.Alarm, null); Spacer(Modifier.width(6.dp)); Text(stringResource(R.string.alarm_minutes, alarmLeadTimeMinutes)) } - } else if (current.getMeanSecondsLeft(tick) > 60) { + } else if (departure.getMeanSecondsLeft(tick) > 60) { OutlinedButton(onClick = { showAlarm = true }, modifier = Modifier.weight(1f)) { Icon(Icons.Filled.Alarm, null); Spacer(Modifier.width(6.dp)); Text(stringResource(R.string.set_alarm)) } } OutlinedButton(onClick = { showClear = true }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.end_trip)) } } } } - item { TripTimeline(current, tick) } + item { TripTimeline(departure, tick) } } } } - if (showAlarm && current != null) { - AlarmPickerDialog(current, timeSource, onDismiss = { showAlarm = false }) { value -> showAlarm = false; onSetAlarm(value) } + if (showAlarm && departure != null) { + AlarmPickerDialog(departure, timeSource, onDismiss = { showAlarm = false }) { value -> showAlarm = false; onSetAlarm(value) } } if (showClear) { AlertDialog(onDismissRequest = { showClear = false }, title = { Text(stringResource(R.string.stop_following_title)) }, text = { Text(stringResource(R.string.stop_following_message)) }, confirmButton = { TextButton(onClick = { showClear = false; onClear() }) { Text(stringResource(R.string.stop_following)) } }, dismissButton = { TextButton(onClick = { showClear = false }) { Text(stringResource(R.string.cancel)) } }) @@ -1249,17 +1442,54 @@ fun TripScreen( confirmButton = { TextButton(onClick = onSilenceAlarm) { Text(stringResource(R.string.silence_alarm)) } }, ) } + if (showFullScreenTrip && departure != null) { + FullScreenTripDialog( + departure = departure, + pair = route ?: departure.getStationPair(), + fare = fare, + timeSource = timeSource, + onDismiss = { showFullScreenTrip = false }, + ) + } } @Composable -private fun TripHero(departure: Departure, pair: StationPair?, fare: String?, timeSource: TimeSource, tick: Long) { +private fun TripHero( + departure: Departure, + pair: StationPair?, + fare: String?, + timeSource: TimeSource, + tick: Long, + onFullScreen: (() -> Unit)? = null, +) { val context = androidx.compose.ui.platform.LocalContext.current val origin = pair?.origin?.getName() ?: departure.origin?.getName().orEmpty() val destination = pair?.destination?.getName() ?: departure.trainDestination?.getName().orEmpty() - val status = tripStatus(context, departure, timeSource, tick) + val status = tripStatus(context, departure, tick) Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer), shape = RoundedCornerShape(24.dp)) { Column(Modifier.padding(20.dp)) { - Text(status, color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + status, + color = MaterialTheme.colorScheme.primary, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + modifier = Modifier.weight(1f), + ) + if (onFullScreen != null) { + IconButton(onClick = onFullScreen) { + Icon( + Icons.Filled.Fullscreen, + contentDescription = stringResource(R.string.full_screen), + tint = MaterialTheme.colorScheme.primary, + ) + } + } + } Text(stringResource(R.string.route_arrow, origin, destination), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(top = 6.dp)) Row(Modifier.padding(top = 16.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { Metric(Icons.Filled.AccessTime, stringResource(R.string.departs), DepartureTextFormatter.estimatedDepartureTime(context, departure).ifBlank { "—" }, Modifier.weight(1f)) @@ -1272,6 +1502,335 @@ private fun TripHero(departure: Departure, pair: StationPair?, fare: String?, ti } } +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FullScreenTripDialog( + departure: Departure, + pair: StationPair?, + fare: String? = null, + timeSource: TimeSource, + onDismiss: () -> Unit, +) { + val tick = rememberSecondTick(timeSource) + val context = androidx.compose.ui.platform.LocalContext.current + val originName = pair?.origin?.getName() ?: departure.origin?.getName().orEmpty() + val destinationName = pair?.destination?.getName() ?: departure.passengerDestination?.getName() ?: departure.trainDestination?.getName().orEmpty() + val countdownText = DepartureTextFormatter.countdown(context, departure, tick) + val departsTime = DepartureTextFormatter.estimatedDepartureTime(context, departure).ifBlank { "—" } + val arrivesTime = DepartureTextFormatter.estimatedArrivalTime(context, departure).ifBlank { "—" } + val platformAndLength = DepartureTextFormatter.trainLengthAndPlatform(context, departure) + + val app = context.applicationContext as? BartRunnerApplication + val nextArrivesTime = remember(departure, tick) { + if (pair != null && app != null) { + val snapshot = app.transitRepository.getLatestSnapshot() + if (snapshot != null) { + val projection = RouteDepartureProjection(pair, app.bartGtfsNetworkSupplier) + val candidateDepartures = projection.project(snapshot).getDepartures() + val nextDeparture = candidateDepartures.firstOrNull { + it.identity != departure.identity && + it.getMeanEstimate() > departure.getMeanEstimate() + } ?: candidateDepartures.getOrNull(1) + nextDeparture?.let { + DepartureTextFormatter.estimatedArrivalTime(context, it).ifBlank { null } + } + } else { + null + } + } else { + null + } + } + + var keepScreenActive by remember { + mutableStateOf(KeepScreenOnPreferences.isKeepScreenOn(context)) + } + + val view = LocalView.current + DisposableEffect(keepScreenActive) { + view.keepScreenOn = keepScreenActive + onDispose { + view.keepScreenOn = false + } + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties( + usePlatformDefaultWidth = false, + decorFitsSystemWindows = false, + ), + ) { + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background, + ) { + Column( + modifier = Modifier + .fillMaxSize() + .systemBarsPadding() + .padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceBetween, + ) { + // Top Header Row: Color-coded Train Icon + Name of the Line & Screen Active / Exit Full Screen Icons + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row( + modifier = Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = Icons.Filled.Train, + contentDescription = null, + tint = lineColor(departure.line), + modifier = Modifier.size(32.dp), + ) + Spacer(Modifier.width(10.dp)) + Text( + text = departure.line?.getDisplayName() ?: stringResource(R.string.trip_in_progress), + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onBackground, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Row(verticalAlignment = Alignment.CenterVertically) { + IconButton( + onClick = { + val newValue = !keepScreenActive + keepScreenActive = newValue + KeepScreenOnPreferences.setKeepScreenOn(context, newValue) + }, + ) { + Icon( + imageVector = Icons.Filled.WbSunny, + contentDescription = stringResource(R.string.keep_screen_active), + modifier = Modifier.size(28.dp), + tint = if (keepScreenActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onBackground.copy(alpha = 0.4f), + ) + } + IconButton(onClick = onDismiss) { + Icon( + imageVector = Icons.Filled.FullscreenExit, + contentDescription = stringResource(R.string.exit_full_screen), + modifier = Modifier.size(36.dp), + tint = MaterialTheme.colorScheme.onBackground, + ) + } + } + } + + // Top Row: 3 Columns (Route, Arrives, If Missed), Justified center-center-center + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + // Column 1: Route Information (Center-justified) + Column( + modifier = Modifier.weight(1f), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.route), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource(R.string.route_arrow, originName, destinationName), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + color = MaterialTheme.colorScheme.onBackground, + ) + if (departure.trainDestination != null && departure.trainDestination != pair?.destination) { + Spacer(Modifier.height(2.dp)) + TrainDestinationLabel( + destination = departure.getTrainDestinationName().orEmpty(), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + // Column 2: Arrival Time (Center-justified) + Column( + modifier = Modifier.weight(1f), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.arrives), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = arrivesTime, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + color = MaterialTheme.colorScheme.onBackground, + ) + } + + // Column 3: Arrival Time If Missed (Center-justified) + Column( + modifier = Modifier.weight(1f), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.if_missed), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = nextArrivesTime ?: "—", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + color = MaterialTheme.colorScheme.onBackground, + ) + } + } + + // CENTER HERO: Countdown Timer ONLY in Large, Friendly Numbers + Card( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 16.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + ), + shape = RoundedCornerShape(32.dp), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 44.dp, horizontal = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Text( + text = countdownText, + style = MaterialTheme.typography.displayLarge.copy( + fontSize = 92.sp, + fontWeight = FontWeight.Black, + lineHeight = 96.sp, + ), + color = MaterialTheme.colorScheme.onPrimaryContainer, + textAlign = TextAlign.Center, + ) + if (platformAndLength.isNotBlank()) { + Spacer(Modifier.height(18.dp)) + Surface( + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.primary, + ) { + Text( + text = platformAndLength, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + } + } + } + + // Bottom Cards: Departs & Fare + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Card( + modifier = Modifier.weight(1f), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + shape = RoundedCornerShape(20.dp), + ) { + Column( + modifier = Modifier.padding(18.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon( + Icons.Filled.AccessTime, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp), + ) + Spacer(Modifier.height(6.dp)) + Text( + text = stringResource(R.string.departs), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = departsTime, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (fare != null) { + Card( + modifier = Modifier.weight(1f), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + shape = RoundedCornerShape(20.dp), + ) { + Column( + modifier = Modifier.padding(18.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon( + painter = painterResource(R.drawable.ic_credit_card), + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp), + ) + Spacer(Modifier.height(6.dp)) + Text( + text = stringResource(R.string.fare), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(2.dp)) + Text( + text = fare, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } + } + } +} + @Composable private fun Metric(icon: ImageVector, label: String, value: String, modifier: Modifier = Modifier) { Row(verticalAlignment = Alignment.CenterVertically, modifier = modifier) { @@ -1423,13 +1982,12 @@ private fun TripTimeline(departure: Departure, tick: Long) { OutlinedCard { Text(stringResource(R.string.detailed_stop_times_unavailable), modifier = Modifier.padding(18.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) } return } - val now = tick - val currentIndex = legs.indexOfFirst { leg -> !legHasPassed(leg, now) }.let { if (it < 0) legs.lastIndex else it } + val currentIndex = legs.indexOfFirst { leg -> !legHasPassed(leg, tick) }.let { if (it < 0) legs.lastIndex else it } Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text(stringResource(R.string.trip_timeline), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) legs.forEachIndexed { index, leg -> - TimelineLeg(leg, index == currentIndex, now) - if (index < legs.lastIndex) ConnectionRow(leg, legs[index + 1], now) + TimelineLeg(leg, index == currentIndex, tick) + if (index < legs.lastIndex) ConnectionRow(leg, legs[index + 1]) } } } @@ -1498,7 +2056,7 @@ private fun StationTimelineRow(stop: TripStop, departure: Boolean, now: Long, co val name = stop.station?.getName().orEmpty() val displayTime = if (departure) stop.departureTime else stop.arrivalTime val scheduleDetails = DepartureTextFormatter.stopSchedulePresentation(context, stop, departure) - val reached = displayTime > 0 && displayTime <= now + val reached = displayTime in 1..now Row(Modifier.fillMaxWidth().height(54.dp), verticalAlignment = Alignment.CenterVertically) { Box(Modifier.width(24.dp).fillMaxHeight(), contentAlignment = Alignment.Center) { if (!isFirst) { @@ -1534,7 +2092,7 @@ private fun StationTimelineRow(stop: TripStop, departure: Boolean, now: Long, co } @Composable -private fun ConnectionRow(arriving: TripLeg, next: TripLeg, now: Long) { +private fun ConnectionRow(arriving: TripLeg, next: TripLeg) { val arrival = arriving.stops.lastOrNull()?.arrivalTime ?: arriving.arrivalTime val departure = next.stops.firstOrNull()?.departureTime ?: next.departureTime val margin = departure - arrival @@ -1609,8 +2167,8 @@ fun SystemMapScreen(onBack: () -> Unit) { } Scaffold(topBar = { TopAppBar(navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) } }, title = { Text(stringResource(R.string.system_map_title), fontWeight = FontWeight.Bold) }) }, contentWindowInsets = WindowInsets.safeDrawing) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { - androidx.compose.foundation.Image( - androidx.compose.ui.res.painterResource(R.drawable.map), + Image( + painterResource(R.drawable.map), stringResource(R.string.system_map_title), Modifier .fillMaxSize() @@ -1659,7 +2217,7 @@ private fun lineColor(line: Line?): Color = when (line) { else -> Color(0xFF546E7A) } -private fun tripStatus(context: Context, departure: Departure, timeSource: TimeSource, now: Long): String { +private fun tripStatus(context: Context, departure: Departure, now: Long): String { if (departure.isCanceled()) return context.getString(R.string.trip_canceled) if (!departure.hasDeparted(now)) return context.getString(R.string.trip_leaves_in, DepartureTextFormatter.countdown(context, departure, now)) departure.tripLegs.forEachIndexed { index, leg -> @@ -1681,7 +2239,7 @@ private fun tripStatus(context: Context, departure: Departure, timeSource: TimeS return context.getString(R.string.trip_current_train) } -private fun legHasPassed(leg: TripLeg, now: Long): Boolean = if (leg.stops.isNotEmpty()) leg.stops.all { it.arrivalTime > 0 && it.arrivalTime <= now } else leg.arrivalTime > 0 && leg.arrivalTime <= now +private fun legHasPassed(leg: TripLeg, now: Long): Boolean = if (leg.stops.isNotEmpty()) leg.stops.all { it.arrivalTime in 1..now } else leg.arrivalTime in 1..now private fun etaText(context: Context, time: Long, now: Long): String { if (time <= 0) return context.getString(R.string.eta_unavailable) @@ -1698,7 +2256,7 @@ internal fun rememberSecondTick(timeSource: TimeSource): Long { LaunchedEffect(timeSource) { while (isActive) { tick = timeSource.nowMillis() - delay(1000) + delay(1000L) } } return tick diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 845a809..4c482c4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -8,6 +8,9 @@ Offline — using stored schedules. Realtime updates and service alerts are unavailable. Connection status Back + Show transfers + Default transfer view + Show routes requiring transfers by default when viewing upcoming trains. Saved trips Add Drag to reorder @@ -113,7 +116,16 @@ Canceled At station %1$dm %2$ds + %1$dh %2$dm %3$ds Estimated arrival unknown + Full screen + Exit full screen + Home station + Default origin in Trip Planner and Add Route. + Keep screen active + Keep screen awake while full-screen ride view is open. + If missed + Route Arrived at destination Arrives ~%1$s (%2$d min) Arrives ~%1$s (1 min) diff --git a/app/src/main/res/xml/automotive_app_desc.xml b/app/src/main/res/xml/automotive_app_desc.xml new file mode 100644 index 0000000..0fb852c --- /dev/null +++ b/app/src/main/res/xml/automotive_app_desc.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/test/kotlin/in/izyum/bart/activities/DeparturesViewModelTest.kt b/app/src/test/kotlin/in/izyum/bart/activities/DeparturesViewModelTest.kt index ed0aa74..4f1de37 100644 --- a/app/src/test/kotlin/in/izyum/bart/activities/DeparturesViewModelTest.kt +++ b/app/src/test/kotlin/in/izyum/bart/activities/DeparturesViewModelTest.kt @@ -29,7 +29,30 @@ class DeparturesViewModelTest { assertEquals(0, viewModel.getState().departures.size) } - private fun departure(tripId: String, estimate: Long): Departure = Departure.builder() + @Test + fun togglingShowTransfersFiltersTransferDepartures() { + val viewModel = DeparturesViewModel { 900_000L } + val directDeparture = departure("trip-1", 1_000_000L) + val transferDeparture = departure("trip-2", 1_060_000L, requiresTransfer = true) + + viewModel.replace(listOf(directDeparture, transferDeparture)) + + assertEquals(2, viewModel.getDepartures().size) + assertEquals(true, viewModel.getState().showTransfers) + + viewModel.toggleShowTransfers() + + assertEquals(1, viewModel.getDepartures().size) + assertEquals("trip-1", viewModel.getDepartures()[0].tripLegs[0].tripId) + assertEquals(false, viewModel.getState().showTransfers) + + viewModel.toggleShowTransfers() + + assertEquals(2, viewModel.getDepartures().size) + assertEquals(true, viewModel.getState().showTransfers) + } + + private fun departure(tripId: String, estimate: Long, requiresTransfer: Boolean = false): Departure = Departure.builder() .setOrigin(Station.CAST) .setTrainDestination(Station.MLPT) .setLine(Line.ORANGE) @@ -37,15 +60,23 @@ class DeparturesViewModelTest { .setPlatform("1") .setMinEstimate(estimate) .setMaxEstimate(estimate + 60_000L) - .setTripLegs(listOf(TripLeg( - Line.ORANGE, - Station.CAST, - Station.MLPT, - Station.MLPT, - tripId, - estimate, - estimate + 30 * 60_000L, - emptyList(), - ))) + .setRequiresTransfer(requiresTransfer) + .setTripLegs(if (requiresTransfer) { + listOf( + TripLeg(Line.ORANGE, Station.CAST, Station.BAYF, Station.BAYF, tripId + "-1", estimate, estimate + 15 * 60_000L, emptyList()), + TripLeg(Line.RED, Station.BAYF, Station.MLPT, Station.MLPT, tripId + "-2", estimate + 16 * 60_000L, estimate + 30 * 60_000L, emptyList()) + ) + } else { + listOf(TripLeg( + Line.ORANGE, + Station.CAST, + Station.MLPT, + Station.MLPT, + tripId, + estimate, + estimate + 30 * 60_000L, + emptyList(), + )) + }) .build() } diff --git a/app/src/test/kotlin/in/izyum/bart/backend/ScheduleTest.kt b/app/src/test/kotlin/in/izyum/bart/backend/ScheduleTest.kt index a2e64c6..17623ae 100644 --- a/app/src/test/kotlin/in/izyum/bart/backend/ScheduleTest.kt +++ b/app/src/test/kotlin/in/izyum/bart/backend/ScheduleTest.kt @@ -10,7 +10,6 @@ import com.google.transit.realtime.GtfsRealtime import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test -import java.time.LocalDate import java.time.ZoneId class ScheduleTest { diff --git a/app/src/test/kotlin/in/izyum/bart/car/BartCarAppTest.kt b/app/src/test/kotlin/in/izyum/bart/car/BartCarAppTest.kt new file mode 100644 index 0000000..fa12be9 --- /dev/null +++ b/app/src/test/kotlin/in/izyum/bart/car/BartCarAppTest.kt @@ -0,0 +1,17 @@ +package `in`.izyum.bart.car + +import org.junit.Assert.assertNotNull +import org.junit.Test + +class BartCarAppTest { + @Test + fun carPreferencesIsNotNull() { + assertNotNull(CarPreferences) + } + + @Test + fun carNotificationHelperIsNotNull() { + assertNotNull(CarNotificationHelper) + } +} + diff --git a/build.gradle b/build.gradle index 5f97c48..e5330fd 100644 --- a/build.gradle +++ b/build.gradle @@ -23,7 +23,7 @@ tasks.register("verifyCompatibility") { throw new GradleException("JDK 17 or newer is required to build this project") } [ - agp: [actual: libs.versions.agp.get(), required: "9.4.0"], + agp: [actual: libs.versions.agp.get(), required: "9.3.0"], kotlin: [actual: libs.versions.kotlin.get(), required: "2.4.20"], androidxCore: [actual: libs.versions.androidxCore.get(), required: "1.19.0"], ].each { name, version -> diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 21206b9..91f4038 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,5 +1,5 @@ [versions] -agp = "9.4.0" +agp = "9.3.0" kotlin = "2.4.20" junit = "4.13.2" androidxTestJunit = "1.3.0" @@ -18,6 +18,7 @@ activityCompose = "1.13.0" composeCompiler = "2.4.20" room = "2.8.4" work = "2.11.0" +carApp = "1.7.0" [plugins] android-application = { id = "com.android.application", version.ref = "agp" } @@ -52,3 +53,5 @@ androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } androidx-compose-foundation = { module = "androidx.compose.foundation:foundation" } androidx-compose-material3 = { module = "androidx.compose.material3:material3" } androidx-compose-material-icons = { module = "androidx.compose.material:material-icons-extended" } +androidx-car-app = { module = "androidx.car.app:app", version.ref = "carApp" } +androidx-car-app-testing = { module = "androidx.car.app:app-testing", version.ref = "carApp" }