improves plak

This commit is contained in:
2026-10-17 17:33:13 +02:00
parent 7b891819b0
commit a92d6f8871
633 changed files with 17623 additions and 7556 deletions
+164
View File
@@ -0,0 +1,164 @@
import AppKit
import PlakCore
/// The look of code: the mono font in ink, with a colour for each kind of token.
enum CodeStyle {
static func attributes(_ font: NSFont) -> [NSAttributedString.Key: Any] {
[.font: font, .foregroundColor: Theme.ink]
}
static func color(_ kind: CodeTokenKind) -> NSColor {
switch kind {
case .keyword: Theme.codeKeyword
case .string: Theme.codeString
case .number: Theme.codeNumber
case .comment: Theme.codeComment
case .variable: Theme.codeVariable
case .tag: Theme.codeTag
case .attribute: Theme.codeAttribute
}
}
/// Gives all of `text` the code look, then the colours of its tokens.
static func highlight(_ text: NSMutableAttributedString, kind: FenceKind, font: NSFont) {
let all = NSRange(location: 0, length: text.length)
text.beginEditing()
text.setAttributes(attributes(font), range: all)
for token in CodeHighlighter.tokens(text.string, kind: kind) where token.range.upperBound <= text.length {
text.addAttribute(.foregroundColor, value: color(token.kind), range: NSRange(token.range))
}
text.endEditing()
}
/// Colours the tokens as temporary attributes, which change the drawing and never the layout.
static func colorize(_ layoutManager: NSLayoutManager, text: String, kind: FenceKind) {
let length = (text as NSString).length
layoutManager.removeTemporaryAttribute(.foregroundColor, forCharacterRange: NSRange(location: 0, length: length))
for token in CodeHighlighter.tokens(text, kind: kind) where token.range.upperBound <= length {
layoutManager.addTemporaryAttribute(.foregroundColor, value: color(token.kind), forCharacterRange: NSRange(token.range))
}
}
}
/// The part of `frame` the current drawing paints, in the coordinates of the view being drawn; nil when none.
/// An empty clip gives a null box, whose origin is infinite.
@MainActor
func drawingClip(within frame: NSRect) -> NSRect? {
guard let box = NSGraphicsContext.current?.cgContext.boundingBoxOfClipPath else { return frame }
let visible = frame.intersection(box)
return visible.isFiniteArea ? visible : nil
}
extension NSRect {
/// Not null, not empty, and with finite edges: safe to turn into row and glyph numbers.
var isFiniteArea: Bool {
!isNull && !isEmpty && minX.isFinite && minY.isFinite && maxX.isFinite && maxY.isFinite
}
}
/// Code laid out at a width the way the code editor lays it out, for the height and the drawing of a code block.
final class CodeLayout {
private let storage = NSTextStorage()
private let layoutManager = NSLayoutManager()
private let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude))
init() {
storage.addLayoutManager(layoutManager)
container.lineFragmentPadding = 0
layoutManager.addTextContainer(container)
}
func set(_ body: String, kind: FenceKind, font: NSFont) {
storage.setAttributedString(NSAttributedString(string: body))
CodeStyle.highlight(storage, kind: kind, font: font)
}
/// The height of the whole block: the wrapped code and the padding around it.
func blockHeight(width: CGFloat) -> CGFloat {
let padding = PageMetrics.codePadding
let textWidth = max(1, width - padding * 2)
if container.size.width != textWidth { container.size = NSSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude) }
layoutManager.ensureLayout(for: container)
return ceil(layoutManager.usedRect(for: container).height) + padding * 2
}
/// Draws the lines of the block that lie in `clip`.
func draw(in block: NSRect, clip: NSRect) {
_ = blockHeight(width: block.width)
let origin = NSPoint(x: block.minX + PageMetrics.codePadding, y: block.minY + PageMetrics.codePadding)
let visible = clip.intersection(block)
guard visible.isFiniteArea else { return }
let range = layoutManager.glyphRange(forBoundingRect: visible.offsetBy(dx: -origin.x, dy: -origin.y), in: container)
layoutManager.drawGlyphs(forGlyphRange: range, at: origin)
}
}
/// A code block in the page: one character that knows its kind and its body.
final class CodeAttachment: NSTextAttachment {
let kind: FenceKind
let body: String
init(kind: FenceKind, body: String, font: NSFont) {
self.kind = kind
self.body = body
super.init(data: nil, ofType: nil)
attachmentCell = CodeBlockCell(kind: kind, body: body, font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
}
/// Highlighted code on the code paper, over the full width of the column.
final class CodeBlockCell: NSTextAttachmentCell, ObjectCell {
private let kind: FenceKind
private let body: String
private let layout = CodeLayout()
private var size = NSSize.zero
/// AppKit reads it in `cellFrame`, which it does not mark main-actor; the page lays out on the main thread only.
nonisolated(unsafe) var editingHeight: CGFloat?
init(kind: FenceKind, body: String, font: NSFont) {
self.kind = kind
self.body = body
super.init(textCell: "")
layout.set(body, kind: kind, font: font)
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
layout.set(body, kind: kind, font: font)
}
override func cellSize() -> NSSize {
size
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
let width = floor(lineFrag.width - max(0, position.x))
size = NSSize(width: width, height: editingHeight ?? layout.blockHeight(width: width))
return NSRect(origin: .zero, size: size)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
Theme.codePaper.setFill()
NSBezierPath(roundedRect: cellFrame, xRadius: PageMetrics.codeCornerRadius, yRadius: PageMetrics.codeCornerRadius).fill()
guard editingHeight == nil, let clip = drawingClip(within: cellFrame) else { return }
layout.draw(in: cellFrame, clip: clip)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
+164
View File
@@ -0,0 +1,164 @@
import AppKit
import PlakCore
/// The editor over a code block: the same font, colours and place as the block, highlighted while you type.
final class CodeEditorView: NSTextView, ObjectEditor {
let kind: FenceKind
private let original: String
/// Its own undo, so that edits in the code never mix with the undo of the page.
private let ownUndo = UndoManager()
var onEnd: ((EditorExit) -> Void)?
var onResize: (() -> Void)?
var onChange: (() -> Void)?
init(kind: FenceKind, body: String, font: NSFont) {
self.kind = kind
original = body
let storage = NSTextStorage()
let layout = NSLayoutManager()
storage.addLayoutManager(layout)
let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude))
container.widthTracksTextView = true
container.lineFragmentPadding = 0
layout.addTextContainer(container)
super.init(frame: NSRect(x: 0, y: 0, width: 100, height: 100), textContainer: container)
isRichText = false
importsGraphics = false
usesFontPanel = false
usesRuler = false
allowsUndo = true
isVerticallyResizable = false
isHorizontallyResizable = false
drawsBackground = true
backgroundColor = Theme.codePaper
wantsLayer = true
layer?.cornerRadius = PageMetrics.codeCornerRadius
layer?.masksToBounds = true
textContainerInset = NSSize(width: PageMetrics.codePadding, height: PageMetrics.codePadding)
isAutomaticQuoteSubstitutionEnabled = false
isAutomaticDashSubstitutionEnabled = false
isAutomaticTextReplacementEnabled = false
isAutomaticSpellingCorrectionEnabled = false
isAutomaticLinkDetectionEnabled = false
isAutomaticDataDetectionEnabled = false
isContinuousSpellCheckingEnabled = false
smartInsertDeleteEnabled = false
insertionPointColor = Theme.accent
selectedTextAttributes = [.backgroundColor: Theme.selection]
storage.setAttributedString(NSAttributedString(string: body, attributes: CodeStyle.attributes(font)))
typingAttributes = CodeStyle.attributes(font)
colorize()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var view: NSView { self }
var focusView: NSView { self }
override var undoManager: UndoManager? { ownUndo }
func size(available width: CGFloat) -> NSSize {
if frame.width != width { setFrameSize(NSSize(width: width, height: frame.height)) }
guard let layoutManager, let textContainer else { return NSSize(width: width, height: frame.height) }
layoutManager.ensureLayout(for: textContainer)
return NSSize(width: width, height: ceil(layoutManager.usedRect(for: textContainer).height) + textContainerInset.height * 2)
}
func setFont(_ font: NSFont) {
typingAttributes = CodeStyle.attributes(font)
textStorage?.setAttributes(typingAttributes, range: NSRange(location: 0, length: textStorage?.length ?? 0))
colorize()
onResize?()
}
func edit() -> ObjectEdit {
let body = PageFile.unixNewlines(string)
if body == original { return .unchanged }
if PageFile.isBlank(body) { return .removed }
return .replaced(kind, body)
}
private func colorize() {
guard let layoutManager else { return }
CodeStyle.colorize(layoutManager, text: string, kind: kind)
}
/// A composition keeps its marked-text look until it is committed.
override func didChangeText() {
super.didChangeText()
if !hasMarkedText() { colorize() }
onResize?()
onChange?()
}
// MARK: Keys
/// A key command the editor does not know beeps, so it never reaches the page behind it.
override func doCommand(by selector: Selector) {
if responds(to: selector) {
super.doCommand(by: selector)
} else {
NSSound.beep()
}
}
override func insertTab(_ sender: Any?) {
insertText(" ", replacementRange: selectedRange())
}
/// Esc closes the editor and never hides Plak; during an input-method composition it only cancels that.
override func cancelOperation(_ sender: Any?) {
if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else {
onEnd?(.after)
}
}
override func moveUp(_ sender: Any?) {
isOnLine(first: true) ? onEnd?(.above) : super.moveUp(sender)
}
override func moveDown(_ sender: Any?) {
isOnLine(first: false) ? onEnd?(.below) : super.moveDown(sender)
}
/// Whether the caret is on the first or the last laid-out line.
private func isOnLine(first: Bool) -> Bool {
guard let layoutManager, let textContainer, selectedRange().length == 0 else { return false }
layoutManager.ensureLayout(for: textContainer)
let length = (string as NSString).length
guard length > 0 else { return true }
let caret = lineRect(at: selectedRange().location)
let edge = first ? lineRect(at: 0) : lineRect(at: length)
return abs(caret.minY - edge.minY) < 0.5
}
private func lineRect(at location: Int) -> NSRect {
guard let layoutManager else { return .zero }
let length = (string as NSString).length
if location >= length, !layoutManager.extraLineFragmentRect.isEmpty { return layoutManager.extraLineFragmentRect }
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
return layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
}
// MARK: Undo
@objc func undo(_ sender: Any?) {
ownUndo.undo()
}
@objc func redo(_ sender: Any?) {
ownUndo.redo()
}
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(undo(_:)): ownUndo.canUndo
case #selector(redo(_:)): ownUndo.canRedo
default: super.validateUserInterfaceItem(item)
}
}
}
+188
View File
@@ -0,0 +1,188 @@
import AppKit
/// Opens an editor over a code block or table, keeps it in place, and puts the edit back as one undoable change.
extension PageTextView {
/// The location of the code block or table under a point; nil when the point is not on one.
func object(at point: NSPoint) -> Int? {
guard let layoutManager, let textContainer, let textStorage, textStorage.length > 0 else { return nil }
let inContainer = NSPoint(x: point.x - textContainerOrigin.x, y: point.y - textContainerOrigin.y)
let location = layoutManager.characterIndexForGlyph(at: layoutManager.glyphIndex(for: inContainer, in: textContainer))
guard location < textStorage.length, isObject(at: location), objectRect(at: location).contains(point) else { return nil }
return location
}
func isObject(at location: Int) -> Bool {
let attachment = textStorage?.attribute(.attachment, at: location, effectiveRange: nil)
return attachment is CodeAttachment || attachment is TableAttachment
}
/// Where the attachment at `location` is drawn, in this view's coordinates.
func objectRect(at location: Int) -> NSRect {
guard let layoutManager else { return .zero }
layoutManager.ensureLayout(forCharacterRange: NSRange(location: location, length: 1))
let glyph = layoutManager.glyphIndexForCharacter(at: location)
let fragment = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
let position = layoutManager.location(forGlyphAt: glyph)
let size = layoutManager.attachmentSize(forGlyphAt: glyph)
return NSRect(x: fragment.minX + position.x, y: fragment.minY + position.y - size.height, width: size.width, height: size.height)
.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// Opens the editor of the object at `location`; a click point puts the caret or picks the cell there.
func openEditor(at location: Int, point: NSPoint? = nil) {
if editor != nil { endEditing(nil) }
guard let textStorage, location < textStorage.length,
let attachment = textStorage.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment else { return }
let rect = objectRect(at: location)
let opened: ObjectEditor
switch attachment {
case let code as CodeAttachment:
opened = CodeEditorView(kind: code.kind, body: code.body, font: pageText.codeFont)
case let table as TableAttachment:
let layout = TableLayout(table.table, font: pageText.codeFont)
let cell = point.flatMap { layout.position(at: NSPoint(x: $0.x - rect.minX, y: $0.y - rect.minY)) }
opened = TableGridView(table: table.table, font: pageText.codeFont, selected: cell ?? TablePosition(row: 0, column: 0))
default:
return
}
opened.onEnd = { [weak self] exit in self?.endEditing(exit) }
opened.onResize = { [weak self] in self?.positionEditor() }
opened.onChange = { [weak self] in self?.onEditorChange?() }
editor = opened
editedAttachment = attachment
editorLocation = location
addSubview(opened.view)
positionEditor()
window?.makeFirstResponder(opened.focusView)
if let code = opened as? CodeEditorView {
let caret = point.map { code.characterIndexForInsertion(at: code.convert($0, from: self)) } ?? (code.string as NSString).length
code.setSelectedRange(NSRange(location: caret, length: 0))
}
}
/// The location of the object the open editor edits, found again when the text moved it; nil when it is gone.
func editedLocation() -> Int? {
guard let editedAttachment, let textStorage else { return nil }
if editorLocation < textStorage.length,
textStorage.attribute(.attachment, at: editorLocation, effectiveRange: nil) as AnyObject? === editedAttachment {
return editorLocation
}
var found: Int?
textStorage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: textStorage.length)) { value, range, stop in
guard value as AnyObject? === editedAttachment else { return }
found = range.location
stop.pointee = true
}
if let found { editorLocation = found }
return found
}
/// Puts the editor over its object; the object takes the height of the editor, so the text below makes room.
func positionEditor() {
guard let editor, let textContainer, let layoutManager, let location = editedLocation(),
let cell = objectCell(at: location) else { return }
var rect = objectRect(at: location)
let size = editor.size(available: textContainer.size.width + textContainerOrigin.x - rect.minX)
if cell.editingHeight != size.height {
cell.editingHeight = size.height
let range = NSRange(location: location, length: 1)
layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
layoutManager.invalidateDisplay(forCharacterRange: range)
sizeToFit()
invalidateMargin()
rect = objectRect(at: location)
}
editor.view.frame = NSRect(origin: rect.origin, size: size)
}
/// The edit of the open editor and the place of its object, for a save while the editor stays open.
func editorDraft() -> (location: Int, edit: ObjectEdit)? {
guard let editor, let location = editedLocation() else { return nil }
return (location, editor.edit())
}
/// Closes the editor and replaces its object with the edit; `exit` places the caret, nil leaves it.
func endEditing(_ exit: EditorExit?) {
guard let closing = editor, let textStorage else { return }
let found = editedLocation()
let edit = closing.edit()
editor = nil
editedAttachment = nil
if let responder = window?.firstResponder as? NSView, responder.isDescendant(of: closing.view) {
window?.makeFirstResponder(self)
}
closing.view.removeFromSuperview()
guard let location = found else { return }
if let cell = objectCell(at: location) {
cell.editingHeight = nil
layoutManager?.invalidateLayout(forCharacterRange: NSRange(location: location, length: 1), actualCharacterRange: nil)
layoutManager?.invalidateDisplay(forCharacterRange: NSRange(location: location, length: 1))
}
var removedAt: Int?
if let (range, text) = replacement(edit, at: location) {
change(range, to: text)
if text.length == 0 { removedAt = range.location }
}
var newlineAdded = false
if removedAt == nil, exit == .after || exit == .below, location + 1 == textStorage.length {
change(NSRange(location: textStorage.length, length: 0), to: pageText.newline())
newlineAdded = true
}
sizeToFit()
invalidateMargin()
guard let exit else { return }
let caret: Int
if let removedAt {
caret = removedAt
} else if newlineAdded {
caret = location + 2
} else {
switch exit {
case .after: caret = location + 1
case .above: caret = max(0, location - 1)
case .below: caret = location + 2
}
}
setSelectedRange(NSRange(location: min(caret, length), length: 0))
scrollRangeToVisible(selectedRange())
}
/// One undoable change of the page, without the typing scroll.
private func change(_ range: NSRange, to text: NSAttributedString) {
guard let textStorage else { return }
isReplacingObject = true
breakUndoCoalescing()
if shouldChangeText(in: range, replacementString: text.string) {
textStorage.replaceCharacters(in: range, with: text)
didChangeText()
}
breakUndoCoalescing()
isReplacingObject = false
}
private func objectCell(at location: Int) -> ObjectCell? {
(textStorage?.attribute(.attachment, at: location, effectiveRange: nil) as? NSTextAttachment)?.attachmentCell as? ObjectCell
}
/// The range an edit replaces and its new text; a removed object takes its line with it.
private func replacement(_ edit: ObjectEdit, at location: Int) -> (NSRange, NSAttributedString)? {
guard let textStorage, location < textStorage.length else { return nil }
switch edit {
case .unchanged:
return nil
case let .replaced(kind, body):
var attributes = textStorage.attributes(at: location, effectiveRange: nil)
attributes[.attachment] = pageText.object(kind, body)
return (NSRange(location: location, length: 1), NSAttributedString(string: "\u{FFFC}", attributes: attributes))
case .removed:
let string = textStorage.string as NSString
var range = NSRange(location: location, length: 1)
if location + 1 < string.length, string.character(at: location + 1) == 0x0A {
range.length = 2
} else if location > 0, string.character(at: location - 1) == 0x0A {
range = NSRange(location: location - 1, length: 2)
}
return (range, NSAttributedString())
}
}
}
+49
View File
@@ -0,0 +1,49 @@
import AppKit
import PlakCore
/// Where the caret goes when an editor closes with a key.
enum EditorExit {
/// Esc: right after the object.
case after
/// ↑ on the first line or row: the end of the line above.
case above
/// ↓ on the last line or row: the start of the line below.
case below
}
/// What an edit does to its object.
enum ObjectEdit: Equatable {
case unchanged
/// The new kind and body; the page builds the object only when the edit closes.
case replaced(FenceKind, String)
case removed
}
/// An editor open over a code block or table, placed by the page over the object.
@MainActor
protocol ObjectEditor: AnyObject {
/// The view the page puts over the object.
var view: NSView { get }
/// The view that takes the keys when the editor opens.
var focusView: NSView { get }
/// Asks the page to close the editor and put the caret back in the text.
var onEnd: ((EditorExit) -> Void)? { get set }
/// The editor needs another size.
var onResize: (() -> Void)? { get set }
/// The content changed.
var onChange: (() -> Void)? { get set }
/// The size of the editor when `width` is the room from the object to the end of the column.
func size(available width: CGFloat) -> NSSize
func setFont(_ font: NSFont)
/// The object as the edit has it now, a cell being edited included; it changes nothing, so a save can ask.
func edit() -> ObjectEdit
}
/// The cell of a code block or table, which takes the height of its editor while that is open.
@MainActor
protocol ObjectCell: AnyObject {
/// The height the open editor needs; nil while no editor is open.
var editingHeight: CGFloat? { get set }
func setFont(_ font: NSFont)
}
+81 -25
View File
@@ -14,6 +14,8 @@ final class PageText {
let imageBase: URL
let images: ImageCache
private(set) var font: NSFont
/// The font of code blocks and tables.
private(set) var codeFont: 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] = [:]
@@ -22,12 +24,14 @@ final class PageText {
self.imageBase = imageBase
self.images = images
font = PlakFonts.body(bodySize)
codeFont = PlakFonts.mono(round(bodySize * PageMetrics.codeScale))
setBodySize(bodySize)
}
/// The minimum line height lets a line with an image grow to the image.
func setBodySize(_ size: CGFloat) {
font = PlakFonts.body(size)
codeFont = PlakFonts.mono(round(size * PageMetrics.codeScale))
lineHeight = PageMetrics.lineHeight(font)
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight
@@ -49,10 +53,8 @@ final class PageText {
/// 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
Self.isObject(line) ? "\u{FFFC}" : line.text
}.joined(separator: "\n")
let text = NSMutableAttributedString(string: string, attributes: attributes)
var starts: [Int] = []
@@ -60,7 +62,7 @@ final class PageText {
var location = 0
for line in file.lines {
starts.append(location)
if case .image = line {
if Self.isObject(line) {
location += 2
} else {
location += (line.text as NSString).length + 1
@@ -69,8 +71,13 @@ final class PageText {
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))
switch line {
case let .image(path):
text.setAttributes(attachmentAttributes(imageAttachment(path)), range: NSRange(location: starts[index], length: 1))
case let .fenced(kind, body):
text.setAttributes(attachmentAttributes(object(kind, body)), range: NSRange(location: starts[index], length: 1))
case .text:
break
}
}
for block in file.blocks {
@@ -85,43 +92,69 @@ final class PageText {
return text
}
/// Pasted plain text; a line that is exactly an image line of an existing image file becomes that image.
/// Pasted plain text; an image line of an existing image file becomes that image, a fenced block its object.
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() {
for (index, line) in PageFile.lines(pasted: plainText).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) {
switch line {
case let .image(path) where FileManager.default.fileExists(atPath: imageURL(path).path):
text.append(imageString(path))
} else {
text.append(NSAttributedString(string: line, attributes: attributes))
case let .fenced(kind, body):
text.append(objectString(kind, body))
default:
text.append(NSAttributedString(string: line.text, attributes: attributes))
}
}
return text
}
/// Pasted text exactly as it is: fences and image lines stay text.
func plainString(_ plainText: String) -> NSAttributedString {
NSAttributedString(string: plainText.replacingOccurrences(of: "\r\n", with: "\n"), attributes: attributes)
}
func imageString(_ path: String) -> NSAttributedString {
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(path))
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(imageAttachment(path)))
}
/// A code block, or a table for csv.
func objectString(_ kind: FenceKind, _ body: String) -> NSAttributedString {
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(object(kind, body)))
}
func object(_ kind: FenceKind, _ body: String) -> NSTextAttachment {
kind == .csv ? TableAttachment(body: body, font: codeFont) : CodeAttachment(kind: kind, body: body, font: codeFont)
}
func newline() -> NSAttributedString {
NSAttributedString(string: "\n", attributes: attributes)
}
private func attachmentAttributes(_ path: String) -> [NSAttributedString.Key: Any] {
private func imageAttachment(_ path: String) -> ImageAttachment {
ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font)
}
private func attachmentAttributes(_ attachment: NSTextAttachment) -> [NSAttributedString.Key: Any] {
var attributes = imageAttributes
attributes[.attachment] = ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font)
attributes[.attachment] = attachment
return attributes
}
private static func isObject(_ line: PageFile.Line) -> Bool {
if case .text = line { return false }
return true
}
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 {
/// The page file of the text: one line per text line, an image or other object always on a line of its own.
/// A draft puts the edit of an open editor in place of its object, without building a new object.
static func pageFile(_ text: NSAttributedString, draft: (location: Int, edit: ObjectEdit)? = nil) -> PageFile {
let string = text.string as NSString
guard string.length > 0 else { return PageFile() }
var lines: [PageFile.Line] = []
@@ -130,7 +163,11 @@ final class PageText {
var location = 0
while location <= string.length {
let end = string.lineEnd(from: location)
let pieces = lineContents(text, NSRange(location: location, length: end - location))
let pieces = lineContents(text, NSRange(location: location, length: end - location), draft: draft)
guard !pieces.isEmpty else {
location = end + 1
continue
}
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
@@ -142,12 +179,12 @@ final class PageText {
return PageFile(lines: lines, dates: dates)
}
/// Plain text of a range, as for the pasteboard: each image becomes its image line.
/// Plain text of a range, as for the pasteboard: each image becomes its image line, each object its fenced block.
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)
if let line = value.flatMap(line(for:)) {
out += Array(repeating: line.text, count: run.length).joined(separator: "\n")
} else {
out += (text.string as NSString).substring(with: run)
}
@@ -156,21 +193,40 @@ final class PageText {
}
/// 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] {
/// An object the draft removes takes its line with it: then there are no lines at all.
private static func lineContents(_ text: NSAttributedString, _ range: NSRange,
draft: (location: Int, edit: ObjectEdit)?) -> [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] = []
var removed = false
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
if let image = value as? ImageAttachment {
lines += Array(repeating: .image(image.path), count: run.length)
if let line = value.flatMap(line(for:)) {
for location in run.location..<NSMaxRange(run) {
switch location == draft?.location ? draft?.edit : nil {
case let .replaced(kind, body)?: lines.append(.fenced(kind, body))
case .removed?: removed = true
case .unchanged?, nil: lines.append(line)
}
}
} else {
let piece = string.substring(with: run)
if !PageFile.isBlank(piece) { lines.append(.text(piece)) }
}
}
return lines.isEmpty ? [.text("")] : lines
return lines.isEmpty && !removed ? [.text("")] : lines
}
/// The page file line of an image, code block or table attachment.
static func line(for attachment: Any) -> PageFile.Line? {
switch attachment {
case let image as ImageAttachment: .image(image.path)
case let code as CodeAttachment: .fenced(code.kind, code.body)
case let table as TableAttachment: .fenced(.csv, table.body)
default: nil
}
}
// MARK: Created dates
+55 -15
View File
@@ -7,7 +7,8 @@ struct MarginDate: Equatable {
var rect: NSRect
}
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, paste and drop.
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, 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.
@@ -17,6 +18,14 @@ final class PageTextView: NSTextView {
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
@@ -89,11 +98,13 @@ final class PageTextView: NSTextView {
textStorage.beginEditing()
textStorage.addAttributes(pageText.attributes, range: all)
textStorage.enumerateAttribute(.attachment, in: all) { value, range, _ in
guard let image = value as? ImageAttachment else { return }
guard let attachment = value as? NSTextAttachment else { return }
textStorage.removeAttribute(.baselineOffset, range: range)
(image.attachmentCell as? MissingImageCell)?.setFont(pageText.font)
(attachment.attachmentCell as? MissingImageCell)?.setFont(pageText.font)
(attachment.attachmentCell as? ObjectCell)?.setFont(pageText.codeFont)
}
textStorage.endEditing()
editor?.setFont(pageText.codeFont)
}
// MARK: Column and spaces
@@ -168,8 +179,16 @@ final class PageTextView: NSTextView {
// MARK: Clicks
/// A plain click on a code block or table opens its editor; any click closes an open one first.
override func mouseDown(with event: NSEvent) {
if convert(event.locationInWindow, from: nil).y > textBottom {
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.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
@@ -182,7 +201,9 @@ final class PageTextView: NSTextView {
/// 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() {
if editor != nil {
endEditing(.after)
} else if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else if let onHide {
@@ -237,38 +258,55 @@ final class PageTextView: NSTextView {
}
override func pasteAsPlainText(_ sender: Any?) {
paste(from: pasteboard)
paste(from: pasteboard, detectsObjects: false)
}
override func pasteAsRichText(_ sender: Any?) {
paste(from: pasteboard)
}
func paste(from pasteboard: NSPasteboard) {
/// 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 {
insert(pageText.attributedString(plainText: text), replacing: selectedRange())
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())
}
}
}
/// Text dropped from a drag, or brought by a service.
/// 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 }
paste(from: pboard)
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
}
/// 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 }
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, path) in paths.enumerated() {
for (index, object) in objects.enumerated() {
if index > 0 { text.append(pageText.newline()) }
text.append(pageText.imageString(path))
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)
@@ -352,8 +390,10 @@ final class PageTextView: NSTextView {
showDropCaret(nil)
}
/// An open editor closes first: a drop would move the object under it.
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingEntered(sender)
if editor != nil { endEditing(nil) }
return PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingEntered(sender)
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+10 -3
View File
@@ -66,6 +66,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
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 = .systemFont(ofSize: 12)
@@ -103,10 +104,15 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
textView.undoManager?.removeAllActions()
}
/// The page file text of the page as it is now.
/// 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).text()
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
@@ -180,7 +186,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
store.changed()
textView.invalidateMargin()
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() }
keepCaretAboveFloor()
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.
@@ -220,6 +226,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
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()
}
@objc private func clipFrameChanged(_ notification: Notification) {
+176
View File
@@ -0,0 +1,176 @@
import AppKit
import PlakCore
/// A cell of a table, by row and column.
struct TablePosition: Equatable {
var row: Int
var column: Int
}
/// The grid of a table at a font: columns sized to their values, every row one line high.
struct TableLayout {
private(set) var columnWidths: [CGFloat]
let rowHeight: CGFloat
let rowCount: Int
let font: NSFont
init(_ table: CSVTable, font: NSFont) {
self.font = font
columnWidths = (0..<table.columnCount).map { Self.columnWidth($0, of: table, font: font) }
rowHeight = PlakFonts.naturalLineHeight(font) + PageMetrics.tableCellPadding.height * 2
rowCount = table.rows.count
}
/// Measures one column again, after a change of one of its values.
mutating func remeasure(column: Int, of table: CSVTable) {
guard column < columnWidths.count else { return }
columnWidths[column] = Self.columnWidth(column, of: table, font: font)
}
private static func columnWidth(_ column: Int, of table: CSVTable, font: NSFont) -> CGFloat {
let attributes: [NSAttributedString.Key: Any] = [.font: font]
var widest: CGFloat = ceil(font.pointSize * 2)
for row in table.rows.indices {
let value = table[row, column]
guard !value.isEmpty else { continue }
widest = max(widest, ceil(NSAttributedString(string: shown(value), attributes: attributes).size().width))
}
return min(PageMetrics.tableColumnMaximum, widest + PageMetrics.tableCellPadding.width * 2)
}
/// A value on one line: a newline in a value shows as a space.
static func shown(_ value: String) -> String {
value.replacingOccurrences(of: "\r\n", with: " ").replacingOccurrences(of: "\n", with: " ")
}
var size: NSSize {
NSSize(width: columnWidths.reduce(0, +) + 1, height: CGFloat(rowCount) * rowHeight + 1)
}
func columnX(_ column: Int) -> CGFloat {
columnWidths.prefix(column).reduce(0, +)
}
/// The rect of a cell, from the top left of the grid, its lines included.
func rect(_ position: TablePosition) -> NSRect {
NSRect(x: columnX(position.column), y: CGFloat(position.row) * rowHeight,
width: columnWidths[position.column] + 1, height: rowHeight + 1)
}
/// The cell under a point from the top left of the grid; nil outside the grid.
func position(at point: NSPoint) -> TablePosition? {
guard point.y.isFinite, point.x.isFinite, point.y >= 0, point.x >= 0, rowCount > 0, rowHeight > 0 else { return nil }
let row = Int(point.y / rowHeight)
var x: CGFloat = 0
for (column, width) in columnWidths.enumerated() {
x += width
if point.x < x { return row < rowCount ? TablePosition(row: row, column: column) : nil }
}
return nil
}
/// Draws the lines and the values of the rows in `clip`, with the grid's top left at `origin`, in a flipped view.
func draw(_ table: CSVTable, at origin: NSPoint, clip: NSRect, scale: CGFloat) {
let size = size
let visible = clip.intersection(NSRect(origin: origin, size: size))
guard rowCount > 0, rowHeight > 0, visible.isFiniteArea else { return }
let line = 1 / max(1, scale)
let first = max(0, min(rowCount - 1, Int((visible.minY - origin.y) / rowHeight)))
let last = max(first, min(rowCount - 1, Int((visible.maxY - origin.y) / rowHeight)))
let top = origin.y + CGFloat(first) * rowHeight
let bottom = origin.y + CGFloat(last + 1) * rowHeight
Theme.selection.setFill()
var x = origin.x
for width in columnWidths + [0] {
NSRect(x: x, y: top, width: line, height: bottom - top + line).fill()
x += width
}
for row in first...(last + 1) {
NSRect(x: origin.x, y: origin.y + CGFloat(row) * rowHeight, width: size.width, height: line).fill()
}
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: Theme.ink, .paragraphStyle: style]
let padding = PageMetrics.tableCellPadding
for row in first...last {
for column in columnWidths.indices {
let value = table[row, column]
guard !value.isEmpty else { continue }
let cell = rect(TablePosition(row: row, column: column)).offsetBy(dx: origin.x, dy: origin.y)
let text = cell.insetBy(dx: padding.width, dy: padding.height)
NSAttributedString(string: Self.shown(value), attributes: attributes)
.draw(with: text, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
}
}
}
}
/// A table in the page: one character that knows its CSV text.
final class TableAttachment: NSTextAttachment {
let table: CSVTable
/// The CSV text as in the page file: as pasted until the table is edited.
let body: String
init(body: String, font: NSFont) {
self.body = body
table = CSVTable(text: body)
super.init(data: nil, ofType: nil)
attachmentCell = TableCell(table: table, font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
}
/// The grid of a table, cut off at the width of the column.
final class TableCell: NSTextAttachmentCell, ObjectCell {
private let table: CSVTable
private(set) var layout: TableLayout
private var size = NSSize.zero
/// AppKit reads it in `cellFrame`, which it does not mark main-actor; the page lays out on the main thread only.
nonisolated(unsafe) var editingHeight: CGFloat?
init(table: CSVTable, font: NSFont) {
self.table = table
layout = TableLayout(table, font: font)
super.init(textCell: "")
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
layout = TableLayout(table, font: font)
}
override func cellSize() -> NSSize {
size
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
let grid = layout.size
size = NSSize(width: min(grid.width, floor(lineFrag.width - max(0, position.x))), height: editingHeight ?? grid.height)
return NSRect(origin: .zero, size: size)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
guard editingHeight == nil, let context = NSGraphicsContext.current, let clip = drawingClip(within: cellFrame) else { return }
context.saveGraphicsState()
cellFrame.clip()
layout.draw(table, at: cellFrame.origin, clip: clip, scale: controlView?.window?.backingScaleFactor ?? 2)
context.restoreGraphicsState()
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
+449
View File
@@ -0,0 +1,449 @@
import AppKit
import PlakCore
/// Where the selection goes after a cell edit is committed.
enum CellMove {
case stay
/// Enter: one row down, a new row on the last one.
case down
/// Tab: one column right, a new column on the last one.
case right
case left
}
/// The editor over a table: a grid with one selected cell, driven by the keys as a spreadsheet.
final class TableGridView: NSView, ObjectEditor, NSUserInterfaceValidations {
private(set) var table: CSVTable
private let original: CSVTable
private(set) var selected: TablePosition
private(set) var cellEditor: TableCellEditor?
private var font: NSFont
private(set) var layout: TableLayout
private let scrollView = NSScrollView()
var onEnd: ((EditorExit) -> Void)?
var onResize: (() -> Void)?
var onChange: (() -> Void)?
init(table: CSVTable, font: NSFont, selected: TablePosition) {
self.table = table
original = table
self.font = font
layout = TableLayout(table, font: font)
self.selected = TablePosition(row: min(selected.row, max(0, table.rows.count - 1)),
column: min(selected.column, max(0, table.columnCount - 1)))
super.init(frame: NSRect(origin: .zero, size: layout.size))
scrollView.drawsBackground = false
scrollView.borderType = .noBorder
scrollView.hasVerticalScroller = false
scrollView.hasHorizontalScroller = true
scrollView.autohidesScrollers = true
scrollView.scrollerStyle = .overlay
scrollView.verticalScrollElasticity = .none
scrollView.documentView = self
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var view: NSView { scrollView }
var focusView: NSView { self }
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { true }
func size(available width: CGFloat) -> NSSize {
let grid = layout.size
return NSSize(width: min(grid.width, floor(width)), height: grid.height)
}
func setFont(_ font: NSFont) {
self.font = font
cellEditor?.setFont(font)
layout = TableLayout(table, font: font)
resized()
}
func edit() -> ObjectEdit {
var table = table
if let cellEditor { table[selected.row, selected.column] = PageFile.unixNewlines(cellEditor.string) }
if table.isEmpty { return .removed }
return table == original ? .unchanged : .replaced(.csv, table.text())
}
/// After rows or columns came or went: the whole grid is measured again.
private func reshaped() {
layout = TableLayout(table, font: font)
resized()
onChange?()
}
/// After one value changed: only its column is measured again.
private func valueChanged() {
layout.remeasure(column: selected.column, of: table)
resized()
onChange?()
}
private func resized() {
setFrameSize(layout.size)
placeCellEditor()
needsDisplay = true
onResize?()
guard !table.isEmpty else { return }
scrollToVisible(layout.rect(selected))
}
// MARK: Drawing
override func draw(_ dirtyRect: NSRect) {
layout.draw(table, at: .zero, clip: dirtyRect, scale: window?.backingScaleFactor ?? 2)
guard !table.isEmpty else { return }
Theme.accent.setStroke()
let outline = NSBezierPath(rect: layout.rect(selected).insetBy(dx: 1, dy: 1))
outline.lineWidth = 2
outline.stroke()
}
// MARK: Selection
func select(_ position: TablePosition) {
guard !table.isEmpty else { return }
selected = TablePosition(row: min(max(0, position.row), table.rows.count - 1),
column: min(max(0, position.column), table.columnCount - 1))
needsDisplay = true
scrollToVisible(layout.rect(selected))
}
private func move(_ move: CellMove) {
switch move {
case .stay:
break
case .down:
if selected.row == table.rows.count - 1 {
table.addRow()
reshaped()
}
select(TablePosition(row: selected.row + 1, column: selected.column))
case .right:
if selected.column == table.columnCount - 1 {
table.addColumn()
reshaped()
}
select(TablePosition(row: selected.row, column: selected.column + 1))
case .left:
select(TablePosition(row: selected.row, column: selected.column - 1))
}
}
override func mouseDown(with event: NSEvent) {
if cellEditor != nil { commitCellEdit(then: .stay) }
if let position = layout.position(at: convert(event.locationInWindow, from: nil)) { select(position) }
window?.makeFirstResponder(self)
if event.clickCount == 2 { beginCellEdit(keepingValue: true) }
}
// MARK: Keys
/// Return, Tab, Delete, Esc, Enter and Forward Delete: commands, never the start of a value.
private static let commandKeys: Set<UInt16> = [36, 48, 51, 53, 76, 117]
private static let commands: Set<Selector> = [
#selector(moveUp(_:)), #selector(moveDown(_:)), #selector(moveLeft(_:)), #selector(moveRight(_:)),
#selector(insertTab(_:)), #selector(insertBacktab(_:)), #selector(insertNewline(_:)),
#selector(deleteBackward(_:)), #selector(deleteForward(_:)), #selector(cancelOperation(_:)),
]
override func keyDown(with event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
if event.keyCode == 51, flags.contains(.command) {
flags.contains(.option) ? deleteColumn() : deleteRow()
} else if event.specialKey == .f2 {
beginCellEdit(keepingValue: true)
} else if startsValue(event, flags: flags) {
// The cell editor takes the key itself, so dead keys, held accents and input methods work.
beginCellEdit(keepingValue: false)
cellEditor?.keyDown(with: event)
} else {
interpretKeyEvents([event])
}
}
private func startsValue(_ event: NSEvent, flags: NSEvent.ModifierFlags) -> Bool {
guard !table.isEmpty, flags.isDisjoint(with: [.command, .control]), event.specialKey == nil,
!Self.commandKeys.contains(event.keyCode) else { return false }
guard let scalar = event.characters?.unicodeScalars.first else { return true }
return scalar.value >= 0x20 && scalar.value != 0x7F && !(0xF700...0xF8FF).contains(scalar.value)
}
/// A key command the grid does not know beeps, so it never reaches the page behind the grid.
override func doCommand(by selector: Selector) {
if Self.commands.contains(selector) {
perform(selector, with: nil)
} else {
NSSound.beep()
}
}
override func insertText(_ insertString: Any) {
let text = (insertString as? NSAttributedString)?.string ?? insertString as? String ?? ""
guard !text.isEmpty, !table.isEmpty else { return }
beginCellEdit(keepingValue: false)
cellEditor?.insertText(text, replacementRange: cellEditor?.selectedRange() ?? NSRange())
}
override func moveUp(_ sender: Any?) {
selected.row == 0 ? onEnd?(.above) : select(TablePosition(row: selected.row - 1, column: selected.column))
}
override func moveDown(_ sender: Any?) {
selected.row >= table.rows.count - 1 ? onEnd?(.below) : select(TablePosition(row: selected.row + 1, column: selected.column))
}
override func moveLeft(_ sender: Any?) {
select(TablePosition(row: selected.row, column: selected.column - 1))
}
override func moveRight(_ sender: Any?) {
select(TablePosition(row: selected.row, column: selected.column + 1))
}
override func insertTab(_ sender: Any?) {
move(.right)
}
override func insertBacktab(_ sender: Any?) {
move(.left)
}
override func insertNewline(_ sender: Any?) {
beginCellEdit(keepingValue: true)
}
override func deleteBackward(_ sender: Any?) {
setValue("")
}
override func deleteForward(_ sender: Any?) {
setValue("")
}
override func cancelOperation(_ sender: Any?) {
onEnd?(.after)
}
private func setValue(_ value: String) {
guard !table.isEmpty, table[selected.row, selected.column] != value else { return }
table[selected.row, selected.column] = value
valueChanged()
}
/// ⌘⌫; the last row takes the table with it.
func deleteRow() {
guard !table.isEmpty else { return }
table.removeRow(at: selected.row)
removed()
}
/// ⌥⌘⌫; the last column takes the table with it.
func deleteColumn() {
guard !table.isEmpty else { return }
table.removeColumn(at: selected.column)
removed()
}
private func removed() {
guard !table.isEmpty else {
onChange?()
onEnd?(.after)
return
}
select(selected)
reshaped()
}
// MARK: Cell edit
/// Opens the cell editor on the selected cell, with its value or empty.
func beginCellEdit(keepingValue: Bool) {
guard cellEditor == nil, !table.isEmpty else { return }
let editor = TableCellEditor(font: font)
editor.string = keepingValue ? table[selected.row, selected.column] : ""
editor.onCommit = { [weak self] move in self?.commitCellEdit(then: move) }
editor.onCancel = { [weak self] in self?.cancelCellEdit() }
editor.onResize = { [weak self] in self?.placeCellEditor() }
editor.onChange = { [weak self] in self?.onChange?() }
cellEditor = editor
addSubview(editor)
placeCellEditor()
window?.makeFirstResponder(editor)
editor.setSelectedRange(NSRange(location: (editor.string as NSString).length, length: 0))
}
func commitCellEdit(then move: CellMove) {
guard let editor = cellEditor else { return }
let value = PageFile.unixNewlines(editor.string)
closeCellEditor()
setValue(value)
self.move(move)
}
func cancelCellEdit() {
closeCellEditor()
}
private func closeCellEditor() {
guard let editor = cellEditor else { return }
cellEditor = nil
window?.makeFirstResponder(self)
editor.removeFromSuperview()
}
private func placeCellEditor() {
guard let editor = cellEditor, !table.isEmpty else { return }
let cell = layout.rect(selected).insetBy(dx: 1, dy: 1)
editor.frame = NSRect(x: cell.minX, y: cell.minY, width: max(cell.width, editor.fittingWidth), height: cell.height)
}
// MARK: Pasteboard
@objc func copy(_ sender: Any?) {
guard !table.isEmpty else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(table[selected.row, selected.column], forType: .string)
}
@objc func cut(_ sender: Any?) {
copy(sender)
setValue("")
}
@objc func paste(_ sender: Any?) {
guard let text = NSPasteboard.general.string(forType: .string) else { return }
setValue(PageFile.unixNewlines(text))
}
@objc func pasteAsPlainText(_ sender: Any?) {
paste(sender)
}
@objc func pasteAsRichText(_ sender: Any?) {
paste(sender)
}
/// The undo of the page waits until the table is closed.
@objc func undo(_ sender: Any?) {}
@objc func redo(_ sender: Any?) {}
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(undo(_:)), #selector(redo(_:)): false
default: true
}
}
}
/// The one-line editor of a table cell; Enter, Tab and Esc go back to the grid.
final class TableCellEditor: NSTextView {
var onCommit: ((CellMove) -> Void)?
var onCancel: (() -> Void)?
var onResize: (() -> Void)?
var onChange: (() -> Void)?
private var cellFont: NSFont
private let ownUndo = UndoManager()
init(font: NSFont) {
cellFont = font
let storage = NSTextStorage()
let layout = NSLayoutManager()
storage.addLayoutManager(layout)
let container = NSTextContainer(size: NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
container.widthTracksTextView = false
container.lineFragmentPadding = 0
layout.addTextContainer(container)
super.init(frame: NSRect(x: 0, y: 0, width: 100, height: 20), textContainer: container)
isRichText = false
importsGraphics = false
allowsUndo = true
isVerticallyResizable = false
isHorizontallyResizable = false
drawsBackground = true
backgroundColor = Theme.paper
let padding = PageMetrics.tableCellPadding
textContainerInset = NSSize(width: padding.width - 1, height: padding.height - 1)
isAutomaticQuoteSubstitutionEnabled = false
isAutomaticDashSubstitutionEnabled = false
isAutomaticTextReplacementEnabled = false
isAutomaticSpellingCorrectionEnabled = false
isContinuousSpellCheckingEnabled = false
insertionPointColor = Theme.accent
selectedTextAttributes = [.backgroundColor: Theme.selection]
setFont(font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
override var undoManager: UndoManager? { ownUndo }
func setFont(_ font: NSFont) {
cellFont = font
typingAttributes = [.font: font, .foregroundColor: Theme.ink]
textStorage?.setAttributes(typingAttributes, range: NSRange(location: 0, length: textStorage?.length ?? 0))
}
override var string: String {
didSet { setFont(cellFont) }
}
/// The width that shows the whole value.
var fittingWidth: CGFloat {
guard let layoutManager, let textContainer else { return 0 }
layoutManager.ensureLayout(for: textContainer)
return ceil(layoutManager.usedRect(for: textContainer).width) + textContainerInset.width * 2 + 2
}
override func didChangeText() {
super.didChangeText()
onResize?()
onChange?()
}
/// A key command the editor does not know beeps, so it never reaches the grid or the page.
override func doCommand(by selector: Selector) {
if responds(to: selector) {
super.doCommand(by: selector)
} else {
NSSound.beep()
}
}
override func insertNewline(_ sender: Any?) {
onCommit?(.down)
}
override func insertTab(_ sender: Any?) {
onCommit?(.right)
}
override func insertBacktab(_ sender: Any?) {
onCommit?(.left)
}
override func cancelOperation(_ sender: Any?) {
if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else {
onCancel?()
}
}
@objc func undo(_ sender: Any?) {
ownUndo.undo()
}
@objc func redo(_ sender: Any?) {
ownUndo.redo()
}
}