11package org.qownnotes.mobile.markdown
22
3+ import android.content.ClipboardManager
34import android.content.Context
45import android.graphics.Color
56import android.graphics.text.LineBreaker
@@ -12,14 +13,18 @@ import android.text.Spanned
1213import android.text.TextWatcher
1314import android.text.style.ForegroundColorSpan
1415import android.util.AttributeSet
16+ import android.view.ActionMode
1517import android.view.GestureDetector
1618import android.view.Gravity
19+ import android.view.Menu
20+ import android.view.MenuItem
1721import android.view.MotionEvent
1822import android.view.View
1923import android.view.inputmethod.BaseInputConnection
2024import android.view.inputmethod.EditorInfo
2125import android.view.inputmethod.InputMethodManager
2226import android.widget.OverScroller
27+ import android.widget.Toast
2328import androidx.appcompat.widget.AppCompatEditText
2429import io.noties.markwon.Markwon
2530import io.noties.markwon.editor.MarkwonEditor
@@ -187,6 +192,10 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
187192 // The view hierarchy may only be touched from the thread that created it, which is the thread
188193 // constructing this view.
189194 private val viewThread = Handler (Looper .myLooper() ? : Looper .getMainLooper())
195+ internal var loadLinkTitle: (String ) -> FetchedLink = LinkTitleFetcher ()::fetch
196+ internal var linkTitleTaskExecutor: Executor = linkTitleExecutor
197+ internal var clipboardWebUrlProvider: () -> String? = ::readClipboardWebUrl
198+ private var attachmentGeneration = 0
190199 private val verticalFling = OverScroller (context)
191200 private val flingDetector =
192201 GestureDetector (
@@ -225,6 +234,32 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
225234 */
226235 var onEditBoundary: (() -> Unit )? = null
227236
237+ private val markdownLinkActionModeCallback =
238+ object : ActionMode .Callback {
239+ override fun onCreateActionMode (mode : ActionMode ? , menu : Menu ): Boolean {
240+ if (clipboardWebUrlProvider() != null ) {
241+ menu.add(
242+ Menu .NONE ,
243+ R .id.paste_as_markdown_link,
244+ Menu .NONE ,
245+ R .string.paste_as_markdown_link
246+ ).setShowAsAction(MenuItem .SHOW_AS_ACTION_IF_ROOM )
247+ }
248+ return true
249+ }
250+
251+ override fun onPrepareActionMode (mode : ActionMode ? , menu : Menu ): Boolean = false
252+
253+ override fun onActionItemClicked (mode : ActionMode ? , item : MenuItem ): Boolean {
254+ if (item.itemId != R .id.paste_as_markdown_link) return false
255+ val handled = pasteClipboardUrlAsMarkdownLink()
256+ if (handled) mode?.finish()
257+ return handled
258+ }
259+
260+ override fun onDestroyActionMode (mode : ActionMode ? ) = Unit
261+ }
262+
228263 init {
229264 gravity = Gravity .TOP or Gravity .START
230265 inputType = InputType .TYPE_CLASS_TEXT or InputType .TYPE_TEXT_FLAG_MULTI_LINE or
@@ -247,6 +282,8 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
247282 // The editor fills a Compose surface that already supplies padding and background.
248283 background = null
249284 isVerticalScrollBarEnabled = true
285+ customSelectionActionModeCallback = markdownLinkActionModeCallback
286+ customInsertionActionModeCallback = markdownLinkActionModeCallback
250287 }
251288
252289 /* * Gives the editor input focus and asks the input method to open. */
@@ -326,6 +363,40 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
326363 setSelection(edit.selectionStart)
327364 }
328365
366+ internal fun pasteClipboardUrlAsMarkdownLink (): Boolean {
367+ val url = clipboardWebUrlProvider() ? : return false
368+ val source = text?.toString() ? : return false
369+ val start = minOf(selectionStart, selectionEnd).coerceIn(0 , source.length)
370+ val end = maxOf(selectionStart, selectionEnd).coerceIn(start, source.length)
371+ val expectedAttachmentGeneration = attachmentGeneration
372+ linkTitleTaskExecutor.execute {
373+ val fetched = runCatching { loadLinkTitle(url) }
374+ viewThread.post {
375+ if (
376+ attachmentGeneration != expectedAttachmentGeneration ||
377+ text?.toString() != source
378+ ) {
379+ return @post
380+ }
381+ fetched.onSuccess { link ->
382+ val editable = text ? : return @onSuccess
383+ onEditBoundary?.invoke()
384+ val replacement = markdownLink(link.title, link.url)
385+ editable.replace(start, end, replacement)
386+ setSelection(start + replacement.length)
387+ resetInputMethod()
388+ }.onFailure {
389+ Toast .makeText(
390+ context,
391+ R .string.paste_markdown_link_failed,
392+ Toast .LENGTH_SHORT
393+ ).show()
394+ }
395+ }
396+ }
397+ return true
398+ }
399+
329400 /* *
330401 * Tells the input method to read the editor again, after the text moved underneath whatever it
331402 * was composing.
@@ -348,6 +419,11 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
348419 return super .onTouchEvent(event)
349420 }
350421
422+ override fun onDetachedFromWindow () {
423+ attachmentGeneration++
424+ super .onDetachedFromWindow()
425+ }
426+
351427 override fun computeScroll () {
352428 super .computeScroll()
353429 if (verticalFling.computeScrollOffset()) {
@@ -374,6 +450,14 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
374450 private fun inputMethodManager () =
375451 context.getSystemService(Context .INPUT_METHOD_SERVICE ) as ? InputMethodManager
376452
453+ private fun readClipboardWebUrl (): String? {
454+ val clipboard = context.getSystemService(Context .CLIPBOARD_SERVICE ) as ? ClipboardManager
455+ ? : return null
456+ val clip = clipboard.primaryClip ? : return null
457+ if (clip.itemCount != 1 ) return null
458+ return clip.getItemAt(0 ).text?.toString()?.let (::canonicalSafeWebUrl)
459+ }
460+
377461 private fun reportVerticalScroll () {
378462 onVerticalScrollChanged?.invoke(scrollY, verticalScrollRange())
379463 }
@@ -383,6 +467,10 @@ class MarkdownEditText @JvmOverloads constructor(context: Context, attrs: Attrib
383467 val contentBottom = textLayout.getLineBottom(textLayout.lineCount - 1 )
384468 return (contentBottom + totalPaddingTop + totalPaddingBottom - height).coerceAtLeast(0 )
385469 }
470+
471+ private companion object {
472+ val linkTitleExecutor = Executors .newFixedThreadPool(2 )
473+ }
386474}
387475
388476internal fun replaceChangedRange (target : Editable , before : String , after : String ) {
0 commit comments