package eu.friedcutlet.yokan.ui.screens.reader import eu.friedcutlet.yokan.AndroidForegroundActivity import android.app.Activity import android.os.Build import android.view.View import android.view.Window import android.view.WindowInsets import android.view.WindowInsetsController import android.view.WindowManager import eu.friedcutlet.yokan.MainActivity actual fun createReaderSystemUiController(): ReaderSystemUiController = AndroidReaderSystemUiController() private class AndroidReaderSystemUiController : ReaderSystemUiController { override fun apply(preferences: ReaderSystemUiPreferences) { val activity = AndroidForegroundActivity.activity ?: return val window = activity.window ?: return activity.runOnUiThread { applyKeepScreenOn(window, preferences.keepScreenOn) applyFullscreen(window, preferences.hideMobileSystemBars) } } override fun reset() { val activity = AndroidForegroundActivity.activity ?: return val window = activity.window ?: return activity.runOnUiThread { applyKeepScreenOn(window, false) applyFullscreen(window, false) } } private fun applyKeepScreenOn(window: Window, enabled: Boolean) { if (enabled) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } private fun applyFullscreen(window: Window, enabled: Boolean) { // The window is always edge-to-edge (enableEdgeToEdge in MainActivity); // never re-fit the decor here — only toggle system bar visibility. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val controller = window.insetsController ?: return if (enabled) { controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE controller.hide(WindowInsets.Type.systemBars()) } else { controller.show(WindowInsets.Type.systemBars()) } } else { @Suppress("DEPRECATION") val hideFlags = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) @Suppress("DEPRECATION") val layoutFlags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) // Keep layout flags (edge-to-edge) and any appearance bits like // SYSTEM_UI_FLAG_LIGHT_STATUS_BAR set by enableEdgeToEdge. @Suppress("DEPRECATION") window.decorView.systemUiVisibility = if (enabled) { window.decorView.systemUiVisibility or layoutFlags or hideFlags } else { (window.decorView.systemUiVisibility or layoutFlags) and hideFlags.inv() } } } }