diff --git a/Sources/Litext/LTXLabel/Attachments/LTXAttachment.swift b/Sources/Litext/LTXLabel/Attachments/LTXAttachment.swift index 8c5df88..4cd1e35 100644 --- a/Sources/Litext/LTXLabel/Attachments/LTXAttachment.swift +++ b/Sources/Litext/LTXLabel/Attachments/LTXAttachment.swift @@ -16,6 +16,11 @@ open class LTXAttachment { size = .zero } + // Avoid the isolated-deinit back-deployment path during synchronous rendering. + // Main-actor-isolated subclasses must also opt out; this is not inherited. + // Stored properties (including `view`) are released on the final releaser's thread. + nonisolated deinit {} + open func attributedStringRepresentation() -> NSAttributedString { if let view = view as? LTXAttributeStringRepresentable { return view.attributedStringRepresentation() diff --git a/Sources/Litext/LTXLabel/LTXLabel.swift b/Sources/Litext/LTXLabel/LTXLabel.swift index 8dbc232..8817989 100644 --- a/Sources/Litext/LTXLabel/LTXLabel.swift +++ b/Sources/Litext/LTXLabel/LTXLabel.swift @@ -228,10 +228,18 @@ public class LTXLabel: LTXPlatformView, Identifiable { fatalError() } - // The view is `@MainActor`, but Swift 6.2 makes `deinit` nonisolated by - // default; this touches main-actor state (`attributedText`, `attachmentViews`, - // selection), so keep the deinit on the main actor. - isolated deinit { + #if canImport(UIKit) + // UIKit releases views on the main thread. Avoid the back-deployed executor hop. + nonisolated deinit { + MainActor.assumeIsolated { tearDown() } + } + #else + isolated deinit { + tearDown() + } + #endif + + private func tearDown() { stopRevealDriver() cancelLongPressTimer() attributedText = .init() diff --git a/Sources/Litext/LTXLabel/Selection/LTXSelectionHandle.swift b/Sources/Litext/LTXLabel/Selection/LTXSelectionHandle.swift index abe40e4..60a5852 100644 --- a/Sources/Litext/LTXLabel/Selection/LTXSelectionHandle.swift +++ b/Sources/Litext/LTXLabel/Selection/LTXSelectionHandle.swift @@ -12,6 +12,9 @@ import Foundation } public class LTXSelectionHandle: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + static let knobRadius: CGFloat = 12 static let knobExtraResponsiveArea: CGFloat = 20 diff --git a/Sources/MarkdownView/Components/CodeView/CodeView.swift b/Sources/MarkdownView/Components/CodeView/CodeView.swift index 0ba0be6..da3c8d2 100644 --- a/Sources/MarkdownView/Components/CodeView/CodeView.swift +++ b/Sources/MarkdownView/Components/CodeView/CodeView.swift @@ -9,6 +9,9 @@ import Litext import UIKit final class CodeView: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + // MARK: - CONTENT var theme: MarkdownTheme = .default { diff --git a/Sources/MarkdownView/Components/CodeView/LineNumberView.swift b/Sources/MarkdownView/Components/CodeView/LineNumberView.swift index 7f15760..9a8377a 100644 --- a/Sources/MarkdownView/Components/CodeView/LineNumberView.swift +++ b/Sources/MarkdownView/Components/CodeView/LineNumberView.swift @@ -9,6 +9,9 @@ import Litext import UIKit final class LineNumberView: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + private var suppressInvalidation = false private var lineRects: [CGRect] = [] diff --git a/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift b/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift index 501838f..21c4fc5 100644 --- a/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift +++ b/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift @@ -8,6 +8,9 @@ /// - **Bounce**: Bounces the icon in place (share) /// - **State toggle**: Replaces between two icons with optional ongoing effect (speaker) class SymbolActionView: UIImageView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + enum Effect { /// Replaces icon with checkmark, then replaces back after completion. diff --git a/Sources/MarkdownView/Components/LineSelection/LineSelectionOverlayView.swift b/Sources/MarkdownView/Components/LineSelection/LineSelectionOverlayView.swift index a49d39d..6be8960 100644 --- a/Sources/MarkdownView/Components/LineSelection/LineSelectionOverlayView.swift +++ b/Sources/MarkdownView/Components/LineSelection/LineSelectionOverlayView.swift @@ -2,6 +2,9 @@ import UIKit final class LineSelectionOverlayView: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + var selectionColor: UIColor = .systemBlue.withAlphaComponent(0.15) { didSet { setNeedsDisplay() } } diff --git a/Sources/MarkdownView/Components/TableView/GridView.swift b/Sources/MarkdownView/Components/TableView/GridView.swift index 4ad5f81..c6a884c 100644 --- a/Sources/MarkdownView/Components/TableView/GridView.swift +++ b/Sources/MarkdownView/Components/TableView/GridView.swift @@ -10,6 +10,9 @@ import UIKit final class GridView: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + private var widths: [CGFloat] = [] private var heights: [CGFloat] = [] private var totalWidth: CGFloat = 0 diff --git a/Sources/MarkdownView/Components/TableView/TableView.swift b/Sources/MarkdownView/Components/TableView/TableView.swift index 18aa5d7..99fb072 100644 --- a/Sources/MarkdownView/Components/TableView/TableView.swift +++ b/Sources/MarkdownView/Components/TableView/TableView.swift @@ -9,6 +9,9 @@ import Litext import UIKit final class TableView: UIView { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + typealias Rows = [NSAttributedString] // MARK: - Constants diff --git a/Sources/MarkdownView/Components/TableView/TableViewCellManager.swift b/Sources/MarkdownView/Components/TableView/TableViewCellManager.swift index f80e028..48de0dd 100644 --- a/Sources/MarkdownView/Components/TableView/TableViewCellManager.swift +++ b/Sources/MarkdownView/Components/TableView/TableViewCellManager.swift @@ -12,6 +12,9 @@ import Litext import UIKit final class TableViewCellManager { + // Avoid the isolated-deinit back-deployment path during synchronous UIKit teardown. + nonisolated deinit {} + // MARK: - Properties private(set) var cells: [LTXLabel] = [] diff --git a/Sources/MarkdownView/MarkdownTextBuilder/BlockProcessor.swift b/Sources/MarkdownView/MarkdownTextBuilder/BlockProcessor.swift index 0de16e5..5b58d54 100644 --- a/Sources/MarkdownView/MarkdownTextBuilder/BlockProcessor.swift +++ b/Sources/MarkdownView/MarkdownTextBuilder/BlockProcessor.swift @@ -105,7 +105,7 @@ final class BlockProcessor { codeView.language = language ?? "" codeView.highlightMap = highlightMap codeView.content = content - let drawer = codeDrawing! + let drawer = codeDrawing let text = buildWithParagraphSync(modifier: { paragraph in let height = self.theme.wrapsCodeBlockLines && self.layoutWidth > 0 ? codeView.preferredHeight(forViewWidth: self.layoutWidth) @@ -115,7 +115,7 @@ final class BlockProcessor { .init(string: LTXReplacementText, attributes: [ .font: theme.fonts.body, .ltxAttachment: LTXAttachment.hold(attrString: .init(string: content + "\n")), - .ltxLineDrawingCallback: LTXLineDrawingAction { drawer($0, $1, $2) }, + .ltxLineDrawingCallback: LTXLineDrawingAction { drawer?($0, $1, $2) }, .contextView: codeView, ]) } @@ -128,7 +128,7 @@ final class BlockProcessor { let diffView = viewProvider.acquireDiffView() diffView.theme = theme diffView.renderBlock = renderBlock - let drawer = diffDrawing! + let drawer = diffDrawing let text = buildWithParagraphSync(modifier: { paragraph in let height = DiffViewConfiguration.intrinsicHeight(for: renderBlock, theme: self.theme) @@ -137,7 +137,7 @@ final class BlockProcessor { .init(string: LTXReplacementText, attributes: [ .font: theme.fonts.body, .ltxAttachment: LTXAttachment.hold(attrString: diffView.attributedStringRepresentation()), - .ltxLineDrawingCallback: LTXLineDrawingAction { drawer($0, $1, $2) }, + .ltxLineDrawingCallback: LTXLineDrawingAction { drawer?($0, $1, $2) }, .contextView: diffView, ]) } @@ -176,8 +176,8 @@ final class BlockProcessor { value: baseParagraphStyle, range: NSRange(location: 0, length: result.length) ) - let marker = blockquoteMarking! - let drawer = blockquoteDrawing! + let marker = blockquoteMarking + let drawer = blockquoteDrawing result.insert(buildWithParagraphSync(withNewLine: false, modifier: { paragraph in paragraph = baseParagraphStyle @@ -185,13 +185,15 @@ final class BlockProcessor { .init(string: LTXReplacementText, attributes: [ .font: theme.fonts.body, .paragraphStyle: baseParagraphStyle, - .ltxLineDrawingCallback: LTXLineDrawingAction { marker($0, $1, $2) }, + .blockquoteStart: true, + .ltxLineDrawingCallback: LTXLineDrawingAction { marker?($0, $1, $2) }, ]) }, at: 0) result.append(buildWithParagraphSync(withNewLine: true) { .init(string: LTXReplacementText, attributes: [ .font: theme.fonts.body, - .ltxLineDrawingCallback: LTXLineDrawingAction { drawer($0, $1, $2) }, + .blockquoteEnd: true, + .ltxLineDrawingCallback: LTXLineDrawingAction { drawer?($0, $1, $2) }, ]) }) @@ -210,7 +212,7 @@ final class BlockProcessor { .joined(separator: "\n") let representedText = NSAttributedString(string: allContent + "\n") tableView.setContents(contents) - let drawer = tableDrawing! + let drawer = tableDrawing let text = buildWithParagraphSync(modifier: { paragraph in paragraph.minimumLineHeight = tableView.intrinsicContentHeight @@ -218,7 +220,7 @@ final class BlockProcessor { .init(string: LTXReplacementText, attributes: [ .font: theme.fonts.body, .ltxAttachment: LTXAttachment.hold(attrString: representedText), - .ltxLineDrawingCallback: LTXLineDrawingAction { drawer($0, $1, $2) }, + .ltxLineDrawingCallback: LTXLineDrawingAction { drawer?($0, $1, $2) }, .contextView: tableView, ]) } diff --git a/Sources/MarkdownView/MarkdownTextBuilder/TextBuilder+Do.swift b/Sources/MarkdownView/MarkdownTextBuilder/TextBuilder+Do.swift index 190e41c..48817e0 100644 --- a/Sources/MarkdownView/MarkdownTextBuilder/TextBuilder+Do.swift +++ b/Sources/MarkdownView/MarkdownTextBuilder/TextBuilder+Do.swift @@ -247,16 +247,21 @@ extension TextBuilder { ) } .withBlockquoteMarking { _, line, lineOrigin in + // RTL runs can visit the end first. Single-line quotes need no saved position. + guard !line.glyphRuns().contains(where: { $0.attributes[.blockquoteEnd] != nil }) else { return } let boundingBox = lineBoundingBox(line, lineOrigin: lineOrigin) blockquoteMarkingStorage = boundingBox.maxY } .withBlockquoteDrawing { context, line, lineOrigin in let boundingBox = lineBoundingBox(line, lineOrigin: lineOrigin) defer { blockquoteMarkingStorage = nil } - let quotingLineHeight: CGFloat = blockquoteMarkingStorage! - boundingBox.minY + // A visible tile can include the end of a quote without its start marker. + let startsOnThisLine = line.glyphRuns().contains { $0.attributes[.blockquoteStart] != nil } + guard let top = startsOnThisLine ? boundingBox.maxY : blockquoteMarkingStorage else { return } + let quotingLineHeight: CGFloat = top - boundingBox.minY let lineRect = CGRect( x: 0, - y: blockquoteMarkingStorage! - quotingLineHeight, + y: top - quotingLineHeight, width: 4, height: quotingLineHeight ) diff --git a/Sources/MarkdownView/Supplements+Extension/LTXAttachment+Extension.swift b/Sources/MarkdownView/Supplements+Extension/LTXAttachment+Extension.swift index 36b2e0d..d765270 100644 --- a/Sources/MarkdownView/Supplements+Extension/LTXAttachment+Extension.swift +++ b/Sources/MarkdownView/Supplements+Extension/LTXAttachment+Extension.swift @@ -9,6 +9,8 @@ import Foundation import Litext private class LTXHolderAttachment: LTXAttachment { + nonisolated deinit {} + let attrString: NSAttributedString init(attrString: NSAttributedString) { self.attrString = attrString diff --git a/Sources/MarkdownView/Supplements/AttributeStringKey.swift b/Sources/MarkdownView/Supplements/AttributeStringKey.swift index 91d37c3..4a909c6 100644 --- a/Sources/MarkdownView/Supplements/AttributeStringKey.swift +++ b/Sources/MarkdownView/Supplements/AttributeStringKey.swift @@ -8,6 +8,8 @@ import Foundation extension NSAttributedString.Key { + static let blockquoteStart: NSAttributedString.Key = .init("blockquoteStart") + static let blockquoteEnd: NSAttributedString.Key = .init("blockquoteEnd") static let contextView: NSAttributedString.Key = .init("contextView") static let contextImage: NSAttributedString.Key = .init("contextImage") static let contextIdentifier: NSAttributedString.Key = .init("contextIdentifier") diff --git a/Tests/MarkdownViewTests/BlockquoteDrawingTests.swift b/Tests/MarkdownViewTests/BlockquoteDrawingTests.swift new file mode 100644 index 0000000..3b8689e --- /dev/null +++ b/Tests/MarkdownViewTests/BlockquoteDrawingTests.swift @@ -0,0 +1,133 @@ +#if canImport(UIKit) +import UIKit +#elseif canImport(AppKit) +import AppKit +#endif +import CoreText +import XCTest +@testable import Litext +@testable import MarkdownView + +@MainActor +final class BlockquoteDrawingTests: XCTestCase { + func testSingleLineRTLQuoteDrawsBarOnFirstPassAndRedraw() throws { + try assertQuoteBars( + markdown: "> مرحبا بالعالم", + quotedTexts: ["مرحبا بالعالم"] + ) + } + + func testSeparatedRTLQuotesDoNotDrawBarAcrossParagraph() throws { + try assertQuoteBars( + markdown: "> مرحبا بالعالم\n\n" + String(repeating: "Intervening paragraph. ", count: 100) + + "\n\n> صباح الخير", + quotedTexts: ["مرحبا بالعالم", "صباح الخير"] + ) + } + + func testWrappedQuoteDrawsContinuousBarOnFullPass() throws { + let quote = String(repeating: "Quoted text. ", count: 100).trimmingCharacters(in: .whitespaces) + try assertQuoteBars(markdown: "> " + quote, quotedTexts: [quote]) + } + + private func assertQuoteBars(markdown: String, quotedTexts: [String]) throws { + let view = MarkdownTextView() + view.document = .init(markdown: markdown, theme: .default) + let document = TextBuilder.build(view: view, viewProvider: .init()).document + let layout = LTXTextLayout(attributedString: document) + let size = CGSize(width: 320, height: 6000) + layout.containerSize = size + let frame = try XCTUnwrap(layout.ctFrame) + let lines = CTFrameGetLines(frame) as! [CTLine] + var origins = [CGPoint](repeating: .zero, count: lines.count) + CTFrameGetLineOrigins(frame, CFRange(location: 0, length: 0), &origins) + let expected = try makeContext(size: size) + let undecorated = NSMutableAttributedString(attributedString: document) + undecorated.removeAttribute(LTXLineDrawingCallbackName, range: NSRange(location: 0, length: document.length)) + let textOnly = LTXTextLayout(attributedString: undecorated) + textOnly.containerSize = size + textOnly.draw(in: expected) + expected.translateBy(x: 0, y: size.height) + expected.scaleBy(x: 1, y: -1) + expected.setFillColor(view.theme.colors.body.withAlphaComponent(0.1).cgColor) + for text in quotedTexts { + let range = (document.string as NSString).range(of: text) + XCTAssertNotEqual(range.location, NSNotFound) + let quoteLines = lines.indices.filter { index in + let lineRange = CTLineGetStringRange(lines[index]) + return NSIntersectionRange(range, NSRange(location: lineRange.location, length: lineRange.length)).length > 0 + } + let first = try XCTUnwrap(quoteLines.first) + let last = try XCTUnwrap(quoteLines.last) + let top = TextBuilder.lineBoundingBox(lines[first], lineOrigin: origins[first]).maxY + let bottom = TextBuilder.lineBoundingBox(lines[last], lineOrigin: origins[last]).minY + let rect = CGRect(x: 0, y: bottom, width: 4, height: top - bottom) + expected.addPath(CGPath(roundedRect: rect, cornerWidth: 2, cornerHeight: 2, transform: nil)) + expected.fillPath() + } + let expectedPixels = try barPixels(expected) + XCTAssertTrue(expectedPixels.contains { $0 != 0 }) + for pass in 1...2 { + let actual = try makeContext(size: size) + layout.draw(in: actual) + XCTAssertEqual(try barPixels(actual), expectedPixels, "Incorrect bar geometry on pass \(pass)") + } + } + + private func makeContext(size: CGSize) throws -> CGContext { + try XCTUnwrap(CGContext( + data: nil, width: Int(size.width), height: Int(size.height), + bitsPerComponent: 8, bytesPerRow: Int(size.width) * 4, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + )) + } + + private func barPixels(_ context: CGContext) throws -> Data { + let data = try XCTUnwrap(context.data) + var pixels = Data() + for row in 0.. " + String(repeating: "Quoted text. ", count: 200), theme: .default) + let document = TextBuilder.build(view: view, viewProvider: .init()).document + let layout = LTXTextLayout(attributedString: document) + let size = CGSize(width: 320, height: 6000) + layout.containerSize = size + + let frame = try XCTUnwrap(layout.ctFrame) + let lines = CTFrameGetLines(frame) as! [CTLine] + var origins = [CGPoint](repeating: .zero, count: lines.count) + CTFrameGetLineOrigins(frame, CFRange(location: 0, length: 0), &origins) + let decoratedLines = lines.indices.filter { index in + let runs = CTLineGetGlyphRuns(lines[index]) as! [CTRun] + return runs.contains { run in + let attributes = CTRunGetAttributes(run) as NSDictionary + return attributes[LTXLineDrawingCallbackName] != nil + } + } + XCTAssertEqual(decoratedLines.count, 2) + let first = try XCTUnwrap(decoratedLines.first) + let last = try XCTUnwrap(decoratedLines.last) + let endBounds = TextBuilder.lineBoundingBox(lines[last], lineOrigin: origins[last]) + let visibleRect = CGRect(x: 0, y: size.height - endBounds.maxY, width: size.width, height: endBounds.height) + let startBounds = TextBuilder.lineBoundingBox(lines[first], lineOrigin: origins[first]) + XCTAssertGreaterThan(startBounds.minY, endBounds.maxY) + + let context = try XCTUnwrap(CGContext( + data: nil, width: Int(size.width), height: Int(size.height), + bitsPerComponent: 8, bytesPerRow: Int(size.width) * 4, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + )) + // Start with the ending tile, as can happen when scrolling into a long quote. + layout.draw(in: context, visibleRect: visibleRect) + layout.draw(in: context) + layout.draw(in: context, visibleRect: visibleRect) + } +} diff --git a/Tests/MarkdownViewTests/RenderingLifetimeTests.swift b/Tests/MarkdownViewTests/RenderingLifetimeTests.swift index ff8e4d4..1c6ddf7 100644 --- a/Tests/MarkdownViewTests/RenderingLifetimeTests.swift +++ b/Tests/MarkdownViewTests/RenderingLifetimeTests.swift @@ -1,5 +1,6 @@ import Foundation import XCTest +@testable import Litext @testable import MarkdownView @MainActor @@ -8,6 +9,45 @@ final class RenderingLifetimeTests: XCTestCase { @TaskLocal static var value = "outside" } + func testAttachmentReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { LTXAttachment() } + } + + func testHolderAttachmentReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { + let text = NSAttributedString(string: "Table contents") + let attachment = LTXAttachment.hold(attrString: text) + XCTAssertEqual(attachment.attributedStringRepresentation(), text) + return attachment + } + } + + #if canImport(UIKit) + func testLabelReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { LTXLabel() } + } + + func testCodeViewReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { + let view = CodeView() + view.content = "let value = 1" + return view + } + } + + func testTableViewReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { + let view = TableView() + view.setContents([[NSAttributedString(string: "Cell")]]) + return view + } + } + + func testMarkdownTextViewReleaseInsideSynchronousTaskLocalScope() { + checkSynchronousRelease { MarkdownTextView() } + } + #endif + func testInlineAttributeCacheReleaseInsideSynchronousTaskLocalScope() { checkSynchronousRelease { InlineAttributeCache(theme: .default) @@ -89,6 +129,22 @@ final class RenderingLifetimeTests: XCTestCase { } } + func testTextBuilderSupportsBlocksWithoutDrawingCallbacks() { + let fixtures = [ + "> Quote", + "```swift\nlet value = 1\n```", + "```diff\n@@ -1 +1 @@\n-old\n+new\n```", + "| Header |\n| --- |\n| Cell |", + ] + for markdown in fixtures { + let context = MarkdownTextView.PreprocessedContent(markdown: markdown, theme: .default) + let builder = TextBuilder(nodes: context.blocks, context: context, viewProvider: .init()) + let result = builder.build() + XCTAssertGreaterThan(result.document.length, 0, markdown) + XCTAssertEqual(result.subviews.count, markdown.hasPrefix(">") ? 0 : 1, markdown) + } + } + func testReusableViewProviderReleaseInsideSynchronousTaskLocalScope() { checkSynchronousRelease { ReusableViewProvider()