I am facing an issue with displaying a copy-paste ...
# compose
o
I am facing an issue with displaying a copy-paste popup inside a Popup composable. My use-case is to display a text field inside our component, which uses Popup underneath. Text field works correctly, but when I try to copy-paste something application crashes. Is it even possible to “nest” popups? Tested with latest Compose 1.2.0-alpha02 & Kotlin 1.6.10, also reproduced in older versions. See video, code example and crash log in the 🧵. Thx for advice.
plus one 3
Copy code
@Composable
fun PopupInPopup() {
    var visible by remember { mutableStateOf(false) }
    var text by remember { mutableStateOf("") }

    Button(onClick = { visible = true }) {
        Text("Show popup")
    }

    if (visible) {
        Popup(
            onDismissRequest = { visible = true },
            properties = PopupProperties(
                focusable = true
            )
        ) {
            Surface {
                TextField(
                    value = text,
                    onValueChange = { text = it },
                )
            }
        }
    }
}
Copy code
2022-01-28 10:16:43.902 23575-23575/com.example.popupinpopup E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.popupinpopup, PID: 23575
    java.lang.NullPointerException: view.startActionMode(
      …           type
            ) must not be null
        at androidx.compose.ui.platform.TextToolbarHelperMethods.startActionMode(AndroidTextToolbar.android.kt:89)
        at androidx.compose.ui.platform.AndroidTextToolbar.showMenu(AndroidTextToolbar.android.kt:53)
        at androidx.compose.foundation.text.selection.TextFieldSelectionManager.showSelectionToolbar$foundation_release(TextFieldSelectionManager.kt:596)
        at androidx.compose.foundation.text.CoreTextFieldKt.SelectionToolbarAndHandles(CoreTextField.kt:840)
        at androidx.compose.foundation.text.CoreTextFieldKt.access$SelectionToolbarAndHandles(CoreTextField.kt:1)
        at androidx.compose.foundation.text.CoreTextFieldKt$CoreTextField$4$1$1.invoke(CoreTextField.kt:565)
        at androidx.compose.foundation.text.CoreTextFieldKt$CoreTextField$4$1$1.invoke(CoreTextField.kt:527)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.foundation.text.selection.SimpleLayoutKt.SimpleLayout(SimpleLayout.kt:79)
        at androidx.compose.foundation.text.CoreTextFieldKt$CoreTextField$4$1.invoke(CoreTextField.kt:527)
        at androidx.compose.foundation.text.CoreTextFieldKt$CoreTextField$4$1.invoke(CoreTextField.kt:510)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:142)
        at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2158)
        at androidx.compose.runtime.ComposerImpl.skipToGroupEnd(Composer.kt:2436)
        at androidx.compose.material.TextFieldKt.IconsWithTextFieldLayout-SxpAMN0(TextField.kt:448)
        at androidx.compose.material.TextFieldKt.access$IconsWithTextFieldLayout-SxpAMN0(TextField.kt:1)
        at androidx.compose.material.TextFieldKt$TextFieldLayout$1.invoke(TextField.kt:369)
        at androidx.compose.material.TextFieldKt$TextFieldLayout$1.invoke(TextField.kt:367)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.foundation.text.CoreTextFieldKt.CoreTextField(CoreTextField.kt:510)
        at androidx.compose.foundation.text.BasicTextFieldKt.BasicTextField(BasicTextField.kt:262)
        at androidx.compose.material.TextFieldKt.TextFieldLayout-uBqXD2s(TextField.kt:347)
        at androidx.compose.material.TextFieldImplKt$TextFieldImpl$3.invoke-h1eT-Ww(TextFieldImpl.kt:178)
        at androidx.compose.material.TextFieldImplKt$TextFieldImpl$3.invoke(TextFieldImpl.kt:129)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:214)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.material.TextFieldTransitionScope.Transition-DTcfvLk(TextFieldImpl.kt:357)
        at androidx.compose.material.TextFieldImplKt.TextFieldImpl(TextFieldImpl.kt:119)
        at androidx.compose.material.TextFieldKt.TextField(TextField.kt:295)
        at androidx.compose.material.TextFieldKt.TextField(TextField.kt:180)
        at androidx.compose.material.TextFieldKt$TextField$3.invoke(Unknown Source:66)
        at androidx.compose.material.TextFieldKt$TextField$3.invoke(Unknown Source:10)
        at androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:142)
        at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2158)
        at androidx.compose.runtime.ComposerImpl.skipCurrentGroup(Composer.kt:2413)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2594)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2580)
