adds first version of the app

This commit is contained in:
2026-10-17 14:33:43 +02:00
parent ab1abadcd1
commit 7b891819b0
3066 changed files with 29585 additions and 0 deletions
+100
View File
@@ -0,0 +1,100 @@
import AppKit
import PlakServices
import PlakUI
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private var store: PageStore?
private var windowController: PageWindowController?
private var shortcut: GlobalShortcut?
private var statusMenu: StatusMenu?
func applicationDidFinishLaunching(_ notification: Notification) {
FontRegistry.registerBundledFonts()
NSApp.mainMenu = MainMenu.make()
let store: PageStore
do {
store = try PageStore()
} catch {
// No store means nothing can flush over the unreadable page file on quit.
showUnreadable(error)
NSApp.terminate(nil)
return
}
self.store = store
let controller = PageWindowController(store: store)
windowController = controller
controller.onHide = { [weak self] in self?.hidePlak() }
open(atEnd: true)
shortcut = GlobalShortcut { [weak self] in self?.togglePlak() }
statusMenu = StatusMenu(
show: { [weak self] in self?.showPlak() },
hide: { [weak self] in self?.hidePlak() }
)
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
open(atEnd: true)
return true
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
false
}
func applicationWillResignActive(_ notification: Notification) {
store?.flush()
}
func applicationWillTerminate(_ notification: Notification) {
store?.flush()
}
private func togglePlak() {
if NSApp.isActive, let window = windowController?.window, window.isVisible, window.isKeyWindow {
hidePlak()
} else {
showPlak()
}
}
private func showPlak() {
open(atEnd: false)
}
/// Only hiding the app gives focus back to the previous app; an ordered-out window leaves Plak active.
private func hidePlak() {
NSApp.hide(nil)
}
private func open(atEnd: Bool) {
if NSApp.isHidden { NSApp.unhideWithoutActivation() }
// NSApp.activate() is cooperative since macOS 14 and loses to the app in front on ⌘P.
(NSApp as ForcedActivation).activate(ignoringOtherApps: true)
if atEnd {
windowController?.showAtEnd()
} else {
windowController?.reveal()
}
}
private func showUnreadable(_ error: Error) {
let alert = NSAlert()
alert.alertStyle = .critical
alert.messageText = "Plak cannot read the page file"
var path = PageStore.defaultURL.path
if case let .unreadable(unreadable)? = error as? PageStoreError { path = unreadable }
alert.informativeText = "\(path) is not readable as text. Plak quits and leaves the file as it is."
alert.addButton(withTitle: "Quit")
NSApp.activate()
alert.runModal()
}
}
/// Calls the deprecated activate(ignoringOtherApps:) without the deprecation warning.
@MainActor
private protocol ForcedActivation {
func activate(ignoringOtherApps flag: Bool)
}
extension NSApplication: ForcedActivation {}
+28
View File
@@ -0,0 +1,28 @@
import AppKit
import Carbon.HIToolbox
/// The system-wide ⌘P that shows or hides Plak from any app; no Accessibility permission needed.
final class GlobalShortcut {
private let onPress: @MainActor () -> Void
private var hotKey: EventHotKeyRef?
private var handler: EventHandlerRef?
init(onPress: @escaping @MainActor () -> Void) {
self.onPress = onPress
var pressed = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
InstallEventHandler(GetApplicationEventTarget(), { _, _, userData in
guard let userData else { return OSStatus(eventNotHandledErr) }
let shortcut = Unmanaged<GlobalShortcut>.fromOpaque(userData).takeUnretainedValue()
// Carbon calls the handler on the main thread, from the app's run loop.
MainActor.assumeIsolated { shortcut.onPress() }
return noErr
}, 1, &pressed, Unmanaged.passUnretained(self).toOpaque(), &handler)
let id = EventHotKeyID(signature: OSType(0x506C_616B), id: 1)
RegisterEventHotKey(UInt32(kVK_ANSI_P), UInt32(cmdKey), id, GetApplicationEventTarget(), 0, &hotKey)
}
deinit {
if let hotKey { UnregisterEventHotKey(hotKey) }
if let handler { RemoveEventHandler(handler) }
}
}
+73
View File
@@ -0,0 +1,73 @@
import AppKit
import PlakUI
/// The app, Edit, View and Window menus; their actions go up the responder chain.
enum MainMenu {
static func make() -> NSMenu {
let main = NSMenu()
main.addItem(submenu(appMenu()))
main.addItem(submenu(fileMenu()))
main.addItem(submenu(editMenu()))
main.addItem(submenu(viewMenu()))
let window = windowMenu()
main.addItem(submenu(window))
NSApp.windowsMenu = window
return main
}
private static func submenu(_ menu: NSMenu) -> NSMenuItem {
let item = NSMenuItem(title: menu.title, action: nil, keyEquivalent: "")
item.submenu = menu
return item
}
private static func appMenu() -> NSMenu {
let menu = NSMenu(title: "Plak")
menu.addItem(withTitle: "About Plak", action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
menu.addItem(.separator())
menu.addItem(withTitle: "Hide Plak", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
let others = menu.addItem(withTitle: "Hide Others", action: #selector(NSApplication.hideOtherApplications(_:)), keyEquivalent: "h")
others.keyEquivalentModifierMask = [.command, .option]
menu.addItem(withTitle: "Show All", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "")
menu.addItem(.separator())
menu.addItem(withTitle: "Quit Plak", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
return menu
}
private static func fileMenu() -> NSMenu {
let menu = NSMenu(title: "File")
menu.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
return menu
}
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")
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")
return menu
}
private static func viewMenu() -> NSMenu {
let menu = NSMenu(title: "View")
menu.addItem(withTitle: "Bigger", action: #selector(PageViewController.makeTextBigger(_:)), keyEquivalent: "+")
// ⌘= is the same key as ⌘+ without Shift.
let equals = menu.addItem(withTitle: "Bigger", action: #selector(PageViewController.makeTextBigger(_:)), keyEquivalent: "=")
equals.isHidden = true
equals.allowsKeyEquivalentWhenHidden = true
menu.addItem(withTitle: "Smaller", action: #selector(PageViewController.makeTextSmaller(_:)), keyEquivalent: "-")
menu.addItem(withTitle: "Default Size", action: #selector(PageViewController.makeTextStandardSize(_:)), keyEquivalent: "0")
return menu
}
private static func windowMenu() -> NSMenu {
let menu = NSMenu(title: "Window")
menu.addItem(withTitle: "Minimize", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
menu.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "")
return menu
}
}
+32
View File
@@ -0,0 +1,32 @@
import AppKit
/// The menu bar icon with Show, Hide and Quit.
@MainActor
final class StatusMenu: NSObject {
private let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
private let show: () -> Void
private let hide: () -> Void
init(show: @escaping () -> Void, hide: @escaping () -> Void) {
self.show = show
self.hide = hide
super.init()
let image = NSImage(systemSymbolName: "note.text", accessibilityDescription: "Plak")
image?.isTemplate = true
item.button?.image = image
let menu = NSMenu()
menu.addItem(withTitle: "Show Plak", action: #selector(showPlak), keyEquivalent: "p").target = self
menu.addItem(withTitle: "Hide Plak", action: #selector(hidePlak), keyEquivalent: "").target = self
menu.addItem(.separator())
menu.addItem(withTitle: "Quit Plak", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
item.menu = menu
}
@objc private func showPlak() {
show()
}
@objc private func hidePlak() {
hide()
}
}
+9
View File
@@ -0,0 +1,9 @@
import AppKit
MainActor.assumeIsolated {
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.setActivationPolicy(.accessory)
app.run()
}
+45
View File
@@ -0,0 +1,45 @@
import Foundation
/// The created date of a block: its date line in the page file and its label in the margin.
public enum CreatedDate {
static let months = ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
/// The date line above the first line of a block, as `<!-- 2026-10-16 08:55 -->`.
public static func line(for date: Date, timeZone: TimeZone = .current) -> String {
let c = calendar(timeZone).dateComponents([.year, .month, .day, .hour, .minute], from: date)
return "<!-- \(pad(c.year, 4))-\(pad(c.month))-\(pad(c.day)) \(pad(c.hour)):\(pad(c.minute)) -->"
}
/// The date a page file line holds; nil when the line is not exactly a date line.
///
/// A line that does not come back the same when written again (`2026-02-30`, or a time
/// skipped by a clock change) is not a date, so the page file round trip stays exact.
public static func date(fromLine line: String, timeZone: TimeZone = .current) -> Date? {
guard let match = line.wholeMatch(of: /<!-- (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}) -->/) else { return nil }
let components = DateComponents(
year: Int(match.1), month: Int(match.2), day: Int(match.3), hour: Int(match.4), minute: Int(match.5)
)
guard let date = calendar(timeZone).date(from: components), self.line(for: date, timeZone: timeZone) == line else { return nil }
return date
}
/// The margin label: `16 okt 08:55`, with the year when it is not the year of `now`.
public static func label(for date: Date, now: Date, timeZone: TimeZone = .current) -> String {
let calendar = calendar(timeZone)
let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let month = months[((c.month ?? 1) - 1) % 12]
let year = c.year == calendar.component(.year, from: now) ? "" : " \(c.year ?? 0)"
return "\(c.day ?? 0) \(month)\(year) \(pad(c.hour)):\(pad(c.minute))"
}
private static func calendar(_ timeZone: TimeZone) -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
return calendar
}
private static func pad(_ value: Int?, _ width: Int = 2) -> String {
let digits = String(value ?? 0)
return String(repeating: "0", count: max(0, width - digits.count)) + digits
}
}
+107
View File
@@ -0,0 +1,107 @@
import Foundation
/// 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)
/// 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)
}
}
public var isBlank: Bool {
if case let .text(text) = self { return PageFile.isBlank(text) }
return false
}
}
public var lines: [Line]
/// Created dates by the index of the first line of a block; a date on any other line is not written.
public var dates: [Int: Date]
public init(lines: [Line] = [], dates: [Int: Date] = [:]) {
self.lines = lines
self.dates = dates
}
/// Reads page file text; a date line directly above the first line of a block is its created date.
public init(text: String, timeZone: TimeZone = .current) {
var raw = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
if raw.last == "" { raw.removeLast() }
var lines: [Line] = []
var dates: [Int: Date] = [:]
var index = 0
while index < raw.count {
let line = raw[index]
let startsBlock = !Self.isBlank(line) && (index == 0 || Self.isBlank(raw[index - 1]))
// A date line with no line under it in its block stays text, so the round trip stays exact.
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
}
lines.append(Self.line(line))
index += 1
}
self.init(lines: lines, dates: dates)
}
/// 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 "" }
var out: [String] = []
out.reserveCapacity(lines.count + dates.count)
for (index, line) in lines.enumerated() {
if let date = dates[index], startsBlock(at: index) {
out.append(CreatedDate.line(for: date, timeZone: timeZone))
}
out.append(line.text)
}
return out.joined(separator: "\n") + "\n"
}
/// The line ranges of the blocks, top to bottom; a run of blank lines of any length separates two blocks.
public var blocks: [Range<Int>] {
var blocks: [Range<Int>] = []
var start: Int?
for (index, line) in lines.enumerated() {
if line.isBlank {
if let first = start { blocks.append(first..<index) }
start = nil
} else if start == nil {
start = index
}
}
if let first = start { blocks.append(first..<lines.count) }
return blocks
}
public func startsBlock(at index: Int) -> Bool {
!lines[index].isBlank && (index == 0 || lines[index - 1].isBlank)
}
public static func isBlank<S: StringProtocol>(_ line: S) -> Bool {
line.allSatisfy(\.isWhitespace)
}
/// The path an image line points to, as `images/<name>`; nil when the line is not exactly an image line.
public static func imagePath(fromLine line: String) -> String? {
line.wholeMatch(of: #/!\[\]\((images/[^/()\s]+)\)/#).map { String($0.1) }
}
public static func imageLine(_ path: String) -> String {
"![](\(path))"
}
private static func line(_ text: String) -> Line {
imagePath(fromLine: text).map(Line.image) ?? .text(text)
}
}
+96
View File
@@ -0,0 +1,96 @@
import Foundation
import ImageIO
import UniformTypeIdentifiers
public enum ImageStoreError: Error, Equatable {
case unsupportedType(String)
/// The data is no image that ImageIO can read, so it cannot become a PNG.
case unreadableImage
case noFreeName
}
/// Puts pasted and dropped images in the image folder and gives back the path of their image line.
public struct ImageStore: Sendable {
public static let fileExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "heic", "webp"]
public static let folderName = "images"
/// The folder of the page file; image links are relative to it.
public let base: URL
private let now: @Sendable () -> Date
private let random: @Sendable () -> UInt16
private let timeZone: TimeZone
public init(
base: URL = PageStore.defaultURL.deletingLastPathComponent(),
now: @escaping @Sendable () -> Date = Date.init,
random: @escaping @Sendable () -> UInt16 = { UInt16.random(in: .min ... .max) },
timeZone: TimeZone = .current
) {
self.base = base
self.now = now
self.random = random
self.timeZone = timeZone
}
public var folder: URL {
base.appendingPathComponent(Self.folderName, isDirectory: true)
}
public static func isImageFile(_ url: URL) -> Bool {
url.isFileURL && fileExtensions.contains(url.pathExtension.lowercased())
}
/// Copies an image file into the image folder with its own extension.
/// - Returns: the path relative to `base`, as `images/<name>`.
public func copy(file: URL) throws -> String {
let ext = file.pathExtension.lowercased()
guard Self.fileExtensions.contains(ext) else { throw ImageStoreError.unsupportedType(ext) }
let target = try freeURL(ext: ext)
try FileManager.default.copyItem(at: file, to: target)
return relativePath(target)
}
/// Writes raw image data, as from the pasteboard, as a PNG file.
/// - Returns: the path relative to `base`, as `images/<name>`.
public func write(imageData data: Data) throws -> String {
let png = data.starts(with: [0x89, 0x50, 0x4E, 0x47]) ? data : try Self.pngData(data)
let target = try freeURL(ext: "png")
try png.write(to: target, options: .withoutOverwriting)
return relativePath(target)
}
/// The name for an image made now: `2026-10-16-085512-a3f0`.
public func name(ext: String) -> String {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now())
let stamp = String(format: "%04d-%02d-%02d-%02d%02d%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
return "\(stamp)-\(String(format: "%04x", random())).\(ext)"
}
private func freeURL(ext: String) throws -> URL {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
for _ in 0..<32 {
let url = folder.appendingPathComponent(name(ext: ext))
if !FileManager.default.fileExists(atPath: url.path) { return url }
}
throw ImageStoreError.noFreeName
}
private func relativePath(_ url: URL) -> String {
"\(Self.folderName)/\(url.lastPathComponent)"
}
private static func pngData(_ data: Data) throws -> Data {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ImageStoreError.unreadableImage }
let out = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil) else {
throw ImageStoreError.unreadableImage
}
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
CGImageDestinationAddImage(destination, image, properties)
guard CGImageDestinationFinalize(destination) else { throw ImageStoreError.unreadableImage }
return out as Data
}
}
+89
View File
@@ -0,0 +1,89 @@
import Foundation
import Observation
import PlakCore
public enum PageStoreError: Error, Equatable {
/// The page file exists but cannot be read as UTF-8; saving over it would lose the page.
case unreadable(path: String)
}
/// Reads the page file at launch and keeps it in step with the page.
///
/// Every `changed()` schedules one save after the debounce; a failed save keeps the page in
/// memory, sets `saveError`, and is tried again on the next change or `flush()`.
@MainActor
@Observable
public final class PageStore {
public nonisolated static var defaultURL: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("plak", isDirectory: true)
.appendingPathComponent("page.md")
}
/// The page file as read at launch; an empty page when there was no file.
public let loaded: PageFile
/// Makes the page file text when a save runs, so a keystroke costs no conversion; nil writes nothing.
@ObservationIgnored public var contents: () -> String? = { nil }
/// The message of the last failed save; nil once a save succeeds.
public private(set) var saveError: String?
public let url: URL
private let debounce: Duration
private let write: @Sendable (Data, URL) throws -> Void
@ObservationIgnored private var pending: Task<Void, Never>?
@ObservationIgnored private var isDirty = false
/// Reads the page file; a missing file gives an empty page.
/// - Throws: `PageStoreError.unreadable` when the file exists but cannot be read.
public init(
url: URL = PageStore.defaultURL,
debounce: Duration = .milliseconds(500),
write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically
) throws {
self.url = url
self.debounce = debounce
self.write = write
if FileManager.default.fileExists(atPath: url.path) {
guard let data = try? Data(contentsOf: url), let text = String(data: data, encoding: .utf8) else {
throw PageStoreError.unreadable(path: url.path)
}
loaded = PageFile(text: text)
} else {
loaded = PageFile()
}
}
/// Marks the page as changed; the save follows after the debounce.
public func changed() {
isDirty = true
pending?.cancel()
let delay = debounce
pending = Task { [weak self] in
try? await Task.sleep(for: delay)
guard !Task.isCancelled else { return }
self?.flush()
}
}
/// Writes a pending change now, as on quit.
public func flush() {
pending?.cancel()
pending = nil
guard isDirty, let text = contents() else { return }
do {
try write(Data(text.utf8), url)
isDirty = false
saveError = nil
} catch {
saveError = error.localizedDescription
}
}
/// Creates the folder when needed and replaces the file in one step.
public nonisolated static func writeAtomically(_ data: Data, to url: URL) throws {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try data.write(to: url, options: .atomic)
}
}
+114
View File
@@ -0,0 +1,114 @@
import AppKit
/// Decoded images by file path, shared by every image of the page.
public final class ImageCache {
private var images: [String: NSImage] = [:]
public init() {}
/// The image at `url`; a missing or unreadable file is not kept, so it shows once it exists.
func image(at url: URL) -> NSImage? {
if let image = images[url.path] { return image }
guard let image = NSImage(contentsOf: url), image.isValid, image.size.width > 0, image.size.height > 0 else { return nil }
images[url.path] = image
return image
}
}
/// An image in the page: one character that knows the path of its image line.
final class ImageAttachment: NSTextAttachment {
/// Relative to the page file folder, as `images/<name>`.
let path: String
init(path: String, image: NSImage?, font: NSFont) {
self.path = path
super.init(data: nil, ofType: nil)
attachmentCell = image.map { PageImageCell(imageCell: $0) } ?? MissingImageCell(font: font)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var isMissing: Bool {
attachmentCell is MissingImageCell
}
}
/// An image at its own size, scaled down to the width of the line, never up.
final class PageImageCell: NSTextAttachmentCell {
static func fitted(_ size: NSSize, width: CGFloat) -> NSSize {
guard size.width > width, size.width > 0, width > 0 else { return size }
return NSSize(width: floor(width), height: floor(size.height * width / size.width))
}
override func cellSize() -> NSSize {
image?.size ?? .zero
}
override func cellBaselineOffset() -> NSPoint {
.zero
}
override func cellFrame(for textContainer: NSTextContainer, proposedLineFragment lineFrag: NSRect,
glyphPosition position: NSPoint, characterIndex charIndex: Int) -> NSRect {
NSRect(origin: .zero, size: Self.fitted(cellSize(), width: lineFrag.width - max(0, position.x)))
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
image?.draw(in: cellFrame, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true,
hints: [.interpolation: NSImageInterpolation.high.rawValue])
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
/// The `image missing` text in place of an image whose file is gone.
final class MissingImageCell: NSTextAttachmentCell {
static let label = "image missing"
private(set) var text: NSAttributedString
init(font: NSFont) {
text = Self.text(font)
super.init(textCell: "")
}
@available(*, unavailable)
required init(coder: NSCoder) { fatalError("init(coder:) is not supported") }
func setFont(_ font: NSFont) {
text = Self.text(font)
}
private static func text(_ font: NSFont) -> NSAttributedString {
NSAttributedString(string: label, attributes: [.font: font, .foregroundColor: Theme.inkMuted])
}
override func cellSize() -> NSSize {
let size = text.size()
return NSSize(width: ceil(size.width), height: ceil(size.height))
}
/// Puts the label's baseline on the line's baseline.
override func cellBaselineOffset() -> NSPoint {
let font = text.attribute(.font, at: 0, effectiveRange: nil) as? NSFont
return NSPoint(x: 0, y: font?.descender ?? 0)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?) {
text.draw(in: cellFrame)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView?, characterIndex charIndex: Int, layoutManager: NSLayoutManager) {
draw(withFrame: cellFrame, in: controlView)
}
override func wantsToTrackMouse() -> Bool {
false
}
}
+284
View File
@@ -0,0 +1,284 @@
import AppKit
import PlakCore
extension NSAttributedString.Key {
/// The created date of the block a character is in.
static let plakCreated = NSAttributedString.Key("plakCreated")
/// A block read from the page file without a date line; it is never stamped.
static let plakUndated = NSAttributedString.Key("plakUndated")
}
/// Turns the page file into the text of the page view and back, and keeps the created dates of the blocks.
final class PageText {
/// The folder of the page file; image paths are relative to it.
let imageBase: URL
let images: ImageCache
private(set) var font: NSFont
private(set) var lineHeight: CGFloat = 0
/// The look of every character; an image leaves out the baseline offset.
private(set) var attributes: [NSAttributedString.Key: Any] = [:]
init(imageBase: URL, images: ImageCache = ImageCache(), bodySize: CGFloat = TextSize.standard) {
self.imageBase = imageBase
self.images = images
font = PlakFonts.body(bodySize)
setBodySize(bodySize)
}
/// The minimum line height lets a line with an image grow to the image.
func setBodySize(_ size: CGFloat) {
font = PlakFonts.body(size)
lineHeight = PageMetrics.lineHeight(font)
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight
attributes = [
.font: font,
.foregroundColor: Theme.ink,
.paragraphStyle: style,
.baselineOffset: max(0, (lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
]
}
var imageAttributes: [NSAttributedString.Key: Any] {
var attributes = attributes
attributes[.baselineOffset] = nil
return attributes
}
// MARK: Page file to text
/// The text of the page; every character of a block carries its date, or the undated mark.
func attributedString(_ file: PageFile) -> NSAttributedString {
let image = "\u{FFFC}"
let string = file.lines.map { line in
if case .image = line { return image }
return line.text
}.joined(separator: "\n")
let text = NSMutableAttributedString(string: string, attributes: attributes)
var starts: [Int] = []
starts.reserveCapacity(file.lines.count + 1)
var location = 0
for line in file.lines {
starts.append(location)
if case .image = line {
location += 2
} else {
location += (line.text as NSString).length + 1
}
}
starts.append(location)
text.beginEditing()
for (index, line) in file.lines.enumerated() {
if case let .image(path) = line {
text.setAttributes(attachmentAttributes(path), range: NSRange(location: starts[index], length: 1))
}
}
for block in file.blocks {
let range = NSRange(location: starts[block.lowerBound], length: starts[block.upperBound] - 1 - starts[block.lowerBound])
if let date = file.dates[block.lowerBound] {
text.addAttribute(.plakCreated, value: date, range: range)
} else {
text.addAttribute(.plakUndated, value: true, range: range)
}
}
text.endEditing()
return text
}
/// Pasted plain text; a line that is exactly an image line of an existing image file becomes that image.
func attributedString(plainText: String) -> NSAttributedString {
let text = NSMutableAttributedString()
let lines = plainText.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
for (index, line) in lines.enumerated() {
if index > 0 { text.append(NSAttributedString(string: "\n", attributes: attributes)) }
if let path = PageFile.imagePath(fromLine: line), FileManager.default.fileExists(atPath: imageURL(path).path) {
text.append(imageString(path))
} else {
text.append(NSAttributedString(string: line, attributes: attributes))
}
}
return text
}
func imageString(_ path: String) -> NSAttributedString {
NSAttributedString(string: "\u{FFFC}", attributes: attachmentAttributes(path))
}
func newline() -> NSAttributedString {
NSAttributedString(string: "\n", attributes: attributes)
}
private func attachmentAttributes(_ path: String) -> [NSAttributedString.Key: Any] {
var attributes = imageAttributes
attributes[.attachment] = ImageAttachment(path: path, image: images.image(at: imageURL(path)), font: font)
return attributes
}
private func imageURL(_ path: String) -> URL {
imageBase.appendingPathComponent(path)
}
// MARK: Text to page file
/// The page file of the text: one line per text line, an image always on a line of its own.
static func pageFile(_ text: NSAttributedString) -> PageFile {
let string = text.string as NSString
guard string.length > 0 else { return PageFile() }
var lines: [PageFile.Line] = []
var dates: [Int: Date] = [:]
var previousBlank = true
var location = 0
while location <= string.length {
let end = string.lineEnd(from: location)
let pieces = lineContents(text, NSRange(location: location, length: end - location))
let blank = pieces.count == 1 && pieces[0].isBlank
if !blank, previousBlank, location < string.length, let date = text.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date {
dates[lines.count] = date
}
lines += pieces
previousBlank = blank
location = end + 1
}
return PageFile(lines: lines, dates: dates)
}
/// Plain text of a range, as for the pasteboard: each image becomes its image line.
static func plainText(_ text: NSAttributedString, range: NSRange) -> String {
var out = ""
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
if let image = value as? ImageAttachment {
out += String(repeating: PageFile.imageLine(image.path), count: run.length)
} else {
out += (text.string as NSString).substring(with: run)
}
}
return out
}
/// One text line as page file lines; text typed beside an image goes on its own line.
private static func lineContents(_ text: NSAttributedString, _ range: NSRange) -> [PageFile.Line] {
let string = text.string as NSString
guard range.length > 0, string.range(of: "\u{FFFC}", range: range).location != NSNotFound else {
return [.text(string.substring(with: range))]
}
var lines: [PageFile.Line] = []
text.enumerateAttribute(.attachment, in: range) { value, run, _ in
if let image = value as? ImageAttachment {
lines += Array(repeating: .image(image.path), count: run.length)
} else {
let piece = string.substring(with: run)
if !PageFile.isBlank(piece) { lines.append(.text(piece)) }
}
}
return lines.isEmpty ? [.text("")] : lines
}
// MARK: Created dates
/// Gives every block around an edit one state: the first date or undated mark found in it, else `now`.
///
/// Characters between blocks lose their state, so typing that starts a new block never takes
/// the date of the block above.
static func stampBlocks(_ text: NSMutableAttributedString, around edit: NSRange, now: () -> Date) {
let string = text.string as NSString
let region = string.blockRegion(around: edit)
var blocks: [NSRange] = []
var blockStart: Int?
var previousEnd = region.location
var location = region.location
while location <= NSMaxRange(region) {
let end = string.lineEnd(from: location)
if string.isBlankLine(NSRange(location: location, length: end - location)) {
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
blockStart = nil
} else if blockStart == nil {
blockStart = location
}
previousEnd = end
location = end + 1
}
if let start = blockStart { blocks.append(NSRange(location: start, length: previousEnd - start)) }
var gapStart = region.location
for range in blocks + [NSRange(location: min(NSMaxRange(region) + 1, string.length), length: 0)] {
let gap = NSRange(location: gapStart, length: range.location - gapStart)
if gap.length > 0 {
text.removeAttribute(.plakCreated, range: gap)
text.removeAttribute(.plakUndated, range: gap)
}
gapStart = NSMaxRange(range)
}
for block in blocks {
var date: Date?
var undated = false
text.enumerateAttributes(in: block) { attributes, _, stop in
if let found = attributes[.plakCreated] as? Date {
date = found
stop.pointee = true
} else if attributes[.plakUndated] != nil {
undated = true
stop.pointee = true
}
}
if undated {
if !text.isUniform(.plakUndated, in: block) { text.addAttribute(.plakUndated, value: true, range: block) }
text.removeAttribute(.plakCreated, range: block)
} else {
let value = date ?? now()
if !text.isUniform(.plakCreated, value as NSDate, in: block) { text.addAttribute(.plakCreated, value: value, range: block) }
text.removeAttribute(.plakUndated, range: block)
}
}
}
}
private extension NSAttributedString {
func isUniform(_ key: NSAttributedString.Key, _ value: NSObject = true as NSNumber, in range: NSRange) -> Bool {
var effective = NSRange()
let found = attribute(key, at: range.location, longestEffectiveRange: &effective, in: range) as? NSObject
return found == value && effective == range
}
}
extension NSString {
/// The index of the newline that ends the line at `location`, or the length for the last line.
func lineEnd(from location: Int) -> Int {
guard location < length else { return length }
let found = range(of: "\n", range: NSRange(location: location, length: length - location))
return found.location == NSNotFound ? length : found.location
}
func lineStart(at location: Int) -> Int {
guard location > 0 else { return 0 }
let found = range(of: "\n", options: .backwards, range: NSRange(location: 0, length: location))
return found.location == NSNotFound ? 0 : found.location + 1
}
func isBlankLine(_ range: NSRange) -> Bool {
PageFile.isBlank(substring(with: range))
}
/// The lines of the blocks an edit touches; an edit in blank lines also takes the block above and below.
func blockRegion(around edit: NSRange) -> NSRange {
var start = lineStart(at: edit.location)
var inBlock = !isBlankLine(NSRange(location: start, length: lineEnd(from: start) - start))
while start > 0 {
let previous = lineStart(at: start - 1)
let blank = isBlankLine(NSRange(location: previous, length: start - 1 - previous))
if blank, inBlock { break }
if !blank { inBlock = true }
start = previous
}
let editEnd = min(NSMaxRange(edit), length)
var end = lineEnd(from: editEnd)
inBlock = !isBlankLine(NSRange(location: lineStart(at: editEnd), length: end - lineStart(at: editEnd)))
while end < length {
let nextEnd = lineEnd(from: end + 1)
let blank = isBlankLine(NSRange(location: end + 1, length: nextEnd - end - 1))
if blank, inBlock { break }
if !blank { inBlock = true }
end = nextEnd
}
return NSRange(location: start, length: end - start)
}
}
+446
View File
@@ -0,0 +1,446 @@
import AppKit
import PlakCore
/// A created date in the left margin: its label and where it is drawn.
struct MarginDate: Equatable {
var label: String
var rect: NSRect
}
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, paste and drop.
final class PageTextView: NSTextView {
let pageText: PageText
/// Images pasted or dropped, and the range they replace.
var onImages: (([PasteboardImage], NSRange) -> Void)?
var now: () -> Date = Date.init
/// Where ⌘V reads from.
var pasteboard: NSPasteboard = .general
/// Esc, which hides Plak.
var onHide: (() -> Void)?
private let ownedStorage: NSTextStorage
private(set) var sideSpace: CGFloat = 0
private(set) var topSpace: CGFloat = 0
init(pageText: PageText) {
self.pageText = pageText
let storage = NSTextStorage()
let layout = NSLayoutManager()
storage.addLayoutManager(layout)
let container = NSTextContainer(size: NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude))
container.widthTracksTextView = false
container.lineFragmentPadding = 0
layout.addTextContainer(container)
ownedStorage = storage
super.init(frame: .zero, textContainer: container)
// Rich text only so that images can be characters; paste and drop bring plain text.
isRichText = true
importsGraphics = false
allowsImageEditing = false
usesFontPanel = false
usesRuler = false
isEditable = true
isSelectable = true
allowsUndo = true
drawsBackground = true
backgroundColor = Theme.paper
isVerticallyResizable = true
isHorizontallyResizable = false
autoresizingMask = [.width]
maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
isAutomaticQuoteSubstitutionEnabled = false
isAutomaticDashSubstitutionEnabled = false
isAutomaticTextReplacementEnabled = false
isAutomaticSpellingCorrectionEnabled = false
isAutomaticLinkDetectionEnabled = false
isAutomaticDataDetectionEnabled = false
isContinuousSpellCheckingEnabled = false
smartInsertDeleteEnabled = false
insertionPointColor = Theme.accent
selectedTextAttributes = [.backgroundColor: Theme.selection]
applyStyle()
updateDragTypeRegistration()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
var length: Int {
(string as NSString).length
}
/// Typing never carries a created date: the block it lands in gives one.
override var typingAttributes: [NSAttributedString.Key: Any] {
get { super.typingAttributes }
set {
var attributes = newValue
attributes[.plakCreated] = nil
attributes[.plakUndated] = nil
attributes[.attachment] = nil
super.typingAttributes = attributes
}
}
/// Sets the look of the text after a change of text size.
func applyStyle() {
typingAttributes = pageText.attributes
defaultParagraphStyle = pageText.attributes[.paragraphStyle] as? NSParagraphStyle
guard let textStorage, textStorage.length > 0 else { return }
let all = NSRange(location: 0, length: textStorage.length)
textStorage.beginEditing()
textStorage.addAttributes(pageText.attributes, range: all)
textStorage.enumerateAttribute(.attachment, in: all) { value, range, _ in
guard let image = value as? ImageAttachment else { return }
textStorage.removeAttribute(.baselineOffset, range: range)
(image.attachmentCell as? MissingImageCell)?.setFont(pageText.font)
}
textStorage.endEditing()
}
// MARK: Column and spaces
override var textContainerOrigin: NSPoint {
NSPoint(x: sideSpace, y: topSpace)
}
/// The column sits `side` from the left; `sizeToFit` adds twice the inset height, so it holds top and bottom.
func setSpaces(side: CGFloat, top: CGFloat, bottom: CGFloat) {
guard side != sideSpace || top != topSpace || textContainerInset.height * 2 != top + bottom else { return }
sideSpace = side
topSpace = top
textContainerInset = NSSize(width: side, height: (top + bottom) / 2)
invalidateTextContainerOrigin()
needsDisplay = true
}
/// The line fragment at a character, in this view's coordinates; the extra line at the very end.
func lineRect(at location: Int) -> NSRect {
guard let layoutManager, let textContainer else { return .zero }
layoutManager.ensureLayout(for: textContainer)
var rect: NSRect
if length == 0 || (location >= length && !layoutManager.extraLineFragmentRect.isEmpty) {
rect = layoutManager.extraLineFragmentRect
} else {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
rect = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
}
return rect.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// The bottom of the last line of text.
var textBottom: CGFloat {
lineRect(at: length).maxY
}
// MARK: Pointer
/// The drag strip over the top of the text; there the pointer is the arrow.
weak var dragStrip: NSView?
/// The visible part of the drag strip, in this view's coordinates.
var dragStripRect: NSRect? {
guard let dragStrip, !dragStrip.isHidden else { return nil }
let rect = convert(dragStrip.bounds, from: dragStrip).intersection(visibleRect)
return rect.isEmpty ? nil : rect
}
func isUnderDragStrip(_ locationInWindow: NSPoint) -> Bool {
guard let dragStrip, !dragStrip.isHidden else { return false }
return dragStrip.bounds.contains(dragStrip.convert(locationInWindow, from: nil))
}
/// Without super, so no I-beam rect lies under the strip.
override func resetCursorRects() {
guard let strip = dragStripRect else { return super.resetCursorRects() }
let visible = visibleRect
addCursorRect(NSRect(x: visible.minX, y: strip.maxY, width: visible.width, height: max(0, visible.maxY - strip.maxY)), cursor: .iBeam)
addCursorRect(strip, cursor: .arrow)
}
override func cursorUpdate(with event: NSEvent) {
guard let window, isUnderDragStrip(window.mouseLocationOutsideOfEventStream) else { return super.cursorUpdate(with: event) }
NSCursor.arrow.set()
}
override func mouseMoved(with event: NSEvent) {
guard isUnderDragStrip(event.locationInWindow) else { return super.mouseMoved(with: event) }
NSCursor.arrow.set()
}
// MARK: Clicks
override func mouseDown(with event: NSEvent) {
if convert(event.locationInWindow, from: nil).y > textBottom {
window?.makeFirstResponder(self)
setSelectedRange(NSRange(location: length, length: 0))
return
}
super.mouseDown(with: event)
}
// MARK: Esc
/// During an input-method composition Esc cancels the composition, not the page.
/// NSTextView has no cancelOperation of its own, so super would crash.
override func cancelOperation(_ sender: Any?) {
if hasMarkedText() {
inputContext?.discardMarkedText()
unmarkText()
} else if let onHide {
onHide()
} else {
nextResponder?.tryToPerform(#selector(cancelOperation(_:)), with: sender)
}
}
// MARK: Copy, paste, drop
override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {
[.string]
}
/// Paste is enabled only for these types: without the image types a screenshot could never be pasted.
override var readablePasteboardTypes: [NSPasteboard.PasteboardType] {
[.string] + PasteboardImages.dragTypes
}
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(paste(_:)), #selector(pasteAsPlainText(_:)), #selector(pasteAsRichText(_:)):
isEditable && canPaste(from: pasteboard)
case #selector(selectAll(_:)):
false
default:
super.validateUserInterfaceItem(item)
}
}
override func validateMenuItem(_ item: NSMenuItem) -> Bool {
item.action == #selector(selectAll(_:)) ? false : super.validateMenuItem(item)
}
/// Plak has no Select All, so the page cannot be cleared in one go.
override func selectAll(_ sender: Any?) {}
func canPaste(from pasteboard: NSPasteboard) -> Bool {
PasteboardImages.contains(pasteboard) || pasteboard.availableType(from: [.string]) != nil
}
override func writeSelection(to pboard: NSPasteboard, types: [NSPasteboard.PasteboardType]) -> Bool {
guard let textStorage else { return false }
let text = selectedRanges.map { PageText.plainText(textStorage, range: $0.rangeValue) }.joined(separator: "\n")
pboard.declareTypes([.string], owner: nil)
return pboard.setString(text, forType: .string)
}
override func paste(_ sender: Any?) {
paste(from: pasteboard)
}
override func pasteAsPlainText(_ sender: Any?) {
paste(from: pasteboard)
}
override func pasteAsRichText(_ sender: Any?) {
paste(from: pasteboard)
}
func paste(from pasteboard: NSPasteboard) {
let images = PasteboardImages.read(pasteboard)
if !images.isEmpty {
onImages?(images, selectedRange())
} else if let text = pasteboard.string(forType: .string), !text.isEmpty {
insert(pageText.attributedString(plainText: text), replacing: selectedRange())
}
}
/// Text dropped from a drag, or brought by a service.
override func readSelection(from pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {
guard canPaste(from: pboard) else { return false }
paste(from: pboard)
return true
}
/// Puts the images in place of `range`, each on a line of its own.
func insertImages(_ paths: [String], replacing range: NSRange) {
guard !paths.isEmpty else { return }
let string = self.string as NSString
let text = NSMutableAttributedString()
if range.location > 0, string.character(at: range.location - 1) != 0x0A { text.append(pageText.newline()) }
for (index, path) in paths.enumerated() {
if index > 0 { text.append(pageText.newline()) }
text.append(pageText.imageString(path))
}
// On an empty line the line moves below the images, so a blank line under it stays blank.
let end = NSMaxRange(range)
let onEmptyLine = range.location == 0 || string.character(at: range.location - 1) == 0x0A
if end < string.length, string.character(at: end) != 0x0A || onEmptyLine { text.append(pageText.newline()) }
insert(text, replacing: range)
}
/// Replaces a range as one undoable change.
func insert(_ text: NSAttributedString, replacing range: NSRange) {
guard let textStorage else { return }
breakUndoCoalescing()
guard shouldChangeText(in: range, replacementString: text.string) else { return }
textStorage.replaceCharacters(in: range, with: text)
didChangeText()
setSelectedRange(NSRange(location: range.location + text.length, length: 0))
breakUndoCoalescing()
scrollRangeToVisible(selectedRange())
}
override var acceptableDragTypes: [NSPasteboard.PasteboardType] {
[.string] + PasteboardImages.dragTypes
}
/// NSTextView leaves this view unregistered here, so no drop would ever reach it.
override func updateDragTypeRegistration() {
super.updateDragTypeRegistration()
registerForDraggedTypes(acceptableDragTypes)
}
// MARK: Image drop
private var isImageDrag = false
private(set) var dropCaret: NSRect?
/// The place an image dropped at `point` lands, and the caret that shows it.
func imageDrop(at point: NSPoint) -> (location: Int, caret: NSRect) {
let location = min(characterIndexForInsertion(at: point), length)
return (location, dropCaretRect(at: location))
}
/// A 2 pt bar at the start of the character at `location`, over the height of its line.
func dropCaretRect(at location: Int) -> NSRect {
let line = lineRect(at: location)
var x = line.minX
if let layoutManager, length > 0, location < length || layoutManager.extraLineFragmentRect.isEmpty {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
if location < length {
x += layoutManager.location(forGlyphAt: glyph).x
} else {
x = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil).maxX + textContainerOrigin.x
}
}
return NSRect(x: round(x) - 1, y: line.minY, width: 2, height: line.height)
}
func showDropCaret(_ rect: NSRect?) {
guard rect != dropCaret else { return }
if let dropCaret { setNeedsDisplay(dropCaret) }
dropCaret = rect
if let rect { setNeedsDisplay(rect) }
}
/// Puts dropped images at `point`; it needs no key window or first responder, so a drop on a background window lands at once.
func dropImages(_ images: [PasteboardImage], at point: NSPoint) {
let location = imageDrop(at: point).location
showDropCaret(nil)
onImages?(images, NSRange(location: location, length: 0))
window?.makeFirstResponder(self)
}
/// Image drags never reach NSTextView: its own drop waits for the window to activate and the caret to settle.
private func imageDragUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
isImageDrag = true
showDropCaret(imageDrop(at: convert(sender.draggingLocation, from: nil)).caret)
return .copy
}
private func endImageDrag() {
isImageDrag = false
showDropCaret(nil)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingEntered(sender)
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
PasteboardImages.contains(sender.draggingPasteboard) ? imageDragUpdated(sender) : super.draggingUpdated(sender)
}
override func draggingExited(_ sender: NSDraggingInfo?) {
isImageDrag ? endImageDrag() : super.draggingExited(sender)
}
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
isImageDrag || super.prepareForDragOperation(sender)
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard isImageDrag else { return super.performDragOperation(sender) }
let images = PasteboardImages.read(sender.draggingPasteboard)
guard !images.isEmpty else {
endImageDrag()
return false
}
dropImages(images, at: convert(sender.draggingLocation, from: nil))
return true
}
override func concludeDragOperation(_ sender: NSDraggingInfo?) {
isImageDrag ? endImageDrag() : super.concludeDragOperation(sender)
}
// MARK: Margin dates
var showsDates: Bool {
sideSpace >= PageMetrics.dateMarginMinimum
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if let dropCaret, dropCaret.intersects(dirtyRect) {
Theme.accent.setFill()
dropCaret.fill()
}
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont, .foregroundColor: Theme.inkMuted]
for date in marginDates(in: dirtyRect) {
NSAttributedString(string: date.label, attributes: attributes).draw(in: date.rect)
}
}
/// Redraws the margin, where the layout does not look after the dates.
func invalidateMargin() {
let visible = visibleRect
setNeedsDisplay(NSRect(x: 0, y: visible.minY, width: sideSpace, height: visible.height))
}
var dateFont: NSFont {
PlakFonts.body(round(pageText.font.pointSize * PageMetrics.dateScale))
}
/// The dates of the blocks whose first line lies in `rect`: right-aligned next to the column, at that line.
func marginDates(in rect: NSRect) -> [MarginDate] {
guard showsDates, let layoutManager, let textContainer, let textStorage, textStorage.length > 0 else { return [] }
let origin = textContainerOrigin
let lineHeight = pageText.lineHeight
let search = NSRect(x: 0, y: rect.minY - origin.y - lineHeight, width: textContainer.size.width, height: rect.height + lineHeight * 2)
let glyphs = layoutManager.glyphRange(forBoundingRect: search, in: textContainer)
let characters = layoutManager.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)
let string = textStorage.string as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont]
let now = now()
var dates: [MarginDate] = []
var location = string.lineStart(at: characters.location)
while location < min(NSMaxRange(characters) + 1, string.length) {
let end = string.lineEnd(from: location)
defer { location = end + 1 }
guard !string.isBlankLine(NSRange(location: location, length: end - location)) else { continue }
if location > 0 {
let previous = string.lineStart(at: location - 1)
guard string.isBlankLine(NSRange(location: previous, length: location - 1 - previous)) else { continue }
}
guard let created = textStorage.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date else { continue }
let label = CreatedDate.label(for: created, now: now)
let size = NSAttributedString(string: label, attributes: attributes).size()
let line = lineRect(at: location)
let midY = line.minY + min(line.height, lineHeight) / 2
let width = ceil(size.width), height = ceil(size.height)
let right = origin.x - PageMetrics.dateSpacing
dates.append(MarginDate(label: label, rect: NSRect(x: right - width, y: round(midY - height / 2), width: width, height: height)))
}
return dates
}
}
@@ -0,0 +1,259 @@
import AppKit
import Observation
import PlakCore
import PlakServices
/// While typing, the caret line stays above a floor at 80% of the visible height.
public enum TypingScroll {
public static let floor: CGFloat = 0.8
/// The scroll y that puts the caret line's bottom on the floor; nil while it is above the floor.
public static func scrollY(caretBottom: CGFloat, visibleTop: CGFloat, visibleHeight: CGFloat) -> CGFloat? {
let limit = visibleHeight * floor
guard caretBottom - visibleTop > limit + 0.5 else { return nil }
return caretBottom - limit
}
}
/// The page: one text view in a scroll view, the column in the middle, half a window of room below the text.
public final class PageViewController: NSViewController, NSTextViewDelegate, NSTextStorageDelegate {
public let store: PageStore
let imageStore: ImageStore
let scrollView = NSScrollView()
let textView: PageTextView
let dragStrip = DragStripView()
private let banner = NSTextField(labelWithString: "")
private var textSize = TextSize()
private var isLoading = false
/// The characters edited since the last stamp of created dates.
private var unstamped: NSRange?
/// The clock for created dates.
let now: () -> Date
var clip: NSClipView { scrollView.contentView }
/// Image files go next to the page file unless `images` says otherwise.
public init(store: PageStore, images: ImageStore? = nil, now: @escaping () -> Date = Date.init) {
self.store = store
self.now = now
imageStore = images ?? ImageStore(base: store.url.deletingLastPathComponent())
textView = PageTextView(pageText: PageText(imageBase: imageStore.base))
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
public override func loadView() {
let root = NSView(frame: NSRect(x: 0, y: 0, width: 920, height: 760))
scrollView.frame = root.bounds
scrollView.autoresizingMask = [.width, .height]
scrollView.drawsBackground = true
scrollView.backgroundColor = Theme.paper
scrollView.borderType = .noBorder
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.autohidesScrollers = true
scrollView.scrollerStyle = .overlay
// The page sets its own room under the transparent title bar.
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsetsZero
scrollView.documentView = textView
clip.postsFrameChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(clipFrameChanged), name: NSView.frameDidChangeNotification, object: clip)
textView.delegate = self
textView.now = now
textView.onImages = { [weak self] images, range in self?.insertImages(images, replacing: range) }
textView.textStorage?.delegate = self
banner.font = .systemFont(ofSize: 12)
banner.textColor = Theme.ink
banner.drawsBackground = true
banner.backgroundColor = Theme.selection
banner.alignment = .center
banner.isHidden = true
banner.translatesAutoresizingMaskIntoConstraints = false
dragStrip.frame = NSRect(x: 0, y: root.bounds.height - DragStripView.height, width: root.bounds.width, height: DragStripView.height)
dragStrip.autoresizingMask = [.width, .minYMargin]
dragStrip.scrollTarget = scrollView
dragStrip.setDropTarget(textView)
textView.dragStrip = dragStrip
root.addSubview(scrollView)
root.addSubview(dragStrip)
root.addSubview(banner)
NSLayoutConstraint.activate([
banner.centerXAnchor.constraint(equalTo: root.centerXAnchor),
banner.topAnchor.constraint(equalTo: root.topAnchor, constant: 30),
banner.widthAnchor.constraint(lessThanOrEqualTo: root.widthAnchor, constant: -40),
])
view = root
load(store.loaded)
store.contents = { [weak self] in self?.pageFileText() }
observeSaveError()
}
private func load(_ file: PageFile) {
isLoading = true
textView.textStorage?.setAttributedString(textView.pageText.attributedString(file))
isLoading = false
textView.undoManager?.removeAllActions()
}
/// The page file text of the page as it is now.
func pageFileText() -> String {
guard let textStorage = textView.textStorage else { return "" }
return PageText.pageFile(textStorage).text()
}
// MARK: Launch
/// Scrolls so the end of the text sits in the vertical middle, with the caret there.
public func showEnd() {
view.layoutSubtreeIfNeeded()
layoutPage()
view.window?.makeFirstResponder(textView)
textView.setSelectedRange(NSRange(location: textView.length, length: 0))
scrollEndToMiddle()
}
// MARK: Images
/// Saves each image in the image folder and puts it in the text; a failed image is skipped.
func insertImages(_ images: [PasteboardImage], replacing range: NSRange) {
let paths = images.compactMap { image -> String? in
do {
return try save(image)
} catch {
NSLog("plak: cannot save image in %@: %@", imageStore.folder.path, String(describing: error))
return nil
}
}
if paths.count < images.count { NSSound.beep() }
textView.insertImages(paths, replacing: range)
}
private func save(_ image: PasteboardImage) throws -> String {
switch image {
case let .file(url): try imageStore.copy(file: url)
case let .data(data): try imageStore.write(imageData: data)
}
}
// MARK: Text size
@objc public func makeTextBigger(_ sender: Any?) {
textSize.bigger()
applyTextSize()
}
@objc public func makeTextSmaller(_ sender: Any?) {
textSize.smaller()
applyTextSize()
}
@objc public func makeTextStandardSize(_ sender: Any?) {
textSize.reset()
applyTextSize()
}
private func applyTextSize() {
textView.pageText.setBodySize(textSize.body)
textView.applyStyle()
layoutPage()
textView.scrollRangeToVisible(textView.selectedRange())
}
// MARK: Text changes
public func textStorage(_ textStorage: NSTextStorage, willProcessEditing editedMask: NSTextStorageEditActions,
range editedRange: NSRange, changeInLength delta: Int) {
guard editedMask.contains(.editedCharacters), !isLoading else { return }
unstamped = unstamped.map { NSUnionRange($0, editedRange) } ?? editedRange
}
public func textDidChange(_ notification: Notification) {
stampBlocks()
store.changed()
textView.invalidateMargin()
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() }
keepCaretAboveFloor()
}
/// Runs after the edit, not inside it: attribute changes during an edit move the caret to the end of the block.
private func stampBlocks() {
guard let range = unstamped, let textStorage = textView.textStorage else { return }
unstamped = nil
let length = textStorage.length
let location = min(range.location, length)
textStorage.beginEditing()
PageText.stampBlocks(textStorage, around: NSRange(location: location, length: min(NSMaxRange(range), length) - location), now: now)
textStorage.endEditing()
}
public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
guard selector == #selector(NSResponder.moveToEndOfDocument(_:)) else { return false }
textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0))
scrollEndToMiddle()
return true
}
// MARK: Layout
/// Puts the column in the middle; a short page gets more room on top so its end stays in the middle.
private func layoutPage() {
let visible = clip.bounds.size
guard visible.width > 0, let container = textView.textContainer, let layoutManager = textView.layoutManager else { return }
let column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body), visible.width - PageMetrics.sideMargin * 2))
if container.size.width != column {
container.size = NSSize(width: column, height: CGFloat.greatestFiniteMagnitude)
}
layoutManager.ensureLayout(for: container)
let side = floor((visible.width - column) / 2)
let bottom = round(visible.height / 2)
let endMid = textView.lineRect(at: textView.length).midY - textView.topSpace
let top = max(PageMetrics.topInset, round(visible.height / 2 - endMid))
textView.minSize = NSSize(width: visible.width, height: visible.height)
textView.setSpaces(side: side, top: top, bottom: bottom)
if textView.frame.width != visible.width { textView.setFrameSize(NSSize(width: visible.width, height: textView.frame.height)) }
textView.sizeToFit()
}
@objc private func clipFrameChanged(_ notification: Notification) {
layoutPage()
}
// MARK: Scrolling
private func scroll(toY y: CGFloat) {
let maxY = max(0, textView.frame.height - clip.bounds.height)
clip.scroll(to: NSPoint(x: 0, y: min(max(0, round(y)), maxY)))
scrollView.reflectScrolledClipView(clip)
}
private func scrollEndToMiddle() {
scroll(toY: textView.lineRect(at: textView.length).midY - clip.bounds.height / 2)
}
private func keepCaretAboveFloor() {
let caret = textView.lineRect(at: textView.selectedRange().location)
if let y = TypingScroll.scrollY(caretBottom: caret.maxY, visibleTop: clip.bounds.minY, visibleHeight: clip.bounds.height) {
scroll(toY: y)
}
}
// MARK: Save error
private func observeSaveError() {
let message = withObservationTracking {
store.saveError
} onChange: { [weak self] in
Task { @MainActor in self?.observeSaveError() }
}
banner.stringValue = message.map { " Cannot save the page: \($0) " } ?? ""
banner.isHidden = message == nil
}
}
@@ -0,0 +1,42 @@
import AppKit
import PlakServices
/// One image on a pasteboard: a file to copy, or raw data to write as PNG.
public enum PasteboardImage: Equatable {
case file(URL)
case data(Data)
}
/// Reads the images a paste or a drop brings.
public enum PasteboardImages {
public static let dragTypes: [NSPasteboard.PasteboardType] = [.fileURL, .png, .tiff]
/// The images on the pasteboard, empty when it holds none.
///
/// File URLs win over data: Finder puts the file icon as TIFF next to a copied file. Rich
/// text keeps its picture of the text out, so a paste from a word processor stays text.
public static func read(_ pasteboard: NSPasteboard) -> [PasteboardImage] {
let urls = fileURLs(pasteboard)
if !urls.isEmpty { return urls.filter(ImageStore.isImageFile).map(PasteboardImage.file) }
guard hasImageData(pasteboard) else { return [] }
if let png = pasteboard.data(forType: .png) { return [.data(png)] }
if let tiff = pasteboard.data(forType: .tiff) { return [.data(tiff)] }
return []
}
/// Whether `read` finds an image, without loading image data, for every move of a drag.
public static func contains(_ pasteboard: NSPasteboard) -> Bool {
let urls = fileURLs(pasteboard)
return urls.isEmpty ? hasImageData(pasteboard) : urls.contains(where: ImageStore.isImageFile)
}
private static func fileURLs(_ pasteboard: NSPasteboard) -> [URL] {
pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
}
private static func hasImageData(_ pasteboard: NSPasteboard) -> Bool {
let types = pasteboard.types ?? []
if types.contains(.rtf) || types.contains(.rtfd) { return false }
return types.contains(.png) || types.contains(.tiff)
}
}
+94
View File
@@ -0,0 +1,94 @@
Copyright (c) 2019-07-29, Abbie Gonzalez (https://abbiecod.es|support@abbiecod.es),
with Reserved Font Name OpenDyslexic.
Copyright (c) 12/2012 - 2019
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
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 THE
COPYRIGHT HOLDER 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.
+61
View File
@@ -0,0 +1,61 @@
import CoreText
import Foundation
/// Registers the bundled OpenDyslexic faces for this process.
public enum FontRegistry {
public static let resourceBundleName = "Plak_PlakUI.bundle"
/// The Fonts folder, found without `Bundle.module`: its generated accessor looks next to
/// the .app (not in Contents/Resources) and falls back to an absolute build path.
public static func fontsDirectory() -> URL? {
let fm = FileManager.default
let candidates = [
Bundle.main.resourceURL,
Bundle.main.bundleURL,
Bundle.main.executableURL?.deletingLastPathComponent(),
// Under `swift test` the code lives in an .xctest bundle beside the resource bundle.
Bundle(for: BundleToken.self).bundleURL.deletingLastPathComponent(),
]
for base in candidates.compactMap({ $0 }) {
let fonts = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Fonts")
if fm.fileExists(atPath: fonts.path) { return fonts }
let flat = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Contents/Resources/Fonts")
if fm.fileExists(atPath: flat.path) { return flat }
}
return nil
}
/// Registers every font file once; returns the PostScript names now available. Safe to call repeatedly.
@discardableResult
public static func registerBundledFonts() -> Set<String> {
lock.lock()
defer { lock.unlock() }
if let done = registered { return done }
var names = Set<String>()
guard let dir = fontsDirectory(),
let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else {
NSLog("plak: bundled fonts not found; using the system fonts")
registered = names
return names
}
for url in files where ["otf", "ttf"].contains(url.pathExtension.lowercased()) {
var error: Unmanaged<CFError>?
let ok = CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error)
let already = (error?.takeRetainedValue()).map { CFErrorGetCode($0) == CTFontManagerError.alreadyRegistered.rawValue } ?? false
if ok || already {
let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []
for d in descriptors {
if let name = CTFontDescriptorCopyAttribute(d, kCTFontNameAttribute) as? String { names.insert(name) }
}
} else {
NSLog("plak: cannot register font %@", url.lastPathComponent)
}
}
registered = names
return names
}
private final class BundleToken {}
private static let lock = NSLock()
nonisolated(unsafe) private static var registered: Set<String>?
}
+16
View File
@@ -0,0 +1,16 @@
import AppKit
/// OpenDyslexic for all text; the system font when the bundled face is missing.
public enum PlakFonts {
public static let regular = "OpenDyslexic-Regular"
public static func body(_ size: CGFloat) -> NSFont {
FontRegistry.registerBundledFonts()
return NSFont(name: regular, size: size) ?? .systemFont(ofSize: size)
}
/// 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)
}
}
+69
View File
@@ -0,0 +1,69 @@
import AppKit
/// The colour tokens of the paper look.
public enum Theme {
/// Window and page background.
public static let paper = NSColor(hex: 0xD8D0C0)
/// Text.
public static let ink = NSColor(hex: 0x2B2621)
/// Dates, `image missing`.
public static let inkMuted = NSColor(hex: 0x6E655A)
/// The caret.
public static let accent = NSColor(hex: 0x8A4B2A)
/// Selected text, and the save error message.
public static let selection = NSColor(hex: 0xB9AE98)
}
public extension NSColor {
convenience init(hex: UInt32, alpha: CGFloat = 1) {
self.init(
srgbRed: CGFloat((hex >> 16) & 0xFF) / 255,
green: CGFloat((hex >> 8) & 0xFF) / 255,
blue: CGFloat(hex & 0xFF) / 255,
alpha: alpha
)
}
}
/// The body text size that ⌘+ / ⌘− / ⌘0 change.
public struct TextSize: Equatable, Sendable {
public static let standard: CGFloat = 16
public static let range: ClosedRange<CGFloat> = 10...32
public static let step: CGFloat = 2
public private(set) var body: CGFloat
public init(body: CGFloat = TextSize.standard) {
self.body = min(max(body, TextSize.range.lowerBound), TextSize.range.upperBound)
}
public mutating func bigger() { self = TextSize(body: body + TextSize.step) }
public mutating func smaller() { self = TextSize(body: body - TextSize.step) }
public mutating func reset() { self = TextSize() }
}
/// Sizes of the page layout that follow the body size.
public enum PageMetrics {
public static let columnCharacters = 68
public static let lineHeightMultiple: CGFloat = 1.6
public static let dateScale: CGFloat = 0.75
/// Room under the transparent title bar.
public static let topInset: CGFloat = 52
public static let sideMargin: CGFloat = 28
/// The narrowest left margin that shows created dates.
public static let dateMarginMinimum: CGFloat = 120
/// Room between a margin date and the column.
public static let dateSpacing: CGFloat = 16
/// The width of about 68 characters of body text.
public static func columnWidth(bodySize: CGFloat) -> CGFloat {
let sample = String(String(repeating: "the quick brown fox jumps over a lazy dog ", count: 2).prefix(columnCharacters))
let width = NSAttributedString(string: sample, attributes: [.font: PlakFonts.body(bodySize)]).size().width
return ceil(width)
}
/// The height of one text line: 1.6 times the size, or more when the font needs it.
public static func lineHeight(_ font: NSFont) -> CGFloat {
max(round(font.pointSize * lineHeightMultiple), PlakFonts.naturalLineHeight(font))
}
}
+121
View File
@@ -0,0 +1,121 @@
import AppKit
/// What a double-click on a title bar does, after the macOS setting.
enum TitleBarDoubleClick: Equatable {
case zoom
case minimize
case none
/// Reads `AppleActionOnDoubleClick`; any value other than Minimize or None zooms, as the system does.
init(setting: String?) {
switch setting {
case "Minimize": self = .minimize
case "None": self = .none
default: self = .zoom
}
}
static var current: TitleBarDoubleClick {
TitleBarDoubleClick(setting: UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick"))
}
}
/// The top of the window, over the text under the transparent title bar: it moves the window and never draws.
final class DragStripView: NSView {
static let height: CGFloat = 28
weak var scrollTarget: NSScrollView?
weak var dropTarget: NSTextView?
override var isOpaque: Bool { false }
override var mouseDownCanMoveWindow: Bool { true }
override var acceptsFirstResponder: Bool { false }
/// The window drags at once, also when it is not key.
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
/// Leaves the window buttons to themselves.
override func hitTest(_ point: NSPoint) -> NSView? {
guard let view = super.hitTest(point) else { return nil }
guard let window, let superview else { return view }
let inWindow = superview.convert(point, to: nil)
for type in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] {
guard let button = window.standardWindowButton(type), !button.isHidden, let holder = button.superview else { continue }
if holder.convert(button.frame, to: nil).contains(inWindow) { return nil }
}
return view
}
// MARK: Pointer
/// The text view below sets the I-beam for these points too; `PageTextView` gives way, and this sets the arrow also when the window is not key.
override func updateTrackingAreas() {
super.updateTrackingAreas()
guard trackingAreas.isEmpty else { return }
addTrackingArea(NSTrackingArea(rect: .zero, options: [.cursorUpdate, .mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self))
}
override func cursorUpdate(with event: NSEvent) {
NSCursor.arrow.set()
}
override func mouseEntered(with event: NSEvent) {
NSCursor.arrow.set()
}
override func mouseMoved(with event: NSEvent) {
NSCursor.arrow.set()
}
override func mouseExited(with event: NSEvent) {}
// MARK: Drag
override func mouseDown(with event: NSEvent) {
guard let window else { return }
guard event.clickCount == 2 else {
window.performDrag(with: event)
return
}
switch TitleBarDoubleClick.current {
case .zoom: window.zoom(nil)
case .minimize: window.miniaturize(nil)
case .none: break
}
}
override func scrollWheel(with event: NSEvent) {
scrollTarget?.scrollWheel(with: event)
}
// MARK: Drops
/// A view above a drop target hides it from the drag, so the strip takes the drag and hands every step on.
func setDropTarget(_ view: NSTextView) {
dropTarget = view
registerForDraggedTypes(view.registeredDraggedTypes)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
dropTarget?.draggingEntered(sender) ?? []
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
dropTarget?.draggingUpdated(sender) ?? []
}
override func draggingExited(_ sender: NSDraggingInfo?) {
dropTarget?.draggingExited(sender)
}
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
dropTarget?.prepareForDragOperation(sender) ?? false
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
dropTarget?.performDragOperation(sender) ?? false
}
override func concludeDragOperation(_ sender: NSDraggingInfo?) {
dropTarget?.concludeDragOperation(sender)
}
}
@@ -0,0 +1,71 @@
import AppKit
import PlakServices
/// The one window: paper up to the top edge, no title, hidden instead of closed.
public final class PageWindowController: NSWindowController, NSWindowDelegate {
public static let frameName = "PlakPage"
public let page: PageViewController
/// Hides Plak on Esc, ⌘W and the close button; without it the window only orders out.
public var onHide: (() -> Void)?
public init(store: PageStore, now: @escaping () -> Date = Date.init) {
page = PageViewController(store: store, now: now)
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 920, height: 760),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered,
defer: false
)
window.title = "Plak"
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.appearance = NSAppearance(named: .aqua)
window.backgroundColor = Theme.paper
window.isReleasedWhenClosed = false
window.minSize = NSSize(width: 420, height: 320)
window.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary]
window.contentViewController = page
if !window.setFrameUsingName(Self.frameName) {
window.setContentSize(NSSize(width: 920, height: 760))
window.center()
}
window.setFrameAutosaveName(Self.frameName)
super.init(window: window)
window.delegate = self
page.textView.onHide = { [weak self] in self?.hide() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
/// Shows the window scrolled to the end of the page: at launch and on a reopen from Spotlight or Finder.
public func showAtEnd() {
showWindow(nil)
bringToFront()
page.showEnd()
}
/// Shows the window again where it was, without scrolling.
public func reveal() {
bringToFront()
}
/// orderFrontRegardless puts the window in front even while the activation of the app still lags.
private func bringToFront() {
window?.makeKeyAndOrderFront(nil)
window?.orderFrontRegardless()
}
public func windowShouldClose(_ sender: NSWindow) -> Bool {
hide()
return false
}
private func hide() {
if let onHide {
onHide()
} else {
window?.orderOut(nil)
}
}
}