nitrowind-native 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/Package.swift +104 -0
  4. package/README.md +39 -2
  5. package/android/src/main/java/com/margelo/nitro/nitrowind/HybridReducedMotion.kt +79 -0
  6. package/android/src/main/java/com/margelo/nitro/nitrowind/HybridThemeCover.kt +38 -0
  7. package/android/src/main/java/com/margelo/nitro/nitrowind/NitroWindCoverLog.kt +36 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrowind/ThemeCoverActivityInitializer.kt +11 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrowind/ThemeCoverController.kt +619 -0
  10. package/ios/HybridReducedMotion.swift +50 -0
  11. package/ios/HybridThemeCover.swift +46 -0
  12. package/ios/NitroWindCoverLog.swift +40 -0
  13. package/ios/ThemeCoverWindow.swift +324 -0
  14. package/nitro.json +13 -0
  15. package/nitrogen/generated/.gitattributes +1 -0
  16. package/nitrogen/generated/android/NitroWindNative+autolinking.cmake +34 -0
  17. package/nitrogen/generated/android/NitroWindNative+autolinking.gradle +10 -0
  18. package/nitrogen/generated/android/NitroWindNativeOnLoad.cpp +25 -0
  19. package/nitrogen/generated/android/c++/JCallback_void.cpp +54 -0
  20. package/nitrogen/generated/android/c++/JCallback_void_bool.cpp +56 -0
  21. package/nitrogen/generated/android/c++/JCoverRequest.cpp +42 -0
  22. package/nitrogen/generated/android/c++/JHybridReducedMotionSpec.cpp +84 -0
  23. package/nitrogen/generated/android/c++/JHybridThemeCoverSpec.cpp +114 -0
  24. package/nitrogen/generated/android/c++/JListenerSubscription.cpp +34 -0
  25. package/nitrogen/generated/android/c++/JThemeTransitionDirection.cpp +52 -0
  26. package/nitrogen/generated/android/c++/JThemeTransitionStyle.cpp +58 -0
  27. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JCallback_void.hpp +53 -0
  28. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JCallback_void_bool.hpp +55 -0
  29. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JCoverRequest.hpp +73 -0
  30. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JHybridReducedMotionSpec.hpp +90 -0
  31. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JHybridReducedMotionSpecJavaPart.hpp +26 -0
  32. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JHybridThemeCoverSpec.hpp +96 -0
  33. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JHybridThemeCoverSpecJavaPart.hpp +26 -0
  34. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JListenerSubscription.hpp +49 -0
  35. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JThemeTransitionDirection.hpp +72 -0
  36. package/nitrogen/generated/android/c++/include/NitroWindNative/private/JThemeTransitionStyle.hpp +82 -0
  37. package/nitrogen/generated/android/include/NitroWindNative/private/NitroWindNativeOnLoad.hpp +13 -0
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/Callback_void.kt +69 -0
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/Callback_void_bool.kt +69 -0
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/CoverRequest.kt +67 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/HybridReducedMotionSpec.kt +89 -0
  42. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/HybridThemeCoverSpec.kt +107 -0
  43. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/ListenerSubscription.kt +46 -0
  44. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/NitroWindNativeOnLoad.kt +22 -0
  45. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/ThemeTransitionDirection.kt +46 -0
  46. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrowind/ThemeTransitionStyle.kt +52 -0
  47. package/nitrogen/generated/apple/NitroWindNative-Swift-Cxx-Bridge.cpp +68 -0
  48. package/nitrogen/generated/apple/NitroWindNativeAppleCxx/NitroWindNativeAppleCxx.cpp +9 -0
  49. package/nitrogen/generated/apple/NitroWindNativeAppleCxx/include/NitroWindNativeAppleCxx/NitroWindNativeAppleCxx.h +64 -0
  50. package/nitrogen/generated/apple/NitroWindNativeAutolinking.cpp +22 -0
  51. package/nitrogen/generated/apple/NitroWindNativeAutolinking.mm +24 -0
  52. package/nitrogen/generated/apple/c++/CoverRequest-Swift.cpp +36 -0
  53. package/nitrogen/generated/apple/c++/HybridReducedMotionSpecSwift.cpp +62 -0
  54. package/nitrogen/generated/apple/c++/HybridReducedMotionSpec_cxx-Swift.cpp +28 -0
  55. package/nitrogen/generated/apple/c++/HybridThemeCoverSpecSwift.cpp +104 -0
  56. package/nitrogen/generated/apple/c++/HybridThemeCoverSpec_cxx-Swift.cpp +28 -0
  57. package/nitrogen/generated/apple/c++/ListenerSubscription-Swift.cpp +37 -0
  58. package/nitrogen/generated/apple/c++/ThemeTransitionDirection-Swift.cpp +46 -0
  59. package/nitrogen/generated/apple/c++/ThemeTransitionStyle-Swift.cpp +52 -0
  60. package/nitrogen/generated/apple/c++/include/NitroWindNative/NitroWindNativeAutolinking.hpp +13 -0
  61. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/CoverRequest-Swift.hpp +23 -0
  62. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/HybridReducedMotionSpecSwift.hpp +74 -0
  63. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/HybridReducedMotionSpec_cxx-Swift.hpp +23 -0
  64. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/HybridThemeCoverSpecSwift.hpp +79 -0
  65. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/HybridThemeCoverSpec_cxx-Swift.hpp +23 -0
  66. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/ListenerSubscription-Swift.hpp +23 -0
  67. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/NitroWindNative-Swift-Cxx-Umbrella.hpp +41 -0
  68. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/ThemeTransitionDirection-Swift.hpp +23 -0
  69. package/nitrogen/generated/apple/c++/include/NitroWindNative/private/ThemeTransitionStyle-Swift.hpp +23 -0
  70. package/nitrogen/generated/apple/c++/include/module.modulemap +12 -0
  71. package/nitrogen/generated/apple/swift/Callback_void.swift +60 -0
  72. package/nitrogen/generated/apple/swift/Callback_void_bool.swift +60 -0
  73. package/nitrogen/generated/apple/swift/CoverRequest.swift +56 -0
  74. package/nitrogen/generated/apple/swift/HybridReducedMotionSpec.swift +66 -0
  75. package/nitrogen/generated/apple/swift/HybridReducedMotionSpec_cxx.swift +164 -0
  76. package/nitrogen/generated/apple/swift/HybridThemeCoverSpec.swift +70 -0
  77. package/nitrogen/generated/apple/swift/HybridThemeCoverSpec_cxx.swift +207 -0
  78. package/nitrogen/generated/apple/swift/ListenerSubscription.swift +29 -0
  79. package/nitrogen/generated/apple/swift/Promise_bool.swift +100 -0
  80. package/nitrogen/generated/apple/swift/Promise_void.swift +100 -0
  81. package/nitrogen/generated/apple/swift/ThemeTransitionDirection.swift +54 -0
  82. package/nitrogen/generated/apple/swift/ThemeTransitionStyle.swift +64 -0
  83. package/nitrogen/generated/hybrid-classes.json +33 -0
  84. package/nitrogen/generated/shared/c++/NitroWindNativeCxxModule.cpp +2 -0
  85. package/nitrogen/generated/shared/c++/include/NitroWindNative/NitroWindNativeCxxModule.hpp +2 -0
  86. package/nitrogen/generated/shared/javascript/ReducedMotion.cjs +19 -0
  87. package/nitrogen/generated/shared/javascript/ReducedMotion.d.cts +9 -0
  88. package/nitrogen/generated/shared/javascript/ThemeCover.cjs +19 -0
  89. package/nitrogen/generated/shared/javascript/ThemeCover.d.cts +9 -0
  90. package/package.json +69 -4
  91. package/src/index.ts +59 -0
  92. package/src/specs/ListenerSubscription.ts +3 -0
  93. package/src/specs/ReducedMotion.nitro.ts +19 -0
  94. package/src/specs/ThemeCover.nitro.ts +49 -0
  95. package/src/testing.ts +18 -0
