Skip to content
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
32 changes: 24 additions & 8 deletions android/src/main/cpp/core_jni.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ int64_t now_micros(void *) {
const cp_language *resolve(void *ctx, const char *id) {
JNIEnv *e = env();
jstring name = java_string(e, id);
if (name == nullptr) {
clear(e);
return nullptr;
}
jlong handle = e->CallLongMethod(static_cast<HostRef *>(ctx)->host, resolve_id, name);
e->DeleteLocalRef(name);
if (e->ExceptionCheck()) {
Expand Down Expand Up @@ -136,14 +140,15 @@ jint fill(JNIEnv *e, jintArray out, Call call) {
FN(abiRange)(JNIEnv *e, jclass) -> jintArray {
jintArray out = e->NewIntArray(2);
jint v[2] = {cp_abi_min(), cp_abi_max()};
e->SetIntArrayRegion(out, 0, 2, v);
if (out != nullptr) e->SetIntArrayRegion(out, 0, 2, v);
return out;
}

// error[0] receives the message: set on failure, and on success when only the injections failed.
FN(languageLoad)(JNIEnv *e, jclass, jstring jid, jlong pointer, jbyteArray highlights, jbyteArray injections,
jobjectArray error) -> jlong {
const char *id = e->GetStringUTFChars(jid, nullptr);
if (id == nullptr) return 0;
jsize hn = e->GetArrayLength(highlights);
jsize in = injections ? e->GetArrayLength(injections) : 0;
std::vector<char> h(static_cast<size_t>(hn));
Expand All @@ -154,12 +159,14 @@ FN(languageLoad)(JNIEnv *e, jclass, jstring jid, jlong pointer, jbyteArray highl
cp_language *language = cp_language_load(id, ptr<const void>(pointer), h.data(), static_cast<uint32_t>(hn), i.data(),
static_cast<uint32_t>(in), message, sizeof(message));
e->ReleaseStringUTFChars(jid, id);
if (message[0] && error) e->SetObjectArrayElement(error, 0, java_string(e, message));
jstring m = message[0] && error ? java_string(e, message) : nullptr;
if (m != nullptr) e->SetObjectArrayElement(error, 0, m);
return handle(language);
}

FN(styleId)(JNIEnv *e, jclass, jstring jname) -> jint {
const char *name = e->GetStringUTFChars(jname, nullptr);
if (name == nullptr) return 0;
jint id = cp_style_id(name);
e->ReleaseStringUTFChars(jname, name);
return id;
Expand Down Expand Up @@ -219,7 +226,7 @@ FN(snapshotChanged)(JNIEnv *e, jclass, jlong snapshot) -> jintArray {
cp_snapshot_info info{};
cp_snapshot_info_get(ptr<cp_snapshot>(snapshot), &info);
jintArray out = e->NewIntArray(static_cast<jsize>(info.changed_len));
if (info.changed_len) {
if (out != nullptr && info.changed_len) {
e->SetIntArrayRegion(out, 0, static_cast<jsize>(info.changed_len),
reinterpret_cast<const jint *>(cp_snapshot_changed(ptr<cp_snapshot>(snapshot))));
}
Expand Down Expand Up @@ -322,7 +329,9 @@ jstring copy_text(JNIEnv *e, const cp_editor *editor, uint32_t start, uint32_t e

jintArray int_array(JNIEnv *e, const int32_t *values, uint32_t n) {
jintArray out = e->NewIntArray(static_cast<jsize>(n));
if (n > 0) e->SetIntArrayRegion(out, 0, static_cast<jsize>(n), reinterpret_cast<const jint *>(values));
if (out != nullptr && n > 0) {
e->SetIntArrayRegion(out, 0, static_cast<jsize>(n), reinterpret_cast<const jint *>(values));
}
return out;
}

Expand Down Expand Up @@ -389,8 +398,12 @@ FN(docOffset)(JNIEnv *, jclass, jlong editor, jint line, jint column) -> jint {
return static_cast<jint>(cp_doc_offset(ed(editor), line, column));
}

FN(docGrapheme)(JNIEnv *, jclass, jlong editor, jint offset, jboolean forward) -> jint {
return static_cast<jint>(cp_doc_grapheme(ed(editor), at(offset), forward ? 1 : 0));
// start in the high 32 bits, end in the low ones.
FN(docWordAt)(JNIEnv *, jclass, jlong editor, jint offset) -> jlong {
uint32_t start = 0;
uint32_t end = 0;
cp_doc_word_at(ed(editor), at(offset), &start, &end);
return static_cast<jlong>(start) << 32 | end;
}

FN(editorSettings)(JNIEnv *, jclass, jlong editor, jint tab, jboolean spaces, jboolean indent, jboolean close)
Expand Down Expand Up @@ -489,6 +502,7 @@ FN(editorSetSearch)(JNIEnv *e, jclass, jlong editor, jstring query, jint flags,
char message[512] = {0};
if (cp_editor_set_search(ed(editor), units_of(q), count_of(q), flags, message, sizeof(message)) != 0) return JNI_TRUE;
jstring m = java_string(e, message);
if (m == nullptr) return JNI_FALSE;
e->SetObjectArrayElement(error, 0, m);
e->DeleteLocalRef(m);
return JNI_FALSE;
Expand All @@ -502,6 +516,7 @@ FN(editorSearchActive)(JNIEnv *, jclass, jlong editor) -> jboolean {

FN(editorSearchStale)(JNIEnv *, jclass, jlong editor) -> jboolean { return cp_editor_search_stale(ed(editor)) != 0; }
FN(editorMatchCount)(JNIEnv *, jclass, jlong editor) -> jint { return cp_editor_match_count(ed(editor)); }
FN(editorMatchLimited)(JNIEnv *, jclass, jlong editor) -> jboolean { return cp_editor_match_limited(ed(editor)) != 0; }

FN(editorMatches)(JNIEnv *e, jclass, jlong editor) -> jintArray {
uint32_t n = cp_editor_matches(ed(editor), nullptr, 0);
Expand All @@ -527,11 +542,12 @@ FN(editorReplaceAll)(JNIEnv *e, jclass, jlong editor, jstring text) -> jint {
return cp_editor_replace_all(ed(editor), units_of(s), count_of(s));
}

FN(editorAcceptMatches)(JNIEnv *e, jclass, jlong editor, jint revision, jintArray pairs) -> jboolean {
FN(editorAcceptMatches)(JNIEnv *e, jclass, jlong editor, jint revision, jintArray pairs, jboolean limited)
-> jboolean {
jsize n = e->GetArrayLength(pairs);
std::vector<int32_t> in(static_cast<size_t>(n));
if (n > 0) e->GetIntArrayRegion(pairs, 0, n, reinterpret_cast<jint *>(in.data()));
return cp_editor_accept_matches(ed(editor), revision, in.data(), static_cast<uint32_t>(n)) != 0;
return cp_editor_accept_matches(ed(editor), revision, in.data(), static_cast<uint32_t>(n), limited ? 1 : 0) != 0;
}

FN(editorSearchQuery)(JNIEnv *, jclass, jlong editor) -> jlong { return handle(cp_editor_search_query(ed(editor))); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,9 +358,9 @@ class HybridCodeEditorView(val context: ThemedReactContext) : HybridCodeEditorVi

override fun paste(): Promise<Unit> = onMain { editor.paste(ChangeOrigin.Api) }

override fun setSearch(query: NativeSearchQuery): Promise<Double> = deferred { promise ->
override fun setSearch(query: NativeSearchQuery): Promise<NativeSearchResult> = deferred { promise ->
editor.setSearch(SearchQuery(query.text, query.regex, query.caseSensitive, query.wholeWord))
editor.whenSearchFresh { promise.resolve(editor.matchCount.toDouble()) }
editor.whenSearchFresh { promise.resolve(NativeSearchResult(editor.matchCount.toDouble(), editor.matchLimited)) }
}

override fun findNext(): Promise<NativeSearchHit> = deferred { promise ->
Expand Down
12 changes: 11 additions & 1 deletion android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl

fun selectWordAt(offset: Int) = mutate { CoreNative.editorSelectWordAt(it, offset) }

/** The word [selectWordAt] would select, without moving the selection. */
fun wordRangeAt(offset: Int): Range {
val packed = CoreNative.docWordAt(handle(), offset)
return Range((packed ushr 32).toInt(), packed.toInt())
}

/** True when a backspace at [caret] removes an auto closed pair. */
fun deletesPair(caret: Int): Boolean = CoreNative.editorDeletesPair(handle(), caret)

Expand All @@ -159,6 +165,9 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl
val matches: IntArray get() = CoreNative.editorMatches(handle())
val matchCount: Int get() = CoreNative.editorMatchCount(handle())

/** True when a match attempt hit PCRE2's match limit, so the matches stop there. */
val matchLimited: Boolean get() = CoreNative.editorMatchLimited(handle())

/** True while a query is active and its matches belong to an older revision. */
val searchStale: Boolean get() = CoreNative.editorSearchStale(handle())

Expand Down Expand Up @@ -188,7 +197,8 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl
fun textSnapshot(): Long = CoreNative.editorText(handle())

/** Stores matches computed elsewhere. False when the document moved on since [revision]. */
fun acceptMatches(revision: Int, matches: IntArray): Boolean = CoreNative.editorAcceptMatches(handle(), revision, matches)
fun acceptMatches(revision: Int, matches: IntArray, limited: Boolean): Boolean =
CoreNative.editorAcceptMatches(handle(), revision, matches, limited)

fun findNext(): SearchHit? = find(true)

Expand Down
35 changes: 0 additions & 35 deletions android/src/main/java/me/sectiontn/codepad/core/TextMovement.kt
Original file line number Diff line number Diff line change
@@ -1,41 +1,6 @@
package me.sectiontn.codepad.core

import me.sectiontn.codepad.syntax.CoreNative

object TextMovement {
/** Ordinals match CP_MOVE_*. */
enum class Unit { Char, Word, LineStart, LineEnd, DocStart, DocEnd }

fun isWordChar(c: Char): Boolean = c == '_' || c in 'a'..'z' || c in 'A'..'Z' || c in '0'..'9'

fun nextGrapheme(doc: Document, offset: Int): Int = CoreNative.docGrapheme(doc.handle, offset, true)

fun prevGrapheme(doc: Document, offset: Int): Int = CoreNative.docGrapheme(doc.handle, offset, false)

/** Double tap target: an identifier run, a whitespace run, or a single punctuation grapheme. */
fun wordRangeAt(doc: Document, offset: Int): Range {
val o = offset.coerceIn(0, doc.length)
val line = doc.lineAt(o)
val start = doc.lineStart(line)
val text = doc.line(line)
if (text.isEmpty()) return Range(start, start)
var col = (o - start).coerceIn(0, text.length)
if (col == text.length) col--
val c = text[col]
val cls: ((Char) -> Boolean)? = when {
isWordChar(c) -> { ch -> isWordChar(ch) }
c.isWhitespace() -> { ch -> ch.isWhitespace() }
else -> null
}
if (cls != null) {
var a = col
var b = col + 1
while (a > 0 && cls(text[a - 1])) a--
while (b < text.length && cls(text[b])) b++
return Range(start + a, start + b)
}
// A punctuation grapheme is its own word, so "a.b" splits in three.
val end = nextGrapheme(doc, start + col)
return Range(prevGrapheme(doc, end), end)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal object CoreNative {
@JvmStatic external fun docText(editor: Long, start: Int, end: Int): String
@JvmStatic external fun docPosition(editor: Long, offset: Int): Long
@JvmStatic external fun docOffset(editor: Long, line: Int, column: Int): Int
@JvmStatic external fun docGrapheme(editor: Long, offset: Int, forward: Boolean): Int
@JvmStatic external fun docWordAt(editor: Long, offset: Int): Long
@JvmStatic external fun editorSettings(editor: Long, tabSize: Int, spaces: Boolean, indent: Boolean, close: Boolean)
@JvmStatic external fun editorReplace(editor: Long, start: Int, end: Int, text: String, origin: Int, typing: Boolean, caretAfter: Boolean)
@JvmStatic external fun editorSetText(editor: Long, text: String, keepHistory: Boolean)
Expand All @@ -58,11 +58,12 @@ internal object CoreNative {
@JvmStatic external fun editorSearchActive(editor: Long): Boolean
@JvmStatic external fun editorSearchStale(editor: Long): Boolean
@JvmStatic external fun editorMatchCount(editor: Long): Int
@JvmStatic external fun editorMatchLimited(editor: Long): Boolean
@JvmStatic external fun editorMatches(editor: Long): IntArray
@JvmStatic external fun editorFind(editor: Long, forward: Boolean, out: IntArray): Boolean
@JvmStatic external fun editorReplaceCurrent(editor: Long, text: String): Boolean
@JvmStatic external fun editorReplaceAll(editor: Long, text: String): Int
@JvmStatic external fun editorAcceptMatches(editor: Long, revision: Int, pairs: IntArray): Boolean
@JvmStatic external fun editorAcceptMatches(editor: Long, revision: Int, pairs: IntArray, limited: Boolean): Boolean
@JvmStatic external fun editorSearchQuery(editor: Long): Long
@JvmStatic external fun searchRelease(search: Long)
@JvmStatic external fun editorText(editor: Long): Long
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ class CodeEditorView(context: Context) : View(context) {
fun setText(text: String, keepHistory: Boolean) {
ime.reset()
core.setText(text, keepHistory)
scroller.abort()
viewport.scrollTo(0, 0)
restartInput()
invalidate()
Expand Down Expand Up @@ -447,16 +448,17 @@ class CodeEditorView(context: Context) : View(context) {
}

fun scrollToLine(line: Int, animated: Boolean) {
val target = viewport.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight
scroller.abort()
val s = viewport.scroll()
if (animated) {
scroller.animateTo(s.x, s.y, s.x, target.coerceIn(0, s.maxY))
} else if (viewport.scrollTo(s.x, target)) {
scroller.animateTo(s.x, s.y) { lineTop(line).coerceAtMost(viewport.maxScrollY) }
} else if (viewport.scrollTo(s.x, lineTop(line))) {
onScrolled()
}
}

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. */
fun revealSelection() {
val m = rowMetrics()
Expand Down Expand Up @@ -506,6 +508,7 @@ class CodeEditorView(context: Context) : View(context) {
fun whenSearchFresh(block: () -> Unit) = search?.whenFresh(block) ?: block()

val matchCount: Int get() = core.matchCount
val matchLimited: Boolean get() = core.matchLimited

fun findNext(): EditorCore.SearchHit? = core.findNext().also { afterSearchMove() }

Expand Down Expand Up @@ -596,6 +599,7 @@ class CodeEditorView(context: Context) : View(context) {
cache.clear()
viewport.widestLine = 0
updateGutter()
scroller.abort()
viewport.scrollTo(0, 0)
invalidate()
}
Expand Down Expand Up @@ -978,7 +982,7 @@ class CodeEditorView(context: Context) : View(context) {

// The word under the long press stays selected and the far end follows the finger by words.
override fun extendWords(offset: Int) {
val word = TextMovement.wordRangeAt(core.document, offset)
val word = core.wordRangeAt(offset)
if (offset >= wordAnchor.start) {
core.setSelection(wordAnchor.start, maxOf(word.end, wordAnchor.end))
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package me.sectiontn.codepad.view
import android.content.Context
import android.graphics.Canvas
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.EdgeEffect
import android.widget.OverScroller
import kotlin.math.roundToInt

/** Fling physics and the four edge glows. The view keeps the scroll position, this only animates it. */
class ScrollController(context: Context, private val view: View) {
Expand All @@ -14,9 +16,17 @@ class ScrollController(context: Context, private val view: View) {
private val left = EdgeEffect(context)
private val right = EdgeEffect(context)

val isFinished: Boolean get() = scroller.isFinished
val currX: Int get() = scroller.currX
val currY: Int get() = scroller.currY
// The animateTo target, read again every frame.
private var target: (() -> Int)? = null
private var aimed = false
private var aimX = 0
private var aimY = 0
private var fromY = 0
private var started = 0L

val isFinished: Boolean get() = target == null && scroller.isFinished
val currX: Int get() = if (aimed) aimX else scroller.currX
val currY: Int get() = if (aimed) aimY else scroller.currY
val currVelocity: Float get() = scroller.currVelocity

/** True between fling() and the next abort() or animateTo(), so only flings light the edges up. */
Expand All @@ -38,24 +48,40 @@ class ScrollController(context: Context, private val view: View) {
}

fun fling(startX: Int, startY: Int, velocityX: Int, velocityY: Int, maxX: Int, maxY: Int) {
abort()
flinging = true
scroller.fling(startX, startY, velocityX, velocityY, 0, maxX, 0, maxY)
view.postInvalidateOnAnimation()
}

fun animateTo(startX: Int, startY: Int, x: Int, y: Int) {
flinging = false
scroller.startScroll(startX, startY, x - startX, y - startY, SCROLL_DURATION_MS)
/** Scrolls vertically to [y], which can move while the scroll runs: wrapped lines take their rows on the way. */
fun animateTo(startX: Int, startY: Int, y: () -> Int) {
abort()
target = y
aimed = true
aimX = startX
aimY = startY
fromY = startY
started = AnimationUtils.currentAnimationTimeMillis()
view.postInvalidateOnAnimation()
}

fun abort() {
flinging = false
scroller.abortAnimation()
target = null
aimed = false
}

/** Advances a running animation. False once it is finished. */
fun step(): Boolean = scroller.computeScrollOffset()
fun step(): Boolean {
val y = target ?: return scroller.computeScrollOffset()
val t = ((AnimationUtils.currentAnimationTimeMillis() - started).toFloat() / SCROLL_DURATION_MS).coerceAtMost(1f)
val eased = 1 - (1 - t) * (1 - t) * (1 - t)
aimY = fromY + ((y() - fromY) * eased).roundToInt()
if (t >= 1f) target = null
return true
}

/** A drag went past an edge by (dx, dy) px with the finger at (x, y). */
fun pull(dx: Float, dy: Float, x: Float, y: Float, width: Int, height: Int) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ class SearchController(
try {
val started = System.nanoTime()
val result = try {
Searcher.find(text, search) { job.cancelled }.matches
Searcher.find(text, search) { job.cancelled }
} catch (e: CancellationException) {
return@Runnable
}
val millis = (System.nanoTime() - started) / 1_000_000
postToMain(Runnable { deliver(job, revision, result, millis) })
postToMain(Runnable { deliver(job, revision, result.matches, result.limited, millis) })
} finally {
Searcher.release(search)
Searcher.releaseText(text)
Expand All @@ -108,8 +108,8 @@ class SearchController(
}
}

private fun deliver(job: Job, revision: Int, result: IntArray, millis: Long) {
if (closed || job.generation != generation || !core.acceptMatches(revision, result)) return
private fun deliver(job: Job, revision: Int, result: IntArray, limited: Boolean, millis: Long) {
if (closed || job.generation != generation || !core.acceptMatches(revision, result, limited)) return
running = null
displayed = result
onResult?.invoke(result.size / 2, millis)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ class VectorRunner(private val case: JSONObject) {
}
}
if (expect.has("result")) assertEquals("result $where", expect.get("result"), lastResult)
if (expect.has("limited")) assertEquals("limited $where", expect.getBoolean("limited"), core.matchLimited)
if (expect.has("brackets")) {
if (expect.isNull("brackets")) assertNull("brackets $where", lastResult)
else {
Expand Down
Loading
Loading