adds first version of the app

This commit is contained in:
2026-10-17 14:33:43 +02:00
parent ab1abadcd1
commit 7b891819b0
3066 changed files with 29585 additions and 0 deletions
+114
View File
@@ -0,0 +1,114 @@
import AppKit
/// Decoded images by file path, shared by every image of the page.
public final class ImageCache {
private var images: [String: NSImage] = [:]
public init() {}
/// The image at `url`; a missing or unreadable file is not kept, so it shows once it exists.
func image(at url: URL) -> NSImage? {
if let image = images[url.path] { return image }
guard let image = NSImage(contentsOf: url), image.isValid, image.size.width > 0, image.size.height > 0 else { return nil }
images[url.path] = image
return image
}
}
/// An image in the page: one character that knows the path of its image line.
final class ImageAttachment: NSTextAttachment {
/// Relative to the page file folder, as `images/<name>`.
let path: String
init(path: String, image: NSImage?, font: NSFont) {
self.path = path
super.init(data: nil, ofType: nil)
attachmentCell = image.map { PageImageCell(imageCell: $0) } ?? MissingImageCell(font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var isMissing: Bool {
attachmentCell is MissingImageCell
}
}
/// An image at its own size, scaled down to the width of the line, never up.
final class PageImageCell: NSTextAttachmentCell {
static func fitted(_ size: NSSize, width: CGFloat) -> NSSize {
guard size.width > width, size.width > 0, width > 0 else { return size }
return NSSize(width: floor(width), height: floor(size.height * width / size.width))
}
override func cellSize() -> NSSize {
image?.size ?? .zero
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
NSRect(origin: .zero, size: Self.fitted(cellSize(), width: lineFrag.width - max(0, position.x)))
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
image?.draw(in: cellFrame, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true,
hints: [.interpolation: NSImageInterpolation.high.rawValue])
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
/// The `image missing` text in place of an image whose file is gone.
final class MissingImageCell: NSTextAttachmentCell {
static let label = "image missing"
private(set) var text: NSAttributedString
init(font: NSFont) {
text = Self.text(font)
super.init(textCell: "")
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
text = Self.text(font)
}
private static func text(_ font: NSFont) -> NSAttributedString {
NSAttributedString(string: label, attributes: [.font: font, .foregroundColor: Theme.inkMuted])
}
override func cellSize() -> NSSize {
let size = text.size()
return NSSize(width: ceil(size.width), height: ceil(size.height))
}
/// Puts the label's baseline on the line's baseline.
override func cellBaselineOffset() -> NSPoint {
let font = text.attribute(.font, at: 0, effectiveRange: nil) as? NSFont
return NSPoint(x: 0, y: font?.descender ?? 0)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
text.draw(in: cellFrame)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
+284
View File
@@ -0,0 +1,284 @@
import AppKit
import PlakCore
extension NSAttributedString.Key {
/// The created date of the block a character is in.
static let plakCreated = NSAttributedString.Key("plakCreated")
/// A block read from the page file without a date line; it is never stamped.
static let plakUndated = NSAttributedString.Key("plakUndated")
}
/// Turns the page file into the text of the page view and back, and keeps the created dates of the blocks.
final class PageText {
/// The folder of the page file; image paths are relative to it.
let imageBase: URL
let images: ImageCache
private(set) var font: NSFont
private(set) var lineHeight: CGFloat = 0
/// The look of every character; an image leaves out the baseline offset.
private(set) var attributes: [NSAttributedString.Key: Any] = [:]
init(imageBase: URL, images: ImageCache = ImageCache(), bodySize: CGFloat = TextSize.standard) {
self.imageBase = imageBase
self.images = images
font = PlakFonts.body(bodySize)
setBodySize(bodySize)
}
/// The minimum line height lets a line with an image grow to the image.
func setBodySize(_ size: CGFloat) {
font = PlakFonts.body(size)
lineHeight = PageMetrics.lineHeight(font)
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight
attributes = [
.font: font,
.foregroundColor: Theme.ink,
.paragraphStyle: style,
.baselineOffset: max(0, (lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
]
}
var imageAttributes: [NSAttributedString.Key: Any] {
var attributes = attributes
attributes[.baselineOffset] = nil
return attributes
}
// MARK: Page file to text
/// The text of the page; every character of a block carries its date, or the undated mark.
func attributedString(_ file: PageFile) -> NSAttributedString {
let image = "\u{FFFC}"
let string = file.lines.map { line in
if case .image = line { return image }
return line.text
}.joined(separator: "\n")
let text = NSMutableAttributedString(string: string, attributes: attributes)
var starts: [Int] = []
starts.reserveCapacity(file.lines.count + 1)
var location = 0
for line in file.lines {
starts.append(location)
if case .image = line {
location += 2
} else {
location += (line.text as NSString).length + 1
}
}
starts.append(location)
text.beginEditing()
for (index, line) in file.lines.enumerated() {
if case let .image(path) = line {
text.setAttributes(attachmentAttributes(path), range: NSRange(location: starts[index], length: 1))
}
}
for block in file.blocks {
let range = NSRange(location: starts[block.lowerBound], length: starts[block.upperBound] - 1 - starts[block.lowerBound])
if let date = file.dates[block.lowerBound] {
text.addAttribute(.plakCreated, value: date, range: range)
} else {
text.addAttribute(.plakUndated, value: true, range: range)
}
}
text.endEditing()
return text
}
/// Pasted plain text; a line that is exactly an image line of an existing image file becomes that image.
func attributedString(plainText: String) -> NSAttributedString {
let text = NSMutableAttributedString()
let lines = plainText.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
for (index, line) in lines.enumerated() {
if index > 0 { text.append(NSAttributedString(string: "\n", attributes: attributes)) }
if let path = PageFile.imagePath(fromLine: line), FileManager.default.fileExists(atPath: imageURL(path).path) {
text.append(imageString(path))
} else {
text.append(NSAttributedString(string: line, attributes: attributes))
}
}
return text
}
func imageString(_ path: String) -> NSAttributedString {
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(path))
}
func newline() -> NSAttributedString {
NSAttributedString(string: "\n", attributes: attributes)
}
private func attachmentAttributes(_ path: String) -> [NSAttributedString.Key: Any] {
var attributes = imageAttributes
attributes[.attachment] = ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font)
return attributes
}
private func imageURL(_ path: String) -> URL {
imageBase.appendingPathComponent(path)
}
// MARK: Text to page file
/// The page file of the text: one line per text line, an image always on a line of its own.
static func pageFile(_ text: NSAttributedString) -> PageFile {
let string = text.string as NSString
guard string.length > 0 else { return PageFile() }
var lines: [PageFile.Line] = []
var dates: [Int: Date] = [:]
var previousBlank = true
var location = 0
while location <= string.length {
let end = string.lineEnd(from: location)
let pieces = lineContents(text, NSRange(location: location, length: end - location))
let blank = pieces.count == 1 && pieces[0].isBlank
if !blank, previousBlank, location < string.length, let date = text.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date {
dates[lines.count] = date
}
lines += pieces
previousBlank = blank
location = end + 1
}
return PageFile(lines: lines, dates: dates)
}
/// Plain text of a range, as for the pasteboard: each image becomes its image line.
static func plainText(_ text: NSAttributedString, range: NSRange) -> String {
var out = ""
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
if let image = value as? ImageAttachment {
out += String(repeating: PageFile.imageLine(image.path), count: run.length)
} else {
out += (text.string as NSString).substring(with: run)
}
}
return out
}
/// One text line as page file lines; text typed beside an image goes on its own line.
private static func lineContents(_ text: NSAttributedString, _ range: NSRange) -> [PageFile.Line] {
let string = text.string as NSString
guard range.length > 0, string.range(of: "\u{FFFC}", range: range).location != NSNotFound else {
return [.text(string.substring(with: range))]
}
var lines: [PageFile.Line] = []
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
if let image = value as? ImageAttachment {
lines += Array(repeating: .image(image.path), count: run.length)
} else {
let piece = string.substring(with: run)
if !PageFile.isBlank(piece) { lines.append(.text(piece)) }
}
}
return lines.isEmpty ? [.text("")] : lines
}
// MARK: Created dates
/// Gives every block around an edit one state: the first date or undated mark found in it, else `now`.
///
/// Characters between blocks lose their state, so typing that starts a new block never takes
/// the date of the block above.
static func stampBlocks(_ text: NSMutableAttributedString, around edit: NSRange, now: () -> Date) {
let string = text.string as NSString
let region = string.blockRegion(around: edit)
var blocks: [NSRange] = []
var blockStart: Int?
var previousEnd = region.location
var location = region.location
while location <= NSMaxRange(region) {
let end = string.lineEnd(from: location)
if string.isBlankLine(NSRange(location: location, length: end - location)) {
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
blockStart = nil
} else if blockStart == nil {
blockStart = location
}
previousEnd = end
location = end + 1
}
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
var gapStart = region.location
for range in blocks + [NSRange(location: min(NSMaxRange(region) + 1, string.length), length: 0)] {
let gap = NSRange(location: gapStart, length: range.location - gapStart)
if gap.length > 0 {
text.removeAttribute(.plakCreated, range: gap)
text.removeAttribute(.plakUndated, range: gap)
}
gapStart = NSMaxRange(range)
}
for block in blocks {
var date: Date?
var undated = false
text.enumerateAttributes(in: block) { attributes, _, stop in
if let found = attributes[.plakCreated] as? Date {
date = found
stop.pointee = true
} else if attributes[.plakUndated] != nil {
undated = true
stop.pointee = true
}
}
if undated {
if !text.isUniform(.plakUndated, in: block) { text.addAttribute(.plakUndated, value: true, range: block) }
text.removeAttribute(.plakCreated, range: block)
} else {
let value = date ?? now()
if !text.isUniform(.plakCreated, value as NSDate, in: block) { text.addAttribute(.plakCreated, value: value, range: block) }
text.removeAttribute(.plakUndated, range: block)
}
}
}
}
private extension NSAttributedString {
func isUniform(_ key: NSAttributedString.Key, _ value: NSObject = true as NSNumber, in range: NSRange) -> Bool {
var effective = NSRange()
let found = attribute(key, at: range.location, longestEffectiveRange: &effective, in: range) as? NSObject
return found == value && effective == range
}
}
extension NSString {
/// The index of the newline that ends the line at `location`, or the length for the last line.
func lineEnd(from location: Int) -> Int {
guard location < length else { return length }
let found = range(of: "\n", range: NSRange(location: location, length: length - location))
return found.location == NSNotFound ? length : found.location
}
func lineStart(at location: Int) -> Int {
guard location > 0 else { return 0 }
let found = range(of: "\n", options: .backwards, range: NSRange(location: 0, length: location))
return found.location == NSNotFound ? 0 : found.location + 1
}
func isBlankLine(_ range: NSRange) -> Bool {
PageFile.isBlank(substring(with: range))
}
/// The lines of the blocks an edit touches; an edit in blank lines also takes the block above and below.
func blockRegion(around edit: NSRange) -> NSRange {
var start = lineStart(at: edit.location)
var inBlock = !isBlankLine(NSRange(location: start, length: lineEnd(from: start) - start))
while start > 0 {
let previous = lineStart(at: start - 1)
let blank = isBlankLine(NSRange(location: previous, length: start - 1 - previous))
if blank, inBlock { break }
if !blank { inBlock = true }
start = previous
}
let editEnd = min(NSMaxRange(edit), length)
var end = lineEnd(from: editEnd)
inBlock = !isBlankLine(NSRange(location: lineStart(at: editEnd), length: end - lineStart(at: editEnd)))
while end < length {
let nextEnd = lineEnd(from: end + 1)
let blank = isBlankLine(NSRange(location: end + 1, length: nextEnd - end - 1))
if blank, inBlock { break }
if !blank { inBlock = true }
end = nextEnd
}
return NSRange(location: start, length: end - start)
}
}
+446
View File
@@ -0,0 +1,446 @@
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
}
}
@@ -0,0 +1,259 @@
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
}
}
@@ -0,0 +1,42 @@
import AppKit
import PlakServices
/// One image on a pasteboard: a file to copy, or raw data to write as PNG.
public enum PasteboardImage: Equatable {
case file(URL)
case data(Data)
}
/// Reads the images a paste or a drop brings.
public enum PasteboardImages {
public static let dragTypes: [NSPasteboard.PasteboardType] = [.fileURL, .png, .tiff]
/// The images on the pasteboard, empty when it holds none.
///
/// File URLs win over data: Finder puts the file icon as TIFF next to a copied file. Rich
/// text keeps its picture of the text out, so a paste from a word processor stays text.
public static func read(_ pasteboard: NSPasteboard) -> [PasteboardImage] {
let urls = fileURLs(pasteboard)
if !urls.isEmpty { return urls.filter(ImageStore.isImageFile).map(PasteboardImage.file) }
guard hasImageData(pasteboard) else { return [] }
if let png = pasteboard.data(forType: .png) { return [.data(png)] }
if let tiff = pasteboard.data(forType: .tiff) { return [.data(tiff)] }
return []
}
/// Whether `read` finds an image, without loading image data, for every move of a drag.
public static func contains(_ pasteboard: NSPasteboard) -> Bool {
let urls = fileURLs(pasteboard)
return urls.isEmpty ? hasImageData(pasteboard) : urls.contains(where: ImageStore.isImageFile)
}
private static func fileURLs(_ pasteboard: NSPasteboard) -> [URL] {
pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
}
private static func hasImageData(_ pasteboard: NSPasteboard) -> Bool {
let types = pasteboard.types ?? []
if types.contains(.rtf) || types.contains(.rtfd) { return false }
return types.contains(.png) || types.contains(.tiff)
}
}