Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compose as LifecycleOwner #1198

Merged
merged 6 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compose/mpp/demo/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ kotlin {
implementation(project(":compose:ui:ui"))
implementation(project(":compose:ui:ui-graphics"))
implementation(project(":compose:ui:ui-text"))
implementation(project(":lifecycle:lifecycle-common"))
implementation(project(":lifecycle:lifecycle-runtime"))
implementation(libs.kotlinStdlib)
implementation(libs.kotlinCoroutinesCore)
api(libs.kotlinSerializationCore)
Expand All @@ -175,6 +177,7 @@ kotlin {
val desktopMain by getting {
dependsOn(skikoMain)
dependencies {
implementation(libs.kotlinCoroutinesSwing)
implementation(libs.skikoCurrentOs)
implementation(project(":compose:desktop:desktop"))
}
Expand Down
33 changes: 33 additions & 0 deletions compose/mpp/demo/src/uikitMain/kotlin/NativePopupExample.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.mpp.demo.Screen
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
Expand All @@ -20,8 +25,10 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.interop.LocalUIViewController
import androidx.compose.ui.interop.UIKitView
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.ComposeUIViewController
import androidx.lifecycle.LifecycleEventObserver
import platform.UIKit.*
import platform.Foundation.*
import platform.darwin.dispatch_async
Expand Down Expand Up @@ -64,9 +71,35 @@ private fun NativeModalWithNavigation() {

@Composable
private fun NativeNavigationPage() {
val lifecycleOwner = LocalLifecycleOwner.current

val states = remember { mutableStateListOf<String>() }

val observer = remember {
LifecycleEventObserver { _, event ->
println(event)
states.add("${states.size} ${event.name}")
}
}

DisposableEffect(lifecycleOwner) {
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}

Column(Modifier.fillMaxSize().background(Color.DarkGray), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
val navigationController = LocalUIViewController.current.navigationController

LazyRow(Modifier.height(50.dp).fillMaxWidth()) {
items(states.size) { index ->
Box(Modifier.background(Color.White).padding(16.dp)) {
Text(states[index], color = Color.Black)
}
}
}

Button(onClick = {
navigationController?.pushViewController(
ComposeUIViewController {
Expand Down
4 changes: 4 additions & 0 deletions compose/ui/ui/api/desktop/ui.api
Original file line number Diff line number Diff line change
Expand Up @@ -3046,6 +3046,10 @@ public final class androidx/compose/ui/platform/CompositionLocalsKt {
public static final fun getLocalWindowInfo ()Landroidx/compose/runtime/ProvidableCompositionLocal;
}

public final class androidx/compose/ui/platform/CompositionLocals_skikoKt {
public static final fun getLocalLifecycleOwner ()Landroidx/compose/runtime/ProvidableCompositionLocal;
}

public final class androidx/compose/ui/platform/DefaultViewConfiguration : androidx/compose/ui/platform/ViewConfiguration {
public static final field $stable I
public fun <init> (Landroidx/compose/ui/unit/Density;)V
Expand Down
2 changes: 2 additions & 0 deletions compose/ui/ui/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ if(AndroidXComposePlugin.isMultiplatformEnabled(project)) {
api project(":compose:ui:ui-unit")
api project(":compose:ui:ui-util")
implementation(project(":annotation:annotation"))
implementation(project(":lifecycle:lifecycle-common"))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because we add a new dependency, this change requires 2 approves, please ask someone else to review this commit (about adding dependency).

It looks fine for me, because we either will release a stable version of lifecycle, or we just depend on stable API of it right now.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eymar, no need to review the whole PR, only this commit

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having these dependencies added, we can't avoid publishing lifecycle libraries (there was an idea that maybe we don't need to publish lifecyclce right now - #1204 (comment)). User projects won't work with this ui library if we don't publish lifecycle.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there was an idea

If you talk about my comment:

If we don't need it urgently

I meant that "if don't need it right now". But we definitely need it for the 1.6.10 release

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

even dev builds won't work untill lifecycle is published if this PR is merged before that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed. Then let's wait until we publish

implementation(project(":lifecycle:lifecycle-runtime"))
}

androidMain.dependencies {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ internal val LocalImageVectorCache = staticCompositionLocalOf<ImageVectorCache>
/**
* The CompositionLocal containing the current [LifecycleOwner].
*/
val LocalLifecycleOwner = staticCompositionLocalOf<LifecycleOwner> {
actual val LocalLifecycleOwner = staticCompositionLocalOf<LifecycleOwner> {
noLocalProvidedFor("LocalLifecycleOwner")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import androidx.annotation.RestrictTo
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocal
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.autofill.Autofill
Expand All @@ -36,6 +37,7 @@ import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.lifecycle.LifecycleOwner

/**
* The CompositionLocal to provide communication with platform accessibility service.
Expand Down Expand Up @@ -172,6 +174,11 @@ val LocalWindowInfo = staticCompositionLocalOf<WindowInfo> {
noLocalProvidedFor("LocalWindowInfo")
}

/**
* The CompositionLocal containing the current [LifecycleOwner].
*/
expect val LocalLifecycleOwner: ProvidableCompositionLocal<LifecycleOwner>

internal val LocalPointerIconService = staticCompositionLocalOf<PointerIconService?> {
null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import androidx.compose.ui.awt.AwtEventListener
import androidx.compose.ui.awt.AwtEventListeners
import androidx.compose.ui.awt.OnlyValidPrimaryMouseButtonFilter
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.PlatformContext
import androidx.compose.ui.platform.PlatformWindowContext
import androidx.compose.ui.scene.skia.SkiaLayerComponent
Expand All @@ -43,12 +44,16 @@ import androidx.compose.ui.window.WindowExceptionHandler
import androidx.compose.ui.window.density
import androidx.compose.ui.window.layoutDirectionFor
import androidx.compose.ui.window.sizeInPx
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import java.awt.Component
import java.awt.Window
import java.awt.event.ComponentEvent
import java.awt.event.ComponentListener
import java.awt.event.WindowEvent
import java.awt.event.WindowFocusListener
import java.awt.event.WindowListener
import javax.swing.JLayeredPane
import javax.swing.SwingUtilities
import kotlin.coroutines.AbstractCoroutineContextElement
Expand Down Expand Up @@ -80,7 +85,7 @@ internal class ComposeContainer(

private val useSwingGraphics: Boolean = ComposeFeatureFlags.useSwingGraphics,
private val layerType: LayerType = ComposeFeatureFlags.layerType,
) : ComponentListener, WindowFocusListener {
) : ComponentListener, WindowFocusListener, WindowListener, LifecycleOwner {
val windowContext = PlatformWindowContext()
var window: Window? = null
private set
Expand Down Expand Up @@ -145,16 +150,22 @@ internal class ComposeContainer(
val renderApi by mediator::renderApi
val preferredSize by mediator::preferredSize

override val lifecycle = LifecycleRegistry(this)

init {
setWindow(window)
this.windowContainer = windowContainer

if (layerType == LayerType.OnComponent && !useSwingGraphics) {
error("Unsupported LayerType.OnComponent might be used only with rendering to Swing graphics")
}

lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}

fun dispose() {
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)

_windowContainer?.removeComponentListener(this)
mediator.dispose()
layers.fastForEach(DesktopComposeSceneLayer::close)
Expand All @@ -175,10 +186,27 @@ internal class ComposeContainer(
override fun windowGainedFocus(event: WindowEvent) = onChangeWindowFocus()
override fun windowLostFocus(event: WindowEvent) = onChangeWindowFocus()

override fun windowOpened(e: WindowEvent) = Unit
override fun windowClosing(e: WindowEvent) = Unit
override fun windowClosed(e: WindowEvent) = Unit
override fun windowIconified(e: WindowEvent) =
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
override fun windowDeiconified(e: WindowEvent) =
// The window is always in focus at this moment, so bump the state to [RESUMED].
// It will generate [ON_START] event implicitly or skip it at all if [windowGainedFocus]
igordmn marked this conversation as resolved.
Show resolved Hide resolved
// happened first.
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
override fun windowActivated(e: WindowEvent) = Unit
override fun windowDeactivated(e: WindowEvent) = Unit

private fun onChangeWindowFocus() {
windowContext.setWindowFocused(window?.isFocused ?: false)
val isFocused = window?.isFocused ?: false
windowContext.setWindowFocused(isFocused)
mediator.onChangeWindowFocus()
layers.fastForEach(DesktopComposeSceneLayer::onChangeWindowFocus)
lifecycle.handleLifecycleEvent(
event = if (isFocused) Lifecycle.Event.ON_RESUME else Lifecycle.Event.ON_PAUSE
)
}

private fun onChangeWindowPosition() {
Expand Down Expand Up @@ -227,9 +255,13 @@ internal class ComposeContainer(
// Re-checking the actual size if it wasn't available during init.
onChangeWindowSize()
onChangeWindowPosition()

lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We set started state on 2 different states:

  • when it is iconified (minimized)
  • when it is added to window hierarchy.

So, we have 2 sources of truth and races between them.

To avoid that, we should either choose one source of truth, or combine isIconified and isAddedToHirarchy states.

}

fun removeNotify() {
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP)

setWindow(null)
}

Expand All @@ -248,7 +280,9 @@ internal class ComposeContainer(
}

this.window?.removeWindowFocusListener(this)
this.window?.removeWindowListener(this)
window?.addWindowFocusListener(this)
window?.addWindowListener(this)
this.window = window

onChangeWindowFocus()
Expand Down Expand Up @@ -441,5 +475,6 @@ private fun ProvideContainerCompositionLocals(
composeContainer: ComposeContainer,
content: @Composable () -> Unit,
) = CompositionLocalProvider(
LocalLifecycleOwner provides composeContainer,
content = content
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2024 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.platform

import androidx.compose.runtime.staticCompositionLocalOf
import androidx.lifecycle.LifecycleOwner

/**
* The CompositionLocal containing the current [LifecycleOwner].
*/
actual val LocalLifecycleOwner = staticCompositionLocalOf<LifecycleOwner> {
noLocalProvidedFor("LocalLifecycleOwner")
}

@Suppress("SameParameterValue")
private fun noLocalProvidedFor(name: String): Nothing {
error("CompositionLocal $name not present")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2024 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 kotlinx.cinterop.ObjCAction
import platform.Foundation.NSNotificationCenter
import platform.Foundation.NSSelectorFromString
import platform.UIKit.UIApplication
import platform.UIKit.UIApplicationDidEnterBackgroundNotification
import platform.UIKit.UIApplicationState
import platform.UIKit.UIApplicationWillEnterForegroundNotification
import platform.darwin.NSObject

internal class ApplicationStateListener(
/**
* Callback which will be called with `true` when the app becomes active, and `false` when the app goes background
*/
private val callback: (Boolean) -> Unit
) : NSObject() {
init {
val notificationCenter = NSNotificationCenter.defaultCenter

notificationCenter.addObserver(
this,
NSSelectorFromString(::applicationWillEnterForeground.name),
UIApplicationWillEnterForegroundNotification,
null
)

notificationCenter.addObserver(
this,
NSSelectorFromString(::applicationDidEnterBackground.name),
UIApplicationDidEnterBackgroundNotification,
null
)
}

@ObjCAction
fun applicationWillEnterForeground() {
callback(true)
}

@ObjCAction
fun applicationDidEnterBackground() {
callback(false)
}

/**
* Deregister from [NSNotificationCenter]
*/
fun dispose() {
val notificationCenter = NSNotificationCenter.defaultCenter

notificationCenter.removeObserver(this, UIApplicationWillEnterForegroundNotification, null)
notificationCenter.removeObserver(this, UIApplicationDidEnterBackgroundNotification, null)
}

companion object {
val isApplicationActive: Boolean
get() = UIApplication.sharedApplication.applicationState != UIApplicationState.UIApplicationStateBackground
}
}
Loading
Loading