Files
plak/Sources/PlakUI/Page/TableAttachment.swift

177 lines
7.2 KiB
Swift

import AppKit
import PlakCore
/// A cell of a table, by row and column.
struct TablePosition: Equatable {
var row: Int
var column: Int
}
/// The grid of a table at a font: columns sized to their values, every row one line high.
struct TableLayout {
private(set) var columnWidths: [CGFloat]
let rowHeight: CGFloat
let rowCount: Int
let font: NSFont
init(_ table: CSVTable, font: NSFont) {
self.font = font
columnWidths = (0..<table.columnCount).map { Self.columnWidth($0, of: table, font: font) }
rowHeight = PlakFonts.naturalLineHeight(font) + PageMetrics.tableCellPadding.height * 2
rowCount = table.rows.count
}
/// Measures one column again, after a change of one of its values.
mutating func remeasure(column: Int, of table: CSVTable) {
guard column < columnWidths.count else { return }
columnWidths[column] = Self.columnWidth(column, of: table, font: font)
}
private static func columnWidth(_ column: Int, of table: CSVTable, font: NSFont) -> CGFloat {
let attributes: [NSAttributedString.Key: Any] = [.font: font]
var widest: CGFloat = ceil(font.pointSize * 2)
for row in table.rows.indices {
let value = table[row, column]
guard !value.isEmpty else { continue }
widest = max(widest, ceil(NSAttributedString(string: shown(value), attributes: attributes).size().width))
}
return min(PageMetrics.tableColumnMaximum, widest + PageMetrics.tableCellPadding.width * 2)
}
/// A value on one line: a newline in a value shows as a space.
static func shown(_ value: String) -> String {
value.replacingOccurrences(of: "\r\n", with: " ").replacingOccurrences(of: "\n", with: " ")
}
var size: NSSize {
NSSize(width: columnWidths.reduce(0, +) + 1, height: CGFloat(rowCount) * rowHeight + 1)
}
func columnX(_ column: Int) -> CGFloat {
columnWidths.prefix(column).reduce(0, +)
}
/// The rect of a cell, from the top left of the grid, its lines included.
func rect(_ position: TablePosition) -> NSRect {
NSRect(x: columnX(position.column), y: CGFloat(position.row) * rowHeight,
width: columnWidths[position.column] + 1, height: rowHeight + 1)
}
/// The cell under a point from the top left of the grid; nil outside the grid.
func position(at point: NSPoint) -> TablePosition? {
guard point.y.isFinite, point.x.isFinite, point.y >= 0, point.x >= 0, rowCount > 0, rowHeight > 0 else { return nil }
let row = Int(point.y / rowHeight)
var x: CGFloat = 0
for (column, width) in columnWidths.enumerated() {
x += width
if point.x < x { return row < rowCount ? TablePosition(row: row, column: column) : nil }
}
return nil
}
/// Draws the lines and the values of the rows in `clip`, with the grid's top left at `origin`, in a flipped view.
func draw(_ table: CSVTable, at origin: NSPoint, clip: NSRect, scale: CGFloat) {
let size = size
let visible = clip.intersection(NSRect(origin: origin, size: size))
guard rowCount > 0, rowHeight > 0, visible.isFiniteArea else { return }
let line = 1 / max(1, scale)
let first = max(0, min(rowCount - 1, Int((visible.minY - origin.y) / rowHeight)))
let last = max(first, min(rowCount - 1, Int((visible.maxY - origin.y) / rowHeight)))
let top = origin.y + CGFloat(first) * rowHeight
let bottom = origin.y + CGFloat(last + 1) * rowHeight
Theme.rule.setFill()
var x = origin.x
for width in columnWidths + [0] {
NSRect(x: x, y: top, width: line, height: bottom - top + line).fill()
x += width
}
for row in first...(last + 1) {
NSRect(x: origin.x, y: origin.y + CGFloat(row) * rowHeight, width: size.width, height: line).fill()
}
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: Theme.ink, .paragraphStyle: style]
let padding = PageMetrics.tableCellPadding
for row in first...last {
for column in columnWidths.indices {
let value = table[row, column]
guard !value.isEmpty else { continue }
let cell = rect(TablePosition(row: row, column: column)).offsetBy(dx: origin.x, dy: origin.y)
let text = cell.insetBy(dx: padding.width, dy: padding.height)
NSAttributedString(string: Self.shown(value), attributes: attributes)
.draw(with: text, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
}
}
}
}
/// A table in the page: one character that knows its CSV text.
final class TableAttachment: NSTextAttachment {
let table: CSVTable
/// The CSV text as in the page file: as pasted until the table is edited.
let body: String
init(body: String, font: NSFont) {
self.body = body
table = CSVTable(text: body)
super.init(data: nil, ofType: nil)
attachmentCell = TableCell(table: table, font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
}
/// The grid of a table, cut off at the width of the column.
final class TableCell: NSTextAttachmentCell, ObjectCell {
private let table: CSVTable
private(set) var layout: TableLayout
private var size = NSSize.zero
/// AppKit reads it in `cellFrame`, which it does not mark main-actor; the page lays out on the main thread only.
nonisolated(unsafe) var editingHeight: CGFloat?
init(table: CSVTable, font: NSFont) {
self.table = table
layout = TableLayout(table, font: font)
super.init(textCell: "")
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
layout = TableLayout(table, font: font)
}
override func cellSize() -> NSSize {
size
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
let grid = layout.size
size = NSSize(width: min(grid.width, floor(lineFrag.width - max(0, position.x))), height: editingHeight ?? grid.height)
return NSRect(origin: .zero, size: size)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
guard editingHeight == nil, let context = NSGraphicsContext.current, let clip = drawingClip(within: cellFrame) else { return }
context.saveGraphicsState()
cellFrame.clip()
layout.draw(table, at: cellFrame.origin, clip: clip, scale: controlView?.window?.backingScaleFactor ?? 2)
context.restoreGraphicsState()
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}