@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import platform.Foundation.NSNotificationCenter import platform.Foundation.NSOperationQueue import platform.UIKit.UIApplication import platform.UIKit.UIApplicationDidBecomeActiveNotification import platform.UIKit.UIApplicationWillResignActiveNotification import platform.UIKit.UIColor import platform.UIKit.UIScreen import platform.UIKit.UIScreenCapturedDidChangeNotification import platform.UIKit.UIView import platform.UIKit.UIViewAutoresizingFlexibleHeight import platform.UIKit.UIViewAutoresizingFlexibleWidth import platform.UIKit.UIWindow import platform.UIKit.UIWindowScene @Composable internal actual fun SecureScreenEffect(secure: Boolean) { DisposableEffect(secure) { IosPrivacyShield.enabled = secure onDispose { } } } /** * iOS cannot block screenshots with public API. While enabled, a cover hides the UI in the app * switcher snapshot (taken after resign-active) and while the screen is recorded or mirrored. */ private object IosPrivacyShield { private var cover: UIView? = null private var inactive = false private var observing = false var enabled = false set(value) { field = value if (value) observe() refresh() } private fun observe() { if (observing) return observing = true val center = NSNotificationCenter.defaultCenter val queue = NSOperationQueue.mainQueue center.addObserverForName(UIApplicationWillResignActiveNotification, null, queue) { _ -> inactive = true; refresh() } center.addObserverForName(UIApplicationDidBecomeActiveNotification, null, queue) { _ -> inactive = false; refresh() } center.addObserverForName(UIScreenCapturedDidChangeNotification, null, queue) { _ -> refresh() } } private fun refresh() { val hide = enabled && (inactive || UIScreen.mainScreen.isCaptured()) if (!hide) { cover?.removeFromSuperview() cover = null return } if (cover != null) return val window = UIApplication.sharedApplication.connectedScenes .filterIsInstance() .flatMap { it.windows } .filterIsInstance() .let { windows -> windows.firstOrNull { it.isKeyWindow() } ?: windows.firstOrNull() } ?: return cover = UIView(frame = window.bounds).apply { backgroundColor = UIColor.blackColor autoresizingMask = UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight window.addSubview(this) } } }