forked from androidx/androidx
/
ComposeWindow.uikit.kt
501 lines (436 loc) · 19.3 KB
/
ComposeWindow.uikit.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.window
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.InternalComposeApi
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.LocalSystemTheme
import androidx.compose.ui.SystemTheme
import androidx.compose.ui.createSkiaLayer
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.interop.LocalLayerContainer
import androidx.compose.ui.interop.LocalUIViewController
import androidx.compose.ui.native.ComposeLayer
import androidx.compose.ui.platform.*
import androidx.compose.ui.text.input.PlatformTextInputService
import androidx.compose.ui.uikit.*
import androidx.compose.ui.unit.*
import kotlin.math.roundToInt
import kotlinx.cinterop.ExportObjCClass
import kotlinx.cinterop.ObjCAction
import kotlinx.cinterop.useContents
import org.jetbrains.skiko.SkikoUIView
import org.jetbrains.skiko.TextActions
import org.jetbrains.skiko.currentSystemTheme
import org.jetbrains.skiko.ios.SkikoUITextInputTraits
import platform.CoreGraphics.CGPointMake
import platform.CoreGraphics.CGRectMake
import platform.Foundation.*
import platform.UIKit.*
import platform.darwin.NSObject
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_main_queue
private val uiContentSizeCategoryToFontScaleMap = mapOf(
UIContentSizeCategoryExtraSmall to 0.8f,
UIContentSizeCategorySmall to 0.85f,
UIContentSizeCategoryMedium to 0.9f,
UIContentSizeCategoryLarge to 1f, // default preference
UIContentSizeCategoryExtraLarge to 1.1f,
UIContentSizeCategoryExtraExtraLarge to 1.2f,
UIContentSizeCategoryExtraExtraExtraLarge to 1.3f,
// These values don't work well if they match scale shown by
// Text Size control hint, because iOS uses non-linear scaling
// calculated by UIFontMetrics, while Compose uses linear.
UIContentSizeCategoryAccessibilityMedium to 1.4f, // 160% native
UIContentSizeCategoryAccessibilityLarge to 1.5f, // 190% native
UIContentSizeCategoryAccessibilityExtraLarge to 1.6f, // 235% native
UIContentSizeCategoryAccessibilityExtraExtraLarge to 1.7f, // 275% native
UIContentSizeCategoryAccessibilityExtraExtraExtraLarge to 1.8f, // 310% native
// UIContentSizeCategoryUnspecified
)
fun ComposeUIViewController(content: @Composable () -> Unit): UIViewController =
ComposeUIViewController(configure = {}, content = content)
fun ComposeUIViewController(
configure: ComposeUIViewControllerConfiguration.() -> Unit = {},
content: @Composable () -> Unit
): UIViewController =
ComposeWindow().apply {
configuration = ComposeUIViewControllerConfiguration()
.apply(configure)
setContent(content)
}
private class AttachedComposeContext(
val composeLayer: ComposeLayer,
val skiaLayer: org.jetbrains.skiko.SkiaLayer,
val view: SkikoUIView,
val inputTraits: SkikoUITextInputTraits,
val platform: Platform
) {
fun dispose() {
composeLayer.dispose()
view.removeFromSuperview()
}
}
@OptIn(InternalComposeApi::class)
@ExportObjCClass
internal actual class ComposeWindow : UIViewController {
internal lateinit var configuration: ComposeUIViewControllerConfiguration
private val keyboardOverlapHeightState = mutableStateOf(0f)
private val safeAreaState = mutableStateOf(IOSInsets())
private val layoutMarginsState = mutableStateOf(IOSInsets())
/*
* Initial value is arbitarily chosen to avoid propagating invalid value logic
* It's never the case in real usage scenario to reflect that in type system
*/
private val interfaceOrientationState = mutableStateOf(
InterfaceOrientation.Portrait
)
private val systemTheme = mutableStateOf(
traitCollection.userInterfaceStyle.asComposeSystemTheme()
)
/*
* On iOS >= 13.0 interfaceOrientation will be deduced from [UIWindowScene] of [UIWindow]
* to which our [ComposeWindow] is attached.
* It's never UIInterfaceOrientationUnknown, if accessed after owning [UIWindow] was made key and visible:
* https://developer.apple.com/documentation/uikit/uiwindow/1621601-makekeyandvisible?language=objc
*/
private val currentInterfaceOrientation: InterfaceOrientation?
get() {
// Flag for checking which API to use
// Modern: https://developer.apple.com/documentation/uikit/uiwindowscene/3198088-interfaceorientation?language=objc
// Deprecated: https://developer.apple.com/documentation/uikit/uiapplication/1623026-statusbarorientation?language=objc
val supportsWindowSceneApi =
NSProcessInfo.processInfo.operatingSystemVersion.useContents {
majorVersion >= 13
}
return if (supportsWindowSceneApi) {
view.window?.windowScene?.interfaceOrientation?.let {
InterfaceOrientation.getByRawValue(it)
}
} else {
InterfaceOrientation.getByRawValue(UIApplication.sharedApplication.statusBarOrientation)
}
}
@OverrideInit
actual constructor() : super(nibName = null, bundle = null)
@OverrideInit
constructor(coder: NSCoder) : super(coder)
private val fontScale: Float
get() {
val contentSizeCategory =
traitCollection.preferredContentSizeCategory ?: UIContentSizeCategoryUnspecified
return uiContentSizeCategoryToFontScaleMap[contentSizeCategory] ?: 1.0f
}
private val density: Density
get() = Density(attachedComposeContext?.skiaLayer?.contentScale ?: 1f, fontScale)
private lateinit var content: @Composable () -> Unit
private var attachedComposeContext: AttachedComposeContext? = null
private val keyboardVisibilityListener = object : NSObject() {
@Suppress("unused")
@ObjCAction
fun keyboardDidShow(arg: NSNotification) {
val keyboardInfo = arg.userInfo!!["UIKeyboardFrameEndUserInfoKey"] as NSValue
val keyboardHeight = keyboardInfo.CGRectValue().useContents { size.height }
val screenHeight = UIScreen.mainScreen.bounds.useContents { size.height }
val composeViewBottomY = UIScreen.mainScreen.coordinateSpace.convertPoint(
point = CGPointMake(0.0, view.frame.useContents { size.height }),
fromCoordinateSpace = view.coordinateSpace
).useContents { y }
val bottomIndent = screenHeight - composeViewBottomY
if (bottomIndent < keyboardHeight) {
keyboardOverlapHeightState.value = (keyboardHeight - bottomIndent).toFloat()
}
val composeLayer = attachedComposeContext?.composeLayer ?: return
if (configuration.onFocusBehavior == OnFocusBehavior.FocusableAboveKeyboard) {
val focusedRect = composeLayer.getActiveFocusRect()
if (focusedRect != null) {
updateViewBounds(
offsetY = calcFocusedLiftingY(focusedRect, keyboardHeight)
)
}
}
}
@Suppress("unused")
@ObjCAction
fun keyboardWillHide(arg: NSNotification) {
keyboardOverlapHeightState.value = 0f
if (configuration.onFocusBehavior == OnFocusBehavior.FocusableAboveKeyboard) {
updateViewBounds(offsetY = 0.0)
}
}
private fun calcFocusedLiftingY(focusedRect: DpRect, keyboardHeight: Double): Double {
val viewHeight = attachedComposeContext?.view?.frame?.useContents {
size.height
} ?: 0.0
val hiddenPartOfFocusedElement: Double =
keyboardHeight - viewHeight + focusedRect.bottom.value
return if (hiddenPartOfFocusedElement > 0) {
// If focused element is partially hidden by the keyboard, we need to lift it upper
val focusedTopY = focusedRect.top.value
val isFocusedElementRemainsVisible = hiddenPartOfFocusedElement < focusedTopY
if (isFocusedElementRemainsVisible) {
// We need to lift focused element to be fully visible
hiddenPartOfFocusedElement
} else {
// In this case focused element height is bigger than remain part of the screen after showing the keyboard.
// Top edge of focused element should be visible. Same logic on Android.
maxOf(focusedTopY, 0f).toDouble()
}
} else {
// Focused element is not hidden by the keyboard.
0.0
}
}
private fun updateViewBounds(offsetX: Double = 0.0, offsetY: Double = 0.0) {
val (width, height) = getViewFrameSize()
view.layer.setBounds(
CGRectMake(
x = offsetX,
y = offsetY,
width = width.toDouble(),
height = height.toDouble()
)
)
}
}
@Suppress("unused")
@ObjCAction
fun viewSafeAreaInsetsDidChange() {
// super.viewSafeAreaInsetsDidChange() // TODO: call super after Kotlin 1.8.20
view.safeAreaInsets.useContents {
safeAreaState.value = IOSInsets(
top = top.dp,
bottom = bottom.dp,
left = left.dp,
right = right.dp,
)
}
view.directionalLayoutMargins.useContents {
layoutMarginsState.value = IOSInsets(
top = top.dp,
bottom = bottom.dp,
left = leading.dp,
right = trailing.dp,
)
}
}
override fun loadView() {
view = UIView().apply {
backgroundColor = UIColor.whiteColor
setClipsToBounds(true)
} // rootView needs to interop with UIKit
}
override fun traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
systemTheme.value = traitCollection.userInterfaceStyle.asComposeSystemTheme()
}
override fun viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// UIKit possesses all required info for layout at this point
currentInterfaceOrientation?.let {
interfaceOrientationState.value = it
}
val composeLayer = attachedComposeContext?.composeLayer ?: return
val (width, height) = getViewFrameSize()
val scale = density.density
composeLayer.setDensity(density)
composeLayer.setSize((width * scale).roundToInt(), (height * scale).roundToInt())
}
override fun viewWillAppear(animated: Boolean) {
super.viewWillAppear(animated)
attachComposeIfNeeded()
}
override fun viewDidAppear(animated: Boolean) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter.addObserver(
observer = keyboardVisibilityListener,
selector = NSSelectorFromString(keyboardVisibilityListener::keyboardDidShow.name + ":"),
name = UIKeyboardDidShowNotification,
`object` = null
)
NSNotificationCenter.defaultCenter.addObserver(
observer = keyboardVisibilityListener,
selector = NSSelectorFromString(keyboardVisibilityListener::keyboardWillHide.name + ":"),
name = UIKeyboardWillHideNotification,
`object` = null
)
}
// viewDidUnload() is deprecated and not called.
override fun viewWillDisappear(animated: Boolean) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter.removeObserver(
observer = keyboardVisibilityListener,
name = UIKeyboardDidShowNotification,
`object` = null
)
NSNotificationCenter.defaultCenter.removeObserver(
observer = keyboardVisibilityListener,
name = UIKeyboardWillHideNotification,
`object` = null
)
}
override fun viewDidDisappear(animated: Boolean) {
super.viewDidDisappear(animated)
dispose()
dispatch_async(dispatch_get_main_queue()) {
kotlin.native.internal.GC.collect()
}
}
override fun didReceiveMemoryWarning() {
println("didReceiveMemoryWarning")
kotlin.native.internal.GC.collect()
super.didReceiveMemoryWarning()
}
actual fun setContent(
content: @Composable () -> Unit
) {
this.content = content
}
actual fun dispose() {
attachedComposeContext?.dispose()
attachedComposeContext = null
}
private fun attachComposeIfNeeded() {
if (attachedComposeContext != null) {
return // already attached
}
val skiaLayer = createSkiaLayer()
val skikoUIView = SkikoUIView(
skiaLayer = skiaLayer,
pointInside = { point, _ ->
val composeLayer = attachedComposeContext?.composeLayer
if (composeLayer == null) {
false
} else {
!composeLayer.hitInteropView(point, isTouchEvent = true)
}
},
skikoUITextInputTrains = DelegateSkikoUITextInputTraits { attachedComposeContext?.inputTraits }
).load()
skikoUIView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(skikoUIView)
NSLayoutConstraint.activateConstraints(
listOf(
skikoUIView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
skikoUIView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
skikoUIView.topAnchor.constraintEqualToAnchor(view.topAnchor),
skikoUIView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
)
)
val inputServices = UIKitTextInputService(
showSoftwareKeyboard = {
skikoUIView.showScreenKeyboard()
},
hideSoftwareKeyboard = {
skikoUIView.hideScreenKeyboard()
},
updateView = {
skikoUIView.setNeedsDisplay() // redraw on next frame
platform.QuartzCore.CATransaction.flush() // clear all animations
skikoUIView.reloadInputViews() // update input (like screen keyboard)
},
textWillChange = { skikoUIView.textWillChange() },
textDidChange = { skikoUIView.textDidChange() },
selectionWillChange = { skikoUIView.selectionWillChange() },
selectionDidChange = { skikoUIView.selectionDidChange() },
)
val inputTraits = inputServices.skikoUITextInputTraits
val platform = object : Platform by Platform.Empty {
override val textInputService: PlatformTextInputService = inputServices
override val viewConfiguration =
object : ViewConfiguration {
override val longPressTimeoutMillis: Long get() = 500
override val doubleTapTimeoutMillis: Long get() = 300
override val doubleTapMinTimeMillis: Long get() = 40
// this value is originating from iOS 16 drag behavior reverse-engenering
override val touchSlop: Float get() = with(density) { 10.dp.toPx() }
}
override val textToolbar = object : TextToolbar {
override fun showMenu(
rect: Rect,
onCopyRequested: (() -> Unit)?,
onPasteRequested: (() -> Unit)?,
onCutRequested: (() -> Unit)?,
onSelectAllRequested: (() -> Unit)?
) {
val skiaRect = with(density) {
org.jetbrains.skia.Rect.makeLTRB(
l = rect.left / density,
t = rect.top / density,
r = rect.right / density,
b = rect.bottom / density,
)
}
skikoUIView.showTextMenu(
targetRect = skiaRect,
textActions = object : TextActions {
override val copy: (() -> Unit)? = onCopyRequested
override val cut: (() -> Unit)? = onCutRequested
override val paste: (() -> Unit)? = onPasteRequested
override val selectAll: (() -> Unit)? = onSelectAllRequested
}
)
}
/**
* TODO on UIKit native behaviour is hide text menu, when touch outside
*/
override fun hide() = skikoUIView.hideTextMenu()
override val status: TextToolbarStatus
get() = if (skikoUIView.isTextMenuShown())
TextToolbarStatus.Shown
else
TextToolbarStatus.Hidden
}
override val inputModeManager = DefaultInputModeManager(InputMode.Touch)
}
val composeLayer = ComposeLayer(
layer = skiaLayer,
platform = platform,
input = inputServices.skikoInput,
)
composeLayer.setContent(
onPreviewKeyEvent = inputServices::onPreviewKeyEvent,
content = {
CompositionLocalProvider(
LocalLayerContainer provides view,
LocalUIViewController provides this,
LocalKeyboardOverlapHeightState provides keyboardOverlapHeightState,
LocalSafeAreaState provides safeAreaState,
LocalLayoutMarginsState provides layoutMarginsState,
LocalInterfaceOrientationState provides interfaceOrientationState,
LocalSystemTheme provides systemTheme.value
) {
content()
}
},
)
attachedComposeContext =
AttachedComposeContext(composeLayer, skiaLayer, skikoUIView, inputTraits, platform)
}
private fun getViewFrameSize(): IntSize {
val (width, height) = view.frame().useContents { this.size.width to this.size.height }
return IntSize(width.toInt(), height.toInt())
}
}
private fun UIUserInterfaceStyle.asComposeSystemTheme(): SystemTheme {
return when (this) {
UIUserInterfaceStyle.UIUserInterfaceStyleLight -> SystemTheme.Light
UIUserInterfaceStyle.UIUserInterfaceStyleDark -> SystemTheme.Dark
else -> SystemTheme.Unknown
}
}