package com.margelo.nitro.codepad import android.graphics.RectF import android.graphics.Typeface import android.view.View import com.facebook.proguard.annotations.DoNotStrip import com.facebook.react.common.assets.ReactFontManager import com.facebook.react.uimanager.ThemedReactContext import com.margelo.nitro.core.Promise import me.sectiontn.codepad.core.ChangeOrigin import me.sectiontn.codepad.core.Decoration import me.sectiontn.codepad.core.Gap import me.sectiontn.codepad.core.LineBackground import me.sectiontn.codepad.core.Underline import me.sectiontn.codepad.core.UnderlineStyle import me.sectiontn.codepad.core.EditorCore import me.sectiontn.codepad.core.EditorSettings import me.sectiontn.codepad.core.SearchQuery import me.sectiontn.codepad.core.TextMovement import me.sectiontn.codepad.input.KeyCommand import me.sectiontn.codepad.view.CodeEditorView import me.sectiontn.codepad.view.GapRect import me.sectiontn.codepad.view.InputMethodBridge import me.sectiontn.codepad.view.ThemeColors import me.sectiontn.codepad.view.TokenStyleColors @DoNotStrip class HybridCodeEditorView(val context: ThemedReactContext) : HybridCodeEditorViewSpec() { private val editor = CodeEditorView(context).apply { // Fonts linked with react-native-asset or expo-font resolve through React Native's font manager. typefaceResolver = { family -> ReactFontManager.getInstance().getTypeface(family, Typeface.NORMAL, context.assets) } // The first draw already has initialValue applied, so ref methods are valid from onReady on. onFirstDraw = { sendReady() } onScrollListener = { f -> onScroll?.invoke(NativeScrollEvent(f.scrollX.toDouble(), f.scrollY.toDouble(), f.contentWidth.toDouble(), f.contentHeight.toDouble())) } onSelectionListener = { s -> onSelectionChange?.invoke(NativeSelection(s.anchor.toDouble(), s.head.toDouble(), core.document.revision.toDouble())) } onContentSizeListener = { w, h -> onContentSizeChange?.invoke(NativeContentSize(w.toDouble(), h.toDouble())) } onChangeListener = { change, origin -> onChange?.invoke(NativeChangeEvent(change.start.toDouble(), change.end.toDouble(), change.inserted, toOrigin(origin), change.revision.toDouble())) onChangeText?.invoke(core.document.text()) } onFocusListener = { focused -> if (focused) onEditorFocus?.invoke() else onEditorBlur?.invoke() } } private var loaded = false private var readySent = false private var fontDirty = false private var settingsDirty = false private var decorationsDirty = false override val view: View = editor // Not mirrored: the document owns the text after the first load and a second copy of a big file is waste. override var initialValue: String? = null set(value) { if (!loaded && value != null) { loaded = true editor.setInitialText(value) // Loading the text clears the decorations, so the current ones go back on in afterUpdate. decorationsDirty = decorations != null decorationsForced = decorationsDirty } } // The wrapper sends "" for an unset string prop, since Nitro rejects the null a removed prop arrives as. override var language: String? = null set(value) { field = value editor.setLanguage(value?.ifEmpty { null }) } override var theme: NativeTheme? = null set(value) { if (value == field) return field = value editor.setTheme(value?.let { toColors(it) } ?: ThemeColors.default) } override var fontFamily: String? = null set(value) { field = value fontDirty = true } override var fontSize: Double? = null set(value) { field = value fontDirty = true } override var lineHeight: Double? = null set(value) { field = value fontDirty = true } override var lineNumbers: Boolean? = null set(value) { field = value editor.setLineNumbers(value ?: true) } override var softWrap: Boolean? = null set(value) { field = value editor.setSoftWrap(value ?: false) } override var readOnly: Boolean? = null set(value) { field = value editor.setReadOnly(value ?: false) } override var highlightActiveLine: Boolean? = null set(value) { field = value editor.setHighlightActiveLine(value ?: true) } override var matchBrackets: Boolean? = null set(value) { field = value editor.setMatchBrackets(value ?: true) } override var placeholder: String? = null set(value) { field = value editor.setPlaceholder(value?.ifEmpty { null }) } override var scrollEnabled: Boolean? = null set(value) { field = value editor.setScrollEnabled(value ?: true) } override var contentInsets: NativeInsets? = null set(value) { if (value == field) return field = value editor.setContentInsets( (value?.top ?: 0.0).toFloat(), (value?.bottom ?: 0.0).toFloat(), (value?.left ?: 0.0).toFloat(), (value?.right ?: 0.0).toFloat(), ) } override var textPadding: Double? = null set(value) { field = value editor.setTextPadding((value ?: 8.0).toFloat()) } override var avoidKeyboard: Boolean? = null set(value) { field = value editor.setAvoidKeyboard(value ?: false) } override var suggestions: NativeSuggestions? = null set(value) { field = value editor.setSuggestions( when (value) { NativeSuggestions.FORCEOFF -> InputMethodBridge.Suggestions.ForceOff NativeSuggestions.ON -> InputMethodBridge.Suggestions.On else -> InputMethodBridge.Suggestions.Off }, ) } override var autoFocus: Boolean? = null set(value) { field = value editor.setAutoFocus(value ?: false) } override var tabSize: Double? = null set(value) { field = value settingsDirty = true } override var insertSpaces: Boolean? = null set(value) { field = value settingsDirty = true } override var autoIndent: Boolean? = null set(value) { field = value settingsDirty = true } override var autoCloseBrackets: Boolean? = null set(value) { field = value settingsDirty = true } override var onReady: (() -> Unit)? = null override var onScroll: ((NativeScrollEvent) -> Unit)? = null override var onSelectionChange: ((NativeSelection) -> Unit)? = null override var onChange: ((NativeChangeEvent) -> Unit)? = null override var onChangeText: ((String) -> Unit)? = null override var onEditorFocus: (() -> Unit)? = null override var onEditorBlur: (() -> Unit)? = null override var onContentSizeChange: ((NativeContentSize) -> Unit)? = null override fun onDropView() = editor.close() override fun afterUpdate() { if (fontDirty) { fontDirty = false editor.setFont(fontFamily?.ifEmpty { null }, (fontSize ?: 14.0).toFloat(), (lineHeight ?: 1.4).toFloat()) } if (settingsDirty) { settingsDirty = false editor.setEditorSettings(EditorSettings((tabSize ?: 4.0).toInt(), insertSpaces ?: true, autoIndent ?: true, autoCloseBrackets ?: true)) } if (decorationsDirty) { decorationsDirty = false val revision = (decorationsRevision ?: -1.0).toInt() if (decorationsGate.admit(decorations, revision, force = decorationsForced)) { editor.setDecorations(decorations?.mapNotNull(::toDecoration) ?: emptyList(), revision) } decorationsForced = false } } private val decorationsGate = DecorationsGate() private var decorationsForced = false override var decorations: Array? = null set(value) { field = value decorationsDirty = true } override var decorationsRevision: Double? = null set(value) { field = value decorationsDirty = true } override var onGapLayout: ((gaps: Array) -> Unit)? = null set(value) { field = value editor.onGapLayoutListener = value?.let { cb -> { gaps -> cb(gaps.map(::toNativeGap).toTypedArray()) } } } override fun getGapRect(line: Double): NativeRect? = editor.gapRect(line.toInt())?.let(::toNativeRect) private fun toNativeRect(r: RectF): NativeRect = NativeRect(r.left.toDouble(), r.top.toDouble(), r.width().toDouble(), r.height().toDouble()) private fun toNativeGap(g: GapRect): NativeGap = NativeGap(g.line.toDouble(), toNativeRect(g.rect)) // An item whose color does not parse is dropped, like an empty range. private fun toDecoration(d: NativeDecoration): Decoration? = when (d.kind) { NativeDecorationKind.UNDERLINE -> ThemeColors.parseColorOrNull(d.color)?.let { val style = if (d.style == NativeUnderlineStyle.WAVY) UnderlineStyle.Wavy else UnderlineStyle.Solid Underline(d.start.toInt(), d.end.toInt(), it, style, d.thickness.toFloat(), d.offset.toFloat()) } NativeDecorationKind.GAP -> Gap(d.line.toInt(), d.rows.toInt()) NativeDecorationKind.LINEBACKGROUND -> ThemeColors.parseColorOrNull(d.color)?.let { LineBackground(d.line.toInt(), it) } } private fun sendReady() { if (readySent) return readySent = true onReady?.invoke() } override fun getText(): String = editor.core.let { c -> c.read { c.document.text() } } override fun getLength(): Double = editor.core.let { c -> c.read { c.document.length.toDouble() } } override fun getLineCount(): Double = editor.core.let { c -> c.read { c.document.lineCount.toDouble() } } override fun getLine(index: Double): String = editor.core.let { c -> c.read { c.document.line(index.toInt()).toString() } } override fun getRevision(): Double = editor.core.let { c -> c.read { c.document.revision.toDouble() } } override fun getSelection(): NativeSelection = editor.core.let { c -> c.read { val s = c.selection NativeSelection(s.anchor.toDouble(), s.head.toDouble(), c.document.revision.toDouble()) } } override fun getTextInRange(start: Double, end: Double): String = editor.core.let { c -> c.read { c.document.text(start.toInt(), end.toInt()) } } override fun offsetToPosition(offset: Double): NativePosition = editor.core.let { c -> c.read { val p = c.document.offsetToPosition(offset.toInt()) NativePosition(p.line.toDouble(), p.column.toDouble()) } } override fun positionToOffset(line: Double, column: Double): Double = editor.core.let { c -> c.read { c.document.positionToOffset(line.toInt(), column.toInt()).toDouble() } } // Both read the frame the main thread published after its last draw. override fun getCursorRect(): NativeRect? = editor.frame.caret?.let { NativeRect(it.left.toDouble(), it.top.toDouble(), it.width().toDouble(), it.height().toDouble()) } override fun getVisibleLines(): NativeVisibleLines = editor.frame.let { NativeVisibleLines(it.firstLine.toDouble(), it.lastLine.toDouble()) } override fun isFocused(): Boolean = editor.focused // Stack size reads without the lock, a benign race like selection. override fun canUndo(): Boolean = editor.core.canUndo override fun canRedo(): Boolean = editor.core.canRedo override fun setText(text: String, keepHistory: Boolean): Promise = onMain { editor.setText(text, keepHistory) } override fun setSelection(anchor: Double, head: Double): Promise = onMain { editor.core.setSelection(anchor.toInt(), head.toInt()) } override fun selectAll(): Promise = onMain { editor.selectAll() } override fun scrollToLine(line: Double, animated: Boolean): Promise = onMain { editor.scrollToLine(line.toInt(), animated) } override fun revealSelection(): Promise = onMain { editor.revealSelection() } override fun insertText(text: String): Promise = onMain { editor.core.insertText(text) } override fun replaceRange(start: Double, end: Double, text: String): Promise = onMain { editor.core.replace(start.toInt(), end.toInt(), text) } override fun undo(): Promise = onMain { editor.undo() } override fun redo(): Promise = onMain { editor.redo() } override fun indent(): Promise = onMain { editor.core.indent() } override fun outdent(): Promise = onMain { editor.core.outdent() } override fun cut(): Promise = onMain { editor.cut(ChangeOrigin.Api) } override fun copy(): Promise = onMain { editor.copy() } override fun paste(): Promise = onMain { editor.paste(ChangeOrigin.Api) } override fun setSearch(query: NativeSearchQuery): Promise = deferred { promise -> editor.setSearch(SearchQuery(query.text, query.regex, query.caseSensitive, query.wholeWord)) editor.whenSearchFresh { promise.resolve(NativeSearchResult(editor.matchCount.toDouble(), editor.matchLimited)) } } override fun findNext(): Promise = deferred { promise -> editor.whenSearchFresh { promise.resolve(toHit(editor.findNext())) } } override fun findPrevious(): Promise = deferred { promise -> editor.whenSearchFresh { promise.resolve(toHit(editor.findPrevious())) } } override fun replaceCurrent(text: String): Promise = deferred { promise -> editor.whenSearchFresh { promise.resolve(editor.replaceCurrent(text)) } } override fun replaceAll(text: String): Promise = deferred { promise -> editor.whenSearchFresh { promise.resolve(editor.replaceAll(text).toDouble()) } } override fun clearSearch(): Promise = onMain { editor.clearSearch() } override fun moveCaret(direction: NativeCaretDirection, select: Boolean): Promise = onMain { editor.perform(toCommand(direction, select)) } override fun typeText(text: String): Promise = onMain { editor.typeText(text) } override fun deleteBackward(): Promise = onMain { editor.perform(KeyCommand.Backspace) } override fun deleteForward(): Promise = onMain { editor.perform(KeyCommand.Delete) } private fun toCommand(direction: NativeCaretDirection, select: Boolean): KeyCommand = when (direction) { NativeCaretDirection.LEFT -> KeyCommand.Move(TextMovement.Unit.Char, false, select) NativeCaretDirection.RIGHT -> KeyCommand.Move(TextMovement.Unit.Char, true, select) NativeCaretDirection.WORDLEFT -> KeyCommand.Move(TextMovement.Unit.Word, false, select) NativeCaretDirection.WORDRIGHT -> KeyCommand.Move(TextMovement.Unit.Word, true, select) NativeCaretDirection.LINESTART -> KeyCommand.Move(TextMovement.Unit.LineStart, false, select) NativeCaretDirection.LINEEND -> KeyCommand.Move(TextMovement.Unit.LineEnd, true, select) NativeCaretDirection.DOCUMENTSTART -> KeyCommand.Move(TextMovement.Unit.DocStart, false, select) NativeCaretDirection.DOCUMENTEND -> KeyCommand.Move(TextMovement.Unit.DocEnd, true, select) NativeCaretDirection.UP -> KeyCommand.Vertical(-1, false, select) NativeCaretDirection.DOWN -> KeyCommand.Vertical(1, false, select) NativeCaretDirection.PAGEUP -> KeyCommand.Vertical(-1, true, select) NativeCaretDirection.PAGEDOWN -> KeyCommand.Vertical(1, true, select) } private fun toHit(hit: EditorCore.SearchHit?): NativeSearchHit = NativeSearchHit(hit?.index?.toDouble() ?: -1.0, hit?.total?.toDouble() ?: 0.0) /** Runs [block] on the main thread with the promise it must settle; a thrown exception rejects it. */ private fun deferred(block: (Promise) -> Unit): Promise { val promise = Promise() editor.runOnMain { try { block(promise) } catch (e: IllegalArgumentException) { promise.reject(ApiError(e.message ?: "invalid argument")) } catch (e: Exception) { promise.reject(e) } } return promise } /** Crosses to JS as its bare message: fbjni appends the Java stack and class name to any other throwable. */ private class ApiError(message: String) : RuntimeException(message, null, false, false) { override fun toString(): String = message ?: "" } override fun focus(): Promise = onMain { editor.focus() } override fun blur(): Promise = onMain { editor.blur() } private fun toOrigin(origin: ChangeOrigin): NativeChangeOrigin = when (origin) { ChangeOrigin.Input -> NativeChangeOrigin.INPUT ChangeOrigin.Api -> NativeChangeOrigin.API ChangeOrigin.Undo -> NativeChangeOrigin.UNDO ChangeOrigin.Redo -> NativeChangeOrigin.REDO } /** Write methods run on the main thread and resolve once the change is applied and a redraw is queued. */ private fun onMain(block: () -> Unit): Promise = deferred { promise -> block() editor.invalidate() promise.resolve(Unit) } private fun toColors(t: NativeTheme): ThemeColors = ThemeColors( background = ThemeColors.parseColor(t.background), foreground = ThemeColors.parseColor(t.foreground), gutterBackground = ThemeColors.parseColor(t.gutterBackground), gutterForeground = ThemeColors.parseColor(t.gutterForeground), gutterActiveForeground = ThemeColors.parseColor(t.gutterActiveForeground), activeLine = ThemeColors.parseColor(t.activeLine), selection = ThemeColors.parseColor(t.selection), cursor = ThemeColors.parseColor(t.cursor), matchingBracket = ThemeColors.parseColor(t.matchingBracket), searchMatch = ThemeColors.parseColor(t.searchMatch), searchMatchActive = ThemeColors.parseColor(t.searchMatchActive), tokens = t.tokens.mapValues { (_, s) -> TokenStyleColors(ThemeColors.parseColor(s.color), s.bold, s.italic) }, ) }