Skip to content

Commit f628bef

Browse files
committed
feat: paste clipboard URLs as Markdown links
1 parent 3f212e1 commit f628bef

10 files changed

Lines changed: 325 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
99

1010
### Added
1111

12+
- The Markdown editor's long-press menu can now turn a clipboard web URL into a Markdown link whose
13+
label is fetched from the page title.
1214
- Note view now provides an information dialog with modified time, Markdown size, text statistics,
1315
category, account, synchronization, access, favorite, and remote ID details.
1416

‎markdown-android/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ dependencies {
3030
implementation(libs.okhttp)
3131
implementation(libs.markwon.linkify)
3232
testImplementation(libs.junit)
33+
testImplementation(libs.okhttp.mockwebserver)
3334
androidTestImplementation(libs.androidx.test.ext.junit)
3435
androidTestImplementation(libs.androidx.test.runner)
3536
}

‎markdown-android/src/androidTest/kotlin/org/qownnotes/mobile/markdown/MarkdownEditorInstrumentedTest.kt‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,31 @@ class MarkdownEditorInstrumentedTest {
196196
}
197197
}
198198

199+
@Test
200+
fun clipboardUrlIsReplacedByAFetchedMarkdownLink() {
201+
lateinit var view: MarkdownEditText
202+
203+
instrumentation.runOnMainSync {
204+
view = editor()
205+
view.setText("Read this")
206+
view.setSelection(5, 9)
207+
view.loadLinkTitle = { FetchedLink(it, "Example [page]") }
208+
view.linkTitleTaskExecutor = java.util.concurrent.Executor { it.run() }
209+
view.clipboardWebUrlProvider = { "https://example.com/article" }
210+
211+
assertTrue(view.pasteClipboardUrlAsMarkdownLink())
212+
}
213+
instrumentation.waitForIdleSync()
214+
215+
instrumentation.runOnMainSync {
216+
assertEquals(
217+
"Read [Example \\[page\\]](https://example.com/article)",
218+
view.text.toString()
219+
)
220+
assertEquals(view.length(), view.selectionStart)
221+
}
222+
}
223+
199224
@Test
200225
fun enterRemovesEmptyListAndChecklistMarkers() {
201226
lateinit var listView: MarkdownEditText
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
package org.qownnotes.mobile.markdown
2+
3+
import java.io.IOException
4+
import java.io.InputStream
5+
import java.net.UnknownHostException
6+
import java.nio.charset.StandardCharsets
7+
import java.util.concurrent.TimeUnit
8+
import okhttp3.Dns
9+
import okhttp3.HttpUrl
10+
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
11+
import okhttp3.OkHttpClient
12+
import okhttp3.Request
13+
14+
internal class LinkTitleFetcher(private val client: OkHttpClient = safeLinkTitleClient()) {
15+
fun fetch(rawUrl: String): FetchedLink {
16+
var url = requireSafeWebUrl(rawUrl)
17+
repeat(MAX_LINK_REDIRECTS + 1) { redirectCount ->
18+
client.newCall(
19+
Request.Builder()
20+
.url(url)
21+
.header("Accept", "text/html, application/xhtml+xml")
22+
.get()
23+
.build()
24+
).execute().use { response ->
25+
if (response.isRedirect) {
26+
if (redirectCount == MAX_LINK_REDIRECTS) throw IOException("Too many redirects")
27+
val location = response.header("Location")
28+
?: throw IOException("Redirect has no location")
29+
url = requireSafeWebUrl(url.resolve(location)?.toString().orEmpty())
30+
return@repeat
31+
}
32+
if (!response.isSuccessful) throw IOException("Page request failed")
33+
val body = response.body ?: throw IOException("Page has no content")
34+
val mediaType = body.contentType()
35+
if (mediaType?.let { it.type != "text" || it.subtype !in HTML_SUBTYPES } == true) {
36+
throw IOException("URL does not point to an HTML page")
37+
}
38+
val declaredLength = body.contentLength()
39+
if (declaredLength > MAX_TITLE_DOCUMENT_BYTES) {
40+
throw IOException("Page is too large")
41+
}
42+
val bytes = body.byteStream().use { it.readAtMost(MAX_TITLE_DOCUMENT_BYTES) }
43+
val charset = mediaType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
44+
val title = extractHtmlTitle(bytes.toString(charset))
45+
?: throw IOException("Page has no title")
46+
return FetchedLink(url.toString(), title)
47+
}
48+
}
49+
throw IOException("Redirect failed")
50+
}
51+
}
52+
53+
private fun InputStream.readAtMost(limit: Int): ByteArray {
54+
val output = java.io.ByteArrayOutputStream()
55+
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
56+
var total = 0
57+
while (true) {
58+
val count = read(buffer)
59+
if (count < 0) return output.toByteArray()
60+
total += count
61+
if (total > limit) throw IOException("Page is too large")
62+
output.write(buffer, 0, count)
63+
}
64+
}
65+
66+
internal data class FetchedLink(val url: String, val title: String)
67+
68+
internal fun canonicalSafeWebUrl(raw: String): String? =
69+
runCatching { requireSafeWebUrl(raw).toString() }.getOrNull()
70+
71+
internal fun requireSafeWebUrl(raw: String): HttpUrl {
72+
val url = raw.trim().toHttpUrlOrNull() ?: throw IllegalArgumentException("Invalid web URL")
73+
require(url.scheme == "http" || url.scheme == "https") { "Only web URLs are allowed" }
74+
require(url.host.isNotBlank() && url.username.isEmpty() && url.password.isEmpty()) {
75+
"URL credentials are blocked"
76+
}
77+
return url
78+
}
79+
80+
internal fun extractHtmlTitle(html: String): String? {
81+
val rawTitle = HTML_TITLE.find(html)?.groupValues?.get(1) ?: return null
82+
val decoded = HTML_ENTITY.replace(rawTitle) { match -> decodeHtmlEntity(match.value) }
83+
return decoded.replace(HTML_WHITESPACE, " ").trim().take(MAX_LINK_TITLE_LENGTH)
84+
.takeIf(String::isNotEmpty)
85+
}
86+
87+
internal fun markdownLink(title: String, url: String): String {
88+
val escapedTitle = title
89+
.replace("\\", "\\\\")
90+
.replace("[", "\\[")
91+
.replace("]", "\\]")
92+
return "[$escapedTitle]($url)"
93+
}
94+
95+
private fun decodeHtmlEntity(entity: String): String {
96+
val value = entity.substring(1, entity.length - 1)
97+
val codePoint = when {
98+
value.startsWith("#x", ignoreCase = true) -> value.drop(2).toIntOrNull(16)
99+
value.startsWith('#') -> value.drop(1).toIntOrNull()
100+
else -> HTML_NAMED_ENTITIES[value.lowercase()]
101+
} ?: return entity
102+
return runCatching { String(Character.toChars(codePoint)) }.getOrDefault(entity)
103+
}
104+
105+
private fun safeLinkTitleClient(): OkHttpClient = OkHttpClient.Builder()
106+
.followRedirects(false)
107+
.followSslRedirects(false)
108+
.dns(
109+
object : Dns {
110+
override fun lookup(hostname: String) =
111+
Dns.SYSTEM.lookup(hostname).takeIf { addresses ->
112+
addresses.isNotEmpty() && addresses.all(::isPublicImageAddress)
113+
} ?: throw UnknownHostException("Blocked link host")
114+
}
115+
)
116+
.connectTimeout(8, TimeUnit.SECONDS)
117+
.readTimeout(12, TimeUnit.SECONDS)
118+
.callTimeout(15, TimeUnit.SECONDS)
119+
.build()
120+
121+
private val HTML_TITLE = Regex(
122+
"<title(?:\\s[^>]*)?>([\\s\\S]*?)</title\\s*>",
123+
RegexOption.IGNORE_CASE
124+
)
125+
private val HTML_ENTITY = Regex("&(?:#[xX][0-9a-fA-F]+|#\\d+|[A-Za-z]+);")
126+
private val HTML_WHITESPACE = Regex("\\s+")
127+
private val HTML_SUBTYPES = setOf("html", "xhtml+xml")
128+
private val HTML_NAMED_ENTITIES = mapOf(
129+
"amp" to '&'.code,
130+
"apos" to '\''.code,
131+
"gt" to '>'.code,
132+
"lt" to '<'.code,
133+
"nbsp" to ' '.code,
134+
"quot" to '"'.code
135+
)
136+
private const val MAX_LINK_REDIRECTS = 3
137+
private const val MAX_TITLE_DOCUMENT_BYTES = 512 * 1024
138+
private const val MAX_LINK_TITLE_LENGTH = 512

‎markdown-android/src/main/kotlin/org/qownnotes/mobile/markdown/MarkdownEditor.kt‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.qownnotes.mobile.markdown
22

3+
import android.content.ClipboardManager
34
import android.content.Context
45
import android.graphics.Color
56
import android.graphics.text.LineBreaker
@@ -12,14 +13,18 @@ import android.text.Spanned
1213
import android.text.TextWatcher
1314
import android.text.style.ForegroundColorSpan
1415
import android.util.AttributeSet
16+
import android.view.ActionMode
1517
import android.view.GestureDetector
1618
import android.view.Gravity
19+
import android.view.Menu
20+
import android.view.MenuItem
1721
import android.view.MotionEvent
1822
import android.view.View
1923
import android.view.inputmethod.BaseInputConnection
2024
import android.view.inputmethod.EditorInfo
2125
import android.view.inputmethod.InputMethodManager
2226
import android.widget.OverScroller
27+
import android.widget.Toast
2328
import androidx.appcompat.widget.AppCompatEditText
2429
import io.noties.markwon.Markwon
2530
import 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

388476
internal fun replaceChangedRange(target: Editable, before: String, after: String) {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<resources>
2+
<item name="paste_as_markdown_link" type="id" />
3+
</resources>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
<resources>
22
<string name="encrypted_content_locked">Encrypted content is locked on this device.</string>
3+
<string name="paste_as_markdown_link">Paste as Markdown link</string>
4+
<string name="paste_markdown_link_failed">Could not fetch the page title</string>
35
</resources>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package org.qownnotes.mobile.markdown
2+
3+
import okhttp3.OkHttpClient
4+
import okhttp3.mockwebserver.MockResponse
5+
import okhttp3.mockwebserver.MockWebServer
6+
import org.junit.Assert.assertEquals
7+
import org.junit.Test
8+
9+
class LinkTitleFetcherTest {
10+
@Test
11+
fun fetchesTitleAndUsesTheRedirectDestination() {
12+
MockWebServer().use { server ->
13+
server.enqueue(
14+
MockResponse().setResponseCode(302).addHeader("Location", "/article")
15+
)
16+
server.enqueue(
17+
MockResponse()
18+
.addHeader("Content-Type", "text/html; charset=utf-8")
19+
.setBody("<html><head><title>Example &amp; Notes</title></head></html>")
20+
)
21+
val client = OkHttpClient.Builder()
22+
.followRedirects(false)
23+
.followSslRedirects(false)
24+
.build()
25+
26+
val fetched = LinkTitleFetcher(client).fetch(server.url("/start").toString())
27+
28+
assertEquals(server.url("/article").toString(), fetched.url)
29+
assertEquals("Example & Notes", fetched.title)
30+
assertEquals("/start", server.takeRequest().path)
31+
assertEquals("/article", server.takeRequest().path)
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)