diff --git a/core/localization/src/androidMain/res/values-de/strings.xml b/core/localization/src/androidMain/res/values-de/strings.xml index 307566af5..fd6d9c234 100644 --- a/core/localization/src/androidMain/res/values-de/strings.xml +++ b/core/localization/src/androidMain/res/values-de/strings.xml @@ -776,4 +776,6 @@ Anbietereinstellungen ersetzen Abbrechen Gemeinsame Zugangsdaten bleiben für nicht ausgewählte Anbieter erhalten: %1$s. + Display dimmen + *Das Display wird nur gedimmt, wenn die Hintergrundgenerierung ausgeschaltet ist. diff --git a/core/localization/src/androidMain/res/values-ru/strings.xml b/core/localization/src/androidMain/res/values-ru/strings.xml index a773bf5f9..e761db33a 100644 --- a/core/localization/src/androidMain/res/values-ru/strings.xml +++ b/core/localization/src/androidMain/res/values-ru/strings.xml @@ -739,4 +739,6 @@ Заменить настройки Отмена Общие учётные данные сохранены для невыбранных провайдеров: %1$s. + Затемнять экран + *Затемнение экрана работает только при отключённой фоновой генерации. diff --git a/core/localization/src/androidMain/res/values-tr/strings.xml b/core/localization/src/androidMain/res/values-tr/strings.xml index a85534a54..26ddaa22e 100644 --- a/core/localization/src/androidMain/res/values-tr/strings.xml +++ b/core/localization/src/androidMain/res/values-tr/strings.xml @@ -739,4 +739,6 @@ Sağlayıcı ayarlarını değiştir İptal Seçilmeyen sağlayıcıları korumak için ortak kimlik bilgileri tutuldu: %1$s. + Ekranı karart + *Ekran karartma yalnızca arka planda üretim kapalıyken etkindir. diff --git a/core/localization/src/androidMain/res/values-uk/strings.xml b/core/localization/src/androidMain/res/values-uk/strings.xml index f05edb7a2..4d6602d82 100644 --- a/core/localization/src/androidMain/res/values-uk/strings.xml +++ b/core/localization/src/androidMain/res/values-uk/strings.xml @@ -739,4 +739,6 @@ Замінити налаштування Скасувати Спільні облікові дані збережено для невибраних провайдерів: %1$s. + Затемнювати екран + *Затемнення екрана працює лише за вимкненої фонової генерації. diff --git a/core/localization/src/androidMain/res/values-zh/strings.xml b/core/localization/src/androidMain/res/values-zh/strings.xml index d90f86b61..54b5f1f3e 100644 --- a/core/localization/src/androidMain/res/values-zh/strings.xml +++ b/core/localization/src/androidMain/res/values-zh/strings.xml @@ -791,4 +791,6 @@ 替换提供商设置 取消 为保留未选提供商的设置,共用凭据未更改:%1$s。 + 调暗屏幕 + *仅在关闭后台生成时才会调暗屏幕。 diff --git a/core/localization/src/androidMain/res/values/strings.xml b/core/localization/src/androidMain/res/values/strings.xml index 9ab4fec8a..75037bc5c 100755 --- a/core/localization/src/androidMain/res/values/strings.xml +++ b/core/localization/src/androidMain/res/values/strings.xml @@ -776,4 +776,6 @@ Replace provider settings Cancel Shared sign-in credentials were kept to preserve unselected providers: %1$s. + Dim screen + *Screen dimming is active only when background generation is off. diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt index c8058de08..baa12a356 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt @@ -585,6 +585,15 @@ internal class PreferenceManagerImpl( get() = keyValueStore.getString(KEY_DESIGN_DARK_TOKEN, "${DarkThemeToken.FRAPPE}") set(value) = putString(KEY_DESIGN_DARK_TOKEN, value) + /** + * Whether active foreground generation lowers display brightness. + * + * @author Dmitriy Moroz + */ + override var shouldDimScreen: Boolean + get() = keyValueStore.getBoolean(KEY_DIM_SCREEN) + set(value) = putBoolean(KEY_DIM_SCREEN, value) + /** * Whether generation is scheduled through the background task manager. * @@ -660,6 +669,7 @@ internal class PreferenceManagerImpl( localDiffusionSchedulerThread = localOnnxSchedulerThread, monitorConnectivity = monitorConnectivity, backgroundGeneration = backgroundGeneration, + shouldDimScreen = shouldDimScreen, autoSaveAiResults = autoSaveAiResults, saveToMediaStore = saveToMediaStore, formAdvancedOptionsAlwaysShow = formAdvancedOptionsAlwaysShow, @@ -1105,10 +1115,14 @@ internal class PreferenceManagerImpl( const val KEY_DESIGN_DARK_TOKEN = "key_design_dark_color_token_theme" /** - * Stable storage key `key_background_generation`; preserve its value to retain existing user settings. + * Stable storage key for the opt-in foreground display dimming preference. * * @author Dmitriy Moroz */ + const val KEY_DIM_SCREEN = "key_dim_screen" + + /** Stable storage key for background generation scheduling. + * @author Dmitriy Moroz */ const val KEY_BACKGROUND_GENERATION = "key_background_generation" /** diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt index 7ef06ca93..e2ad53364 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt @@ -101,6 +101,7 @@ internal class BackupPreferencesGatewayImpl( "taggedInput" to BackupValue.Flag(preferences.formPromptTaggedInput), "connectionTimeout" to BackupValue.Integer(preferences.connectionTimeout.seconds), "generationTimeout" to BackupValue.Integer(preferences.generationRequestTimeout.seconds), + "dimScreen" to BackupValue.Flag(preferences.shouldDimScreen), "backgroundGeneration" to BackupValue.Flag(preferences.backgroundGeneration), "monitorConnection" to BackupValue.Flag(preferences.monitorConnectivity), "textToImageSteps" to BackupValue.Integer(preferences.textToImageSamplingSteps), diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt index fcaf12d17..548c3bfd5 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt @@ -146,6 +146,7 @@ internal object PortablePreferenceSchema { "key_generation_request_timeout_seconds", PortablePreferenceType.INTEGER ), + "dimScreen" to PortablePreferenceField("key_dim_screen", PortablePreferenceType.FLAG), "backgroundGeneration" to PortablePreferenceField( "key_background_generation", PortablePreferenceType.FLAG diff --git a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/repository/IosWakeLockRepository.kt b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/repository/IosWakeLockRepository.kt index 5f0b5aafd..14c8e06c4 100644 --- a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/repository/IosWakeLockRepository.kt +++ b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/repository/IosWakeLockRepository.kt @@ -2,45 +2,33 @@ package com.shifthackz.aisdv1.data.repository import com.shifthackz.aisdv1.domain.repository.WakeLock import com.shifthackz.aisdv1.domain.repository.WakeLockRepository -import platform.Foundation.NSThread -import platform.UIKit.UIApplication -import platform.darwin.dispatch_get_main_queue -import platform.darwin.dispatch_sync /** - * Implements `WakeLockRepository` behavior for iOS. + * Supplies the shared CPU wake-lock API on iOS, where no Android-style partial lock exists. + * Display idle prevention belongs to the resumed application UI, which restores it on pause. * * @author Dmitriy Moroz */ internal class IosWakeLockRepository : WakeLockRepository { /** - * Exposes the `wakeLock` value used by the SDAI data layer. - * + * Shared no-op CPU lock; display protection is managed by the resumed UI. * @author Dmitriy Moroz */ - override val wakeLock: WakeLock = IosWakeLock + override val wakeLock: WakeLock = NoOpIosWakeLock } -private object IosWakeLock : WakeLock { - override fun acquire(timeout: Long) { - runOnMainThread { - UIApplication.sharedApplication.idleTimerDisabled = true - } - } - - override fun release() { - runOnMainThread { - UIApplication.sharedApplication.idleTimerDisabled = false - } - } +/** + * CPU wake locks are unsupported on iOS; foreground display protection is owned by the UI. + * @author Dmitriy Moroz */ +private object NoOpIosWakeLock : WakeLock { + /** + * Leaves CPU scheduling to iOS. + * @param timeout Android CPU lock timeout in milliseconds; unused on iOS. + * @author Dmitriy Moroz */ + override fun acquire(timeout: Long) = Unit - private inline fun runOnMainThread(crossinline block: () -> Unit) { - if (NSThread.isMainThread) { - block() - } else { - dispatch_sync(dispatch_get_main_queue()) { - block() - } - } - } + /** + * Has no CPU resource to release on iOS. + * @author Dmitriy Moroz */ + override fun release() = Unit } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt index e349c4ff1..664dfe589 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt @@ -4,13 +4,18 @@ import com.shifthackz.aisdv1.core.common.schedulers.SchedulersToken /** * Observable application preferences including the selected generation source. + * + * @param shouldDimScreen Whether active foreground generation lowers screen brightness. * @param providerSelectionRevision Durable source revision used to invalidate earlier queued work. * * @author Dmitriy Moroz */ data class Settings( - /** Durable source-selection identity used to invalidate work even after an away/back switch. - * @author Dmitriy Moroz */ + /** + * Durable source-selection identity used to invalidate work even after an away/back switch. + * + * @author Dmitriy Moroz + */ val providerSelectionRevision: Long = 0L, /** * Deadline for provider setup and metadata requests; defaults to 120 seconds. @@ -25,139 +30,145 @@ data class Settings( */ val generationRequestTimeout: NetworkTimeout = NetworkTimeout.TWO_MINUTES, /** - * Exposes the `serverUrl` value used by the SDAI domain layer. + * AUTOMATIC1111 server base URL. * * @author Dmitriy Moroz */ val serverUrl: String = "", /** - * Exposes the `sdModel` value used by the SDAI domain layer. + * Selected server checkpoint identifier. * * @author Dmitriy Moroz */ val sdModel: String = "", /** - * Exposes the `demoMode` value used by the SDAI domain layer. + * Whether bundled demonstration data is active. * * @author Dmitriy Moroz */ val demoMode: Boolean = false, /** - * Exposes the `developerMode` value used by the SDAI domain layer. + * Whether developer tools are visible. * * @author Dmitriy Moroz */ val developerMode: Boolean = false, /** - * Exposes the `localDiffusionAllowCancel` value used by the SDAI domain layer. + * Whether local inference exposes cancellation controls. * * @author Dmitriy Moroz */ val localDiffusionAllowCancel: Boolean = false, /** - * Exposes the `localDiffusionSchedulerThread` value used by the SDAI domain layer. + * Coroutine scheduler selected for local inference. * * @author Dmitriy Moroz */ val localDiffusionSchedulerThread: SchedulersToken = SchedulersToken.COMPUTATION, /** - * Exposes the `monitorConnectivity` value used by the SDAI domain layer. + * Whether server connectivity is monitored. * * @author Dmitriy Moroz */ val monitorConnectivity: Boolean = false, /** - * Exposes the `backgroundGeneration` value used by the SDAI domain layer. + * Whether new generation requests use background scheduling. * * @author Dmitriy Moroz */ val backgroundGeneration: Boolean = false, /** - * Exposes the `autoSaveAiResults` value used by the SDAI domain layer. + * Enables minimum display brightness during active foreground generation. + * + * @author Dmitriy Moroz + */ + val shouldDimScreen: Boolean = false, + /** + * Whether completed images are automatically persisted to the gallery. * * @author Dmitriy Moroz */ val autoSaveAiResults: Boolean = false, /** - * Exposes the `saveToMediaStore` value used by the SDAI domain layer. + * Whether saved images are also exported to the device media library. * * @author Dmitriy Moroz */ val saveToMediaStore: Boolean = false, /** - * Exposes the `formAdvancedOptionsAlwaysShow` value used by the SDAI domain layer. + * Whether generation forms initially expand advanced controls. * * @author Dmitriy Moroz */ val formAdvancedOptionsAlwaysShow: Boolean = false, /** - * Exposes the `formPromptTaggedInput` value used by the SDAI domain layer. + * Whether prompt editors display tags. * * @author Dmitriy Moroz */ val formPromptTaggedInput: Boolean = false, /** - * Exposes the `source` value used by the SDAI domain layer. + * Selected generation provider. * * @author Dmitriy Moroz */ val source: ServerSource = ServerSource.AUTOMATIC1111, /** - * Exposes the `hordeApiKey` value used by the SDAI domain layer. + * Credential used for Horde generation requests. * * @author Dmitriy Moroz */ val hordeApiKey: String = "", /** - * Exposes the `arliAiModel` value used by the SDAI domain layer. + * Selected Arli AI model identifier. * * @author Dmitriy Moroz */ val arliAiModel: String = "", /** - * Exposes the `localUseNNAPI` value used by the SDAI domain layer. + * Whether ONNX inference requests Android NNAPI acceleration. * * @author Dmitriy Moroz */ val localUseNNAPI: Boolean = false, /** - * Exposes the `designUseSystemColorPalette` value used by the SDAI domain layer. + * Whether supported platforms use system dynamic colors. * * @author Dmitriy Moroz */ val designUseSystemColorPalette: Boolean = false, /** - * Exposes the `designUseSystemDarkTheme` value used by the SDAI domain layer. + * Whether appearance follows system dark mode. * * @author Dmitriy Moroz */ val designUseSystemDarkTheme: Boolean = false, /** - * Exposes the `designDarkTheme` value used by the SDAI domain layer. + * Manual dark-mode preference when system appearance is disabled. * * @author Dmitriy Moroz */ val designDarkTheme: Boolean = false, /** - * Exposes the `designColorToken` value used by the SDAI domain layer. + * Selected accent palette token. * * @author Dmitriy Moroz */ val designColorToken: String = "", /** - * Exposes the `designDarkThemeToken` value used by the SDAI domain layer. + * Selected dark background palette token. * * @author Dmitriy Moroz */ val designDarkThemeToken: String = "", /** - * Exposes the `galleryGrid` value used by the SDAI domain layer. + * Gallery column layout preference. * * @author Dmitriy Moroz */ val galleryGrid: Grid = Grid.Fixed2, /** - * Exposes the `languageCode` value used by the SDAI domain layer. + * Preferred language code; empty follows the platform language. * * @author Dmitriy Moroz */ diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt index 2fa5aaf4d..d9b98c8b3 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt @@ -429,6 +429,12 @@ interface PreferenceManager { */ var backgroundGeneration: Boolean + /** + * Whether foreground generation lowers display brightness while the app is active. + * @author Dmitriy Moroz + */ + var shouldDimScreen: Boolean + /** * Number of background processes tracked by the existing work UI. * diff --git a/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.android.kt b/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.android.kt new file mode 100644 index 000000000..b28d84869 --- /dev/null +++ b/presentation/app/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.android.kt @@ -0,0 +1,55 @@ +package com.shifthackz.aisdv1.presentation.app + +import android.view.WindowManager +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalView +import androidx.lifecycle.compose.LifecycleResumeEffect +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper + +/** + * Owns the Activity display override only while generation and the host are active. Brightness + * remains window-local, preserving the system slider and automatic brightness configuration. + * + * @param isGenerating Whether foreground generation needs the display kept awake. + * @param shouldDimScreen Whether to set the window to its lowest visible brightness. + * @author Dmitriy Moroz + */ +@Composable +internal actual fun GenerationScreenEffect(isGenerating: Boolean, shouldDimScreen: Boolean) { + val view = LocalView.current + val window = view.context.findActivity()?.window + LifecycleResumeEffect(window, isGenerating, shouldDimScreen) { + val previousBrightness = window?.attributes?.screenBrightness + val wasScreenKeptOn = window?.attributes?.flags?.and( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + ) == WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + if (isGenerating && window != null) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + if (shouldDimScreen) { + window.attributes = window.attributes.apply { screenBrightness = 0.01f } + } + } + onPauseOrDispose { + if (isGenerating && window != null) { + if (!wasScreenKeptOn) window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + if (shouldDimScreen && previousBrightness != null) { + window.attributes = + window.attributes.apply { screenBrightness = previousBrightness } + } + } + } + } +} + +/** + * Resolves the Activity behind Compose context wrappers without retaining it beyond composition. + * @receiver Context belonging to the application's Compose view. + * @author Dmitriy Moroz + */ +private tailrec fun Context.findActivity(): Activity? = when (this) { + is Activity -> this + is ContextWrapper -> baseContext.findActivity() + else -> null +} diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt index cb9acf8ac..be5a530d1 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt @@ -14,6 +14,8 @@ import com.shifthackz.aisdv1.presentation.components.widget.image.OriginalImageL import com.shifthackz.aisdv1.presentation.components.widget.image.GalleryImageLoader import com.shifthackz.aisdv1.presentation.components.widget.image.LocalGalleryImageLoader import androidx.compose.runtime.Composable +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.distinctUntilChanged import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -25,6 +27,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LifecycleEventEffect +import com.shifthackz.aisdv1.presentation.components.extensions.generationBrightnessInteraction import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider import com.shifthackz.aisdv1.core.extensions.clearFocusOnTap import com.shifthackz.aisdv1.core.localization.Localization @@ -74,6 +77,16 @@ fun AiSdApp( parametersOf(router, imageToImagePlatformActions) } } + val isTextGenerating by remember(textToImageViewModel) { + textToImageViewModel.state.map { it.generating }.distinctUntilChanged() + }.collectAsState(false) + val isImageGenerating by remember(imageToImageViewModel) { + imageToImageViewModel.state.map { it.generating }.distinctUntilChanged() + }.collectAsState(false) + val displaySettings by remember(preferenceManager) { + preferenceManager.observe().map { it.backgroundGeneration to it.shouldDimScreen } + .distinctUntilChanged() + }.collectAsState(preferenceManager.backgroundGeneration to preferenceManager.shouldDimScreen) val visitedHomeRoutes = remember { mutableStateListOf() } LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { textToImageViewModel.processIntent(TextToImageIntent.RetrySamplers) @@ -97,44 +110,50 @@ fun AiSdApp( onBack = router::navigateBack, ) - CompositionLocalProvider( - LocalGalleryImageLoader provides remember(koin) { koin.get() }, - LocalOriginalImageLoader provides remember(koin) { koin.get() }) { - AiSdAppTheme { - Surface( - modifier = modifier - .fillMaxSize() - .clearFocusOnTap(), - color = MaterialTheme.colorScheme.background, - ) { - Box(modifier = Modifier.fillMaxSize()) { - val shellHomeRoute = selectedHomeRoute ?: lastHomeRoute - val renderedHomeRoutes = - (visitedHomeRoutes + listOfNotNull(shellHomeRoute)).distinct() + GenerationScreenProtection( + isGenerating = (isTextGenerating || isImageGenerating) && !displaySettings.first, + shouldDimScreen = displaySettings.second, + ) { + CompositionLocalProvider( + LocalGalleryImageLoader provides remember(koin) { koin.get() }, + LocalOriginalImageLoader provides remember(koin) { koin.get() }) { + AiSdAppTheme { + Surface( + modifier = modifier + .fillMaxSize() + .generationBrightnessInteraction() + .clearFocusOnTap(), + color = MaterialTheme.colorScheme.background, + ) { + Box(modifier = Modifier.fillMaxSize()) { + val shellHomeRoute = selectedHomeRoute ?: lastHomeRoute + val renderedHomeRoutes = + (visitedHomeRoutes + listOfNotNull(shellHomeRoute)).distinct() - if (shellHomeRoute != null) { - HomeRoutesScaffold( - languageCode = languageCode, - activeRoute = shellHomeRoute, - renderedRoutes = renderedHomeRoutes, - router = router, - buildInfoProvider = koin.get(), - preferenceManager = preferenceManager, - shouldShowHomeChrome = selectedHomeRoute != null, - textToImageViewModel = textToImageViewModel, - imageToImageViewModel = imageToImageViewModel, - ) - } + if (shellHomeRoute != null) { + HomeRoutesScaffold( + languageCode = languageCode, + activeRoute = shellHomeRoute, + renderedRoutes = renderedHomeRoutes, + router = router, + buildInfoProvider = koin.get(), + preferenceManager = preferenceManager, + shouldShowHomeChrome = selectedHomeRoute != null, + textToImageViewModel = textToImageViewModel, + imageToImageViewModel = imageToImageViewModel, + ) + } - if (selectedHomeRoute == null) { - OverlayRouteContent( - languageCode = languageCode, - route = currentRoute, - koin = koin, - router = router, - urlLauncher = urlLauncher, - imageToImageViewModel = imageToImageViewModel, - ) + if (selectedHomeRoute == null) { + OverlayRouteContent( + languageCode = languageCode, + route = currentRoute, + koin = koin, + router = router, + urlLauncher = urlLauncher, + imageToImageViewModel = imageToImageViewModel, + ) + } } } } diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.kt new file mode 100644 index 000000000..5282c0bd1 --- /dev/null +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.presentation.app + +import androidx.compose.runtime.Composable + +/** + * Applies native display overrides while generation and the host are active. Restores the + * previous display settings before replacing an override, on pause, completion or disposal. + * + * @param isGenerating Whether foreground generation needs the display kept awake. + * @param shouldDimScreen Whether the current interaction state permits minimum brightness. + * @author Dmitriy Moroz + */ +@Composable +internal expect fun GenerationScreenEffect(isGenerating: Boolean, shouldDimScreen: Boolean) diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenProtection.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenProtection.kt new file mode 100644 index 000000000..4e13a244f --- /dev/null +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenProtection.kt @@ -0,0 +1,61 @@ +package com.shifthackz.aisdv1.presentation.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import com.shifthackz.aisdv1.presentation.components.extensions.LocalGenerationBrightnessInteraction +import kotlinx.coroutines.delay + +/** + * Keeps foreground generation awake and temporarily restores brightness after interaction. + * Each touch restarts a 1,750 ms inactivity timer. Pausing, finishing or disabling dimming + * clears the temporary override; resuming an ongoing generation applies dimming again. + * + * @param isGenerating Whether either form is generating with background generation disabled. + * @param shouldDimScreen Whether the persisted opt-in permits minimum display brightness. + * @param content Application surfaces and dialogs that can report brightness interaction. + * @author Dmitriy Moroz + */ +@Composable +internal fun GenerationScreenProtection( + isGenerating: Boolean, + shouldDimScreen: Boolean, + content: @Composable () -> Unit, +) { + var interactionRevision by remember(isGenerating, shouldDimScreen) { mutableLongStateOf(0L) } + var isTemporarilyBright by remember(isGenerating, shouldDimScreen) { mutableStateOf(false) } + val onInteraction: (() -> Unit)? = if (isGenerating && shouldDimScreen) { + remember(isGenerating, shouldDimScreen) { + { + isTemporarilyBright = true + interactionRevision++ + } + } + } else null + + LaunchedEffect(interactionRevision, isGenerating, shouldDimScreen) { + if (isTemporarilyBright) { + delay(BRIGHTNESS_INTERACTION_TIMEOUT_MS) + isTemporarilyBright = false + } + } + LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { + isTemporarilyBright = false + } + GenerationScreenEffect( + isGenerating = isGenerating, + shouldDimScreen = shouldDimScreen && !isTemporarilyBright, + ) + CompositionLocalProvider(LocalGenerationBrightnessInteraction provides onInteraction) { + content() + } +} + +private const val BRIGHTNESS_INTERACTION_TIMEOUT_MS = 1_750L diff --git a/presentation/app/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.ios.kt b/presentation/app/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.ios.kt new file mode 100644 index 000000000..531b7a89a --- /dev/null +++ b/presentation/app/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/app/GenerationScreenEffect.ios.kt @@ -0,0 +1,34 @@ +package com.shifthackz.aisdv1.presentation.app + +import androidx.compose.runtime.Composable +import androidx.lifecycle.compose.LifecycleResumeEffect +import platform.UIKit.UIApplication +import platform.UIKit.UIScreen + +/** + * Prevents idle sleep and optionally dims the screen during active foreground generation. + * Each resume captures current brightness again so changes made outside SDAI are preserved. + * + * @param isGenerating Whether foreground generation needs the display kept awake. + * @param shouldDimScreen Whether to lower brightness until pause or generation completion. + * @author Dmitriy Moroz + */ +@Composable +internal actual fun GenerationScreenEffect(isGenerating: Boolean, shouldDimScreen: Boolean) { + LifecycleResumeEffect(isGenerating, shouldDimScreen) { + val application = UIApplication.sharedApplication + val screen = UIScreen.mainScreen + val previousBrightness = screen.brightness + val wasIdleTimerDisabled = application.idleTimerDisabled + if (isGenerating) { + application.idleTimerDisabled = true + if (shouldDimScreen) screen.brightness = 0.01 + } + onPauseOrDispose { + if (isGenerating) { + application.idleTimerDisabled = wasIdleTimerDisabled + if (shouldDimScreen) screen.brightness = previousBrightness + } + } + } +} diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/extensions/GenerationBrightnessInteraction.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/extensions/GenerationBrightnessInteraction.kt new file mode 100644 index 000000000..350420932 --- /dev/null +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/extensions/GenerationBrightnessInteraction.kt @@ -0,0 +1,41 @@ +package com.shifthackz.aisdv1.presentation.components.extensions + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.pointerInput + +/** + * Reports interaction to the application-owned dimming timer. Null disables observation when + * foreground dimming is unavailable; descendants never own or persist the brightness preference. + * + * @author Dmitriy Moroz + */ +val LocalGenerationBrightnessInteraction = compositionLocalOf<(() -> Unit)?> { null } + +/** + * Observes touches before child controls without consuming their pointer events. Press, release + * and movement while pressed restart the dimming timer, including while brightness is restored. + * + * @receiver Surface whose interactions temporarily restore generation brightness. + * @return The receiver with passive pointer observation when foreground dimming is enabled. + * @author Dmitriy Moroz + */ +@Composable +fun Modifier.generationBrightnessInteraction(): Modifier { + val onInteraction = LocalGenerationBrightnessInteraction.current ?: return this + return pointerInput(onInteraction) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.type == PointerEventType.Press || event.type == PointerEventType.Release || + event.changes.any { it.pressed && it.position != it.previousPosition } + ) { + onInteraction() + } + } + } + } +} diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt index c2b256d29..8f8fbeedd 100644 --- a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt @@ -4,6 +4,8 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties +import com.shifthackz.aisdv1.presentation.components.extensions.LocalGenerationBrightnessInteraction +import com.shifthackz.aisdv1.presentation.components.extensions.generationBrightnessInteraction import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.core.localization.formatter.DurationFormatter import com.shifthackz.aisdv1.core.model.UiText @@ -12,6 +14,8 @@ import com.shifthackz.aisdv1.core.model.asUiText /** * Shows generation or remote-queue progress with optional cancellation content. + * Touches inside the dialog or its scrim notify the active dimming timer without dismissing + * non-dismissible progress or intercepting child controls. * * @param title Heading naming the provider or operation. * @param subTitle Stage or waiting explanation beneath the heading. @@ -37,14 +41,19 @@ fun ProgressDialog( overallPercentage: Int? = null, content: (@Composable () -> Unit)? = null, ) { + val onBrightnessInteraction = LocalGenerationBrightnessInteraction.current Dialog( - onDismissRequest = onDismissRequest, + onDismissRequest = { + onBrightnessInteraction?.invoke() + if (canDismiss) onDismissRequest() + }, properties = DialogProperties( - dismissOnClickOutside = canDismiss, + dismissOnClickOutside = canDismiss || onBrightnessInteraction != null, dismissOnBackPress = canDismiss, ), ) { GeneratingProgressDialogContent( + modifier = Modifier.generationBrightnessInteraction(), title = title, subTitle = subTitle, waitTimeSeconds = waitTimeSeconds, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt index ff8204cc8..2de51f2f7 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt @@ -17,6 +17,7 @@ internal fun SettingsListItem.contentType(): SettingsContentType = when (this) { SettingsListItem.COMMUNITY_HEADER, SettingsListItem.INFO_HEADER -> SettingsContentType.HEADER + SettingsListItem.DIM_SCREEN, SettingsListItem.NNAPI, SettingsListItem.BACKGROUND_GENERATION, SettingsListItem.MONITOR_CONNECTION, @@ -28,6 +29,7 @@ internal fun SettingsListItem.contentType(): SettingsContentType = when (this) { SettingsListItem.SYSTEM_DARK, SettingsListItem.MANUAL_DARK -> SettingsContentType.SWITCH + SettingsListItem.DIM_SCREEN_WARNING, SettingsListItem.NNAPI_WARNING, SettingsListItem.BACKGROUND_WARNING, SettingsListItem.AUTO_SAVE_WARNING -> SettingsContentType.WARNING diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt index 15e2391fd..8b9ae4d5d 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt @@ -159,6 +159,13 @@ sealed interface SettingsIntent : MviIntent { data class NNAPI(override val flag: Boolean) : UpdateFlag + /** + * Persists foreground generation display dimming. + * @param flag Whether dimming is enabled. + * @author Dmitriy Moroz + */ + data class DimScreen(override val flag: Boolean) : UpdateFlag + data class MonitorConnection(override val flag: Boolean) : UpdateFlag data class AutoSaveResult(override val flag: Boolean) : UpdateFlag diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt index 55c59dd1d..dabbba5ad 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt @@ -21,6 +21,8 @@ internal enum class SettingsListItem { BACKGROUND_WARNING, DEBUG_MENU, APP_HEADER, + DIM_SCREEN, + DIM_SCREEN_WARNING, MONITOR_CONNECTION, AUTO_SAVE, AUTO_SAVE_WARNING, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt index 4526c62da..1425ef953 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt @@ -41,6 +41,8 @@ internal fun settingsListItems( } if (!state.loading && state.developerMode) add(SettingsListItem.DEBUG_MENU) add(SettingsListItem.APP_HEADER) + add(SettingsListItem.DIM_SCREEN) + if (!state.loading && state.backgroundGeneration) add(SettingsListItem.DIM_SCREEN_WARNING) if (state.showMonitorConnectionOption) add(SettingsListItem.MONITOR_CONNECTION) add(SettingsListItem.AUTO_SAVE) if (!state.loading && state.backgroundGeneration) add(SettingsListItem.AUTO_SAVE_WARNING) diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt index 17c9e0894..86cb23061 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt @@ -27,6 +27,7 @@ import com.shifthackz.aisdv1.domain.entity.ServerSourceType * @param stabilityAiCredits Current Stability AI balance shown in Settings. * @param localUseNNAPI Whether ONNX local diffusion should use NNAPI acceleration. * @param backgroundGenerationAvailable Whether background generation is supported by this target. + * @param shouldDimScreen Whether active foreground generation dims the screen. * @param backgroundGeneration Whether background generation is currently enabled. * @param monitorConnectivity Whether server connectivity monitoring is enabled. * @param autoSaveAiResults Whether generated images should be saved automatically. @@ -60,6 +61,7 @@ data class SettingsState( val localUseNNAPI: Boolean = false, val backgroundGenerationAvailable: Boolean = false, val backgroundGeneration: Boolean = false, + val shouldDimScreen: Boolean = false, val monitorConnectivity: Boolean = false, val autoSaveAiResults: Boolean = false, val saveToMediaStore: Boolean = false, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt index 051732b38..7bbc52eab 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt @@ -172,6 +172,7 @@ class SettingsViewModel( ?: "", stabilityAiCredits = credits, localUseNNAPI = settings.localUseNNAPI, + shouldDimScreen = settings.shouldDimScreen, backgroundGenerationAvailable = platformActions.supportsBackgroundGeneration, backgroundGeneration = settings.backgroundGeneration && platformActions.supportsBackgroundGeneration, @@ -270,6 +271,10 @@ class SettingsViewModel( preferenceManager.autoSaveAiResults = intent.flag } + is SettingsIntent.UpdateFlag.DimScreen -> { + preferenceManager.shouldDimScreen = intent.flag + } + is SettingsIntent.UpdateFlag.MonitorConnection -> { preferenceManager.monitorConnectivity = intent.flag } diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt index 50369bb77..eaf8c6bfe 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt @@ -78,6 +78,8 @@ internal fun ContentSettingsState( SettingsListItem.BACKGROUND_WARNING, SettingsListItem.DEBUG_MENU, SettingsListItem.APP_HEADER, + SettingsListItem.DIM_SCREEN, + SettingsListItem.DIM_SCREEN_WARNING, SettingsListItem.MONITOR_CONNECTION, SettingsListItem.AUTO_SAVE, SettingsListItem.AUTO_SAVE_WARNING, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt index ec0978958..bc4604763 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.presentation.settings.section +import androidx.compose.material.icons.filled.BrightnessLow import androidx.compose.material.icons.filled.Backup import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountTree @@ -211,6 +212,26 @@ internal fun SettingsServerSection( ) } + SettingsListItem.DIM_SCREEN -> { + SettingsToggleItem( + modifier = itemModifier, + isLoading = isLoading, + startIcon = Icons.Default.BrightnessLow, + text = (Localization.string("settings_item_dim_screen") + + if (isBackgroundGenerationEnabled) "*" else "").asUiText(), + isChecked = state.shouldDimScreen, + onCheckedChange = { processIntent(SettingsIntent.UpdateFlag.DimScreen(it)) }, + ) + } + + SettingsListItem.DIM_SCREEN_WARNING -> { + Text( + modifier = warningModifier, + text = Localization.string("settings_item_dim_screen_warning"), + style = MaterialTheme.typography.labelMedium, + ) + } + SettingsListItem.MONITOR_CONNECTION -> { SettingsToggleItem( modifier = itemModifier,