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
5 changes: 5 additions & 0 deletions Sources/Litext/LTXLabel/Attachments/LTXAttachment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
16 changes: 12 additions & 4 deletions Sources/Litext/LTXLabel/LTXLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 3 additions & 0 deletions Sources/Litext/LTXLabel/Selection/LTXSelectionHandle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions Sources/MarkdownView/Components/CodeView/CodeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions Sources/MarkdownView/Components/CodeView/LineNumberView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] = []

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
}
Expand Down
3 changes: 3 additions & 0 deletions Sources/MarkdownView/Components/TableView/GridView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions Sources/MarkdownView/Components/TableView/TableView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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] = []
Expand Down
22 changes: 12 additions & 10 deletions Sources/MarkdownView/MarkdownTextBuilder/BlockProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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,
])
}
Expand All @@ -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)
Expand All @@ -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,
])
}
Expand Down Expand Up @@ -176,22 +176,24 @@ 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
}) {
.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) },
])
})

Expand All @@ -210,15 +212,15 @@ 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
}) {
.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,
])
}
Expand Down
9 changes: 7 additions & 2 deletions Sources/MarkdownView/MarkdownTextBuilder/TextBuilder+Do.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The stored start position survives between draw passes. It is only cleared when an end callback runs, so a pass that sees a start without its end leaves a value behind for the next pass. With clipped draws on a document that has two long quotes and a paragraph between them:

  • Draw the tile holding quote B's start, then the tile holding quote A's end: a bar is drawn from A's end down to B's start, over the paragraph (the negative-height rect is normalized).
  • Draw one long quote as three tiles, top to bottom: no bar in the first two tiles, and a bar in the last one only because the first tile's start was still stored.

It is also a single captured var shared by every quote in the document, so it is not safe if a Markdown layout is ever drawn from concurrent tile renders the way DiffTileRenderer draws diffs.

The description already scopes continuous bars out, so this can be a follow-up. A stateless version, where each quote line draws its own bar segment from its own bounds, would fix the pass-order dependence, the RTL case above and the missing tiles together.

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
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import Foundation
import Litext

private class LTXHolderAttachment: LTXAttachment {
nonisolated deinit {}

let attrString: NSAttributedString
init(attrString: NSAttributedString) {
self.attrString = attrString
Expand Down
2 changes: 2 additions & 0 deletions Sources/MarkdownView/Supplements/AttributeStringKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
133 changes: 133 additions & 0 deletions Tests/MarkdownViewTests/BlockquoteDrawingTests.swift
Original file line number Diff line number Diff line change
@@ -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..<context.height {
pixels.append(Data(bytes: data.advanced(by: row * context.bytesPerRow), count: 4 * 4))
}
return pixels
}

func testQuoteEndCanBeDrawnWithoutItsStartMarker() throws {
let view = MarkdownTextView()
view.document = .init(markdown: "> " + 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)
Comment on lines +129 to +131

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These three calls only prove that drawing does not crash. With the guard, the first call draws no bar for the quote's last line, and nothing here would catch a change in bar geometry.

Consider asserting on the pixels in the bar column (x 0..<4), at least for the full layout.draw(in:), the way TiledLayoutTests compares pixels(_:).

}
}
Loading
Loading