c
Is it correct to assume that you aren't calling
view.startActionMode
in your code? If you aren't, then you could try throwing a break point in that method and finding what gets passed to it when it works for the first pop up and where it comes from in that case. Also, have you tried doing the second pop up from outside of the first pop up and had it work?
a
Please file this on the issue tracker. At a minimum it should give a more descriptive exception than this 🙂
Nesting popups on Android has traditionally been somewhere between heavily discouraged and unsupported for reasons of being heavily discouraged. Cascading is usually achieved by using content within a single popup window that may present at different sizes in different containers in an otherwise transparent window.
o
@clark Yeap, I am not calling
view.startActionMode
in the code. Moreover, I have attached ☝️ literally full code to reproduce it 🤷 I have been trying to debug it, but in inspector I see none of params to be null. Actually by “second popup” I mean the action menu with copy-paste actions, which is shown on long press. And yes, it normally works out of popup. @Adam Powell Filed, thx for the info. https://issuetracker.google.com/issues/216662636
👍 1
Hmm, I have investigated it a bit further: When I long-press the text field in the Popup, the app’s view hierarchy is following:
Copy code
+ ViewRootImpl
\--+ PopupLayout
   \--- AndroidComposeView
This means, that the call chain of “startActionModeForChild()” is ended in the “ViewRootImpl”, which than always return “null”, and causes a crash. In the main part of the app (outside of the popup) the view hierarchy differs:
Copy code
+ ViewRootImpl
\--+ DecorView
   \--+ ...
      \--+ ContentFrameLayout
         \--+ ComposeView
            \--- AndroidComposeView
