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 } } /// A drawn bookmark label and its rules. struct BookmarkMark: Equatable { var label: String var rect: NSRect var rules: [NSRect] } /// The one editable text view of the page, on TextKit 1: the reading column, the bookmark labels, 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() } @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 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 { 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)) } /// 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 = 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) } /// 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] = [] private var widestBookmarkLabel: CGFloat = 0 /// 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 invalidateBookmarks() } /// True when the side space holds the bookmark index on the left and the full labels on the right. var bookmarksAreWide: Bool { !bookmarks.isEmpty && sideSpace >= PageMetrics.bookmarkWideSide(widestLabel: widestBookmarkLabel, reasonableLabel: reasonableBookmarkLabel) } /// The width of a label of `bookmarkLabelCharacters` characters. var reasonableBookmarkLabel: CGFloat { let sample = String(repeating: "0", count: PageMetrics.bookmarkLabelCharacters) return NSAttributedString(string: sample, attributes: [.font: bookmarkFont]).size().width } var bookmarkFont: NSFont { PlakFonts.mono(round(pageText.font.pointSize * PageMetrics.dateScale)) } /// The look of a bookmark label; a label too long for its room ends in an ellipsis. var bookmarkAttributes: [NSAttributedString.Key: Any] { let style = NSMutableParagraphStyle() style.lineBreakMode = .byTruncatingTail return [.font: bookmarkFont, .foregroundColor: Theme.inkMuted, .paragraphStyle: style] } /// NSTextView leaves the clip narrowed to the column after drawing, which would hide every label right of it. override func draw(_ dirtyRect: NSRect) { NSGraphicsContext.saveGraphicsState() super.draw(dirtyRect) NSGraphicsContext.restoreGraphicsState() if let dropCaret, dropCaret.intersects(dirtyRect) { Theme.accent.setFill() dropCaret.fill() } let attributes = bookmarkAttributes for mark in bookmarkMarks(in: dirtyRect) { Theme.bookmarkRule.setFill() mark.rules.forEach { $0.fill() } NSAttributedString(string: mark.label, attributes: attributes) .draw(with: mark.rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine]) } } /// Redraws the visible page: the labels right of the column are not looked after by the layout. func invalidateBookmarks() { setNeedsDisplay(visibleRect) } /// The labels and rules of the bookmarks whose line lies in `rect`. func bookmarkMarks(in rect: NSRect) -> [BookmarkMark] { guard !bookmarks.isEmpty, let layoutManager, let textContainer else { return [] } let wide = bookmarksAreWide let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont] let columnRight = textContainerOrigin.x + textContainer.size.width let gap = PageMetrics.bookmarkGap var marks: [BookmarkMark] = [] for bookmark in bookmarks { let label = wide ? bookmark.label : bookmark.date guard let label, NSMaxRange(bookmark.range) <= length else { continue } let size = NSAttributedString(string: label, attributes: attributes).size() let width = ceil(size.width), height = ceil(size.height) let lastCharacter = max(bookmark.range.location, NSMaxRange(bookmark.range) - 1) let line = lineRect(at: wide ? bookmark.range.location : lastCharacter) guard line.maxY >= rect.minY, line.minY <= rect.maxY else { continue } let midY = line.minY + min(line.height, pageText.lineHeight) / 2 let labelY = round(midY - height / 2) let ruleY = floor(midY) if wide { let ruleStart = columnRight + gap let labelMaxX = bounds.maxX - PageMetrics.bookmarkTail - gap let room = labelMaxX - (ruleStart + PageMetrics.bookmarkRuleMinimum + gap) guard room > 0 else { continue } let labelX = labelMaxX - min(width, room) marks.append(BookmarkMark( label: label, rect: NSRect(x: labelX, y: labelY, width: labelMaxX - labelX, height: height), rules: [ NSRect(x: ruleStart, y: ruleY, width: labelX - gap - ruleStart, height: 1), NSRect(x: labelMaxX + gap, y: ruleY, width: bounds.maxX - labelMaxX - gap, height: 1), ] )) } else { let glyph = layoutManager.glyphIndexForCharacter(at: lastCharacter) let textEnd = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil).maxX + textContainerOrigin.x let labelX = columnRight - width guard labelX - gap > textEnd + gap else { continue } var rules = [NSRect(x: textEnd + gap, y: ruleY, width: labelX - gap - textEnd - gap, height: 1)] let tailEnd = min(columnRight + gap + PageMetrics.bookmarkTail, bounds.maxX) if tailEnd - columnRight - gap >= 4 { rules.append(NSRect(x: columnRight + gap, y: ruleY, width: tailEnd - columnRight - gap, height: 1)) } marks.append(BookmarkMark(label: label, rect: NSRect(x: labelX, y: labelY, width: width, height: height), rules: rules)) } } return marks } } 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 } } }