Skip to content
Open
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
136 changes: 125 additions & 11 deletions android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import android.view.KeyEvent
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewTreeObserver
import android.view.ViewConfiguration
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
Expand Down Expand Up @@ -227,6 +228,27 @@ class CodeEditorView(context: Context) : View(context) {
// Keyboard avoidance: the tracker turns the window's IME overlap into a second bottom inset in px.
private var avoidsKeyboard = false
private var keyboardInset = 0
private var keyboardTop = Int.MAX_VALUE
private val windowSpot = IntArray(2)
// Page mode under avoidKeyboard: a reveal due before the next draw, and the scroller height the layout watch saw.
private var pageRevealPending = false
private var watchingPage = false
private var pageHeight = -1
private val onPageLayout = ViewTreeObserver.OnGlobalLayoutListener {
val h = pageScroller()?.height ?: -1
if (h != pageHeight) {
pageHeight = h
revealInPage()
}
}
// Before the draw, so the page moves in the frame that shows the caret's new row.
private val onPagePreDraw = ViewTreeObserver.OnPreDrawListener {
if (revealPending || pageRevealPending) {
pageRevealPending = false
revealInPage()
}
true
}
private var keyboardOffset = 0
private var keyboardTracker: KeyboardInsetTracker? = null
private var contentInsetTop = 0f
Expand Down Expand Up @@ -360,7 +382,7 @@ class CodeEditorView(context: Context) : View(context) {
}

fun focus() {
requestFocus()
focusKeepingPage()
showKeyboard()
}

Expand Down Expand Up @@ -408,17 +430,87 @@ class CodeEditorView(context: Context) : View(context) {
if (isFocused) revealPending = true
}

/** Pixels of the view under the keyboard, from KeyboardInsetTracker; applied like a bottom inset. */
fun applyKeyboardInset(px: Int) {
if (px == keyboardInset) return
keyboardInset = px
/** The keyboard's top in window pixels from KeyboardInsetTracker, Int.MAX_VALUE with none. Tests inject one here. */
fun applyKeyboardTop(px: Int) {
keyboardTop = px
updateKeyboardInset()
revealInPage()
}

// A scrolling editor takes its overlap with the keyboard's top raised by keyboardOffset as a bottom inset.
private fun updateKeyboardInset() {
var inset = 0
if (isScrollEnabled && keyboardTop != Int.MAX_VALUE) {
getLocationInWindow(windowSpot)
inset = KeyboardInset.overlap(windowSpot[1] + height, keyboardTop - keyboardOffset)
}
if (inset == keyboardInset) return
keyboardInset = inset
applyInsets()
}

/**
* Page mode under avoidKeyboard: scrolls the nearest vertical scroller the least that shows the caret row inside it
* and above the keyboard's top raised by keyboardOffset.
*/
private fun revealInPage() {
if (isScrollEnabled || !avoidsKeyboard || !isFocused) return
val page = pageScroller() ?: return
// From the layout, as revealCaret reads it, so a reveal before the draw sees the caret's new row.
val m = rowMetrics()
val head = core.selection.head
val line = core.document.lineAt(head)
val entry = cache[line] ?: layoutLine(line)
getLocationInWindow(windowSpot)
val rowTop = windowSpot[1] + viewport.lineTop(line) + entry.layout.rowOf(head - core.document.lineStart(line)) * m.rowHeight
page.getLocationInWindow(windowSpot)
// The scroller clamps its own scrollBy, so a direction it can move in is open-ended here.
val delta = CoreNative.pageRevealDelta(
rowTop, rowTop + m.rowHeight, windowSpot[1], windowSpot[1] + page.height, keyboardTop, keyboardOffset,
if (page.canScrollVertically(-1)) Int.MAX_VALUE else 0, if (page.canScrollVertically(1)) Int.MAX_VALUE else 0,
)
if (delta != 0) page.scrollBy(0, delta)
}

// The nearest parent that scrolls vertically: a horizontal scroller in between is skipped.
private fun pageScroller(): View? {
var p = parent as? View
while (p != null && !(p.canScrollVertically(1) || p.canScrollVertically(-1))) p = p.parent as? View
return p
}

// While a page-mode editor under avoidKeyboard has the focus, any layout (a scroller shrinking with an avoiding
// view, the editor growing a line) shows the caret again.
private fun watchPage() {
val on = isFocused && isAttachedToWindow && !isScrollEnabled && avoidsKeyboard
if (on == watchingPage) return
watchingPage = on
val observer = viewTreeObserver
if (on) {
pageHeight = pageScroller()?.height ?: -1
observer.addOnGlobalLayoutListener(onPageLayout)
observer.addOnPreDrawListener(onPagePreDraw)
} else {
pageRevealPending = false
observer.removeOnGlobalLayoutListener(onPageLayout)
observer.removeOnPreDrawListener(onPagePreDraw)
}
}

// A ScrollView scrolls a focused child's whole rect into view before onFocusChanged, which moves the page under a
// tall page-mode editor before the keyboard opens. The page reveal shows the caret instead.
private fun focusKeepingPage() {
val page = if (isFocused || isScrollEnabled || !avoidsKeyboard) null else pageScroller()
val y = page?.scrollY ?: 0
requestFocus()
if (page != null && page.scrollY != y) page.scrollTo(page.scrollX, y)
}

/** Follows the window's IME insets while attached; off by default. */
fun setAvoidKeyboard(on: Boolean) {
avoidsKeyboard = on
if (on && isAttachedToWindow) startKeyboardTracker() else stopKeyboardTracker()
watchPage()
}

val isAvoidingKeyboard: Boolean get() = keyboardTracker != null
Expand All @@ -428,7 +520,8 @@ class CodeEditorView(context: Context) : View(context) {
val px = dp(value.coerceAtLeast(0f))
if (px == keyboardOffset) return
keyboardOffset = px
applyInsets()
updateKeyboardInset()
revealInPage()
}

private fun applyInsets() {
Expand All @@ -442,7 +535,7 @@ class CodeEditorView(context: Context) : View(context) {

private fun startKeyboardTracker() {
if (keyboardTracker != null) return
keyboardTracker = KeyboardInsetTracker(this, ::applyKeyboardInset).also { it.start() }
keyboardTracker = KeyboardInsetTracker(this, ::applyKeyboardTop).also { it.start() }
}

private fun stopKeyboardTracker() {
Expand All @@ -454,6 +547,12 @@ class CodeEditorView(context: Context) : View(context) {
if (enabled == isScrollEnabled) return
isScrollEnabled = enabled
scroller.abort()
updateKeyboardInset()
watchPage()
if (watchingPage) {
pageRevealPending = true
invalidate()
}
}

fun scrollToLine(line: Int, animated: Boolean) {
Expand All @@ -468,8 +567,16 @@ class CodeEditorView(context: Context) : View(context) {

private fun lineTop(line: Int): Int = viewport.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight

/** Scrolls the least amount that shows the caret with the text padding around it. */
/** Scrolls the least amount that shows the caret with the text padding around it, the page too in page mode. */
fun revealSelection() {
revealCaret()
if (watchingPage) {
pageRevealPending = true
invalidate()
}
}

private fun revealCaret() {
val m = rowMetrics()
val head = core.selection.head
val line = core.document.lineAt(head)
Expand Down Expand Up @@ -976,14 +1083,14 @@ class CodeEditorView(context: Context) : View(context) {

override fun placeCaret(offset: Int) {
menu.hide()
requestFocus()
focusKeepingPage()
showKeyboard()
core.setSelection(offset, offset)
showInsertionHandle()
}

override fun selectWord(offset: Int) {
requestFocus()
focusKeepingPage()
showKeyboard()
core.selectWordAt(offset)
wordAnchor = core.selection.range
Expand Down Expand Up @@ -1205,6 +1312,7 @@ class CodeEditorView(context: Context) : View(context) {
override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
focused = gainFocus
watchPage()
if (gainFocus) {
restartBlink()
} else {
Expand All @@ -1220,12 +1328,18 @@ class CodeEditorView(context: Context) : View(context) {
if (dropped) return
engine()
if (avoidsKeyboard) startKeyboardTracker()
watchPage()
if (autoFocusPending) runAutoFocus()
}

override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stopKeyboardTracker()
if (watchingPage) {
watchingPage = false
viewTreeObserver.removeOnGlobalLayoutListener(onPageLayout)
viewTreeObserver.removeOnPreDrawListener(onPagePreDraw)
}
removeCallbacks(longPressRunnable)
removeCallbacks(blink)
removeCallbacks(hideInsertion)
Expand Down Expand Up @@ -1281,7 +1395,7 @@ class CodeEditorView(context: Context) : View(context) {
viewport.beginDraw(checksCalls = debugSwitch())
if (revealPending) {
revealPending = false
revealSelection()
revealCaret()
}
// One core call for the document. Until publish returns, every document read comes from it.
var f = readFrame()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import android.view.WindowManager

/** The arithmetic behind KeyboardInsetTracker, kept pure so JUnit covers it. */
internal object KeyboardInset {
/** Pixels of the view covered by the keyboard, both measured in window coordinates. */
fun overlap(viewBottomInWindow: Int, windowHeight: Int, imeBottom: Int): Int =
maxOf(0, viewBottomInWindow - (windowHeight - imeBottom))
/** The keyboard's top in window pixels, Int.MAX_VALUE with no keyboard up. */
fun keyboardTop(windowHeight: Int, imeBottom: Int): Int = if (imeBottom <= 0) Int.MAX_VALUE else windowHeight - imeBottom

/** Pixels of the view under a keyboard whose top is at keyboardTop, both in window coordinates. */
fun overlap(viewBottomInWindow: Int, keyboardTop: Int): Int =
if (keyboardTop == Int.MAX_VALUE) 0 else maxOf(0, viewBottomInWindow - keyboardTop)

/** adjustPan moves the whole window instead, so an inset on top of it would double the avoidance. */
fun applies(softInputMode: Int): Boolean =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,32 @@ import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat

/** Listens to the window's IME insets on behalf of one view and reports its overlap with the keyboard in pixels. */
internal class KeyboardInsetTracker(private val view: View, private val apply: (Int) -> Unit) {
private val location = IntArray(2)
/** Listens to the window's IME insets on behalf of one view and reports the keyboard's top in window pixels. */
internal class KeyboardInsetTracker(private val view: View, private val apply: (keyboardTop: Int) -> Unit) {
// The window applies the end state before an IME animation's first frame. Skipping it lets a page ride the frames.
private var animating = false

// Progress frames arrive on every view with a callback; androidx emulates them below API 30.
private val callback = object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
override fun onPrepare(animation: WindowInsetsAnimationCompat) {
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) animating = true
}

override fun onProgress(insets: WindowInsetsCompat, running: List<WindowInsetsAnimationCompat>): WindowInsetsCompat {
if (running.any { it.typeMask and WindowInsetsCompat.Type.ime() != 0 }) update(insets)
return insets
}

override fun onEnd(animation: WindowInsetsAnimationCompat) {
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) animating = false
ViewCompat.getRootWindowInsets(view)?.let(::update)
}
}

fun start() {
ViewCompat.setWindowInsetsAnimationCallback(view, callback)
ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets ->
update(insets)
if (!animating) update(insets)
insets
}
ViewCompat.getRootWindowInsets(view)?.let(::update)
Expand All @@ -36,19 +42,18 @@ internal class KeyboardInsetTracker(private val view: View, private val apply: (
fun stop() {
ViewCompat.setWindowInsetsAnimationCallback(view, null)
ViewCompat.setOnApplyWindowInsetsListener(view, null)
apply(0)
apply(Int.MAX_VALUE)
}

private fun update(insets: WindowInsetsCompat) {
val mode = activity(view.context)?.window?.attributes?.softInputMode ?: 0
if (!KeyboardInset.applies(mode)) {
apply(0)
apply(Int.MAX_VALUE)
return
}
val root = view.rootView ?: return
view.getLocationInWindow(location)
val ime = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
apply(KeyboardInset.overlap(location[1] + view.height, root.height, ime))
apply(KeyboardInset.keyboardTop(root.height, ime))
}

private fun activity(context: Context): Activity? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,17 @@ import org.junit.Test

class KeyboardInsetTest {
@Test
fun overlapIsTheViewBandUnderTheKeyboard() {
assertEquals(0, KeyboardInset.overlap(viewBottomInWindow = 1000, windowHeight = 2000, imeBottom = 0))
assertEquals(0, KeyboardInset.overlap(1000, 2000, 900))
assertEquals(300, KeyboardInset.overlap(1500, 2000, 800))
assertEquals(800, KeyboardInset.overlap(2000, 2000, 800))
fun theKeyboardTopIsTheWindowLessTheImeAndOutOfReachWithNone() {
assertEquals(Int.MAX_VALUE, KeyboardInset.keyboardTop(windowHeight = 2000, imeBottom = 0))
assertEquals(1200, KeyboardInset.keyboardTop(2000, 800))
}

@Test
fun overlapIsTheViewBandUnderTheKeyboardTop() {
assertEquals(0, KeyboardInset.overlap(viewBottomInWindow = 1000, keyboardTop = Int.MAX_VALUE))
assertEquals(0, KeyboardInset.overlap(1000, 1100))
assertEquals(300, KeyboardInset.overlap(1500, 1200))
assertEquals(800, KeyboardInset.overlap(2000, 1200))
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,23 @@ class AvoidKeyboardTest {
val sizes = ArrayList<Float>()
editor.onContentSizeListener = { _, h -> sizes.add(h) }
editor.setAvoidKeyboard(true)
editor.setInitialText(List(50) { "line $it" }.joinToString("\n"))
val text = List(50) { "line $it" }.joinToString("\n")
editor.setInitialText(text)
// The window may give the editor focus, and then an inset change reveals the caret: keep it on line 49.
editor.core.setSelection(text.length, text.length)
layout(editor)
draw(editor)
editor.scrollToLine(49, false)
draw(editor)
val before = editor.frame.scrollY
val density = editor.resources.displayMetrics.density
editor.applyKeyboardInset(300)
val bottom = IntArray(2).also { editor.getLocationInWindow(it) }[1] + editor.height
editor.applyKeyboardTop(bottom - 300)
editor.scrollToLine(49, false)
draw(editor)
assertEquals(300 / density, editor.frame.scrollY - before, 1f)
assertEquals("content size excludes the keyboard inset", 1, sizes.size)
editor.applyKeyboardInset(0)
editor.applyKeyboardTop(Int.MAX_VALUE)
editor.scrollToLine(49, false)
draw(editor)
assertEquals(before, editor.frame.scrollY, 1f)
Expand Down
Loading