updates plug with all sorts of awesome improvements
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import AppKit
|
||||
|
||||
/// The bookmark index at the top left of the window: one line per bookmark, the last bookmarks of the page only.
|
||||
final class BookmarkIndexView: NSScrollView {
|
||||
let list = BookmarkIndexList()
|
||||
|
||||
/// A click on the entry at this index.
|
||||
var onSelect: ((Int) -> Void)? {
|
||||
get { list.onSelect }
|
||||
set { list.onSelect = newValue }
|
||||
}
|
||||
|
||||
var labels: [String] { list.labels }
|
||||
|
||||
/// The height of all entries.
|
||||
var contentHeight: CGFloat { list.frame.height }
|
||||
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
drawsBackground = false
|
||||
borderType = .noBorder
|
||||
hasVerticalScroller = true
|
||||
hasHorizontalScroller = false
|
||||
autohidesScrollers = true
|
||||
scrollerStyle = .overlay
|
||||
automaticallyAdjustsContentInsets = false
|
||||
contentInsets = NSEdgeInsetsZero
|
||||
contentView.drawsBackground = false
|
||||
documentView = list
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
|
||||
|
||||
func show(labels: [String], font: NSFont, width: CGFloat) {
|
||||
list.update(labels: labels, font: font, width: width)
|
||||
}
|
||||
|
||||
/// The pointing hand over an entry, the arrow elsewhere.
|
||||
func updateCursor(at locationInWindow: NSPoint) {
|
||||
let point = list.convert(locationInWindow, from: nil)
|
||||
(list.entry(at: point) != nil ? NSCursor.pointingHand : NSCursor.arrow).set()
|
||||
}
|
||||
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
}
|
||||
|
||||
/// The entries of the bookmark index, top to bottom.
|
||||
final class BookmarkIndexList: NSView {
|
||||
private(set) var labels: [String] = []
|
||||
private(set) var font = PlakFonts.mono(10)
|
||||
var onSelect: ((Int) -> Void)?
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
override var acceptsFirstResponder: Bool { false }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
|
||||
var lineHeight: CGFloat { PageMetrics.lineHeight(font) }
|
||||
|
||||
func update(labels: [String], font: NSFont, width: CGFloat) {
|
||||
guard labels != self.labels || font != self.font || width != frame.width else { return }
|
||||
self.labels = labels
|
||||
self.font = font
|
||||
setFrameSize(NSSize(width: width, height: CGFloat(labels.count) * lineHeight))
|
||||
needsDisplay = true
|
||||
window?.invalidateCursorRects(for: self)
|
||||
}
|
||||
|
||||
func entryRect(_ index: Int) -> NSRect {
|
||||
NSRect(x: 0, y: CGFloat(index) * lineHeight, width: bounds.width, height: lineHeight)
|
||||
}
|
||||
|
||||
func entry(at point: NSPoint) -> Int? {
|
||||
guard bounds.contains(point) else { return nil }
|
||||
let index = Int(point.y / lineHeight)
|
||||
return labels.indices.contains(index) ? index : nil
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
let style = NSMutableParagraphStyle()
|
||||
style.lineBreakMode = .byTruncatingTail
|
||||
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: Theme.inkMuted, .paragraphStyle: style]
|
||||
let natural = PlakFonts.naturalLineHeight(font)
|
||||
for (index, label) in labels.enumerated() {
|
||||
let row = entryRect(index)
|
||||
guard row.intersects(dirtyRect) else { continue }
|
||||
let rect = NSRect(x: row.minX, y: row.minY + floor((row.height - natural) / 2), width: row.width, height: natural)
|
||||
NSAttributedString(string: label, attributes: attributes).draw(with: rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
guard let index = entry(at: convert(event.locationInWindow, from: nil)) else { return }
|
||||
onSelect?(index)
|
||||
}
|
||||
|
||||
override func resetCursorRects() {
|
||||
for index in labels.indices {
|
||||
let rect = entryRect(index).intersection(visibleRect)
|
||||
if !rect.isEmpty { addCursorRect(rect, cursor: .pointingHand) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ extension PageTextView {
|
||||
layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
|
||||
layoutManager.invalidateDisplay(forCharacterRange: range)
|
||||
sizeToFit()
|
||||
invalidateMargin()
|
||||
invalidateBookmarks()
|
||||
rect = objectRect(at: location)
|
||||
}
|
||||
editor.view.frame = NSRect(origin: rect.origin, size: size)
|
||||
@@ -129,7 +129,7 @@ extension PageTextView {
|
||||
newlineAdded = true
|
||||
}
|
||||
sizeToFit()
|
||||
invalidateMargin()
|
||||
invalidateBookmarks()
|
||||
guard let exit else { return }
|
||||
let caret: Int
|
||||
if let removedAt {
|
||||
|
||||
@@ -23,14 +23,14 @@ final class PageText {
|
||||
init(imageBase: URL, images: ImageCache = ImageCache(), bodySize: CGFloat = TextSize.standard) {
|
||||
self.imageBase = imageBase
|
||||
self.images = images
|
||||
font = PlakFonts.body(bodySize)
|
||||
font = PlakFonts.mono(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)
|
||||
font = PlakFonts.mono(size)
|
||||
codeFont = PlakFonts.mono(round(size * PageMetrics.codeScale))
|
||||
lineHeight = PageMetrics.lineHeight(font)
|
||||
let style = NSMutableParagraphStyle()
|
||||
@@ -314,6 +314,17 @@ extension NSString {
|
||||
PageFile.isBlank(substring(with: range))
|
||||
}
|
||||
|
||||
/// The start of the first line of the block that holds the line at `location`.
|
||||
func blockStart(at location: Int) -> Int {
|
||||
var start = lineStart(at: location)
|
||||
while start > 0 {
|
||||
let previous = lineStart(at: start - 1)
|
||||
if isBlankLine(NSRange(location: previous, length: start - 1 - previous)) { break }
|
||||
start = previous
|
||||
}
|
||||
return start
|
||||
}
|
||||
|
||||
/// 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)
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
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
|
||||
/// A bookmark of the page with the created date of its block.
|
||||
struct PageBookmark: Equatable {
|
||||
var title: String
|
||||
/// The created date label, nil when the block has no date.
|
||||
var date: String?
|
||||
/// The bookmark line, without its newline.
|
||||
var range: NSRange
|
||||
|
||||
/// `title - date`, or the title alone.
|
||||
var label: String {
|
||||
date.map { "\(title) - \($0)" } ?? title
|
||||
}
|
||||
}
|
||||
|
||||
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, paste and drop,
|
||||
/// A drawn bookmark label and its rules.
|
||||
struct BookmarkMark: Equatable {
|
||||
var label: String
|
||||
var rect: NSRect
|
||||
var rules: [NSRect]
|
||||
}
|
||||
|
||||
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark labels, paste and drop,
|
||||
/// and the editors of code blocks and tables.
|
||||
final class PageTextView: NSTextView {
|
||||
let pageText: PageText
|
||||
@@ -105,6 +120,7 @@ final class PageTextView: NSTextView {
|
||||
}
|
||||
textStorage.endEditing()
|
||||
editor?.setFont(pageText.codeFont)
|
||||
reloadBookmarks()
|
||||
}
|
||||
|
||||
// MARK: Column and spaces
|
||||
@@ -159,31 +175,131 @@ final class PageTextView: NSTextView {
|
||||
return dragStrip.bounds.contains(dragStrip.convert(locationInWindow, from: nil))
|
||||
}
|
||||
|
||||
/// Without super, so no I-beam rect lies under the strip.
|
||||
/// The bookmark index over the left of the page; it sets its own pointer.
|
||||
weak var bookmarkIndex: BookmarkIndexView?
|
||||
|
||||
/// The visible part of the bookmark index, in this view's coordinates.
|
||||
var bookmarkIndexRect: NSRect? {
|
||||
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return nil }
|
||||
let rect = convert(bookmarkIndex.bounds, from: bookmarkIndex).intersection(visibleRect)
|
||||
return rect.isEmpty ? nil : rect
|
||||
}
|
||||
|
||||
func isOverBookmarkIndex(_ locationInWindow: NSPoint) -> Bool {
|
||||
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return false }
|
||||
return bookmarkIndex.bounds.contains(bookmarkIndex.convert(locationInWindow, from: nil))
|
||||
}
|
||||
|
||||
/// Without super, so no I-beam rect lies under the strip or the bookmark index.
|
||||
override func resetCursorRects() {
|
||||
guard let strip = dragStripRect else { return super.resetCursorRects() }
|
||||
let strip = dragStripRect
|
||||
let index = bookmarkIndexRect
|
||||
guard strip != nil || index != nil 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)
|
||||
let top = strip?.maxY ?? visible.minY
|
||||
let text = NSRect(x: visible.minX, y: top, width: visible.width, height: max(0, visible.maxY - top))
|
||||
for rect in text.subtracting(index) { addCursorRect(rect, cursor: .iBeam) }
|
||||
if let strip { 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()
|
||||
guard let window else { return super.cursorUpdate(with: event) }
|
||||
let location = window.mouseLocationOutsideOfEventStream
|
||||
if isUnderDragStrip(location) {
|
||||
NSCursor.arrow.set()
|
||||
} else if isOverBookmarkIndex(location) {
|
||||
bookmarkIndex?.updateCursor(at: location)
|
||||
} else if updateHoveredLink(at: location, modifiers: NSEvent.modifierFlags) {
|
||||
NSCursor.pointingHand.set()
|
||||
} else {
|
||||
super.cursorUpdate(with: event)
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseMoved(with event: NSEvent) {
|
||||
guard isUnderDragStrip(event.locationInWindow) else { return super.mouseMoved(with: event) }
|
||||
NSCursor.arrow.set()
|
||||
let overLink = updateHoveredLink(at: event.locationInWindow, modifiers: event.modifierFlags)
|
||||
guard !isUnderDragStrip(event.locationInWindow) else { return NSCursor.arrow.set() }
|
||||
guard !isOverBookmarkIndex(event.locationInWindow) else { return bookmarkIndex?.updateCursor(at: event.locationInWindow) ?? () }
|
||||
super.mouseMoved(with: event)
|
||||
if overLink { NSCursor.pointingHand.set() }
|
||||
}
|
||||
|
||||
override func mouseExited(with event: NSEvent) {
|
||||
super.mouseExited(with: event)
|
||||
updateHoveredLink(at: event.locationInWindow, modifiers: [])
|
||||
}
|
||||
|
||||
/// ⌘ pressed or let go while the pointer rests on a link.
|
||||
override func flagsChanged(with event: NSEvent) {
|
||||
super.flagsChanged(with: event)
|
||||
guard let window else { return }
|
||||
let location = window.mouseLocationOutsideOfEventStream
|
||||
let wasOverLink = hoveredLink != nil
|
||||
if updateHoveredLink(at: location, modifiers: event.modifierFlags) {
|
||||
NSCursor.pointingHand.set()
|
||||
} else if wasOverLink {
|
||||
NSCursor.iBeam.set()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Links
|
||||
|
||||
/// Opens a ⌘-clicked link.
|
||||
var openLink: (URL) -> Void = { NSWorkspace.shared.open($0) }
|
||||
/// The link under the pointer while ⌘ is held; it shows underlined.
|
||||
private(set) var hoveredLink: NSRange?
|
||||
private var linkTracking: NSTrackingArea?
|
||||
|
||||
/// The link at `point`, only over its glyphs: the space past the end of a line holds no link.
|
||||
func link(at point: NSPoint) -> (url: URL, range: NSRange)? {
|
||||
guard let layoutManager, let textContainer, length > 0 else { return nil }
|
||||
let inContainer = NSPoint(x: point.x - textContainerOrigin.x, y: point.y - textContainerOrigin.y)
|
||||
let glyph = layoutManager.glyphIndex(for: inContainer, in: textContainer)
|
||||
let glyphRect = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: textContainer)
|
||||
guard glyphRect.contains(inContainer) else { return nil }
|
||||
return PageLink.link(in: string as NSString, at: layoutManager.characterIndexForGlyph(at: glyph))
|
||||
}
|
||||
|
||||
/// Underlines the link under the pointer while ⌘ is held; true when there is one.
|
||||
@discardableResult
|
||||
func updateHoveredLink(at locationInWindow: NSPoint, modifiers: NSEvent.ModifierFlags) -> Bool {
|
||||
var range: NSRange?
|
||||
if modifiers.contains(.command), editor == nil, !isUnderDragStrip(locationInWindow) {
|
||||
range = link(at: convert(locationInWindow, from: nil))?.range
|
||||
}
|
||||
guard range != hoveredLink, let layoutManager else { return range != nil }
|
||||
// The text may have changed since the underline was set.
|
||||
if let old = hoveredLink.map({ NSIntersectionRange($0, NSRange(location: 0, length: length)) }), old.length > 0 {
|
||||
layoutManager.removeTemporaryAttribute(.underlineStyle, forCharacterRange: old)
|
||||
}
|
||||
if let range {
|
||||
layoutManager.addTemporaryAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, forCharacterRange: range)
|
||||
}
|
||||
hoveredLink = range
|
||||
return range != nil
|
||||
}
|
||||
|
||||
/// NSTextView does not send every pointer move on its own.
|
||||
override func updateTrackingAreas() {
|
||||
super.updateTrackingAreas()
|
||||
if let linkTracking { removeTrackingArea(linkTracking) }
|
||||
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)
|
||||
addTrackingArea(area)
|
||||
linkTracking = area
|
||||
}
|
||||
|
||||
// MARK: Clicks
|
||||
|
||||
/// A plain click on a code block or table opens its editor; any click closes an open one first.
|
||||
/// ⌘-click on a link opens it; a plain click on a code block or table opens its editor; any click closes an open editor first.
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
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.contains(.command), let link = link(at: point) {
|
||||
updateHoveredLink(at: event.locationInWindow, modifiers: [])
|
||||
openLink(link.url)
|
||||
return
|
||||
}
|
||||
if event.modifierFlags.intersection([.shift, .command, .option, .control]).isEmpty, let location = object(at: point) {
|
||||
openEditor(at: location, point: point)
|
||||
return
|
||||
@@ -213,6 +329,33 @@ final class PageTextView: NSTextView {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Lorem
|
||||
|
||||
/// The sentences `#lorem` picks from.
|
||||
var loremSentences: [String] = LoremText.sentences
|
||||
|
||||
override func insertText(_ string: Any, replacementRange: NSRange) {
|
||||
super.insertText(string, replacementRange: replacementRange)
|
||||
expandLorem()
|
||||
}
|
||||
|
||||
/// Replaces a typed `#lorem` at the start of a line with lorem text, as an undo step of its own.
|
||||
private func expandLorem() {
|
||||
let caret = selectedRange()
|
||||
let trigger = LoremText.trigger as NSString
|
||||
guard caret.length == 0, !hasMarkedText(), caret.location >= trigger.length else { return }
|
||||
let text = self.string as NSString
|
||||
let range = NSRange(location: caret.location - trigger.length, length: trigger.length)
|
||||
guard text.lineStart(at: caret.location) == range.location, text.substring(with: range) == LoremText.trigger,
|
||||
let lorem = LoremText.pick(from: loremSentences) else { return }
|
||||
// Grouping by event would undo the typed `m` together with the lorem text.
|
||||
if let undoManager, undoManager.groupsByEvent, undoManager.groupingLevel == 1 {
|
||||
undoManager.endUndoGrouping()
|
||||
undoManager.beginUndoGrouping()
|
||||
}
|
||||
insert(pageText.plainString(lorem.text), replacing: range)
|
||||
}
|
||||
|
||||
// MARK: Copy, paste, drop
|
||||
|
||||
override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {
|
||||
@@ -282,6 +425,19 @@ final class PageTextView: NSTextView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pastes at the end of the page as a new block, after a blank line.
|
||||
func append(from pasteboard: NSPasteboard) {
|
||||
guard canPaste(from: pasteboard) else { return }
|
||||
let string = self.string
|
||||
let end = NSRange(location: length, length: 0)
|
||||
if string.hasSuffix("\n\n") || string.isEmpty {
|
||||
setSelectedRange(end)
|
||||
} else {
|
||||
insert(pageText.plainString(string.hasSuffix("\n") ? "\n" : "\n\n"), replacing: end)
|
||||
}
|
||||
paste(from: pasteboard)
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
@@ -423,64 +579,132 @@ final class PageTextView: NSTextView {
|
||||
isImageDrag ? endImageDrag() : super.concludeDragOperation(sender)
|
||||
}
|
||||
|
||||
// MARK: Margin dates
|
||||
// MARK: Bookmarks
|
||||
|
||||
var showsDates: Bool {
|
||||
sideSpace >= PageMetrics.dateMarginMinimum
|
||||
/// The bookmarks of the page, as found at the last `reloadBookmarks`.
|
||||
private(set) var bookmarks: [PageBookmark] = []
|
||||
private var widestBookmarkLabel: CGFloat = 0
|
||||
|
||||
/// Finds the bookmarks again; call it after a change of text, created dates or text size.
|
||||
func reloadBookmarks() {
|
||||
guard let textStorage else { return }
|
||||
let string = textStorage.string as NSString
|
||||
let now = now()
|
||||
bookmarks = Bookmark.find(in: string).map { bookmark in
|
||||
let start = string.blockStart(at: bookmark.range.location)
|
||||
let created = textStorage.attribute(.plakCreated, at: start, effectiveRange: nil) as? Date
|
||||
return PageBookmark(title: bookmark.title, date: created.map { CreatedDate.label(for: $0, now: now) }, range: bookmark.range)
|
||||
}
|
||||
let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont]
|
||||
widestBookmarkLabel = bookmarks.map { NSAttributedString(string: $0.label, attributes: attributes).size().width }.max() ?? 0
|
||||
invalidateBookmarks()
|
||||
}
|
||||
|
||||
/// True when the side space holds the bookmark index on the left and the full labels on the right.
|
||||
var bookmarksAreWide: Bool {
|
||||
!bookmarks.isEmpty && sideSpace >= PageMetrics.bookmarkWideSide(widestLabel: widestBookmarkLabel, reasonableLabel: reasonableBookmarkLabel)
|
||||
}
|
||||
|
||||
/// The width of a label of `bookmarkLabelCharacters` characters.
|
||||
var reasonableBookmarkLabel: CGFloat {
|
||||
let sample = String(repeating: "0", count: PageMetrics.bookmarkLabelCharacters)
|
||||
return NSAttributedString(string: sample, attributes: [.font: bookmarkFont]).size().width
|
||||
}
|
||||
|
||||
var bookmarkFont: NSFont {
|
||||
PlakFonts.mono(round(pageText.font.pointSize * PageMetrics.dateScale))
|
||||
}
|
||||
|
||||
/// The look of a bookmark label; a label too long for its room ends in an ellipsis.
|
||||
var bookmarkAttributes: [NSAttributedString.Key: Any] {
|
||||
let style = NSMutableParagraphStyle()
|
||||
style.lineBreakMode = .byTruncatingTail
|
||||
return [.font: bookmarkFont, .foregroundColor: Theme.inkMuted, .paragraphStyle: style]
|
||||
}
|
||||
|
||||
/// NSTextView leaves the clip narrowed to the column after drawing, which would hide every label right of it.
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
super.draw(dirtyRect)
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
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)
|
||||
let attributes = bookmarkAttributes
|
||||
for mark in bookmarkMarks(in: dirtyRect) {
|
||||
Theme.bookmarkRule.setFill()
|
||||
mark.rules.forEach { $0.fill() }
|
||||
NSAttributedString(string: mark.label, attributes: attributes)
|
||||
.draw(with: mark.rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
/// Redraws the visible page: the labels right of the column are not looked after by the layout.
|
||||
func invalidateBookmarks() {
|
||||
setNeedsDisplay(visibleRect)
|
||||
}
|
||||
|
||||
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)
|
||||
/// The labels and rules of the bookmarks whose line lies in `rect`.
|
||||
func bookmarkMarks(in rect: NSRect) -> [BookmarkMark] {
|
||||
guard !bookmarks.isEmpty, let layoutManager, let textContainer else { return [] }
|
||||
let wide = bookmarksAreWide
|
||||
let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont]
|
||||
let columnRight = textContainerOrigin.x + textContainer.size.width
|
||||
let gap = PageMetrics.bookmarkGap
|
||||
var marks: [BookmarkMark] = []
|
||||
for bookmark in bookmarks {
|
||||
let label = wide ? bookmark.label : bookmark.date
|
||||
guard let label, NSMaxRange(bookmark.range) <= length else { continue }
|
||||
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)))
|
||||
let lastCharacter = max(bookmark.range.location, NSMaxRange(bookmark.range) - 1)
|
||||
let line = lineRect(at: wide ? bookmark.range.location : lastCharacter)
|
||||
guard line.maxY >= rect.minY, line.minY <= rect.maxY else { continue }
|
||||
let midY = line.minY + min(line.height, pageText.lineHeight) / 2
|
||||
let labelY = round(midY - height / 2)
|
||||
let ruleY = floor(midY)
|
||||
if wide {
|
||||
let ruleStart = columnRight + gap
|
||||
let labelMaxX = bounds.maxX - PageMetrics.bookmarkTail - gap
|
||||
let room = labelMaxX - (ruleStart + PageMetrics.bookmarkRuleMinimum + gap)
|
||||
guard room > 0 else { continue }
|
||||
let labelX = labelMaxX - min(width, room)
|
||||
marks.append(BookmarkMark(
|
||||
label: label,
|
||||
rect: NSRect(x: labelX, y: labelY, width: labelMaxX - labelX, height: height),
|
||||
rules: [
|
||||
NSRect(x: ruleStart, y: ruleY, width: labelX - gap - ruleStart, height: 1),
|
||||
NSRect(x: labelMaxX + gap, y: ruleY, width: bounds.maxX - labelMaxX - gap, height: 1),
|
||||
]
|
||||
))
|
||||
} else {
|
||||
let glyph = layoutManager.glyphIndexForCharacter(at: lastCharacter)
|
||||
let textEnd = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil).maxX + textContainerOrigin.x
|
||||
let labelX = columnRight - width
|
||||
guard labelX - gap > textEnd + gap else { continue }
|
||||
var rules = [NSRect(x: textEnd + gap, y: ruleY, width: labelX - gap - textEnd - gap, height: 1)]
|
||||
let tailEnd = min(columnRight + gap + PageMetrics.bookmarkTail, bounds.maxX)
|
||||
if tailEnd - columnRight - gap >= 4 {
|
||||
rules.append(NSRect(x: columnRight + gap, y: ruleY, width: tailEnd - columnRight - gap, height: 1))
|
||||
}
|
||||
marks.append(BookmarkMark(label: label, rect: NSRect(x: labelX, y: labelY, width: width, height: height), rules: rules))
|
||||
}
|
||||
}
|
||||
return dates
|
||||
return marks
|
||||
}
|
||||
}
|
||||
|
||||
private extension NSRect {
|
||||
/// The parts of this rect outside `hole`: above, below, left and right of it.
|
||||
func subtracting(_ hole: NSRect?) -> [NSRect] {
|
||||
guard let hole, intersects(hole) else { return [self] }
|
||||
let cut = intersection(hole)
|
||||
return [
|
||||
NSRect(x: minX, y: minY, width: width, height: cut.minY - minY),
|
||||
NSRect(x: minX, y: cut.maxY, width: width, height: maxY - cut.maxY),
|
||||
NSRect(x: minX, y: cut.minY, width: cut.minX - minX, height: cut.height),
|
||||
NSRect(x: cut.maxX, y: cut.minY, width: maxX - cut.maxX, height: cut.height),
|
||||
].filter { $0.width > 0 && $0.height > 0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
let scrollView = NSScrollView()
|
||||
let textView: PageTextView
|
||||
let dragStrip = DragStripView()
|
||||
let bookmarkIndex = BookmarkIndexView()
|
||||
private let banner = NSTextField(labelWithString: "")
|
||||
private var textSize = TextSize()
|
||||
private var columnWidth = ColumnWidth()
|
||||
private var isLoading = false
|
||||
/// The characters edited since the last stamp of created dates.
|
||||
private var unstamped: NSRange?
|
||||
@@ -69,10 +71,10 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.onEditorChange = { [weak self] in self?.store.changed() }
|
||||
textView.textStorage?.delegate = self
|
||||
|
||||
banner.font = .systemFont(ofSize: 12)
|
||||
banner.font = PlakFonts.body(12)
|
||||
banner.textColor = Theme.ink
|
||||
banner.drawsBackground = true
|
||||
banner.backgroundColor = Theme.selection
|
||||
banner.backgroundColor = Theme.panel
|
||||
banner.alignment = .center
|
||||
banner.isHidden = true
|
||||
banner.translatesAutoresizingMaskIntoConstraints = false
|
||||
@@ -83,7 +85,12 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
dragStrip.setDropTarget(textView)
|
||||
textView.dragStrip = dragStrip
|
||||
|
||||
bookmarkIndex.isHidden = true
|
||||
bookmarkIndex.onSelect = { [weak self] index in self?.showBookmark(entry: index) }
|
||||
textView.bookmarkIndex = bookmarkIndex
|
||||
|
||||
root.addSubview(scrollView)
|
||||
root.addSubview(bookmarkIndex)
|
||||
root.addSubview(dragStrip)
|
||||
root.addSubview(banner)
|
||||
NSLayoutConstraint.activate([
|
||||
@@ -102,6 +109,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.textStorage?.setAttributedString(textView.pageText.attributedString(file))
|
||||
isLoading = false
|
||||
textView.undoManager?.removeAllActions()
|
||||
textView.reloadBookmarks()
|
||||
}
|
||||
|
||||
/// The page file text of the page as it is now, with the edit of an open editor in it.
|
||||
@@ -126,6 +134,13 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
scrollEndToMiddle()
|
||||
}
|
||||
|
||||
/// Pastes at the end of the page as a new block, then shows the end in the middle.
|
||||
public func append(from pasteboard: NSPasteboard) {
|
||||
closeEditor()
|
||||
textView.append(from: pasteboard)
|
||||
showEnd()
|
||||
}
|
||||
|
||||
// MARK: Images
|
||||
|
||||
/// Saves each image in the image folder and puts it in the text; a failed image is skipped.
|
||||
@@ -173,6 +188,23 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.scrollRangeToVisible(textView.selectedRange())
|
||||
}
|
||||
|
||||
// MARK: Column width
|
||||
|
||||
@objc public func makeColumnWider(_ sender: Any?) {
|
||||
columnWidth.wider()
|
||||
applyColumnWidth()
|
||||
}
|
||||
|
||||
@objc public func makeColumnNarrower(_ sender: Any?) {
|
||||
columnWidth.narrower()
|
||||
applyColumnWidth()
|
||||
}
|
||||
|
||||
private func applyColumnWidth() {
|
||||
layoutPage()
|
||||
textView.scrollRangeToVisible(textView.selectedRange())
|
||||
}
|
||||
|
||||
// MARK: Text changes
|
||||
|
||||
public func textStorage(_ textStorage: NSTextStorage, willProcessEditing editedMask: NSTextStorageEditActions,
|
||||
@@ -184,8 +216,12 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
public func textDidChange(_ notification: Notification) {
|
||||
stampBlocks()
|
||||
store.changed()
|
||||
textView.invalidateMargin()
|
||||
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() }
|
||||
textView.reloadBookmarks()
|
||||
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 {
|
||||
layoutPage()
|
||||
} else {
|
||||
layoutBookmarkIndex()
|
||||
}
|
||||
if !textView.isReplacingObject { keepCaretAboveFloor() }
|
||||
}
|
||||
|
||||
@@ -213,7 +249,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
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))
|
||||
let column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body, characters: columnWidth.characters), visible.width - PageMetrics.sideMargin * 2))
|
||||
if container.size.width != column {
|
||||
container.size = NSSize(width: column, height: CGFloat.greatestFiniteMagnitude)
|
||||
}
|
||||
@@ -227,6 +263,40 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
if textView.frame.width != visible.width { textView.setFrameSize(NSSize(width: visible.width, height: textView.frame.height)) }
|
||||
textView.sizeToFit()
|
||||
textView.positionEditor()
|
||||
layoutBookmarkIndex()
|
||||
}
|
||||
|
||||
/// Shows the bookmark index at the top left when bookmarks are wide, as wide as the side space.
|
||||
private func layoutBookmarkIndex() {
|
||||
let labels = textView.bookmarksAreWide ? textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount).map(\.label) : []
|
||||
let wasHidden = bookmarkIndex.isHidden
|
||||
bookmarkIndex.isHidden = labels.isEmpty
|
||||
if !labels.isEmpty {
|
||||
let inset = PageMetrics.bookmarkIndexInset
|
||||
let width = max(0, textView.sideSpace - inset - PageMetrics.bookmarkGap * 2)
|
||||
bookmarkIndex.show(labels: labels, font: textView.bookmarkFont, width: width)
|
||||
let top = view.bounds.height - PageMetrics.topInset
|
||||
let height = max(0, min(bookmarkIndex.contentHeight, top - inset))
|
||||
let frame = NSRect(x: inset, y: top - height, width: width, height: height)
|
||||
if bookmarkIndex.frame != frame { bookmarkIndex.frame = frame }
|
||||
// When the entries do not fit, the lowest bookmarks stay in sight.
|
||||
bookmarkIndex.contentView.scroll(to: NSPoint(x: 0, y: max(0, bookmarkIndex.contentHeight - height)))
|
||||
bookmarkIndex.reflectScrolledClipView(bookmarkIndex.contentView)
|
||||
}
|
||||
if wasHidden != bookmarkIndex.isHidden || !labels.isEmpty { view.window?.invalidateCursorRects(for: textView) }
|
||||
}
|
||||
|
||||
/// Puts the caret at the end of the bookmark line and scrolls that line to the vertical middle.
|
||||
/// `entry` counts from the first entry of the index, which holds only the last bookmarks.
|
||||
func showBookmark(entry: Int) {
|
||||
let shown = textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount)
|
||||
let index = shown.startIndex + entry
|
||||
closeEditor()
|
||||
guard textView.bookmarks.indices.contains(index) else { return }
|
||||
let end = NSMaxRange(textView.bookmarks[index].range)
|
||||
view.window?.makeFirstResponder(textView)
|
||||
textView.setSelectedRange(NSRange(location: end, length: 0))
|
||||
scroll(toY: textView.lineRect(at: end).midY - clip.bounds.height / 2)
|
||||
}
|
||||
|
||||
@objc private func clipFrameChanged(_ notification: Notification) {
|
||||
|
||||
@@ -79,7 +79,7 @@ struct TableLayout {
|
||||
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()
|
||||
Theme.rule.setFill()
|
||||
var x = origin.x
|
||||
for width in columnWidths + [0] {
|
||||
NSRect(x: x, y: top, width: line, height: bottom - top + line).fill()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
Copyright (c) 2019-07-29, Abbie Gonzalez (https://abbiecod.es|support@abbiecod.es),
|
||||
with Reserved Font Name OpenDyslexic.
|
||||
Copyright (c) 12/2012 - 2019
|
||||
Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ThinItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLight.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Light.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-LightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Regular.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Italic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Medium.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-MediumItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Bold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-BoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved.
|
||||
|
||||
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
|
||||
@@ -19,7 +18,7 @@ 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,
|
||||
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
|
||||
|
||||
Binary file not shown.
@@ -1,40 +0,0 @@
|
||||
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.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,7 @@
|
||||
import CoreText
|
||||
import Foundation
|
||||
|
||||
/// Registers the bundled OpenDyslexic and OpenDyslexic Mono faces for this process.
|
||||
/// Registers the bundled IBM Plex faces for this process. CoreText reads WOFF2 directly.
|
||||
public enum FontRegistry {
|
||||
public static let resourceBundleName = "Plak_PlakUI.bundle"
|
||||
|
||||
@@ -38,7 +38,7 @@ public enum FontRegistry {
|
||||
registered = names
|
||||
return names
|
||||
}
|
||||
for url in files where ["otf", "ttf"].contains(url.pathExtension.lowercased()) {
|
||||
for url in files where ["woff2", "woff", "ttf", "otf"].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
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import AppKit
|
||||
|
||||
/// OpenDyslexic for text, OpenDyslexic Mono for code and tables; a system font when a bundled face is missing.
|
||||
/// IBM Plex Mono for the page, code, tables and bookmarks, IBM Plex Sans for the banner; the system fonts when Plex 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)
|
||||
return NSFont(name: "IBMPlexSans-Regular", size: size) ?? NSFont.systemFont(ofSize: size)
|
||||
}
|
||||
|
||||
public static func mono(_ size: CGFloat) -> NSFont {
|
||||
FontRegistry.registerBundledFonts()
|
||||
return NSFont(name: monoRegular, size: size) ?? .monospacedSystemFont(ofSize: size, weight: .regular)
|
||||
return NSFont(name: "IBMPlexMono-Regular", size: size) ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
|
||||
}
|
||||
|
||||
/// The height of one line of this font with no paragraph style.
|
||||
|
||||
@@ -1,33 +1,39 @@
|
||||
import AppKit
|
||||
|
||||
/// The colour tokens of the paper look.
|
||||
/// The colour tokens of the Kade dark slate look, the same as Helder.
|
||||
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, the save error message, and the lines of a table.
|
||||
public static let selection = NSColor(hex: 0xB9AE98)
|
||||
public static let paper = NSColor(hex: 0x101720)
|
||||
/// Text, also on the save error banner.
|
||||
public static let ink = NSColor(hex: 0xE4E7E6)
|
||||
/// Bookmark labels, the bookmark index, `image missing`.
|
||||
public static let inkMuted = NSColor(hex: 0x6C7783)
|
||||
/// The caret, the drop caret and the frame of the selected table cell.
|
||||
public static let accent = NSColor(hex: 0xE8913A)
|
||||
/// The tint behind selected text.
|
||||
public static let selection = NSColor(hex: 0xE8913A, alpha: 0.22)
|
||||
/// The grid lines of a table.
|
||||
public static let rule = NSColor(hex: 0x3A424C)
|
||||
/// The hairline from a bookmark to its label.
|
||||
public static let bookmarkRule = NSColor(hex: 0x6C7783)
|
||||
/// The background of the save error banner.
|
||||
public static let panel = NSColor(hex: 0x18202B)
|
||||
/// The tint behind a code block.
|
||||
public static let codePaper = NSColor(hex: 0xCBC2B0)
|
||||
public static let codePaper = NSColor(hex: 0x18202B)
|
||||
/// Code keywords, and true, false and null.
|
||||
public static let codeKeyword = NSColor(hex: 0x7A2E14)
|
||||
public static let codeKeyword = NSColor(hex: 0xC3A6CE)
|
||||
/// 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)
|
||||
public static let codeString = NSColor(hex: 0x8FBFB4)
|
||||
/// Code comments.
|
||||
public static let codeComment = NSColor(hex: 0x6C7783)
|
||||
/// Code numbers.
|
||||
public static let codeNumber = NSColor(hex: 0x2E4A7A)
|
||||
public static let codeNumber = NSColor(hex: 0xF0B476)
|
||||
/// PHP `$variables`.
|
||||
public static let codeVariable = NSColor(hex: 0x0E5064)
|
||||
public static let codeVariable = NSColor(hex: 0xBAC0C0)
|
||||
/// XML tags and the PHP open and close tags.
|
||||
public static let codeTag = NSColor(hex: 0x7A3B12)
|
||||
public static let codeTag = NSColor(hex: 0xC3A6CE)
|
||||
/// XML attribute names and JSON keys.
|
||||
public static let codeAttribute = NSColor(hex: 0x5E4A12)
|
||||
public static let codeAttribute = NSColor(hex: 0xBAC0C0)
|
||||
}
|
||||
|
||||
public extension NSColor {
|
||||
@@ -43,7 +49,7 @@ public extension NSColor {
|
||||
|
||||
/// The body text size that ⌘+ / ⌘− / ⌘0 change.
|
||||
public struct TextSize: Equatable, Sendable {
|
||||
public static let standard: CGFloat = 16
|
||||
public static let standard: CGFloat = 13
|
||||
public static let range: ClosedRange<CGFloat> = 10...32
|
||||
public static let step: CGFloat = 2
|
||||
|
||||
@@ -58,35 +64,67 @@ public struct TextSize: Equatable, Sendable {
|
||||
public mutating func reset() { self = TextSize() }
|
||||
}
|
||||
|
||||
/// The width of the reading column in characters, that ⌘. / ⌘, change.
|
||||
public struct ColumnWidth: Equatable, Sendable {
|
||||
public static let standard = 68
|
||||
public static let range: ClosedRange<Int> = 40...160
|
||||
public static let step = 8
|
||||
|
||||
public private(set) var characters: Int
|
||||
|
||||
public init(characters: Int = ColumnWidth.standard) {
|
||||
self.characters = min(max(characters, ColumnWidth.range.lowerBound), ColumnWidth.range.upperBound)
|
||||
}
|
||||
|
||||
public mutating func wider() { self = ColumnWidth(characters: characters + ColumnWidth.step) }
|
||||
public mutating func narrower() { self = ColumnWidth(characters: characters - ColumnWidth.step) }
|
||||
public mutating func reset() { self = ColumnWidth() }
|
||||
}
|
||||
|
||||
/// 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 lineHeightMultiple: CGFloat = 20.0 / 13.0
|
||||
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 size of code and tables against the body size.
|
||||
public static let codeScale: CGFloat = 0.875
|
||||
/// Room between the left edge of the window and the bookmark index.
|
||||
public static let bookmarkIndexInset: CGFloat = 8
|
||||
/// The bookmark index shows only the last bookmarks of the page.
|
||||
public static let bookmarkIndexCount = 10
|
||||
/// Room between the column, a bookmark rule and a bookmark label.
|
||||
public static let bookmarkGap: CGFloat = 8
|
||||
/// The rule right of a bookmark label.
|
||||
public static let bookmarkTail: CGFloat = 16
|
||||
/// The shortest rule between the column and a bookmark label.
|
||||
public static let bookmarkRuleMinimum: CGFloat = 24
|
||||
/// Below this side space bookmarks are always narrow.
|
||||
public static let bookmarkSideMinimum: CGFloat = 160
|
||||
/// A label longer than this many characters never keeps bookmarks narrow; it is cut off with an ellipsis instead.
|
||||
public static let bookmarkLabelCharacters = 40
|
||||
/// The size of code and tables against the body size; the same as the page text.
|
||||
public static let codeScale: CGFloat = 1
|
||||
/// Room around the code inside a code block.
|
||||
public static let codePadding: CGFloat = 8
|
||||
public static let codeCornerRadius: CGFloat = 4
|
||||
public static let codeCornerRadius: CGFloat = 2
|
||||
/// 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 {
|
||||
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
|
||||
/// The side space from which bookmarks are wide: room for the widest label, at most `reasonableLabel`, with its rules.
|
||||
public static func bookmarkWideSide(widestLabel: CGFloat, reasonableLabel: CGFloat) -> CGFloat {
|
||||
let label = ceil(min(widestLabel, reasonableLabel))
|
||||
return max(bookmarkGap + bookmarkRuleMinimum + bookmarkGap + label + bookmarkGap + bookmarkTail, bookmarkSideMinimum)
|
||||
}
|
||||
|
||||
/// The width of about `characters` characters of body text.
|
||||
public static func columnWidth(bodySize: CGFloat, characters: Int) -> CGFloat {
|
||||
let sample = String(String(repeating: "the quick brown fox jumps over a lazy dog ", count: 4).prefix(characters))
|
||||
let width = NSAttributedString(string: sample, attributes: [.font: PlakFonts.mono(bodySize)]).size().width
|
||||
return ceil(width)
|
||||
}
|
||||
|
||||
/// The height of one text line: 1.6 times the size, or more when the font needs it.
|
||||
/// The height of one text line: 20/13 of the size, Helder's code line, or more when the font needs it.
|
||||
public static func lineHeight(_ font: NSFont) -> CGFloat {
|
||||
max(round(font.pointSize * lineHeightMultiple), PlakFonts.naturalLineHeight(font))
|
||||
}
|
||||
|
||||
@@ -20,9 +20,10 @@ enum TitleBarDoubleClick: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// The top of the window, over the text under the transparent title bar: it moves the window and never draws.
|
||||
/// The top of the window, over the text under the transparent title bar: it moves the window and covers the text that scrolls under the buttons.
|
||||
final class DragStripView: NSView {
|
||||
static let height: CGFloat = 28
|
||||
static let fadeHeight: CGFloat = 8
|
||||
weak var scrollTarget: NSScrollView?
|
||||
weak var dropTarget: NSTextView?
|
||||
|
||||
@@ -33,6 +34,13 @@ final class DragStripView: NSView {
|
||||
/// The window drags at once, also when it is not key.
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
let (fade, solid) = bounds.divided(atDistance: Self.fadeHeight, from: isFlipped ? .maxYEdge : .minYEdge)
|
||||
Theme.paper.setFill()
|
||||
solid.fill()
|
||||
NSGradient(starting: Theme.paper.withAlphaComponent(0), ending: Theme.paper)?.draw(in: fade, angle: isFlipped ? -90 : 90)
|
||||
}
|
||||
|
||||
/// Leaves the window buttons to themselves.
|
||||
override func hitTest(_ point: NSPoint) -> NSView? {
|
||||
guard let view = super.hitTest(point) else { return nil }
|
||||
|
||||
@@ -19,7 +19,7 @@ public final class PageWindowController: NSWindowController, NSWindowDelegate {
|
||||
window.title = "Plak"
|
||||
window.titleVisibility = .hidden
|
||||
window.titlebarAppearsTransparent = true
|
||||
window.appearance = NSAppearance(named: .aqua)
|
||||
window.appearance = NSAppearance(named: .darkAqua)
|
||||
window.backgroundColor = Theme.paper
|
||||
window.isReleasedWhenClosed = false
|
||||
window.minSize = NSSize(width: 420, height: 320)
|
||||
|
||||
Reference in New Issue
Block a user