diff --git a/app/src/main/java/com/sameerasw/airsync/data/local/DataStoreManager.kt b/app/src/main/java/com/sameerasw/airsync/data/local/DataStoreManager.kt index 8ee9920c..1ab1cb72 100644 --- a/app/src/main/java/com/sameerasw/airsync/data/local/DataStoreManager.kt +++ b/app/src/main/java/com/sameerasw/airsync/data/local/DataStoreManager.kt @@ -105,6 +105,7 @@ class DataStoreManager(private val context: Context) { private val BLE_SYNC_ENABLED = booleanPreferencesKey("ble_sync_enabled") private val BLE_AUTO_CONNECT_ENABLED = booleanPreferencesKey("ble_auto_connect_enabled") private val NOTIFY_ON_CRASH = booleanPreferencesKey("notify_on_crash") + private val APP_ENABLED = booleanPreferencesKey("app_enabled") private const val NETWORK_DEVICES_PREFIX = "network_device_" private const val NETWORK_CONNECTIONS_PREFIX = "network_connections_" @@ -1060,4 +1061,11 @@ class DataStoreManager(private val context: Context) { fun getBleAutoConnectEnabled(): Flow = context.dataStore.data.map { it[BLE_AUTO_CONNECT_ENABLED] ?: true } + + suspend fun setAppEnabled(enabled: Boolean) { + context.dataStore.edit { it[APP_ENABLED] = enabled } + } + + fun getAppEnabled(): Flow = + context.dataStore.data.map { it[APP_ENABLED] != false } } diff --git a/app/src/main/java/com/sameerasw/airsync/data/repository/AirSyncRepositoryImpl.kt b/app/src/main/java/com/sameerasw/airsync/data/repository/AirSyncRepositoryImpl.kt index ce4df9e9..69c69737 100644 --- a/app/src/main/java/com/sameerasw/airsync/data/repository/AirSyncRepositoryImpl.kt +++ b/app/src/main/java/com/sameerasw/airsync/data/repository/AirSyncRepositoryImpl.kt @@ -313,4 +313,12 @@ class AirSyncRepositoryImpl( override fun getNotifyOnCrashEnabled(): Flow { return dataStoreManager.getNotifyOnCrashEnabled() } + + override suspend fun setAppEnabled(enabled: Boolean) { + dataStoreManager.setAppEnabled(enabled) + } + + override fun getAppEnabled(): Flow { + return dataStoreManager.getAppEnabled() + } } \ No newline at end of file diff --git a/app/src/main/java/com/sameerasw/airsync/domain/model/UiState.kt b/app/src/main/java/com/sameerasw/airsync/domain/model/UiState.kt index 9c40b45d..cc9a5059 100644 --- a/app/src/main/java/com/sameerasw/airsync/domain/model/UiState.kt +++ b/app/src/main/java/com/sameerasw/airsync/domain/model/UiState.kt @@ -52,5 +52,6 @@ data class UiState( val isQuickShareEnabled: Boolean = false, val isFileAccessEnabled: Boolean = true, val isNotifyOnCrashEnabled: Boolean = true, + val isAppEnabled: Boolean = true, val bleConnectionState: com.sameerasw.airsync.data.ble.BleGattServer.BleConnectionState = com.sameerasw.airsync.data.ble.BleGattServer.BleConnectionState.DISCONNECTED ) \ No newline at end of file diff --git a/app/src/main/java/com/sameerasw/airsync/domain/repository/AirSyncRepository.kt b/app/src/main/java/com/sameerasw/airsync/domain/repository/AirSyncRepository.kt index 9fb01cb0..373c7f78 100644 --- a/app/src/main/java/com/sameerasw/airsync/domain/repository/AirSyncRepository.kt +++ b/app/src/main/java/com/sameerasw/airsync/domain/repository/AirSyncRepository.kt @@ -140,4 +140,8 @@ interface AirSyncRepository { suspend fun setNotifyOnCrashEnabled(enabled: Boolean) fun getNotifyOnCrashEnabled(): Flow + + // Global Active Toggle + suspend fun setAppEnabled(enabled: Boolean) + fun getAppEnabled(): Flow } \ No newline at end of file diff --git a/app/src/main/java/com/sameerasw/airsync/presentation/ui/screens/AirSyncMainScreen.kt b/app/src/main/java/com/sameerasw/airsync/presentation/ui/screens/AirSyncMainScreen.kt index 75a7ab95..b9bb7d25 100644 --- a/app/src/main/java/com/sameerasw/airsync/presentation/ui/screens/AirSyncMainScreen.kt +++ b/app/src/main/java/com/sameerasw/airsync/presentation/ui/screens/AirSyncMainScreen.kt @@ -31,8 +31,12 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.Image import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.ui.text.style.TextAlign import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.pager.HorizontalPager @@ -108,6 +112,7 @@ import com.sameerasw.airsync.presentation.ui.components.cards.LastConnectedDevic import com.sameerasw.airsync.presentation.ui.components.cards.ManualConnectionCard import com.sameerasw.airsync.presentation.ui.components.cards.RateAppCard import com.sameerasw.airsync.presentation.ui.components.cards.RemoteFunctionsCard +import com.sameerasw.airsync.presentation.ui.components.cards.IconToggleItem import com.sameerasw.airsync.presentation.ui.components.dialogs.ConnectionDialog import com.sameerasw.airsync.presentation.ui.components.sheets.HelpSupportBottomSheet import com.sameerasw.airsync.presentation.ui.composables.WelcomeScreen @@ -768,102 +773,90 @@ fun AirSyncMainScreen( verticalArrangement = Arrangement.spacedBy(24.dp) ) { - Spacer( - modifier = Modifier - .height(topSpacing) - .fillMaxWidth() - ) - - RoundedCardContainer { - - // Rating Prompt Card - AnimatedVisibility( - visible = uiState.shouldShowRatingPrompt, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() + if (!uiState.isAppEnabled) { + // AirSync is Off landing page + Column( + modifier = Modifier + .fillMaxWidth() + .padding(top = 60.dp) + .padding(horizontal = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp) ) { - RateAppCard( - onDismiss = { viewModel.setRatingCardDismissed() }, - onRate = { viewModel.setAppRated() } + Image( + painter = painterResource(id = R.drawable.ic_launcher_monochrome), + contentDescription = null, + modifier = Modifier.size(130.dp), + colorFilter = androidx.compose.ui.graphics.ColorFilter.tint( + MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.35f) + ) ) - } - - // Connection Status Card - ConnectionStatusCard( - isConnected = uiState.isConnected, - isConnecting = uiState.isConnecting, - onDisconnect = { disconnect() }, - connectedDevice = uiState.lastConnectedDevice, - lastConnected = uiState.lastConnectedDevice != null, - uiState = uiState, - ) + Text( + text = "AirSync is Off", + style = MaterialTheme.typography.headlineMedium, + fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) - // Remote Functions Card (Lock Screen, etc.) - AnimatedVisibility( - visible = uiState.isConnected, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() - ) { - RemoteFunctionsCard( - onRemoteAction = { sendRemoteAction(it) } + Text( + text = "Turn on AirSync to start scanning and connecting to your Mac.", + textAlign = TextAlign.Center, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp) ) + + Spacer(modifier = Modifier.height(16.dp)) + + Button( + onClick = { + HapticUtil.performClick(haptics) + viewModel.setAppEnabled(context, true) + }, + shape = RoundedCornerShape(16.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary + ), + modifier = Modifier + .height(56.dp) + .fillMaxWidth(0.8f) + ) { + Icon( + painter = painterResource(id = R.drawable.rounded_sync_desktop_24), + contentDescription = null, + modifier = Modifier.size(24.dp) + ) + Spacer(modifier = Modifier.size(8.dp)) + Text( + "Turn On AirSync", + style = MaterialTheme.typography.titleMedium, + fontWeight = androidx.compose.ui.text.font.FontWeight.Bold + ) + } } - } + } else { + Spacer( + modifier = Modifier + .height(topSpacing) + .fillMaxWidth() + ) - RoundedCardContainer { - // Nearby Devices (UDP Discovery) - val discoveredDevices by viewModel.discoveredDevices.collectAsState() + RoundedCardContainer { - // Last Connected Device Section - AnimatedVisibility( - visible = !uiState.isConnected && uiState.lastConnectedDevice != null, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() - ) { - uiState.lastConnectedDevice?.let { device -> - LastConnectedDeviceCard( - device = device, - isAutoReconnectEnabled = uiState.isAutoReconnectEnabled, - onToggleAutoReconnect = { enabled -> - viewModel.setAutoReconnectEnabled( - enabled - ) - }, - onQuickConnect = { - // Check if we can use network-aware connection first - val networkAwareDevice = - viewModel.getNetworkAwareLastConnectedDevice() - if (networkAwareDevice != null) { - // Use network-aware device IP for current network - viewModel.updateIpAddress(networkAwareDevice.ipAddress) - viewModel.updatePort(networkAwareDevice.port) - connect( - ipAddress = networkAwareDevice.ipAddress, - port = networkAwareDevice.port, - symmetricKey = networkAwareDevice.symmetricKey - ) - } else { - // Fallback to legacy stored device - viewModel.updateIpAddress(device.ipAddress) - viewModel.updatePort(device.port) - viewModel.updateSymmetricKey(device.symmetricKey) - connect( - ipAddress = device.ipAddress, - port = device.port, - symmetricKey = device.symmetricKey - ) - } - } + // Rating Prompt Card + AnimatedVisibility( + visible = uiState.shouldShowRatingPrompt, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + RateAppCard( + onDismiss = { viewModel.setRatingCardDismissed() }, + onRate = { viewModel.setAppRated() } ) } - } - AnimatedVisibility( - visible = !uiState.isConnected, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() - ) { + // Normal toggle on top Card( modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.extraSmall, @@ -871,203 +864,325 @@ fun AirSyncMainScreen( containerColor = MaterialTheme.colorScheme.surfaceBright ) ) { - Column( + Row( modifier = Modifier .fillMaxWidth() - .padding(16.dp) + .clickable { + HapticUtil.performClick(haptics) + viewModel.setAppEnabled(context, false) + } + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(bottom = 12.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically + Icon( + painter = painterResource(id = R.drawable.rounded_sync_desktop_24), + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.primary + ) + + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.Center ) { Text( - text = "Available Devices", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.primary + text = "AirSync Active", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface ) + } + + Switch( + checked = true, + onCheckedChange = { enabled -> + HapticUtil.performClick(haptics) + viewModel.setAppEnabled(context, enabled) + } + ) + } + } + + // Connection Status Card + ConnectionStatusCard( + isConnected = uiState.isConnected, + isConnecting = uiState.isConnecting, + onDisconnect = { disconnect() }, + connectedDevice = uiState.lastConnectedDevice, + lastConnected = uiState.lastConnectedDevice != null, + uiState = uiState, + ) + + // Remote Functions Card (Lock Screen, etc.) + AnimatedVisibility( + visible = uiState.isConnected, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + RemoteFunctionsCard( + onRemoteAction = { sendRemoteAction(it) } + ) + } + } - Switch( - checked = uiState.isDeviceDiscoveryEnabled, - onCheckedChange = { enabled -> - HapticUtil.performClick(haptics) - viewModel.setDeviceDiscoveryEnabled( - context, - enabled + RoundedCardContainer { + // Nearby Devices (UDP Discovery) + val discoveredDevices by viewModel.discoveredDevices.collectAsState() + + // Last Connected Device Section + AnimatedVisibility( + visible = !uiState.isConnected && uiState.lastConnectedDevice != null, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + uiState.lastConnectedDevice?.let { device -> + LastConnectedDeviceCard( + device = device, + isAutoReconnectEnabled = uiState.isAutoReconnectEnabled, + onToggleAutoReconnect = { enabled -> + viewModel.setAutoReconnectEnabled( + enabled + ) + }, + onQuickConnect = { + // Check if we can use network-aware connection first + val networkAwareDevice = + viewModel.getNetworkAwareLastConnectedDevice() + if (networkAwareDevice != null) { + // Use network-aware device IP for current network + viewModel.updateIpAddress(networkAwareDevice.ipAddress) + viewModel.updatePort(networkAwareDevice.port) + connect( + ipAddress = networkAwareDevice.ipAddress, + port = networkAwareDevice.port, + symmetricKey = networkAwareDevice.symmetricKey ) - }, - thumbContent = if (uiState.isDeviceDiscoveryEnabled) { - { - Icon( - painter = painterResource(R.drawable.rounded_android_wifi_3_bar_24), - contentDescription = null, - modifier = Modifier.size( - SwitchDefaults.IconSize - ), - ) - } - } else null - ) - } + } else { + // Fallback to legacy stored device + viewModel.updateIpAddress(device.ipAddress) + viewModel.updatePort(device.port) + viewModel.updateSymmetricKey(device.symmetricKey) + connect( + ipAddress = device.ipAddress, + port = device.port, + symmetricKey = device.symmetricKey + ) + } + } + ) + } + } - AnimatedVisibility( - visible = uiState.isDeviceDiscoveryEnabled, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() + AnimatedVisibility( + visible = !uiState.isConnected, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.extraSmall, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceBright + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) ) { - Column { - if (discoveredDevices.isEmpty()) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy( - 4.dp + Row( + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 12.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Available Devices", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary + ) + + Switch( + checked = uiState.isDeviceDiscoveryEnabled, + onCheckedChange = { enabled -> + HapticUtil.performClick(haptics) + viewModel.setDeviceDiscoveryEnabled( + context, + enabled ) - ) { - LoadingIndicator() - - Text( - text = "Scanning...", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding( - vertical = 8.dp + }, + thumbContent = if (uiState.isDeviceDiscoveryEnabled) { + { + Icon( + painter = painterResource(R.drawable.rounded_android_wifi_3_bar_24), + contentDescription = null, + modifier = Modifier.size( + SwitchDefaults.IconSize + ), ) - ) - } - } + } + } else null + ) + } - discoveredDevices.forEachIndexed { index, device -> - if (index > 0) { - Spacer(modifier = Modifier.height(8.dp)) + AnimatedVisibility( + visible = uiState.isDeviceDiscoveryEnabled, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + Column { + if (discoveredDevices.isEmpty()) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy( + 4.dp + ) + ) { + LoadingIndicator() + + Text( + text = "Scanning...", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding( + vertical = 8.dp + ) + ) + } } - Row( - modifier = Modifier - .fillMaxWidth() - .clip(MaterialTheme.shapes.medium) - .background(MaterialTheme.colorScheme.surfaceContainerHigh) - .clickable { - HapticUtil.performClick( - haptics - ) - val bestIp = device.getBestIp() - val devicePort = device.port.toString() - val deviceName = device.name - - viewModel.updateIpAddress(bestIp) - viewModel.updatePort(devicePort) - viewModel.updateManualPcName(deviceName) - - val savedKey = viewModel.getSymmetricKeyForDevice(deviceName) - if (savedKey != null) { - viewModel.updateSymmetricKey(savedKey) - } - - connect( - deviceId = device.id, - ipAddress = bestIp, - port = devicePort, - symmetricKey = savedKey ?: uiState.symmetricKey - ) - } - .padding( - horizontal = 16.dp, - vertical = 12.dp - ), - verticalAlignment = Alignment.CenterVertically - ) { - Icon( - painter = painterResource(R.drawable.apple), - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) - Spacer(modifier = Modifier.width(12.dp)) - Column { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = device.name, - style = MaterialTheme.typography.bodyLarge - ) - Spacer( - modifier = Modifier.width( - 8.dp + discoveredDevices.forEachIndexed { index, device -> + if (index > 0) { + Spacer(modifier = Modifier.height(8.dp)) + } + + Row( + modifier = Modifier + .fillMaxWidth() + .clip(MaterialTheme.shapes.medium) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .clickable { + HapticUtil.performClick( + haptics ) - ) - if (device.hasLocalIp()) { - Icon( - painter = painterResource( - R.drawable.rounded_android_wifi_3_bar_24 - ), - contentDescription = "Wi-Fi", - modifier = Modifier.size( - 14.dp - ), - tint = MaterialTheme.colorScheme.primary + val bestIp = device.getBestIp() + val devicePort = device.port.toString() + val deviceName = device.name + + viewModel.updateIpAddress(bestIp) + viewModel.updatePort(devicePort) + viewModel.updateManualPcName(deviceName) + + val savedKey = viewModel.getSymmetricKeyForDevice(deviceName) + if (savedKey != null) { + viewModel.updateSymmetricKey(savedKey) + } + + connect( + deviceId = device.id, + ipAddress = bestIp, + port = devicePort, + symmetricKey = savedKey ?: uiState.symmetricKey ) } - if (device.hasTailscaleIp()) { - if (device.hasLocalIp()) Spacer( + .padding( + horizontal = 16.dp, + vertical = 12.dp + ), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + painter = painterResource(R.drawable.apple), + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(12.dp)) + Column { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = device.name, + style = MaterialTheme.typography.bodyLarge + ) + Spacer( modifier = Modifier.width( - 4.dp + 8.dp ) ) - Icon( - painter = painterResource( - R.drawable.rounded_network_node_24 - ), - contentDescription = "Tailscale", - modifier = Modifier.size( - 14.dp - ), - tint = MaterialTheme.colorScheme.secondary - ) - } - } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp) - ) { - Text( - text = "${device.getBestIp()}:${device.port}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Box( - modifier = Modifier - .clip(RoundedCornerShape(4.dp)) - .background( - if (device.discoverySource == DiscoverySource.MDNS) - MaterialTheme.colorScheme.primaryContainer - else - MaterialTheme.colorScheme.secondaryContainer + if (device.hasLocalIp()) { + Icon( + painter = painterResource( + R.drawable.rounded_android_wifi_3_bar_24 + ), + contentDescription = "Wi-Fi", + modifier = Modifier.size( + 14.dp + ), + tint = MaterialTheme.colorScheme.primary + ) + } + if (device.hasTailscaleIp()) { + if (device.hasLocalIp()) Spacer( + modifier = Modifier.width( + 4.dp + ) ) - .padding(horizontal = 4.dp, vertical = 1.dp) + Icon( + painter = painterResource( + R.drawable.rounded_network_node_24 + ), + contentDescription = "Tailscale", + modifier = Modifier.size( + 14.dp + ), + tint = MaterialTheme.colorScheme.secondary + ) + } + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) ) { Text( - text = if (device.discoverySource == DiscoverySource.MDNS) "mDNS" else "UDP", - style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp), - color = if (device.discoverySource == DiscoverySource.MDNS) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSecondaryContainer + text = "${device.getBestIp()}:${device.port}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant ) + Box( + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background( + if (device.discoverySource == DiscoverySource.MDNS) + MaterialTheme.colorScheme.primaryContainer + else + MaterialTheme.colorScheme.secondaryContainer + ) + .padding(horizontal = 4.dp, vertical = 1.dp) + ) { + Text( + text = if (device.discoverySource == DiscoverySource.MDNS) "mDNS" else "UDP", + style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp), + color = if (device.discoverySource == DiscoverySource.MDNS) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSecondaryContainer + ) + } } } - } - Spacer(modifier = Modifier.weight(1f)) - if (uiState.isConnecting && uiState.connectingDeviceId == device.id) { - CircularWavyProgressIndicator( - modifier = Modifier.size(20.dp) - ) - } else { - Icon( - Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = "Connect", - modifier = Modifier.size(20.dp), - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) + Spacer(modifier = Modifier.weight(1f)) + if (uiState.isConnecting && uiState.connectingDeviceId == device.id) { + CircularWavyProgressIndicator( + modifier = Modifier.size(20.dp) + ) + } else { + Icon( + Icons.AutoMirrored.Filled.ArrowForward, + contentDescription = "Connect", + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } } } } @@ -1075,35 +1190,35 @@ fun AirSyncMainScreen( } } } - } - AnimatedVisibility( - visible = !uiState.isConnected, - enter = expandVertically() + fadeIn(), - exit = shrinkVertically() + fadeOut() - ) { - Column { - ManualConnectionCard( - isConnected = uiState.isConnected, - lastConnected = uiState.lastConnectedDevice != null, - uiState = uiState, - onIpChange = { viewModel.updateIpAddress(it) }, - onPortChange = { viewModel.updatePort(it) }, - onPcNameChange = { viewModel.updateManualPcName(it) }, - onIsPlusChange = { viewModel.updateManualIsPlus(it) }, - onSymmetricKeyChange = { - viewModel.updateSymmetricKey( - it - ) - }, - onConnect = { viewModel.prepareForManualConnection() }, - onQrScanClick = { launchScanner(context) } - ) + AnimatedVisibility( + visible = !uiState.isConnected, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + Column { + ManualConnectionCard( + isConnected = uiState.isConnected, + lastConnected = uiState.lastConnectedDevice != null, + uiState = uiState, + onIpChange = { viewModel.updateIpAddress(it) }, + onPortChange = { viewModel.updatePort(it) }, + onPcNameChange = { viewModel.updateManualPcName(it) }, + onIsPlusChange = { viewModel.updateManualIsPlus(it) }, + onSymmetricKeyChange = { + viewModel.updateSymmetricKey( + it + ) + }, + onConnect = { viewModel.prepareForManualConnection() }, + onQrScanClick = { launchScanner(context) } + ) + } } } - } - Spacer(modifier = Modifier.height(100.dp)) + Spacer(modifier = Modifier.height(100.dp)) + } } } diff --git a/app/src/main/java/com/sameerasw/airsync/presentation/viewmodel/AirSyncViewModel.kt b/app/src/main/java/com/sameerasw/airsync/presentation/viewmodel/AirSyncViewModel.kt index 97f4af08..a0d1befc 100644 --- a/app/src/main/java/com/sameerasw/airsync/presentation/viewmodel/AirSyncViewModel.kt +++ b/app/src/main/java/com/sameerasw/airsync/presentation/viewmodel/AirSyncViewModel.kt @@ -390,6 +390,7 @@ class AirSyncViewModel( val isBlurProblematic = DeviceInfoUtil.isBlurProblematicDevice() val isQuickShareEnabled = repository.isQuickShareEnabled().first() val isNotifyOnCrashEnabled = repository.getNotifyOnCrashEnabled().first() + val isAppEnabled = repository.getAppEnabled().first() // Replicate Essentials logic for initial state val isBlurEnabled = isBlurEnabledSetting && !isPowerSaveMode && !isBlurProblematic @@ -452,7 +453,8 @@ class AirSyncViewModel( isBlurEnabled = isBlurEnabled, isOnboardingCompleted = !isFirstRun, isQuickShareEnabled = isQuickShareEnabled, - isNotifyOnCrashEnabled = isNotifyOnCrashEnabled + isNotifyOnCrashEnabled = isNotifyOnCrashEnabled, + isAppEnabled = isAppEnabled ) updateRatingPromptDisplay() @@ -748,6 +750,17 @@ class AirSyncViewModel( } } + fun setAppEnabled(context: Context, enabled: Boolean) { + _uiState.value = _uiState.value.copy(isAppEnabled = enabled) + viewModelScope.launch { + repository.setAppEnabled(enabled) + if (!enabled) { + WebSocketUtil.disconnect(context) + } + ServiceManager.updateServiceState(context) + } + } + fun setQuickShareEnabled(context: Context, enabled: Boolean) { _uiState.value = _uiState.value.copy(isQuickShareEnabled = enabled) viewModelScope.launch { diff --git a/app/src/main/java/com/sameerasw/airsync/service/AirSyncService.kt b/app/src/main/java/com/sameerasw/airsync/service/AirSyncService.kt index f6d6afd0..b5b60f51 100644 --- a/app/src/main/java/com/sameerasw/airsync/service/AirSyncService.kt +++ b/app/src/main/java/com/sameerasw/airsync/service/AirSyncService.kt @@ -25,6 +25,7 @@ import com.sameerasw.airsync.utils.ShortcutUtil import com.sameerasw.airsync.utils.discovery.DiscoveryOrchestrator import com.sameerasw.airsync.utils.WebDavServer import com.sameerasw.airsync.utils.WebSocketUtil +import com.sameerasw.airsync.utils.ServiceManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -88,6 +89,22 @@ class AirSyncService : Service() { Log.d(TAG, "AirSyncService started with action: ${intent?.action}") val action = intent?.action + + // Immediately stop self if the service should not run + val shouldRun = runBlocking { ServiceManager.shouldServiceRun(applicationContext) } + if (!shouldRun && action != ACTION_STOP_SYNC) { + Log.d(TAG, "Service started but should not run based on settings. Stopping.") + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + try { + startForeground(NOTIFICATION_ID, buildNotification()) + } catch (e: Exception) { + Log.e(TAG, "Error calling startForeground on early stop", e) + } + } + stopSelf() + return START_NOT_STICKY + } + when (action) { ACTION_START_SCANNING -> startScanning() ACTION_START_SYNC -> { @@ -447,6 +464,12 @@ class AirSyncService : Service() { if (isRunning()) { context.startService(intent) } else { + val shouldRun = runBlocking { ServiceManager.shouldServiceRun(context) } + if (!shouldRun && intent.action != ACTION_STOP_SYNC) { + Log.d(TAG, "Service should not run based on settings. Skipping startAction.") + return + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent) } else { diff --git a/app/src/main/java/com/sameerasw/airsync/utils/ServiceManager.kt b/app/src/main/java/com/sameerasw/airsync/utils/ServiceManager.kt index f8aa4b6a..41a0d437 100644 --- a/app/src/main/java/com/sameerasw/airsync/utils/ServiceManager.kt +++ b/app/src/main/java/com/sameerasw/airsync/utils/ServiceManager.kt @@ -19,6 +19,11 @@ object ServiceManager { */ suspend fun shouldServiceRun(context: Context): Boolean { val dataStore = DataStoreManager.getInstance(context) + val isAppEnabled = dataStore.getAppEnabled().first() + if (!isAppEnabled) { + return false + } + val isConnected = WebSocketUtil.isConnected() val isAutoReconnectEnabled = dataStore.getAutoReconnectEnabled().first() val isDiscoveryEnabled = dataStore.getDeviceDiscoveryEnabled().first() diff --git a/app/src/main/java/com/sameerasw/airsync/utils/WebSocketUtil.kt b/app/src/main/java/com/sameerasw/airsync/utils/WebSocketUtil.kt index 57b95343..4d55e6dc 100644 --- a/app/src/main/java/com/sameerasw/airsync/utils/WebSocketUtil.kt +++ b/app/src/main/java/com/sameerasw/airsync/utils/WebSocketUtil.kt @@ -125,6 +125,15 @@ object WebSocketUtil { // Cache application context for future cleanup even if callers don't pass context on disconnect appContext = context.applicationContext + val isAppEnabled = kotlinx.coroutines.runBlocking { + com.sameerasw.airsync.data.local.DataStoreManager.getInstance(context).getAppEnabled().first() + } + if (!isAppEnabled) { + Log.d(TAG, "Skipping connection attempt: AirSync is globally disabled.") + onConnectionStatus?.invoke(false) + return + } + if (isConnecting.get() || isConnected.get()) { Log.d(TAG, "Already connected or connecting") return @@ -1023,6 +1032,14 @@ object WebSocketUtil { fun requestAutoReconnect(context: Context) { // Only if not already connected or connecting if (isConnected() || isConnecting.get()) return + + val isAppEnabled = kotlinx.coroutines.runBlocking { + com.sameerasw.airsync.data.local.DataStoreManager.getInstance(context).getAppEnabled().first() + } + if (!isAppEnabled) { + Log.d(TAG, "Skipping auto-reconnect request: AirSync is globally disabled.") + return + } tryStartAutoReconnect(context) } } diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 00000000..6c1139ec --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,12 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/73bcfb608d1fde9fb62e462f834a3299/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/846ee0d876d26a26f37aa1ce8de73224/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/9482ddec596298c84656d31d16652665/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/39701d92e1756bb2f141eb67cd4c660e/redirect +toolchainVersion=21 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c0..b1b8ef56 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 66fe04e3..a9db1155 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,9 @@ -#Mon Jul 28 23:54:01 IST 2025 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c..249efbb0 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,114 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index ac1b06f9..8508ef68 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,22 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +43,15 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +59,24 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL%