import AppKit import Observation import PlakCore import PlakServices /// While typing, the caret line stays above a floor at 80% of the visible height. public enum TypingScroll { public static let floor: CGFloat = 0.8 /// The scroll y that puts the caret line's bottom on the floor; nil while it is above the floor. public static func scrollY(caretBottom: CGFloat, visibleTop: CGFloat, visibleHeight: CGFloat) -> CGFloat? { let limit = visibleHeight * floor guard caretBottom - visibleTop > limit + 0.5 else { return nil } return caretBottom - limit } } /// The page: one text view in a scroll view, the column in the middle, half a window of room below the text. public final class PageViewController: NSViewController, NSTextViewDelegate, NSTextStorageDelegate { public let store: PageStore let imageStore: ImageStore let scrollView = NSScrollView() let textView: PageTextView let dragStrip = DragStripView() let bookmarkIndex = BookmarkIndexView() private let banner = NSTextField(labelWithString: "") private var textSize = TextSize() private var columnWidth = ColumnWidth() private var isLoading = false /// The characters edited since the last stamp of created dates. private var unstamped: NSRange? /// The clock for created dates. let now: () -> Date var clip: NSClipView { scrollView.contentView } /// Image files go next to the page file unless `images` says otherwise. public init(store: PageStore, images: ImageStore? = nil, now: @escaping () -> Date = Date.init) { self.store = store self.now = now imageStore = images ?? ImageStore(base: store.url.deletingLastPathComponent()) textView = PageTextView(pageText: PageText(imageBase: imageStore.base)) super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } public override func loadView() { let root = NSView(frame: NSRect(x: 0, y: 0, width: 920, height: 760)) scrollView.frame = root.bounds scrollView.autoresizingMask = [.width, .height] scrollView.drawsBackground = true scrollView.backgroundColor = Theme.paper scrollView.borderType = .noBorder scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.autohidesScrollers = true scrollView.scrollerStyle = .overlay // The page sets its own room under the transparent title bar. scrollView.automaticallyAdjustsContentInsets = false scrollView.contentInsets = NSEdgeInsetsZero scrollView.documentView = textView clip.postsFrameChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(clipFrameChanged), name: NSView.frameDidChangeNotification, object: clip) textView.delegate = self textView.now = now textView.onImages = { [weak self] images, range in self?.insertImages(images, replacing: range) } textView.onEditorChange = { [weak self] in self?.store.changed() } textView.textStorage?.delegate = self banner.font = PlakFonts.body(12) banner.textColor = Theme.ink banner.drawsBackground = true banner.backgroundColor = Theme.panel banner.alignment = .center banner.isHidden = true banner.translatesAutoresizingMaskIntoConstraints = false dragStrip.frame = NSRect(x: 0, y: root.bounds.height - DragStripView.height, width: root.bounds.width, height: DragStripView.height) dragStrip.autoresizingMask = [.width, .minYMargin] dragStrip.scrollTarget = scrollView dragStrip.setDropTarget(textView) textView.dragStrip = dragStrip bookmarkIndex.isHidden = true bookmarkIndex.onSelect = { [weak self] index in self?.showBookmark(entry: index) } textView.bookmarkIndex = bookmarkIndex root.addSubview(scrollView) root.addSubview(bookmarkIndex) root.addSubview(dragStrip) root.addSubview(banner) NSLayoutConstraint.activate([ banner.centerXAnchor.constraint(equalTo: root.centerXAnchor), banner.topAnchor.constraint(equalTo: root.topAnchor, constant: 30), banner.widthAnchor.constraint(lessThanOrEqualTo: root.widthAnchor, constant: -40), ]) view = root load(store.loaded) store.contents = { [weak self] in self?.pageFileText() } observeSaveError() } private func load(_ file: PageFile) { isLoading = true textView.textStorage?.setAttributedString(textView.pageText.attributedString(file)) isLoading = false textView.undoManager?.removeAllActions() textView.reloadBookmarks() } /// The page file text of the page as it is now, with the edit of an open editor in it. func pageFileText() -> String { guard let textStorage = textView.textStorage else { return "" } return PageText.pageFile(textStorage, draft: textView.editorDraft()).text() } /// Closes an open code block or table editor and puts its edit in the page, as before Plak hides or quits. public func closeEditor() { textView.endEditing(nil) } // MARK: Launch /// Scrolls so the end of the text sits in the vertical middle, with the caret there. public func showEnd() { view.layoutSubtreeIfNeeded() layoutPage() view.window?.makeFirstResponder(textView) textView.setSelectedRange(NSRange(location: textView.length, length: 0)) scrollEndToMiddle() } /// Pastes at the end of the page as a new block, then shows the end in the middle. public func append(from pasteboard: NSPasteboard) { closeEditor() textView.append(from: pasteboard) showEnd() } // MARK: Images /// Saves each image in the image folder and puts it in the text; a failed image is skipped. func insertImages(_ images: [PasteboardImage], replacing range: NSRange) { let paths = images.compactMap { image -> String? in do { return try save(image) } catch { NSLog("plak: cannot save image in %@: %@", imageStore.folder.path, String(describing: error)) return nil } } if paths.count < images.count { NSSound.beep() } textView.insertImages(paths, replacing: range) } private func save(_ image: PasteboardImage) throws -> String { switch image { case let .file(url): try imageStore.copy(file: url) case let .data(data): try imageStore.write(imageData: data) } } // MARK: Text size @objc public func makeTextBigger(_ sender: Any?) { textSize.bigger() applyTextSize() } @objc public func makeTextSmaller(_ sender: Any?) { textSize.smaller() applyTextSize() } @objc public func makeTextStandardSize(_ sender: Any?) { textSize.reset() applyTextSize() } private func applyTextSize() { textView.pageText.setBodySize(textSize.body) textView.applyStyle() layoutPage() textView.scrollRangeToVisible(textView.selectedRange()) } // MARK: Column width @objc public func makeColumnWider(_ sender: Any?) { columnWidth.wider() applyColumnWidth() } @objc public func makeColumnNarrower(_ sender: Any?) { columnWidth.narrower() applyColumnWidth() } private func applyColumnWidth() { layoutPage() textView.scrollRangeToVisible(textView.selectedRange()) } // MARK: Text changes public func textStorage(_ textStorage: NSTextStorage, willProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) { guard editedMask.contains(.editedCharacters), !isLoading else { return } unstamped = unstamped.map { NSUnionRange($0, editedRange) } ?? editedRange } public func textDidChange(_ notification: Notification) { stampBlocks() store.changed() textView.reloadBookmarks() if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() } else { layoutBookmarkIndex() } if !textView.isReplacingObject { keepCaretAboveFloor() } } /// Runs after the edit, not inside it: attribute changes during an edit move the caret to the end of the block. private func stampBlocks() { guard let range = unstamped, let textStorage = textView.textStorage else { return } unstamped = nil let length = textStorage.length let location = min(range.location, length) textStorage.beginEditing() PageText.stampBlocks(textStorage, around: NSRange(location: location, length: min(NSMaxRange(range), length) - location), now: now) textStorage.endEditing() } public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool { guard selector == #selector(NSResponder.moveToEndOfDocument(_:)) else { return false } textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0)) scrollEndToMiddle() return true } // MARK: Layout /// Puts the column in the middle; a short page gets more room on top so its end stays in the middle. private func layoutPage() { let visible = clip.bounds.size guard visible.width > 0, let container = textView.textContainer, let layoutManager = textView.layoutManager else { return } let column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body, characters: columnWidth.characters), visible.width - PageMetrics.sideMargin * 2)) if container.size.width != column { container.size = NSSize(width: column, height: CGFloat.greatestFiniteMagnitude) } layoutManager.ensureLayout(for: container) let side = floor((visible.width - column) / 2) let bottom = round(visible.height / 2) let endMid = textView.lineRect(at: textView.length).midY - textView.topSpace let top = max(PageMetrics.topInset, round(visible.height / 2 - endMid)) textView.minSize = NSSize(width: visible.width, height: visible.height) textView.setSpaces(side: side, top: top, bottom: bottom) if textView.frame.width != visible.width { textView.setFrameSize(NSSize(width: visible.width, height: textView.frame.height)) } textView.sizeToFit() textView.positionEditor() layoutBookmarkIndex() } /// Shows the bookmark index at the top left when bookmarks are wide, as wide as the side space. private func layoutBookmarkIndex() { let labels = textView.bookmarksAreWide ? textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount).map(\.label) : [] let wasHidden = bookmarkIndex.isHidden bookmarkIndex.isHidden = labels.isEmpty if !labels.isEmpty { let inset = PageMetrics.bookmarkIndexInset let width = max(0, textView.sideSpace - inset - PageMetrics.bookmarkGap * 2) bookmarkIndex.show(labels: labels, font: textView.bookmarkFont, width: width) let top = view.bounds.height - PageMetrics.topInset let height = max(0, min(bookmarkIndex.contentHeight, top - inset)) let frame = NSRect(x: inset, y: top - height, width: width, height: height) if bookmarkIndex.frame != frame { bookmarkIndex.frame = frame } // When the entries do not fit, the lowest bookmarks stay in sight. bookmarkIndex.contentView.scroll(to: NSPoint(x: 0, y: max(0, bookmarkIndex.contentHeight - height))) bookmarkIndex.reflectScrolledClipView(bookmarkIndex.contentView) } if wasHidden != bookmarkIndex.isHidden || !labels.isEmpty { view.window?.invalidateCursorRects(for: textView) } } /// Puts the caret at the end of the bookmark line and scrolls that line to the vertical middle. /// `entry` counts from the first entry of the index, which holds only the last bookmarks. func showBookmark(entry: Int) { let shown = textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount) let index = shown.startIndex + entry closeEditor() guard textView.bookmarks.indices.contains(index) else { return } let end = NSMaxRange(textView.bookmarks[index].range) view.window?.makeFirstResponder(textView) textView.setSelectedRange(NSRange(location: end, length: 0)) scroll(toY: textView.lineRect(at: end).midY - clip.bounds.height / 2) } @objc private func clipFrameChanged(_ notification: Notification) { layoutPage() } // MARK: Scrolling private func scroll(toY y: CGFloat) { let maxY = max(0, textView.frame.height - clip.bounds.height) clip.scroll(to: NSPoint(x: 0, y: min(max(0, round(y)), maxY))) scrollView.reflectScrolledClipView(clip) } private func scrollEndToMiddle() { scroll(toY: textView.lineRect(at: textView.length).midY - clip.bounds.height / 2) } private func keepCaretAboveFloor() { let caret = textView.lineRect(at: textView.selectedRange().location) if let y = TypingScroll.scrollY(caretBottom: caret.maxY, visibleTop: clip.bounds.minY, visibleHeight: clip.bounds.height) { scroll(toY: y) } } // MARK: Save error private func observeSaveError() { let message = withObservationTracking { store.saveError } onChange: { [weak self] in Task { @MainActor in self?.observeSaveError() } } banner.stringValue = message.map { " Cannot save the page: \($0) " } ?? "" banner.isHidden = message == nil } }