Thus the call chain of
startActionModeForChild()
is ended up in the
DecorView
which has proper handling of ActionModes. Maybe a dummy question, but is there any way how to supply
DecorView
in Popup hierarchy? One thing that I have already tried is to supply the custom
TextToolbar
, which starts an action mode right on the decor view of the window. There are several issues though when popup is aligned not in top start corner. I have to modify the PopupLayout to expose it’s position to then offset the Rect for an action mode. But this trick does not fix the text field handles and they remains aligned in the top-left corner (see attached video) :( I also tried it another way, and force popup to be placed inside the
DecorView
, instead of the window itself. But this way I have to change
WindowManager.LayoutParams
to
ViewGroup.LayoutParams
and lose a possibility to setup window parameters. Is there some other way how to place the popup in the window inside the decoration view?
a
ah, yeah not having a handler for
startActionModeForChild
would do it too
you could probably copy the code for the popup composable, have PopupLayout implement that method, and delegate to the view from
LocalView.current
from the parent composition
💡 1
it's been a few years but I think the window layering for action modes might place that correctly
o
Nice catch, just overriding this method for
PopupLayout
did the same thing as custom text toolbar 😅
Copy code
override fun startActionModeForChild(originalView: View?, callback: ActionMode.Callback?, type: Int): ActionMode =
        composeView.parent.startActionModeForChild(originalView, callback, type)
Thus action menu is placed correctly, but handles are still aligned at the top-start 🤔 The offset in
SelectionHandle
is Offset(0.0, 58.0), which I assume is calculated from text field position inside a popup (+ status bar height maybe?)
a
Yeah at that point it can't find a path from the action mode anchor view in the popup to the host view to calculate the offset. You can do some more math in there to fix up the offsets, TextView passes reference coordinates within the view when it shows this normally
o
Thx, I could try to calculate it, but if I understand correctly there is no easy way to provide those offset to the
SelectionHandle
instead of copying the whole
CoreTextField
?
a
You should be able to, you'll just need to plumb it through the action mode
If you don't actually need this to be a popup and can use a dialog for this instead you'll probably have a much easier time
But it should be possible to get all of this plumbed through. I can check some more of the specifics later
🙏 1
👍 1
o
I have already tried the Dialog approach, but I failed to force the dialog to be below the system bars (navigation bar, to be specific), which is a requirement for our component built above
I have chosen the other way how to solve this for now. Thx @Adam Powell for your time 👍 For our usage the popup should be fullscreen, thus we do not need properties, which were bound to the window layout params. So I could go with adding a
PopupLayout
to the decor view with “match_parent” params. This reduces a lot of Popup positioning logic and fixes action menu crash & position, as well as text handle position. I will share a source code, in case someone will be interested 👇
Copy code
/**
 * Opens a popup with the given content.
 * The popup is visible as long as it is part of the composition hierarchy.
 *
 * Note: This is highly reduced version of the official Popup composable with some changes:
 * * Fixes an issue with action mode (copy-paste) menu, see <https://issuetracker.google.com/issues/216662636>
 * * Adds the view to the decor view of the window, instead of the window itself.
 * * Do not have properties, as Popup is laid out as fullscreen.
 *
 * @param onDismissRequest Executes when the user clicks outside of the popup.
 * @param content The content to be displayed inside the popup.
 */
@Composable
fun FullScreenPopup(
    onDismissRequest: (() -> Unit)? = null,
    content: @Composable () -> Unit
) {
    val view = LocalView.current
    val parentComposition = rememberCompositionContext()
    val currentContent by rememberUpdatedState(content)
    val popupId = rememberSaveable { UUID.randomUUID() }
    val popupLayout = remember {
        PopupLayout(
            onDismissRequest = onDismissRequest,
            composeView = view,
            popupId = popupId
        ).apply {
            setContent(parentComposition) {
                Box(Modifier.semantics { this.popup() }) {
                    currentContent()
                }
            }
        }
    }

    DisposableEffect(popupLayout) {
        popupLayout.show()
        popupLayout.updateParameters(
            onDismissRequest = onDismissRequest
        )
        onDispose {
            popupLayout.disposeComposition()
            // Remove the window
            popupLayout.dismiss()
        }
    }

    SideEffect {
        popupLayout.updateParameters(
            onDismissRequest = onDismissRequest
        )
    }
}

/**
 * The layout the popup uses to display its content.
 */
@SuppressLint("ViewConstructor")
internal class PopupLayout(
    private var onDismissRequest: (() -> Unit)?,
    composeView: View,
    popupId: UUID
) : AbstractComposeView(composeView.context),
    ViewRootForInspector {

    private val decorView = findOwner<Activity>(composeView.context)?.window?.decorView as ViewGroup

    override val subCompositionView: AbstractComposeView get() = this

    init {
        id = android.R.id.content
        ViewTreeLifecycleOwner.set(this, ViewTreeLifecycleOwner.get(composeView))
        ViewTreeViewModelStoreOwner.set(this, ViewTreeViewModelStoreOwner.get(composeView))
        ViewTreeSavedStateRegistryOwner.set(this, ViewTreeSavedStateRegistryOwner.get(composeView))
        // Set unique id for AbstractComposeView. This allows state restoration for the state
        // defined inside the Popup via rememberSaveable()
        setTag(R.id.compose_view_saveable_id_tag, "Popup:$popupId")
    }

    private var content: @Composable () -> Unit by mutableStateOf({})

    override var shouldCreateCompositionOnAttachedToWindow: Boolean = false
        private set

    fun show() {
        decorView.addView(this, MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))

        requestFocus()
    }

    fun setContent(parent: CompositionContext, content: @Composable () -> Unit) {
        setParentCompositionContext(parent)
        this.content = content
        shouldCreateCompositionOnAttachedToWindow = true
    }

    @Composable
    override fun Content() {
        content()
    }

    /**
     * Taken from PopupWindow
     */
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            if (keyDispatcherState == null) {
                return super.dispatchKeyEvent(event)
            }
            if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
                val state = keyDispatcherState
                state?.startTracking(event, this)
                return true
            } else if (event.action == KeyEvent.ACTION_UP) {
                val state = keyDispatcherState
                if (state != null && state.isTracking(event) && !event.isCanceled) {
                    onDismissRequest?.invoke()
                    return true
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }

    fun updateParameters(
        onDismissRequest: (() -> Unit)?
    ) {
        this.onDismissRequest = onDismissRequest
    }

    fun dismiss() {
        ViewTreeLifecycleOwner.set(this, null)
        decorView.removeView(this)
    }
}

private inline fun <reified T> findOwner(context: Context): T? {
    var innerContext = context
    while (innerContext is ContextWrapper) {
        if (innerContext is T) {
            return innerContext
        }
        innerContext = innerContext.baseContext
    }
    return null
}