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
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package com.logseq.logseq

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.graphics.Paint
import android.graphics.Bitmap
import android.graphics.pdf.PdfDocument
import android.net.Uri
import android.os.SystemClock
import android.provider.OpenableColumns
import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
Expand All @@ -28,18 +32,23 @@ import androidx.compose.ui.test.printToString
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.pdf.PdfPoint
import androidx.pdf.view.PdfView
import androidx.core.content.IntentCompat
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.intent.IntentCallback
import androidx.test.runner.intent.IntentMonitorRegistry
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage
import com.logseq.logseq.ui.extensions.logseqExtensionRegistry
import com.logseq.logseq.ui.extensions.pdfTextSelectionAvailable
import dev.lui.LuiBackend
import dev.lui.LuiEvent
import java.io.File
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.runBlocking
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
Expand Down Expand Up @@ -73,8 +82,46 @@ class AndroidPdfWorkspaceTest {

@Test fun nativePdfSelectsWithStylusAndLeavesMainVisible() = runNativePdfScenario(compact = false)
@Test fun narrowWindowsOpenPdfFullscreenByDefault() = runNativePdfScenario(compact = true)
@Test fun nativePdfSharesDownloadedFileWithDocumentName() = runNativePdfScenario(compact = true, verifyShare = true)

private fun runNativePdfScenario(compact: Boolean) {
private fun assertPdfShare(file: File) {
val chooser = AtomicReference<Intent>()
val monitor = IntentMonitorRegistry.getInstance()
val callback = IntentCallback { intent ->
if (intent.action == Intent.ACTION_CHOOSER) chooser.set(intent)
}
monitor.addIntentCallback(callback)
try {
ui.onNodeWithTag("pdf.share").assertIsDisplayed().assertIsEnabled().performClick()
ui.waitUntil(5_000) { chooser.get() != null }
val excluded = IntentCompat.getParcelableArrayExtra(chooser.get(), Intent.EXTRA_EXCLUDE_COMPONENTS, ComponentName::class.java)
assertEquals(listOf(ComponentName(instrumentation.targetContext, MainActivity::class.java)), excluded?.toList())
val share = requireNotNull(IntentCompat.getParcelableExtra(chooser.get(), Intent.EXTRA_INTENT, Intent::class.java))
val stream = requireNotNull(IntentCompat.getParcelableExtra(share, Intent.EXTRA_STREAM, Uri::class.java))
assertEquals(Intent.ACTION_SEND, share.action)
assertEquals("application/pdf", share.type)
assertEquals("content", stream.scheme)
assertTrue(share.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0)
assertEquals(0, share.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
assertEquals(stream, share.clipData?.getItemAt(0)?.uri)

val resolver = instrumentation.targetContext.contentResolver
resolver.query(stream, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
assertTrue(cursor.moveToFirst())
assertEquals("Research.pdf", cursor.getString(0))
} ?: throw AssertionError("The shared PDF must expose its document name")
requireNotNull(resolver.openInputStream(stream)).use {
assertArrayEquals(file.readBytes(), it.readBytes())
}
} finally {
monitor.removeIntentCallback(callback)
if (chooser.get() != null) {
instrumentation.uiAutomation.executeShellCommand("input keyevent KEYCODE_BACK").close()
}
}
}

private fun runNativePdfScenario(compact: Boolean, verifyShare: Boolean = false) {
val file = File(instrumentation.targetContext.cacheDir, "native-pdf-test.pdf")
val document = PdfDocument()
try {
Expand All @@ -86,10 +133,16 @@ class AndroidPdfWorkspaceTest {
file.outputStream().use { document.writeTo(it) }
} finally { document.close() }
payload = JSONObject().put("assetUuid", "a9000000-0000-4000-8000-000000000001")
.put("graphId", "pdf-native-test").put("title", "Research.pdf").put("path", file.path)
.put("graphId", "pdf-native-test").put("title", "Research.pdf").put("path", if (verifyShare) "" else file.path)
.put("highlights", JSONArray()).put("page", 1).put("loading", true)
if (!compact) payload.put("fullScreen", false)
backend = LuiBackend(extensions = logseqExtensionRegistry(), onEvent = { event ->
val loadImage: (suspend (String, String) -> String)? = if (verifyShare) {
{ _, assetType ->
assertEquals("pdf", assetType)
file.path
}
} else null
backend = LuiBackend(extensions = logseqExtensionRegistry(loadImage = loadImage), onEvent = { event ->
if (event is LuiEvent.Extension && event.name == "event") {
val command = JSONObject(event.values["payload"] as String)
commands.add(command)
Expand Down Expand Up @@ -127,6 +180,11 @@ class AndroidPdfWorkspaceTest {
instrumentation.runOnMainSync { loaded = pdf()?.pdfToViewPoint(PdfPoint(0, 40f, 90f)) != null }
loaded
}
ui.onNodeWithTag("pdf.share").assertIsDisplayed().assertIsEnabled()
if (verifyShare) {
assertPdfShare(file)
return
}
fun waitForPage(pageIndex: Int) {
ui.waitUntil(10_000) {
var onPage = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.logseq.logseq

import android.content.ClipData
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
Expand Down Expand Up @@ -218,6 +219,25 @@ class AndroidPlatformServices(private val context: Context) {
return start(Intent.createChooser(intent, "Share from Logseq"))
}

internal fun sharePdf(file: File, title: String): Boolean {
if (!file.isFile) return false
val name = title.trim().replace('/', '-').replace('\\', '-').ifBlank { file.name }
val filename = if (name.endsWith(".pdf", ignoreCase = true)) name else "$name.pdf"
val uri = runCatching {
FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file, filename)
}.getOrNull() ?: return false
val intent = Intent(Intent.ACTION_SEND).apply {
type = "application/pdf"
putExtra(Intent.EXTRA_STREAM, uri)
clipData = ClipData.newUri(context.contentResolver, filename, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val chooser = Intent.createChooser(intent, "Share PDF").apply {
putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, arrayOf(ComponentName(context, MainActivity::class.java)))
}
return start(chooser)
}

fun deleteLocalGraph(graphId: String): Boolean {
if (graphId.isBlank() || graphId.contains('/') || graphId.contains("..")) return false
val directory = AndroidGraphLocalStorage.directory(File(context.filesDir, "graphs"), graphId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.FullscreenExit
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
Expand Down Expand Up @@ -50,6 +51,7 @@ import androidx.pdf.compose.rememberPdfViewerState
import androidx.pdf.content.PageSelection
import androidx.pdf.content.PdfPageTextContent
import androidx.pdf.selection.model.TextSelection
import com.logseq.logseq.AndroidPlatformServices
import dev.lui.LuiExtensionContext
import dev.lui.LuiExtensionEventSchema
import dev.lui.LuiExtensionProperty
Expand Down Expand Up @@ -137,7 +139,8 @@ internal fun LuiExtensionRegistry.registerPdfWorkspace(loadAsset: (suspend (Stri
}
Box(Modifier.width(if (payload == null) 0.dp else readerWidth).fillMaxHeight()) {
if (payload != null) key(payload.optString("graphId"), payload.optString("assetUuid")) {
NativePdfReader(payload, loadAsset, fullScreen, ::send)
// Keep the close and fullscreen controls visible in narrow splits.
NativePdfReader(payload, loadAsset, fullScreen, shareInHeader = readerWidth >= 144.dp, send = ::send)
}
}
if (payload != null && !fullScreen) Box(Modifier.offset(x = pdfWidth).width(14.dp).fillMaxHeight()
Expand All @@ -158,20 +161,31 @@ internal fun pdfTextSelectionAvailable(): Boolean =
SdkExtensions.getExtensionVersion(Build.VERSION_CODES.S) >= 13

@OptIn(ExperimentalPdfApi::class)
@Composable private fun NativePdfReader(payload: JSONObject, loadAsset: (suspend (String, String) -> String)?, fullScreen: Boolean, send: (JSONObject) -> Unit) {
private data class OpenedPdf(val document: PdfDocument, val file: File)

@OptIn(ExperimentalPdfApi::class)
@Composable private fun NativePdfReader(
payload: JSONObject,
loadAsset: (suspend (String, String) -> String)?,
fullScreen: Boolean,
shareInHeader: Boolean,
send: (JSONObject) -> Unit,
) {
val context = LocalContext.current
val keyboard = LocalSoftwareKeyboardController.current
val focus = LocalFocusManager.current
LaunchedEffect(fullScreen) { if (fullScreen) { focus.clearFocus(); keyboard?.hide() } }
val scope = rememberCoroutineScope()
val clipboard = LocalClipboard.current
val copyFeedback = remember { SnackbarHostState() }
val feedback = remember { SnackbarHostState() }
val viewer = rememberPdfViewerState()
val textSelectionAvailable = remember { pdfTextSelectionAvailable() }
val latestSend by rememberUpdatedState<(JSONObject) -> Unit>({ value ->
send(value.put("graphId", payload.getString("graphId")).put("assetUuid", payload.getString("assetUuid")))
})
var document by remember { mutableStateOf<PdfDocument?>(null) }
var openedPdf by remember { mutableStateOf<OpenedPdf?>(null) }
val document = openedPdf?.document
val title = payload.optString("title")
var error by remember { mutableStateOf<String?>(null) }
var retry by remember { mutableIntStateOf(0) }
var ready by remember { mutableStateOf(false) }
Expand Down Expand Up @@ -202,11 +216,11 @@ internal fun pdfTextSelectionAvailable(): Boolean =
val descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
opened = try { SandboxedPdfLoader(context, Dispatchers.IO).openDocument(Uri.fromFile(file), descriptor) }
catch (failure: Throwable) { descriptor.close(); throw failure }
document = opened
openedPdf = OpenedPdf(opened, file)
awaitCancellation()
} catch (cancelled: CancellationException) { throw cancelled }
catch (failure: Exception) { error = failure.localizedMessage ?: "Unable to open PDF" }
finally { document = null; opened?.close() }
finally { openedPdf = null; opened?.close() }
}

LaunchedEffect(document, contentLoaded, payload.optBoolean("loading"), payload.optInt("page", 1),
Expand Down Expand Up @@ -304,12 +318,27 @@ internal fun pdfTextSelectionAvailable(): Boolean =
}
}

val shareButton: @Composable () -> Unit = {
IconButton(
enabled = openedPdf != null,
onClick = {
val file = openedPdf?.file ?: return@IconButton
if (!AndroidPlatformServices(context).sharePdf(file, title)) {
scope.launch { feedback.showSnackbar("Unable to share PDF") }
}
},
modifier = Modifier.testTag("pdf.share"),
) {
Icon(Icons.Filled.Share, "Share PDF")
}
}
Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface).statusBarsPadding()) {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { latestSend(JSONObject().put("action", "close")) }, modifier = Modifier.testTag("pdf.close")) {
Icon(Icons.Filled.Close, "Close PDF")
}
Text(payload.optString("title"), modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleSmall)
Text(title, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleSmall)
if (shareInHeader) shareButton()
IconButton(onClick = {
latestSend(JSONObject().put("action", "set-fullscreen").put("fullScreen", !fullScreen))
},
Expand All @@ -319,6 +348,7 @@ internal fun pdfTextSelectionAvailable(): Boolean =
}
}
Row(Modifier.horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.CenterVertically) {
if (!shareInHeader) shareButton()
if (textSelectionAvailable) {
TextButton(onClick = ::save, enabled = ready && !selecting &&
(penSelection != null || (viewer.currentSelection as? TextSelection)?.text?.isNotBlank() == true),
Expand All @@ -337,8 +367,8 @@ internal fun pdfTextSelectionAvailable(): Boolean =
TextButton(onClick = { latestSend(JSONObject().put("action", "open-annotations")) }) { Text("Notes") }
TextButton(enabled = selectedID != null, onClick = { selectedID?.let { id -> scope.launch {
clipboard.setClipEntry(android.content.ClipData.newPlainText("Annotation reference", "[[$id]]").toClipEntry())
copyFeedback.currentSnackbarData?.dismiss()
copyFeedback.showSnackbar("Reference copied", duration = SnackbarDuration.Short)
feedback.currentSnackbarData?.dismiss()
feedback.showSnackbar("Reference copied", duration = SnackbarDuration.Short)
} } }) { Text("Copy reference") }
TextButton(enabled = selectedID != null, onClick = {
latestSend(JSONObject().put("action", "delete").put("id", selectedID)); selectedID = null
Expand Down Expand Up @@ -420,7 +450,7 @@ internal fun pdfTextSelectionAvailable(): Boolean =
if (textSelectionAvailable) item("logseq-highlight", "Highlight", "Highlight selected text") { save() }
},
onFirstContentLoad = { contentLoaded = true })
SnackbarHost(copyFeedback, Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(16.dp))
SnackbarHost(feedback, Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(16.dp))
}
}
}
Expand Down
Loading
Loading