Files
plak/Sources/PlakUI/Page/PageTextView.swift
T

447 lines
18 KiB
Swift

import AppKit
import PlakCore
/// A created date in the left margin: its label and where it is drawn.
struct MarginDate: Equatable {
var label: String
var rect: NSRect
}
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, paste and drop.
final class PageTextView: NSTextView {
let pageText: PageText
/// Images pasted or dropped, and the range they replace.
var onImages: (([PasteboardImage], NSRange) -> Void)?
var now: () -> Date = Date.init
/// Where ⌘V reads from.
var pasteboard: NSPasteboard = .general
/// Esc, which hides Plak.
var onHide: (() -> Void)?
private let ownedStorage: NSTextStorage
private(set) var sideSpace: CGFloat = 0
private(set) var topSpace: CGFloat = 0
init(pageText: PageText) {
self.pageText = pageText
let storage = NSTextStorage()
let layout = NSLayoutManager()
storage.addLayoutManager(layout)
let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude))
container.widthTracksTextView = false
container.lineFragmentPadding = 0
layout.addTextContainer(container)
ownedStorage = storage
super.init(frame: .zero, textContainer: container)
// Rich text only so that images can be characters; paste and drop bring plain text.
isRichText = true
importsGraphics = false
allowsImageEditing = false
usesFontPanel = false
usesRuler = false
isEditable = true
isSelectable = true
allowsUndo = true
drawsBackground = true
backgroundColor = Theme.paper
isVerticallyResizable = true
isHorizontallyResizable = false
autoresizingMask = [.width]
maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
isAutomaticQuoteSubstitutionEnabled = false
isAutomaticDashSubstitutionEnabled = false
isAutomaticTextReplacementEnabled = false
isAutomaticSpellingCorrectionEnabled = false
isAutomaticLinkDetectionEnabled = false
isAutomaticDataDetectionEnabled = false
isContinuousSpellCheckingEnabled = false
smartInsertDeleteEnabled = false
insertionPointColor = Theme.accent
selectedTextAttributes = [.backgroundColor: Theme.selection]
applyStyle()
updateDragTypeRegistration()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var length: Int {
(string as NSString).length
}
/// Typing never carries a created date: the block it lands in gives one.
override var typingAttributes: [NSAttributedString.Key: Any] {
get { super.typingAttributes }
set {
var attributes = newValue
attributes[.plakCreated] = nil
attributes[.plakUndated] = nil
attributes[.attachment] = nil
super.typingAttributes = attributes
}
}
/// Sets the look of the text after a change of text size.
func applyStyle() {
typingAttributes = pageText.attributes
defaultParagraphStyle = pageText.attributes[.paragraphStyle] as? NSParagraphStyle
guard let textStorage, textStorage.length > 0 else { return }
let all = NSRange(location: 0, length: textStorage.length)
textStorage.beginEditing()
textStorage.addAttributes(pageText.attributes, range: all)
textStorage.enumerateAttribute(.attachment, in: all) { value, range, _ in
guard let image = value as? ImageAttachment else { return }
textStorage.removeAttribute(.baselineOffset, range: range)
(image.attachmentCell as? MissingImageCell)?.setFont(pageText.font)
}
textStorage.endEditing()
}
// MARK: Column and spaces
override var textContainerOrigin: NSPoint {
NSPoint(x: sideSpace, y: topSpace)
}
/// The column sits `side` from the left; `sizeToFit` adds twice the inset height, so it holds top and bottom.
func setSpaces(side: CGFloat, top: CGFloat, bottom: CGFloat) {
guard side != sideSpace || top != topSpace || textContainerInset.height * 2 != top + bottom else { return }
sideSpace = side
topSpace = top
textContainerInset = NSSize(width: side, height: (top + bottom) / 2)
invalidateTextContainerOrigin()
needsDisplay = true
}
/// The line fragment at a character, in this view's coordinates; the extra line at the very end.
func lineRect(at location: Int) -> NSRect {
guard let layoutManager, let textContainer else { return .zero }
layoutManager.ensureLayout(for: textContainer)
var rect: NSRect
if length == 0 || (location >= length && !layoutManager.extraLineFragmentRect.isEmpty) {
rect = layoutManager.extraLineFragmentRect
} else {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
rect = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
}
return rect.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// The bottom of the last line of text.
var textBottom: CGFloat {
lineRect(at: length).maxY
}
// MARK: Pointer
/// The drag strip over the top of the text; there the pointer is the arrow.
weak var dragStrip: NSView?
/// The visible part of the drag strip, in this view's coordinates.
var dragStripRect: NSRect? {
guard let dragStrip, !dragStrip.isHidden else { return nil }
let rect = convert(dragStrip.bounds, from: dragStrip).intersection(visibleRect)
return rect.isEmpty ? nil : rect
}
func isUnderDragStrip(_ locationInWindow: NSPoint) -> Bool {
guard let dragStrip, !dragStrip.isHidden else { return false }
return dragStrip.bounds.contains(dragStrip.convert(locationInWindow, from: nil))
}
/// Without super, so no I-beam rect lies under the strip.
override func resetCursorRects() {
guard let strip = dragStripRect else { return super.resetCursorRects() }
let visible = visibleRect
addCursorRect(NSRect(x: visible.minX, y: strip.maxY, width: visible.width, height: max(0, visible.maxY - strip.maxY)), cursor: .iBeam)
addCursorRect(strip, cursor: .arrow)
}
override func cursorUpdate(with event: NSEvent) {
guard let window, isUnderDragStrip(window.mouseLocationOutsideOfEventStream) else { return super.cursorUpdate(with: event) }
NSCursor.arrow.set()
}
override func mouseMoved(with event: NSEvent) {
guard isUnderDragStrip(event.locationInWindow) else { return super.mouseMoved(with: event) }
NSCursor.arrow.set()
}
// MARK: Clicks
override func mouseDown(with event: NSEvent) {
if convert(event.locationInWindow, from: nil).y > textBottom {
window?.makeFirstResponder(self)
setSelectedRange(NSRange(location: length, length: 0))
return
}
super.mouseDown(with: event)
}
// MARK: Esc
/// During an input-method composition Esc cancels the composition, not the page.
/// NSTextView has no cancelOperation of its own, so super would crash.
override func cancelOperation(_ sender: Any?) {
if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else if let onHide {
onHide()
} else {
nextResponder?.tryToPerform(#selector(cancelOperation(_:)), with: sender)
}
}
// MARK: Copy, paste, drop
override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {
[.string]
}
/// Paste is enabled only for these types: without the image types a screenshot could never be pasted.
override var readablePasteboardTypes: [NSPasteboard.PasteboardType] {
[.string] + PasteboardImages.dragTypes
}
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(paste(_:)), #selector(pasteAsPlainText(_:)), #selector(pasteAsRichText(_:)):
isEditable && canPaste(from: pasteboard)
case #selector(selectAll(_:)):
false
default:
super.validateUserInterfaceItem(item)
}
}
override func validateMenuItem(_ item: NSMenuItem) -> Bool {
item.action == #selector(selectAll(_:)) ? false : super.validateMenuItem(item)
}
/// Plak has no Select All, so the page cannot be cleared in one go.
override func selectAll(_ sender: Any?) {}
func canPaste(from pasteboard: NSPasteboard) -> Bool {
PasteboardImages.contains(pasteboard) || pasteboard.availableType(from: [.string]) != nil
}
override func writeSelection(to pboard: NSPasteboard, types: [NSPasteboard.PasteboardType]) -> Bool {
guard let textStorage else { return false }
let text = selectedRanges.map { PageText.plainText(textStorage, range: $0.rangeValue) }.joined(separator: "\n")
pboard.declareTypes([.string], owner: nil)
return pboard.setString(text, forType: .string)
}
override func paste(_ sender: Any?) {
paste(from: pasteboard)
}
override func pasteAsPlainText(_ sender: Any?) {
paste(from: pasteboard)
}
override func pasteAsRichText(_ sender: Any?) {
paste(from: pasteboard)
}
func paste(from pasteboard: NSPasteboard) {
let images = PasteboardImages.read(pasteboard)
if !images.isEmpty {
onImages?(images, selectedRange())
} else if let text = pasteboard.string(forType: .string), !text.isEmpty {
insert(pageText.attributedString(plainText: text), replacing: selectedRange())
}
}
/// Text dropped from a drag, or brought by a service.
override func readSelection(from pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {
guard canPaste(from: pboard) else { return false }
paste(from: pboard)
return true
}
/// Puts the images in place of `range`, each on a line of its own.
func insertImages(_ paths: [String], replacing range: NSRange) {
guard !paths.isEmpty else { return }
let string = self.string as NSString
let text = NSMutableAttributedString()
if range.location > 0, string.character(at: range.location - 1) != 0x0A { text.append(pageText.newline()) }
for (index, path) in paths.enumerated() {
if index > 0 { text.append(pageText.newline()) }
text.append(pageText.imageString(path))
}
// On an empty line the line moves below the images, so a blank line under it stays blank.
let end = NSMaxRange(range)
let onEmptyLine = range.location == 0 || string.character(at: range.location - 1) == 0x0A
if end < string.length, string.character(at: end) != 0x0A || onEmptyLine { text.append(pageText.newline()) }
insert(text, replacing: range)
}
/// Replaces a range as one undoable change.
func insert(_ text: NSAttributedString, replacing range: NSRange) {
guard let textStorage else { return }
breakUndoCoalescing()
guard shouldChangeText(in: range, replacementString: text.string) else { return }
textStorage.replaceCharacters(in: range, with: text)
didChangeText()
setSelectedRange(NSRange(location: range.location + text.length, length: 0))
breakUndoCoalescing()
scrollRangeToVisible(selectedRange())
}
override var acceptableDragTypes: [NSPasteboard.PasteboardType] {
[.string] + PasteboardImages.dragTypes
}
/// NSTextView leaves this view unregistered here, so no drop would ever reach it.
override func updateDragTypeRegistration() {
super.updateDragTypeRegistration()
registerForDraggedTypes(acceptableDragTypes)
}
// MARK: Image drop
private var isImageDrag = false
private(set) var dropCaret: NSRect?
/// The place an image dropped at `point` lands, and the caret that shows it.
func imageDrop(at point: NSPoint) -> (location: Int, caret: NSRect) {
let location = min(characterIndexForInsertion(at: point), length)
return (location, dropCaretRect(at: location))
}
/// A 2 pt bar at the start of the character at `location`, over the height of its line.
func dropCaretRect(at location: Int) -> NSRect {
let line = lineRect(at: location)
var x = line.minX
if let layoutManager, length > 0, location < length || layoutManager.extraLineFragmentRect.isEmpty {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
if location < length {
x += layoutManager.location(forGlyphAt: glyph).x
} else {
x = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil).maxX + textContainerOrigin.x
}
}
return NSRect(x: round(x) - 1, y: line.minY, width: 2, height: line.height)
}
func showDropCaret(_ rect: NSRect?) {
guard rect != dropCaret else { return }
if let dropCaret { setNeedsDisplay(dropCaret) }
dropCaret = rect
if let rect { setNeedsDisplay(rect) }
}
/// Puts dropped images at `point`; it needs no key window or first responder, so a drop on a background window lands at once.
func dropImages(_ images: [PasteboardImage], at point: NSPoint) {
let location = imageDrop(at: point).location
showDropCaret(nil)
onImages?(images, NSRange(location: location, length: 0))
window?.makeFirstResponder(self)
}
/// Image drags never reach NSTextView: its own drop waits for the window to activate and the caret to settle.
private func imageDragUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
isImageDrag = true
showDropCaret(imageDrop(at: convert(sender.draggingLocation, from: nil)).caret)
return .copy
}
private func endImageDrag() {
isImageDrag = false
showDropCaret(nil)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingEntered(sender)
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingUpdated(sender)
}
override func draggingExited(_ sender: NSDraggingInfo?) {
isImageDrag ? endImageDrag() : super.draggingExited(sender)
}
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
isImageDrag || super.prepareForDragOperation(sender)
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard isImageDrag else { return super.performDragOperation(sender) }
let images = PasteboardImages.read(sender.draggingPasteboard)
guard !images.isEmpty else {
endImageDrag()
return false
}
dropImages(images, at: convert(sender.draggingLocation, from: nil))
return true
}
override func concludeDragOperation(_ sender: NSDraggingInfo?) {
isImageDrag ? endImageDrag() : super.concludeDragOperation(sender)
}
// MARK: Margin dates
var showsDates: Bool {
sideSpace >= PageMetrics.dateMarginMinimum
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if let dropCaret, dropCaret.intersects(dirtyRect) {
Theme.accent.setFill()
dropCaret.fill()
}
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont, .foregroundColor: Theme.inkMuted]
for date in marginDates(in: dirtyRect) {
NSAttributedString(string: date.label, attributes: attributes).draw(in: date.rect)
}
}
/// Redraws the margin, where the layout does not look after the dates.
func invalidateMargin() {
let visible = visibleRect
setNeedsDisplay(NSRect(x: 0, y: visible.minY, width: sideSpace, height: visible.height))
}
var dateFont: NSFont {
PlakFonts.body(round(pageText.font.pointSize * PageMetrics.dateScale))
}
/// The dates of the blocks whose first line lies in `rect`: right-aligned next to the column, at that line.
func marginDates(in rect: NSRect) -> [MarginDate] {
guard showsDates, let layoutManager, let textContainer, let textStorage, textStorage.length > 0 else { return [] }
let origin = textContainerOrigin
let lineHeight = pageText.lineHeight
let search = NSRect(x: 0, y: rect.minY - origin.y - lineHeight, width: textContainer.size.width, height: rect.height + lineHeight * 2)
let glyphs = layoutManager.glyphRange(forBoundingRect: search, in: textContainer)
let characters = layoutManager.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)
let string = textStorage.string as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont]
let now = now()
var dates: [MarginDate] = []
var location = string.lineStart(at: characters.location)
while location < min(NSMaxRange(characters) + 1, string.length) {
let end = string.lineEnd(from: location)
defer { location = end + 1 }
guard !string.isBlankLine(NSRange(location: location, length: end - location)) else { continue }
if location > 0 {
let previous = string.lineStart(at: location - 1)
guard string.isBlankLine(NSRange(location: previous, length: location - 1 - previous)) else { continue }
}
guard let created = textStorage.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date else { continue }
let label = CreatedDate.label(for: created, now: now)
let size = NSAttributedString(string: label, attributes: attributes).size()
let line = lineRect(at: location)
let midY = line.minY + min(line.height, lineHeight) / 2
let width = ceil(size.width), height = ceil(size.height)
let right = origin.x - PageMetrics.dateSpacing
dates.append(MarginDate(label: label, rect: NSRect(x: right - width, y: round(midY - height / 2), width: width, height: height)))
}
return dates
}
}