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 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) setBodySize(bodySize) } /// The minimum line height lets a line with an image grow to the image. func setBodySize(_ size: CGFloat) { font = PlakFonts.body(size) 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 image = "\u{FFFC}" let string = file.lines.map { line in if case .image = line { return image } return 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 case .image = line { location += 2 } else { location += (line.text as NSString).length + 1 } } starts.append(location) text.beginEditing() for (index, line) in file.lines.enumerated() { if case let .image(path) = line { text.setAttributes(attachmentAttributes(path), range: NSRange(location: starts[index], length: 1)) } } 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; a line that is exactly an image line of an existing image file becomes that image. func attributedString(plainText: String) -> NSAttributedString { let text = NSMutableAttributedString() let lines = plainText.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n") for (index, line) in lines.enumerated() { if index > 0 { text.append(NSAttributedString(string: "\n", attributes: attributes)) } if let path = PageFile.imagePath(fromLine: line), FileManager.default.fileExists(atPath: imageURL(path).path) { text.append(imageString(path)) } else { text.append(NSAttributedString(string: line, attributes: attributes)) } } return text } func imageString(_ path: String) -> NSAttributedString { NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(path)) } func newline() -> NSAttributedString { NSAttributedString(string: "\n", attributes: attributes) } private func attachmentAttributes(_ path: String) -> [NSAttributedString.Key: Any] { var attributes = imageAttributes attributes[.attachment] = ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font) return attributes } 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 always on a line of its own. static func pageFile(_ text: NSAttributedString) -> 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)) 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. static func plainText(_ text: NSAttributedString, range: NSRange) -> String { var out = "" text.enumerateAttribute(.attachment, in: range) { value, run, _ in if let image = value as? ImageAttachment { out += String(repeating: PageFile.imageLine(image.path), count: run.length) } 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. private static func lineContents(_ text: NSAttributedString, _ range: NSRange) -> [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] = [] text.enumerateAttribute(.attachment, in: range) { value, run, _ in if let image = value as? ImageAttachment { lines += Array(repeating: .image(image.path), count: run.length) } else { let piece = string.substring(with: run) if !PageFile.isBlank(piece) { lines.append(.text(piece)) } } } return lines.isEmpty ? [.text("")] : lines } // 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) } }