diff --git a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidPdfWorkspaceTest.kt b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidPdfWorkspaceTest.kt index 5de69428..061d0526 100644 --- a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidPdfWorkspaceTest.kt +++ b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidPdfWorkspaceTest.kt @@ -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 @@ -28,8 +32,11 @@ 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 @@ -37,9 +44,11 @@ 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 @@ -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() + 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 { @@ -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) @@ -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 diff --git a/android/app/src/main/kotlin/com/logseq/logseq/AndroidPlatformServices.kt b/android/app/src/main/kotlin/com/logseq/logseq/AndroidPlatformServices.kt index 45ee65e9..0f7d62e2 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/AndroidPlatformServices.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/AndroidPlatformServices.kt @@ -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 @@ -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) diff --git a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/PdfWorkspace.kt b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/PdfWorkspace.kt index 94557243..1bfc9cae 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/PdfWorkspace.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/PdfWorkspace.kt @@ -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 @@ -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 @@ -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() @@ -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(null) } + var openedPdf by remember { mutableStateOf(null) } + val document = openedPdf?.document + val title = payload.optString("title") var error by remember { mutableStateOf(null) } var retry by remember { mutableIntStateOf(0) } var ready by remember { mutableStateOf(false) } @@ -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), @@ -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)) }, @@ -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), @@ -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 @@ -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)) } } } diff --git a/apple/Sources/Logseq/LGPDFWorkspace.swift b/apple/Sources/Logseq/LGPDFWorkspace.swift index 993df493..46489386 100644 --- a/apple/Sources/Logseq/LGPDFWorkspace.swift +++ b/apple/Sources/Logseq/LGPDFWorkspace.swift @@ -40,6 +40,17 @@ private struct LGPDFWorkspace: View { } } +private enum LGPDFControlsLayout { + static let buttonSize: CGFloat = 44 + static let panePadding: CGFloat = 4 + static let headerSpacing: CGFloat = 4 + static let dividerOverlap: CGFloat = 15 + + static func headerWidth(buttons: Int, dividerInset: CGFloat) -> CGFloat { + CGFloat(buttons) * (buttonSize + headerSpacing) + 2 * panePadding + dividerInset + } +} + private struct LGPDFSplitContent: View { let context: LUIAppleExtensionViewContext let payload: [String: Any]? @@ -53,18 +64,20 @@ private struct LGPDFSplitContent: View { let open = payload != nil let fullScreen = open && ((payload?["fullScreen"] as? Bool) ?? (geometry.size.width < 600)) let available = max(1, geometry.size.width - 14) - let minimum = min(CGFloat(240), available * 0.35) + let minimumHeaderWidth = LGPDFControlsLayout.headerWidth(buttons: 2, dividerInset: LGPDFControlsLayout.dividerOverlap) + let minimum = min(240, max(available * 0.35, min(minimumHeaderWidth, available / 2))) let width = min(max(minimum, available * fraction), available - minimum) + let readerWidth = fullScreen ? geometry.size.width : width HStack(spacing: 0) { #if os(iOS) if let payload { - LGPDFReader(payload: payload.merging(["fullScreen": fullScreen]) { _, mode in mode }, send: { value in + LGPDFReader(payload: payload.merging(["fullScreen": fullScreen]) { _, mode in mode }, width: readerWidth, send: { value in var value = value value["assetUuid"] = payload["assetUuid"] value["graphId"] = payload["graphId"] send(value) }) - .frame(width: fullScreen ? geometry.size.width : width) + .frame(width: readerWidth) .accessibilityIdentifier("pdf.reader") LGPDFResizeHandle(onDelta: { delta in let current = min(max(minimum, available * fraction), available - minimum) @@ -79,7 +92,7 @@ private struct LGPDFSplitContent: View { withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { fraction = 0.5 } }) .frame(width: 44, height: geometry.size.height) - .padding(.horizontal, -15) + .padding(.horizontal, -LGPDFControlsLayout.dividerOverlap) .zIndex(1) .opacity(fullScreen ? 0 : 1) .allowsHitTesting(!fullScreen) @@ -194,16 +207,17 @@ final class LGPDFResizeHandleView: UIView { private struct LGPDFReader: UIViewControllerRepresentable { let payload: [String: Any] + let width: CGFloat let send: ([String: Any]) -> Void func makeUIViewController(context: Context) -> LGPDFReaderController { let controller = LGPDFReaderController() controller.send = send - controller.apply(payload) + controller.apply(payload, paneWidth: width) return controller } func updateUIViewController(_ controller: LGPDFReaderController, context: Context) { controller.send = send - controller.apply(payload) + controller.apply(payload, paneWidth: width) } } @@ -295,12 +309,16 @@ final class LGPDFReaderController: UIViewController { private var color = "yellow" private let titleLabel = UILabel() private let status = UILabel() + private let header = UIStackView() + private let toolbar = UIStackView() private let highlightButton = UIButton(type: .system) private let copyButton = UIButton(type: .system) private let copyFeedback = UIStackView() private var copyFeedbackTask: Task? private let deleteButton = UIButton(type: .system) private let colorButton = UIButton(type: .system) + private let shareButton = UIButton(type: .system) + private var isPreparingShare = false private let fullScreenButton = UIButton(type: .system) private var documentTask: Task? private var visitTask: Task? @@ -322,6 +340,9 @@ final class LGPDFReaderController: UIViewController { titleLabel.adjustsFontForContentSizeCategory = true titleLabel.lineBreakMode = .byTruncatingMiddle titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + configure(shareButton, title: "Share PDF", image: "square.and.arrow.up", id: "pdf.share") { [weak self] in + self?.shareDocument() + } configure(fullScreenButton, title: "Full-screen PDF", image: "arrow.up.left.and.arrow.down.right", id: "pdf.toggle-fullscreen") { [weak self] in guard let self else { return } let fullScreen = !(payload["fullScreen"] as? Bool ?? false) @@ -329,10 +350,12 @@ final class LGPDFReaderController: UIViewController { if fullScreen { view.window?.endEditing(true) } send(["action": "set-fullscreen", "fullScreen": fullScreen]) } - let header = UIStackView(arrangedSubviews: [close, titleLabel, fullScreenButton]) + [close, titleLabel, fullScreenButton].forEach(header.addArrangedSubview) header.alignment = .center - header.spacing = 4 - let toolbar = UIStackView() + header.spacing = LGPDFControlsLayout.headerSpacing + header.isLayoutMarginsRelativeArrangement = true + header.insetsLayoutMarginsFromSafeArea = false + header.directionalLayoutMargins = .zero toolbar.alignment = .center toolbar.spacing = 2 configure(highlightButton, title: "Highlight selected text", image: "highlighter", id: "pdf.highlight") { [weak self] in self?.highlightSelection() } @@ -365,7 +388,7 @@ final class LGPDFReaderController: UIViewController { if pdfView.document == nil { identity = ""; apply(payload) } send(["action": "load"]) } - [highlightButton, colorButton, annotations, copyButton, deleteButton, previous, next, retry].forEach(toolbar.addArrangedSubview) + [shareButton, highlightButton, colorButton, annotations, copyButton, deleteButton, previous, next, retry].forEach(toolbar.addArrangedSubview) let scroller = UIScrollView() scroller.showsHorizontalScrollIndicator = false scroller.addSubview(toolbar) @@ -388,8 +411,8 @@ final class LGPDFReaderController: UIViewController { stack.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stack) NSLayoutConstraint.activate([ - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 4), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -4), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: LGPDFControlsLayout.panePadding), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -LGPDFControlsLayout.panePadding), stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), stack.bottomAnchor.constraint(equalTo: view.bottomAnchor), scroller.heightAnchor.constraint(equalToConstant: 44), @@ -448,11 +471,12 @@ final class LGPDFReaderController: UIViewController { if payload["fullScreen"] as? Bool == true { view.window?.endEditing(true) } } - func apply(_ payload: [String: Any]) { + func apply(_ payload: [String: Any], paneWidth: CGFloat? = nil) { self.payload = payload loadViewIfNeeded() titleLabel.text = payload["title"] as? String let fullScreen = payload["fullScreen"] as? Bool ?? false + if let paneWidth { layoutHeader(paneWidth: paneWidth, fullScreen: fullScreen) } fullScreenButton.setImage(UIImage(systemName: fullScreen ? "rectangle.split.2x1" : "arrow.up.left.and.arrow.down.right"), for: .normal) fullScreenButton.accessibilityLabel = fullScreen ? "Show PDF and notes" : "Full-screen PDF" highlights = payload["highlights"] as? [[String: Any]] ?? [] @@ -520,12 +544,24 @@ final class LGPDFReaderController: UIViewController { } } + private func layoutHeader(paneWidth: CGFloat, fullScreen: Bool) { + let dividerInset = fullScreen ? 0 : LGPDFControlsLayout.dividerOverlap + if header.directionalLayoutMargins.trailing != dividerInset { + header.directionalLayoutMargins.trailing = dividerInset + } + let fitsShare = paneWidth >= LGPDFControlsLayout.headerWidth(buttons: 3, dividerInset: dividerInset) + let destination = fitsShare ? header : toolbar + guard shareButton.superview !== destination else { return } + shareButton.removeFromSuperview() + destination.insertArrangedSubview(shareButton, at: fitsShare ? 2 : 0) + } + private func configure(_ button: UIButton, title: String, image: String, id: String, action: @escaping () -> Void) { button.setImage(UIImage(systemName: image), for: .normal) button.accessibilityLabel = title button.accessibilityIdentifier = id - button.widthAnchor.constraint(equalToConstant: 44).isActive = true - button.heightAnchor.constraint(equalToConstant: 44).isActive = true + button.widthAnchor.constraint(equalToConstant: LGPDFControlsLayout.buttonSize).isActive = true + button.heightAnchor.constraint(equalToConstant: LGPDFControlsLayout.buttonSize).isActive = true button.addAction(UIAction { _ in action() }, for: .touchUpInside) } @@ -535,7 +571,53 @@ final class LGPDFReaderController: UIViewController { return button } + private func shareDocument() { + guard !isPreparingShare, presentedViewController == nil, let document = pdfView.document, + let source = document.documentURL else { return } + let title = titleLabel.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let name = title.isEmpty ? source.lastPathComponent : title.replacingOccurrences(of: "/", with: "-") + let filename = name.lowercased().hasSuffix(".pdf") ? name : name + ".pdf" + let directory = URL.temporaryDirectory.appendingPathComponent("logseq-pdf-share-" + UUID().uuidString, isDirectory: true) + let sharedFile = directory.appendingPathComponent(filename) + isPreparingShare = true + shareButton.isEnabled = false + Task { [weak self] in + var presented = false + defer { + if !presented { try? FileManager.default.removeItem(at: directory) } + self?.isPreparingShare = false + self?.updateSelection() + } + do { + try await Self.preparePDFShare(from: source, to: sharedFile) + } catch { + guard let self, pdfView.document === document, viewIfLoaded?.window != nil, + presentedViewController == nil else { return } + let alert = UIAlertController(title: "Unable to Share PDF", message: error.localizedDescription, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + return + } + guard let self, pdfView.document === document, viewIfLoaded?.window != nil, + presentedViewController == nil else { return } + let activity = UIActivityViewController(activityItems: [sharedFile], applicationActivities: nil) + activity.popoverPresentationController?.sourceView = shareButton + activity.popoverPresentationController?.sourceRect = shareButton.bounds + activity.completionWithItemsHandler = { _, _, _, _ in + try? FileManager.default.removeItem(at: directory) + } + present(activity, animated: true) + presented = true + } + } + + @concurrent private static func preparePDFShare(from source: URL, to destination: URL) async throws { + try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: false) + try FileManager.default.copyItem(at: source, to: destination) + } + private func updateSelection() { + shareButton.isEnabled = !isPreparingShare && pdfView.document?.documentURL != nil let selection = pdfView.currentSelection?.string?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !selection.isEmpty { selectedID = nil } highlightButton.isEnabled = !selection.isEmpty diff --git a/apple/Tests/UI/pdf-workspace.swift b/apple/Tests/UI/pdf-workspace.swift index 8088b6b4..0fff26ed 100644 --- a/apple/Tests/UI/pdf-workspace.swift +++ b/apple/Tests/UI/pdf-workspace.swift @@ -78,6 +78,21 @@ import UIKit } throw failure(description) } + func hitTarget(_ identifier: String) throws -> UIButton { + guard let button = views(window).compactMap({ $0 as? UIButton }).first(where: { + $0.accessibilityIdentifier == identifier + }), button.isEnabled, button.bounds.width >= 44, button.bounds.height >= 44 else { + throw failure("\(identifier) must have an enabled 44-point touch target") + } + for x in [CGFloat(2), button.bounds.midX, button.bounds.width - 2] { + let point = button.convert(CGPoint(x: x, y: button.bounds.midY), to: window) + let hitView = window.hitTest(point, with: nil) + guard let hitView, hitView === button || hitView.isDescendant(of: button) else { + throw failure("\(identifier) must receive touches across its width at \(point), got \(String(describing: hitView))") + } + } + return button + } let opening = String(decoding: try JSONSerialization.data(withJSONObject: ["uuid": asset, "title": "Research.pdf", "path": url.path]), as: UTF8.self) for cycle in 0..<3 { @@ -127,7 +142,7 @@ import UIKit guard views(window).first(where: { $0.accessibilityIdentifier == "outliner.block-action.main-note" }) === originalMain else { throw failure("Main must retain its native content while full-screen PDF is open") } - guard let divider = views(window).first(where: { $0.accessibilityIdentifier == "pdf.divider" }), divider.bounds.width >= 44 else { + guard let divider = views(window).compactMap({ $0 as? LGPDFResizeHandleView }).first, divider.bounds.width >= 44 else { throw failure("The split divider needs a real 44-point touch target") } for x in [CGFloat(2), divider.bounds.width - 2] { @@ -148,6 +163,39 @@ import UIKit throw failure("The PDF must occupy the left column and leave main on the right: \(frame)") } guard host.presentedViewController == nil else { throw failure("PDF opening must not present Quick Look or a modal") } + if cycle == 0 { + let narrowPhone = contentFrame.width <= 430 + if narrowPhone { + divider.onDelta(-contentFrame.width) + try await wait("Dragging the divider must reach the narrowest split") { + pdf.bounds.width < beforeResize - 25 + } + _ = try hitTarget("pdf.close") + _ = try hitTarget("pdf.toggle-fullscreen") + } + let share = try hitTarget("pdf.share") + if narrowPhone { + guard share.superview !== fullScreenButton.superview else { + throw failure("Share must move into the toolbar at the narrowest split") + } + } + let currentPage = pdf.currentPage + share.sendActions(for: .touchUpInside) + try await wait("Tapping Share must present the iOS activity sheet") { + host.presentedViewController is UIActivityViewController + } + host.dismiss(animated: false) + try await wait("Dismissing Share must return to the PDF") { host.presentedViewController == nil } + guard pdf.document === documentBeforeResize, pdf.currentPage === currentPage else { + throw failure("Sharing must preserve the open document and reading page") + } + if narrowPhone { + divider.onReset() + try await wait("Widening the split must restore the header Share action") { + abs(pdf.bounds.width - beforeResize) < 1 && share.superview === fullScreenButton.superview + } + } + } guard pdf.gestureRecognizers?.contains(where: { $0 is UIPanGestureRecognizer && $0.allowedTouchTypes == [NSNumber(value: UITouch.TouchType.pencil.rawValue)] }) == true else { throw failure("Pencil text selection needs a direct pencil drag without hijacking finger scrolling") } @@ -226,7 +274,7 @@ import UIKit throw failure("Annotation operations must keep their graph and asset identity") } guard runtime.lastError == nil else { throw failure(runtime.lastError!) } - print("PASS: PDF/main split, Pencil selection gesture, text highlights on normal/rotated/cropped pages, zoom and reopening") + print("PASS: PDF/main split, system sharing, Pencil selection, text highlights on normal/rotated/cropped pages, zoom and reopening") } static func failure(_ message: String) -> NSError {