improvements on the ui

This commit is contained in:
2026-11-25 07:14:49 +01:00
parent 3afdb6d67f
commit b7c72b9e16
249 changed files with 19702 additions and 17358 deletions
+123 -87
View File
@@ -15,14 +15,12 @@ struct PageBookmark: Equatable {
}
}
/// A drawn bookmark label and its rules.
struct BookmarkMark: Equatable {
var label: String
var rect: NSRect
var rules: [NSRect]
extension NSAttributedString.Key {
/// A bookmark line that shows in the bookmark look.
static let plakBookmarkLine = NSAttributedString.Key("plakBookmarkLine")
}
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark labels, paste and drop,
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark lines, paste and drop,
/// and the editors of code blocks and tables.
final class PageTextView: NSTextView {
let pageText: PageText
@@ -83,6 +81,7 @@ final class PageTextView: NSTextView {
selectedTextAttributes = [.backgroundColor: Theme.selection]
applyStyle()
updateDragTypeRegistration()
layout.delegate = self
}
@available(*, unavailable)
@@ -93,6 +92,7 @@ final class PageTextView: NSTextView {
}
/// Typing never carries a created date: the block it lands in gives one.
/// It is always page text, also next to a bookmark line in the bookmark look.
override var typingAttributes: [NSAttributedString.Key: Any] {
get { super.typingAttributes }
set {
@@ -100,6 +100,8 @@ final class PageTextView: NSTextView {
attributes[.plakCreated] = nil
attributes[.plakUndated] = nil
attributes[.attachment] = nil
attributes[.plakBookmarkLine] = nil
attributes.merge(pageTextLook) { _, page in page }
super.typingAttributes = attributes
}
}
@@ -147,12 +149,18 @@ final class PageTextView: NSTextView {
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)
rect = layoutManager.lineFragmentRect(forGlyphAt: shownGlyph(at: min(location, length - 1)), effectiveRange: nil)
}
return rect.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// The glyph of a character; for a hidden bookmark `=` the glyph of the title after it.
/// A null glyph has no line fragment and no place of its own.
func shownGlyph(at location: Int) -> Int {
guard let layoutManager else { return 0 }
return layoutManager.glyphIndexForCharacter(at: isHiddenBookmarkSign(at: location) ? location + 1 : location)
}
/// The bottom of the last line of text.
var textBottom: CGFloat {
lineRect(at: length).maxY
@@ -509,7 +517,7 @@ final class PageTextView: NSTextView {
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))
let glyph = shownGlyph(at: min(location, length - 1))
if location < length {
x += layoutManager.location(forGlyphAt: glyph).x
} else {
@@ -583,7 +591,10 @@ final class PageTextView: NSTextView {
/// The bookmarks of the page, as found at the last `reloadBookmarks`.
private(set) var bookmarks: [PageBookmark] = []
private var widestBookmarkLabel: CGFloat = 0
/// The width of the longest full bookmark label.
private(set) var widestBookmarkLabel: CGFloat = 0
/// True from a text change until `reloadBookmarks`: the bookmark ranges may point at other text then.
private var bookmarksAreStale = false
/// Finds the bookmarks again; call it after a change of text, created dates or text size.
func reloadBookmarks() {
@@ -597,32 +608,104 @@ final class PageTextView: NSTextView {
}
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
bookmarksAreStale = false
styleBookmarkLines()
}
/// The font of the bookmark index.
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]
/// The look of a bookmark line away from the selection.
var bookmarkLineAttributes: [NSAttributedString.Key: Any] {
let font = PlakFonts.monoBold(pageText.font.pointSize + PageMetrics.bookmarkLineGrowth)
return [
.font: font,
.foregroundColor: Theme.accent,
.baselineOffset: max(0, (pageText.lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
.plakBookmarkLine: true,
]
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would hide every label right of it.
/// The parts of the page look that a bookmark line changes.
private var pageTextLook: [NSAttributedString.Key: Any] {
pageText.attributes.filter { [NSAttributedString.Key.font, .foregroundColor, .baselineOffset].contains($0.key) }
}
override func shouldChangeText(in affectedCharRange: NSRange, replacementString: String?) -> Bool {
let allowed = super.shouldChangeText(in: affectedCharRange, replacementString: replacementString)
if allowed { bookmarksAreStale = true }
return allowed
}
override func setSelectedRanges(_ ranges: [NSValue], affinity: NSSelectionAffinity, stillSelecting: Bool) {
super.setSelectedRanges(ranges, affinity: affinity, stillSelecting: stillSelecting)
if !stillSelecting, !bookmarksAreStale { styleBookmarkLines() }
}
/// Shows each bookmark line in the bookmark look while the selection is off it, and as page text while it is on it.
/// Set straight on the text storage, so it adds no undo step and posts no text change: nothing is stamped or saved.
func styleBookmarkLines() {
guard let textStorage, textStorage.editedMask.isEmpty else { return }
let length = textStorage.length
let selection = selectedRanges.map(\.rangeValue)
let wanted = bookmarks.map(\.range).filter { $0.length > 0 && NSMaxRange($0) <= length && !Self.touches(selection, line: $0) }
let look = bookmarkLineAttributes
let font = look[.font] as? NSFont
var kept = Set<Int>()
var stale: [NSRange] = []
textStorage.enumerateAttribute(.plakBookmarkLine, in: NSRange(location: 0, length: length)) { value, run, _ in
guard value != nil else { return }
if wanted.contains(run), textStorage.attribute(.font, at: run.location, effectiveRange: nil) as? NSFont == font {
kept.insert(run.location)
} else {
stale.append(run)
}
}
let added = wanted.filter { !kept.contains($0.location) }
guard !stale.isEmpty || !added.isEmpty else { return }
let plain = pageTextLook
textStorage.beginEditing()
for range in stale {
textStorage.removeAttribute(.plakBookmarkLine, range: range)
forEachTextRun(in: range) { textStorage.addAttributes(plain, range: $0) }
}
for range in added {
forEachTextRun(in: range) { textStorage.addAttributes(look, range: $0) }
}
textStorage.endEditing()
for range in stale + added {
layoutManager?.invalidateGlyphs(forCharacterRange: NSRange(location: range.location, length: 1), changeInLength: 0, actualCharacterRange: nil)
layoutManager?.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
}
}
/// True for the `=` of a bookmark line in the bookmark look, which is not shown.
func isHiddenBookmarkSign(at location: Int) -> Bool {
guard let textStorage, location < textStorage.length,
textStorage.attribute(.plakBookmarkLine, at: location, effectiveRange: nil) != nil else { return false }
let string = textStorage.string as NSString
return string.character(at: location) == 0x3D && (location == 0 || string.character(at: location - 1) == 0x0A)
}
/// The runs of `range` without an image or other object, which keep their own look.
private func forEachTextRun(in range: NSRange, _ body: (NSRange) -> Void) {
textStorage?.enumerateAttribute(.attachment, in: range) { value, run, _ in
if value == nil { body(run) }
}
}
/// True when a caret lies on `line`, its end included, or a selection overlaps it.
static func touches(_ selection: [NSRange], line: NSRange) -> Bool {
selection.contains { range in
range.length == 0
? range.location >= line.location && range.location <= NSMaxRange(line)
: range.location <= NSMaxRange(line) && NSMaxRange(range) > line.location
}
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would cut off the drop caret.
override func draw(_ dirtyRect: NSRect) {
NSGraphicsContext.saveGraphicsState()
super.draw(dirtyRect)
@@ -631,67 +714,20 @@ final class PageTextView: NSTextView {
Theme.accent.setFill()
dropCaret.fill()
}
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 visible page: the labels right of the column are not looked after by the layout.
func invalidateBookmarks() {
setNeedsDisplay(visibleRect)
}
/// 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 width = ceil(size.width), height = ceil(size.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 marks
extension PageTextView: NSLayoutManagerDelegate {
/// Gives the hidden `=` of a bookmark line a null glyph: it stays in the text but takes no room.
func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>,
properties: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes: UnsafePointer<Int>,
font: NSFont, forGlyphRange glyphRange: NSRange) -> Int {
let hidden = (0..<glyphRange.length).filter { isHiddenBookmarkSign(at: characterIndexes[$0]) }
guard !hidden.isEmpty else { return 0 }
var changed = Array(UnsafeBufferPointer(start: properties, count: glyphRange.length))
for index in hidden { changed[index] = .null }
layoutManager.setGlyphs(glyphs, properties: changed, characterIndexes: characterIndexes, font: font, forGlyphRange: glyphRange)
return glyphRange.length
}
}