Skip to content

Commit

Permalink
rendering attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Dec 6, 2024
1 parent 154d332 commit 3c80958
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func enumerateLineFragments(with provider: NSTextElementProvider, block: (NSText
func characterIndexes(within rect: CGRect) -> IndexSet
var visibleCharacterIndexes: IndexSet
func boundingRect(for range: NSRange) -> CGRect?

func setRenderingAttributes(_ attributes: [NSAttributedString.Key : Any], for range: NSRange)
```

### `NSRange` and `NSTextRange` Additions
Expand Down
14 changes: 14 additions & 0 deletions Sources/Glyph/NSTextRange+NSRange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ extension NSTextRange {

self.init(location: start, end: end)
}

convenience init?(_ range: NSRange, provider: NSTextElementProvider) {
let docLocation = provider.documentRange.location

guard let start = provider.location?(docLocation, offsetBy: range.location) else {
return nil
}

guard let end = provider.location?(start, offsetBy: range.length) else {
return nil
}

self.init(location: start, end: end)
}
}

#endif
24 changes: 24 additions & 0 deletions Sources/Glyph/NSTextView+Additions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,28 @@ extension TextView {
#endif
}
}

extension TextView {
/// Apply attributes that do not affect layout, if supported by the text system.
public func setRenderingAttributes(_ attributes: [NSAttributedString.Key : Any], for range: NSRange) {
// first determine if TK2 is enabled, so we do not downgrade
if #available(macOS 12.0, iOS 16.0, *), let textLayoutManager = textLayoutManager {
guard
let contentManager = textLayoutManager.textContentManager,
let textRange = NSTextRange(range, provider: contentManager)
else {
return
}

textLayoutManager.setRenderingAttributes(attributes, for: textRange)

return
}

#if os(macOS)
layoutManager?.setTemporaryAttributes(attributes, forCharacterRange: range)
#endif
}
}

#endif

0 comments on commit 3c80958

Please sign in to comment.