glacia-native 0.5.1 → 0.6.0

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 (403) hide show
  1. package/LICENSE +29 -4
  2. package/README.md +111 -17
  3. package/lib/module/Accordion.js +58 -0
  4. package/lib/module/ActionSheet.js +38 -0
  5. package/lib/module/Alert.js +23 -0
  6. package/lib/module/AlertDialog.js +47 -0
  7. package/lib/module/Avatar.js +48 -0
  8. package/lib/module/Badge.js +36 -0
  9. package/lib/module/Bars.js +13 -267
  10. package/lib/module/Button.js +57 -36
  11. package/lib/module/Card.js +32 -20
  12. package/lib/module/Checkbox.js +42 -0
  13. package/lib/module/Chip.js +80 -0
  14. package/lib/module/Collapsible.js +26 -0
  15. package/lib/module/ContextMenu.js +33 -0
  16. package/lib/module/Dialog.js +39 -124
  17. package/lib/module/DropdownMenu.js +33 -0
  18. package/lib/module/Field.js +22 -0
  19. package/lib/module/Glass.js +12 -5
  20. package/lib/module/Group.js +36 -0
  21. package/lib/module/IconButton.js +40 -0
  22. package/lib/module/Input.js +47 -40
  23. package/lib/module/Label.js +17 -0
  24. package/lib/module/MorphGroup.js +47 -0
  25. package/lib/module/Popover.js +29 -0
  26. package/lib/module/Progress.js +32 -0
  27. package/lib/module/RadioGroup.js +51 -0
  28. package/lib/module/Scrim.js +44 -0
  29. package/lib/module/SegmentedControl.js +74 -58
  30. package/lib/module/Select.js +51 -0
  31. package/lib/module/Separator.js +25 -0
  32. package/lib/module/Sheet.js +51 -0
  33. package/lib/module/Skeleton.js +48 -0
  34. package/lib/module/Slider.js +60 -40
  35. package/lib/module/Stepper.js +167 -0
  36. package/lib/module/Switch.js +45 -43
  37. package/lib/module/TabBar.js +62 -50
  38. package/lib/module/Tabs.js +3 -2
  39. package/lib/module/Textarea.js +18 -0
  40. package/lib/module/Toast.js +55 -0
  41. package/lib/module/Toggle.js +47 -0
  42. package/lib/module/ToggleGroup.js +56 -0
  43. package/lib/module/Toolbar.js +37 -0
  44. package/lib/module/Tooltip.js +31 -0
  45. package/lib/module/glass-provider.js +28 -0
  46. package/lib/module/glass-stack.js +61 -0
  47. package/lib/module/index.js +78 -109
  48. package/lib/module/internal/GlassBackdrop.js +36 -0
  49. package/lib/module/internal/GlassView.js +45 -13
  50. package/lib/module/internal/blur-community.js +20 -0
  51. package/lib/module/internal/blur-community.web.js +9 -0
  52. package/lib/module/internal/blur.js +75 -0
  53. package/lib/module/internal/fallback.js +110 -20
  54. package/lib/module/internal/glass-routing.js +154 -30
  55. package/lib/module/internal/glow.js +36 -0
  56. package/lib/module/internal/initials.js +12 -0
  57. package/lib/module/internal/lens.js +70 -0
  58. package/lib/module/internal/material.js +64 -0
  59. package/lib/module/internal/overlay.js +147 -0
  60. package/lib/module/internal/primitives.js +17 -0
  61. package/lib/module/internal/rim.js +35 -0
  62. package/lib/module/internal/tokens.js +34 -2
  63. package/lib/typescript/Accordion.d.ts +22 -0
  64. package/lib/typescript/ActionSheet.d.ts +24 -0
  65. package/lib/typescript/Alert.d.ts +15 -0
  66. package/lib/typescript/AlertDialog.d.ts +17 -0
  67. package/lib/typescript/Avatar.d.ts +22 -0
  68. package/lib/typescript/Badge.d.ts +12 -0
  69. package/lib/typescript/Bars.d.ts +3 -188
  70. package/lib/typescript/Button.d.ts +44 -10
  71. package/lib/typescript/Card.d.ts +30 -3
  72. package/lib/typescript/Checkbox.d.ts +14 -0
  73. package/lib/typescript/Chip.d.ts +19 -0
  74. package/lib/typescript/Collapsible.d.ts +17 -0
  75. package/lib/typescript/ContextMenu.d.ts +23 -0
  76. package/lib/typescript/Dialog.d.ts +8 -68
  77. package/lib/typescript/DropdownMenu.d.ts +23 -0
  78. package/lib/typescript/Field.d.ts +19 -0
  79. package/lib/typescript/Glass.d.ts +11 -2
  80. package/lib/typescript/Group.d.ts +35 -0
  81. package/lib/typescript/IconButton.d.ts +21 -0
  82. package/lib/typescript/Input.d.ts +17 -18
  83. package/lib/typescript/Label.d.ts +14 -0
  84. package/lib/typescript/MorphGroup.d.ts +46 -0
  85. package/lib/typescript/Popover.d.ts +17 -0
  86. package/lib/typescript/Progress.d.ts +13 -0
  87. package/lib/typescript/RadioGroup.d.ts +21 -0
  88. package/lib/typescript/Scrim.d.ts +33 -0
  89. package/lib/typescript/SegmentedControl.d.ts +24 -13
  90. package/lib/typescript/Select.d.ts +19 -0
  91. package/lib/typescript/Separator.d.ts +10 -0
  92. package/lib/typescript/Sheet.d.ts +45 -0
  93. package/lib/typescript/Skeleton.d.ts +10 -0
  94. package/lib/typescript/Slider.d.ts +15 -7
  95. package/lib/typescript/Stepper.d.ts +49 -0
  96. package/lib/typescript/Switch.d.ts +19 -12
  97. package/lib/typescript/TabBar.d.ts +18 -6
  98. package/lib/typescript/Textarea.d.ts +6 -0
  99. package/lib/typescript/Toast.d.ts +40 -0
  100. package/lib/typescript/Toggle.d.ts +21 -0
  101. package/lib/typescript/ToggleGroup.d.ts +22 -0
  102. package/lib/typescript/Toolbar.d.ts +35 -0
  103. package/lib/typescript/Tooltip.d.ts +16 -0
  104. package/lib/typescript/glass-provider.d.ts +34 -0
  105. package/lib/typescript/glass-stack.d.ts +54 -0
  106. package/lib/typescript/index.d.ts +39 -17
  107. package/lib/typescript/internal/GlassBackdrop.d.ts +33 -0
  108. package/lib/typescript/internal/GlassView.d.ts +31 -2
  109. package/lib/typescript/internal/blur-community.d.ts +2 -0
  110. package/lib/typescript/internal/blur-community.web.d.ts +2 -0
  111. package/lib/typescript/internal/blur.d.ts +24 -0
  112. package/lib/typescript/internal/fallback.d.ts +27 -2
  113. package/lib/typescript/internal/glass-routing.d.ts +83 -15
  114. package/lib/typescript/internal/glow.d.ts +11 -0
  115. package/lib/typescript/internal/initials.d.ts +2 -0
  116. package/lib/typescript/internal/lens.d.ts +47 -0
  117. package/lib/typescript/internal/material.d.ts +27 -0
  118. package/lib/typescript/internal/overlay.d.ts +74 -0
  119. package/lib/typescript/internal/primitives.d.ts +13 -0
  120. package/lib/typescript/internal/rim.d.ts +16 -0
  121. package/lib/typescript/internal/tokens.d.ts +36 -0
  122. package/package.json +15 -4
  123. package/src/Accordion.tsx +165 -0
  124. package/src/ActionSheet.tsx +149 -0
  125. package/src/Alert.tsx +85 -0
  126. package/src/AlertDialog.tsx +124 -0
  127. package/src/Avatar.tsx +102 -0
  128. package/src/Badge.tsx +80 -0
  129. package/src/Bars.tsx +10 -797
  130. package/src/Button.tsx +196 -60
  131. package/src/Card.tsx +106 -33
  132. package/src/Checkbox.tsx +98 -0
  133. package/src/Chip.tsx +149 -0
  134. package/src/Collapsible.tsx +66 -0
  135. package/src/ContextMenu.tsx +103 -0
  136. package/src/Dialog.tsx +86 -325
  137. package/src/DropdownMenu.tsx +103 -0
  138. package/src/Field.tsx +65 -0
  139. package/src/Glass.tsx +19 -5
  140. package/src/Group.tsx +98 -0
  141. package/src/IconButton.tsx +110 -0
  142. package/src/Input.tsx +143 -87
  143. package/src/Label.tsx +56 -0
  144. package/src/MorphGroup.tsx +134 -0
  145. package/src/Popover.tsx +81 -0
  146. package/src/Progress.tsx +83 -0
  147. package/src/RadioGroup.tsx +122 -0
  148. package/src/Scrim.tsx +94 -0
  149. package/src/SegmentedControl.tsx +147 -90
  150. package/src/Select.tsx +136 -0
  151. package/src/Separator.tsx +52 -0
  152. package/src/Sheet.tsx +139 -0
  153. package/src/Skeleton.tsx +77 -0
  154. package/src/Slider.tsx +100 -54
  155. package/src/Stepper.tsx +315 -0
  156. package/src/Switch.tsx +80 -58
  157. package/src/TabBar.tsx +118 -84
  158. package/src/Tabs.tsx +5 -0
  159. package/src/Textarea.tsx +34 -0
  160. package/src/Toast.tsx +131 -0
  161. package/src/Toggle.tsx +113 -0
  162. package/src/ToggleGroup.tsx +129 -0
  163. package/src/Toolbar.tsx +111 -0
  164. package/src/Tooltip.tsx +79 -0
  165. package/src/engine/CHANGELOG.md +430 -0
  166. package/src/engine/NOTICE +54 -0
  167. package/src/engine/README.md +975 -0
  168. package/src/engine/android/build.gradle +18 -0
  169. package/src/engine/android/src/main/AndroidManifest.xml +2 -0
  170. package/src/engine/android/src/main/java/expo/modules/liquidglass/ExpoLiquidGlassModule.kt +174 -0
  171. package/src/engine/android/src/main/java/expo/modules/liquidglass/GlassConstants.kt +7 -0
  172. package/src/engine/android/src/main/java/expo/modules/liquidglass/LiquidGlassContainerView.kt +16 -0
  173. package/src/engine/android/src/main/java/expo/modules/liquidglass/LiquidGlassProviderView.kt +165 -0
  174. package/src/engine/android/src/main/java/expo/modules/liquidglass/LiquidGlassView.kt +1731 -0
  175. package/src/engine/android/src/main/java/expo/modules/liquidglass/enums/GlassEnums.kt +171 -0
  176. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/BackdropGraph.kt +146 -0
  177. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/BackdropSource.kt +53 -0
  178. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/ContinuousCorners.kt +188 -0
  179. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/CornerRadii.kt +62 -0
  180. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassAppearance.kt +352 -0
  181. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassDebug.kt +109 -0
  182. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassEnvironment.kt +139 -0
  183. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassHdr.kt +85 -0
  184. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassLuminanceProbe.kt +189 -0
  185. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassPressAnimator.kt +264 -0
  186. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassProgressiveBlur.kt +249 -0
  187. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassShaderCache.kt +256 -0
  188. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassShaderSource.kt +845 -0
  189. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/GlassTier.kt +63 -0
  190. package/src/engine/android/src/main/java/expo/modules/liquidglass/glass/ProviderRegistry.kt +71 -0
  191. package/src/engine/android/src/main/java/expo/modules/liquidglass/records/GlassRecords.kt +288 -0
  192. package/src/engine/index.ts +24 -0
  193. package/src/engine/ios/Enums/GlassBlurDirection.swift +21 -0
  194. package/src/engine/ios/Enums/GlassVariant.swift +86 -0
  195. package/src/engine/ios/ExpoLiquidGlass.podspec +93 -0
  196. package/src/engine/ios/ExpoLiquidGlassModule.swift +77 -0
  197. package/src/engine/ios/Glass/BackdropCapturer.swift +811 -0
  198. package/src/engine/ios/Glass/ContinuousCorners.swift +165 -0
  199. package/src/engine/ios/Glass/GlassBackdrop.swift +176 -0
  200. package/src/engine/ios/Glass/GlassFramePhase.swift +126 -0
  201. package/src/engine/ios/Glass/GlassFrameScheduler.swift +261 -0
  202. package/src/engine/ios/Glass/GlassPressAnimator.swift +250 -0
  203. package/src/engine/ios/Glass/GlassRenderContext.swift +168 -0
  204. package/src/engine/ios/Glass/GlassRenderer.swift +186 -0
  205. package/src/engine/ios/Glass/GlassSurfaceView.swift +452 -0
  206. package/src/engine/ios/Glass/NonRenderableView.swift +54 -0
  207. package/src/engine/ios/Glass/StripCache.swift +545 -0
  208. package/src/engine/ios/Records/GlassCornerRadii.swift +79 -0
  209. package/src/engine/ios/Records/GlassMetalOptions.swift +180 -0
  210. package/src/engine/ios/Records/GlassRefractionCurve.swift +14 -0
  211. package/src/engine/ios/Shaders/LiquidGlass.metal +480 -0
  212. package/src/engine/ios/Shaders/bundle-marker.txt +6 -0
  213. package/src/engine/ios/Views/LiquidGlassContainerView.swift +99 -0
  214. package/src/engine/ios/Views/LiquidGlassView.swift +859 -0
  215. package/src/engine/package.json +70 -0
  216. package/src/engine/src/components/LiquidGlassButton/LiquidGlassButton.tsx +424 -0
  217. package/src/engine/src/components/LiquidGlassCard/LiquidGlassCard.tsx +98 -0
  218. package/src/engine/src/components/LiquidGlassChip/LiquidGlassChip.tsx +65 -0
  219. package/src/engine/src/components/LiquidGlassGroup/LiquidGlassGroup.tsx +350 -0
  220. package/src/engine/src/components/LiquidGlassIconButton/LiquidGlassIconButton.tsx +24 -0
  221. package/src/engine/src/components/LiquidGlassMorphGroup/LiquidGlassMorphGroup.tsx +434 -0
  222. package/src/engine/src/components/LiquidGlassScrim/LiquidGlassScrim.tsx +100 -0
  223. package/src/engine/src/components/LiquidGlassSegmentedControl/LiquidGlassSegmentedControl.tsx +213 -0
  224. package/src/engine/src/components/LiquidGlassSheet/LiquidGlassSheet.tsx +218 -0
  225. package/src/engine/src/components/LiquidGlassSlider/LiquidGlassSlider.tsx +327 -0
  226. package/src/engine/src/components/LiquidGlassStepper/LiquidGlassStepper.tsx +321 -0
  227. package/src/engine/src/components/LiquidGlassSwitch/LiquidGlassSwitch.tsx +296 -0
  228. package/src/engine/src/components/LiquidGlassTabBar/LiquidGlassTabBar.tsx +952 -0
  229. package/src/engine/src/components/LiquidGlassTextInput/LiquidGlassTextInput.tsx +151 -0
  230. package/src/engine/src/components/LiquidGlassToast/LiquidGlassToast.tsx +169 -0
  231. package/src/engine/src/components/LiquidGlassToolbar/LiquidGlassToolbar.tsx +124 -0
  232. package/src/engine/src/components/index.ts +16 -0
  233. package/src/engine/src/constants/index.ts +4 -0
  234. package/src/engine/src/constants/metal.constants.ts +327 -0
  235. package/src/engine/src/constants/metrics.constants.ts +325 -0
  236. package/src/engine/src/constants/springs.constants.ts +107 -0
  237. package/src/engine/src/constants/styles.constants.ts +12 -0
  238. package/src/engine/src/context/glass-group.context.ts +65 -0
  239. package/src/engine/src/context/index.ts +6 -0
  240. package/src/engine/src/core/components/LiquidGlassContainer/LiquidGlassContainer.tsx +32 -0
  241. package/src/engine/src/core/components/LiquidGlassContainer/index.ts +1 -0
  242. package/src/engine/src/core/components/LiquidGlassProvider/LiquidGlassProvider.tsx +66 -0
  243. package/src/engine/src/core/components/LiquidGlassProvider/index.ts +1 -0
  244. package/src/engine/src/core/components/LiquidGlassStack/LiquidGlassStack.tsx +184 -0
  245. package/src/engine/src/core/components/LiquidGlassStack/index.ts +1 -0
  246. package/src/engine/src/core/components/LiquidGlassView/LiquidGlassView.tsx +126 -0
  247. package/src/engine/src/core/components/LiquidGlassView/index.ts +1 -0
  248. package/src/engine/src/core/components/index.ts +4 -0
  249. package/src/engine/src/core/constants/glass.constants.ts +57 -0
  250. package/src/engine/src/core/constants/index.ts +20 -0
  251. package/src/engine/src/core/constants/native.constants.ts +16 -0
  252. package/src/engine/src/core/context/glass-stack.context.ts +30 -0
  253. package/src/engine/src/core/context/index.ts +4 -0
  254. package/src/engine/src/core/enum/index.ts +12 -0
  255. package/src/engine/src/core/index.ts +1 -0
  256. package/src/engine/src/core/interfaces/glass-hdr.interface.ts +15 -0
  257. package/src/engine/src/core/interfaces/glass-metal.interface.ts +248 -0
  258. package/src/engine/src/core/interfaces/glass-surface.interface.ts +9 -0
  259. package/src/engine/src/core/interfaces/index.ts +31 -0
  260. package/src/engine/src/core/interfaces/liquid-glass-container.interface.ts +6 -0
  261. package/src/engine/src/core/interfaces/liquid-glass-provider.interface.ts +14 -0
  262. package/src/engine/src/core/interfaces/liquid-glass-stack.interface.ts +21 -0
  263. package/src/engine/src/core/interfaces/liquid-glass-view.interface.ts +129 -0
  264. package/src/engine/src/core/interfaces/native-liquid-glass-view.interface.ts +19 -0
  265. package/src/engine/src/core/modules/ExpoLiquidGlassModule.ts +26 -0
  266. package/src/engine/src/core/modules/index.ts +2 -0
  267. package/src/engine/src/core/root/index.ts +51 -0
  268. package/src/engine/src/core/types/glass.types.ts +25 -0
  269. package/src/engine/src/core/types/index.ts +8 -0
  270. package/src/engine/src/core/utils/debug.utils.ts +17 -0
  271. package/src/engine/src/core/utils/dev-warn.utils.ts +17 -0
  272. package/src/engine/src/core/utils/hdr.utils.ts +37 -0
  273. package/src/engine/src/core/utils/index.ts +5 -0
  274. package/src/engine/src/core/utils/native-view.utils.ts +33 -0
  275. package/src/engine/src/core/utils/platform.utils.ts +34 -0
  276. package/src/engine/src/core/views/NativeGlassBackdropView.ts +24 -0
  277. package/src/engine/src/core/views/NativeLiquidGlassContainerView.ts +13 -0
  278. package/src/engine/src/core/views/NativeLiquidGlassContainerView.web.ts +10 -0
  279. package/src/engine/src/core/views/NativeLiquidGlassProviderView.ts +13 -0
  280. package/src/engine/src/core/views/NativeLiquidGlassProviderView.web.ts +10 -0
  281. package/src/engine/src/core/views/NativeLiquidGlassView.ts +19 -0
  282. package/src/engine/src/core/views/NativeLiquidGlassView.web.ts +14 -0
  283. package/src/engine/src/core/views/index.ts +4 -0
  284. package/src/engine/src/hooks/index.ts +18 -0
  285. package/src/engine/src/hooks/use-adaptive-glass.ts +91 -0
  286. package/src/engine/src/hooks/use-damped-drag.ts +332 -0
  287. package/src/engine/src/hooks/use-echo-filter.ts +55 -0
  288. package/src/engine/src/hooks/use-glass-group-member.ts +169 -0
  289. package/src/engine/src/hooks/use-gravity-highlight.ts +79 -0
  290. package/src/engine/src/hooks/use-press-progress.ts +44 -0
  291. package/src/engine/src/index.ts +120 -0
  292. package/src/engine/src/interfaces/index.ts +28 -0
  293. package/src/engine/src/interfaces/liquid-glass-button.interface.ts +94 -0
  294. package/src/engine/src/interfaces/liquid-glass-card.interface.ts +40 -0
  295. package/src/engine/src/interfaces/liquid-glass-chip.interface.ts +29 -0
  296. package/src/engine/src/interfaces/liquid-glass-group.interface.ts +32 -0
  297. package/src/engine/src/interfaces/liquid-glass-icon-button.interface.ts +19 -0
  298. package/src/engine/src/interfaces/liquid-glass-morph-group.interface.ts +59 -0
  299. package/src/engine/src/interfaces/liquid-glass-scrim.interface.ts +36 -0
  300. package/src/engine/src/interfaces/liquid-glass-segmented-control.interface.ts +32 -0
  301. package/src/engine/src/interfaces/liquid-glass-sheet.interface.ts +38 -0
  302. package/src/engine/src/interfaces/liquid-glass-slider.interface.ts +37 -0
  303. package/src/engine/src/interfaces/liquid-glass-stepper.interface.ts +35 -0
  304. package/src/engine/src/interfaces/liquid-glass-switch.interface.ts +27 -0
  305. package/src/engine/src/interfaces/liquid-glass-tab-bar.interface.ts +116 -0
  306. package/src/engine/src/interfaces/liquid-glass-text-input.interface.ts +42 -0
  307. package/src/engine/src/interfaces/liquid-glass-toast.interface.ts +36 -0
  308. package/src/engine/src/interfaces/liquid-glass-toolbar.interface.ts +33 -0
  309. package/src/engine/src/theme/glass-ui-theme.ts +100 -0
  310. package/src/engine/src/theme/index.ts +2 -0
  311. package/src/engine/src/utils/button-press.utils.ts +63 -0
  312. package/src/engine/src/utils/index.ts +3 -0
  313. package/src/engine/src/utils/metal.utils.ts +164 -0
  314. package/src/glass-provider.tsx +60 -0
  315. package/src/glass-stack.tsx +115 -0
  316. package/src/index.ts +48 -190
  317. package/src/internal/GlassBackdrop.tsx +60 -0
  318. package/src/internal/GlassView.tsx +70 -18
  319. package/src/internal/blur-community.ts +19 -0
  320. package/src/internal/blur-community.web.ts +7 -0
  321. package/src/internal/blur.ts +89 -0
  322. package/src/internal/fallback.tsx +158 -20
  323. package/src/internal/glass-routing.ts +211 -34
  324. package/src/internal/glow.tsx +62 -0
  325. package/src/internal/initials.ts +7 -0
  326. package/src/internal/lens.tsx +105 -0
  327. package/src/internal/material.ts +92 -0
  328. package/src/internal/overlay.tsx +258 -0
  329. package/src/internal/primitives.ts +26 -0
  330. package/src/internal/rim.tsx +79 -0
  331. package/src/internal/tokens.ts +34 -1
  332. package/lib/module/Carousel.js +0 -103
  333. package/lib/module/Display.js +0 -317
  334. package/lib/module/Feedback.js +0 -386
  335. package/lib/module/Form.js +0 -164
  336. package/lib/module/Forms2.js +0 -454
  337. package/lib/module/Message.js +0 -88
  338. package/lib/module/Overlays.js +0 -328
  339. package/lib/module/Pickers.js +0 -243
  340. package/lib/module/Table.js +0 -99
  341. package/lib/module/ai.js +0 -280
  342. package/lib/module/charts/AreaChart.js +0 -32
  343. package/lib/module/charts/BarChart.js +0 -67
  344. package/lib/module/charts/FunnelChart.js +0 -50
  345. package/lib/module/charts/HeatmapChart.js +0 -71
  346. package/lib/module/charts/LineChart.js +0 -81
  347. package/lib/module/charts/PlotChart.js +0 -52
  348. package/lib/module/charts/RadarChart.js +0 -78
  349. package/lib/module/charts/RingChart.js +0 -52
  350. package/lib/module/charts/ScatterChart.js +0 -95
  351. package/lib/module/charts/WaterfallChart.js +0 -85
  352. package/lib/module/charts/advanced.js +0 -313
  353. package/lib/module/charts/extra.js +0 -108
  354. package/lib/module/charts/index.js +0 -50
  355. package/lib/module/charts/scales.js +0 -140
  356. package/lib/typescript/Carousel.d.ts +0 -47
  357. package/lib/typescript/Display.d.ts +0 -178
  358. package/lib/typescript/Feedback.d.ts +0 -196
  359. package/lib/typescript/Form.d.ts +0 -97
  360. package/lib/typescript/Forms2.d.ts +0 -209
  361. package/lib/typescript/Message.d.ts +0 -71
  362. package/lib/typescript/Overlays.d.ts +0 -146
  363. package/lib/typescript/Pickers.d.ts +0 -105
  364. package/lib/typescript/Table.d.ts +0 -64
  365. package/lib/typescript/ai.d.ts +0 -166
  366. package/lib/typescript/charts/AreaChart.d.ts +0 -44
  367. package/lib/typescript/charts/BarChart.d.ts +0 -19
  368. package/lib/typescript/charts/FunnelChart.d.ts +0 -25
  369. package/lib/typescript/charts/HeatmapChart.d.ts +0 -23
  370. package/lib/typescript/charts/LineChart.d.ts +0 -30
  371. package/lib/typescript/charts/PlotChart.d.ts +0 -31
  372. package/lib/typescript/charts/RadarChart.d.ts +0 -27
  373. package/lib/typescript/charts/RingChart.d.ts +0 -28
  374. package/lib/typescript/charts/ScatterChart.d.ts +0 -34
  375. package/lib/typescript/charts/WaterfallChart.d.ts +0 -22
  376. package/lib/typescript/charts/advanced.d.ts +0 -107
  377. package/lib/typescript/charts/extra.d.ts +0 -63
  378. package/lib/typescript/charts/index.d.ts +0 -13
  379. package/lib/typescript/charts/scales.d.ts +0 -35
  380. package/src/Carousel.tsx +0 -233
  381. package/src/Display.tsx +0 -778
  382. package/src/Feedback.tsx +0 -969
  383. package/src/Form.tsx +0 -425
  384. package/src/Forms2.tsx +0 -1014
  385. package/src/Message.tsx +0 -219
  386. package/src/Overlays.tsx +0 -685
  387. package/src/Pickers.tsx +0 -590
  388. package/src/Table.tsx +0 -231
  389. package/src/ai.tsx +0 -707
  390. package/src/charts/AreaChart.tsx +0 -73
  391. package/src/charts/BarChart.tsx +0 -183
  392. package/src/charts/FunnelChart.tsx +0 -125
  393. package/src/charts/HeatmapChart.tsx +0 -155
  394. package/src/charts/LineChart.tsx +0 -247
  395. package/src/charts/PlotChart.tsx +0 -168
  396. package/src/charts/RadarChart.tsx +0 -208
  397. package/src/charts/RingChart.tsx +0 -133
  398. package/src/charts/ScatterChart.tsx +0 -223
  399. package/src/charts/WaterfallChart.tsx +0 -201
  400. package/src/charts/advanced.tsx +0 -676
  401. package/src/charts/extra.tsx +0 -242
  402. package/src/charts/index.ts +0 -86
  403. package/src/charts/scales.ts +0 -163