@@ -0,0 +1,619 @@
1
+ package com.margelo.nitro.nitrowind
2
+
3
+ import android.animation.Animator
4
+ import android.animation.AnimatorListenerAdapter
5
+ import android.animation.ValueAnimator
6
+ import android.app.Activity
7
+ import android.content.Context
8
+ import android.content.res.Configuration
9
+ import android.graphics.Bitmap
10
+ import android.graphics.Canvas
11
+ import android.graphics.Paint
12
+ import android.graphics.PorterDuff
13
+ import android.graphics.PorterDuffXfermode
14
+ import android.graphics.Rect
15
+ import android.graphics.RenderEffect
16
+ import android.graphics.Shader
17
+ import android.os.Build
18
+ import android.os.Handler
19
+ import android.os.Looper
20
+ import android.os.SystemClock
21
+ import android.view.MotionEvent
22
+ import android.view.PixelCopy
23
+ import android.view.View
24
+ import android.view.ViewGroup
25
+ import android.view.animation.AccelerateDecelerateInterpolator
26
+ import android.view.animation.DecelerateInterpolator
27
+ import androidx.core.view.WindowCompat
28
+ import com.margelo.nitro.renderer.AndroidHost
29
+ import java.lang.ref.WeakReference
30
+ import kotlin.math.abs
31
+ import kotlin.math.hypot
32
+ import kotlin.math.max
33
+
34
+ /**
35
+ * Process-level snapshot cover for Android theme transitions across Activity recreation.
36
+ * Held strictly in memory: if the process dies mid-switch, the app starts cold in the new scheme.
37
+ */
38
+ internal object ThemeCoverController {
39
+ // Peak blur radius of the 'blur' style. RenderEffect needs API 31; older devices fade instead.
40
+ private const val BLUR_RADIUS_DP = 24f
41
+
42
+ private val DEFAULT_REQUEST =
43
+ CoverRequest(ThemeTransitionStyle.FADE, 400.0, null, null, ThemeTransitionDirection.LEFT)
44
+
45
+ private val mainHandler = Handler(Looper.getMainLooper())
46
+
47
+ @Volatile
48
+ private var active: Boolean = false
49
+
50
+ private var bitmap: Bitmap? = null
51
+ private var coverView: ThemeCoverView? = null
52
+ private var animator: ValueAnimator? = null
53
+ private var request: CoverRequest = DEFAULT_REQUEST
54
+ private var generation: Int = 0
55
+ private var pendingFinish: (() -> Unit)? = null
56
+
57
+ // System-bar icon appearances captured from the old window and kept until the animation is halfway.
58
+ private var oldLightStatusBars: Boolean? = null
59
+ private var oldLightNavigationBars: Boolean? = null
60
+
61
+ // Dev diagnostics only (CoverLog): when the current cover was captured and its finish animation started.
62
+ private var capturedAt: Long = 0L
63
+ private var finishStartedAt: Long? = null
64
+
65
+ private fun now(): Long = SystemClock.uptimeMillis()
66
+
67
+ // The newest Activity seen by onActivityCreated. A recreated Activity exists from onCreate,
68
+ // but AndroidHost only attaches it after its first layout.
69
+ private var latestActivity: WeakReference<Activity>? = null
70
+
71
+ // Test seam (lastCaptureOutcome): what the most recent capture did.
72
+ private var lastOutcome: String = "none"
73
+
74
+ private fun isAlive(activity: Activity?): Boolean =
75
+ activity != null && !activity.isFinishing && !activity.isDestroyed
76
+
77
+ // Dev diagnostics only (CoverLog.v): Activity lifecycle callbacks, registered once in debug builds.
78
+ private var lifecycleLogRegistered = false
79
+
80
+ private fun id(activity: Activity?): String =
81
+ if (activity == null) "none" else "activity@${Integer.toHexString(System.identityHashCode(activity))}"
82
+
83
+ private fun hostActivity(): Activity? = runCatching { AndroidHost.activity }.getOrNull()
84
+
85
+ /** One-line identity and state of [activity], for CoverLog.v only. */
86
+ private fun describe(activity: Activity?): String {
87
+ if (activity == null) return "none"
88
+ val state = (activity as? androidx.lifecycle.LifecycleOwner)?.lifecycle?.currentState
89
+ val decor = activity.window?.decorView
90
+ return buildString {
91
+ append(id(activity))
92
+ append(" state=$state changingConfigurations=${activity.isChangingConfigurations}")
93
+ append(" finishing=${activity.isFinishing} destroyed=${activity.isDestroyed}")
94
+ append(" night=${isDarkConfiguration(activity)}")
95
+ if (decor != null) {
96
+ append(" decor=${decor.width}x${decor.height} attached=${decor.isAttachedToWindow} inLayout=${decor.isInLayout}")
97
+ }
98
+ append(" host=${hostActivity() === activity}")
99
+ }
100
+ }
101
+
102
+ private fun registerLifecycleLog(activity: Activity) {
103
+ if (!CoverLog.enabled || lifecycleLogRegistered) return
104
+ lifecycleLogRegistered = true
105
+ activity.application.registerActivityLifecycleCallbacks(
106
+ object : android.app.Application.ActivityLifecycleCallbacks {
107
+ private fun log(event: String, a: Activity) {
108
+ CoverLog.v { "lifecycle $event ${id(a)} changingConfigurations=${a.isChangingConfigurations} host=${hostActivity() === a}" }
109
+ }
110
+
111
+ override fun onActivityCreated(a: Activity, savedInstanceState: android.os.Bundle?) = log("created", a)
112
+ override fun onActivityStarted(a: Activity) = log("started", a)
113
+ override fun onActivityResumed(a: Activity) = log("resumed", a)
114
+ override fun onActivityPaused(a: Activity) = log("paused", a)
115
+ override fun onActivityStopped(a: Activity) = log("stopped", a)
116
+ override fun onActivitySaveInstanceState(a: Activity, outState: android.os.Bundle) {}
117
+ override fun onActivityDestroyed(a: Activity) = log("destroyed", a)
118
+ },
119
+ )
120
+ }
121
+
122
+ /** Removes [view] from its parent, logging (CoverLog.v) whether the window was mid-layout (#38). */
123
+ private fun removeCover(view: View?, why: String) {
124
+ val parent = view?.parent as? ViewGroup ?: return
125
+ if (CoverLog.verbose) {
126
+ val message =
127
+ "cover removed ($why) from ${id(view.context as? Activity)} children=${parent.childCount} " +
128
+ "parentInLayout=${parent.isInLayout} layoutRequested=${parent.isLayoutRequested}"
129
+ // Removing a child mid-layout is the #38 suspect, so log who did it.
130
+ if (parent.isInLayout) {
131
+ android.util.Log.v(CoverLog.TAG, message, Throwable("cover removed during layout"))
132
+ } else {
133
+ android.util.Log.v(CoverLog.TAG, message)
134
+ }
135
+ }
136
+ parent.removeView(view)
137
+ }
138
+
139
+ /** The Activity a cover goes on: AndroidHost's, or a recreated one AndroidHost has not attached yet. */
140
+ private fun liveActivity(): Activity? {
141
+ val host = runCatching { AndroidHost.activity }.getOrNull()
142
+ if (isAlive(host)) return host
143
+ return latestActivity?.get()?.takeIf { isAlive(it) }
144
+ }
145
+
146
+ val isActive: Boolean
147
+ get() = active
148
+
149
+ /**
150
+ * Test-only: what the most recent capture did. `none` before the first capture, `pending` until its
151
+ * callback runs, then `captured`, `captured on the recreated Activity`, `reused: <reason>`,
152
+ * `failed: <reason>` or `superseded`.
153
+ */
154
+ val lastCaptureOutcome: String
155
+ get() = lastOutcome
156
+
157
+ private fun runOnMain(block: () -> Unit) {
158
+ if (Looper.myLooper() == Looper.getMainLooper()) {
159
+ block()
160
+ } else {
161
+ mainHandler.post(block)
162
+ }
163
+ }
164
+
165
+ private fun applySystemBars(activity: Activity, lightStatusBars: Boolean, lightNavigationBars: Boolean) {
166
+ val controller = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
167
+ controller.isAppearanceLightStatusBars = lightStatusBars
168
+ controller.isAppearanceLightNavigationBars = lightNavigationBars
169
+ }
170
+
171
+ private fun isDarkConfiguration(activity: Activity): Boolean =
172
+ (activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
173
+ Configuration.UI_MODE_NIGHT_YES
174
+
175
+ private fun attachCover(activity: Activity, shot: Bitmap) {
176
+ coverView?.let { existing ->
177
+ removeCover(existing, "replaced by a new cover")
178
+ }
179
+ val view = ThemeCoverView(activity, shot)
180
+ val decor = activity.window.decorView as ViewGroup
181
+ CoverLog.v { "cover added to ${id(activity)} children=${decor.childCount} decorInLayout=${decor.isInLayout}" }
182
+ decor.addView(
183
+ view,
184
+ ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT),
185
+ )
186
+ view.bringToFront()
187
+ coverView = view
188
+ }
189
+
190
+ /**
191
+ * Called from [ThemeCoverActivityInitializer.onCreate] on the main thread, right after
192
+ * `enableEdgeToEdge()` and before `setContentView` / first frame.
193
+ */
194
+ fun onActivityCreated(activity: Activity) {
195
+ registerLifecycleLog(activity)
196
+ CoverLog.v {
197
+ "onActivityCreated ${describe(activity)} previous=${id(latestActivity?.get())} " +
198
+ "cover=${bitmap?.takeIf { !it.isRecycled } != null}"
199
+ }
200
+ latestActivity = WeakReference(activity)
201
+ val shot = bitmap
202
+ if (shot == null || shot.isRecycled) {
203
+ bitmap = null
204
+ active = false
205
+ return
206
+ }
207
+
208
+ // Stop any animator tied to the previous Activity without clearing the cover state;
209
+ // JS will invoke finish() once the recreated Activity has rendered its first frame.
210
+ val runningAnimator = animator
211
+ animator = null
212
+ runningAnimator?.cancel()
213
+
214
+ attachCover(activity, shot)
215
+ CoverLog.d { "cover re-attached to the recreated Activity (${now() - capturedAt} ms after capture)" }
216
+
217
+ val lightStatus = oldLightStatusBars
218
+ val lightNav = oldLightNavigationBars
219
+ if (lightStatus != null || lightNav != null) {
220
+ val controller = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
221
+ if (lightStatus != null) controller.isAppearanceLightStatusBars = lightStatus
222
+ if (lightNav != null) controller.isAppearanceLightNavigationBars = lightNav
223
+ }
224
+ }
225
+
226
+ /** Clamps the duration, drops a partial or non-finite origin, and defaults the direction to left. */
227
+ private fun normalize(request: CoverRequest): CoverRequest {
228
+ val x = request.originX?.takeIf { it.isFinite() }
229
+ val y = request.originY?.takeIf { it.isFinite() }
230
+ val hasOrigin = x != null && y != null
231
+ return request.copy(
232
+ durationMs = request.durationMs.coerceAtLeast(0.0),
233
+ originX = if (hasOrigin) x else null,
234
+ originY = if (hasOrigin) y else null,
235
+ direction = request.direction ?: ThemeTransitionDirection.LEFT,
236
+ )
237
+ }
238
+
239
+ fun capture(requested: CoverRequest, callback: (Boolean) -> Unit) {
240
+ runOnMain {
241
+ // Supersede any in-flight capture or finish animation without removing the current cover,
242
+ // so the new PixelCopy photographs the screen with the existing cover included.
243
+ generation += 1
244
+ val captureGen = generation
245
+ lastOutcome = "pending"
246
+ val runningAnimator = animator
247
+ animator = null
248
+ runningAnimator?.cancel()
249
+
250
+ val prevFinish = pendingFinish
251
+ pendingFinish = null
252
+ prevFinish?.invoke()
253
+
254
+ val target = normalize(requested)
255
+ val style = target.style
256
+
257
+ val keepExistingCoverOrFail: (reason: String) -> Unit = { reason ->
258
+ val fallbackShot = bitmap?.takeIf { !it.isRecycled }
259
+ CoverLog.d {
260
+ if (fallbackShot != null) {
261
+ "capture failed ($reason); reusing the cover already on screen (style=$style)"
262
+ } else {
263
+ "instant: capture failed ($reason), theme switches without animating (style=$style)"
264
+ }
265
+ }
266
+ if (fallbackShot != null) {
267
+ lastOutcome = "reused: $reason"
268
+ request = target
269
+ coverView?.resetEffects()
270
+ callback(true)
271
+ } else {
272
+ lastOutcome = "failed: $reason"
273
+ callback(false)
274
+ }
275
+ }
276
+
277
+ val activity = runCatching { AndroidHost.activity }.getOrNull()
278
+ CoverLog.v {
279
+ "capture request gen=$captureGen style=$style on ${describe(activity)} latest=${id(latestActivity?.get())}"
280
+ }
281
+ if (activity == null || activity.isFinishing || activity.isDestroyed) {
282
+ keepExistingCoverOrFail(if (activity == null) "no Activity" else "Activity finishing or destroyed")
283
+ return@runOnMain
284
+ }
285
+
286
+ val window = activity.window
287
+ val decor = window.decorView as? ViewGroup
288
+ if (decor == null || decor.width <= 0 || decor.height <= 0) {
289
+ keepExistingCoverOrFail("window not laid out yet")
290
+ return@runOnMain
291
+ }
292
+ val captureStart = now()
293
+
294
+ val insetsController = WindowCompat.getInsetsController(window, decor)
295
+ val capturedLightStatus = oldLightStatusBars ?: insetsController.isAppearanceLightStatusBars
296
+ val capturedLightNav = oldLightNavigationBars ?: insetsController.isAppearanceLightNavigationBars
297
+
298
+ val shot =
299
+ try {
300
+ Bitmap.createBitmap(decor.width, decor.height, Bitmap.Config.ARGB_8888)
301
+ } catch (_: Throwable) {
302
+ keepExistingCoverOrFail("bitmap allocation failed")
303
+ return@runOnMain
304
+ }
305
+
306
+ try {
307
+ PixelCopy.request(
308
+ window,
309
+ shot,
310
+ { result ->
311
+ CoverLog.v {
312
+ "PixelCopy gen=$captureGen result=$result after ${now() - captureStart} ms (current gen=$generation); " +
313
+ "requested on ${describe(activity)}; host now ${describe(hostActivity())}; " +
314
+ "latest=${id(latestActivity?.get())}; cover goes on ${id(liveActivity())}"
315
+ }
316
+ if (captureGen != generation) {
317
+ CoverLog.d { "capture superseded by a newer capture or cancel (style=$style)" }
318
+ lastOutcome = "superseded"
319
+ shot.recycle()
320
+ callback(false)
321
+ return@request
322
+ }
323
+ if (result != PixelCopy.SUCCESS) {
324
+ shot.recycle()
325
+ keepExistingCoverOrFail("PixelCopy result $result")
326
+ return@request
327
+ }
328
+
329
+ // A relaunch (theme, rotation) can destroy the photographed Activity while PixelCopy runs (#36).
330
+ // The pixels are still the old frame, so the cover goes on the recreated Activity.
331
+ val currentActivity = liveActivity()
332
+ if (currentActivity == null) {
333
+ shot.recycle()
334
+ keepExistingCoverOrFail("Activity gone after PixelCopy")
335
+ return@request
336
+ }
337
+ lastOutcome = if (currentActivity === activity) "captured" else "captured on the recreated Activity"
338
+
339
+ val previousBitmap = bitmap
340
+ bitmap = shot
341
+ active = true
342
+ request = target
343
+ oldLightStatusBars = capturedLightStatus
344
+ oldLightNavigationBars = capturedLightNav
345
+ attachCover(currentActivity, shot)
346
+ if (previousBitmap != null && previousBitmap !== shot && !previousBitmap.isRecycled) {
347
+ previousBitmap.recycle()
348
+ }
349
+ capturedAt = now()
350
+ finishStartedAt = null
351
+ CoverLog.d {
352
+ buildString {
353
+ append("capture style=$style duration=${target.durationMs.toLong()} ms")
354
+ val x = target.originX
355
+ val y = target.originY
356
+ if (x != null && y != null) append(" origin=(${x.toInt()}, ${y.toInt()})")
357
+ if (requested.direction != null) append(" direction=${requested.direction}")
358
+ append(" (PixelCopy ${capturedAt - captureStart} ms")
359
+ if (previousBitmap != null) append(", interrupts a cover still on screen")
360
+ append(")")
361
+ }
362
+ }
363
+ if (style == ThemeTransitionStyle.BLUR && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
364
+ CoverLog.d { "fallback: blur needs RenderEffect (API 31), fading instead on API ${Build.VERSION.SDK_INT}" }
365
+ }
366
+ callback(true)
367
+ },
368
+ mainHandler,
369
+ )
370
+ } catch (_: Throwable) {
371
+ shot.recycle()
372
+ keepExistingCoverOrFail("PixelCopy request threw")
373
+ }
374
+ }
375
+ }
376
+
377
+ fun finish(completion: () -> Unit) {
378
+ runOnMain {
379
+ val view = coverView
380
+ if (view == null) {
381
+ CoverLog.d { "finish: no cover on screen, nothing to animate" }
382
+ val shot = bitmap
383
+ bitmap = null
384
+ active = false
385
+ oldLightStatusBars = null
386
+ oldLightNavigationBars = null
387
+ if (shot != null && !shot.isRecycled) {
388
+ shot.recycle()
389
+ }
390
+ completion()
391
+ return@runOnMain
392
+ }
393
+
394
+ val prevFinish = pendingFinish
395
+ pendingFinish = completion
396
+ prevFinish?.invoke()
397
+
398
+ val gen = generation
399
+ val current = request
400
+ val currentStyle = current.style
401
+ val currentDuration = current.durationMs.toLong()
402
+ val activity = (view.context as? Activity) ?: runCatching { AndroidHost.activity }.getOrNull()
403
+ val targetLightBars = activity?.let { !isDarkConfiguration(it) }
404
+ val finishStart = now()
405
+ finishStartedAt = finishStart
406
+ CoverLog.d {
407
+ "finish start style=$currentStyle duration=$currentDuration ms (${finishStart - capturedAt} ms after capture)"
408
+ }
409
+
410
+ val complete: () -> Unit = {
411
+ if (gen == generation) {
412
+ CoverLog.d {
413
+ val end = now()
414
+ "finish style=$currentStyle elapsed=${end - finishStart} ms (${end - capturedAt} ms since capture)"
415
+ }
416
+ finishStartedAt = null
417
+ if (activity != null && !activity.isFinishing && !activity.isDestroyed && targetLightBars != null) {
418
+ if (oldLightStatusBars != null || oldLightNavigationBars != null) {
419
+ oldLightStatusBars = null
420
+ oldLightNavigationBars = null
421
+ applySystemBars(activity, targetLightBars, targetLightBars)
422
+ }
423
+ }
424
+ view.resetEffects()
425
+ removeCover(view, "finish")
426
+ if (coverView === view) {
427
+ coverView = null
428
+ }
429
+ val shot = bitmap
430
+ bitmap = null
431
+ active = false
432
+ animator = null
433
+ oldLightStatusBars = null
434
+ oldLightNavigationBars = null
435
+ if (shot != null && !shot.isRecycled) {
436
+ shot.recycle()
437
+ }
438
+ val callback = pendingFinish
439
+ pendingFinish = null
440
+ callback?.invoke()
441
+ }
442
+ }
443
+
444
+ if (currentDuration <= 0L) {
445
+ CoverLog.d { "instant: duration is 0 ms, cover removed without animating" }
446
+ complete()
447
+ return@runOnMain
448
+ }
449
+
450
+ val existingAnimator = animator
451
+ animator = null
452
+ existingAnimator?.cancel()
453
+
454
+ val w = view.width.toFloat()
455
+ val h = view.height.toFloat()
456
+ val density = view.resources.displayMetrics.density
457
+ val cx = current.originX?.let { it.toFloat() * density } ?: (w / 2f)
458
+ val cy = current.originY?.let { it.toFloat() * density } ?: (h / 2f)
459
+ val maxR = hypot(max(abs(cx), abs(w - cx)), max(abs(cy), abs(h - cy)))
460
+ val slideDx = if (current.direction == ThemeTransitionDirection.RIGHT) w else -w
461
+
462
+ var barsFlipped = false
463
+ val revealAnimator =
464
+ ValueAnimator.ofFloat(0f, 1f).apply {
465
+ duration = currentDuration
466
+ interpolator =
467
+ if (currentStyle == ThemeTransitionStyle.SLIDE) {
468
+ AccelerateDecelerateInterpolator()
469
+ } else {
470
+ DecelerateInterpolator()
471
+ }
472
+ addUpdateListener { anim ->
473
+ if (gen != generation) return@addUpdateListener
474
+ val progress = anim.animatedValue as Float
475
+ when (currentStyle) {
476
+ ThemeTransitionStyle.CIRCLE -> view.setHole(cx, cy, progress * maxR)
477
+ // Moves only the drawn snapshot: the view stays full screen, so the strip it uncovers still blocks touches.
478
+ ThemeTransitionStyle.SLIDE -> view.setSlideOffset(slideDx * progress)
479
+ ThemeTransitionStyle.BLUR -> {
480
+ view.setBlur(BLUR_RADIUS_DP * density * progress)
481
+ view.alpha = 1f - progress
482
+ }
483
+ ThemeTransitionStyle.FADE -> view.alpha = 1f - progress
484
+ }
485
+ if (!barsFlipped && anim.animatedFraction >= 0.5f) {
486
+ barsFlipped = true
487
+ oldLightStatusBars = null
488
+ oldLightNavigationBars = null
489
+ if (activity != null && !activity.isFinishing && !activity.isDestroyed && targetLightBars != null) {
490
+ applySystemBars(activity, targetLightBars, targetLightBars)
491
+ }
492
+ }
493
+ }
494
+ addListener(
495
+ object : AnimatorListenerAdapter() {
496
+ override fun onAnimationEnd(animation: Animator) {
497
+ if (gen != generation || animator !== animation) return
498
+ complete()
499
+ }
500
+ },
501
+ )
502
+ }
503
+ animator = revealAnimator
504
+ revealAnimator.start()
505
+ }
506
+ }
507
+
508
+ fun cancel() {
509
+ runOnMain {
510
+ if (coverView != null || bitmap != null) {
511
+ CoverLog.d {
512
+ val end = now()
513
+ val phase = finishStartedAt?.let { "finish animation running for ${end - it} ms" } ?: "finish not started"
514
+ "instant: cover cancelled from JS ${end - capturedAt} ms after capture ($phase); see the JS log for the reason"
515
+ }
516
+ }
517
+ finishStartedAt = null
518
+ generation += 1
519
+ val runningAnimator = animator
520
+ animator = null
521
+ runningAnimator?.cancel()
522
+
523
+ val view = coverView
524
+ coverView = null
525
+ val activity = (view?.context as? Activity) ?: runCatching { AndroidHost.activity }.getOrNull()
526
+ view?.resetEffects()
527
+ removeCover(view, "cancel")
528
+
529
+ val shot = bitmap
530
+ bitmap = null
531
+ active = false
532
+ if (shot != null && !shot.isRecycled) {
533
+ shot.recycle()
534
+ }
535
+
536
+ if (oldLightStatusBars != null || oldLightNavigationBars != null) {
537
+ oldLightStatusBars = null
538
+ oldLightNavigationBars = null
539
+ if (activity != null && !activity.isFinishing && !activity.isDestroyed) {
540
+ val targetLight = !isDarkConfiguration(activity)
541
+ applySystemBars(activity, targetLight, targetLight)
542
+ }
543
+ }
544
+
545
+ val callback = pendingFinish
546
+ pendingFinish = null
547
+ callback?.invoke()
548
+ }
549
+ }
550
+
551
+ private class ThemeCoverView(context: Context, private val shot: Bitmap) : View(context) {
552
+ private val dstRect = Rect()
553
+ private val clearPaint =
554
+ Paint(Paint.ANTI_ALIAS_FLAG).apply {
555
+ xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
556
+ }
557
+ private var holeX = 0f
558
+ private var holeY = 0f
559
+ private var holeRadius = 0f
560
+ private var slideOffset = 0f
561
+
562
+ init {
563
+ setLayerType(LAYER_TYPE_HARDWARE, null)
564
+ isClickable = true
565
+ isFocusable = true
566
+ }
567
+
568
+ fun setHole(x: Float, y: Float, radius: Float) {
569
+ holeX = x
570
+ holeY = y
571
+ holeRadius = radius
572
+ invalidate()
573
+ }
574
+
575
+ /** Draws the snapshot shifted by [dx] px while the view itself keeps covering, and blocking, the whole window. */
576
+ fun setSlideOffset(dx: Float) {
577
+ slideOffset = dx
578
+ invalidate()
579
+ }
580
+
581
+ /** Blurs the cover by [radius] px. RenderEffect needs API 31; older devices ignore it. */
582
+ fun setBlur(radius: Float) {
583
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
584
+ setRenderEffect(
585
+ if (radius > 0.01f) RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP) else null,
586
+ )
587
+ }
588
+ }
589
+
590
+ /** Returns the cover to a fully opaque, unshifted, unblurred snapshot with no circle hole. */
591
+ fun resetEffects() {
592
+ alpha = 1f
593
+ setBlur(0f)
594
+ if (holeRadius != 0f || slideOffset != 0f) {
595
+ holeRadius = 0f
596
+ slideOffset = 0f
597
+ invalidate()
598
+ }
599
+ }
600
+
601
+ override fun onTouchEvent(event: MotionEvent): Boolean = true
602
+
603
+ override fun onDraw(canvas: Canvas) {
604
+ if (shot.isRecycled) return
605
+ dstRect.set(0, 0, width, height)
606
+ if (slideOffset != 0f) {
607
+ canvas.save()
608
+ canvas.translate(slideOffset, 0f)
609
+ canvas.drawBitmap(shot, null, dstRect, null)
610
+ canvas.restore()
611
+ } else {
612
+ canvas.drawBitmap(shot, null, dstRect, null)
613
+ }
614
+ if (holeRadius > 0f) {
615
+ canvas.drawCircle(holeX, holeY, holeRadius, clearPaint)
616
+ }
617
+ }
618
+ }
619
+ }
@@ -0,0 +1,50 @@
1
+ internal import Foundation
2
+ internal import NitroModules
3
+ internal import UIKit
4
+
5
+ final class HybridReducedMotion: HybridReducedMotionSpec {
6
+ private var listeners: [UUID: (Bool) -> Void] = [:]
7
+ private var observer: (any NSObjectProtocol)?
8
+
9
+ override init() throws {
10
+ try super.init()
11
+ observer = NotificationCenter.default.addObserver(
12
+ forName: UIAccessibility.reduceMotionStatusDidChangeNotification,
13
+ object: nil,
14
+ queue: .main
15
+ ) { [weak self] _ in
16
+ self?.emit(UIAccessibility.isReduceMotionEnabled)
17
+ }
18
+ }
19
+
20
+ deinit {
21
+ if let observer {
22
+ NotificationCenter.default.removeObserver(observer)
23
+ }
24
+ }
25
+
26
+ func isReducedMotionEnabled() throws -> Bool {
27
+ UIAccessibility.isReduceMotionEnabled
28
+ }
29
+
30
+ func addOnReducedMotionChangedListener(listener: any Callback<Bool, Void>) throws -> ListenerSubscription {
31
+ let id = UUID()
32
+ listeners[id] = { reducedMotion in
33
+ do {
34
+ try listener.callSync(reducedMotion)
35
+ } catch {
36
+ // Ignore callback errors if the JS listener has already been torn down.
37
+ }
38
+ }
39
+ return ListenerSubscription(remove: .native { [weak self] in
40
+ self?.listeners.removeValue(forKey: id)
41
+ })
42
+ }
43
+
44
+ private func emit(_ reducedMotion: Bool) {
45
+ let currentListeners = Array(listeners.values)
46
+ for listener in currentListeners {
47
+ listener(reducedMotion)
48
+ }
49
+ }
50
+ }