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
+3
View File
@@ -43,10 +43,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
func applicationWillResignActive(_ notification: Notification) {
windowController?.page.closeEditor()
store?.flush()
}
func applicationWillTerminate(_ notification: Notification) {
windowController?.page.closeEditor()
store?.flush()
}
@@ -64,6 +66,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
/// Only hiding the app gives focus back to the previous app; an ordered-out window leaves Plak active.
private func hidePlak() {
windowController?.page.closeEditor()
NSApp.hide(nil)
}
+4 -2
View File
@@ -42,13 +42,15 @@ enum MainMenu {
private static func editMenu() -> NSMenu {
let menu = NSMenu(title: "Edit")
menu.addItem(withTitle: "Undo", action: Selector(("undo:")), keyEquivalent: "z")
let redo = menu.addItem(withTitle: "Redo", action: Selector(("redo:")), keyEquivalent: "z")
menu.addItem(withTitle: "Undo", action: NSSelectorFromString("undo:"), keyEquivalent: "z")
let redo = menu.addItem(withTitle: "Redo", action: NSSelectorFromString("redo:"), keyEquivalent: "z")
redo.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(.separator())
menu.addItem(withTitle: "Cut", action: #selector(NSText.cut(_:)), keyEquivalent: "x")
menu.addItem(withTitle: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")
menu.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
let plain = menu.addItem(withTitle: "Paste as Plain Text", action: #selector(NSTextView.pasteAsPlainText(_:)), keyEquivalent: "v")
plain.keyEquivalentModifierMask = [.command, .option, .shift]
return menu
}
+114
View File
@@ -0,0 +1,114 @@
/// The kinds of code that get their own colour.
public enum CodeTokenKind: Sendable, Equatable {
case keyword
case string
case number
case comment
case variable
case tag
/// An attribute name in XML, a key in JSON.
case attribute
}
/// A highlighted piece of code; the range counts UTF-16 units, as NSRange does.
public struct CodeToken: Sendable, Equatable {
public let kind: CodeTokenKind
public let range: Range<Int>
public init(_ kind: CodeTokenKind, _ range: Range<Int>) {
self.kind = kind
self.range = range
}
}
/// The highlighted pieces of a code body; text between them is plain code.
public enum CodeHighlighter {
public static func tokens(_ body: String, kind: FenceKind) -> [CodeToken] {
switch kind {
case .php: PHPTokenizer.tokens(body)
case .json: JSONTokenizer.tokens(body)
case .xml: XMLTokenizer.tokens(body)
case .csv: []
}
}
}
/// Walks the UTF-16 units of a code body; all syntax that matters is ASCII.
struct CodeScanner {
let units: [UInt16]
var index = 0
private(set) var tokens: [CodeToken] = []
init(_ text: String) {
units = Array(text.utf16)
}
var atEnd: Bool {
index >= units.count
}
func peek(_ offset: Int = 0) -> UInt16? {
index + offset < units.count ? units[index + offset] : nil
}
func peekIs(_ character: Character, _ offset: Int = 0) -> Bool {
peek(offset) == character.utf16.first
}
func starts(with text: String) -> Bool {
var offset = 0
for unit in text.utf16 {
guard peek(offset) == unit else { return false }
offset += 1
}
return true
}
func text(from start: Int) -> String {
String(decoding: units[start..<index], as: UTF16.self)
}
mutating func add(_ kind: CodeTokenKind, from start: Int) {
if index > start { tokens.append(CodeToken(kind, start..<index)) }
}
mutating func skip(while condition: (UInt16) -> Bool) {
while let unit = peek(), condition(unit) { index += 1 }
}
/// Moves past `end`, or to the end when it never comes.
mutating func skip(past end: String) {
while !atEnd, !starts(with: end) { index += 1 }
index = min(units.count, index + end.utf16.count)
}
/// From an opening quote to past its closing quote.
mutating func skipQuoted(escapes: Bool) {
let quote = units[index]
index += 1
while let unit = peek() {
index += 1
if escapes, unit == 0x5C {
index = min(units.count, index + 1)
} else if unit == quote {
return
}
}
}
static func isLetter(_ unit: UInt16) -> Bool {
(unit >= 0x41 && unit <= 0x5A) || (unit >= 0x61 && unit <= 0x7A) || unit == 0x5F || unit >= 0x80
}
static func isDigit(_ unit: UInt16) -> Bool {
unit >= 0x30 && unit <= 0x39
}
static func isWord(_ unit: UInt16) -> Bool {
isLetter(unit) || isDigit(unit)
}
static func isSpace(_ unit: UInt16) -> Bool {
unit == 0x20 || unit == 0x09 || unit == 0x0A || unit == 0x0D
}
}
+27
View File
@@ -0,0 +1,27 @@
/// JSON: keys apart from string values, numbers, and true, false and null.
enum JSONTokenizer {
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while let unit = scanner.peek() {
let start = scanner.index
if scanner.peekIs("\"") {
scanner.skipQuoted(escapes: true)
let end = scanner.index
scanner.skip(while: CodeScanner.isSpace)
let isKey = scanner.peekIs(":")
scanner.index = end
scanner.add(isKey ? .attribute : .string, from: start)
} else if scanner.peekIs("-") || CodeScanner.isDigit(unit) {
scanner.index += 1
scanner.skip { CodeScanner.isDigit($0) || $0 == 0x2E || $0 == 0x65 || $0 == 0x45 || $0 == 0x2B || $0 == 0x2D }
scanner.add(.number, from: start)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: CodeScanner.isWord)
if ["true", "false", "null"].contains(scanner.text(from: start)) { scanner.add(.keyword, from: start) }
} else {
scanner.index += 1
}
}
return scanner.tokens
}
}
+72
View File
@@ -0,0 +1,72 @@
/// PHP: keywords, strings and heredocs, comments, `$variables`, numbers and the open and close tags.
enum PHPTokenizer {
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "bool", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor",
"endforeach", "endif", "endswitch", "endwhile", "enum", "extends", "false", "final", "finally", "float", "fn",
"for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof",
"insteadof", "int", "interface", "isset", "iterable", "list", "match", "mixed", "namespace", "never", "new",
"null", "object", "or", "parent", "print", "private", "protected", "public", "readonly", "require",
"require_once", "return", "self", "static", "string", "switch", "throw", "trait", "true", "try", "unset", "use",
"var", "void", "while", "xor", "yield",
]
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while let unit = scanner.peek() {
let start = scanner.index
if scanner.starts(with: "<?php") || scanner.starts(with: "<?=") || scanner.starts(with: "?>") {
scanner.index += scanner.starts(with: "<?php") ? 5 : scanner.starts(with: "<?=") ? 3 : 2
scanner.add(.tag, from: start)
} else if scanner.starts(with: "//") || (scanner.peekIs("#") && !scanner.peekIs("[", 1)) {
scanner.skip { $0 != 0x0A }
scanner.add(.comment, from: start)
} else if scanner.starts(with: "/*") {
scanner.skip(past: "*/")
scanner.add(.comment, from: start)
} else if scanner.starts(with: "<<<") {
heredoc(&scanner)
scanner.add(.string, from: start)
} else if scanner.peekIs("'") || scanner.peekIs("\"") {
scanner.skipQuoted(escapes: true)
scanner.add(.string, from: start)
} else if scanner.peekIs("$"), let next = scanner.peek(1), CodeScanner.isLetter(next) {
scanner.index += 1
scanner.skip(while: CodeScanner.isWord)
scanner.add(.variable, from: start)
} else if CodeScanner.isDigit(unit) {
scanner.skip { CodeScanner.isWord($0) || $0 == 0x2E }
scanner.add(.number, from: start)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: CodeScanner.isWord)
if keywords.contains(scanner.text(from: start).lowercased()) { scanner.add(.keyword, from: start) }
} else {
scanner.index += 1
}
}
return scanner.tokens
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` up to the line that starts with ID, indented or not.
private static func heredoc(_ scanner: inout CodeScanner) {
scanner.index += 3
scanner.skip { $0 == 0x20 || $0 == 0x09 }
let quoted = scanner.peekIs("'") || scanner.peekIs("\"")
if quoted { scanner.index += 1 }
let nameStart = scanner.index
scanner.skip(while: CodeScanner.isWord)
let name = scanner.text(from: nameStart)
if quoted { scanner.index += 1 }
guard !name.isEmpty else { return }
while !scanner.atEnd {
scanner.skip { $0 != 0x0A }
guard !scanner.atEnd else { return }
scanner.index += 1
scanner.skip { $0 == 0x20 || $0 == 0x09 }
if scanner.starts(with: name), !(scanner.peek(name.utf16.count).map(CodeScanner.isWord) ?? false) {
scanner.index += name.utf16.count
return
}
}
}
}
+55
View File
@@ -0,0 +1,55 @@
/// XML: tags, attribute names, attribute values, comments and CDATA.
enum XMLTokenizer {
static func tokens(_ body: String) -> [CodeToken] {
var scanner = CodeScanner(body)
while !scanner.atEnd {
let start = scanner.index
if scanner.starts(with: "<!--") {
scanner.skip(past: "-->")
scanner.add(.comment, from: start)
} else if scanner.starts(with: "<![CDATA[") {
scanner.skip(past: "]]>")
scanner.add(.string, from: start)
} else if scanner.peekIs("<"), let next = scanner.peek(1),
CodeScanner.isLetter(next) || next == 0x2F || next == 0x3F || next == 0x21 {
tag(&scanner)
} else {
scanner.index += 1
}
}
return scanner.tokens
}
/// From `<` up to and including `>`, `/>` or `?>`.
private static func tag(_ scanner: inout CodeScanner) {
let start = scanner.index
scanner.index += 1
if scanner.peekIs("/") || scanner.peekIs("?") || scanner.peekIs("!") { scanner.index += 1 }
scanner.skip(while: isName)
scanner.add(.tag, from: start)
while let unit = scanner.peek() {
let piece = scanner.index
if scanner.starts(with: "/>") || scanner.starts(with: "?>") {
scanner.index += 2
scanner.add(.tag, from: piece)
return
} else if scanner.peekIs(">") {
scanner.index += 1
scanner.add(.tag, from: piece)
return
} else if scanner.peekIs("\"") || scanner.peekIs("'") {
scanner.skipQuoted(escapes: false)
scanner.add(.string, from: piece)
} else if CodeScanner.isLetter(unit) {
scanner.skip(while: isName)
scanner.add(.attribute, from: piece)
} else {
scanner.index += 1
}
}
}
private static func isName(_ unit: UInt16) -> Bool {
CodeScanner.isWord(unit) || unit == 0x3A || unit == 0x2D || unit == 0x2E
}
}
+70 -7
View File
@@ -1,17 +1,25 @@
import Foundation
/// The info string of a fenced block that the page shows as one object: a code block, or a table for csv.
public enum FenceKind: String, Sendable, CaseIterable {
case php, json, xml, csv
}
/// The page file as lines, with the created date of each block; reads the text and writes it back unchanged.
public struct PageFile: Sendable, Equatable {
public enum Line: Sendable, Equatable {
case text(String)
/// An image line; the path is relative to the page file folder, as `images/<name>`.
case image(String)
/// A code block or table: the whole fenced block, whose body may hold newlines and blank lines.
case fenced(FenceKind, String)
/// The line as it stands in the page file.
public var text: String {
switch self {
case let .text(text): text
case let .image(path): PageFile.imageLine(path)
case let .fenced(kind, body): PageFile.fencedBlock(kind, body)
}
}
@@ -44,16 +52,28 @@ public struct PageFile: Sendable, Equatable {
if startsBlock, index + 1 < raw.count, !Self.isBlank(raw[index + 1]),
let date = CreatedDate.date(fromLine: line, timeZone: timeZone) {
dates[lines.count] = date
lines.append(Self.line(raw[index + 1]))
index += 2
continue
index += 1
}
lines.append(Self.line(line))
index += 1
let (parsed, next) = Self.line(raw, at: index, timeZone: timeZone)
lines.append(parsed)
index = next
}
self.init(lines: lines, dates: dates)
}
/// The lines of pasted text: image lines and fenced blocks, but no dates.
public static func lines(pasted text: String) -> [Line] {
let raw = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
var lines: [Line] = []
var index = 0
while index < raw.count {
let (parsed, next) = Self.line(raw, at: index, timeZone: .current)
lines.append(parsed)
index = next
}
return lines
}
/// The page file text: every line, the date line above each dated block, and a trailing newline.
public func text(timeZone: TimeZone = .current) -> String {
guard !lines.isEmpty else { return "" }
@@ -101,7 +121,50 @@ public struct PageFile: Sendable, Equatable {
"![](\(path))"
}
private static func line(_ text: String) -> Line {
imagePath(fromLine: text).map(Line.image) ?? .text(text)
/// The fence line, the body and the closing fence; the fence is longer than any run of backticks that starts a body line.
public static func fencedBlock(_ kind: FenceKind, _ body: String) -> String {
let fence = fence(for: body)
return "\(fence)\(kind.rawValue)\n\(body)\n\(fence)"
}
/// Every line break as LF: a CR or CRLF in a body would hide a fence line inside it.
public static func unixNewlines(_ text: String) -> String {
text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
}
/// Split on "\n" itself: as a Character, "\r\n" is one grapheme and would not split.
static func fence(for body: String) -> String {
var longest = 0
for line in body.components(separatedBy: "\n") {
longest = max(longest, line.prefix(while: { $0 == "`" }).count)
}
return String(repeating: "`", count: max(3, longest + 1))
}
/// The line that starts at `raw[index]`, and the index of the line after it.
private static func line(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int) {
if let fenced = fencedBlock(raw, at: index, timeZone: timeZone) { return fenced }
let text = raw[index]
return (imagePath(fromLine: text).map(Line.image) ?? .text(text), index + 1)
}
/// A fence of a known kind with a body of at least one line and a closing fence of the same length.
///
/// A fence that is not the one `fencedBlock` would write stays text, so the round trip stays exact. A body
/// with a date line after a blank line stays text too: a stray fence must not swallow the dated blocks below it.
private static func fencedBlock(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int)? {
let open = raw[index]
let ticks = open.prefix(while: { $0 == "`" }).count
guard ticks >= 3, let kind = FenceKind(rawValue: String(open.dropFirst(ticks))) else { return nil }
let fence = String(repeating: "`", count: ticks)
var close = index + 1
while close < raw.count, raw[close] != fence { close += 1 }
guard close < raw.count, close > index + 1 else { return nil }
for line in (index + 2)..<close where isBlank(raw[line - 1]) && CreatedDate.date(fromLine: raw[line], timeZone: timeZone) != nil {
return nil
}
let body = raw[(index + 1)..<close].joined(separator: "\n")
guard Self.fence(for: body) == fence else { return nil }
return (.fenced(kind, body), close + 1)
}
}
+150
View File
@@ -0,0 +1,150 @@
import Foundation
/// A table read from CSV text, quote-aware as RFC 4180, and written back with its own delimiter.
public struct CSVTable: Sendable, Equatable {
/// In order of preference when more than one gives a table.
public static let delimiters: [Character] = ["\t", ";", ","]
public var rows: [[String]]
public let delimiter: Character
public init(rows: [[String]], delimiter: Character = ",") {
self.rows = rows
self.delimiter = delimiter
}
/// Reads the body of a stored table: the delimiter that gives every row the same field count, else the one
/// that splits the first row most.
public init(text: String) {
if let table = Self.detect(text, minimumRows: 1) {
self = table
return
}
let splits = Self.delimiters.map { (delimiter: $0, records: Self.records(text, delimiter: $0).records) }
let best = splits.max { ($0.records.first?.count ?? 0) < ($1.records.first?.count ?? 0) }
let split = best.flatMap { ($0.records.first?.count ?? 0) > 1 ? $0 : nil } ?? splits[splits.count - 1]
self.init(rows: split.records, delimiter: split.delimiter)
let width = columnCount
rows = rows.map { $0 + Array(repeating: "", count: width - $0.count) }
}
/// Pasted text as a table: at least two rows, every row the same number of fields, two or more, and no open quote.
public static func detect(_ text: String) -> CSVTable? {
detect(text, minimumRows: 2)
}
private static func detect(_ text: String, minimumRows: Int) -> CSVTable? {
for delimiter in delimiters {
let (records, closed) = records(text, delimiter: delimiter)
guard closed, records.count >= minimumRows, let count = records.first?.count, count >= 2,
records.allSatisfy({ $0.count == count }) else { continue }
return CSVTable(rows: records, delimiter: delimiter)
}
return nil
}
/// The records of CSV text; empty lines are skipped, and `closed` is false when a quote is never closed.
public static func records(_ text: String, delimiter: Character) -> (records: [[String]], closed: Bool) {
var records: [[String]] = []
var fields: [String] = []
var field = ""
var inQuotes = false
var quoted = false
var recordQuoted = false
let characters = Array(text.replacingOccurrences(of: "\r\n", with: "\n"))
func endRecord() {
fields.append(field)
if !(fields.count == 1 && fields[0].isEmpty && !recordQuoted) { records.append(fields) }
fields = []
field = ""
quoted = false
recordQuoted = false
}
var index = 0
while index < characters.count {
let character = characters[index]
if inQuotes {
if character == "\"" {
if index + 1 < characters.count, characters[index + 1] == "\"" {
field.append("\"")
index += 1
} else {
inQuotes = false
}
} else {
field.append(character)
}
} else if character == "\"", field.isEmpty, !quoted {
inQuotes = true
quoted = true
recordQuoted = true
} else if character == delimiter {
fields.append(field)
field = ""
quoted = false
} else if character == "\n" {
endRecord()
} else {
field.append(character)
}
index += 1
}
if !field.isEmpty || !fields.isEmpty || recordQuoted { endRecord() }
return (records, !inQuotes)
}
/// The CSV text, rows padded to the same width; a field is quoted only when it must be.
public func text() -> String {
let width = columnCount
return rows.map { row in
let padded = row + Array(repeating: "", count: width - row.count)
// A lone empty field would be an empty line, which reads back as no row at all.
if padded.count == 1, padded[0].isEmpty { return "\"\"" }
return padded.map(quoted).joined(separator: String(delimiter))
}.joined(separator: "\n")
}
private func quoted(_ field: String) -> String {
// Any delimiter, not only its own: a read-back picks the delimiter that splits every row the same.
guard field.contains(where: { Self.delimiters.contains($0) || $0 == "\"" || $0 == "\n" || $0 == "\r" }) else { return field }
return "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\""
}
public var columnCount: Int {
rows.map(\.count).max() ?? 0
}
/// A table without a cell is no table any more.
public var isEmpty: Bool {
rows.isEmpty || columnCount == 0
}
public subscript(row: Int, column: Int) -> String {
get { column < rows[row].count ? rows[row][column] : "" }
set {
if rows[row].count <= column { rows[row] += Array(repeating: "", count: column + 1 - rows[row].count) }
rows[row][column] = newValue
}
}
public mutating func addRow() {
rows.append(Array(repeating: "", count: max(1, columnCount)))
}
public mutating func addColumn() {
let width = columnCount
rows = rows.map { $0 + Array(repeating: "", count: width + 1 - $0.count) }
}
public mutating func removeRow(at index: Int) {
rows.remove(at: index)
}
public mutating func removeColumn(at index: Int) {
rows = rows.map { row in
var row = row
if index < row.count { row.remove(at: index) }
return row
}
}
}
@@ -0,0 +1,64 @@
/// Pretty-prints JSON text with a 2-space indent.
///
/// It works on the text itself, not on a parsed value: a parse loses the key order and the
/// spelling of numbers (`1.50`, `1e3`).
public enum JSONFormatter {
public static func pretty(_ text: String) -> String {
let scalars = Array(text.unicodeScalars)
var out = String.UnicodeScalarView()
var depth = 0
func newline() {
out.append("\n")
out.append(contentsOf: String(repeating: " ", count: max(0, depth)).unicodeScalars)
}
var index = 0
while index < scalars.count {
let scalar = scalars[index]
switch scalar {
case "\"":
out.append(scalar)
index += 1
while index < scalars.count {
out.append(scalars[index])
if scalars[index] == "\\", index + 1 < scalars.count {
index += 1
out.append(scalars[index])
} else if scalars[index] == "\"" {
break
}
index += 1
}
case "{", "[":
let close: Unicode.Scalar = scalar == "{" ? "}" : "]"
var next = index + 1
while next < scalars.count, isSpace(scalars[next]) { next += 1 }
if next < scalars.count, scalars[next] == close {
out.append(scalar)
out.append(close)
index = next
} else {
out.append(scalar)
depth += 1
newline()
}
case "}", "]":
depth -= 1
newline()
out.append(scalar)
case ",":
out.append(scalar)
newline()
case ":":
out.append(contentsOf: ": ".unicodeScalars)
default:
if !isSpace(scalar) { out.append(scalar) }
}
index += 1
}
return String(out)
}
private static func isSpace(_ scalar: Unicode.Scalar) -> Bool {
scalar == " " || scalar == "\t" || scalar == "\n" || scalar == "\r"
}
}
+42
View File
@@ -0,0 +1,42 @@
import Foundation
/// What a paste of plain text becomes: text as it is, or a code block or table.
public enum PasteKind: Sendable, Equatable {
case text
/// The kind and the body of the object; one-line JSON comes pretty-printed.
case object(FenceKind, String)
/// Looks at the whole pasted text, trimmed: PHP, JSON, XML, then CSV.
public init(_ pasted: String) {
let text = pasted.replacingOccurrences(of: "\r\n", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
if text.hasPrefix("<?php") || text.hasPrefix("<?=") {
self = .object(.php, text)
} else if Self.isJSON(text) {
self = .object(.json, text.contains("\n") ? text : JSONFormatter.pretty(text))
} else if Self.isXML(text) {
self = .object(.xml, text)
} else if let csv = Self.csvText(pasted), CSVTable.detect(csv) != nil {
self = .object(.csv, csv)
} else {
self = .text
}
}
/// The text without its blank first and last lines; a tab at the edge is an empty cell, so it stays.
private static func csvText(_ pasted: String) -> String? {
var lines = PageFile.unixNewlines(pasted).components(separatedBy: "\n")
while let first = lines.first, first.allSatisfy({ $0 == " " }) { lines.removeFirst() }
while let last = lines.last, last.allSatisfy({ $0 == " " }) { lines.removeLast() }
return lines.isEmpty ? nil : lines.joined(separator: "\n")
}
private static func isJSON(_ text: String) -> Bool {
guard text.hasPrefix("{") || text.hasPrefix("[") else { return false }
return (try? JSONSerialization.jsonObject(with: Data(text.utf8))) != nil
}
private static func isXML(_ text: String) -> Bool {
guard text.hasPrefix("<") else { return false }
return XMLParser(data: Data(text.utf8)).parse()
}
}
+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()
}
}
@@ -0,0 +1,40 @@
OpenDyslexicMono-Regular.otf (Version 1.001)
Font by Abelardo Gonzalez (http://abbiecod.es), based on Bitstream Vera Sans.
Source: https://github.com/antijingoist/open-dyslexic, file otf/OpenDyslexicMono-Regular.otf
(now at https://forge.hackers.town/antijingoist/open-dyslexic).
OpenDyslexic changes and additional glyphs are licensed under the
Creative Commons Attribution 3.0 Unported License:
https://creativecommons.org/licenses/by/3.0/
Copyright notice in the font file:
Original Fonts are © Bitstream. OpenDyslexic changes and additional glyphs by Abelardo Gonzalez are licensed under a Creative Commons Attribution 3.0 Unported License.
Based on a work at http://dyslexicfonts.com. _2012 by Abelardo Gonzalez. Copying is an act of love. Please copy.
Bitstream license available here: http://opendyslexic.org/legal/
Licence section of README.md in antijingoist/open-dyslexic, commit ba3809e2b981dcc8f52abe750028e713600551f6:
License
-------
The license for this font is:
♡ Copying is an act of love. Please copy.
Bitstream License:
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license (“Fonts”) and associated documentation files (the “Font Software”), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the “Bitstream Vera” names.
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
+1 -1
View File
@@ -1,7 +1,7 @@
import CoreText
import Foundation
/// Registers the bundled OpenDyslexic faces for this process.
/// Registers the bundled OpenDyslexic and OpenDyslexic Mono faces for this process.
public enum FontRegistry {
public static let resourceBundleName = "Plak_PlakUI.bundle"
+7 -1
View File
@@ -1,14 +1,20 @@
import AppKit
/// OpenDyslexic for all text; the system font when the bundled face is missing.
/// OpenDyslexic for text, OpenDyslexic Mono for code and tables; a system font when a bundled face is missing.
public enum PlakFonts {
public static let regular = "OpenDyslexic-Regular"
public static let monoRegular = "OpenDyslexicMono-Regular"
public static func body(_ size: CGFloat) -> NSFont {
FontRegistry.registerBundledFonts()
return NSFont(name: regular, size: size) ?? .systemFont(ofSize: size)
}
public static func mono(_ size: CGFloat) -> NSFont {
FontRegistry.registerBundledFonts()
return NSFont(name: monoRegular, size: size) ?? .monospacedSystemFont(ofSize: size, weight: .regular)
}
/// The height of one line of this font with no paragraph style.
static func naturalLineHeight(_ font: NSFont) -> CGFloat {
ceil(font.ascender - font.descender + font.leading)
+25 -1
View File
@@ -10,8 +10,24 @@ public enum Theme {
public static let inkMuted = NSColor(hex: 0x6E655A)
/// The caret.
public static let accent = NSColor(hex: 0x8A4B2A)
/// Selected text, and the save error message.
/// Selected text, the save error message, and the lines of a table.
public static let selection = NSColor(hex: 0xB9AE98)
/// The tint behind a code block.
public static let codePaper = NSColor(hex: 0xCBC2B0)
/// Code keywords, and true, false and null.
public static let codeKeyword = NSColor(hex: 0x7A2E14)
/// Code strings and heredocs, XML attribute values and CDATA.
public static let codeString = NSColor(hex: 0x385218)
/// Code comments: muted, yet readable on the code paper.
public static let codeComment = NSColor(hex: 0x564E44)
/// Code numbers.
public static let codeNumber = NSColor(hex: 0x2E4A7A)
/// PHP `$variables`.
public static let codeVariable = NSColor(hex: 0x0E5064)
/// XML tags and the PHP open and close tags.
public static let codeTag = NSColor(hex: 0x7A3B12)
/// XML attribute names and JSON keys.
public static let codeAttribute = NSColor(hex: 0x5E4A12)
}
public extension NSColor {
@@ -54,6 +70,14 @@ public enum PageMetrics {
public static let dateMarginMinimum: CGFloat = 120
/// Room between a margin date and the column.
public static let dateSpacing: CGFloat = 16
/// The size of code and tables against the body size.
public static let codeScale: CGFloat = 0.875
/// Room around the code inside a code block.
public static let codePadding: CGFloat = 8
public static let codeCornerRadius: CGFloat = 4
/// The widest a table column shows; a longer value is cut off with an ellipsis.
public static let tableColumnMaximum: CGFloat = 240
public static let tableCellPadding = NSSize(width: 6, height: 3)
/// The width of about 68 characters of body text.
public static func columnWidth(bodySize: CGFloat) -> CGFloat {
@@ -62,6 +62,7 @@ public final class PageWindowController: NSWindowController, NSWindowDelegate {
}
private func hide() {
page.closeEditor()
if let onHide {
onHide()
} else {