diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift index 555ff9d429..508606e124 100644 --- a/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift +++ b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift @@ -3,6 +3,7 @@ import SimpleXChat import Ink private let MAX_MARKDOWN_VIEW_SIZE: Int64 = 1_048_576 +private let MAX_MARKDOWN_COPY_SIZE: Int64 = 131_072 private let MAX_MARKDOWN_LINE_LENGTH = 15_000 private let MAX_MARKDOWN_NESTING = 16 private let MAX_MARKDOWN_LINK_NESTING = 4 @@ -27,7 +28,7 @@ func showMarkdownFile(_ file: CIFile) { let hasBidiControls = text.unicodeScalars.contains(where: isBidiControl) await MainActor.run { showAppSheet { - MarkdownFileView(file: file, fileSource: fileSource, lines: shownLines, html: html, hasBidiControls: hasBidiControls) + MarkdownFileView(file: file, fileSource: fileSource, text: text, lines: shownLines, html: html, hasBidiControls: hasBidiControls) } } } catch { @@ -166,10 +167,31 @@ private func openMarkdownFileLink(_ url: URL) { } } +func copyMarkdownFile(_ file: CIFile, _ text: String) { + if file.fileSize > MAX_MARKDOWN_COPY_SIZE { + showAlert( + NSLocalizedString("File too large", comment: "alert title"), + message: String.localizedStringWithFormat( + NSLocalizedString("Your file is %@. Do you want to copy it?", comment: "alert message"), + ByteCountFormatter.string(fromByteCount: file.fileSize, countStyle: .binary) + ), + actions: {[ + cancelAlertAction, + UIAlertAction(title: NSLocalizedString("Copy", comment: "alert button"), style: .default) { _ in + UIPasteboard.general.string = text + } + ]} + ) + } else { + UIPasteboard.general.string = text + } +} + struct MarkdownFileView: View { @AppStorage(DEFAULT_MARKDOWN_FILE_TEXT_VIEW) private var textView = false let file: CIFile let fileSource: CryptoFile + let text: String let lines: [String] let html: String? let hasBidiControls: Bool @@ -203,6 +225,11 @@ struct MarkdownFileView: View { .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItemGroup(placement: .navigationBarTrailing) { + Button { + copyMarkdownFile(file, text) + } label: { + Image(systemName: "doc.on.doc") + } if html != nil { Button { textView.toggle() @@ -221,3 +248,17 @@ struct MarkdownFileView: View { .navigationViewStyle(.stack) } } + +struct MarkdownFileView_Previews: PreviewProvider { + static var previews: some View { + let text = "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n" + MarkdownFileView( + file: CIFile.getSample(fileName: "notes.md", fileSize: Int64(text.utf8.count), filePath: "notes.md"), + fileSource: CryptoFile.plain("notes.md"), + text: text, + lines: text.components(separatedBy: "\n"), + html: nil, + hasBidiControls: false + ) + } +} diff --git a/apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png b/apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png new file mode 100644 index 0000000000..a9969a1186 Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png differ diff --git a/apps/ios/SimpleX Snapshots/References/MarkdownFileView-light-large.png b/apps/ios/SimpleX Snapshots/References/MarkdownFileView-light-large.png new file mode 100644 index 0000000000..e0ce6284ae Binary files /dev/null and b/apps/ios/SimpleX Snapshots/References/MarkdownFileView-light-large.png differ diff --git a/apps/ios/SimpleX Snapshots/SnapshotTests.swift b/apps/ios/SimpleX Snapshots/SnapshotTests.swift index fc47a3a336..a3ccd35cdc 100644 --- a/apps/ios/SimpleX Snapshots/SnapshotTests.swift +++ b/apps/ios/SimpleX Snapshots/SnapshotTests.swift @@ -728,6 +728,7 @@ private func previewScenes() -> [SnapshotScene] { SnapshotScene(IntegrityErrorItemView_Previews.self, allSizes: true), SnapshotScene(LargeLinkPreview_Previews.self, allSizes: true), SnapshotScene(LocalAuthView_Previews.self), + SnapshotScene(MarkdownFileView_Previews.self, device: true), SnapshotScene(MarkdownHelp_Previews.self), SnapshotScene(MarkedDeletedItemView_Previews.self, allSizes: true), SnapshotScene(MemberAdmissionView_Previews.self), diff --git a/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift b/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift new file mode 100644 index 0000000000..92e931f3e5 --- /dev/null +++ b/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift @@ -0,0 +1,26 @@ +import XCTest +import UIKit +@testable import SimpleX +@testable import SimpleXChat + +final class MarkdownFileTests: XCTestCase { + @MainActor + func testCopyAsksAbove128KB() async throws { + let text = "alpha\n\ngamma" + UIPasteboard.general.string = "unchanged" + copyMarkdownFile(CIFile.getSample(fileSize: 131_072), text) + XCTAssertEqual(UIPasteboard.general.string, text) + UIPasteboard.general.string = "unchanged" + copyMarkdownFile(CIFile.getSample(fileSize: 131_073), text) + try await waitFor { (getTopViewController() as? UIAlertController)?.isBeingPresented == false } + let alert = try XCTUnwrap(getTopViewController() as? UIAlertController) + XCTAssertEqual(alert.title, "File too large") + XCTAssertEqual(alert.message, "Your file is 128 KB. Do you want to copy it?") + XCTAssertEqual(UIPasteboard.general.string, "unchanged") + let copy = try XCTUnwrap(alert.actions.first { $0.title == "Copy" }) + let handler = unsafeBitCast(copy.value(forKey: "handler") as AnyObject, to: (@convention(block) (UIAlertAction) -> Void).self) + await withCheckedContinuation { done in alert.dismiss(animated: false) { done.resume() } } + handler(copy) + XCTAssertEqual(UIPasteboard.general.string, text) + } +} diff --git a/apps/ios/SimpleX.xcodeproj/project.pbxproj b/apps/ios/SimpleX.xcodeproj/project.pbxproj index 530bc4c124..3242c7ea27 100644 --- a/apps/ios/SimpleX.xcodeproj/project.pbxproj +++ b/apps/ios/SimpleX.xcodeproj/project.pbxproj @@ -272,6 +272,7 @@ E5AEC0C22F9C000100270665 /* SnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0C12F9C000100270665 /* SnapshotTests.swift */; }; 4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000005 /* NameAlertsTests.swift */; }; 4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */; }; + 6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */; }; E5AEC0AF2F91A73500270665 /* ComposeChatLinkView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */; }; E5C0BBE82F82B45500EA7527 /* SimpleXAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */; }; E5C0BBEB2F82B45500EA7527 /* SharedAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBEA2F82B45500EA7527 /* SharedAssets.xcassets */; }; @@ -684,6 +685,7 @@ E5AEC0C32F9C000100270665 /* SimpleX Snapshots.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Snapshots.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 4E57A1E70000000000000005 /* NameAlertsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NameAlertsTests.swift; sourceTree = ""; }; 4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatItemUpdateTests.swift; sourceTree = ""; }; + 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownFileTests.swift; sourceTree = ""; }; 4E57A1E70000000000000007 /* SimpleX Unit Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeChatLinkView.swift; sourceTree = ""; }; E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = SimpleXAssets.xcassets; sourceTree = ""; }; @@ -1038,6 +1040,7 @@ children = ( 4E57A1E70000000000000005 /* NameAlertsTests.swift */, 4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */, + 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */, ); path = "SimpleX Unit Tests"; sourceTree = ""; @@ -1926,6 +1929,7 @@ files = ( 4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */, 4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */, + 6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt index a763e47d43..7681120144 100644 --- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt +++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt @@ -1,18 +1,22 @@ package chat.simplex.common.views.chat.item import SectionBottomSpacer +import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.* import androidx.compose.runtime.* +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter +import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.UriHandler +import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString @@ -25,6 +29,7 @@ import chat.simplex.common.model.* import chat.simplex.common.model.ChatController.appPrefs import chat.simplex.common.platform.* import chat.simplex.common.ui.theme.DEFAULT_PADDING +import chat.simplex.common.ui.theme.SimpleXTheme import chat.simplex.common.ui.theme.WarningOrange import chat.simplex.common.views.chat.topPaddingToContent import chat.simplex.common.views.helpers.* @@ -41,6 +46,7 @@ import dev.icerock.moko.resources.compose.painterResource import dev.icerock.moko.resources.compose.stringResource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode @@ -56,6 +62,8 @@ import java.util.Base64 private const val DATA_IMAGE = "data:image/" private val IMAGE_TYPES = listOf(ImageFileType.JPEG, ImageFileType.PNG) private const val MAX_MARKDOWN_VIEW_SIZE: Long = 1_048_576 +private const val MAX_MARKDOWN_COPY_SIZE = 131_072 +private const val MAX_ANDROID_COPY_SIZE = 524_288 private const val MAX_MARKDOWN_LINE_LENGTH = 15_000 private const val MAX_MARKDOWN_DEPTH = 32 private const val MAX_MARKDOWN_TABLE_ROWS = 200 @@ -67,7 +75,9 @@ private val bidiControlChar = Regex("[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u206 private val invisibleCharMarkerStyle = SpanStyle(color = WarningOrange) -private class MarkdownDocument(val lines: List, val formatted: State.Success?, val hasBidiControls: Boolean) +internal class MarkdownLine(val text: String, val lineBreak: Boolean) + +internal class MarkdownDocument(val text: String, val lines: List, val formatted: State.Success?, val hasBidiControls: Boolean) fun isMarkdownFile(file: CIFile): Boolean = file.fileSize <= MAX_MARKDOWN_VIEW_SIZE && file.fileName.substringAfterLast('.', "").lowercase() in listOf("md", "markdown") @@ -90,26 +100,31 @@ fun showMarkdownFile(file: CIFile) { AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error), e.message) return@withLongRunningApi } - val text = decodedText(bytes) - val lines = text.lines() - val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null - val document = MarkdownDocument( - lines.flatMap { line -> line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") } }, - formatted, - bidiControlChar.containsMatchIn(text) - ) + val document = markdownDocument(bytes) withContext(Dispatchers.Main) { if (appPlatform.isDesktop && ModalManager.center.isTopModalOpen(ModalViewId.MARKDOWN_FILE)) ModalManager.center.closeModal() - ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = { - if (formatted != null) MarkdownViewSwitch() - MarkdownFileSaveButton(file, bytes) - }) { + ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = { MarkdownFileButtons(file, bytes, document) }) { key(this) { MarkdownFileView(file.fileName, document) } } } } } +internal suspend fun markdownDocument(bytes: ByteArray): MarkdownDocument { + val text = decodedText(bytes) + val lines = text.lines() + val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null + return MarkdownDocument( + text, + lines.flatMapIndexed { i, line -> + val chunks = line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") } + chunks.mapIndexed { j, chunk -> MarkdownLine(chunk, lineBreak = i < lines.lastIndex && j == chunks.lastIndex) } + }, + formatted, + bidiControlChar.containsMatchIn(text) + ) +} + private fun decodedText(bytes: ByteArray): String = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) @@ -145,6 +160,39 @@ private fun MarkdownViewSwitch() { } } +@Composable +private fun MarkdownFileButtons(file: CIFile, bytes: ByteArray, document: MarkdownDocument) { + MarkdownFileCopyButton(document.text, bytes.size, if (appPlatform.isAndroid) MAX_ANDROID_COPY_SIZE else null) + if (document.formatted != null) MarkdownViewSwitch() + MarkdownFileSaveButton(file, bytes) +} + +@Composable +internal fun MarkdownFileCopyButton(text: String, fileSize: Int, maxSize: Int?) { + val clipboard = LocalClipboardManager.current + IconButton({ + val copy = { + clipboard.setText(AnnotatedString(text)) + showToast(generalGetString(MR.strings.copied)) + } + when { + maxSize != null && fileSize > maxSize -> AlertManager.shared.showAlertMsg( + generalGetString(MR.strings.markdown_file_too_large), + String.format(generalGetString(MR.strings.markdown_file_copy_limit), formatBytes(maxSize.toLong())) + ) + fileSize > MAX_MARKDOWN_COPY_SIZE -> AlertManager.shared.showAlertDialog( + title = generalGetString(MR.strings.markdown_file_too_large), + text = String.format(generalGetString(MR.strings.markdown_file_copy_large), formatBytes(fileSize.toLong())), + confirmText = generalGetString(MR.strings.copy_verb), + onConfirm = copy + ) + else -> copy() + } + }) { + Icon(painterResource(MR.images.ic_content_copy), stringResource(MR.strings.copy_verb), tint = MaterialTheme.colors.primary) + } +} + @Composable private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) { val saveFileLauncher = rememberFileChooserLauncher(false, bytes) { to: URI? -> @@ -156,14 +204,17 @@ private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) { } @Composable -private fun MarkdownFileView(fileName: String, document: MarkdownDocument) { +internal fun MarkdownFileView(fileName: String, document: MarkdownDocument) { val textView = remember { appPrefs.markdownFileTextView.state } val formatted = document.formatted if (textView.value || formatted == null) { SelectionContainer { MarkdownFileColumn(fileName, document.hasBidiControls) { items(document.lines) { line -> - Text(remember(line) { withInvisibleCharMarkers(line) }, Modifier.padding(horizontal = DEFAULT_PADDING), fontFamily = FontFamily.Monospace) + Box(Modifier.padding(horizontal = DEFAULT_PADDING)) { + Text(remember(line) { withInvisibleCharMarkers(line.text) }, fontFamily = FontFamily.Monospace) + if (line.lineBreak) SelectableLineBreak() + } } } } @@ -172,6 +223,11 @@ private fun MarkdownFileView(fileName: String, document: MarkdownDocument) { } } +@Composable +private fun BoxScope.SelectableLineBreak() { + Text("\n", Modifier.align(Alignment.BottomEnd).height(1.dp).clearAndSetSemantics {}) +} + private fun withInvisibleCharMarkers(line: String): AnnotatedString = buildAnnotatedString { var start = 0 invisibleChar.findAll(line).forEach { @@ -294,3 +350,15 @@ private fun hasImageSignature(base64: String): Boolean { val header = runCatching { Base64.getDecoder().decode(base64.take(12)) }.getOrNull() ?: return false return IMAGE_TYPES.any { it.matches(header) } } + +@Preview +@Composable +fun PreviewMarkdownFileView() { + val bytes = remember { "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n".encodeToByteArray() } + val document = remember { runBlocking { markdownDocument(bytes) } } + SimpleXTheme { + ModalView(close = {}, endButtons = { MarkdownFileButtons(CIFile.getSample(fileName = "notes.md"), bytes, document) }) { + MarkdownFileView("notes.md", document) + } + } +} diff --git a/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml b/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml index af5b3a089d..27cf5f7f17 100644 --- a/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml +++ b/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml @@ -721,6 +721,9 @@ Formatted view Text view This file has text direction characters. The text can be shown in a different order than it is written. + File too large + Only files up to %s can be copied. Save the file to open it in another app. + Your file is %s. Do you want to copy it? Loading the file Please, wait while the file is being loaded from the linked mobile File error diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt new file mode 100644 index 0000000000..14bb297d90 --- /dev/null +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt @@ -0,0 +1,134 @@ +package chat.simplex.app + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.Clipboard +import androidx.compose.ui.platform.ClipboardManager +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.NativeClipboard +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.runComposeUiTest +import androidx.compose.ui.text.AnnotatedString +import chat.simplex.common.model.ChatController.appPrefs +import chat.simplex.common.simplexWindowState +import chat.simplex.common.views.chat.item.MarkdownFileCopyButton +import chat.simplex.common.views.chat.item.MarkdownFileView +import chat.simplex.common.views.chat.item.markdownDocument +import chat.simplex.common.views.helpers.AlertManager +import chat.simplex.common.views.helpers.LocalAppBarHandler +import chat.simplex.common.views.helpers.rememberAppBarHandler +import kotlinx.coroutines.runBlocking +import java.awt.datatransfer.DataFlavor +import java.awt.datatransfer.Transferable +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +@OptIn(ExperimentalTestApi::class) +class MarkdownFileViewTest { + @Test + fun copiedSelectionKeepsLineBreaks() = runComposeUiTest { + val textView = appPrefs.markdownFileTextView.get() + appPrefs.markdownFileTextView.set(true) + try { + val clipboard = RecordingClipboard() + val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) } + setContent { + CompositionLocalProvider(LocalClipboard provides clipboard, LocalAppBarHandler provides rememberAppBarHandler()) { + MarkdownFileView("test.md", document) + } + } + val first = onNodeWithText("alpha").fetchSemanticsNode().boundsInRoot + val last = onNodeWithText("gamma").fetchSemanticsNode().boundsInRoot + onRoot().performMouseInput { + moveTo(Offset(first.left + 1f, first.center.y)) + press() + moveTo(Offset(last.right + 10f, last.center.y)) + release() + } + onRoot().performKeyInput { pressKey(Key.Copy) } + waitForIdle() + assertEquals("alpha\n\ngamma", clipboard.text) + } finally { + appPrefs.markdownFileTextView.set(textView) + } + } + + @Test + fun copyButtonWarnsAbove128KB() = runComposeUiTest { + var copied: String? = null + val clipboard = object : ClipboardManager { + override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text } + override fun getText(): AnnotatedString? = null + } + val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) } + var fileSize by mutableStateOf(131_072) + try { + setContent { + CompositionLocalProvider(LocalClipboardManager provides clipboard) { + MarkdownFileCopyButton(document.text, fileSize, null) + } + AlertManager.shared.showInView() + } + onNodeWithContentDescription("Copy").performClick() + assertEquals("alpha\n\ngamma", copied) + copied = null + fileSize = 131_073 + onNodeWithContentDescription("Copy").performClick() + onNodeWithText("Your file is 128 KB. Do you want to copy it?").assertExists() + assertNull(copied) + onNodeWithText("Copy").performClick() + assertEquals("alpha\n\ngamma", copied) + } finally { + AlertManager.shared.hideAllAlerts() + simplexWindowState.toasts.clear() + } + } + + @Test + fun copyButtonRefusesAboveHardLimit() = runComposeUiTest { + var copied: String? = null + val clipboard = object : ClipboardManager { + override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text } + override fun getText(): AnnotatedString? = null + } + try { + setContent { + CompositionLocalProvider(LocalClipboardManager provides clipboard) { + MarkdownFileCopyButton("alpha", 524_289, 524_288) + } + AlertManager.shared.showInView() + } + onNodeWithContentDescription("Copy").performClick() + onNodeWithText("Only files up to 512 KB can be copied. Save the file to open it in another app.").assertExists() + assertNull(copied) + } finally { + AlertManager.shared.hideAllAlerts() + } + } +} + +private class RecordingClipboard : Clipboard { + var text: String? = null + + override suspend fun getClipEntry(): ClipEntry? = null + + override suspend fun setClipEntry(clipEntry: ClipEntry?) { + text = (clipEntry?.nativeClipEntry as Transferable).getTransferData(DataFlavor.stringFlavor) as String + } + + override val nativeClipboard: NativeClipboard get() = this +} diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt index 69c657e2a7..1d4f9c7167 100644 --- a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt +++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt @@ -99,6 +99,7 @@ private val previewScenes = listOf( SnapshotScene("DeletedItemView.PreviewDeletedItemView", chatItemFontScales) { PreviewDeletedItemView() }, SnapshotScene("IntegrityErrorItemView.IntegrityErrorItemViewPreview", chatItemFontScales) { IntegrityErrorItemViewPreview() }, SnapshotScene("MarkedDeletedItemView.PreviewMarkedDeletedItemView", chatItemFontScales) { PreviewMarkedDeletedItemView() }, + SnapshotScene("MarkdownFileView.PreviewMarkdownFileView") { PreviewMarkdownFileView() }, SnapshotScene("ChatHelpView.PreviewChatHelpLayout") { PreviewChatHelpLayout() }, SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkDirect") { PreviewChatListNavLinkDirect() }, SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkGroup") { PreviewChatListNavLinkGroup() }, diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png new file mode 100644 index 0000000000..1e04eb43d5 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png differ diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png new file mode 100644 index 0000000000..37b173d0e9 Binary files /dev/null and b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png differ