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
50 changes: 39 additions & 11 deletions Sources/Litext/LTXLabel/TextLayout/LTXTextLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public nonisolated class LTXTextLayout: NSObject {
private var framesetter: CTFramesetter
private var lines: [CTLine]?
private var lineOrigins: [CGPoint]?
private var lineBands: [LineBand] = []
private var hasOrderedLineBands = true
private var _highlightRegions: [Int: LTXHighlightRegion]
private var cachedSuggestedSize: CGSize?
private var cachedSuggestedSizeConstraint: CGSize?
Expand Down Expand Up @@ -409,6 +411,8 @@ public nonisolated class LTXTextLayout: NSObject {
private func generateLayout() {
lines = nil
lineOrigins = nil
lineBands.removeAll(keepingCapacity: true)
hasOrderedLineBands = true

let containerBounds = CGRect(
origin: .zero,
Expand All @@ -433,6 +437,22 @@ public nonisolated class LTXTextLayout: NSObject {
var origins = [CGPoint](repeating: .zero, count: frameLines.count)
CTFrameGetLineOrigins(ctFrame, CFRange(location: 0, length: 0), &origins)
lineOrigins = origins
lineBands.reserveCapacity(frameLines.count)
for (index, line) in frameLines.enumerated() {
var ascent: CGFloat = 0
var descent: CGFloat = 0
var leading: CGFloat = 0
CTLineGetTypographicBounds(line, &ascent, &descent, &leading)
let band = LineBand(
minY: origins[index].y - descent,
maxY: origins[index].y + ascent + leading
)
if let previous = lineBands.last,
band.minY > previous.minY || band.maxY > previous.maxY {
hasOrderedLineBands = false
}
lineBands.append(band)
}
}
}
}
Expand Down Expand Up @@ -515,18 +535,26 @@ public nonisolated class LTXTextLayout: NSObject {
) {
guard let lines, let lineOrigins else { return }

for i in 0 ..< lines.count {
var start = 0
if let band, hasOrderedLineBands {
var end = lineBands.count
while start < end {
let middle = start + (end - start) / 2
if lineBands[middle].minY > band.maxY {
start = middle + 1
} else {
end = middle
}
}
}
for i in start ..< lines.count {
if let band {
let origin = lineOrigins[i]
var ascent: CGFloat = 0
var descent: CGFloat = 0
var leading: CGFloat = 0
_ = CTLineGetTypographicBounds(lines[i], &ascent, &descent, &leading)
// Same vertical extents as `lineRects()`. Origins descend as
// the index grows (CoreText is bottom-up), so once a line falls
// below the band no later line can re-enter it.
if origin.y - descent > band.maxY { continue }
if origin.y + ascent + leading < band.minY { break }
let bounds = lineBands[i]
if bounds.minY > band.maxY { continue }
if bounds.maxY < band.minY {
if hasOrderedLineBands { break }
continue
}
}
block(lines[i], i, lineOrigins[i])
}
Expand Down
79 changes: 45 additions & 34 deletions Sources/MarkdownParser/MarkdownParser/MarkdownParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public class MarkdownParser {
return cmark_parser_finish(parser)
}
}
defer { if let nodes { cmark_node_free(nodes) } }
var blocks = dumpBlocks(root: nodes)
blocks = finalizeMathBlocks(blocks, mathContext: math)
return .init(document: blocks, mathContext: math.contents)
Expand Down Expand Up @@ -80,6 +81,9 @@ public class MarkdownParser {
return ranges
}

defer { cmark_node_free(root) }
let sourceLines = SourceLineIndex(markdown)

assert(root.pointee.type == CMARK_NODE_DOCUMENT.rawValue)
for block in root.children {
let node = block.pointee
Expand All @@ -89,8 +93,8 @@ public class MarkdownParser {
let endLine = Int(node.end_line)
let endColumn = Int(node.end_column)

guard let startIndex = getIndex(forLine: startLine, column: startColumn, in: markdown),
let endIndex = getIndex(forLine: endLine, column: endColumn, in: markdown)
guard let startIndex = sourceLines.index(line: startLine, column: startColumn),
let endIndex = sourceLines.index(line: endLine, column: endColumn)
else {
assertionFailure()
continue
Expand Down Expand Up @@ -160,38 +164,45 @@ public class MarkdownParser {
}
}

private func getIndex(forLine targetLine: Int, column targetColumn: Int, in text: String) -> String.Index? {
var currentLine = 1
var lineStartIndex = text.startIndex

while currentLine < targetLine {
guard let newlineIndex = text[lineStartIndex...].firstIndex(of: "\n") else {
return nil
private struct SourceLineIndex {
let text: String
let lines: [Range<String.UTF8View.Index>]

init(_ text: String) {
self.text = text
let bytes = text.utf8
var lines: [Range<String.UTF8View.Index>] = []
var start = bytes.startIndex
var cursor = start
while cursor < bytes.endIndex {
let byte = bytes[cursor]
if byte == 10 || byte == 13 {
lines.append(start..<cursor)
cursor = bytes.index(after: cursor)
if byte == 13, cursor < bytes.endIndex, bytes[cursor] == 10 {
cursor = bytes.index(after: cursor)
}
start = cursor
} else {
cursor = bytes.index(after: cursor)
}
}
lineStartIndex = text.index(after: newlineIndex)
currentLine += 1
lines.append(start..<bytes.endIndex)
self.lines = lines
}

// cmark 使用 1-based 列号,需要减1转换为 0-based
let targetOffset = targetColumn - 1

let lineEndIndex: String.Index = if let newlineIndex = text[lineStartIndex...].firstIndex(of: "\n") {
newlineIndex
} else {
text.endIndex
}

let maxOffset = text.distance(from: lineStartIndex, to: lineEndIndex)

if targetOffset > maxOffset {
return lineEndIndex
}

if targetOffset < 0 {
return lineStartIndex
func index(line: Int, column: Int) -> String.Index? {
guard line > 0, line <= lines.count else { return nil }
let range = lines[line - 1]
let bytes = text.utf8
let offset = min(max(column - 1, 0), bytes.distance(from: range.lowerBound, to: range.upperBound))
var position = bytes.index(range.lowerBound, offsetBy: offset)
// cmark columns are UTF-8 bytes; inclusive ends can land inside a scalar.
while String.Index(position, within: text) == nil, position > range.lowerBound {
position = bytes.index(before: position)
}
return String.Index(position, within: text)
}

return text.index(lineStartIndex, offsetBy: targetOffset)
}

private extension MarkdownParser {
Expand Down Expand Up @@ -360,12 +371,12 @@ private extension MarkdownParser {
at boundary: String.Index
) -> [RootBlockRange] {
ranges.map { range in
let startOffset = tailMarkdown.distance(from: tailMarkdown.startIndex, to: range.startIndex)
let endOffset = tailMarkdown.distance(from: tailMarkdown.startIndex, to: range.endIndex)
let startOffset = tailMarkdown.utf8.distance(from: tailMarkdown.startIndex, to: range.startIndex)
let endOffset = tailMarkdown.utf8.distance(from: tailMarkdown.startIndex, to: range.endIndex)
return .init(
type: range.type,
startIndex: fullMarkdown.index(boundary, offsetBy: startOffset),
endIndex: fullMarkdown.index(boundary, offsetBy: endOffset),
startIndex: fullMarkdown.utf8.index(boundary, offsetBy: startOffset),
endIndex: fullMarkdown.utf8.index(boundary, offsetBy: endOffset),
outputBlockCount: range.outputBlockCount
)
}
Expand Down
130 changes: 78 additions & 52 deletions Sources/MarkdownView/MarkdownTextView/MarkdownTextView+Private.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ import MarkdownParser

extension MarkdownTextView {
// Flows through the background preprocessing queue, so both the context and the
// pipeline's update enum are nonisolated (they only carry Sendable payloads).
// pipeline's update enum are nonisolated immutable snapshots.
nonisolated struct IncrementalParsingContext {
let previousRawMarkdown: String
let previousContent: PreprocessedContent
let previousRanges: [MarkdownParser.RootBlockRange]?
}

nonisolated enum RawMarkdownUpdate {
// Immutable snapshots cross the serial worker boundary. Background processing
// reads AST data and builds new content; UI rendering stays on the main actor.
// Platform colors/images in these snapshots lack checked Sendable conformance.
nonisolated enum RawMarkdownUpdate: @unchecked Sendable {
case ready(content: PreprocessedContent, rawMarkdown: String)
case parse(markdown: String, theme: MarkdownTheme, incrementalContext: IncrementalParsingContext?)
case parsedFull(
Expand Down Expand Up @@ -91,6 +94,8 @@ extension MarkdownTextView {
)

func resetCombine() {
rawPipelineGeneration &+= 1
pendingRawMarkdown = nil
cancellables.forEach { $0.cancel() }
cancellables.removeAll()
contentPipelineMode = .none
Expand Down Expand Up @@ -125,57 +130,76 @@ extension MarkdownTextView {
}

pipeline
.map { [weak self] rawMarkdown -> RawMarkdownUpdate in
let markdown = RawDiffMarkdownNormalizer.normalizeForParsing(rawMarkdown)
guard let self else {
return .parse(markdown: markdown, theme: .default, incrementalContext: nil)
}
if let content = self.makePlainTextAppendFastPath(for: markdown) {
return .ready(content: content, rawMarkdown: markdown)
}
return .parse(
markdown: markdown,
theme: self.theme,
incrementalContext: self.makeIncrementalParsingContext()
)
.sink { [weak self] markdown in
guard let self else { return }
self.pendingRawMarkdown = markdown
self.processPendingRawMarkdown()
}
.receive(on: Self.preprocessingQueue)
// Runs on `preprocessingQueue` (off the main actor), so it must be a
// `nonisolated` function — a main-actor-isolated closure here would trap
// the runtime isolation check when Combine delivers it on that queue.
.map(Self.processOnPreprocessingQueue)
.receive(on: DispatchQueue.main)
.sink { [weak self] update in
.store(in: &cancellables)
}

private func processPendingRawMarkdown() {
guard !isRawPreprocessing, contentPipelineMode == .raw,
let rawMarkdown = pendingRawMarkdown else { return }
pendingRawMarkdown = nil
let markdown = RawDiffMarkdownNormalizer.normalizeForParsing(rawMarkdown)
if let content = makePlainTextAppendFastPath(for: markdown) {
applyRawMarkdownUpdate(.ready(content: content, rawMarkdown: markdown))
return
}
let generation = rawPipelineGeneration
let request = RawMarkdownUpdate.parse(
markdown: markdown,
theme: theme,
incrementalContext: makeIncrementalParsingContext()
)
isRawPreprocessing = true
// Only one job per view is queued. The main actor retains just the latest
// pending input, and reset invalidates results without racing the worker.
Self.preprocessingQueue.async { [weak self] in
let update = Self.processOnPreprocessingQueue(request)
DispatchQueue.main.async { [weak self] in
guard let self else { return }
switch update {
case let .ready(content, rawMarkdown):
self.lastRawMarkdown = rawMarkdown
self.lastRootBlockRanges = nil
self.use(content)
case let .parsedFull(result, content, theme, rawMarkdown):
// Complete math rendering on main thread where UI context is available
let finalContent = content.completeMathRendering(parserResult: result, theme: theme)
self.lastRawMarkdown = rawMarkdown
self.lastRootBlockRanges = nil
self.use(finalContent)
case let .parsedIncremental(result, tailContent, context, theme, rawMarkdown):
let completedTailContent = tailContent.completeMathRendering(
parserResult: result.tailResult,
theme: theme
)
let mergedContent = PreprocessedContent.incrementalMerged(
prefix: context.previousContent,
stablePrefixBlockCount: result.stablePrefixBlockCount,
tail: completedTailContent
)
self.lastRawMarkdown = rawMarkdown
self.lastRootBlockRanges = result.blockRanges
self.use(mergedContent)
case .parse:
assertionFailure("Unexpected raw markdown parse request on main thread")
self.isRawPreprocessing = false
if self.rawPipelineGeneration == generation,
self.contentPipelineMode == .raw {
// Publish progress even while newer input is pending; otherwise
// continuous streams can starve rendering until input stops.
self.applyRawMarkdownUpdate(update)
}
self.processPendingRawMarkdown()
}
.store(in: &cancellables)
}
}

private func applyRawMarkdownUpdate(_ update: RawMarkdownUpdate) {
switch update {
case let .ready(content, rawMarkdown):
lastRawMarkdown = rawMarkdown
lastRootBlockRanges = nil
use(content, layoutImmediately: false)
case let .parsedFull(result, content, theme, rawMarkdown):
// Complete math rendering on main thread where UI context is available
let finalContent = content.completeMathRendering(parserResult: result, theme: theme)
lastRawMarkdown = rawMarkdown
lastRootBlockRanges = nil
use(finalContent, layoutImmediately: false)
case let .parsedIncremental(result, tailContent, context, theme, rawMarkdown):
let completedTailContent = tailContent.completeMathRendering(
parserResult: result.tailResult,
theme: theme
)
let mergedContent = PreprocessedContent.incrementalMerged(
prefix: context.previousContent,
stablePrefixBlockCount: result.stablePrefixBlockCount,
tail: completedTailContent
)
lastRawMarkdown = rawMarkdown
lastRootBlockRanges = result.blockRanges
use(mergedContent, layoutImmediately: false)
case .parse:
assertionFailure("Unexpected raw markdown parse request on main thread")
}
}

private func makeIncrementalParsingContext() -> IncrementalParsingContext? {
Expand Down Expand Up @@ -276,7 +300,7 @@ extension MarkdownTextView {
use(document)
}

func use(_ content: PreprocessedContent) {
func use(_ content: PreprocessedContent, layoutImmediately: Bool = true) {
assert(Thread.isMainThread)
document = content
// due to a bug in model gemini-flash
Expand All @@ -287,9 +311,11 @@ extension MarkdownTextView {
invalidateIntrinsicContentSize()

#if canImport(UIKit)
layoutIfNeeded()
setNeedsLayout()
if layoutImmediately { layoutIfNeeded() }
#elseif canImport(AppKit)
layoutSubtreeIfNeeded()
needsLayout = true
if layoutImmediately { layoutSubtreeIfNeeded() }
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ extension MarkdownTextView {
}
}

for goneView in oldViews where !artifacts.subviews.contains(goneView) {
let currentViewIDs = Set(artifacts.subviews.map { ObjectIdentifier($0) })
for goneView in oldViews where !currentViewIDs.contains(ObjectIdentifier(goneView)) {
goneView.removeFromSuperview()
}
}
Expand Down
Loading
Loading