341 lines
15 KiB
Swift
341 lines
15 KiB
Swift
import AppKit
|
|
import PlakCore
|
|
|
|
extension NSAttributedString.Key {
|
|
/// The created date of the block a character is in.
|
|
static let plakCreated = NSAttributedString.Key("plakCreated")
|
|
/// A block read from the page file without a date line; it is never stamped.
|
|
static let plakUndated = NSAttributedString.Key("plakUndated")
|
|
}
|
|
|
|
/// Turns the page file into the text of the page view and back, and keeps the created dates of the blocks.
|
|
final class PageText {
|
|
/// The folder of the page file; image paths are relative to it.
|
|
let imageBase: URL
|
|
let images: ImageCache
|
|
private(set) var font: NSFont
|
|
/// The font of code blocks and tables.
|
|
private(set) var codeFont: NSFont
|
|
private(set) var lineHeight: CGFloat = 0
|
|
/// The look of every character; an image leaves out the baseline offset.
|
|
private(set) var attributes: [NSAttributedString.Key: Any] = [:]
|
|
|
|
init(imageBase: URL, images: ImageCache = ImageCache(), bodySize: CGFloat = TextSize.standard) {
|
|
self.imageBase = imageBase
|
|
self.images = images
|
|
font = PlakFonts.body(bodySize)
|
|
codeFont = PlakFonts.mono(round(bodySize * PageMetrics.codeScale))
|
|
setBodySize(bodySize)
|
|
}
|
|
|
|
/// The minimum line height lets a line with an image grow to the image.
|
|
func setBodySize(_ size: CGFloat) {
|
|
font = PlakFonts.body(size)
|
|
codeFont = PlakFonts.mono(round(size * PageMetrics.codeScale))
|
|
lineHeight = PageMetrics.lineHeight(font)
|
|
let style = NSMutableParagraphStyle()
|
|
style.minimumLineHeight = lineHeight
|
|
attributes = [
|
|
.font: font,
|
|
.foregroundColor: Theme.ink,
|
|
.paragraphStyle: style,
|
|
.baselineOffset: max(0, (lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
|
|
]
|
|
}
|
|
|
|
var imageAttributes: [NSAttributedString.Key: Any] {
|
|
var attributes = attributes
|
|
attributes[.baselineOffset] = nil
|
|
return attributes
|
|
}
|
|
|
|
// MARK: Page file to text
|
|
|
|
/// The text of the page; every character of a block carries its date, or the undated mark.
|
|
func attributedString(_ file: PageFile) -> NSAttributedString {
|
|
let string = file.lines.map { line in
|
|
Self.isObject(line) ? "\u{FFFC}" : line.text
|
|
}.joined(separator: "\n")
|
|
let text = NSMutableAttributedString(string: string, attributes: attributes)
|
|
var starts: [Int] = []
|
|
starts.reserveCapacity(file.lines.count + 1)
|
|
var location = 0
|
|
for line in file.lines {
|
|
starts.append(location)
|
|
if Self.isObject(line) {
|
|
location += 2
|
|
} else {
|
|
location += (line.text as NSString).length + 1
|
|
}
|
|
}
|
|
starts.append(location)
|
|
text.beginEditing()
|
|
for (index, line) in file.lines.enumerated() {
|
|
switch line {
|
|
case let .image(path):
|
|
text.setAttributes(attachmentAttributes(imageAttachment(path)), range: NSRange(location: starts[index], length: 1))
|
|
case let .fenced(kind, body):
|
|
text.setAttributes(attachmentAttributes(object(kind, body)), range: NSRange(location: starts[index], length: 1))
|
|
case .text:
|
|
break
|
|
}
|
|
}
|
|
for block in file.blocks {
|
|
let range = NSRange(location: starts[block.lowerBound], length: starts[block.upperBound] - 1 - starts[block.lowerBound])
|
|
if let date = file.dates[block.lowerBound] {
|
|
text.addAttribute(.plakCreated, value: date, range: range)
|
|
} else {
|
|
text.addAttribute(.plakUndated, value: true, range: range)
|
|
}
|
|
}
|
|
text.endEditing()
|
|
return text
|
|
}
|
|
|
|
/// Pasted plain text; an image line of an existing image file becomes that image, a fenced block its object.
|
|
func attributedString(plainText: String) -> NSAttributedString {
|
|
let text = NSMutableAttributedString()
|
|
for (index, line) in PageFile.lines(pasted: plainText).enumerated() {
|
|
if index > 0 { text.append(NSAttributedString(string: "\n", attributes: attributes)) }
|
|
switch line {
|
|
case let .image(path) where FileManager.default.fileExists(atPath: imageURL(path).path):
|
|
text.append(imageString(path))
|
|
case let .fenced(kind, body):
|
|
text.append(objectString(kind, body))
|
|
default:
|
|
text.append(NSAttributedString(string: line.text, attributes: attributes))
|
|
}
|
|
}
|
|
return text
|
|
}
|
|
|
|
/// Pasted text exactly as it is: fences and image lines stay text.
|
|
func plainString(_ plainText: String) -> NSAttributedString {
|
|
NSAttributedString(string: plainText.replacingOccurrences(of: "\r\n", with: "\n"), attributes: attributes)
|
|
}
|
|
|
|
func imageString(_ path: String) -> NSAttributedString {
|
|
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(imageAttachment(path)))
|
|
}
|
|
|
|
/// A code block, or a table for csv.
|
|
func objectString(_ kind: FenceKind, _ body: String) -> NSAttributedString {
|
|
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(object(kind, body)))
|
|
}
|
|
|
|
func object(_ kind: FenceKind, _ body: String) -> NSTextAttachment {
|
|
kind == .csv ? TableAttachment(body: body, font: codeFont) : CodeAttachment(kind: kind, body: body, font: codeFont)
|
|
}
|
|
|
|
func newline() -> NSAttributedString {
|
|
NSAttributedString(string: "\n", attributes: attributes)
|
|
}
|
|
|
|
private func imageAttachment(_ path: String) -> ImageAttachment {
|
|
ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font)
|
|
}
|
|
|
|
private func attachmentAttributes(_ attachment: NSTextAttachment) -> [NSAttributedString.Key: Any] {
|
|
var attributes = imageAttributes
|
|
attributes[.attachment] = attachment
|
|
return attributes
|
|
}
|
|
|
|
private static func isObject(_ line: PageFile.Line) -> Bool {
|
|
if case .text = line { return false }
|
|
return true
|
|
}
|
|
|
|
private func imageURL(_ path: String) -> URL {
|
|
imageBase.appendingPathComponent(path)
|
|
}
|
|
|
|
// MARK: Text to page file
|
|
|
|
/// The page file of the text: one line per text line, an image or other object always on a line of its own.
|
|
/// A draft puts the edit of an open editor in place of its object, without building a new object.
|
|
static func pageFile(_ text: NSAttributedString, draft: (location: Int, edit: ObjectEdit)? = nil) -> PageFile {
|
|
let string = text.string as NSString
|
|
guard string.length > 0 else { return PageFile() }
|
|
var lines: [PageFile.Line] = []
|
|
var dates: [Int: Date] = [:]
|
|
var previousBlank = true
|
|
var location = 0
|
|
while location <= string.length {
|
|
let end = string.lineEnd(from: location)
|
|
let pieces = lineContents(text, NSRange(location: location, length: end - location), draft: draft)
|
|
guard !pieces.isEmpty else {
|
|
location = end + 1
|
|
continue
|
|
}
|
|
let blank = pieces.count == 1 && pieces[0].isBlank
|
|
if !blank, previousBlank, location < string.length, let date = text.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date {
|
|
dates[lines.count] = date
|
|
}
|
|
lines += pieces
|
|
previousBlank = blank
|
|
location = end + 1
|
|
}
|
|
return PageFile(lines: lines, dates: dates)
|
|
}
|
|
|
|
/// Plain text of a range, as for the pasteboard: each image becomes its image line, each object its fenced block.
|
|
static func plainText(_ text: NSAttributedString, range: NSRange) -> String {
|
|
var out = ""
|
|
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
|
|
if let line = value.flatMap(line(for:)) {
|
|
out += Array(repeating: line.text, count: run.length).joined(separator: "\n")
|
|
} else {
|
|
out += (text.string as NSString).substring(with: run)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
/// One text line as page file lines; text typed beside an image goes on its own line.
|
|
/// An object the draft removes takes its line with it: then there are no lines at all.
|
|
private static func lineContents(_ text: NSAttributedString, _ range: NSRange,
|
|
draft: (location: Int, edit: ObjectEdit)?) -> [PageFile.Line] {
|
|
let string = text.string as NSString
|
|
guard range.length > 0, string.range(of: "\u{FFFC}", range: range).location != NSNotFound else {
|
|
return [.text(string.substring(with: range))]
|
|
}
|
|
var lines: [PageFile.Line] = []
|
|
var removed = false
|
|
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
|
|
if let line = value.flatMap(line(for:)) {
|
|
for location in run.location..<NSMaxRange(run) {
|
|
switch location == draft?.location ? draft?.edit : nil {
|
|
case let .replaced(kind, body)?: lines.append(.fenced(kind, body))
|
|
case .removed?: removed = true
|
|
case .unchanged?, nil: lines.append(line)
|
|
}
|
|
}
|
|
} else {
|
|
let piece = string.substring(with: run)
|
|
if !PageFile.isBlank(piece) { lines.append(.text(piece)) }
|
|
}
|
|
}
|
|
return lines.isEmpty && !removed ? [.text("")] : lines
|
|
}
|
|
|
|
/// The page file line of an image, code block or table attachment.
|
|
static func line(for attachment: Any) -> PageFile.Line? {
|
|
switch attachment {
|
|
case let image as ImageAttachment: .image(image.path)
|
|
case let code as CodeAttachment: .fenced(code.kind, code.body)
|
|
case let table as TableAttachment: .fenced(.csv, table.body)
|
|
default: nil
|
|
}
|
|
}
|
|
|
|
// MARK: Created dates
|
|
|
|
/// Gives every block around an edit one state: the first date or undated mark found in it, else `now`.
|
|
///
|
|
/// Characters between blocks lose their state, so typing that starts a new block never takes
|
|
/// the date of the block above.
|
|
static func stampBlocks(_ text: NSMutableAttributedString, around edit: NSRange, now: () -> Date) {
|
|
let string = text.string as NSString
|
|
let region = string.blockRegion(around: edit)
|
|
var blocks: [NSRange] = []
|
|
var blockStart: Int?
|
|
var previousEnd = region.location
|
|
var location = region.location
|
|
while location <= NSMaxRange(region) {
|
|
let end = string.lineEnd(from: location)
|
|
if string.isBlankLine(NSRange(location: location, length: end - location)) {
|
|
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
|
|
blockStart = nil
|
|
} else if blockStart == nil {
|
|
blockStart = location
|
|
}
|
|
previousEnd = end
|
|
location = end + 1
|
|
}
|
|
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
|
|
|
|
var gapStart = region.location
|
|
for range in blocks + [NSRange(location: min(NSMaxRange(region) + 1, string.length), length: 0)] {
|
|
let gap = NSRange(location: gapStart, length: range.location - gapStart)
|
|
if gap.length > 0 {
|
|
text.removeAttribute(.plakCreated, range: gap)
|
|
text.removeAttribute(.plakUndated, range: gap)
|
|
}
|
|
gapStart = NSMaxRange(range)
|
|
}
|
|
for block in blocks {
|
|
var date: Date?
|
|
var undated = false
|
|
text.enumerateAttributes(in: block) { attributes, _, stop in
|
|
if let found = attributes[.plakCreated] as? Date {
|
|
date = found
|
|
stop.pointee = true
|
|
} else if attributes[.plakUndated] != nil {
|
|
undated = true
|
|
stop.pointee = true
|
|
}
|
|
}
|
|
if undated {
|
|
if !text.isUniform(.plakUndated, in: block) { text.addAttribute(.plakUndated, value: true, range: block) }
|
|
text.removeAttribute(.plakCreated, range: block)
|
|
} else {
|
|
let value = date ?? now()
|
|
if !text.isUniform(.plakCreated, value as NSDate, in: block) { text.addAttribute(.plakCreated, value: value, range: block) }
|
|
text.removeAttribute(.plakUndated, range: block)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private extension NSAttributedString {
|
|
func isUniform(_ key: NSAttributedString.Key, _ value: NSObject = true as NSNumber, in range: NSRange) -> Bool {
|
|
var effective = NSRange()
|
|
let found = attribute(key, at: range.location, longestEffectiveRange: &effective, in: range) as? NSObject
|
|
return found == value && effective == range
|
|
}
|
|
}
|
|
|
|
extension NSString {
|
|
/// The index of the newline that ends the line at `location`, or the length for the last line.
|
|
func lineEnd(from location: Int) -> Int {
|
|
guard location < length else { return length }
|
|
let found = range(of: "\n", range: NSRange(location: location, length: length - location))
|
|
return found.location == NSNotFound ? length : found.location
|
|
}
|
|
|
|
func lineStart(at location: Int) -> Int {
|
|
guard location > 0 else { return 0 }
|
|
let found = range(of: "\n", options: .backwards, range: NSRange(location: 0, length: location))
|
|
return found.location == NSNotFound ? 0 : found.location + 1
|
|
}
|
|
|
|
func isBlankLine(_ range: NSRange) -> Bool {
|
|
PageFile.isBlank(substring(with: range))
|
|
}
|
|
|
|
/// The lines of the blocks an edit touches; an edit in blank lines also takes the block above and below.
|
|
func blockRegion(around edit: NSRange) -> NSRange {
|
|
var start = lineStart(at: edit.location)
|
|
var inBlock = !isBlankLine(NSRange(location: start, length: lineEnd(from: start) - start))
|
|
while start > 0 {
|
|
let previous = lineStart(at: start - 1)
|
|
let blank = isBlankLine(NSRange(location: previous, length: start - 1 - previous))
|
|
if blank, inBlock { break }
|
|
if !blank { inBlock = true }
|
|
start = previous
|
|
}
|
|
let editEnd = min(NSMaxRange(edit), length)
|
|
var end = lineEnd(from: editEnd)
|
|
inBlock = !isBlankLine(NSRange(location: lineStart(at: editEnd), length: end - lineStart(at: editEnd)))
|
|
while end < length {
|
|
let nextEnd = lineEnd(from: end + 1)
|
|
let blank = isBlankLine(NSRange(location: end + 1, length: nextEnd - end - 1))
|
|
if blank, inBlock { break }
|
|
if !blank { inBlock = true }
|
|
end = nextEnd
|
|
}
|
|
return NSRange(location: start, length: end - start)
|
|
}
|
|
}
|