https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
o

Oleksandr Balan

01/28/2022, 9:49 AM
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
@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 },
                )
            }
        }
    }
}
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

clark

01/28/2022, 1:43 PM
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

Adam Powell

01/28/2022, 2:56 PM
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

Oleksandr Balan

01/28/2022, 3:53 PM
@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:
+ 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:
+ 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

Adam Powell

01/31/2022, 11:31 PM
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

Oleksandr Balan

01/31/2022, 11:49 PM
Nice catch, just overriding this method for
PopupLayout
did the same thing as custom text toolbar 😅
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

Adam Powell

02/01/2022, 2:42 AM
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

Oleksandr Balan

02/01/2022, 6:38 AM
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

Adam Powell

02/01/2022, 2:43 PM
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

Oleksandr Balan

02/01/2022, 2:47 PM
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 👇
/**
 * 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
}