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

260 lines
10 KiB
Swift

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()
private let banner = NSTextField(labelWithString: "")
private var textSize = TextSize()
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.textStorage?.delegate = self
banner.font = .systemFont(ofSize: 12)
banner.textColor = Theme.ink
banner.drawsBackground = true
banner.backgroundColor = Theme.selection
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
root.addSubview(scrollView)
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()
}
/// The page file text of the page as it is now.
func pageFileText() -> String {
guard let textStorage = textView.textStorage else { return "" }
return PageText.pageFile(textStorage).text()
}
// 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()
}
// 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: 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.invalidateMargin()
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() }
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), 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()
}
@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
}
}