diff --git a/README.md b/README.md index 5f0a6ab..e4a2c80 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut marker) are built in, and you can draw shapes of your own, and animate a tag's letters and shapes when it finishes arriving. - **Fade-in.** Optionally, text fades in as it streams in. Core Animation plays the fades. +- **Right-to-left text.** Paragraphs in Arabic, Hebrew and other right-to-left scripts start at the right edge, and + selection follows the glyphs in text of mixed direction. - **SwiftUI and UIKit.** `TranscriptText` for SwiftUI, `TranscriptTextView` for UIKit. ## Requirements @@ -435,6 +437,26 @@ TranscriptText(document) The same values are `lineLimit` and `textAlignment` on `TranscriptStyle`. The alignment moves paragraphs and headings; lists, quotes, code and tables stay at the leading edge. A table is shown whole or not at all. +### Right-to-left text + +Each block takes its direction from its first strong character, such as a letter. Digits, punctuation and spaces do +not count. So a paragraph that starts with a word in Arabic or Hebrew is right to left, and a paragraph that starts with +an English word is left to right, also when it holds words in other scripts. + +In a right-to-left block, the leading edge is on the right. Lines start there, and `textAlignment` counts from there: +`.trailing` puts the lines at the left. The indents of lists and quotes, list markers and quote bars are on the right, +and a table puts its first column on the right. A table column with no colon in its delimiter cell (`---`) starts at +the leading edge. A colon on one side (`:---` or `---:`) puts the column's text at the left or at the right, in both +directions. Code blocks are always left to right. + +A custom tag takes the direction of its first strong character. A right-to-left tag starts at the right: its padding +and its image before the text are on the right, and the built-in shapes are open on the correct side where the tag +wraps. `TranscriptFragment.isRightToLeft` tells a shape of your own the same. + +A selection follows the glyphs. In text of mixed direction, one line can have several selection rects. In a line with +right-to-left text, the left and right arrow keys move the caret to the next caret on that side of the screen. Copy +gives the text in the order it was written. + ### Styling `TranscriptStyle` sets the body size, line, block and list spacing, indents, padding and the maximum image height. diff --git a/Sources/TranscriptKit/Layout/AccessibilityContent.swift b/Sources/TranscriptKit/Layout/AccessibilityContent.swift index 1f2b2bc..6e8a60b 100644 --- a/Sources/TranscriptKit/Layout/AccessibilityContent.swift +++ b/Sources/TranscriptKit/Layout/AccessibilityContent.swift @@ -81,7 +81,8 @@ extension DocumentLayout { definitions: definitions) words?.keep(made, for: key, layout: entry.layout) if let model = block.kind.table, let grid = entry.layout.table { - let table = Self.accessibilityTable(model, grid: grid, of: block, at: entry.y, words: made.cells, + let table = Self.accessibilityTable(model, grid: grid, of: block, at: entry.y, + rightToLeft: entry.layout.isRightToLeft, words: made.cells, position: positions[index].map(AccessibilityText.position)) guard !table.cells.isEmpty else { continue } items.append(AccessibilityItem(key: key, frame: entry.frame, label: "", value: nil, isHeading: false, @@ -142,12 +143,15 @@ extension DocumentLayout { } private static func accessibilityTable(_ model: TranscriptTable, grid: BlockLayout.Table, of block: TranscriptBlock, at y: CGFloat, - words: [AccessibilityWords.Words], position: String?) -> AccessibilityItem.Table { + rightToLeft: Bool, words: [AccessibilityWords.Words], + position: String?) -> AccessibilityItem.Table { var cells: [AccessibilityItem.Table.Cell] = [] let (rowCount, columnCount) = accessibilityGridSize(model, grid: grid) for row in 0.. if let model = block.kind.table { let laidOut = Self.layOutTable(model, block: block, style: style, x: contentLeading, available: available, - blockWidth: width, images: images, definitions: definitions, + blockWidth: width, direction: direction, images: images, definitions: definitions, reusing: previous.flatMap { $0.width == width && $0.style == style && $0.imageRevision == revision ? $0 : nil }) lines = laidOut.lines self.height = laidOut.height @@ -163,7 +187,7 @@ final class BlockLayout: @unchecked Sendable { let scrolls = Self.scrollsSideways(block, style: style) let sizing = ImageSizing(store: images, maximumWidth: scrolls ? Self.unlimitedWidth : available) let laidOut = Self.layOutText(block, style: style, insets: insets, available: available, blockWidth: width, - wraps: !scrolls, sizing: sizing, definitions: definitions, + wraps: !scrolls, direction: direction, sizing: sizing, definitions: definitions, reusing: previous.flatMap { $0.width == width && $0.imageRevision == revision ? $0 : nil }) lines = laidOut.lines self.height = laidOut.height @@ -172,7 +196,8 @@ final class BlockLayout: @unchecked Sendable { self.maximumScrollOffset = scrolls ? max(ceil(laidOut.right + insets.trailing - width), 0) : 0 } self.lines = lines - self.marker = Self.makeMarker(for: block, style: style, firstLine: lines.first) + self.marker = Self.makeMarker(for: block, style: style, firstLine: lines.first, width: width, + rightToLeft: direction == .rightToLeft) self.attachments = hasImages ? Self.findAttachments(in: lines) : [] } @@ -180,8 +205,8 @@ final class BlockLayout: @unchecked Sendable { /// - Parameter wraps: whether lines break at `available`, or only at line breaks. private static func layOutText(_ block: TranscriptBlock, style: TranscriptStyle, insets: TranscriptStyle.Insets, - available: CGFloat, blockWidth: CGFloat, wraps: Bool, sizing: ImageSizing, - definitions: [String: String], + available: CGFloat, blockWidth: CGFloat, wraps: Bool, direction: WritingDirection?, + sizing: ImageSizing, definitions: [String: String], reusing previous: BlockLayout?) -> (lines: SharedList, height: CGFloat, right: CGFloat) { let length = block.utf16Count let font = style.font(for: block.kind) @@ -190,7 +215,7 @@ final class BlockLayout: @unchecked Sendable { var y = insets.vertical var restart = 0 var right: CGFloat = 0 - if let previous, previous.style == style, previous.block.isStyledPrefix(of: block), previous.lines.count > 1 { + if let previous, previous.style == style, previous.lines.count > 1 { // Line breaks are chosen greedily, so appended text can only // change the last line and what follows it. var keep = previous.lines.count - 1 @@ -230,16 +255,17 @@ final class BlockLayout: @unchecked Sendable { } // Only the tags on the lines laid out again; the others' lines are kept. - let decorated = hasDecorations ? DecoratedTags(block, from: restart) : nil + let decorated = hasDecorations ? DecoratedTags(block, from: restart, direction: direction) : nil let fixedHeight = style.lineHeight(for: block.kind) let gap = fixedHeight == nil ? style.lineSpacing : 0 let isDisplayMath = Self.isDisplayMath(block) func add(_ ctLine: CTLine, range: Range, indexBase: Int, leading: CGFloat = 0, text: NSAttributedString? = nil) { let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight) - let x = insets.leading + leading + (isDisplayMath + let x = place(insets.leading + leading + (isDisplayMath ? offset(for: style.displayMathAlignment, width: metrics.width, room: available - leading) - : alignmentOffset(block, style: style, width: metrics.width, room: available - leading)) + : alignmentOffset(block, style: style, width: metrics.width, room: available - leading)), + width: metrics.width, in: blockWidth, direction: direction) right = max(right, x + metrics.width) var decorations: LineDecorations? if let decorated, let text { @@ -261,7 +287,7 @@ final class BlockLayout: @unchecked Sendable { if restart < length { let attributed = style.attributedString(for: block, from: restart, images: sizing, definitions: definitions, - kerns: decorated?.kerns ?? [:]) + kerns: decorated?.kerns ?? [:], direction: direction) let typesetter = CTTypesetterCreateWithAttributedString(attributed) let string = attributed.string as NSString var start = restart @@ -318,14 +344,23 @@ final class BlockLayout: @unchecked Sendable { return (metrics.width, height, metrics.ascent + ((height - metrics.height) / 2).rounded()) } - /// How far a line `width` wide moves right in `room` for the style's - /// alignment. Only paragraphs and headings outside lists and quotes move. + /// Where a line `width` wide starts in a block `blockWidth` wide, if it + /// starts `leading` from the block's leading edge: the left edge, or the + /// right edge in right-to-left text. + static func place(_ leading: CGFloat, width: CGFloat, in blockWidth: CGFloat, direction: WritingDirection?) -> CGFloat { + direction == .rightToLeft ? blockWidth - leading - width : leading + } + + /// How far a line `width` wide moves from the leading edge in `room` for + /// the style's alignment. Only paragraphs and headings outside lists and + /// quotes move. static func alignmentOffset(_ block: TranscriptBlock, style: TranscriptStyle, width: CGFloat, room: CGFloat) -> CGFloat { guard isAligned(block, style: style) else { return 0 } return offset(for: style.textAlignment, width: width, room: room) } - /// How far a line `width` wide moves right in `room` for `alignment`. + /// How far a line `width` wide moves from the leading edge in `room` + /// for `alignment`. /// A line wider than `room` stays at the leading edge. static func offset(for alignment: TranscriptTextAlignment, width: CGFloat, room: CGFloat) -> CGFloat { let slack = max(room - width, 0) @@ -358,12 +393,15 @@ final class BlockLayout: @unchecked Sendable { table = original.table imageRevision = original.imageRevision definedReferences = original.definedReferences + directionScan = original.directionScan + paragraphDirection = original.paragraphDirection let count = min(max(count, 1), original.lines.count) var kept = original.lines.prefix(count) let insets = style.insets(for: block) if ellipsis, let last = kept.last { _ = kept.removeLast() - kept.append(Self.withEllipsis(last, block: block, style: style, insets: insets, width: original.width)) + kept.append(Self.withEllipsis(last, block: block, style: style, insets: insets, width: original.width, + direction: original.paragraphDirection)) } lines = kept let bottom = kept.last.map { $0.frame.maxY } ?? 0 @@ -376,9 +414,10 @@ final class BlockLayout: @unchecked Sendable { } private static func withEllipsis(_ line: Line, block: TranscriptBlock, style: TranscriptStyle, - insets: TranscriptStyle.Insets, width: CGFloat) -> Line { + insets: TranscriptStyle.Insets, width: CGFloat, direction: WritingDirection?) -> Line { let available = max(width - insets.leading - insets.trailing, 1) - let rest = NSMutableAttributedString(attributedString: style.attributedString(for: block, range: line.range.lowerBound.. 0 ? rest.attributes(at: rest.length - 1, effectiveRange: nil) : style.attributes(for: block.kind) // Trailing line breaks would end the line before the ellipsis. while rest.length > 0, (rest.string as NSString).character(at: rest.length - 1) == 0x0A { @@ -390,12 +429,14 @@ final class BlockLayout: @unchecked Sendable { let token = CTLineCreateWithAttributedString(NSAttributedString(string: "…", attributes: attributes)) let full = CTLineCreateWithAttributedString(rest) let aligned = isAligned(block, style: style) - let start = aligned ? insets.leading : line.frame.minX + // From the leading edge. + let start = aligned ? insets.leading : (direction == .rightToLeft ? width - line.frame.maxX : line.frame.minX) let room = max(insets.leading + available - start, 1) let ctLine = CTLineCreateTruncatedLine(full, Double(room), .end, token) ?? full let font = style.font(for: block.kind) let metrics = lineMetrics(ctLine, isEmpty: false, font: font) - let x = aligned ? insets.leading + alignmentOffset(block, style: style, width: metrics.width, room: available) : start + let x = place(aligned ? insets.leading + alignmentOffset(block, style: style, width: metrics.width, room: available) : start, + width: metrics.width, in: width, direction: direction) return Line(ctLine: ctLine, indexBase: line.range.lowerBound, range: line.range, frame: CGRect(x: x, y: line.frame.minY, width: metrics.width, height: line.frame.height), baseline: line.baseline, decorations: nil) @@ -429,7 +470,8 @@ final class BlockLayout: @unchecked Sendable { /// neither measured nor typeset again, and keep their lines if the /// columns did not change, so only the row being written is redrawn. private static func layOutTable(_ model: TranscriptTable, block: TranscriptBlock, style: TranscriptStyle, x: CGFloat, - available: CGFloat, blockWidth: CGFloat, images: TranscriptImageStore?, definitions: [String: String], + available: CGFloat, blockWidth: CGFloat, direction: WritingDirection?, + images: TranscriptImageStore?, definitions: [String: String], reusing previous: BlockLayout?) -> (lines: SharedList, height: CGFloat, table: Table) { let columns = max(model.columnCount, 1) let padding = style.tableCellPadding @@ -437,7 +479,7 @@ final class BlockLayout: @unchecked Sendable { let font = style.font(for: block.kind) let fixedHeight = style.lineHeight(for: block.kind) let gap = fixedHeight == nil ? style.lineSpacing : 0 - let decorated = DecoratedTags(block) + let decorated = DecoratedTags(block, direction: direction) let sizing = ImageSizing(store: images, maximumWidth: max(available / CGFloat(columns) - padding * 2, 20)) let minimumWidth = padding * 2 + style.effectiveBodySize @@ -445,13 +487,15 @@ final class BlockLayout: @unchecked Sendable { var kept = 0 var old: Table? if let previous, let oldTable = previous.table, let oldModel = previous.block.kind.table, - oldModel.alignments == model.alignments, previous.block.isStyledPrefix(of: block) { + oldModel.alignments == model.alignments, oldModel.sidedColumns == model.sidedColumns { let limit = min(oldModel.rows.count - 1, model.rows.count) while kept < limit, oldModel.rows[kept] == model.rows[kept] { kept += 1 } old = oldTable } typealias Cell = (text: NSAttributedString, typesetter: CTTypesetter, range: Range) + // Each cell is typeset on its own, so Core Text gives it the direction + // of its own text. The table's direction sets the order of the columns. func makeCells(_ row: Int) -> [Cell] { let header = row == 0 let weight = header ? style.tableHeaderWeight : nil @@ -481,7 +525,8 @@ final class BlockLayout: @unchecked Sendable { let isBreak = index == start + count || [0x20, 0x09, 0x0A].contains(string.character(at: index)) guard isBreak else { continue } if index > wordStart { - let width = CTLineGetOffsetForStringIndex(line, index, nil) - CTLineGetOffsetForStringIndex(line, wordStart, nil) + // Negative in right-to-left text. + let width = abs(CTLineGetOffsetForStringIndex(line, index, nil) - CTLineGetOffsetForStringIndex(line, wordStart, nil)) longestWord = max(longestWord, width) } wordStart = index + 1 @@ -537,14 +582,16 @@ final class BlockLayout: @unchecked Sendable { } } } + // From the leading edge; mirrored once the table is laid out, if it is right to left. var columnX = [x] for width in widths { columnX.append(columnX[columnX.count - 1] + width) } + let shownColumnX = direction == .rightToLeft ? columnX.reversed().map { blockWidth - $0 } : columnX var lines = SharedList() var rowY: [CGFloat] = [0] var cellLines: [[Range]] = [] var firstRow = 0 - if kept > 0, let old, let previous, old.columnX == columnX { + if kept > 0, let old, let previous, old.columnX == shownColumnX { // Same columns: the kept rows look exactly as before. lines = previous.lines.prefix(old.cellLines[kept - 1].last?.upperBound ?? 0) rowY = Array(old.rowY[...kept]) @@ -564,11 +611,16 @@ final class BlockLayout: @unchecked Sendable { let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight) let slack = max(textWidth - metrics.width, 0) let offset: CGFloat - switch column < model.alignments.count ? model.alignments[column] : .leading { + var alignment = column < model.alignments.count ? model.alignments[column] : .leading + if direction == .rightToLeft, model.sidedColumns.contains(column) { + alignment = alignment == .leading ? .trailing : .leading + } + switch alignment { case .leading: offset = 0 case .center: offset = (slack / 2).rounded() case .trailing: offset = slack } + let lineX = place(columnX[column] + padding + offset, width: metrics.width, in: blockWidth, direction: direction) var decorations: LineDecorations? if let decorated { // A tag at the start of a cell gets no room on its left: it @@ -576,13 +628,13 @@ final class BlockLayout: @unchecked Sendable { decorations = LineDecorations.make(line: ctLine, range: range, indexBase: cell.range.lowerBound, visibleWidth: metrics.width, top: -metrics.ascent, bottom: metrics.height - metrics.ascent, - lineX: columnX[column] + padding + offset, blockWidth: blockWidth, + lineX: lineX, blockWidth: blockWidth, block: block.id, tags: decorated, text: cell.text, textBase: cell.range.lowerBound) } lines.append(Line( ctLine: ctLine, indexBase: cell.range.lowerBound, range: range, - frame: CGRect(x: columnX[column] + padding + offset, y: y, width: metrics.width, height: metrics.height), + frame: CGRect(x: lineX, y: y, width: metrics.width, height: metrics.height), baseline: y + metrics.ascent, decorations: decorations )) @@ -612,13 +664,14 @@ final class BlockLayout: @unchecked Sendable { rowY.append(ceil(bottom)) cellLines.append(rowLines) } - let table = Table(columnX: columnX, rowY: rowY, cellLines: cellLines, naturalWidths: rowNaturals, minimumWidths: rowMinimums) + let table = Table(columnX: shownColumnX, rowY: rowY, cellLines: cellLines, naturalWidths: rowNaturals, minimumWidths: rowMinimums) return (lines, rowY[rowY.count - 1], table) } // MARK: Markers and images - private static func makeMarker(for block: TranscriptBlock, style: TranscriptStyle, firstLine: Line?) -> Marker? { + private static func makeMarker(for block: TranscriptBlock, style: TranscriptStyle, firstLine: Line?, width: CGFloat, + rightToLeft: Bool) -> Marker? { guard let kind = block.marker, let firstLine, let item = block.containers.lastIndex(of: .listItem) else { return nil } // The marker sits in the gutter of the innermost list item. let gutterEnd = style.contentLeading(for: Array(block.containers[...item])) @@ -628,7 +681,8 @@ final class BlockLayout: @unchecked Sendable { case .task(let checked): let side = (style.effectiveBodySize * 0.82).rounded() let middle = firstLine.baseline - CTFontGetCapHeight(font) / 2 - return .checkbox(CGRect(x: gutterEnd - side - 6, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked) + let x = rightToLeft ? width - gutterEnd + 6 : gutterEnd - side - 6 + return .checkbox(CGRect(x: x, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked) case .bullet, .number: let text: String var attributes: [NSAttributedString.Key: Any] @@ -642,9 +696,12 @@ final class BlockLayout: @unchecked Sendable { attributes = style.attributes(for: .paragraph) if let color = bullet.color ?? quoteColor { attributes[TranscriptStyle.foregroundKey] = color } } + // So that a number's period is on the side of the text: ".1". + if rightToLeft { attributes[TranscriptStyle.paragraphStyleKey] = WritingDirection.rightToLeft.paragraphStyle } let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attributes)) let markerWidth = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) - return .text(line, origin: CGPoint(x: max(gutterEnd - markerWidth - 7, 0), y: firstLine.baseline)) + let x = rightToLeft ? min(width - gutterEnd + 7, width - markerWidth) : max(gutterEnd - markerWidth - 7, 0) + return .text(line, origin: CGPoint(x: x, y: firstLine.baseline)) } } @@ -688,12 +745,39 @@ final class BlockLayout: @unchecked Sendable { return CGRect(x: x(forOffset: offset, in: line) - 1, y: line.frame.minY, width: 2, height: line.frame.height) } + /// Where a caret at `offset` goes when it moves one stop to the right, + /// or to the left, in a line with right-to-left text: to the nearest + /// caret on that side, else to the end of the line on that side. Nil in + /// other lines, where a stop is one character, or when the caret is at + /// that end of the line already. + func visualStep(from offset: Int, right: Bool) -> Int? { + guard offset >= 0, offset <= length else { return nil } + let index = lineIndex(forOffset: offset) + let line = lines[index] + guard !line.range.isEmpty, hasRightToLeftText(line) else { return nil } + // The end of a line that wraps is a caret on the next line. + let last = index == lines.count - 1 ? line.range.upperBound : line.range.upperBound - 1 + let text = block.text as NSString + let x = self.x(forOffset: offset, in: line) + var best: (offset: Int, distance: CGFloat)? + for candidate in line.range.lowerBound...max(last, line.range.lowerBound) where candidate != offset { + if candidate < text.length, text.rangeOfComposedCharacterSequence(at: candidate).location != candidate { continue } + let distance = (self.x(forOffset: candidate, in: line) - x) * (right ? 1 : -1) + if distance > 0.5, best.map({ distance < $0.distance }) ?? true { best = (candidate, distance) } + } + if let best { return best.offset } + let end = right != isRightToLeft ? line.range.upperBound : line.range.lowerBound + return end == offset ? nil : end + } + func closestOffset(to point: CGPoint) -> Int { guard let table else { return closestOffset(to: point, amongLines: 0..= 0, !table.cellLines[row].isEmpty else { return 0 } - let column = min(max((table.columnX.lastIndex { $0 <= point.x } ?? 0), 0), table.cellLines[row].count - 1) + var column = table.columnX.lastIndex { $0 <= point.x } ?? 0 + if isRightToLeft { column = table.columnX.count - 2 - column } + column = min(max(column, 0), table.cellLines[row].count - 1) return closestOffset(to: point, amongLines: table.cellLines[row][column]) } @@ -719,6 +803,16 @@ final class BlockLayout: @unchecked Sendable { guard let line = lines.first(where: { $0.frame.minY <= point.y && point.y < $0.frame.maxY && point.x >= $0.frame.minX && point.x < $0.frame.maxX }), !line.range.isEmpty else { return nil } + if hasRightToLeftText(line) { + let x = point.x - line.frame.minX + guard let glyph = glyphs(of: line).first(where: { $0.minX <= x && x < $0.maxX }) else { return nil } + // In a ligature, the character whose part of the glyph is under the point. + let character = glyph.characters.first { offset in + let part = glyph.part(offset..<(offset + 1), in: line) + return part.minX <= x && x < part.maxX + } ?? glyph.characters.lowerBound + return line.range.contains(character) ? character : nil + } let localBoundary = CTLineGetStringIndexForPosition(line.ctLine, CGPoint(x: point.x - line.frame.minX, y: 0)) guard localBoundary != kCFNotFound else { return nil } let boundary = localBoundary + line.indexBase @@ -739,21 +833,180 @@ final class BlockLayout: @unchecked Sendable { return nil } - /// One rect per line touched by `range`. Left-to-right only for now. + + /// A part of a selection on one line: the glyphs of one or more runs + /// next to each other that go the same way. + struct SelectionSegment: Equatable { + var rect: CGRect + var isRightToLeft: Bool + /// The first and the last of its selected characters, in block offsets. + var characters: ClosedRange + /// The index of its line in the block. + var line: Int + /// Whether it holds the first selected character, where the start + /// handle goes, and the last one, where the end handle goes. + var containsStart = false + var containsEnd = false + } + + /// One rect per line touched by `range`, in lines that are all left to + /// right. A line with right-to-left text gets one rect for each stretch + /// of glyphs that go the same way, from left to right, so a selection in + /// text of mixed direction can have several rects on a line. func selectionRects(for range: Range) -> [CGRect] { + selectionSegments(for: range).map(\.rect) + } + + func selectionSegments(for range: Range) -> [SelectionSegment] { guard !range.isEmpty else { return [] } - var rects: [CGRect] = [] + var segments: [SelectionSegment] = [] let first = lineIndex(forOffset: range.lowerBound) for index in first..= range.upperBound { break } - let startX = x(forOffset: max(range.lowerBound, line.range.lowerBound), in: line) let continuesPastLine = range.upperBound >= line.range.upperBound && index < lines.count - 1 + let lower = max(range.lowerBound, line.range.lowerBound) + if hasRightToLeftText(line) { + segments += runSegments(of: line, at: index, selecting: range, continuesPastLine: continuesPastLine) + continue + } + let startX = x(forOffset: lower, in: line) let endX = continuesPastLine ? max(line.frame.maxX, startX) : x(forOffset: range.upperBound, in: line) if endX > startX || continuesPastLine { - rects.append(CGRect(x: startX, y: line.frame.minY, width: max(endX - startX, 4), height: line.frame.height)) + let last = max(min(range.upperBound, line.range.upperBound) - 1, lower) + segments.append(SelectionSegment( + rect: CGRect(x: startX, y: line.frame.minY, width: max(endX - startX, 4), height: line.frame.height), + isRightToLeft: false, characters: lower...last, line: index)) + } + } + if let start = segments.indices.min(by: { segments[$0].characters.lowerBound < segments[$1].characters.lowerBound }) { + segments[start].containsStart = true + } + if let last = segments.map(\.characters.upperBound).max(), + let end = segments.indices.last(where: { segments[$0].characters.upperBound == last }) { + segments[end].containsEnd = true + } + return segments + } + + /// Whether Core Text can have drawn some of the line right to left. A + /// block without a right-to-left character has no such line. + private func hasRightToLeftText(_ line: Line) -> Bool { + isRightToLeft || (paragraphDirection != nil && line.hasRightToLeftRuns) + } + + /// The selected glyphs of a line, as rects of the runs they are in. + /// Whitespace at the end of a line, which Core Text puts outside the + /// line box, is left out. + private func runSegments(of line: Line, at lineIndex: Int, selecting range: Range, + continuesPastLine: Bool) -> [SelectionSegment] { + var segments: [SelectionSegment] = [] + var current: (run: Int, minX: CGFloat, maxX: CGFloat, characters: ClosedRange, rightToLeft: Bool)? + func flush() { + guard let part = current else { return } + current = nil + let rect = CGRect(x: line.frame.minX + part.minX, y: line.frame.minY, width: part.maxX - part.minX, height: line.frame.height) + if let last = segments.last, last.isRightToLeft == part.rightToLeft, abs(last.rect.maxX - rect.minX) < 0.5 { + segments[segments.count - 1].rect = last.rect.union(rect) + segments[segments.count - 1].characters = min(last.characters.lowerBound, part.characters.lowerBound) + ... max(last.characters.upperBound, part.characters.upperBound) + } else { + segments.append(SelectionSegment(rect: rect, isRightToLeft: part.rightToLeft, characters: part.characters, + line: lineIndex)) } } - return rects + for glyph in glyphs(of: line) { + let lower = max(range.lowerBound, line.range.lowerBound, glyph.characters.lowerBound) + let upper = min(range.upperBound, line.range.upperBound, glyph.characters.upperBound) + guard lower < upper else { continue } + let selected = lower.. minX else { continue } + let characters = selected.lowerBound...(selected.upperBound - 1) + if let part = current, part.run == glyph.run { + current = (part.run, min(part.minX, minX), max(part.maxX, maxX), + min(part.characters.lowerBound, characters.lowerBound)...max(part.characters.upperBound, characters.upperBound), + part.rightToLeft) + } else { + flush() + current = (glyph.run, minX, maxX, characters, glyph.rightToLeft) + } + } + flush() + if segments.isEmpty, continuesPastLine { + // Only a line break or spaces: a sliver at the caret shows that they are selected. + let lower = max(range.lowerBound, line.range.lowerBound) + let x = x(forOffset: lower, in: line) + segments.append(SelectionSegment(rect: CGRect(x: isRightToLeft ? x - 4 : x, y: line.frame.minY, width: 4, height: line.frame.height), + isRightToLeft: isRightToLeft, characters: lower...lower, line: lineIndex)) + } + return segments + } + + /// A glyph of a line: the characters it stands for (block offsets), and + /// its left and right edges in the line. + private struct Glyph { + /// More than one character for a ligature. + let characters: Range + let minX: CGFloat + let maxX: CGFloat + let rightToLeft: Bool + let run: Int + + /// The left and right edges of the part of the glyph that stands for + /// the characters of `range`. + func part(_ range: Range, in line: Line) -> (minX: CGFloat, maxX: CGFloat) { + let lower = max(range.lowerBound, characters.lowerBound) + let upper = min(range.upperBound, characters.upperBound) + guard lower > characters.lowerBound || upper < characters.upperBound else { return (minX, maxX) } + let a = edge(before: lower, in: line) + let b = edge(before: upper, in: line) + return (min(a, b), max(a, b)) + } + + /// Where the caret before character `offset` is in the glyph: from + /// Core Text if it puts it inside the glyph, else at an even share. + private func edge(before offset: Int, in line: Line) -> CGFloat { + let start = rightToLeft ? maxX : minX + let end = rightToLeft ? minX : maxX + if offset <= characters.lowerBound { return start } + if offset >= characters.upperBound { return end } + let x = CTLineGetOffsetForStringIndex(line.ctLine, offset - line.indexBase, nil) + if x > minX + 0.01, x < maxX - 0.01 { return x } + return start + (end - start) * CGFloat(offset - characters.lowerBound) / CGFloat(characters.count) + } + } + + /// The glyphs of a line from left to right. + private func glyphs(of line: Line) -> [Glyph] { + var result: [Glyph] = [] + for (runIndex, run) in (CTLineGetGlyphRuns(line.ctLine) as! [CTRun]).enumerated() { + let count = CTRunGetGlyphCount(run) + guard count > 0 else { continue } + var indices = [CFIndex](repeating: 0, count: count) + var positions = [CGPoint](repeating: .zero, count: count) + var advances = [CGSize](repeating: .zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: 0), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: 0), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: 0), &advances) + let rightToLeft = CTRunGetStatus(run).contains(.rightToLeft) + let runRange = CTRunGetStringRange(run) + // A glyph stands for its character and those after it up to the + // next one that a glyph of the run starts at. + let starts = Set(indices).sorted() + var ends: [CFIndex: CFIndex] = [:] + for (position, start) in starts.enumerated() { + ends[start] = position + 1 < starts.count ? starts[position + 1] : max(runRange.location + runRange.length, start + 1) + } + for glyph in 0.. [CGRect] { + let entry = entry(at: index) + let layout = entry.layout + let above = index > 0 ? self.entry(at: index - 1) : nil + let width = max(style.quoteBarWidth, 0) + var bars: [CGRect] = [] + var x: CGFloat = 0 + for (depth, container) in layout.block.containers.enumerated() { + if container == .quote { + var top = entry.y + if let above, Self.shareQuote(above.layout.block, layout.block, at: depth) { top = above.frame.maxY } + bars.append(CGRect(x: layout.isRightToLeft ? layout.width - x - width : x, y: top, width: width, + height: entry.frame.maxY - top)) + } + x += style.width(of: container) + } + return bars + } + // MARK: Offsets and geometry /// The last entry whose `key` is at most `value`, by binary search; @@ -310,7 +333,9 @@ public final class DocumentLayout: @unchecked Sendable { .first } - /// One rect per line covered by `range`, across as many blocks as it spans. + /// One rect per line covered by `range`, across as many blocks as it + /// spans. A line with right-to-left text can have several: one for each + /// stretch of glyphs that go the same way. public func selectionRects(for range: Range) -> [CGRect] { selectionRects(for: range, scroll: .none) } @@ -319,29 +344,110 @@ public final class DocumentLayout: @unchecked Sendable { /// `scroll`. In a block that scrolls, the rects are cut to its box; a rect /// outside the box becomes an empty one at its edge. func selectionRects(for range: Range, scroll: SideScroll) -> [CGRect] { + selectionSegments(for: range, scroll: scroll).map(\.rect) + } + + /// The parts of the selection of `range`, line by line, with their + /// direction, and with blocks scrolled sideways by `scroll` as in + /// `selectionRects(for:scroll:)`. One holds the start of the range, and + /// one the end. + func selectionSegments(for range: Range, scroll: SideScroll = .none) -> [BlockLayout.SelectionSegment] { guard !range.isEmpty, let first = entryIndex(forOffset: range.lowerBound) else { return [] } - var rects: [CGRect] = [] + var segments: [BlockLayout.SelectionSegment] = [] + var start: Int? + var end: Int? for index in first..= range.upperBound { break } let lower = max(range.lowerBound - entry.start, 0) let upper = min(range.upperBound - entry.start, entry.layout.length) guard lower < upper else { continue } - let scrolls = entry.layout.maximumScrollOffset > 0 - let dx = scroll.offset(of: entry.layout) - let box = entry.layout.scrollBox - for rect in entry.layout.selectionRects(for: lower.. CGRect { + var shifted = rect.offsetBy(dx: -scroll.offset(of: entry.layout), dy: entry.y) + guard entry.layout.maximumScrollOffset > 0 else { return shifted } + let box = entry.layout.scrollBox + let minX = min(max(shifted.minX, box.minX), box.maxX) + let maxX = min(max(shifted.maxX, box.minX), box.maxX) + shifted.origin.x = minX + shifted.size.width = maxX - minX + return shifted + } + + /// The rect of the first line of the selection of `range`: all of it, + /// though text of mixed direction splits it into several rects. Nil + /// when nothing is selected. Blocks are scrolled sideways by `scroll` as + /// in `selectionRects(for:scroll:)`. + func firstLineRect(for range: Range, scroll: SideScroll = .none) -> CGRect? { + guard !range.isEmpty, let first = entryIndex(forOffset: range.lowerBound) else { return nil } + for index in first..= range.upperBound { break } + let lower = max(range.lowerBound - entry.start, 0) + let upper = min(range.upperBound - entry.start, entry.layout.length) + guard lower < upper else { continue } + let segments = entry.layout.selectionSegments(for: lower.. Int { + let right = count < 0 ? !right : right + var offset = offset + for _ in 0.., right: Bool) -> Int { + let lower = caretRect(at: range.lowerBound) + let upper = caretRect(at: range.upperBound) + if abs(lower.minY - upper.minY) < 0.5, abs(lower.midX - upper.midX) > 0.5 { + return (upper.midX > lower.midX) == right ? range.upperBound : range.lowerBound + } + return right != isRightToLeft(at: range.lowerBound) ? range.upperBound : range.lowerBound + } + + /// Whether the text at `offset` is in a right-to-left paragraph. + /// `backward` asks about the character before `offset`. + func isRightToLeft(at offset: Int, backward: Bool = false) -> Bool { + guard let index = entryIndex(forOffset: backward ? max(offset - 1, 0) : offset) else { return false } + return entry(at: index).layout.isRightToLeft } /// The top of the first line that differs between `earlier` and this @@ -389,6 +495,8 @@ public final class DocumentLayout: @unchecked Sendable { index += 1 continue } + // The marker and the quote bars, which reach into the gap, moved to the other side. + if new.layout.isRightToLeft != old.layout.isRightToLeft { return min(gapAbove(index, in: self), gapAbove(index, in: earlier)) } if new.layout.table != nil || old.layout.table != nil { return new.y + Self.firstChangedY(in: new.layout, since: old.layout) } @@ -575,20 +683,9 @@ public final class DocumentLayout: @unchecked Sendable { let layout = entry.layout let block = layout.block - // Quote bars, run on through the gap from the block above when it - // is in the same quote. - let above = index > 0 ? self.entry(at: index - 1) : nil + // Quote bars. Square ends, so that segments of one bar meet cleanly. let bar = style.quoteBarColor?.cgColor(dark: dark, highContrast: highContrast) ?? accent - var x: CGFloat = 0 - for (depth, container) in block.containers.enumerated() { - if container == .quote { - var top = frame.minY - if let above, Self.shareQuote(above.layout.block, block, at: depth) { top = above.frame.maxY } - // Square ends, so that segments of one bar meet cleanly. - fill(CGRect(x: x, y: top, width: max(style.quoteBarWidth, 0), height: frame.maxY - top), radius: 0, color: bar) - } - x += style.width(of: container) - } + for rect in quoteBars(at: index) { fill(rect, radius: 0, color: bar) } if frame.minY - overhang > dirtyRect.maxY { break } let box = CGRect(x: layout.contentLeading, y: frame.minY, width: max(frame.width - layout.contentLeading, 0), height: frame.height) diff --git a/Sources/TranscriptKit/Layout/FadeRenderer.swift b/Sources/TranscriptKit/Layout/FadeRenderer.swift index ac08566..d021165 100644 --- a/Sources/TranscriptKit/Layout/FadeRenderer.swift +++ b/Sources/TranscriptKit/Layout/FadeRenderer.swift @@ -85,7 +85,7 @@ final class FadeRenderer { func pixel(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { (value * scale).rounded(rule) / scale } let lines = layout.lines(from: from) - let rightToLeft = lines.map { Self.hasRightToLeftText($0.line.ctLine) } + let rightToLeft = lines.map { $0.line.hasRightToLeftRuns } let definitions = layout.document.linkDefinitions.count var pieces: [FadeFrame.Piece] = [] for fade in fades { @@ -168,8 +168,4 @@ final class FadeRenderer { in: context, text: colors.text, dark: colors.dark, highContrast: colors.highContrast) return context.makeImage() } - - private static func hasRightToLeftText(_ line: CTLine) -> Bool { - (CTLineGetGlyphRuns(line) as! [CTRun]).contains { CTRunGetStatus($0).contains(.rightToLeft) } - } } diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index 917e8d5..98ca7e2 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -13,6 +13,8 @@ struct DecoratedTags { let tag: InlineSpan.CustomTag /// Its place among the block's spans, where outer tags come first. let order: Int + /// Whether its text is right to left: it starts at the right. + let isRightToLeft: Bool /// It keeps together and has no line break in its text, so it can /// stay on one line. @@ -30,20 +32,30 @@ struct DecoratedTags { /// line break), and its padding after it on its last character. Kept /// even while the tag is open, so its end acts like a wider last glyph: /// only the word being written can wrap because of it. + /// + /// Core Text puts the extra advance of a character on its right, also + /// in right-to-left text. So in a block with right-to-left text, a + /// right-to-left tag has the padding before it on its first character, + /// and the character to the left of a tag gets the padding on that side. let kerns: [Int: CGFloat] /// The padding of the tags that start at an offset, added up: a line /// that starts there is moved right by it, since there is no character - /// before it on the line to carry it. + /// before it on the line to carry it. Not in a right-to-left paragraph. let startPadding: [Int: CGFloat] + /// Whether the block has right-to-left text. + let hasRightToLeftText: Bool /// Whether any of the block's tags take padding or draw shapes. static func appear(in block: TranscriptBlock) -> Bool { block.spans.contains { $0.customTag?.shapesText == true } } - /// - Parameter start: only tags that reach this offset or past it are - /// kept: a streaming update lays out only the lines from there on. - init?(_ block: TranscriptBlock, from start: Int = 0) { + /// - Parameters: + /// - start: only tags that reach this offset or past it are kept: a + /// streaming update lays out only the lines from there on. + /// - direction: the direction that the block is typeset with. A tag + /// takes the direction of its first strong character, or this one. + init?(_ block: TranscriptBlock, from start: Int = 0, direction: WritingDirection? = nil) { guard Self.appear(in: block) else { return nil } let text = block.text as NSString var tags: [Tag] = [] @@ -55,9 +67,30 @@ struct DecoratedTags { while textEnd > span.range.lowerBound, text.character(at: textEnd - 1) == 0x0A { textEnd -= 1 } let keepsTogether = custom.decoration.keepsTogether && !(span.range.lowerBound.. 0 else { continue } + if let direction { + // The room on the right of the tag goes on its rightmost + // character. The room on its left goes on the character to + // its left: the one after it in a right-to-left paragraph. + let rightRoom = isRightToLeft ? tag.leadingRoom : tag.padding + let leftRoom = isRightToLeft ? tag.padding : tag.leadingRoom + let rightmost = isRightToLeft ? span.range.lowerBound : textEnd - 1 + let leftNeighbor = direction == .rightToLeft ? textEnd : span.range.lowerBound - 1 + if textEnd > span.range.lowerBound, rightRoom > 0 { kerns[rightmost, default: 0] += rightRoom } + if leftRoom > 0, leftNeighbor >= 0, leftNeighbor < text.length, text.character(at: leftNeighbor) != 0x0A { + kerns[leftNeighbor, default: 0] += leftRoom + } + if direction == .leftToRight, leftRoom > 0 { startPadding[span.range.lowerBound, default: 0] += leftRoom } + continue + } let before = span.range.lowerBound - 1 if before >= 0, text.character(at: before) != 0x0A { kerns[before, default: 0] += tag.leadingRoom } if textEnd > span.range.lowerBound, tag.padding > 0 { kerns[textEnd - 1, default: 0] += tag.padding } @@ -66,6 +99,7 @@ struct DecoratedTags { self.tags = tags self.kerns = kerns self.startPadding = startPadding + hasRightToLeftText = direction != nil } /// Where a line that starts at block offset `start` and would end at @@ -244,14 +278,31 @@ final class LineDecorations: @unchecked Sendable { guard end > start, start - textBase >= 0, start - textBase < text.length else { continue } let isStart = tag.range.lowerBound >= range.lowerBound let isEnd = tag.textEnd <= range.upperBound - // From the glyphs: Core Text puts the caret halfway through - // spacing added after a character, which is where padding is. - let minX = glyphs.start(at: start - indexBase) ?? CTLineGetOffsetForStringIndex(line, start - indexBase, nil) - // At the tag's end, the spacing after its last character is padding, not text. - let maxX = isEnd - ? (glyphs.end(through: end - 1 - indexBase) ?? CTLineGetOffsetForStringIndex(line, end - indexBase, nil)) - - (tags.kerns[end - 1] ?? 0) - : visibleWidth + var minX: CGFloat + var maxX: CGFloat + if tag.isRightToLeft { + // The glyphs of its text, without the spacing on its first + // character, which is padding. Whitespace at the end of the line is left out. + guard let extent = glyphs.extent(of: (start - indexBase)..<(end - indexBase)) else { continue } + minX = max(extent.minX, 0) + maxX = min(extent.maxX - (tags.kerns[start] ?? 0), visibleWidth) + } else { + // From the glyphs: Core Text puts the caret halfway through + // spacing added after a character, which is where padding is. + minX = glyphs.start(at: start - indexBase) ?? CTLineGetOffsetForStringIndex(line, start - indexBase, nil) + // At the tag's end, the spacing after its last character is padding, not text. + maxX = isEnd + ? (glyphs.end(through: end - 1 - indexBase) ?? CTLineGetOffsetForStringIndex(line, end - indexBase, nil)) + - (tags.kerns[end - 1] ?? 0) + : visibleWidth + // A tag with text in both directions: its first and last + // characters can be anywhere in it. + if maxX <= minX, tags.hasRightToLeftText, + let extent = glyphs.extent(of: (start - indexBase)..<(end - indexBase)) { + minX = max(extent.minX, 0) + maxX = min(extent.maxX, visibleWidth) + } + } guard maxX > minX else { continue } // The tag's own font, which a fallback font for an emoji doesn't change. let font = text.attribute(TranscriptStyle.fontKey, at: start - textBase, effectiveRange: nil).map { $0 as! CTFont } @@ -259,8 +310,10 @@ final class LineDecorations: @unchecked Sendable { let ascent = CTFontGetAscent(font) let descent = CTFontGetDescent(font) let textRect = CGRect(x: minX, y: -ascent, width: maxX - minX, height: ascent + descent) - let left = minX - (isStart ? tags.startPadding(of: tag) : 0) - let right = maxX + (isEnd ? tags.endPadding(of: tag) : 0) + let startPadding = isStart ? tags.startPadding(of: tag) : 0 + let endPadding = isEnd ? tags.endPadding(of: tag) : 0 + let left = minX - (tag.isRightToLeft ? endPadding : startPadding) + let right = maxX + (tag.isRightToLeft ? startPadding : endPadding) let rect = CGRect(x: left, y: -ascent, width: right - left, height: ascent + descent) // An animated tag shows its shapes once it has closed, when its // animation brings them in; until then it is plain text. @@ -279,7 +332,7 @@ final class LineDecorations: @unchecked Sendable { ascent: ascent, descent: descent, xHeight: CTFontGetXHeight(font), capHeight: CTFontGetCapHeight(font), underlineOffset: -CTFontGetUnderlinePosition(font), underlineThickness: CTFontGetUnderlineThickness(font), seed: stableHash(tag.tag.name, tag.range.lowerBound, start), - visibleRect: visible, glyphs: glyphBoxes + visibleRect: visible, glyphs: glyphBoxes, isRightToLeft: tag.isRightToLeft ) let showsShapes = animation == nil || !tag.tag.isOpen if let animation, let key, showsShapes { @@ -302,7 +355,8 @@ final class LineDecorations: @unchecked Sendable { if let image = tag.tag.decoration.image, isStart, showsShapes || image.showsDuringAnimation { // Just before the text, centred on its cap height. let capHeight = CTFontGetCapHeight(font) - let imageRect = CGRect(x: minX - image.gap - image.size.width, y: -capHeight / 2 - image.size.height / 2, + let imageX = tag.isRightToLeft ? maxX + image.gap : minX - image.gap - image.size.width + let imageRect = CGRect(x: imageX, y: -capHeight / 2 - image.size.height / 2, width: image.size.width, height: image.size.height) // One that shows during the animation is never left out. images.append((imageRect, image, image.showsDuringAnimation ? nil : key)) @@ -374,6 +428,18 @@ private struct GlyphTable { return found.sorted { $0.stringIndex < $1.stringIndex } } + /// The left edge of the leftmost glyph for a string index in `range`, + /// and the right edge of the rightmost one, its advance included. + func extent(of range: Range) -> (minX: CGFloat, maxX: CGFloat)? { + var result: (minX: CGFloat, maxX: CGFloat)? + for glyph in indices.indices where range.contains(indices[glyph]) { + let minX = positions[glyph] + let maxX = positions[glyph] + advances[glyph] + result = result.map { (min($0.minX, minX), max($0.maxX, maxX)) } ?? (minX, maxX) + } + return result + } + /// The left edge of the first glyph for string index `index` or later. func start(at index: Int) -> CGFloat? { var best: (index: Int, x: CGFloat)? diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index f584585..792adb2 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -63,9 +63,11 @@ public struct TranscriptStyle: Equatable, Sendable { /// Spacing above a list item that follows other list content. public var listItemSpacing: CGFloat = 6 public var codePadding: CGFloat = 12 - /// Indent added by each list item; the marker sits inside it. + /// Indent added by each list item; the marker sits inside it, on the + /// right of right-to-left text. public var listIndent: CGFloat = 24 - /// Indent added by each block quote; its bar sits at the left of it. + /// Indent added by each block quote; its bar sits at the left of it, or + /// at the right of right-to-left text. public var quoteIndent: CGFloat = 14 /// Space between a table cell's border and its text. public var tableCellPadding: CGFloat = 8 @@ -141,7 +143,8 @@ public struct TranscriptStyle: Equatable, Sendable { /// are shown whole or not at all. public var lineLimit: Int? /// Where the lines of paragraphs and headings sit in their column. Lists, - /// quotes, code and tables stay at the leading edge. + /// quotes, code and tables stay at the leading edge. The leading edge is + /// the left edge, or the right edge of a right-to-left paragraph. public var textAlignment: TranscriptTextAlignment = .leading /// Whether the lines of code blocks wrap at the width of the text column. /// On by default. Off, a line of code breaks only where its text has a @@ -392,6 +395,7 @@ public struct TranscriptStyle: Equatable, Sendable { /// The fill behind inline code, a `TranscriptColor`, drawn like a highlight. static let inlineCodeBackgroundKey = NSAttributedString.Key("TranscriptKit.inlineCodeBackground") private static let kernKey = NSAttributedString.Key(kCTKernAttributeName as String) + static let paragraphStyleKey = NSAttributedString.Key(kCTParagraphStyleAttributeName as String) func attributes(for kind: TranscriptBlock.Kind, weight: CGFloat? = nil) -> [NSAttributedString.Key: Any] { var attributes: [NSAttributedString.Key: Any] = [ @@ -405,23 +409,27 @@ public struct TranscriptStyle: Equatable, Sendable { /// The styled text of `block` from UTF-16 offset `start` to its end. func attributedString(for block: TranscriptBlock, from start: Int = 0, images: ImageSizing? = nil, - definitions: [String: String] = [:], kerns: [Int: CGFloat] = [:]) -> NSAttributedString { - attributedString(for: block, range: start.. NSAttributedString { + attributedString(for: block, range: start.., extraTraits: InlineSpan.Traits = [], weight: CGFloat? = nil, images: ImageSizing? = nil, definitions: [String: String] = [:], - kerns: [Int: CGFloat] = [:]) -> NSAttributedString { + kerns: [Int: CGFloat] = [:], direction: WritingDirection? = nil) -> NSAttributedString { let start = range.lowerBound let text = range == 0.. CTParagraphStyle { + var value = direction + return withUnsafeBytes(of: &value) { bytes in + var setting = CTParagraphStyleSetting(spec: .baseWritingDirection, valueSize: MemoryLayout.size, + value: bytes.baseAddress!) + return CTParagraphStyleCreate(&setting, 1) + } + } +} + +/// What a scan of a text found about its direction, so far: the direction +/// of its first strong character (the natural base direction, as the +/// Unicode bidirectional algorithm finds it), and whether it holds any +/// right-to-left character. +/// +/// A scan goes on from where it stopped, so text that grows by appends is +/// not read again. +struct DirectionScan: Equatable, Sendable { + private(set) var firstStrong: WritingDirection? + private(set) var hasRightToLeft = false + /// The UTF-16 length of the text scanned. + private(set) var length = 0 + /// How many isolates (U+2066 to U+2068) are open: the first strong + /// character is not looked for inside them. + private var isolates = 0 + + init() {} + + init(_ text: String) { + scan(text) + } + + /// The direction to set on the text when it is typeset: nil when it has + /// no right-to-left character, as Core Text then lays it out from the + /// left without being told. + var paragraphDirection: WritingDirection? { + hasRightToLeft ? (firstStrong ?? .leftToRight) : nil + } + + /// Scans `text` from `length`, the end of the text scanned before. The + /// text before it must not have changed. + mutating func scan(_ text: String) { + let utf16 = text.utf16 + guard utf16.count > length else { return } + guard firstStrong == nil || !hasRightToLeft else { + length = utf16.count + return + } + var index = utf16.index(utf16.startIndex, offsetBy: length) + while index < utf16.endIndex { + var value = UInt32(utf16[index]) + utf16.formIndex(after: &index) + if UTF16.isLeadSurrogate(UInt16(value)), index < utf16.endIndex, UTF16.isTrailSurrogate(utf16[index]) { + value = 0x10000 + ((value - 0xD800) << 10) + (UInt32(utf16[index]) - 0xDC00) + utf16.formIndex(after: &index) + } + guard let scalar = Unicode.Scalar(value) else { continue } + if Self.isRightToLeftCharacter(scalar) { hasRightToLeft = true } + if firstStrong == nil { + switch value { + case 0x2066...0x2068: isolates += 1 + case 0x2069: isolates = max(isolates - 1, 0) + default: + if isolates == 0 { firstStrong = Self.strongDirection(of: scalar) } + } + } + if firstStrong != nil, hasRightToLeft { break } + } + length = utf16.count + } + + /// Whether the scalar belongs to a right-to-left script, or is a mark or + /// control that makes text right-to-left. + static func isRightToLeftCharacter(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 0x0590...0x08FF, 0xFB1D...0xFDFF, 0xFE70...0xFEFE, 0x10800...0x10FFF, 0x1E800...0x1EFFF: return true + case 0x200F, 0x202B, 0x202E, 0x2067: return true + default: return false + } + } + + /// The direction of a strong character, or nil for one that takes its + /// direction from the text around it: digits, punctuation, spaces, + /// symbols and marks. This is the bidirectional class of the character + /// (L, or R and AL). + static func strongDirection(of scalar: Unicode.Scalar) -> WritingDirection? { + if let exception = exception(for: scalar.value) { return exception.direction } + switch scalar.value { + case 0x200E: return .leftToRight + case 0x200F, 0x061C: return .rightToLeft + // Arabic punctuation and signs that are weak or neutral. + case 0x0600...0x0605, 0x0609, 0x060A, 0x060C, 0x066A...0x066C, 0x06DD, 0x06E9, 0x08E2: return nil + default: break + } + let category = scalar.properties.generalCategory + if isRightToLeftCharacter(scalar) { + switch category { + case .nonspacingMark, .enclosingMark, .decimalNumber, .format, .control: return nil + default: return .rightToLeft + } + } + switch category { + case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter, .spacingMark: + return .leftToRight + default: + return nil + } + } + private static func exception(for value: UInt32) -> (lower: UInt32, upper: UInt32, direction: WritingDirection?)? { + var low = 0 + var high = exceptions.count - 1 + while low <= high { + let mid = (low + high) / 2 + let entry = exceptions[mid] + if value < entry.lower { + high = mid - 1 + } else if value > entry.upper { + low = mid + 1 + } else { + return entry + } + } + return nil + } + + /// The assigned characters, in ranges, whose bidirectional class in + /// Unicode 16.0 is not the one that `strongDirection(of:)` finds from + /// the general category: for example Roman numerals, regional + /// indicators, private use characters and the digits of Indic scripts + /// are L, and some modifier letters are neutral. + private static let exceptions: [(lower: UInt32, upper: UInt32, direction: WritingDirection?)] = [ + (0x02B9, 0x02BA, nil), (0x02C6, 0x02CF, nil), (0x02EC, 0x02EC, nil), (0x0374, 0x0374, nil), + (0x0482, 0x0482, .leftToRight), (0x055A, 0x055F, .leftToRight), (0x0589, 0x0589, .leftToRight), (0x0606, 0x0607, nil), + (0x060E, 0x060F, nil), (0x06DE, 0x06DE, nil), (0x070F, 0x070F, .rightToLeft), (0x07C0, 0x07C9, .rightToLeft), + (0x07F6, 0x07F9, nil), (0x0964, 0x0970, .leftToRight), (0x09E6, 0x09EF, .leftToRight), (0x09F4, 0x09FA, .leftToRight), + (0x09FD, 0x09FD, .leftToRight), (0x0A66, 0x0A6F, .leftToRight), (0x0A76, 0x0A76, .leftToRight), + (0x0AE6, 0x0AF0, .leftToRight), (0x0B66, 0x0B70, .leftToRight), (0x0B72, 0x0B77, .leftToRight), + (0x0BE6, 0x0BF2, .leftToRight), (0x0C66, 0x0C6F, .leftToRight), (0x0C77, 0x0C77, .leftToRight), + (0x0C7F, 0x0C7F, .leftToRight), (0x0C84, 0x0C84, .leftToRight), (0x0CBF, 0x0CBF, .leftToRight), + (0x0CC6, 0x0CC6, .leftToRight), (0x0CE6, 0x0CEF, .leftToRight), (0x0D4F, 0x0D4F, .leftToRight), + (0x0D58, 0x0D5E, .leftToRight), (0x0D66, 0x0D79, .leftToRight), (0x0DE6, 0x0DEF, .leftToRight), + (0x0DF4, 0x0DF4, .leftToRight), (0x0E4F, 0x0E5B, .leftToRight), (0x0ED0, 0x0ED9, .leftToRight), + (0x0F01, 0x0F17, .leftToRight), (0x0F1A, 0x0F34, .leftToRight), (0x0F36, 0x0F36, .leftToRight), + (0x0F38, 0x0F38, .leftToRight), (0x0F85, 0x0F85, .leftToRight), (0x0FBE, 0x0FC5, .leftToRight), + (0x0FC7, 0x0FCC, .leftToRight), (0x0FCE, 0x0FDA, .leftToRight), (0x1040, 0x104F, .leftToRight), + (0x1090, 0x1099, .leftToRight), (0x109E, 0x109F, .leftToRight), (0x10FB, 0x10FB, .leftToRight), + (0x1360, 0x137C, .leftToRight), (0x166D, 0x166E, .leftToRight), (0x16EB, 0x16F0, .leftToRight), + (0x1735, 0x1736, .leftToRight), (0x17D4, 0x17D6, .leftToRight), (0x17D8, 0x17DA, .leftToRight), + (0x17E0, 0x17E9, .leftToRight), (0x1810, 0x1819, .leftToRight), (0x1946, 0x194F, .leftToRight), + (0x19D0, 0x19DA, .leftToRight), (0x1A1E, 0x1A1F, .leftToRight), (0x1A80, 0x1A89, .leftToRight), + (0x1A90, 0x1A99, .leftToRight), (0x1AA0, 0x1AA6, .leftToRight), (0x1AA8, 0x1AAD, .leftToRight), + (0x1B4E, 0x1B6A, .leftToRight), (0x1B74, 0x1B7F, .leftToRight), (0x1BB0, 0x1BB9, .leftToRight), + (0x1BFC, 0x1BFF, .leftToRight), (0x1C3B, 0x1C49, .leftToRight), (0x1C50, 0x1C59, .leftToRight), + (0x1C7E, 0x1C7F, .leftToRight), (0x1CC0, 0x1CC7, .leftToRight), (0x1CD3, 0x1CD3, .leftToRight), + (0x214F, 0x214F, .leftToRight), (0x2160, 0x2182, .leftToRight), (0x2185, 0x2188, .leftToRight), + (0x2336, 0x237A, .leftToRight), (0x2395, 0x2395, .leftToRight), (0x249C, 0x24E9, .leftToRight), + (0x26AC, 0x26AC, .leftToRight), (0x2800, 0x28FF, .leftToRight), (0x2D70, 0x2D70, .leftToRight), (0x2E2F, 0x2E2F, nil), + (0x3007, 0x3007, .leftToRight), (0x3021, 0x3029, .leftToRight), (0x3038, 0x303A, .leftToRight), + (0x3190, 0x319F, .leftToRight), (0x3200, 0x321C, .leftToRight), (0x3220, 0x324F, .leftToRight), + (0x3260, 0x327B, .leftToRight), (0x327F, 0x32B0, .leftToRight), (0x32C0, 0x32CB, .leftToRight), + (0x32D0, 0x3376, .leftToRight), (0x337B, 0x33DD, .leftToRight), (0x33E0, 0x33FE, .leftToRight), + (0xA4FE, 0xA4FF, .leftToRight), (0xA620, 0xA629, .leftToRight), (0xA67F, 0xA67F, nil), (0xA6E6, 0xA6EF, .leftToRight), + (0xA6F2, 0xA6F7, .leftToRight), (0xA717, 0xA71F, nil), (0xA788, 0xA788, nil), (0xA789, 0xA78A, .leftToRight), + (0xA830, 0xA837, .leftToRight), (0xA8CE, 0xA8D9, .leftToRight), (0xA8F8, 0xA8FA, .leftToRight), + (0xA8FC, 0xA8FC, .leftToRight), (0xA900, 0xA909, .leftToRight), (0xA92E, 0xA92F, .leftToRight), + (0xA95F, 0xA95F, .leftToRight), (0xA9C1, 0xA9CD, .leftToRight), (0xA9D0, 0xA9D9, .leftToRight), + (0xA9DE, 0xA9DF, .leftToRight), (0xA9F0, 0xA9F9, .leftToRight), (0xAA50, 0xAA59, .leftToRight), + (0xAA5C, 0xAA5F, .leftToRight), (0xAA77, 0xAA79, .leftToRight), (0xAADE, 0xAADF, .leftToRight), + (0xAAF0, 0xAAF1, .leftToRight), (0xAB5B, 0xAB5B, .leftToRight), (0xABEB, 0xABEB, .leftToRight), + (0xABF0, 0xABF9, .leftToRight), (0xE000, 0xF8FF, .leftToRight), (0xFB29, 0xFB29, nil), (0xFD3E, 0xFD4F, nil), + (0xFDCF, 0xFDCF, nil), (0xFDFD, 0xFDFF, nil), (0x10100, 0x10100, .leftToRight), (0x10102, 0x10102, .leftToRight), + (0x10107, 0x10133, .leftToRight), (0x10137, 0x1013F, .leftToRight), (0x1018D, 0x1018E, .leftToRight), + (0x101D0, 0x101FC, .leftToRight), (0x10320, 0x10323, .leftToRight), (0x10341, 0x10341, .leftToRight), + (0x1034A, 0x1034A, .leftToRight), (0x1039F, 0x1039F, .leftToRight), (0x103D0, 0x103D5, .leftToRight), + (0x104A0, 0x104A9, .leftToRight), (0x1056F, 0x1056F, .leftToRight), (0x1091F, 0x1091F, nil), (0x10B39, 0x10B3F, nil), + (0x10D6E, 0x10D6E, nil), (0x10E60, 0x10E7E, nil), (0x11047, 0x1104D, .leftToRight), (0x11066, 0x1106F, .leftToRight), + (0x110BB, 0x110C1, .leftToRight), (0x110CD, 0x110CD, .leftToRight), (0x110F0, 0x110F9, .leftToRight), + (0x11136, 0x11143, .leftToRight), (0x11174, 0x11175, .leftToRight), (0x111C5, 0x111C8, .leftToRight), + (0x111CD, 0x111CD, .leftToRight), (0x111D0, 0x111D9, .leftToRight), (0x111DB, 0x111DB, .leftToRight), + (0x111DD, 0x111DF, .leftToRight), (0x111E1, 0x111F4, .leftToRight), (0x11238, 0x1123D, .leftToRight), + (0x112A9, 0x112A9, .leftToRight), (0x112F0, 0x112F9, .leftToRight), (0x113D4, 0x113D5, .leftToRight), + (0x113D7, 0x113D8, .leftToRight), (0x1144B, 0x1145B, .leftToRight), (0x1145D, 0x1145D, .leftToRight), + (0x114C6, 0x114C6, .leftToRight), (0x114D0, 0x114D9, .leftToRight), (0x115C1, 0x115D7, .leftToRight), + (0x11641, 0x11643, .leftToRight), (0x11650, 0x11659, .leftToRight), (0x116B9, 0x116B9, .leftToRight), + (0x116C0, 0x116C9, .leftToRight), (0x116D0, 0x116E3, .leftToRight), (0x11730, 0x1173F, .leftToRight), + (0x1183B, 0x1183B, .leftToRight), (0x118E0, 0x118F2, .leftToRight), (0x11944, 0x11946, .leftToRight), + (0x11950, 0x11959, .leftToRight), (0x119E2, 0x119E2, .leftToRight), (0x11A07, 0x11A08, .leftToRight), + (0x11A3F, 0x11A46, .leftToRight), (0x11A9A, 0x11A9C, .leftToRight), (0x11A9E, 0x11AA2, .leftToRight), + (0x11B00, 0x11B09, .leftToRight), (0x11BE1, 0x11BE1, .leftToRight), (0x11BF0, 0x11BF9, .leftToRight), + (0x11C3F, 0x11C3F, .leftToRight), (0x11C41, 0x11C45, .leftToRight), (0x11C50, 0x11C6C, .leftToRight), + (0x11C70, 0x11C71, .leftToRight), (0x11D50, 0x11D59, .leftToRight), (0x11DA0, 0x11DA9, .leftToRight), + (0x11EF7, 0x11EF8, .leftToRight), (0x11F43, 0x11F59, .leftToRight), (0x11FC0, 0x11FD4, .leftToRight), + (0x11FFF, 0x11FFF, .leftToRight), (0x12400, 0x1246E, .leftToRight), (0x12470, 0x12474, .leftToRight), + (0x12FF1, 0x12FF2, .leftToRight), (0x13430, 0x1343F, .leftToRight), (0x16130, 0x16139, .leftToRight), + (0x16A60, 0x16A69, .leftToRight), (0x16A6E, 0x16A6F, .leftToRight), (0x16AC0, 0x16AC9, .leftToRight), + (0x16AF5, 0x16AF5, .leftToRight), (0x16B37, 0x16B3F, .leftToRight), (0x16B44, 0x16B45, .leftToRight), + (0x16B50, 0x16B59, .leftToRight), (0x16B5B, 0x16B61, .leftToRight), (0x16D6D, 0x16D79, .leftToRight), + (0x16E80, 0x16E9A, .leftToRight), (0x1BC9C, 0x1BC9C, .leftToRight), (0x1BC9F, 0x1BC9F, .leftToRight), + (0x1CCD6, 0x1CCEF, .leftToRight), (0x1CF50, 0x1CFC3, .leftToRight), (0x1D000, 0x1D0F5, .leftToRight), + (0x1D100, 0x1D126, .leftToRight), (0x1D129, 0x1D164, .leftToRight), (0x1D16A, 0x1D16C, .leftToRight), + (0x1D183, 0x1D184, .leftToRight), (0x1D18C, 0x1D1A9, .leftToRight), (0x1D1AE, 0x1D1E8, .leftToRight), + (0x1D2C0, 0x1D2D3, .leftToRight), (0x1D2E0, 0x1D2F3, .leftToRight), (0x1D360, 0x1D378, .leftToRight), + (0x1D800, 0x1D9FF, .leftToRight), (0x1DA37, 0x1DA3A, .leftToRight), (0x1DA6D, 0x1DA74, .leftToRight), + (0x1DA76, 0x1DA83, .leftToRight), (0x1DA85, 0x1DA8B, .leftToRight), (0x1E140, 0x1E149, .leftToRight), + (0x1E14F, 0x1E14F, .leftToRight), (0x1E2F0, 0x1E2F9, .leftToRight), (0x1E4F0, 0x1E4F9, .leftToRight), + (0x1E5F1, 0x1E5FA, .leftToRight), (0x1E5FF, 0x1E5FF, .leftToRight), (0x1E950, 0x1E959, .rightToLeft), + (0x1EEF0, 0x1EEF1, nil), (0x1F110, 0x1F12E, .leftToRight), (0x1F130, 0x1F169, .leftToRight), + (0x1F170, 0x1F1AC, .leftToRight), (0x1F1E6, 0x1F202, .leftToRight), (0x1F210, 0x1F23B, .leftToRight), + (0x1F240, 0x1F248, .leftToRight), (0x1F250, 0x1F251, .leftToRight), (0xF0000, 0xFFFFD, .leftToRight), + (0x100000, 0x10FFFD, .leftToRight) + ] +} diff --git a/Sources/TranscriptKit/Markdown/BlockParser.swift b/Sources/TranscriptKit/Markdown/BlockParser.swift index f16a775..6a6b625 100644 --- a/Sources/TranscriptKit/Markdown/BlockParser.swift +++ b/Sources/TranscriptKit/Markdown/BlockParser.swift @@ -18,7 +18,7 @@ enum BlockParser { /// `fence` is nil for an indented code block. case code(language: String?, fence: Character?, fenceLength: Int, indent: Int, closed: Bool) case rule - case table(alignments: [TranscriptTable.Alignment]) + case table(alignments: [TranscriptTable.Alignment], sided: Set) /// Display math that a line starting with `\[` or `$$` opened, until /// `closer` ends it. Its lines are kept as written. case math(closer: String, closed: Bool) @@ -110,9 +110,9 @@ enum BlockParser { } /// Turns a one-line paragraph into a table with that line as its header. - mutating func becomeTable(alignments: [TranscriptTable.Alignment]) { + mutating func becomeTable(alignments: [TranscriptTable.Alignment], sided: Set) { let header = lastLine ?? "" - kind = .table(alignments: alignments) + kind = .table(alignments: alignments, sided: sided) committedSource = [] lastLine = nil lastLineUnits = [] @@ -480,9 +480,9 @@ enum BlockParser { return } if canContinue, sameContext, let last = blocks.last, last.couldBecomeTable, - let alignments = BlockParser.delimiterRow(leaf), - alignments.count == BlockParser.tableCells(last.lastLine ?? "").count { - blocks[blocks.count - 1].becomeTable(alignments: alignments) + let delimiters = BlockParser.delimiterRow(leaf), + delimiters.alignments.count == BlockParser.tableCells(last.lastLine ?? "").count { + blocks[blocks.count - 1].becomeTable(alignments: delimiters.alignments, sided: delimiters.sided) canContinue = false tableOpen = true return @@ -1074,18 +1074,21 @@ enum BlockParser { } /// The column alignments if `content` is a delimiter row such as - /// "| --- | :---: | ---: |". - static func delimiterRow(_ content: Substring) -> [TranscriptTable.Alignment]? { + /// "| --- | :---: | ---: |", and the columns with a colon on one side + /// only (see `TranscriptTable.sidedColumns`). + static func delimiterRow(_ content: Substring) -> (alignments: [TranscriptTable.Alignment], sided: Set)? { guard content.utf8.contains(UInt8(ascii: "-")), content.allSatisfy({ "|:- \t".contains($0) }) else { return nil } let cells = tableCells(String(content)) var alignments: [TranscriptTable.Alignment] = [] + var sided = Set() for cell in cells { let core = trimmingSpaceAndTab(Substring(cell)) guard core.utf8.contains(UInt8(ascii: "-")), core.dropFirst().dropLast().allSatisfy({ $0 == "-" }) || core.count <= 2 else { return nil } let left = core.hasPrefix(":") let right = core.hasSuffix(":") + if left != right { sided.insert(alignments.count) } alignments.append(left && right ? .center : (right ? .trailing : .leading)) } - return alignments.isEmpty ? nil : alignments + return alignments.isEmpty ? nil : (alignments, sided) } } diff --git a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift index 3eabdf1..78ae501 100644 --- a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift +++ b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift @@ -167,8 +167,8 @@ public struct MarkdownStreamParser: Sendable { containers: raw.containers, marker: raw.marker) case .rule: return TranscriptBlock(id: id, kind: .rule, text: "", containers: raw.containers, marker: raw.marker) - case .table(let alignments): - return makeTable(&raw, id: id, alignments: alignments, open: open, completeRows: completeRows) + case .table(let alignments, let sided): + return makeTable(&raw, id: id, alignments: alignments, sided: sided, open: open, completeRows: completeRows) case .math(let closer, let closed): let source = raw.mathLines.joined(separator: "\n") let tex = closed ? source.dropFirst(2).dropLast(closer.count).trimmingCharacters(in: .whitespacesAndNewlines) : "" @@ -202,7 +202,7 @@ public struct MarkdownStreamParser: Sendable { /// rows are padded or cut to the column count; a row still being written /// shows only the cells it has so far, so its text only grows. private func makeTable(_ raw: inout BlockParser.RawBlock, id: String, alignments: [TranscriptTable.Alignment], - open: Bool, completeRows: Int) -> TranscriptBlock { + sided: Set, open: Bool, completeRows: Int) -> TranscriptBlock { let columns = alignments.count var text: [UInt16] = [] var spans: [InlineSpan] = [] @@ -238,7 +238,8 @@ public struct MarkdownStreamParser: Sendable { } rows.append(ranges) } - let table = TranscriptTable(alignments: alignments, rows: rows) + var table = TranscriptTable(alignments: alignments, rows: rows) + table.sidedColumns = sided return TranscriptBlock(id: id, kind: .table(table), text: String(decoding: text, as: UTF16.self), spans: spans, containers: raw.containers, marker: raw.marker) } diff --git a/Sources/TranscriptKit/Model/TranscriptDocument.swift b/Sources/TranscriptKit/Model/TranscriptDocument.swift index c4d9d2b..4eb56b3 100644 --- a/Sources/TranscriptKit/Model/TranscriptDocument.swift +++ b/Sources/TranscriptKit/Model/TranscriptDocument.swift @@ -141,6 +141,10 @@ public struct TranscriptTable: Equatable, Sendable { public var alignments: [Alignment] /// Cell ranges, row by row; the first row is the header. public var rows: [[Range]] + /// The columns whose delimiter cell has a colon on one side only, as in + /// ":---" or "---:". Their alignment is a side of the screen, the left + /// or the right, so a right-to-left table does not mirror it. + var sidedColumns: Set = [] public init(alignments: [Alignment], rows: [[Range]]) { self.alignments = alignments @@ -153,7 +157,7 @@ public struct TranscriptTable: Equatable, Sendable { /// end, and the last cell perhaps longer: the structure of a table whose /// text grew at its end. func isExtended(by newer: TranscriptTable) -> Bool { - guard alignments == newer.alignments, newer.rows.count >= rows.count else { return false } + guard alignments == newer.alignments, sidedColumns == newer.sidedColumns, newer.rows.count >= rows.count else { return false } guard let lastRow = rows.indices.last else { return true } for index in 0.. 0 { - result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.isStart, - closedRight: fragment.isEnd, forFill: false), + result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.closesLeft, + closedRight: fragment.closesRight, forFill: false), stroke: border, lineWidth: borderWidth)) } return result @@ -375,8 +383,8 @@ struct UnderlineRecipe: TranscriptShapeRecipe { let bottom = fragment.descent * 0.55 + offset let top = bottom - height // Overshoots the text a little at the tag's ends, as a quick stroke does. - let start = text.minX - (fragment.isStart ? 2 : 0) - let end = text.maxX + (fragment.isEnd ? 2 : 0) + let start = text.minX - (fragment.closesLeft ? 2 : 0) + let end = text.maxX + (fragment.closesRight ? 2 : 0) let length = max(end - start, 0) let slant: CGFloat = min(3, length / 3) let phase1 = CGFloat(fragment.seed & 0xFFFF) / 0xFFFF * 2 * .pi @@ -396,8 +404,8 @@ struct UnderlineRecipe: TranscriptShapeRecipe { } distances.append(length) let path = CGMutablePath() - let startSlant = fragment.isStart ? slant : 0 - let endSlant = fragment.isEnd ? slant : 0 + let startSlant = fragment.closesLeft ? slant : 0 + let endSlant = fragment.closesRight ? slant : 0 path.move(to: CGPoint(x: start + startSlant, y: topEdge(0))) for d in distances.dropFirst() { path.addLine(to: CGPoint(x: start + min(d, length), y: topEdge(d))) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index f5efa98..0480dda 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1828,8 +1828,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD onMainThread { let start = self.offset(of: position) switch direction { - case .left: return TranscriptTextPosition(offset: clamp(start - offset)) - case .right: return TranscriptTextPosition(offset: clamp(start + offset)) + case .left, .right: + return TranscriptTextPosition(offset: currentLayout.offset(from: clamp(start), movingRight: direction == .right, by: offset)) case .up, .down: let caret = currentLayout.caretRect(at: start, scroll: sideScroll) let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) @@ -1854,8 +1854,10 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD onMainThread { let range = self.range(of: range) switch direction { - case .left, .up: return TranscriptTextPosition(offset: range.lowerBound) - case .right, .down: return TranscriptTextPosition(offset: range.upperBound) + case .left, .right: + return TranscriptTextPosition(offset: currentLayout.farthestOffset(in: range, right: direction == .right)) + case .up: return TranscriptTextPosition(offset: range.lowerBound) + case .down: return TranscriptTextPosition(offset: range.upperBound) @unknown default: return nil } } @@ -1865,8 +1867,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD onMainThread { let start = offset(of: position) switch direction { - case .left, .up: return TranscriptTextRange(range: clamp(start - 1).. CGRect { onMainThread { let range = self.range(of: range) - return currentLayout.selectionRects(for: range, scroll: sideScroll).first + return currentLayout.firstLineRect(for: range, scroll: sideScroll) ?? currentLayout.caretRect(at: range.lowerBound, scroll: sideScroll) } } nonisolated public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { onMainThread { - let rects = currentLayout.selectionRects(for: self.range(of: range), scroll: sideScroll) - return rects.enumerated().map { index, rect in - TranscriptSelectionRect(rect: rect, containsStart: index == 0, containsEnd: index == rects.count - 1) + currentLayout.selectionSegments(for: self.range(of: range), scroll: sideScroll).map { segment in + TranscriptSelectionRect(rect: segment.rect, writingDirection: segment.isRightToLeft ? .rightToLeft : .leftToRight, + containsStart: segment.containsStart, containsEnd: segment.containsEnd) } } } @@ -1942,7 +1947,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } nonisolated public func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection { - .leftToRight + onMainThread { + currentLayout.isRightToLeft(at: clamp(offset(of: position)), backward: direction == .backward) ? .rightToLeft : .leftToRight + } } nonisolated public func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} @@ -2045,18 +2052,20 @@ final class TranscriptTextRange: UITextRange { final class TranscriptSelectionRect: UITextSelectionRect { private nonisolated let storedRect: CGRect + private nonisolated let storedWritingDirection: NSWritingDirection private nonisolated let storedContainsStart: Bool private nonisolated let storedContainsEnd: Bool - init(rect: CGRect, containsStart: Bool, containsEnd: Bool) { + init(rect: CGRect, writingDirection: NSWritingDirection, containsStart: Bool, containsEnd: Bool) { storedRect = rect + storedWritingDirection = writingDirection storedContainsStart = containsStart storedContainsEnd = containsEnd super.init() } nonisolated override var rect: CGRect { storedRect } - nonisolated override var writingDirection: NSWritingDirection { .leftToRight } + nonisolated override var writingDirection: NSWritingDirection { storedWritingDirection } nonisolated override var containsStart: Bool { storedContainsStart } nonisolated override var containsEnd: Bool { storedContainsEnd } nonisolated override var isVertical: Bool { false } diff --git a/Tests/TranscriptKitTests/AccessibilityTests.swift b/Tests/TranscriptKitTests/AccessibilityTests.swift index 538ce24..9f93649 100644 --- a/Tests/TranscriptKitTests/AccessibilityTests.swift +++ b/Tests/TranscriptKitTests/AccessibilityTests.swift @@ -145,6 +145,21 @@ private func items(_ markdown: String, width: CGFloat = 300) -> [AccessibilityIt #expect(table.cells.allSatisfy { list[1].frame.insetBy(dx: -0.5, dy: -0.5).contains($0.frame) }) } +@Test func theCellsOfARightToLeftTableAreWhereTheirTextIs() throws { + let layout = DocumentLayout(document: MarkdownStreamParser.document(from: "| שם | ערך |\n| --- | --- |\n| א | ב |"), width: 300) + let block = layout.entry(at: 0).layout + #expect(block.isRightToLeft) + let grid = try #require(block.table) + let table = try #require(layout.accessibilityItems().first?.table) + #expect(table.cells.map(\.label) == ["שם", "ערך", "א", "ב"]) + // The first column is the one on the right. + #expect(table.cells[0].frame.minX >= table.cells[1].frame.maxX - 0.5) + for cell in table.cells { + let line = block.lines[grid.cellLines[cell.row][cell.column].lowerBound] + #expect(cell.frame.minX <= line.frame.minX && line.frame.maxX <= cell.frame.maxX, "\(cell.label)") + } +} + @Test func aTableThatStreamsInChangesTheShapeWithEachCell() { var parser = MarkdownStreamParser() parser.append("| A | B |\n| - | - |\n| 1 |") diff --git a/Tests/TranscriptKitTests/DecorationShapeTests.swift b/Tests/TranscriptKitTests/DecorationShapeTests.swift index 9d64727..b99cd64 100644 --- a/Tests/TranscriptKitTests/DecorationShapeTests.swift +++ b/Tests/TranscriptKitTests/DecorationShapeTests.swift @@ -465,3 +465,117 @@ private func linesHolding(_ layout: DocumentLayout, tagAt offset: Int) -> [Range #expect(try lineCount("whole") == 1) #expect(try lineCount("pill") > 1) } + +// MARK: Right-to-left text + +@Test func rightToLeftPaddingMakesRoomAndPillsGetTheirBox() throws { + let padded = layout("שאל אנה עכשיו") + let plain = layout("שאל אנה עכשיו") + let line = padded.entry(at: 0).layout.lines[0] + let plainLine = plain.entry(at: 0).layout.lines[0] + #expect(abs(line.frame.width - plainLine.frame.width - 12) < 0.01) + let decorations = try #require(line.decorations) + #expect(decorations.behind.count == 2) + let box = decorations.behind[0].path.boundingBoxOfPath + // Without padding, the name is from the caret after it, on the left, + // to the caret before it, on the right. + let left = CTLineGetOffsetForStringIndex(plainLine.ctLine, 7, nil) + let right = CTLineGetOffsetForStringIndex(plainLine.ctLine, 4, nil) + #expect(abs(box.minX - left) <= 1) + #expect(abs(box.maxX - (right + 12)) <= 1) + let y = line.frame.midY + #expect(padded.link(at: CGPoint(x: line.frame.minX + box.minX + 1, y: y)) == "app://ana") + #expect(padded.link(at: CGPoint(x: line.frame.minX + box.maxX - 1, y: y)) == "app://ana") +} + +@Test func rightToLeftTagInLeftToRightTextGetsRoomOnBothSides() throws { + let padded = layout("Ask אנה now") + let plain = layout("Ask אנה now") + let line = padded.entry(at: 0).layout.lines[0] + let plainLine = plain.entry(at: 0).layout.lines[0] + #expect(abs(line.frame.width - plainLine.frame.width - 12) < 0.01) + let box = try #require(line.decorations).behind[0].path.boundingBoxOfPath + // The glyphs of the name in the line without padding. + var glyphs: [CGFloat] = [] + for run in CTLineGetGlyphRuns(plainLine.ctLine) as! [CTRun] { + let count = CTRunGetGlyphCount(run) + var indices = [CFIndex](repeating: 0, count: count) + var positions = [CGPoint](repeating: .zero, count: count) + var advances = [CGSize](repeating: .zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: 0), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: 0), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: 0), &advances) + for glyph in 0..\(words)סוף זנב", width: 200) + let lines = layout.entry(at: 0).layout.lines.filter { $0.decorations != nil } + try #require(lines.count >= 3) + let rects = lines.map { $0.decorations!.behind[0].path.boundingBoxOfPath } + let fills = lines.compactMap { $0.decorations!.behind[0].fill } + #expect(fills.first == FragmentProbe.start) + #expect(fills.last == FragmentProbe.end) + // The tag starts at the right of its first line and goes on to its left end. + #expect(rects[0].minX < 1) + #expect(rects[0].maxX < lines[0].frame.width - 20) + // It ends on the last line, from the right end of the line. + #expect(abs(rects[rects.count - 1].maxX - lines[lines.count - 1].frame.width) < 1) + #expect(rects[rects.count - 1].minX > 20) +} + +@Test func pillsCloseTheSideWhereARightToLeftTagStarts() { + let rect = CGRect(x: 0, y: -14, width: 40, height: 18) + func fragment(rightToLeft: Bool) -> TranscriptFragment { + TranscriptFragment(textRect: rect, rect: rect, isStart: true, isEnd: false, ascent: 14, descent: 4, xHeight: 8, + capHeight: 11, underlineOffset: 2, underlineThickness: 1, seed: 1, isRightToLeft: rightToLeft) + } + #expect(fragment(rightToLeft: false).closesLeft && !fragment(rightToLeft: false).closesRight) + #expect(fragment(rightToLeft: true).closesRight && !fragment(rightToLeft: true).closesLeft) + let pill = TranscriptDecoration.Shape.pill(fill: indigo) + let ltr = pill.paths(for: fragment(rightToLeft: false))[0].path + let rtl = pill.paths(for: fragment(rightToLeft: true))[0].path + // The closed end is round: its corner is not filled. + #expect(!ltr.contains(CGPoint(x: 0.5, y: -13.5)) && ltr.contains(CGPoint(x: 39.5, y: -13.5))) + #expect(!rtl.contains(CGPoint(x: 39.5, y: -13.5)) && rtl.contains(CGPoint(x: 0.5, y: -13.5))) +} + +private let hebrewWords = String(repeating: "מילה ", count: 20) +private let streamedTags: [String] = [ + "פתח \(hebrewWords)סוף זנב ועוד מילים", + "Lead \(hebrewWords)סוף tail", + "פתח abc \(hebrewWords) זנב", +] + +@Test(arguments: streamedTags) +func streamedRightToLeftTagsAreLaidOutAsAWhole(markdown: String) { + var parser = MarkdownStreamParser(idPrefix: "d", tags: shapeTags) + var layout: DocumentLayout? + var text = Substring(markdown) + while !text.isEmpty { + parser.append(String(text.prefix(5))) + text = text.dropFirst(5) + layout = DocumentLayout(document: parser.document, width: 200, reusing: layout) + } + let fresh = DocumentLayout(document: parser.document, width: 200) + func summary(_ layout: DocumentLayout) -> [String] { + layout.entry(at: 0).layout.lines.map { line in + "\(line.range) \(line.frame) " + (line.decorations?.behind.map { "\($0.path.boundingBoxOfPath)" } ?? []).joined() + } + } + #expect(summary(layout!) == summary(fresh)) +} + +@Test func aTagWithTextInBothDirectionsKeepsItsShapes() throws { + let layout = layout("שלום abc אבג וכולם") + let decorations = try #require(layout.entry(at: 0).layout.lines[0].decorations) + #expect(!decorations.behind.isEmpty) + #expect(decorations.behind[0].path.boundingBoxOfPath.width > 20) +} diff --git a/Tests/TranscriptKitTests/FadeTests.swift b/Tests/TranscriptKitTests/FadeTests.swift index 77dc2bf..9cf45b1 100644 --- a/Tests/TranscriptKitTests/FadeTests.swift +++ b/Tests/TranscriptKitTests/FadeTests.swift @@ -187,6 +187,37 @@ func fadePiecesAndTheDrawingMakeUpTheText(chunk: Int, centered: Bool) { #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") } +/// Fades in right-to-left text, and in a block that turns right to left +/// when its first letter arrives, make up the text as it is drawn. +@Test(arguments: [3, 8]) +func fadePiecesMakeUpRightToLeftText(chunk: Int) { + let markdown = """ + # כותרת בעברית + + שלום עולם, זה משפט ארוך בעברית עם **מילה מודגשת** שעובר לשורה הבאה ברוחב הזה. + + > 2024: ציטוט ארוך בעברית שעובר לשורה השנייה + + English, then עברית at the end of the line. + + """ + var checked = 0 + var mismatches: [String] = [] + var step = 0 + streamFades(markdown, chunk: chunk) { output in + step += 1 + guard step % 2 == 0 else { return } + let document = documentDifference(output, scale: 2) + let tail = tailDifference(output, scale: 2) ?? (0, 0) + if document.count + tail.count > 0, mismatches.count < 3 { + mismatches.append("step \(step), fading from \(output.hidden.fadingFrom.map(String.init) ?? "-"): document \(document), tail \(tail)") + } + checked += 1 + } + #expect(checked > 10) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") +} + @Test func theFrontierMovesALineAtATimeAndItsRowsAreDrawnAgain() { var froms: [Int?] = [] var redraws = 0 diff --git a/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift new file mode 100644 index 0000000..584203f --- /dev/null +++ b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift @@ -0,0 +1,197 @@ +import CoreGraphics +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +private let hebrew = String(repeating: "שלום עולם, זה משפט ארוך בעברית. ", count: 5) +private let arabic = "مرحبا بالعالم" + +private func layout(_ markdown: String, width: CGFloat = 300, style: TranscriptStyle = .init()) -> DocumentLayout { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width, style: style) +} + +/// Each line's text range and frame, for comparing two layouts. +private func lineSummary(_ layout: BlockLayout) -> [String] { + layout.lines.map { "\($0.range) \($0.frame) \($0.baseline)" } +} + +// MARK: Lines + +@Test func rightToLeftParagraphLinesEndAtTheRightEdge() { + let block = layout(hebrew).entry(at: 0).layout + #expect(block.isRightToLeft) + #expect(block.lines.count > 2) + for line in block.lines { + #expect(abs(line.frame.maxX - 300) < 0.01) + // The first character of the line is at its right end. + #expect(abs(block.caretRect(atOffset: line.range.lowerBound).midX - line.frame.maxX) < 1) + } +} + +@Test func leftToRightTextGetsNoDirection() { + let block = layout("Plain text that wraps onto more than one line of the layout, with digits 123.").entry(at: 0).layout + #expect(block.paragraphDirection == nil) + #expect(!block.isRightToLeft) + #expect(block.lines.allSatisfy { $0.frame.minX == 0 }) + let text = TranscriptStyle().attributedString(for: block.block) + #expect(text.attribute(TranscriptStyle.paragraphStyleKey, at: 0, effectiveRange: nil) == nil) +} + +@Test func eachParagraphHasItsOwnDirection() { + let document = layout("Hello world\n\n\(arabic)\n\nThe word \(arabic) in English") + #expect((0..<3).map { document.entry(at: $0).layout.isRightToLeft } == [false, true, false]) + #expect(document.entry(at: 2).layout.paragraphDirection == .leftToRight) + #expect(document.entry(at: 2).layout.lines[0].frame.minX == 0) +} + +@Test func alignmentIsFromTheLeadingEdgeOfTheParagraph() { + var style = TranscriptStyle() + style.textAlignment = .trailing + let trailing = layout(arabic, style: style).entry(at: 0).layout.lines[0] + #expect(trailing.frame.minX == 0) + style.textAlignment = .center + let centered = layout(arabic, style: style).entry(at: 0).layout.lines[0] + #expect(abs((300 - centered.frame.maxX) - centered.frame.minX) <= 1) +} + +@Test func codeStaysLeftToRight() { + let block = layout("```\nlet name = \"\(arabic)\"\n```").entry(at: 0).layout + #expect(block.paragraphDirection == .leftToRight) + #expect(!block.isRightToLeft) + #expect(block.lines[0].frame.minX == TranscriptStyle().codePadding) +} + +@Test func truncatedRightToLeftLineKeepsItsWidth() { + var style = TranscriptStyle() + style.lineLimit = 1 + let line = layout(hebrew, style: style).entry(at: 0).layout.lines[0] + #expect(abs(line.frame.maxX - 300) < 0.01) + #expect(line.frame.width > 250) +} + +// MARK: Lists and quotes + +@Test func listMarkersAndQuoteBarsGoOnTheRight() { + let style = TranscriptStyle() + let document = layout("- \(arabic)\n- [ ] \(arabic)\n\n> \(arabic)\n\n1. \(arabic)") + let bullet = document.entry(at: 0).layout + guard case .text(_, let origin)? = bullet.marker else { Issue.record("no bullet"); return } + #expect(bullet.lines[0].frame.maxX == 300 - style.listIndent) + #expect(origin.x > bullet.lines[0].frame.maxX) + #expect(origin.x < 300) + + guard case .checkbox(let box, _)? = document.entry(at: 1).layout.marker else { Issue.record("no checkbox"); return } + #expect(box.minX > document.entry(at: 1).layout.lines[0].frame.maxX) + #expect(box.maxX <= 300) + + let quote = document.entry(at: 2).layout + #expect(quote.lines[0].frame.maxX == 300 - style.quoteIndent) + #expect(document.quoteBars(at: 2).map(\.minX) == [297]) + + // The number's period is on the side of the text. + guard case .text(let number, _)? = document.entry(at: 3).layout.marker else { Issue.record("no number"); return } + let runs = CTLineGetGlyphRuns(number) as! [CTRun] + #expect(CTRunGetStringRange(runs[0]).location == 1) +} + +@Test func leftToRightQuoteBarsStayOnTheLeft() { + let document = layout("> quoted\n>\n> > nested") + #expect(document.quoteBars(at: 0).map(\.minX) == [0]) + #expect(document.quoteBars(at: 1).map(\.minX) == [0, TranscriptStyle().quoteIndent]) +} + +// MARK: Tables + +@Test func rightToLeftTableStartsOnTheRight() { + let document = layout("| \(arabic) | ب |\n|---|---|\n| א | ב |") + let block = document.entry(at: 0).layout + #expect(block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + #expect(table.columnX == table.columnX.sorted()) + #expect(table.columnX.last == 300) + let first = block.lines[table.cellLines[0][0].lowerBound] + let second = block.lines[table.cellLines[0][1].lowerBound] + #expect(first.frame.minX > second.frame.minX) + // A point in the right column hits the first cell. + let offset = block.closestOffset(to: CGPoint(x: first.frame.midX, y: first.frame.midY)) + #expect(first.range.contains(offset) || offset == first.range.upperBound) + #expect(table.minimumWidths[0].allSatisfy { $0 > TranscriptStyle().tableCellPadding * 2 }) +} + +@Test func columnAlignedToASideKeepsThatSideInRightToLeftText() { + let padding = TranscriptStyle().tableCellPadding + // ":---" is left, "---:" is right, and "---" is the leading edge: the right. + let markdown = "| א | ב | ג |\n|:---|---:|---|\n| אחת ארוכה מאוד | שתיים ארוכה מאוד | שלוש ארוכה מאוד |" + let block = layout(markdown, width: 400).entry(at: 0).layout + #expect(block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + let count = table.columnX.count + func cell(_ column: Int) -> (line: BlockLayout.Line, left: CGFloat, right: CGFloat) { + (block.lines[table.cellLines[0][column].lowerBound], table.columnX[count - 2 - column], table.columnX[count - 1 - column]) + } + let left = cell(0) + #expect(abs(left.line.frame.minX - (left.left + padding)) < 0.5) + #expect(left.line.frame.maxX < left.right - padding - 1) + let right = cell(1) + #expect(abs(right.line.frame.maxX - (right.right - padding)) < 0.5) + #expect(right.line.frame.minX > right.left + padding + 1) + let leading = cell(2) + #expect(abs(leading.line.frame.maxX - (leading.right - padding)) < 0.5) + + // The same marks in left-to-right text. + let english = layout("| a | b |\n|:---|---:|\n| one long text | two long text |", width: 400).entry(at: 0).layout + guard let grid = english.table else { Issue.record("no table"); return } + let first = english.lines[grid.cellLines[0][0].lowerBound] + let second = english.lines[grid.cellLines[0][1].lowerBound] + #expect(abs(first.frame.minX - (grid.columnX[0] + padding)) < 0.5) + #expect(abs(second.frame.maxX - (grid.columnX[2] - padding)) < 0.5) +} + +@Test func eachTableCellKeepsTheDirectionOfItsOwnText() { + let block = layout("| Word | Meaning |\n|---|---|\n| \(arabic)! | hello |").entry(at: 0).layout + #expect(!block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + // In right-to-left text, the "!" at the end is drawn at the left. + let cell = block.lines[table.cellLines[1][0].lowerBound] + let runs = CTLineGetGlyphRuns(cell.ctLine) as! [CTRun] + #expect(CTRunGetStringRange(runs[0]).location == (arabic as NSString).length) +} + +// MARK: Streaming + +private func streamed(_ markdown: String, chunk: Int, width: CGFloat = 300) -> (grown: DocumentLayout, fresh: DocumentLayout) { + var parser = MarkdownStreamParser(idPrefix: "s") + var layout: DocumentLayout? + var text = Substring(markdown) + while !text.isEmpty { + parser.append(String(text.prefix(chunk))) + text = text.dropFirst(chunk) + layout = DocumentLayout(document: parser.document, width: width, reusing: layout) + } + return (layout!, DocumentLayout(document: parser.document, width: width)) +} + +private let hebrewTable = "| מילה | פירוש |\n|---|---|\n" + (1...8).map { "| שורה \($0) | \(String(repeating: "מילה ", count: $0)) |" }.joined(separator: "\n") + +@Test(arguments: [hebrew, "2024: " + hebrew, "Some English first, then " + hebrew, "- " + hebrew, "> 12 " + hebrew, hebrewTable]) +func streamedRightToLeftTextIsLaidOutAsAWhole(markdown: String) { + let (grown, fresh) = streamed(markdown, chunk: 7) + #expect(grown.entryCount == fresh.entryCount) + for index in 0.. 12 ") + let second = MarkdownStreamParser.document(from: "Intro\n\n> 12 \(arabic)") + let earlier = DocumentLayout(document: first, width: 300) + let later = DocumentLayout(document: second, width: 300, reusing: earlier) + #expect(!earlier.entry(at: 1).layout.isRightToLeft) + #expect(later.entry(at: 1).layout.isRightToLeft) + #expect(later.changes(since: earlier).top <= earlier.entry(at: 0).frame.maxY) +} diff --git a/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift new file mode 100644 index 0000000..e1b131a --- /dev/null +++ b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift @@ -0,0 +1,220 @@ +import CoreGraphics +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +private let hebrew = String(repeating: "שלום עולם, זה משפט ארוך בעברית. ", count: 5) + +private func layout(_ markdown: String, width: CGFloat = 300) -> DocumentLayout { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width) +} + +// MARK: Selection and hit testing + +@Test func directionIsFoundByOffset() { + let document = layout("Hello world\n\nمرحبا بالعالم") + let start = document.entry(at: 1).start + #expect(document.isRightToLeft(at: start)) + #expect(!document.isRightToLeft(at: start, backward: true)) + #expect(document.isRightToLeft(at: start + 1, backward: true)) + #expect(!document.isRightToLeft(at: 0)) +} + +@Test func caretsHitTestBackInRightToLeftText() { + let document = layout(hebrew) + for offset in stride(from: 0, to: document.length, by: 5) { + let rect = document.caretRect(at: offset) + let hit = document.closestOffset(to: CGPoint(x: rect.midX, y: rect.midY)) + #expect(abs(hit - offset) <= 1, "offset \(offset) hit-tested to \(hit)") + } + // Right of a line is its start; left of it is its end. + let line = document.entry(at: 0).layout.lines[0] + #expect(document.closestOffset(to: CGPoint(x: 299, y: line.frame.midY)) == 0) + #expect(document.closestOffset(to: CGPoint(x: 1, y: line.frame.midY)) == line.range.upperBound - 1) +} + +@Test func rightToLeftSelectionStartsOnTheRight() { + let document = layout(hebrew) + let line = document.entry(at: 0).layout.lines[0] + let segments = document.selectionSegments(for: 0..<4) + #expect(segments.count == 1) + #expect(segments[0].isRightToLeft) + #expect(abs(segments[0].rect.maxX - line.frame.maxX) < 0.5) + #expect(segments[0].containsStart && segments[0].containsEnd) + + let all = document.selectionSegments(for: 0..= line.frame.minX && $0.rect.maxX <= line.frame.maxX + 0.5 }) + // The first Hebrew word is drawn at the right of the Hebrew, so the + // second word lies between the two rects. + #expect(abs(segments[1].rect.minX - document.caretRect(at: 8).midX) < 1) + #expect(segments[1].rect.minX - segments[0].rect.maxX > 10) + #expect(segments[0].containsStart && segments[1].containsEnd) + #expect(document.selectionRects(for: range) == segments.map(\.rect)) +} + +@Test func leftToRightSelectionIsOneRectPerLine() { + let document = layout(String(repeating: "The quick brown fox jumps over the lazy dog. ", count: 4)) + let segments = document.selectionSegments(for: 3.. document.caretRect(at: offset).midX + 0.5 else { break } + offset = next + visited.append(offset) + } + // Every caret stop of the line is visited, from left to right. + let stops = Set((0...document.length).map { document.caretRect(at: $0).midX.rounded() }) + #expect(visited.count == stops.count, "visited \(visited)") + #expect(abs(document.caretRect(at: offset).midX - line.frame.maxX) < 2) +} + +@Test func farthestEndOfARangeIsFoundOnTheScreen() { + let document = layout("שלום abc") + #expect(document.farthestOffset(in: 0..<4, right: true) == 0) + #expect(document.farthestOffset(in: 0..<4, right: false) == 4) + #expect(document.farthestOffset(in: 5..<7, right: true) == 7) + let plain = layout("Hello world") + #expect(plain.farthestOffset(in: 1..<4, right: true) == 4) + #expect(plain.farthestOffset(in: 1..<4, right: false) == 1) +} + +@Test func firstLineRectCoversTheRectsOfTheFirstLine() { + let mixed = layout("Say שלום עולם to all", width: 400) + let segments = mixed.selectionSegments(for: 2..<8) + #expect(segments.count == 2) + #expect(mixed.firstLineRect(for: 2..<8) == segments[0].rect.union(segments[1].rect)) + + // The cells of a row start at the same height, but each has its own line. + let table = layout("| a | b |\n|---|---|\n| c | d |") + let block = table.entry(at: 0).layout + let row = block.table!.cellLines[1] + let range = block.lines[row[0].lowerBound].range.lowerBound.. CGFloat { #expect(abs(rect.midY + capHeight / 2) < 0.5) } +@Test func aTagImageSitsOnTheRightOfRightToLeftText() throws { + let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4) + let plain = layout("ראה שישי בקרוב", image: nil) + let laidOut = layout("ראה שישי בקרוב", image: image) + let line = laidOut.entry(at: 0).layout.lines[0] + let rect = try #require(line.decorations?.images.first).rect + // "שישי" starts at offset 4, with its rightmost glyph. The image is + // after that glyph, on its right, past the gap. + let plainLine = plain.entry(at: 0).layout.lines[0] + var advance = CGSize.zero + for run in CTLineGetGlyphRuns(plainLine.ctLine) as! [CTRun] { + let count = CTRunGetGlyphCount(run) + var indices = [CFIndex](repeating: 0, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: count), &indices) + if let found = indices.firstIndex(of: 4) { CTRunGetAdvances(run, CFRange(location: found, length: 1), &advance) } + } + #expect(advance.width > 0) + #expect(abs(rect.minX - (glyphStart(line, at: 4) + advance.width + 4)) < 0.5) + // The room for the image is there: the line is wider by it. + #expect(abs(line.frame.width - plainLine.frame.width - 18) < 0.5) +} + @Test func aTagImageIsDrawn() { let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4) let laidOut = layout("See Friday soon", image: image) diff --git a/Tests/TranscriptKitTests/TailRendererTests.swift b/Tests/TranscriptKitTests/TailRendererTests.swift index b6a68af..050bdb9 100644 --- a/Tests/TranscriptKitTests/TailRendererTests.swift +++ b/Tests/TranscriptKitTests/TailRendererTests.swift @@ -214,6 +214,45 @@ func tailFramesMatchWithTablesAndContainers(chunk: Int) { #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") } +/// Right-to-left text, and a block that turns right to left when its first +/// letter arrives, stream into the tail as they draw from scratch. +@Test(arguments: [2, 7]) +func tailFramesMatchInRightToLeftText(chunk: Int) { + let markdown = """ + שלום עולם, זה משפט ארוך בעברית שעובר לשורה הבאה ברוחב הזה. + + > 2024: מרחבא בעולם, וזה ציטוט ארוך + + - פריט ראשון ברשימה + - [ ] משימה פתוחה + + | מילה | פירוש | + | --- | --- | + | אחת | ראשונה | + + English, then עברית at the end. + + """ + let scale: CGFloat = 2 + var checked = 0 + var mismatches: [String] = [] + var frameIndex = 0 + streamTail(markdown, chunk: chunk, scale: scale) { layout, frame in + frameIndex += 1 + let width = Int(((layout.width + 2 * TailRenderer.sideMargin) * scale).rounded()) + let height = Int((TailRenderer.height * scale).rounded()) + let actual = pixels(of: frame.surface, width: width, height: height) + let expected = expectedPixels(layout, top: frame.top, scale: scale) + let differing = zip(actual, expected).filter { abs(Int($0) - Int($1)) > 2 }.count + if differing > 0, mismatches.count < 3 { + mismatches.append("frame \(frameIndex), top \(frame.top): \(differing) bytes differ") + } + checked += 1 + } + #expect(checked > 10) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") +} + /// Rows already written keep their lines while a table streams, as long as /// the columns stay the same. @Test func streamingTableKeepsFinishedRows() throws { diff --git a/Tests/TranscriptKitTests/WritingDirectionTests.swift b/Tests/TranscriptKitTests/WritingDirectionTests.swift new file mode 100644 index 0000000..0d2f2d4 --- /dev/null +++ b/Tests/TranscriptKitTests/WritingDirectionTests.swift @@ -0,0 +1,70 @@ +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +@Test(arguments: [ + ("Hello", WritingDirection?.some(.leftToRight)), + ("שלום", .rightToLeft), + ("مرحبا", .rightToLeft), + ("123 שלום", .rightToLeft), + ("(\"שלום\") hello", .rightToLeft), + ("hello שלום", .leftToRight), + ("١٢٣ abc", .leftToRight), + ("\u{05B0}abc", .leftToRight), + ("\u{2067}abc\u{2069} שלום", .rightToLeft), + ("\u{200F}123", .rightToLeft), + ("日本語", .leftToRight), + ("Ⅳ שלום", .leftToRight), + ("🇺🇸 שלום", .leftToRight), + ("😀 שלום", .rightToLeft), + ("\u{02B9}שלום", .rightToLeft), + ("१२ שלום", .leftToRight), + ("123 !?", nil), + ("", nil), +]) +func firstStrongCharacterSetsTheDirection(text: String, expected: WritingDirection?) { + #expect(DirectionScan(text).firstStrong == expected) +} + +@Test func onlyTextWithRightToLeftCharactersGetsADirection() { + #expect(DirectionScan("Plain text, 123.").paragraphDirection == nil) + #expect(DirectionScan("Some שלום inside").paragraphDirection == .leftToRight) + #expect(DirectionScan("שלום and more").paragraphDirection == .rightToLeft) + // No strong character before the first right-to-left one. + #expect(DirectionScan("12 \u{0661}\u{0662}").paragraphDirection == .leftToRight) + // A zero width no-break space is not right to left. + #expect(DirectionScan("\u{FEFF}Plain text").paragraphDirection == nil) +} + +@Test func scanGoesOnFromWhereItStopped() { + var scan = DirectionScan("12. ") + #expect(scan.firstStrong == nil) + scan.scan("12. שלום") + #expect(scan.firstStrong == .rightToLeft) + #expect(scan == DirectionScan("12. שלום")) + + var grown = DirectionScan("Text") + grown.scan("Text and 😀 then עברית") + #expect(grown.paragraphDirection == .leftToRight) + #expect(grown.length == "Text and 😀 then עברית".utf16.count) +} + +/// Each run's string range and position, in the order Core Text draws them. +private func runLayout(_ text: String, direction: WritingDirection?) -> [[Double]] { + var attributes: [NSAttributedString.Key: Any] = [TranscriptStyle.fontKey: CTFontCreateUIFontForLanguage(.system, 17, nil)!] + if let direction { attributes[TranscriptStyle.paragraphStyleKey] = direction.paragraphStyle } + let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attributes)) + return (CTLineGetGlyphRuns(line) as! [CTRun]).map { run in + let range = CTRunGetStringRange(run) + var position = CGPoint.zero + CTRunGetPositions(run, CFRange(location: 0, length: 1), &position) + return [Double(range.location), Double(range.length), position.x.rounded()] + } +} + +@Test(arguments: ["שלום עולם ", "123 שלום", "Ⅳ שלום", "🇺🇸 שלום", "😀 שלום", "hello שלום world ", "(\"مرحبا\") hello", "١٢٣ abc", "\u{2067}abc\u{2069} שלום"]) +func scanFindsTheDirectionThatCoreTextFinds(text: String) { + let direction = DirectionScan(text).firstStrong + #expect(runLayout(text, direction: nil) == runLayout(text, direction: direction)) +}