@@ -0,0 +1,1731 @@
1
+ package expo.modules.liquidglass
2
+
3
+ import android.content.Context
4
+ import android.content.res.Configuration
5
+ import android.graphics.Canvas
6
+ import android.graphics.Color
7
+ import android.graphics.ColorMatrix
8
+ import android.graphics.ColorMatrixColorFilter
9
+ import android.graphics.LinearGradient
10
+ import android.graphics.Matrix
11
+ import android.graphics.Paint
12
+ import android.graphics.Path
13
+ import android.graphics.PorterDuff
14
+ import android.graphics.PorterDuffXfermode
15
+ import android.graphics.RadialGradient
16
+ import android.graphics.RectF
17
+ import android.graphics.RenderEffect
18
+ import android.graphics.RenderNode
19
+ import android.graphics.Shader
20
+ import android.os.Build
21
+ import android.util.Log
22
+ import android.view.MotionEvent
23
+ import android.view.View
24
+ import android.view.ViewTreeObserver
25
+ import androidx.annotation.RequiresApi
26
+ import expo.modules.kotlin.AppContext
27
+ import expo.modules.kotlin.viewevent.EventDispatcher
28
+ import expo.modules.kotlin.views.ExpoView
29
+ import expo.modules.liquidglass.enums.GlassBackend
30
+ import expo.modules.liquidglass.enums.GlassCornerStyle
31
+ import expo.modules.liquidglass.enums.GlassQuality
32
+ import expo.modules.liquidglass.enums.GlassVariant
33
+ import expo.modules.liquidglass.glass.BackdropConsumer
34
+ import expo.modules.liquidglass.glass.BackdropGraph
35
+ import expo.modules.liquidglass.glass.BackdropSource
36
+ import expo.modules.liquidglass.glass.ContinuousCorners
37
+ import expo.modules.liquidglass.glass.CornerRadii
38
+ import expo.modules.liquidglass.glass.GlassAppearance
39
+ import expo.modules.liquidglass.glass.GlassDebug
40
+ import expo.modules.liquidglass.glass.GlassEnvironment
41
+ import expo.modules.liquidglass.glass.GlassHdr
42
+ import expo.modules.liquidglass.glass.GlassLuminanceProbe
43
+ import expo.modules.liquidglass.glass.GlassPressAnimator
44
+ import expo.modules.liquidglass.glass.GlassShaderCache
45
+ import expo.modules.liquidglass.glass.GlassShaderSource
46
+ import expo.modules.liquidglass.glass.GlassTier
47
+ import expo.modules.liquidglass.glass.GlassProgressiveBlur
48
+ import expo.modules.liquidglass.glass.ProviderRegistry
49
+ import expo.modules.liquidglass.glass.ShaderQuality
50
+ import expo.modules.liquidglass.records.GlassGlowOptions
51
+ import expo.modules.liquidglass.records.GlassMetalOptions
52
+ import kotlin.math.abs
53
+ import kotlin.math.max
54
+ import kotlin.math.min
55
+
56
+ /**
57
+ * The glass surface.
58
+ *
59
+ * React children are **not** re-parented — `ExpoView` is a `ViewGroup` and React Native's mounting
60
+ * layer applies Yoga frames to them directly. The glass is drawn in `dispatchDraw` *before*
61
+ * `super.dispatchDraw(canvas)`, which keeps children fully interactive and makes `containerStyle`
62
+ * work with no Kotlin code at all.
63
+ *
64
+ * The effect chain goes on this view's own padded [RenderNode] — never on the provider's node, and
65
+ * never via `View.setRenderEffect`, which cannot be cropped and clips to the view bounds.
66
+ *
67
+ * There are three draw paths, picked by [tier]:
68
+ *
69
+ * | Tier | API | Path |
70
+ * |---------|-------|------|
71
+ * | `FULL` | 33+ | the AGSL shader: refraction, dispersion, highlight, frost and tint all in one pass |
72
+ * | `BLUR` | 31–32 | `createBlurEffect` on the backdrop, then frost and tint on the canvas, clipped |
73
+ * | `SCRIM` | 29–30 | the backdrop untouched, then frost and tint on the canvas, clipped |
74
+ */
75
+ class LiquidGlassView(context: Context, appContext: AppContext) :
76
+ ExpoView(context, appContext), BackdropConsumer {
77
+
78
+ // ---------------------------------------------------------------- props (raw, as they arrive)
79
+
80
+ /** Which [LiquidGlassProviderView] supplies this view's backdrop. */
81
+ var providerId: String = DEFAULT_PROVIDER_ID
82
+ set(value) {
83
+ if (field == value) return
84
+ field = value
85
+ detachFromProviders()
86
+ invalidate()
87
+ }
88
+
89
+ /**
90
+ * Combined backdrop: multiple providers composited in list order — first at the bottom. The
91
+ * nested-layer pattern reads `[screen, layer]`, so a pill over a glass bar refracts the bar
92
+ * *composited over* the content behind it, exactly what the eye sees under the pill — Kyant's
93
+ * `CombinedBackdrop`, ported. When set (non-empty) this wins over [providerId].
94
+ */
95
+ var providerIds: List<String>? = null
96
+ set(value) {
97
+ if (field == value) return
98
+ field = value
99
+ detachFromProviders()
100
+ invalidate()
101
+ }
102
+
103
+ var variant: GlassVariant = GlassVariant.regular
104
+ var backend: GlassBackend = GlassBackend.auto
105
+
106
+ /**
107
+ * iOS's `CALayerCornerCurve`, honoured for real since the squircle port: `continuous` renders
108
+ * the calibrated Apple corner family in the SDF, the clip and the border
109
+ * (`ContinuousCorners`, research/05). No setter side effects needed — `onPropsUpdated`
110
+ * invalidates geometry and effect after every prop batch.
111
+ */
112
+ var cornerStyle: GlassCornerStyle = GlassCornerStyle.continuous
113
+
114
+ /** Already `processColor`ed on the JS side — see the module definition for why. */
115
+ var tint: Int? = null
116
+
117
+ /** The wash that draws: the recipe's own `metal.tint` when it carries one, else the prop. */
118
+ private val effectiveTint: Int?
119
+ get() = metal?.tint ?: tint
120
+
121
+ /**
122
+ * iOS 26's `isInteractive`, ported: a spring-driven specular that blooms under the finger and
123
+ * follows it, plus a subtle whole-view inflation. Still ignored by iOS's Metal path — this is
124
+ * the Android implementation of the system behaviour.
125
+ */
126
+ var isInteractive: Boolean = false
127
+ set(value) {
128
+ if (field == value) return
129
+ field = value
130
+ if (!value) {
131
+ // Mid-press prop flip: stop dead and restore rest state, including any RN transform.
132
+ ownsGesture = false
133
+ removeCallbacks(holdToOwnRunnable)
134
+ pressAnimator?.reset()
135
+ applyPressTransform(1f, 1f, 0f, 0f)
136
+ effectDirty = true
137
+ invalidate()
138
+ }
139
+ }
140
+
141
+ /**
142
+ * A press choreographed by the app, usually one happening on some *other* view — see
143
+ * [GlassGlowOptions]. Non-null takes over the press uniforms entirely, so [isInteractive]'s own
144
+ * animator stops reaching the shader while this is set; null hands them straight back.
145
+ *
146
+ * Cheap to animate: the glass uniforms are re-uploaded and the view redrawn, and nothing else in
147
+ * the pipeline is touched — no geometry rebuild, no backdrop re-record, no change to the padding
148
+ * budget. Reanimated's `useAnimatedProps` drives it per frame without a JS round trip.
149
+ */
150
+ var glow: GlassGlowOptions? = null
151
+ set(value) {
152
+ field = value
153
+ effectDirty = true
154
+ invalidate()
155
+ }
156
+
157
+ var metal: GlassMetalOptions? = null
158
+
159
+ /**
160
+ * The `adaptive` prop: the glass reads the mean luminance of the backdrop under it (a
161
+ * [GlassLuminanceProbe], at most every [LUMINANCE_PROBE_INTERVAL_MS]), reports it through
162
+ * `onBackdropLuminance`, and lets the frost's polarity follow the backdrop instead of the
163
+ * colour scheme — dark content gets the dark frost and light content the light one, which is
164
+ * what makes the content ON the glass legible when the kit flips its palette to match. The
165
+ * flip has hysteresis ([ADAPTIVE_DARK_BELOW] / [ADAPTIVE_LIGHT_ABOVE]) and crosses over
166
+ * [FROST_CROSSFADE_MS]. Off, the frost is the scheme's, exactly as before.
167
+ */
168
+ var isAdaptive: Boolean = false
169
+ set(value) {
170
+ if (field == value) return
171
+ field = value
172
+ removeCallbacks(luminanceProbeRunnable)
173
+ luminanceProbePosted = false
174
+ removeCallbacks(frostCrossfadeStep)
175
+ frostCrossfadePosted = false
176
+ if (!value) {
177
+ luminanceProbe?.release()
178
+ luminanceProbe = null
179
+ lastEmittedLuminance = Float.NaN
180
+ }
181
+ // Either way the frost starts from the scheme's polarity; adaptive earns its way off it.
182
+ frostPolarityDark = isDarkMode()
183
+ frostDarkTarget = if (frostPolarityDark) 1f else 0f
184
+ frostDarkMix = frostDarkTarget
185
+ effectDirty = true
186
+ invalidate()
187
+ }
188
+
189
+ /** `internal`, because [CornerRadii] is not part of this package's API. */
190
+ internal var rawCornerRadii: CornerRadii = CornerRadii.ZERO
191
+
192
+ // -------------------------------------------------------------------- resolved / derived state
193
+
194
+ private val density: Float get() = resources.displayMetrics.density
195
+
196
+ private var appearance: GlassAppearance =
197
+ GlassAppearance.resolve(GlassVariant.regular, null, 1f)
198
+
199
+ /**
200
+ * `metal.android.quality`, or null when the caller left the choice to us.
201
+ *
202
+ * The distinction is the whole of **R4**: an explicit value is an escape hatch and is honoured
203
+ * exactly, size be damned, while an absent one is resolved from screen coverage by
204
+ * [resolveShaderQuality].
205
+ */
206
+ private var requestedQuality: ShaderQuality? = null
207
+
208
+ /** Which compiled shader variant this view actually draws with. */
209
+ private var shaderQuality: ShaderQuality = ShaderQuality.MEDIUM
210
+
211
+ /** `metal.android.maxTier`, resolved. Null means "whatever the device supports". */
212
+ private var tierCeiling: GlassTier? = null
213
+
214
+ /** The tier this view is actually drawing at. */
215
+ private var tier: GlassTier = resolveTier()
216
+
217
+ /** [rawCornerRadii] clamped to this view's current size. Recomputed on size change. */
218
+ private var clampedRadii: CornerRadii = CornerRadii.ZERO
219
+
220
+ private val clipPath = Path()
221
+ private val borderPath = Path()
222
+ private val bounds = RectF()
223
+ private val borderBounds = RectF()
224
+ private val pathRadii = FloatArray(8)
225
+
226
+ /** Per-corner cell extents/exponents in [CornerRadii] field order (TL, TR, BR, BL). */
227
+ private val cornerExtents = FloatArray(4)
228
+ private val cornerShapes = FloatArray(4)
229
+ private val borderExtents = FloatArray(4)
230
+ private val borderShapes = FloatArray(4)
231
+
232
+ /** Scratch for the shader's (BL, BR, TR, TL) packing. */
233
+ private val shaderVec = FloatArray(4)
234
+ private var geometryValid = false
235
+
236
+ /**
237
+ * The Kotlin property name *is* the event name, and it must match `Events("onRendererChange")`
238
+ * exactly — otherwise the event is silently dropped with a "wasn't exported" warning.
239
+ */
240
+ private val onRendererChange by EventDispatcher<Map<String, Any>>()
241
+
242
+ /** `{ luminance: 0..1 }`, the backdrop's mean luma under this view — see [isAdaptive]. */
243
+ private val onBackdropLuminance by EventDispatcher<Map<String, Any>>()
244
+
245
+ // ---------------------------------------------------------------------- adaptive luminance
246
+
247
+ private var luminanceProbe: GlassLuminanceProbe? = null
248
+ private var luminanceProbePosted = false
249
+ private var lastLuminanceProbeMs = 0L
250
+ private var lastEmittedLuminance = Float.NaN
251
+
252
+ /**
253
+ * A recording arrived while a probe was in flight. The probe takes one request at a time, and
254
+ * a mounting screen records several times in its first frames — the reading in flight may be
255
+ * of a half-built backdrop, and without this the settled content would never be re-read.
256
+ */
257
+ private var luminanceProbeDirty = false
258
+
259
+ /** The polarity the frost currently follows (true = dark frost), with hysteresis. */
260
+ private var frostPolarityDark = false
261
+
262
+ /** 0 = the light frost (white), 1 = the dark one (black); crossfades between the two. */
263
+ private var frostDarkMix = 0f
264
+ private var frostDarkTarget = 0f
265
+ private var frostCrossfadePosted = false
266
+ private var frostCrossfadeLastNanos = 0L
267
+
268
+ private val luminanceProbeRunnable = Runnable {
269
+ luminanceProbePosted = false
270
+ runLuminanceProbe()
271
+ }
272
+
273
+ /**
274
+ * The frost crossfade, stepped in the animation stage like the press springs — posted only
275
+ * while the mix is moving, so a settled polarity costs no frames.
276
+ */
277
+ private val frostCrossfadeStep = object : Runnable {
278
+ override fun run() {
279
+ frostCrossfadePosted = false
280
+ if (!isAttachedToWindow) return
281
+ val now = System.nanoTime()
282
+ val dt = ((now - frostCrossfadeLastNanos) / 1e6f).coerceIn(0f, 64f)
283
+ frostCrossfadeLastNanos = now
284
+ val step = dt / FROST_CROSSFADE_MS
285
+ frostDarkMix = if (frostDarkTarget > frostDarkMix) {
286
+ min(frostDarkMix + step, frostDarkTarget)
287
+ } else {
288
+ max(frostDarkMix - step, frostDarkTarget)
289
+ }
290
+ effectDirty = true
291
+ invalidate()
292
+ if (frostDarkMix != frostDarkTarget) {
293
+ frostCrossfadePosted = true
294
+ postOnAnimation(this)
295
+ }
296
+ }
297
+ }
298
+
299
+ /** Posted from the draw path, so the probe's own sync never runs inside a traversal. */
300
+ private fun scheduleLuminanceProbe() {
301
+ if (!isAdaptive || luminanceProbePosted) return
302
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
303
+ val now = android.os.SystemClock.uptimeMillis()
304
+ val wait = (lastLuminanceProbeMs + LUMINANCE_PROBE_INTERVAL_MS - now).coerceAtLeast(0L)
305
+ luminanceProbePosted = true
306
+ postDelayed(luminanceProbeRunnable, wait)
307
+ }
308
+
309
+ @RequiresApi(Build.VERSION_CODES.Q)
310
+ private fun runLuminanceProbe() {
311
+ if (!isAdaptive || !isAttachedToWindow || providers.isEmpty()) return
312
+ if (recordedTransforms.size != providers.size) return
313
+ val probe = luminanceProbe ?: GlassLuminanceProbe().also { luminanceProbe = it }
314
+ luminanceProbeDirty = false
315
+ val accepted = probe.request(providers, recordedTransforms, width, height) { luminance ->
316
+ if (!isAttachedToWindow || !isAdaptive) return@request
317
+ onBackdropLuminance(luminance)
318
+ // Whatever changed under us while this reading was in flight gets its own.
319
+ if (luminanceProbeDirty) scheduleLuminanceProbe()
320
+ }
321
+ if (accepted) {
322
+ lastLuminanceProbeMs = android.os.SystemClock.uptimeMillis()
323
+ } else {
324
+ luminanceProbeDirty = true
325
+ }
326
+ }
327
+
328
+ private fun onBackdropLuminance(luminance: Float) {
329
+ // Hysteresis: a bar sitting on a mid-grey card must not flap between palettes.
330
+ val dark = if (frostPolarityDark) luminance < ADAPTIVE_LIGHT_ABOVE else luminance < ADAPTIVE_DARK_BELOW
331
+ if (dark != frostPolarityDark) {
332
+ frostPolarityDark = dark
333
+ frostDarkTarget = if (dark) 1f else 0f
334
+ if (!frostCrossfadePosted) {
335
+ frostCrossfadePosted = true
336
+ frostCrossfadeLastNanos = System.nanoTime()
337
+ postOnAnimation(frostCrossfadeStep)
338
+ }
339
+ }
340
+ // The raw value crosses to JS whenever it has moved enough to matter, or the polarity did.
341
+ val moved =
342
+ lastEmittedLuminance.isNaN() || abs(luminance - lastEmittedLuminance) >= LUMINANCE_EMIT_DELTA
343
+ if (moved || dark != frostPolarityDark) {
344
+ lastEmittedLuminance = luminance
345
+ this.onBackdropLuminance(mapOf("luminance" to luminance.toDouble(), "dark" to dark))
346
+ }
347
+ }
348
+
349
+ /** What the frost mixes toward: the scheme's polarity, or the backdrop's while adaptive. */
350
+ private val frostDarkness: Float
351
+ get() = if (isAdaptive) frostDarkMix else if (isDarkMode()) 1f else 0f
352
+
353
+ /** Last value sent to JS, so we only emit on a genuine change (matching iOS). */
354
+ private var reportedRenderer: String? = null
355
+
356
+ private val glassNode: RenderNode? =
357
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) RenderNode("LiquidGlass") else null
358
+
359
+ /** Resolved in [requestedProviderIds] order; empty until every requested id resolves. */
360
+ private val providers = ArrayList<BackdropSource>()
361
+
362
+ /** Non-shader tiers only: the effect parameters currently installed on [glassNode]. */
363
+ private var appliedBlurRadius: Float = Float.NaN
364
+ private var appliedSaturation: Float = Float.NaN
365
+
366
+ /** The dev-mode topology checks run once per view, not once per attach. */
367
+ private var environmentChecked = false
368
+
369
+ /** Lazily created on the first interactive press; null means no press has ever happened. */
370
+ private var pressAnimator: GlassPressAnimator? = null
371
+
372
+ /**
373
+ * The press factors we last multiplied/added in, so the base (RN `transform` styles included)
374
+ * can be recovered at any time — the animator must never stomp a transform the app owns.
375
+ */
376
+ private var lastScaleFactorX = 1f
377
+ private var lastScaleFactorY = 1f
378
+ private var lastFollowX = 0f
379
+ private var lastFollowY = 0f
380
+
381
+ /** True while an interactive press on bare glass (no child claimed) owns the event stream. */
382
+ private var ownsGesture = false
383
+
384
+ /**
385
+ * Hold-to-own: a bare-glass press still held after [HOLD_TO_OWN_MS] takes the gesture from
386
+ * ancestor scrollers, so dragging interactive glass follows and stretches instead of scrolling
387
+ * away. Quick flicks stay scrolls — they breach the scroller's touch slop before this fires —
388
+ * and JS responders (a `PanResponder` drag wrapper) grant even faster, so they keep winning too.
389
+ */
390
+ private val holdToOwnRunnable = Runnable {
391
+ if (ownsGesture && isInteractive && isAttachedToWindow) {
392
+ parent?.requestDisallowInterceptTouchEvent(true)
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Shader tier only. HWUI short-circuits `setRenderEffect` on pointer identity and Skia snapshots
398
+ * the uniform values when the effect is created, so a *new* [RenderEffect] must be built whenever
399
+ * a uniform changes. These two together are the "has anything changed" test.
400
+ */
401
+ private var effectDirty = true
402
+ private var appliedPadding = -1
403
+
404
+ /** The provider's [BackdropSource.contentGeneration] as of our last successful draw. */
405
+ private var drawnGeneration = Int.MIN_VALUE
406
+
407
+ /**
408
+ * Bounds the "provider has not drawn yet" retry, so a provider that never produces a display
409
+ * list — zero-sized, or detached mid-flight — cannot spin the main thread.
410
+ */
411
+ private var pendingRetries = 0
412
+
413
+ /**
414
+ * [BackdropGraph]'s verdict on this view's providers, latched.
415
+ *
416
+ * Checked once per resolve because the answer cannot change without one: it depends on the view
417
+ * tree and on who samples whom, and both of those go through [detachFromProviders].
418
+ */
419
+ private var backdropGraphChecked = false
420
+ private var backdropGraphFaulted = false
421
+
422
+ /**
423
+ * Provider-local -> our-local, as of the last recording.
424
+ *
425
+ * The recorded backdrop is only correct for this transform. A pure `(dx, dy)` would cover scroll
426
+ * and drag, but a matrix also survives an ancestor that scales or rotates, and it costs the same
427
+ * to compare.
428
+ */
429
+ /** One matrix per provider, in [providers] order; empty means nothing recorded yet. */
430
+ private val recordedTransforms = ArrayList<Matrix>()
431
+
432
+ private val localToWindow = Matrix()
433
+ private val providerToWindow = Matrix()
434
+ private val windowToLocal = Matrix()
435
+ private val providerToLocal = Matrix()
436
+
437
+ /**
438
+ * The shader's sampling clamp: the provider content actually recorded, half a pixel in — see
439
+ * [updateShaderCrop]. Blur stages read an edge-extended copy of that content (see
440
+ * [GlassProgressiveBlur.extendEffect]), so nothing outside it can leak into what the glass
441
+ * samples and no further inset is needed. Valid only while [hasShaderCrop]; falls back to the
442
+ * full node rect.
443
+ */
444
+ private val shaderCropRect = RectF()
445
+ private var hasShaderCrop = false
446
+ private val mappedContentRect = RectF()
447
+
448
+ /**
449
+ * The glass moving is not the same event as the backdrop changing, and nothing else reports it.
450
+ *
451
+ * When an **ancestor** moves this view — a `FlatList` scrolling its rows, a Reanimated transform
452
+ * on a wrapper, `Animated` with the native driver — this view is not dirty, so `dispatchDraw`
453
+ * never re-runs and the recorded backdrop offset silently goes stale: the glass carries its old
454
+ * backdrop along like a decal. Measured on device before this listener existed.
455
+ *
456
+ * A pre-draw listener is the right instrument because it is **self-gating** — it is dispatched
457
+ * from `ViewRootImpl.performTraversals`, so no traversal means no callback and no work. That is
458
+ * why this is not a `Choreographer.postFrameCallback`, which would fire every vsync forever and
459
+ * burn power at idle.
460
+ */
461
+ private val preDrawListener = ViewTreeObserver.OnPreDrawListener {
462
+ if (backdropTransformChanged()) invalidate()
463
+ true
464
+ }
465
+
466
+ /** The observer we registered with, so detach removes the listener from the *same* one. */
467
+ private var observedTree: ViewTreeObserver? = null
468
+
469
+ // ------------------------------------------------------------------------------- HDR headroom
470
+
471
+ /** Last ratio read from the display. Only consulted when [GlassHdr.requested] is true. */
472
+ private var hdrHeadroom = 1f
473
+
474
+ /** The display the ratio listener is registered on — unregister needs the same instance. */
475
+ private var ratioDisplay: android.view.Display? = null
476
+
477
+ /**
478
+ * Brightness moves the ratio continuously, so this fires often while HDR is on — each change
479
+ * is one effect rebuild, the same cost as one press-animation frame. Only registered while
480
+ * [GlassHdr.requested] and the display reports a ratio, so SDR sessions never pay it.
481
+ */
482
+ private val ratioConsumer = java.util.function.Consumer<android.view.Display> { d ->
483
+ if (Build.VERSION.SDK_INT >= 34) {
484
+ val ratio = d.hdrSdrRatio.coerceAtLeast(1f)
485
+ if (abs(ratio - hdrHeadroom) > 0.01f) {
486
+ hdrHeadroom = ratio
487
+ effectDirty = true
488
+ invalidate()
489
+ }
490
+ }
491
+ }
492
+
493
+ /** The runtime opt-in flipping (setHdrEnabled with views mounted) lands here. */
494
+ private val hdrStateListener = GlassHdr.Listener {
495
+ post {
496
+ if (!isAttachedToWindow) return@post
497
+ syncHdrListener()
498
+ hdrHeadroom = GlassHdr.currentHeadroom(display)
499
+ effectDirty = true
500
+ invalidate()
501
+ }
502
+ }
503
+
504
+ /** Registers/unregisters the per-display ratio listener to match the current opt-in state. */
505
+ private fun syncHdrListener() {
506
+ if (Build.VERSION.SDK_INT < 34) return
507
+ val d = display
508
+ val want = GlassHdr.requested && isAttachedToWindow && GlassHdr.isSupported(d)
509
+ if (want && ratioDisplay == null) {
510
+ d!!.registerHdrSdrRatioChangedListener(context.mainExecutor, ratioConsumer)
511
+ ratioDisplay = d
512
+ } else if (!want && ratioDisplay != null) {
513
+ ratioDisplay?.unregisterHdrSdrRatioChangedListener(ratioConsumer)
514
+ ratioDisplay = null
515
+ }
516
+ }
517
+
518
+ private fun releaseHdr() {
519
+ GlassHdr.removeListener(hdrStateListener)
520
+ if (Build.VERSION.SDK_INT >= 34) {
521
+ ratioDisplay?.unregisterHdrSdrRatioChangedListener(ratioConsumer)
522
+ }
523
+ ratioDisplay = null
524
+ hdrHeadroom = 1f
525
+ }
526
+
527
+ private val fillPaint = Paint().apply { isAntiAlias = true }
528
+
529
+ /** Additive blend for the press wash; allocated once, installed and removed per draw. */
530
+ private val addXfermode = PorterDuffXfermode(PorterDuff.Mode.ADD)
531
+ private val borderPaint = Paint().apply {
532
+ isAntiAlias = true
533
+ style = Paint.Style.STROKE
534
+ }
535
+
536
+ // --------------------------------------------------------------------------------- lifecycle
537
+
538
+ /**
539
+ * The coalescing hook — the analogue of iOS's `setNeedsAppearanceUpdate()`. Prop setters run in
540
+ * JS-map order rather than DSL order, so nothing may be resolved inside one; everything that
541
+ * depends on more than one prop is resolved here, once, after the whole batch has landed.
542
+ */
543
+ fun onPropsUpdated() {
544
+ appearance = GlassAppearance.resolve(variant, metal, density)
545
+ appliedSaturation = Float.NaN
546
+ requestedQuality = when (metal?.android?.quality) {
547
+ GlassQuality.low -> ShaderQuality.LOW
548
+ GlassQuality.medium -> ShaderQuality.MEDIUM
549
+ GlassQuality.high -> ShaderQuality.HIGH
550
+ null -> null
551
+ }
552
+ shaderQuality = resolveShaderQuality()
553
+ tierCeiling = metal?.android?.maxTier?.tier
554
+ // A tier that was lowered because its shader would not compile can come back if the caller
555
+ // switches to a quality that does, so re-resolve rather than latching.
556
+ tier = resolveTier()
557
+ reportRendererIfChanged()
558
+ geometryValid = false
559
+ appliedBlurRadius = Float.NaN
560
+ effectDirty = true
561
+ invalidate()
562
+ }
563
+
564
+ override fun onAttachedToWindow() {
565
+ super.onAttachedToWindow()
566
+ // Eager, and quiet about a miss: in every sanctioned topology the provider is an earlier
567
+ // sibling, so it attaches first and learns about this consumer before either view draws —
568
+ // which keeps its first frame recorded now that consumer-less providers skip recording.
569
+ // A miss here is legitimate (a provider mounted later in the same commit); the draw-path
570
+ // resolve keeps the warnings.
571
+ resolveProviders(warnOnMiss = false)
572
+ startWatchingGeometry()
573
+ GlassHdr.addListener(hdrStateListener)
574
+ syncHdrListener()
575
+ hdrHeadroom = GlassHdr.currentHeadroom(display)
576
+ reportRendererIfChanged()
577
+ if (!environmentChecked) {
578
+ environmentChecked = true
579
+ // Posted, not immediate: `canScrollVertically` needs the container's children measured, and
580
+ // a provider mounted in the same commit may not be in the hierarchy yet.
581
+ post {
582
+ if (isAttachedToWindow) {
583
+ for (id in requestedProviderIds()) GlassEnvironment.checkGlassView(this, id)
584
+ }
585
+ }
586
+ }
587
+ }
588
+
589
+ override fun onDetachedFromWindow() {
590
+ release()
591
+ super.onDetachedFromWindow()
592
+ }
593
+
594
+ /** `OnViewDestroys`. Detach is not guaranteed to have run, so this must be idempotent. */
595
+ fun release() {
596
+ stopWatchingGeometry()
597
+ releaseHdr()
598
+ detachFromProviders()
599
+ // A parked postOnAnimation would otherwise fire on the next attach of a recycled view.
600
+ ownsGesture = false
601
+ removeCallbacks(holdToOwnRunnable)
602
+ pressAnimator?.reset()
603
+ removeCallbacks(luminanceProbeRunnable)
604
+ luminanceProbePosted = false
605
+ removeCallbacks(frostCrossfadeStep)
606
+ frostCrossfadePosted = false
607
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
608
+ luminanceProbe?.release()
609
+ luminanceProbe = null
610
+ glassNode?.discardDisplayList()
611
+ }
612
+ }
613
+
614
+ private fun startWatchingGeometry() {
615
+ stopWatchingGeometry()
616
+ val observer = viewTreeObserver
617
+ if (!observer.isAlive) return
618
+ observer.addOnPreDrawListener(preDrawListener)
619
+ observedTree = observer
620
+ }
621
+
622
+ private fun stopWatchingGeometry() {
623
+ val observer = observedTree ?: return
624
+ observedTree = null
625
+ // The observer is merged and replaced when a view moves between hierarchies, so remove from the
626
+ // one we actually registered with; a dead observer's own list is already gone.
627
+ if (observer.isAlive) {
628
+ observer.removeOnPreDrawListener(preDrawListener)
629
+ } else {
630
+ viewTreeObserver.removeOnPreDrawListener(preDrawListener)
631
+ }
632
+ }
633
+
634
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
635
+ super.onSizeChanged(w, h, oldw, oldh)
636
+ // Size-dependent state belongs here, never in a prop setter — width/height are not yet valid
637
+ // when props arrive. R4's coverage test is size-dependent, so it is resolved here too, and a
638
+ // change of variant has to be pushed through the tier because a tier can be lowered by a
639
+ // quality whose shader will not compile.
640
+ val quality = resolveShaderQuality()
641
+ if (quality != shaderQuality) {
642
+ shaderQuality = quality
643
+ tier = resolveTier()
644
+ reportRendererIfChanged()
645
+ }
646
+ geometryValid = false
647
+ effectDirty = true
648
+ }
649
+
650
+ override fun onConfigurationChanged(newConfig: Configuration?) {
651
+ super.onConfigurationChanged(newConfig)
652
+ // Frost resolves against the light/dark background colour, as `traitCollectionDidChange` does.
653
+ effectDirty = true
654
+ invalidate()
655
+ }
656
+
657
+ override fun onBackdropChanged() {
658
+ // The provider notifies after every recording pass. Redraw only when the content it recorded
659
+ // has actually changed, otherwise every redraw would provoke the next one.
660
+ if (providers.isEmpty()) return
661
+ var generation = 0
662
+ for (source in providers) generation += source.contentGeneration
663
+ if (generation != drawnGeneration) invalidate()
664
+ }
665
+
666
+ // ------------------------------------------------------------------------------------ drawing
667
+
668
+ override fun dispatchDraw(canvas: Canvas) {
669
+ drawGlass(canvas)
670
+ super.dispatchDraw(canvas)
671
+ }
672
+
673
+ // ------------------------------------------------------------------------- interactive presses
674
+
675
+ /**
676
+ * Pure observer — the return value is `super`'s, untouched. The full event stream flows through
677
+ * here whenever anything in this subtree (including [onTouchEvent] below) is the touch target,
678
+ * and an ancestor that steals the gesture (a scroller, a `PanResponder` grant via RN's
679
+ * `JSResponderHandler`) hands us ACTION_CANCEL, which releases like an UP.
680
+ */
681
+ override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
682
+ if (isInteractive) when (ev.actionMasked) {
683
+ MotionEvent.ACTION_DOWN -> {
684
+ // Base captured before the first scale write of this press, so an RN transform applied
685
+ // between presses is respected.
686
+ obtainPressAnimator().pressDown(ev.x, ev.y)
687
+ }
688
+ MotionEvent.ACTION_MOVE -> pressAnimator?.follow(ev.x, ev.y)
689
+ MotionEvent.ACTION_UP,
690
+ MotionEvent.ACTION_CANCEL -> {
691
+ ownsGesture = false
692
+ removeCallbacks(holdToOwnRunnable)
693
+ pressAnimator?.releasePress()
694
+ }
695
+ }
696
+ return super.dispatchTouchEvent(ev)
697
+ }
698
+
699
+ /**
700
+ * The claim, kept separate from the observation: `ViewGroup` consults this only when no child
701
+ * claimed the DOWN, and returning true there is what keeps MOVE/UP arriving for a press on bare
702
+ * glass. RN is unaffected — its responder pipeline is fed from the root's intercept hook
703
+ * regardless of native claims, and RN child views claim their own DOWNs anyway.
704
+ */
705
+ override fun onTouchEvent(event: MotionEvent): Boolean {
706
+ if (super.onTouchEvent(event)) return true
707
+ if (!isInteractive) return false
708
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) {
709
+ ownsGesture = true
710
+ postDelayed(holdToOwnRunnable, HOLD_TO_OWN_MS)
711
+ }
712
+ return true
713
+ }
714
+
715
+ // ------------------------------------------------------------------ resolved press uniforms
716
+ //
717
+ // Two sources feed the same three uniforms: this view's own `interactive` animator, and a `glow`
718
+ // record the app drives. An explicit record wins — it is the caller saying "I am choreographing
719
+ // this", and silently mixing the two would make a mid-press prop change look like a glitch.
720
+
721
+ /** 0 at rest, which is what keeps the shader's uniform-coherent press branch switched off. */
722
+ private val effectiveGlow: Float
723
+ get() {
724
+ val external = glow ?: return if (isInteractive) pressAnimator?.glow ?: 0f else 0f
725
+ return external.progress.toFloat().coerceIn(0f, 1f)
726
+ }
727
+
728
+ /** Hotspot in view-local px — the space the shader calls `pixels`. */
729
+ private val effectiveGlowX: Float
730
+ get() {
731
+ val external = glow ?: return pressAnimator?.posX ?: 0f
732
+ return external.x?.let { it.toFloat() * density } ?: (width * 0.5f)
733
+ }
734
+
735
+ private val effectiveGlowY: Float
736
+ get() {
737
+ val external = glow ?: return pressAnimator?.posY ?: 0f
738
+ return external.y?.let { it.toFloat() * density } ?: (height * 0.5f)
739
+ }
740
+
741
+ /** Gates the dent and the lens boost; see the `touchLens` uniform. */
742
+ private val effectiveGlowLens: Float
743
+ get() {
744
+ val external = glow ?: return 1f
745
+ return if (external.lens) 1f else 0f
746
+ }
747
+
748
+ private fun obtainPressAnimator(): GlassPressAnimator {
749
+ pressAnimator?.let { return it }
750
+ val created = GlassPressAnimator(this) { onPressFrame() }
751
+ pressAnimator = created
752
+ return created
753
+ }
754
+
755
+ /** Animation-stage write-through: fresh uniforms, fresh transform, and a draw this same frame. */
756
+ private fun onPressFrame() {
757
+ val animator = pressAnimator ?: return
758
+ effectDirty = true
759
+ applyPressTransform(
760
+ animator.scale * animator.stretchX,
761
+ animator.scale * animator.stretchY,
762
+ animator.followX,
763
+ animator.followY,
764
+ )
765
+ invalidate()
766
+ }
767
+
768
+ private fun applyPressTransform(
769
+ factorX: Float,
770
+ factorY: Float,
771
+ followX: Float,
772
+ followY: Float,
773
+ ) {
774
+ scaleX = (scaleX / lastScaleFactorX) * factorX
775
+ scaleY = (scaleY / lastScaleFactorY) * factorY
776
+ translationX = (translationX - lastFollowX) + followX
777
+ translationY = (translationY - lastFollowY) + followY
778
+ lastScaleFactorX = factorX
779
+ lastScaleFactorY = factorY
780
+ lastFollowX = followX
781
+ lastFollowY = followY
782
+ }
783
+
784
+ private fun drawGlass(canvas: Canvas) {
785
+ if (width <= 0 || height <= 0) return
786
+ if (!geometryValid) rebuildGeometry()
787
+
788
+ val drewShader =
789
+ tier == GlassTier.FULL &&
790
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
791
+ drawShaderGlass(canvas)
792
+
793
+ if (!drewShader) {
794
+ // The shader path only declines when there is no backdrop to shade — no provider yet, or a
795
+ // software canvas — so the fallback must not try to draw one either.
796
+ drawCompositedGlass(canvas, allowBackdrop = tier != GlassTier.FULL)
797
+ }
798
+
799
+ drawBorder(canvas)
800
+ }
801
+
802
+ // -------------------------------------------------------------------------- the shader path
803
+
804
+ /**
805
+ * Returns false when there is nothing to shade, so the caller can fall back to a plain scrim
806
+ * rather than leaving the view invisible.
807
+ */
808
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
809
+ private fun drawShaderGlass(canvas: Canvas): Boolean {
810
+ // A software canvas (screenshots, PDF export, some OEM paths) cannot draw a RenderNode at all.
811
+ if (!canvas.isHardwareAccelerated) return false
812
+ val node = glassNode ?: return false
813
+
814
+ val pad = appearance.backdropPaddingPx(GlassTier.FULL)
815
+ if (!recordBackdrop(node, pad)) return false
816
+
817
+ if (effectDirty || pad != appliedPadding) {
818
+ val effect = buildShaderEffect(pad)
819
+ if (effect == null) {
820
+ // The tier check passed at construction, so this is a driver or platform surprise. Drop to
821
+ // the blur tier for the rest of this view's life rather than flickering between the two.
822
+ tier = GlassTier.BLUR
823
+ reportRendererIfChanged()
824
+ return false
825
+ }
826
+ node.setRenderEffect(effect)
827
+ effectDirty = false
828
+ appliedPadding = pad
829
+ }
830
+
831
+ // R3: the effect is evaluated over the padded node, which at `regular` defaults is ~4.9x the
832
+ // view's area. HWUI propagates the device clip into the image filter's requested output rect,
833
+ // so clipping first genuinely shrinks the shaded region. Inflated by 2 px because the SDF
834
+ // feather spans sd in [-1, +1] and its outer half lies beyond the view rect.
835
+ val save = canvas.save()
836
+ canvas.clipRect(
837
+ -CLIP_INFLATE_PX,
838
+ -CLIP_INFLATE_PX,
839
+ width + CLIP_INFLATE_PX,
840
+ height + CLIP_INFLATE_PX
841
+ )
842
+ canvas.translate(-pad.toFloat(), -pad.toFloat())
843
+ canvas.drawRenderNode(node)
844
+ canvas.restoreToCount(save)
845
+
846
+ GlassDebug.onGlassDrawn()
847
+ return true
848
+ }
849
+
850
+ /**
851
+ * Uploads the uniforms and builds a fresh [RenderEffect].
852
+ *
853
+ * Every `setFloatUniform` is gated on the variant's live-uniform set. A uniform the compiler
854
+ * optimised out — which is exactly what the `LOW` tier does to five of them — makes
855
+ * `setFloatUniform` throw `unable to find uniform named …`, and a declared uniform that is never
856
+ * set throws at draw time instead. Both directions throw, so neither list may drift.
857
+ */
858
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
859
+ private fun buildShaderEffect(pad: Int): RenderEffect? {
860
+ val variant = GlassShaderCache.variantOrNull(shaderQuality) ?: return null
861
+ val shader = GlassShaderCache.shaderOrNull(shaderQuality) ?: return null
862
+ val live = variant.liveUniforms
863
+
864
+ val w = width.toFloat()
865
+ val h = height.toFloat()
866
+ val p = pad.toFloat()
867
+ val d = density
868
+
869
+ fun set(name: String, value: Float) {
870
+ if (name in live) shader.setFloatUniform(name, value)
871
+ }
872
+
873
+ fun set(name: String, a: Float, b: Float) {
874
+ if (name in live) shader.setFloatUniform(name, a, b)
875
+ }
876
+
877
+ fun set(name: String, a: Float, b: Float, c: Float) {
878
+ if (name in live) shader.setFloatUniform(name, a, b, c)
879
+ }
880
+
881
+ fun set(name: String, a: Float, b: Float, c: Float, e: Float) {
882
+ if (name in live) shader.setFloatUniform(name, a, b, c, e)
883
+ }
884
+
885
+ return try {
886
+ set(GlassShaderSource.SIZE, w, h)
887
+ set(GlassShaderSource.OFFSET, -p, -p)
888
+ // Half-pixel inset so Skia's bilinear filter never blends the outermost real texel with the
889
+ // transparent black outside the node — that shows up as a dark hairline the clamp is supposed
890
+ // to be hiding. When the provider content underfills the node, the clamp tightens further to
891
+ // the content itself — see updateShaderCrop.
892
+ val nodeCrop = floatArrayOf(0.5f, 0.5f, w + 2f * p - 0.5f, h + 2f * p - 0.5f)
893
+ val crop = if (hasShaderCrop) {
894
+ floatArrayOf(
895
+ shaderCropRect.left, shaderCropRect.top,
896
+ shaderCropRect.right, shaderCropRect.bottom
897
+ )
898
+ } else {
899
+ nodeCrop
900
+ }
901
+ set(GlassShaderSource.CROP, crop[0], crop[1], crop[2], crop[3])
902
+
903
+ // The blur stage, if any. Progressive replaces uniform when both are asked for — one ramp
904
+ // already contains a flat blur as its degenerate case, and running both would double-blur.
905
+ // If the pyramid is unusable on this driver, degrade to a uniform hwui blur at the ramp's
906
+ // mean rather than dropping the stage: a scrim that suddenly stops blurring reads as a bug,
907
+ // a scrim that blurs evenly reads as conservative.
908
+ val blurStage: RenderEffect? = when {
909
+ appearance.hasProgressiveBlur ->
910
+ GlassProgressiveBlur.buildEffect(appearance, shaderQuality, w, h, p)
911
+ ?: appearance.hwuiRadius(appearance.fallbackBlurPx).takeIf { it > 0f }?.let {
912
+ RenderEffect.createBlurEffect(it, it, Shader.TileMode.CLAMP)
913
+ }
914
+ appearance.hasBlur ->
915
+ RenderEffect.createBlurEffect(
916
+ appearance.hwuiBlurRadius,
917
+ appearance.hwuiBlurRadius,
918
+ Shader.TileMode.CLAMP
919
+ )
920
+ else -> null
921
+ }
922
+
923
+ // hwui's blur smears whatever surrounds the recorded content inward by its reach, and when
924
+ // the content underfills the node that surround is transparent black. Fill the padding with
925
+ // the content's clamped edge pixels before any blur runs — see GlassProgressiveBlur — so
926
+ // every stage is clean right up to the content edge, where the clamp above lets the glass
927
+ // read. Skipped when the content covers the node: there is nothing to extend.
928
+ val underfilled = hasShaderCrop && !crop.contentEquals(nodeCrop)
929
+ val blurInput: RenderEffect? =
930
+ if (blurStage != null && underfilled) GlassProgressiveBlur.extendEffect(crop) else null
931
+
932
+ // Resolved by rebuildGeometry, which drawGlass runs before this. Circular style resolves to
933
+ // (E = r, n = 2), which the shader's corner branch reduces to the pre-squircle SDF exactly.
934
+ ContinuousCorners.writeShaderVec(cornerExtents, shaderVec)
935
+ set(
936
+ GlassShaderSource.CORNER_EXTENTS,
937
+ shaderVec[0], shaderVec[1], shaderVec[2], shaderVec[3]
938
+ )
939
+ ContinuousCorners.writeShaderVec(cornerShapes, shaderVec)
940
+ set(
941
+ GlassShaderSource.CORNER_SHAPES,
942
+ shaderVec[0], shaderVec[1], shaderVec[2], shaderVec[3]
943
+ )
944
+ set(GlassShaderSource.UNIT_SCALE, d)
945
+
946
+ set(
947
+ GlassShaderSource.REFRACTION_SCALE,
948
+ appearance.refractionWidthPx,
949
+ appearance.refractionHeightPx
950
+ )
951
+ set(GlassShaderSource.REFRACTION_AMOUNT, appearance.refractionAmountPx)
952
+ set(GlassShaderSource.REFRACTION_SWIRL, appearance.refractionSwirl)
953
+ set(GlassShaderSource.DEPTH_EFFECT, appearance.refractionDepth)
954
+ set(GlassShaderSource.PROFILE_POWER, appearance.curvePower)
955
+ set(GlassShaderSource.PROFILE_BIAS, appearance.curveBias)
956
+
957
+ set(GlassShaderSource.DISPERSION_HEIGHT, appearance.dispersionReachPx)
958
+ set(GlassShaderSource.DISPERSION_AMOUNT, appearance.dispersionAmountPx)
959
+ // iOS takes one tap per *point*, so `density` reproduces it exactly. The invariant that keeps
960
+ // every channel weight non-zero is `spacing <= unitScale`, hence the min.
961
+ set(
962
+ GlassShaderSource.DISPERSION_TAP_SPACING,
963
+ if (shaderQuality == ShaderQuality.HIGH) min(1f, d) else d
964
+ )
965
+ set(GlassShaderSource.DISPERSION_QUADRANT, appearance.dispersionQuadrant)
966
+
967
+ val tintColor = effectiveTint
968
+ set(
969
+ GlassShaderSource.TINT_COLOR,
970
+ if (tintColor == null) 0f else Color.red(tintColor) / 255f,
971
+ if (tintColor == null) 0f else Color.green(tintColor) / 255f,
972
+ if (tintColor == null) 0f else Color.blue(tintColor) / 255f,
973
+ if (tintColor == null) 0f else Color.alpha(tintColor) / 255f
974
+ )
975
+ // White, black, or — mid-crossfade while adaptive — the grey between.
976
+ val frostBase = 1f - frostDarkness
977
+ set(
978
+ GlassShaderSource.FROST_COLOR,
979
+ frostBase, frostBase, frostBase,
980
+ appearance.frost.coerceIn(0f, 1f)
981
+ )
982
+
983
+ set(GlassShaderSource.HIGHLIGHT_INTENSITY, appearance.highlightIntensity)
984
+ set(GlassShaderSource.HIGHLIGHT_DIR, appearance.highlightCos, appearance.highlightSin)
985
+ set(GlassShaderSource.HIGHLIGHT_WIDTH, appearance.highlightWidthPx)
986
+ set(GlassShaderSource.HIGHLIGHT_FALLOFF, appearance.highlightFalloff)
987
+ set(GlassShaderSource.LIGHT_INTENSITY, appearance.light)
988
+ set(GlassShaderSource.GLASS_OPACITY, appearance.opacity)
989
+ set(GlassShaderSource.SATURATION, appearance.saturation)
990
+ set(GlassShaderSource.NOISE_AMOUNT, appearance.noise)
991
+ // Pinned to 1.0 whenever the opt-in is off or unsupported, which keeps the shader
992
+ // bit-identical to the pre-HDR build everywhere the window is SDR.
993
+ set(
994
+ GlassShaderSource.HDR_HEADROOM,
995
+ if (GlassHdr.requested) hdrHeadroom.coerceAtLeast(1f) else 1f
996
+ )
997
+
998
+ // Always set, even at rest — a declared-but-unset uniform throws at draw time. Rest values
999
+ // keep the shader's uniform-coherent branch off; MotionEvent coords are already view-local
1000
+ // px, the same space as the shader's `pixels`.
1001
+ set(GlassShaderSource.TOUCH_POS, effectiveGlowX, effectiveGlowY)
1002
+ set(GlassShaderSource.TOUCH_GLOW, effectiveGlow)
1003
+ set(GlassShaderSource.TOUCH_LENS, effectiveGlowLens)
1004
+
1005
+ // Always set, like the touch uniforms. Both rects convert the records' top-left corners
1006
+ // into center offsets — the same packing the Metal renderer uses: the shape's from the
1007
+ // view center, the partner's from the SHAPE center, so the two knobs compose without
1008
+ // either knowing about the other. Defaults reproduce the view-filling shape exactly.
1009
+ val shapeW = if (appearance.hasShape) appearance.shapeWidthPx else w
1010
+ val shapeH = if (appearance.hasShape) appearance.shapeHeightPx else h
1011
+ val shapeCx = if (appearance.hasShape) appearance.shapeXPx + shapeW * 0.5f else w * 0.5f
1012
+ val shapeCy = if (appearance.hasShape) appearance.shapeYPx + shapeH * 0.5f else h * 0.5f
1013
+ set(
1014
+ GlassShaderSource.SHAPE_RECT,
1015
+ shapeCx - w * 0.5f, shapeCy - h * 0.5f,
1016
+ shapeW * 0.5f, shapeH * 0.5f
1017
+ )
1018
+ set(
1019
+ GlassShaderSource.MORPH_RECT,
1020
+ appearance.morphXPx + appearance.morphWidthPx * 0.5f - shapeCx,
1021
+ appearance.morphYPx + appearance.morphHeightPx * 0.5f - shapeCy,
1022
+ appearance.morphWidthPx * 0.5f,
1023
+ appearance.morphHeightPx * 0.5f
1024
+ )
1025
+ set(
1026
+ GlassShaderSource.MORPH_SHAPE,
1027
+ appearance.morphRadiusPx,
1028
+ if (appearance.hasMorph) appearance.morphSmoothingPx else 0f
1029
+ )
1030
+
1031
+ // Always set, like the rest. Off = alpha 0 and radius 0, both of which the shader gates on.
1032
+ set(
1033
+ GlassShaderSource.INNER_SHADOW_COLOR,
1034
+ 0f, 0f, 0f,
1035
+ if (appearance.hasInnerShadow) appearance.innerShadowOpacity else 0f
1036
+ )
1037
+ set(
1038
+ GlassShaderSource.INNER_SHADOW_GEOM,
1039
+ if (appearance.hasInnerShadow) appearance.innerShadowRadiusPx else 0f,
1040
+ appearance.innerShadowOffsetXPx,
1041
+ appearance.innerShadowOffsetYPx
1042
+ )
1043
+ set(GlassShaderSource.MAGNIFICATION, appearance.magnification)
1044
+
1045
+ val glassEffect = RenderEffect.createRuntimeShaderEffect(shader, SHADER_INPUT_NAME)
1046
+
1047
+ if (blurStage == null) {
1048
+ glassEffect
1049
+ } else {
1050
+ // createChainEffect(outer, inner) runs `inner` first, so this is extend -> blur -> glass.
1051
+ // Written the other way round it still compiles and just looks wrong.
1052
+ val stage =
1053
+ if (blurInput != null) RenderEffect.createChainEffect(blurStage, blurInput) else blurStage
1054
+ RenderEffect.createChainEffect(glassEffect, stage)
1055
+ }
1056
+ } catch (t: Throwable) {
1057
+ Log.e(LOG_TAG, "Failed to build the glass RenderEffect; falling back to blur", t)
1058
+ null
1059
+ }
1060
+ }
1061
+
1062
+ // ------------------------------------------------------- the blur / scrim / no-backdrop paths
1063
+
1064
+ /**
1065
+ * Everything below API 33, plus the "no backdrop yet" fallback for the shader tier.
1066
+ *
1067
+ * The blur tier has no refraction, no dispersion and no highlight — it is a clipped, blurred,
1068
+ * frosted, tinted rectangle. That is an honest degradation, not an approximation of the shader.
1069
+ */
1070
+ private fun drawCompositedGlass(canvas: Canvas, allowBackdrop: Boolean) {
1071
+ val opacity = appearance.opacity
1072
+ val layer = if (opacity < 1f) {
1073
+ canvas.saveLayerAlpha(bounds, (opacity.coerceIn(0f, 1f) * 255f).toInt())
1074
+ } else {
1075
+ canvas.save()
1076
+ }
1077
+
1078
+ if (!clampedRadii.isZero) canvas.clipPath(clipPath)
1079
+
1080
+ if (allowBackdrop) drawBlurredBackdrop(canvas)
1081
+ drawFrostAndTint(canvas)
1082
+ drawPressWash(canvas)
1083
+
1084
+ canvas.restoreToCount(layer)
1085
+ }
1086
+
1087
+ /**
1088
+ * Press feedback for every frame the shader does not draw — the BLUR and SCRIM tiers, and the
1089
+ * FULL tier's declined frames — so a press never loses its glow mid-gesture. Same model as the
1090
+ * shader fragment: flat 0.08 wash plus a 0.15 radial lobe, additive. Fed by whichever source
1091
+ * owns the press, `interactive` or [glow]; only the *optical* half of a press is shader-only, and
1092
+ * this is the other half.
1093
+ *
1094
+ * `PorterDuffXfermode(ADD)`, not `BlendMode.PLUS`: minSdk is 24 and this path runs there.
1095
+ * Drawn inside the rounded clip and the opacity layer, so shape and `metal.opacity` behave
1096
+ * exactly like the frost above.
1097
+ */
1098
+ private fun drawPressWash(canvas: Canvas) {
1099
+ val glow = effectiveGlow
1100
+ if (glow <= 0f) return
1101
+
1102
+ fillPaint.xfermode = addXfermode
1103
+ fillPaint.color = Color.WHITE
1104
+ fillPaint.alpha = (0.08f * glow * 255f).toInt()
1105
+ canvas.drawRect(bounds, fillPaint)
1106
+
1107
+ val radius = 1.5f * min(width, height).toFloat()
1108
+ if (radius > 0f) {
1109
+ // Stops 0 / 0.5 / 1 = white / white / transparent — full strength inside half the radius,
1110
+ // the RadialGradient approximation of the shader's smoothstep falloff.
1111
+ fillPaint.shader = RadialGradient(
1112
+ effectiveGlowX, effectiveGlowY, radius,
1113
+ intArrayOf(Color.WHITE, Color.WHITE, Color.TRANSPARENT),
1114
+ floatArrayOf(0f, 0.5f, 1f),
1115
+ Shader.TileMode.CLAMP
1116
+ )
1117
+ fillPaint.alpha = (0.15f * glow * 255f).toInt()
1118
+ canvas.drawRect(bounds, fillPaint)
1119
+ fillPaint.shader = null
1120
+ }
1121
+ fillPaint.xfermode = null
1122
+ }
1123
+
1124
+ private fun drawBlurredBackdrop(canvas: Canvas) {
1125
+ if (!tier.hasLiveBackdrop) return
1126
+ if (!canvas.isHardwareAccelerated) return
1127
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
1128
+
1129
+ val node = glassNode ?: return
1130
+ val pad = appearance.backdropPaddingPx(tier)
1131
+ if (!recordBackdrop(node, pad)) return
1132
+
1133
+ // Gated on the tier, not only on the API level. SCRIM is "the backdrop drawn straight through"
1134
+ // by definition, and a view lowered to SCRIM on a modern device would otherwise still get a
1135
+ // blur that a genuine API 29–30 device cannot produce — which would make the fallback untestable
1136
+ // anywhere but on hardware that old.
1137
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1138
+ if (tier == GlassTier.BLUR) applyFallbackEffect(node) else clearFallbackEffect(node)
1139
+ }
1140
+
1141
+ val padF = pad.toFloat()
1142
+ val save = canvas.save()
1143
+ canvas.translate(-padF, -padF)
1144
+ canvas.drawRenderNode(node)
1145
+ canvas.restoreToCount(save)
1146
+
1147
+ GlassDebug.onGlassDrawn()
1148
+ }
1149
+
1150
+ /**
1151
+ * Frost mixes toward the system background — hardcoded white/black rather than resolved from
1152
+ * `?attr/colorSurface`, because iOS uses `UIColor.systemBackground` (`#FFFFFF`/`#000000`) and
1153
+ * Material's dark default of `#121212` would visibly diverge at the `regular` frost of 0.36.
1154
+ */
1155
+ private fun drawFrostAndTint(canvas: Canvas) {
1156
+ val frost = appearance.frost
1157
+ if (frost > 0f) {
1158
+ val level = ((1f - frostDarkness) * 255f).toInt().coerceIn(0, 255)
1159
+ fillPaint.color = Color.rgb(level, level, level)
1160
+ fillPaint.alpha = (frost.coerceIn(0f, 1f) * 255f).toInt()
1161
+ canvas.drawRect(bounds, fillPaint)
1162
+ }
1163
+
1164
+ effectiveTint?.let { color ->
1165
+ fillPaint.color = color
1166
+ canvas.drawRect(bounds, fillPaint)
1167
+ }
1168
+ }
1169
+
1170
+ // ------------------------------------------------------------------------------ shared plumbing
1171
+
1172
+ /**
1173
+ * Records the providers' content into [node], padded and aligned to this view — composited in
1174
+ * [providers] order, first at the bottom, each through its own provider-to-local transform.
1175
+ */
1176
+ @RequiresApi(Build.VERSION_CODES.Q)
1177
+ private fun recordBackdrop(node: RenderNode, pad: Int): Boolean {
1178
+ val sources = resolveProviders()
1179
+ if (sources.isEmpty()) return false
1180
+ if (!backdropGraphIsSafe(sources)) return false
1181
+
1182
+ // Every layer must be ready — recording a partial composite would flash the missing layer in.
1183
+ for (source in sources) {
1184
+ if (source.contentNode == null) {
1185
+ if (pendingRetries < MAX_PENDING_RETRIES) {
1186
+ pendingRetries++
1187
+ invalidate()
1188
+ }
1189
+ return false
1190
+ }
1191
+ }
1192
+ pendingRetries = 0
1193
+
1194
+ while (recordedTransforms.size < sources.size) recordedTransforms.add(Matrix())
1195
+ while (recordedTransforms.size > sources.size) {
1196
+ recordedTransforms.removeAt(recordedTransforms.size - 1)
1197
+ }
1198
+ for (i in sources.indices) {
1199
+ if (!computeProviderToLocal(sources[i].sourceView, providerToLocal)) {
1200
+ // A singular transform mid-animation has no inverse; drawing nothing this frame is
1201
+ // correct — the view has no area.
1202
+ recordedTransforms.clear()
1203
+ return false
1204
+ }
1205
+ recordedTransforms[i].set(providerToLocal)
1206
+ }
1207
+ updateShaderCrop(sources, pad)
1208
+
1209
+ val padF = pad.toFloat()
1210
+ val paddedWidth = width + pad * 2
1211
+ val paddedHeight = height + pad * 2
1212
+
1213
+ node.setPosition(0, 0, paddedWidth, paddedHeight)
1214
+ val recording = node.beginRecording(paddedWidth, paddedHeight)
1215
+ try {
1216
+ for (i in sources.indices) {
1217
+ // Vetted above; a detach racing us just drops that layer for one frame.
1218
+ val content = sources[i].contentNode ?: continue
1219
+ val save = recording.save()
1220
+ // Provider-local -> our-local -> node-local. The provider content that sits under our
1221
+ // top-left corner therefore lands at (pad, pad).
1222
+ recording.translate(padF, padF)
1223
+ recording.concat(recordedTransforms[i])
1224
+ recording.drawRenderNode(content)
1225
+ recording.restoreToCount(save)
1226
+ }
1227
+ } finally {
1228
+ node.endRecording()
1229
+ }
1230
+
1231
+ // The same sum onBackdropChanged compares against, so the two never disagree about "changed".
1232
+ var generation = 0
1233
+ for (source in sources) generation += source.contentGeneration
1234
+ drawnGeneration = generation
1235
+ // A recording only happens when the backdrop or the geometry changed — exactly when the
1236
+ // luminance under the glass may have.
1237
+ if (isAdaptive) scheduleLuminanceProbe()
1238
+ return true
1239
+ }
1240
+
1241
+ /**
1242
+ * Tightens the shader's `crop` clamp to the provider content actually recorded into the node.
1243
+ *
1244
+ * The padded node is transparent wherever the provider's mapped bounds do not reach. A
1245
+ * screen-sized provider always covers it, but a *small* provider — the nested-layer pattern: a
1246
+ * switch track, a tab bar recorded for its own pill — leaves the node's margins empty, and
1247
+ * `.rgb` of that premultiplied transparent black paints black bands exactly where
1248
+ * SAMPLE_BACKDROP's clamp is supposed to be extending edge texels. Intersecting the mapped
1249
+ * provider bounds into `crop` restores edge-extend semantics at the *content* boundary.
1250
+ *
1251
+ * The content rect is additionally inset by the blur's reach: the blur stage runs before the
1252
+ * shader samples, and content texels within one blur reach of the empty margin have already
1253
+ * been mixed toward transparent black — clamping just inside that band keeps the extended edge
1254
+ * at full strength.
1255
+ *
1256
+ * For a full-node provider the intersection IS the node rect, so the uniforms never change and
1257
+ * no extra effect rebuilds happen. During relative motion between a glass view and a small
1258
+ * provider the rect changes per frame; rebuilding the effect then is the same cost the press
1259
+ * animator already pays every frame. A rotated or skewed provider chain has no node-space rect
1260
+ * and falls back to the full node rect — the pre-fix behavior.
1261
+ */
1262
+ private fun updateShaderCrop(sources: List<BackdropSource>, pad: Int) {
1263
+ val p = pad.toFloat()
1264
+ val nodeL = 0.5f
1265
+ val nodeT = 0.5f
1266
+ val nodeR = width + 2f * p - 0.5f
1267
+ val nodeB = height + 2f * p - 0.5f
1268
+
1269
+ // The union bounding box of every layer's mapped rect. For a combined backdrop whose first
1270
+ // layer is the screen, that is the whole node and the clamp stays at the node rect.
1271
+ var unionL = Float.POSITIVE_INFINITY
1272
+ var unionT = Float.POSITIVE_INFINITY
1273
+ var unionR = Float.NEGATIVE_INFINITY
1274
+ var unionB = Float.NEGATIVE_INFINITY
1275
+ var rectLike = sources.isNotEmpty()
1276
+ for (i in sources.indices) {
1277
+ val matrix = recordedTransforms.getOrNull(i)
1278
+ if (matrix == null || !matrix.rectStaysRect()) {
1279
+ rectLike = false
1280
+ break
1281
+ }
1282
+ mappedContentRect.set(
1283
+ 0f, 0f,
1284
+ sources[i].sourceView.width.toFloat(), sources[i].sourceView.height.toFloat()
1285
+ )
1286
+ matrix.mapRect(mappedContentRect)
1287
+ mappedContentRect.offset(p, p)
1288
+ unionL = min(unionL, mappedContentRect.left)
1289
+ unionT = min(unionT, mappedContentRect.top)
1290
+ unionR = max(unionR, mappedContentRect.right)
1291
+ unionB = max(unionB, mappedContentRect.bottom)
1292
+ }
1293
+
1294
+ var l = nodeL
1295
+ var t = nodeT
1296
+ var r = nodeR
1297
+ var b = nodeB
1298
+ if (rectLike) {
1299
+ // Half a pixel in, so bilinear filtering never blends the outermost real texel with whatever
1300
+ // lies beyond it. The blur reach is deliberately *not* added: blur stages run over an
1301
+ // edge-extended copy of the content, which has nothing beyond the edge to smear inward.
1302
+ val inset = 0.5f
1303
+ l = max(nodeL, unionL + inset)
1304
+ t = max(nodeT, unionT + inset)
1305
+ r = min(nodeR, unionR - inset)
1306
+ b = min(nodeB, unionB - inset)
1307
+ // Content entirely outside (or thinner than the inset): collapse to its centre line rather
1308
+ // than handing the shader an inverted rect.
1309
+ if (r < l) {
1310
+ val cx = (l + r) * 0.5f
1311
+ l = cx
1312
+ r = cx
1313
+ }
1314
+ if (b < t) {
1315
+ val cy = (t + b) * 0.5f
1316
+ t = cy
1317
+ b = cy
1318
+ }
1319
+ }
1320
+
1321
+ if (!hasShaderCrop ||
1322
+ shaderCropRect.left != l || shaderCropRect.top != t ||
1323
+ shaderCropRect.right != r || shaderCropRect.bottom != b
1324
+ ) {
1325
+ shaderCropRect.set(l, t, r, b)
1326
+ hasShaderCrop = true
1327
+ effectDirty = true
1328
+ }
1329
+ }
1330
+
1331
+ /**
1332
+ * Provider-local -> our-local, via the window.
1333
+ *
1334
+ * Both walks stop at the topmost `View` rather than the window itself. Whatever the `ViewRootImpl`
1335
+ * contributes above that is common to both — [ProviderRegistry] only ever pairs views in the same
1336
+ * window — and cancels in the composition, so there is nothing to be gained by chasing it.
1337
+ *
1338
+ * Returns false when our own transform is singular (a zero scale mid-animation), which is the one
1339
+ * case that has no inverse. Drawing nothing for that frame is correct: the view has no area.
1340
+ */
1341
+ private fun computeProviderToLocal(providerView: View, out: Matrix): Boolean {
1342
+ accumulateLocalToWindow(this, localToWindow)
1343
+ accumulateLocalToWindow(providerView, providerToWindow)
1344
+ if (!localToWindow.invert(windowToLocal)) return false
1345
+ out.set(windowToLocal)
1346
+ out.preConcat(providerToWindow)
1347
+ return true
1348
+ }
1349
+
1350
+ /**
1351
+ * The public-API equivalent of `View.transformMatrixToGlobal`, which is `@hide`. Mirrors it
1352
+ * exactly: recurse to the parent, undo the parent's scroll, apply this view's offset within it,
1353
+ * then this view's own transform.
1354
+ */
1355
+ private fun accumulateLocalToWindow(view: View, out: Matrix) {
1356
+ out.reset()
1357
+ accumulate(view, out)
1358
+ }
1359
+
1360
+ private fun accumulate(view: View, out: Matrix) {
1361
+ val parent = view.parent
1362
+ if (parent is View) {
1363
+ accumulate(parent, out)
1364
+ out.preTranslate(-parent.scrollX.toFloat(), -parent.scrollY.toFloat())
1365
+ }
1366
+ out.preTranslate(view.left.toFloat(), view.top.toFloat())
1367
+ val transform = view.matrix
1368
+ if (!transform.isIdentity) out.preConcat(transform)
1369
+ }
1370
+
1371
+ /** Whether this view has moved relative to any of its providers since the backdrop was recorded. */
1372
+ private fun backdropTransformChanged(): Boolean {
1373
+ if (recordedTransforms.isEmpty() || recordedTransforms.size != providers.size) return false
1374
+ if (width <= 0 || height <= 0) return false
1375
+ for (i in providers.indices) {
1376
+ if (!computeProviderToLocal(providers[i].sourceView, providerToLocal)) return false
1377
+ if (providerToLocal != recordedTransforms[i]) return true
1378
+ }
1379
+ return false
1380
+ }
1381
+
1382
+ /**
1383
+ * The iOS Metal-fallback border is a `CAGradientLayer` running black → white → white → black
1384
+ * corner to corner (`LiquidGlassView.swift:108-123`, `:273`). Android deliberately diverges:
1385
+ * real iOS 26 glass has **no black in its edge** — eye-tested, the edge is purely the glass
1386
+ * border *light* — so the same four stops keep their geometry but the black ends are replaced
1387
+ * with transparent white, and the axis follows `highlight.angle` instead of being pinned to the
1388
+ * bottom-left→top-right diagonal. The opaque middle band covers the two corners the shader's
1389
+ * rim lobes light; the stroke fades out where they die. See [rebuildGeometry].
1390
+ */
1391
+ private fun drawBorder(canvas: Canvas) {
1392
+ val strokeWidth = appearance.borderWidthPx
1393
+ if (strokeWidth <= 0f || appearance.borderOpacity <= 0f) return
1394
+ if (borderPath.isEmpty) return
1395
+
1396
+ borderPaint.strokeWidth = strokeWidth
1397
+ borderPaint.color = Color.WHITE
1398
+ borderPaint.alpha = (appearance.borderOpacity.coerceIn(0f, 1f) * 255f).toInt()
1399
+ canvas.drawPath(borderPath, borderPaint)
1400
+ }
1401
+
1402
+ /**
1403
+ * The API 31–32 tier's effect chain: blur, then saturation.
1404
+ *
1405
+ * Saturation is a `ColorMatrixColorFilter` here rather than shader arithmetic, which is the one
1406
+ * place the two paths genuinely differ. `ColorMatrix.setSaturation` uses (0.213, 0.715, 0.072)
1407
+ * against the shader's Rec.709 (0.2126, 0.7152, 0.0722) — a difference below one 8-bit step — but
1408
+ * it saturates the *blurred backdrop only*, whereas the shader saturates the refracted,
1409
+ * dispersion-averaged colour. Without refraction there is nothing to diverge from.
1410
+ */
1411
+ @RequiresApi(Build.VERSION_CODES.S)
1412
+ private fun applyFallbackEffect(node: RenderNode) {
1413
+ // A progressive ramp collapses to its mean here — this tier has no shader to ramp with.
1414
+ val radius = when {
1415
+ appearance.hasProgressiveBlur ->
1416
+ appearance.hwuiRadius(appearance.fallbackBlurPx).coerceAtLeast(0f)
1417
+ appearance.hasBlur -> appearance.hwuiBlurRadius
1418
+ else -> 0f
1419
+ }
1420
+ val saturation = appearance.saturation
1421
+ if (radius == appliedBlurRadius && saturation == appliedSaturation) return
1422
+ appliedBlurRadius = radius
1423
+ appliedSaturation = saturation
1424
+
1425
+ // `createBlurEffect(0f, …)` throws — b/241546169 — so the zero case must skip the stage.
1426
+ var effect: RenderEffect? =
1427
+ if (radius > 0f) {
1428
+ RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
1429
+ } else {
1430
+ null
1431
+ }
1432
+
1433
+ if (saturation != 1f) {
1434
+ val filter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(saturation) })
1435
+ effect = if (effect == null) {
1436
+ RenderEffect.createColorFilterEffect(filter)
1437
+ } else {
1438
+ RenderEffect.createColorFilterEffect(filter, effect)
1439
+ }
1440
+ }
1441
+
1442
+ node.setRenderEffect(effect)
1443
+ }
1444
+
1445
+ /**
1446
+ * Strips whatever [applyFallbackEffect] last installed, for a view that has since dropped to
1447
+ * SCRIM. The sentinel pair is the identity chain, so a later `applyFallbackEffect` with those
1448
+ * exact values still correctly does nothing.
1449
+ */
1450
+ @RequiresApi(Build.VERSION_CODES.S)
1451
+ private fun clearFallbackEffect(node: RenderNode) {
1452
+ if (appliedBlurRadius == 0f && appliedSaturation == 1f) return
1453
+ appliedBlurRadius = 0f
1454
+ appliedSaturation = 1f
1455
+ node.setRenderEffect(null)
1456
+ }
1457
+
1458
+ private fun rebuildGeometry() {
1459
+ val w = width.toFloat()
1460
+ val h = height.toFloat()
1461
+ bounds.set(0f, 0f, w, h)
1462
+ clampedRadii = rawCornerRadii.clampedTo(w, h)
1463
+
1464
+ // One resolver feeds the clip path, the border path and the shader uniforms, so all three
1465
+ // renderers sit on the same curve — the whole point of the (E, n) family (research/05).
1466
+ val continuous = cornerStyle == GlassCornerStyle.continuous
1467
+ ContinuousCorners.resolve(clampedRadii, continuous, w, h, cornerExtents, cornerShapes)
1468
+
1469
+ clipPath.reset()
1470
+ if (!clampedRadii.isZero) {
1471
+ if (continuous) {
1472
+ ContinuousCorners.addContinuousRoundRect(clipPath, bounds, cornerExtents, cornerShapes)
1473
+ } else {
1474
+ clampedRadii.writePathRadii(pathRadii)
1475
+ clipPath.addRoundRect(bounds, pathRadii, Path.Direction.CW)
1476
+ }
1477
+ }
1478
+
1479
+ // The border is stroked, so it needs its own path: inset by half the stroke width so the
1480
+ // whole line stays inside the view, with each radius shrunk to match. Per-corner radii are
1481
+ // preserved — a single `drawRoundRect` cannot express them.
1482
+ val half = appearance.borderWidthPx / 2f
1483
+ borderBounds.set(
1484
+ bounds.left + half,
1485
+ bounds.top + half,
1486
+ bounds.right - half,
1487
+ bounds.bottom - half
1488
+ )
1489
+ borderPath.reset()
1490
+ if (borderBounds.width() > 0f && borderBounds.height() > 0f) {
1491
+ if (clampedRadii.isZero) {
1492
+ borderPath.addRect(borderBounds, Path.Direction.CW)
1493
+ } else if (continuous) {
1494
+ val borderRadii = clampedRadii.insetBy(half)
1495
+ ContinuousCorners.resolve(
1496
+ borderRadii, true, borderBounds.width(), borderBounds.height(),
1497
+ borderExtents, borderShapes
1498
+ )
1499
+ ContinuousCorners.addContinuousRoundRect(
1500
+ borderPath, borderBounds, borderExtents, borderShapes
1501
+ )
1502
+ } else {
1503
+ clampedRadii.writePathRadii(pathRadii)
1504
+ for (i in pathRadii.indices) pathRadii[i] = (pathRadii[i] - half).coerceAtLeast(0f)
1505
+ borderPath.addRoundRect(borderBounds, pathRadii, Path.Direction.CW)
1506
+ }
1507
+ }
1508
+
1509
+ // Laid along the highlight axis, so one prop steers the shader lobes, the swirl and this
1510
+ // stroke together. `reach` is half the view's footprint projected onto that axis: the extreme
1511
+ // corners project exactly onto stops 0 and 1 at any angle, the way the CALayer original's
1512
+ // corner-to-corner endpoints did for its fixed diagonal.
1513
+ val dirX = appearance.highlightCos
1514
+ val dirY = appearance.highlightSin
1515
+ val cx = width / 2f
1516
+ val cy = height / 2f
1517
+ val reach = 0.5f * (abs(width * dirX) + abs(height * dirY))
1518
+ borderPaint.shader = LinearGradient(
1519
+ cx - reach * dirX,
1520
+ cy - reach * dirY,
1521
+ cx + reach * dirX,
1522
+ cy + reach * dirY,
1523
+ BORDER_GRADIENT_COLORS,
1524
+ BORDER_GRADIENT_STOPS,
1525
+ Shader.TileMode.CLAMP
1526
+ )
1527
+
1528
+ geometryValid = true
1529
+ }
1530
+
1531
+ private fun isDarkMode(): Boolean =
1532
+ (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
1533
+ Configuration.UI_MODE_NIGHT_YES
1534
+
1535
+ private fun requestedProviderIds(): List<String> =
1536
+ providerIds?.takeIf { it.isNotEmpty() } ?: listOf(providerId)
1537
+
1538
+ /**
1539
+ * Which providers this view would draw into its own node, without binding to them.
1540
+ *
1541
+ * [BackdropGraph] asks this of *other* views mid-walk, where resolving for real would attach
1542
+ * consumers to providers on their behalf and make a provider start recording for a view that has
1543
+ * not drawn yet. A faulted view answers with nothing, because that is what it will actually
1544
+ * sample: its backdrop is off.
1545
+ */
1546
+ internal fun peekSampledSources(): List<BackdropSource> {
1547
+ if (backdropGraphFaulted) return emptyList()
1548
+ if (providers.isNotEmpty()) return providers
1549
+ val peeked = ArrayList<BackdropSource>(2)
1550
+ for (id in requestedProviderIds()) {
1551
+ peeked.add(ProviderRegistry.find(id, this, warnOnMiss = false) ?: return emptyList())
1552
+ }
1553
+ return peeked
1554
+ }
1555
+
1556
+ /**
1557
+ * The cycle check, run from the draw path rather than from attach.
1558
+ *
1559
+ * [BackdropGraph] walks the providers' subtrees, and at attach time the subtree that closes the
1560
+ * loop may not be mounted — a screen inside a provider builds after the provider does. By the
1561
+ * first draw the tree is whole, and bailing here still happens *before* anything is recorded, so
1562
+ * the frame that discovers the loop never builds one.
1563
+ */
1564
+ private fun backdropGraphIsSafe(sources: List<BackdropSource>): Boolean {
1565
+ if (backdropGraphFaulted) return false
1566
+ if (backdropGraphChecked) return true
1567
+ backdropGraphChecked = true
1568
+ val fault = BackdropGraph.inspect(this, sources) ?: return true
1569
+ // Not gated on dev mode. The alternative to this line is a SIGSEGV in the RenderThread with a
1570
+ // backtrace that names nothing of ours, which is not a thing to ship quietly to a release user.
1571
+ GlassDebug.warnOnce(
1572
+ "backdrop-graph:${fault.kind}:${fault.providerId}",
1573
+ BackdropGraph.describe(fault)
1574
+ )
1575
+ // Order matters: detaching resets the verdict along with the rest of the consumer state.
1576
+ detachFromProviders()
1577
+ backdropGraphChecked = true
1578
+ backdropGraphFaulted = true
1579
+ return false
1580
+ }
1581
+
1582
+ /**
1583
+ * All requested providers, or nothing: partial resolution is never cached, so a provider
1584
+ * mounted later in the same commit is picked up by the draw-path retry, and no consumer leaks
1585
+ * onto the ones that did resolve.
1586
+ */
1587
+ private fun resolveProviders(warnOnMiss: Boolean = true): List<BackdropSource> {
1588
+ // A view whose graph is unsafe stays unbound until something changes the topology, which is
1589
+ // exactly what clears the latch.
1590
+ if (backdropGraphFaulted) return emptyList()
1591
+ if (providers.isNotEmpty()) return providers
1592
+ for (id in requestedProviderIds()) {
1593
+ val found = ProviderRegistry.find(id, this, warnOnMiss)
1594
+ if (found == null) {
1595
+ providers.clear()
1596
+ return emptyList()
1597
+ }
1598
+ providers.add(found)
1599
+ }
1600
+ for (source in providers) source.addConsumer(this)
1601
+ return providers
1602
+ }
1603
+
1604
+ private fun detachFromProviders() {
1605
+ for (source in providers) source.removeConsumer(this)
1606
+ providers.clear()
1607
+ drawnGeneration = Int.MIN_VALUE
1608
+ pendingRetries = 0
1609
+ recordedTransforms.clear()
1610
+ // Every route here is a topology change — a new id, a detach, a re-parent — so the graph gets
1611
+ // a fresh verdict rather than inheriting one from wherever this view used to live.
1612
+ backdropGraphChecked = false
1613
+ backdropGraphFaulted = false
1614
+ }
1615
+
1616
+ /**
1617
+ * **R4.** Which shader variant to draw with, when the caller has not said.
1618
+ *
1619
+ * Measured on a Galaxy S23 (Adreno 740, 120 Hz, 8.33 ms budget) with one animating glass view
1620
+ * over a static provider, `dumpsys gfxinfo` sampled over ~480 frames per step, two passes:
1621
+ *
1622
+ * | coverage | jank pass A | jank pass B | p50 |
1623
+ * |---------:|------------:|------------:|----:|
1624
+ * | 5% | 0.6% | 0.2% | 5ms |
1625
+ * | 10% | 2.1% | 1.2% | 6ms |
1626
+ * | 25% | 0.2% | 2.1% | 6ms |
1627
+ * | 50% | 3.3% | 17.9% | 7ms |
1628
+ * | 75% | 40.4% | 77.8% | 9ms |
1629
+ * | 100% | 49.9% | 79.6% | 10ms |
1630
+ *
1631
+ * The *cliff* is between 50% and 75%, but the threshold is set at **25%** because pass B — the
1632
+ * warmer, later run — is already at 18% jank at 50% while 25% holds. A cold measurement at 50%
1633
+ * looks fine and is not; sustained load is the case that matters.
1634
+ *
1635
+ * Only [ShaderQuality.LOW] is below the [ShaderQuality.MEDIUM] default, so this is a single step,
1636
+ * and it is worth being precise about how much that step buys. Interleaved low/medium/high at
1637
+ * 100% coverage, three rounds, to cancel thermal drift:
1638
+ *
1639
+ * | quality | jank (3 rounds) | p50 | p90 |
1640
+ * |---------|----------------------|-----:|-----:|
1641
+ * | `LOW` | 71.3 / 71.9 / 74.8 % | 9ms | 10ms |
1642
+ * | `MEDIUM`| 79.3 / 81.1 / 84.9 % | 10ms | 11ms |
1643
+ * | `HIGH` | 83.5 / 82.3 / 86.0 % | 11ms | 12ms |
1644
+ *
1645
+ * So quality is monotonic and reproducible, but each step is worth about **1 ms** — and all three
1646
+ * are far past the 8.33 ms budget. The downgrade is a cheap marginal win, not a rescue: at high
1647
+ * coverage the cost is fill rate over a full-screen shader pass and a full-screen padded node, not
1648
+ * the dispersion tap count. Nothing at this layer makes full-screen glass hold 120 Hz; only less
1649
+ * glass does. Taken anyway because it costs a caller nothing and chromatic fringing is invisible
1650
+ * on a surface that large.
1651
+ *
1652
+ * (An earlier non-interleaved batch appeared to show 21% jank at `LOW` against 29% at `MEDIUM`.
1653
+ * That gap was thermal state, not quality — hence the interleaving.)
1654
+ *
1655
+ * An explicit `metal.android.quality` is never overridden — a caller who asks for `high` on a
1656
+ * full-screen view owns that.
1657
+ */
1658
+ private fun resolveShaderQuality(): ShaderQuality {
1659
+ requestedQuality?.let { return it }
1660
+ val metrics = resources.displayMetrics
1661
+ val screenArea = metrics.widthPixels.toLong() * metrics.heightPixels.toLong()
1662
+ if (screenArea <= 0L) return ShaderQuality.MEDIUM
1663
+ val viewArea = width.toLong() * height.toLong()
1664
+ val coversTooMuch = viewArea * 100L >= screenArea * AUTO_LOW_COVERAGE_PERCENT
1665
+ return if (coversTooMuch) ShaderQuality.LOW else ShaderQuality.MEDIUM
1666
+ }
1667
+
1668
+ /**
1669
+ * The device's ceiling, lowered if the AGSL source will not compile on this platform, and lowered
1670
+ * again by [tierCeiling] if the caller asked for less.
1671
+ */
1672
+ private fun resolveTier(): GlassTier {
1673
+ val device = when {
1674
+ GlassTier.supported != GlassTier.FULL -> GlassTier.supported
1675
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU -> GlassTier.BLUR
1676
+ GlassShaderCache.isAvailable(shaderQuality) -> GlassTier.FULL
1677
+ else -> GlassTier.BLUR
1678
+ }
1679
+ val ceiling = tierCeiling ?: return device
1680
+ return GlassTier.weakest(device, ceiling)
1681
+ }
1682
+
1683
+ private fun reportRendererIfChanged() {
1684
+ // Props can land before the first attach, and iOS guards this the same way (`window != nil`).
1685
+ if (!isAttachedToWindow) return
1686
+ val name = tier.rendererName
1687
+ if (name == reportedRenderer) return
1688
+ reportedRenderer = name
1689
+ onRendererChange(mapOf("renderer" to name))
1690
+ }
1691
+
1692
+ private companion object {
1693
+ const val MAX_PENDING_RETRIES = 8
1694
+
1695
+ /**
1696
+ * How long a bare-glass interactive press must hold before it takes the gesture from ancestor
1697
+ * scrollers. Longer than a flick's slop-breach, shorter than a deliberate drag's wind-up.
1698
+ */
1699
+ const val HOLD_TO_OWN_MS = 150L
1700
+
1701
+ /** **R4.** Screen coverage at or above which an unrequested quality drops to `LOW`. */
1702
+ const val AUTO_LOW_COVERAGE_PERCENT = 25L
1703
+
1704
+ /** How often the adaptive sensor may re-read the backdrop, at most. */
1705
+ const val LUMINANCE_PROBE_INTERVAL_MS = 250L
1706
+
1707
+ /** Hysteresis band for the frost polarity: flips dark below one, light above the other. */
1708
+ const val ADAPTIVE_DARK_BELOW = 0.45f
1709
+ const val ADAPTIVE_LIGHT_ABOVE = 0.55f
1710
+
1711
+ /** The frost's light/dark crossfade. */
1712
+ const val FROST_CROSSFADE_MS = 350f
1713
+
1714
+ /** A luminance change smaller than this is not worth a JS event. */
1715
+ const val LUMINANCE_EMIT_DELTA = 0.02f
1716
+
1717
+ /** Must match the child-shader name passed to `createRuntimeShaderEffect`. */
1718
+ const val SHADER_INPUT_NAME = "content"
1719
+
1720
+ const val CLIP_INFLATE_PX = 2f
1721
+
1722
+ /**
1723
+ * White with transparent-white tails. The iOS Metal fallback paints the tails BLACK — the
1724
+ * "heavy dark corner" this port deliberately does not reproduce, because real iOS 26 glass
1725
+ * has no dark edge component anywhere (neither does Kyant's `Plain`/`Default` highlight).
1726
+ */
1727
+ val BORDER_GRADIENT_COLORS =
1728
+ intArrayOf(0x00FFFFFF, Color.WHITE, Color.WHITE, 0x00FFFFFF)
1729
+ val BORDER_GRADIENT_STOPS = floatArrayOf(0f, 0.25f, 0.75f, 1f)
1730
+ }
1731
+ }