Files
2026-11-25 07:14:49 +01:00

747 lines
33 KiB
Swift

import AppKit
import PlakCore
/// A bookmark of the page with the created date of its block.
struct PageBookmark: Equatable {
var title: String
/// The created date label, nil when the block has no date.
var date: String?
/// The bookmark line, without its newline.
var range: NSRange
/// `title - date`, or the title alone.
var label: String {
date.map { "\(title) - \($0)" } ?? title
}
}
extension NSAttributedString.Key {
/// A bookmark line that shows in the bookmark look.
static let plakBookmarkLine = NSAttributedString.Key("plakBookmarkLine")
}
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark lines, paste and drop,
/// and the editors of code blocks and tables.
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)?
/// The editor open over a code block or table, the object it edits, and where that object was last seen.
var editor: ObjectEditor?
var editedAttachment: NSTextAttachment?
var editorLocation = 0
/// The content of the open editor changed.
var onEditorChange: (() -> Void)?
/// True while a closing editor puts its object back; the typing scroll leaves the page alone then.
var isReplacingObject = false
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()
layout.delegate = self
}
@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.
/// It is always page text, also next to a bookmark line in the bookmark look.
override var typingAttributes: [NSAttributedString.Key: Any] {
get { super.typingAttributes }
set {
var attributes = newValue
attributes[.plakCreated] = nil
attributes[.plakUndated] = nil
attributes[.attachment] = nil
attributes[.plakBookmarkLine] = nil
attributes.merge(pageTextLook) { _, page in page }
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 attachment = value as? NSTextAttachment else { return }
textStorage.removeAttribute(.baselineOffset, range: range)
(attachment.attachmentCell as? MissingImageCell)?.setFont(pageText.font)
(attachment.attachmentCell as? ObjectCell)?.setFont(pageText.codeFont)
}
textStorage.endEditing()
editor?.setFont(pageText.codeFont)
reloadBookmarks()
}
// 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 {
rect = layoutManager.lineFragmentRect(forGlyphAt: shownGlyph(at: min(location, length - 1)), effectiveRange: nil)
}
return rect.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// The glyph of a character; for a hidden bookmark `=` the glyph of the title after it.
/// A null glyph has no line fragment and no place of its own.
func shownGlyph(at location: Int) -> Int {
guard let layoutManager else { return 0 }
return layoutManager.glyphIndexForCharacter(at: isHiddenBookmarkSign(at: location) ? location + 1 : location)
}
/// 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))
}
/// The bookmark index over the left of the page; it sets its own pointer.
weak var bookmarkIndex: BookmarkIndexView?
/// The visible part of the bookmark index, in this view's coordinates.
var bookmarkIndexRect: NSRect? {
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return nil }
let rect = convert(bookmarkIndex.bounds, from: bookmarkIndex).intersection(visibleRect)
return rect.isEmpty ? nil : rect
}
func isOverBookmarkIndex(_ locationInWindow: NSPoint) -> Bool {
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return false }
return bookmarkIndex.bounds.contains(bookmarkIndex.convert(locationInWindow, from: nil))
}
/// Without super, so no I-beam rect lies under the strip or the bookmark index.
override func resetCursorRects() {
let strip = dragStripRect
let index = bookmarkIndexRect
guard strip != nil || index != nil else { return super.resetCursorRects() }
let visible = visibleRect
let top = strip?.maxY ?? visible.minY
let text = NSRect(x: visible.minX, y: top, width: visible.width, height: max(0, visible.maxY - top))
for rect in text.subtracting(index) { addCursorRect(rect, cursor: .iBeam) }
if let strip { addCursorRect(strip, cursor: .arrow) }
}
override func cursorUpdate(with event: NSEvent) {
guard let window else { return super.cursorUpdate(with: event) }
let location = window.mouseLocationOutsideOfEventStream
if isUnderDragStrip(location) {
NSCursor.arrow.set()
} else if isOverBookmarkIndex(location) {
bookmarkIndex?.updateCursor(at: location)
} else if updateHoveredLink(at: location, modifiers: NSEvent.modifierFlags) {
NSCursor.pointingHand.set()
} else {
super.cursorUpdate(with: event)
}
}
override func mouseMoved(with event: NSEvent) {
let overLink = updateHoveredLink(at: event.locationInWindow, modifiers: event.modifierFlags)
guard !isUnderDragStrip(event.locationInWindow) else { return NSCursor.arrow.set() }
guard !isOverBookmarkIndex(event.locationInWindow) else { return bookmarkIndex?.updateCursor(at: event.locationInWindow) ?? () }
super.mouseMoved(with: event)
if overLink { NSCursor.pointingHand.set() }
}
override func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
updateHoveredLink(at: event.locationInWindow, modifiers: [])
}
/// ⌘ pressed or let go while the pointer rests on a link.
override func flagsChanged(with event: NSEvent) {
super.flagsChanged(with: event)
guard let window else { return }
let location = window.mouseLocationOutsideOfEventStream
let wasOverLink = hoveredLink != nil
if updateHoveredLink(at: location, modifiers: event.modifierFlags) {
NSCursor.pointingHand.set()
} else if wasOverLink {
NSCursor.iBeam.set()
}
}
// MARK: Links
/// Opens a ⌘-clicked link.
var openLink: (URL) -> Void = { NSWorkspace.shared.open($0) }
/// The link under the pointer while ⌘ is held; it shows underlined.
private(set) var hoveredLink: NSRange?
private var linkTracking: NSTrackingArea?
/// The link at `point`, only over its glyphs: the space past the end of a line holds no link.
func link(at point: NSPoint) -> (url: URL, range: NSRange)? {
guard let layoutManager, let textContainer, length > 0 else { return nil }
let inContainer = NSPoint(x: point.x - textContainerOrigin.x, y: point.y - textContainerOrigin.y)
let glyph = layoutManager.glyphIndex(for: inContainer, in: textContainer)
let glyphRect = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: textContainer)
guard glyphRect.contains(inContainer) else { return nil }
return PageLink.link(in: string as NSString, at: layoutManager.characterIndexForGlyph(at: glyph))
}
/// Underlines the link under the pointer while ⌘ is held; true when there is one.
@discardableResult
func updateHoveredLink(at locationInWindow: NSPoint, modifiers: NSEvent.ModifierFlags) -> Bool {
var range: NSRange?
if modifiers.contains(.command), editor == nil, !isUnderDragStrip(locationInWindow) {
range = link(at: convert(locationInWindow, from: nil))?.range
}
guard range != hoveredLink, let layoutManager else { return range != nil }
// The text may have changed since the underline was set.
if let old = hoveredLink.map({ NSIntersectionRange($0, NSRange(location: 0, length: length)) }), old.length > 0 {
layoutManager.removeTemporaryAttribute(.underlineStyle, forCharacterRange: old)
}
if let range {
layoutManager.addTemporaryAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, forCharacterRange: range)
}
hoveredLink = range
return range != nil
}
/// NSTextView does not send every pointer move on its own.
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let linkTracking { removeTrackingArea(linkTracking) }
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)
addTrackingArea(area)
linkTracking = area
}
// MARK: Clicks
/// ⌘-click on a link opens it; a plain click on a code block or table opens its editor; any click closes an open editor first.
override func mouseDown(with event: NSEvent) {
if editor != nil { endEditing(nil) }
// Measured after the edit is put back: a removed object moves the text under the pointer.
let point = convert(event.locationInWindow, from: nil)
if event.modifierFlags.contains(.command), let link = link(at: point) {
updateHoveredLink(at: event.locationInWindow, modifiers: [])
openLink(link.url)
return
}
if event.modifierFlags.intersection([.shift, .command, .option, .control]).isEmpty, let location = object(at: point) {
openEditor(at: location, point: point)
return
}
if point.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 editor != nil {
endEditing(.after)
} else if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else if let onHide {
onHide()
} else {
nextResponder?.tryToPerform(#selector(cancelOperation(_:)), with: sender)
}
}
// MARK: Lorem
/// The sentences `#lorem` picks from.
var loremSentences: [String] = LoremText.sentences
override func insertText(_ string: Any, replacementRange: NSRange) {
super.insertText(string, replacementRange: replacementRange)
expandLorem()
}
/// Replaces a typed `#lorem` at the start of a line with lorem text, as an undo step of its own.
private func expandLorem() {
let caret = selectedRange()
let trigger = LoremText.trigger as NSString
guard caret.length == 0, !hasMarkedText(), caret.location >= trigger.length else { return }
let text = self.string as NSString
let range = NSRange(location: caret.location - trigger.length, length: trigger.length)
guard text.lineStart(at: caret.location) == range.location, text.substring(with: range) == LoremText.trigger,
let lorem = LoremText.pick(from: loremSentences) else { return }
// Grouping by event would undo the typed `m` together with the lorem text.
if let undoManager, undoManager.groupsByEvent, undoManager.groupingLevel == 1 {
undoManager.endUndoGrouping()
undoManager.beginUndoGrouping()
}
insert(pageText.plainString(lorem.text), replacing: range)
}
// 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, detectsObjects: false)
}
override func pasteAsRichText(_ sender: Any?) {
paste(from: pasteboard)
}
/// Pasted PHP, JSON, XML or CSV becomes a code block or table, unless the text already holds an object line.
/// Paste as Plain Text keeps fences and image lines as text.
func paste(from pasteboard: NSPasteboard, detectsObjects: Bool = true) {
let images = PasteboardImages.read(pasteboard)
if !images.isEmpty {
onImages?(images, selectedRange())
} else if let text = pasteboard.string(forType: .string), !text.isEmpty {
guard detectsObjects else { return insert(pageText.plainString(text), replacing: selectedRange()) }
let plain = pageText.attributedString(plainText: text)
if !plain.containsAttachments, case let .object(kind, body) = PasteKind(text) {
insertObjects([pageText.objectString(kind, body)], replacing: selectedRange())
} else {
insert(plain, replacing: selectedRange())
}
}
}
/// Pastes at the end of the page as a new block, after a blank line.
func append(from pasteboard: NSPasteboard) {
guard canPaste(from: pasteboard) else { return }
let string = self.string
let end = NSRange(location: length, length: 0)
if string.hasSuffix("\n\n") || string.isEmpty {
setSelectedRange(end)
} else {
insert(pageText.plainString(string.hasSuffix("\n") ? "\n" : "\n\n"), replacing: end)
}
paste(from: pasteboard)
}
/// Text dropped from a drag, or brought by a service; only ⌘V turns text into an object.
override func readSelection(from pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {
guard canPaste(from: pboard) else { return false }
let images = PasteboardImages.read(pboard)
if !images.isEmpty {
onImages?(images, selectedRange())
} else if let text = pboard.string(forType: .string), !text.isEmpty {
insert(pageText.attributedString(plainText: text), replacing: selectedRange())
}
return true
}
func insertImages(_ paths: [String], replacing range: NSRange) {
insertObjects(paths.map(pageText.imageString), replacing: range)
}
/// Puts the objects in place of `range`, each on a line of its own.
func insertObjects(_ objects: [NSAttributedString], replacing range: NSRange) {
guard !objects.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, object) in objects.enumerated() {
if index > 0 { text.append(pageText.newline()) }
text.append(object)
}
// 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 = shownGlyph(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)
}
/// An open editor closes first: a drop would move the object under it.
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if editor != nil { endEditing(nil) }
return 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: Bookmarks
/// The bookmarks of the page, as found at the last `reloadBookmarks`.
private(set) var bookmarks: [PageBookmark] = []
/// The width of the longest full bookmark label.
private(set) var widestBookmarkLabel: CGFloat = 0
/// True from a text change until `reloadBookmarks`: the bookmark ranges may point at other text then.
private var bookmarksAreStale = false
/// Finds the bookmarks again; call it after a change of text, created dates or text size.
func reloadBookmarks() {
guard let textStorage else { return }
let string = textStorage.string as NSString
let now = now()
bookmarks = Bookmark.find(in: string).map { bookmark in
let start = string.blockStart(at: bookmark.range.location)
let created = textStorage.attribute(.plakCreated, at: start, effectiveRange: nil) as? Date
return PageBookmark(title: bookmark.title, date: created.map { CreatedDate.label(for: $0, now: now) }, range: bookmark.range)
}
let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont]
widestBookmarkLabel = bookmarks.map { NSAttributedString(string: $0.label, attributes: attributes).size().width }.max() ?? 0
bookmarksAreStale = false
styleBookmarkLines()
}
/// The font of the bookmark index.
var bookmarkFont: NSFont {
PlakFonts.mono(round(pageText.font.pointSize * PageMetrics.dateScale))
}
/// The look of a bookmark line away from the selection.
var bookmarkLineAttributes: [NSAttributedString.Key: Any] {
let font = PlakFonts.monoBold(pageText.font.pointSize + PageMetrics.bookmarkLineGrowth)
return [
.font: font,
.foregroundColor: Theme.accent,
.baselineOffset: max(0, (pageText.lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
.plakBookmarkLine: true,
]
}
/// The parts of the page look that a bookmark line changes.
private var pageTextLook: [NSAttributedString.Key: Any] {
pageText.attributes.filter { [NSAttributedString.Key.font, .foregroundColor, .baselineOffset].contains($0.key) }
}
override func shouldChangeText(in affectedCharRange: NSRange, replacementString: String?) -> Bool {
let allowed = super.shouldChangeText(in: affectedCharRange, replacementString: replacementString)
if allowed { bookmarksAreStale = true }
return allowed
}
override func setSelectedRanges(_ ranges: [NSValue], affinity: NSSelectionAffinity, stillSelecting: Bool) {
super.setSelectedRanges(ranges, affinity: affinity, stillSelecting: stillSelecting)
if !stillSelecting, !bookmarksAreStale { styleBookmarkLines() }
}
/// Shows each bookmark line in the bookmark look while the selection is off it, and as page text while it is on it.
/// Set straight on the text storage, so it adds no undo step and posts no text change: nothing is stamped or saved.
func styleBookmarkLines() {
guard let textStorage, textStorage.editedMask.isEmpty else { return }
let length = textStorage.length
let selection = selectedRanges.map(\.rangeValue)
let wanted = bookmarks.map(\.range).filter { $0.length > 0 && NSMaxRange($0) <= length && !Self.touches(selection, line: $0) }
let look = bookmarkLineAttributes
let font = look[.font] as? NSFont
var kept = Set<Int>()
var stale: [NSRange] = []
textStorage.enumerateAttribute(.plakBookmarkLine, in: NSRange(location: 0, length: length)) { value, run, _ in
guard value != nil else { return }
if wanted.contains(run), textStorage.attribute(.font, at: run.location, effectiveRange: nil) as? NSFont == font {
kept.insert(run.location)
} else {
stale.append(run)
}
}
let added = wanted.filter { !kept.contains($0.location) }
guard !stale.isEmpty || !added.isEmpty else { return }
let plain = pageTextLook
textStorage.beginEditing()
for range in stale {
textStorage.removeAttribute(.plakBookmarkLine, range: range)
forEachTextRun(in: range) { textStorage.addAttributes(plain, range: $0) }
}
for range in added {
forEachTextRun(in: range) { textStorage.addAttributes(look, range: $0) }
}
textStorage.endEditing()
for range in stale + added {
layoutManager?.invalidateGlyphs(forCharacterRange: NSRange(location: range.location, length: 1), changeInLength: 0, actualCharacterRange: nil)
layoutManager?.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
}
}
/// True for the `=` of a bookmark line in the bookmark look, which is not shown.
func isHiddenBookmarkSign(at location: Int) -> Bool {
guard let textStorage, location < textStorage.length,
textStorage.attribute(.plakBookmarkLine, at: location, effectiveRange: nil) != nil else { return false }
let string = textStorage.string as NSString
return string.character(at: location) == 0x3D && (location == 0 || string.character(at: location - 1) == 0x0A)
}
/// The runs of `range` without an image or other object, which keep their own look.
private func forEachTextRun(in range: NSRange, _ body: (NSRange) -> Void) {
textStorage?.enumerateAttribute(.attachment, in: range) { value, run, _ in
if value == nil { body(run) }
}
}
/// True when a caret lies on `line`, its end included, or a selection overlaps it.
static func touches(_ selection: [NSRange], line: NSRange) -> Bool {
selection.contains { range in
range.length == 0
? range.location >= line.location && range.location <= NSMaxRange(line)
: range.location <= NSMaxRange(line) && NSMaxRange(range) > line.location
}
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would cut off the drop caret.
override func draw(_ dirtyRect: NSRect) {
NSGraphicsContext.saveGraphicsState()
super.draw(dirtyRect)
NSGraphicsContext.restoreGraphicsState()
if let dropCaret, dropCaret.intersects(dirtyRect) {
Theme.accent.setFill()
dropCaret.fill()
}
}
}
extension PageTextView: NSLayoutManagerDelegate {
/// Gives the hidden `=` of a bookmark line a null glyph: it stays in the text but takes no room.
func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>,
properties: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes: UnsafePointer<Int>,
font: NSFont, forGlyphRange glyphRange: NSRange) -> Int {
let hidden = (0..<glyphRange.length).filter { isHiddenBookmarkSign(at: characterIndexes[$0]) }
guard !hidden.isEmpty else { return 0 }
var changed = Array(UnsafeBufferPointer(start: properties, count: glyphRange.length))
for index in hidden { changed[index] = .null }
layoutManager.setGlyphs(glyphs, properties: changed, characterIndexes: characterIndexes, font: font, forGlyphRange: glyphRange)
return glyphRange.length
}
}
private extension NSRect {
/// The parts of this rect outside `hole`: above, below, left and right of it.
func subtracting(_ hole: NSRect?) -> [NSRect] {
guard let hole, intersects(hole) else { return [self] }
let cut = intersection(hole)
return [
NSRect(x: minX, y: minY, width: width, height: cut.minY - minY),
NSRect(x: minX, y: cut.maxY, width: width, height: maxY - cut.maxY),
NSRect(x: minX, y: cut.minY, width: cut.minX - minX, height: cut.height),
NSRect(x: cut.maxX, y: cut.minY, width: maxX - cut.maxX, height: cut.height),
].filter { $0.width > 0 && $0.height > 0 }
}
}