-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathTextViewController+LoadView.swift
More file actions
240 lines (205 loc) · 8.82 KB
/
TextViewController+LoadView.swift
File metadata and controls
240 lines (205 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
// TextViewController+LoadView.swift
// CodeEditSourceEditor
//
// Created by Khan Winter on 10/14/23.
//
import CodeEditTextView
import AppKit
extension TextViewController {
override public func loadView() {
super.loadView()
// Create scroll view
scrollView = NSScrollView()
scrollView.documentView = textView
// Create gutter view
gutterView = GutterView(
font: font.rulerFont,
textColor: theme.text.color.withAlphaComponent(0.35),
selectedTextColor: theme.text.color,
textView: textView,
delegate: self
)
gutterView.updateWidthIfNeeded()
scrollView.addFloatingSubview(gutterView, for: .horizontal)
// Create reformatting guide view
guideView = ReformattingGuideView(
column: self.reformatAtColumn,
isVisible: self.showReformattingGuide,
theme: theme
)
guideView.wantsLayer = true
scrollView.addFloatingSubview(guideView, for: .vertical)
guideView.updatePosition(in: textView)
// Create minimap view
minimapView = MinimapView(textView: textView, theme: theme)
scrollView.addFloatingSubview(minimapView, for: .vertical)
// Create find view
let findViewController = FindViewController(target: self, childView: scrollView)
addChild(findViewController)
self.findViewController = findViewController
self.view.addSubview(findViewController.view)
findViewController.view.viewDidMoveToSuperview()
self.findViewController = findViewController
if let _undoManager {
textView.setUndoManager(_undoManager)
}
// Style views
styleTextView()
styleScrollView()
styleGutterView()
styleMinimapView()
// Set up
setUpHighlighter()
setUpTextFormation()
if !cursorPositions.isEmpty {
setCursorPositions(cursorPositions)
}
setUpConstraints()
setUpListeners()
textView.updateFrameIfNeeded()
if let localEventMonitor = self.localEvenMonitor {
NSEvent.removeMonitor(localEventMonitor)
}
setUpKeyBindings(eventMonitor: &self.localEvenMonitor)
updateContentInsets()
}
func setUpConstraints() {
guard let findViewController else { return }
let maxWidthConstraint = minimapView.widthAnchor.constraint(lessThanOrEqualToConstant: MinimapView.maxWidth)
let relativeWidthConstraint = minimapView.widthAnchor.constraint(
equalTo: view.widthAnchor,
multiplier: 0.17
)
relativeWidthConstraint.priority = .defaultLow
let minimapXConstraint = minimapView.trailingAnchor.constraint(
equalTo: scrollView.contentView.safeAreaLayoutGuide.trailingAnchor
)
self.minimapXConstraint = minimapXConstraint
NSLayoutConstraint.activate([
findViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
findViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
findViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
findViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
minimapView.topAnchor.constraint(equalTo: scrollView.contentView.topAnchor),
minimapView.bottomAnchor.constraint(equalTo: scrollView.contentView.bottomAnchor),
minimapXConstraint,
maxWidthConstraint,
relativeWidthConstraint
])
}
func setUpListeners() {
// Layout on scroll change
NotificationCenter.default.addObserver(
forName: NSView.boundsDidChangeNotification,
object: scrollView.contentView,
queue: .main
) { [weak self] notification in
guard let clipView = notification.object as? NSClipView,
let textView = self?.textView else { return }
textView.updatedViewport(self?.scrollView.documentVisibleRect ?? .zero)
self?.gutterView.needsDisplay = true
self?.minimapXConstraint?.constant = clipView.bounds.origin.x
}
// Layout on frame change
NotificationCenter.default.addObserver(
forName: NSView.frameDidChangeNotification,
object: scrollView.contentView,
queue: .main
) { [weak self] _ in
self?.textView.updatedViewport(self?.scrollView.documentVisibleRect ?? .zero)
self?.gutterView.needsDisplay = true
self?.emphasisManager?.removeEmphases(for: EmphasisGroup.brackets)
self?.updateTextInsets()
}
NotificationCenter.default.addObserver(
forName: NSView.frameDidChangeNotification,
object: textView,
queue: .main
) { [weak self] _ in
guard let textView = self?.textView else { return }
self?.gutterView.frame.size.height = (self?.textView.frame.height ?? 0) + 10
self?.gutterView.frame.origin.y = (self?.textView.frame.origin.y ?? 0.0)
- (self?.scrollView.contentInsets.top ?? 0)
self?.gutterView.needsDisplay = true
self?.guideView?.updatePosition(in: textView)
self?.scrollView.needsLayout = true
}
NotificationCenter.default.addObserver(
forName: TextSelectionManager.selectionChangedNotification,
object: textView.selectionManager,
queue: .main
) { [weak self] _ in
self?.updateCursorPosition()
self?.emphasizeSelectionPairs()
}
NSApp.publisher(for: \.effectiveAppearance)
.receive(on: RunLoop.main)
.sink { [weak self] newValue in
guard let self = self else { return }
if self.systemAppearance != newValue.name {
self.systemAppearance = newValue.name
// Reset content insets and gutter position when appearance changes
self.styleScrollView()
self.gutterView.frame.origin.y = self.textView.frame.origin.y - self.scrollView.contentInsets.top
}
}
.store(in: &cancellables)
}
func setUpKeyBindings(eventMonitor: inout Any?) {
eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event -> NSEvent? in
guard let self = self else { return event }
// Check if this window is key and if the text view is the first responder
let isKeyWindow = self.view.window?.isKeyWindow ?? false
let isFirstResponder = self.view.window?.firstResponder === self.textView
// Only handle commands if this is the key window and text view is first responder
guard isKeyWindow && isFirstResponder else { return event }
let modifierFlags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let tabKey: UInt16 = 0x30
if event.keyCode == tabKey {
return self.handleTab(event: event, modifierFalgs: modifierFlags.rawValue)
} else {
return self.handleCommand(event: event, modifierFlags: modifierFlags.rawValue)
}
}
}
func handleCommand(event: NSEvent, modifierFlags: UInt) -> NSEvent? {
let commandKey = NSEvent.ModifierFlags.command.rawValue
switch (modifierFlags, event.charactersIgnoringModifiers) {
case (commandKey, "/"):
handleCommandSlash()
return nil
case (commandKey, "["):
handleIndent(inwards: true)
return nil
case (commandKey, "]"):
handleIndent()
return nil
case (commandKey, "f"):
_ = self.textView.resignFirstResponder()
self.findViewController?.showFindPanel()
return nil
case (0, "\u{1b}"): // Escape key
self.findViewController?.findPanel.dismiss()
return nil
case (_, _):
return event
}
}
/// Handles the tab key event.
/// If the Shift key is pressed, it handles unindenting. If no modifier key is pressed, it checks if multiple lines
/// are highlighted and handles indenting accordingly.
///
/// - Returns: The original event if it should be passed on, or `nil` to indicate handling within the method.
func handleTab(event: NSEvent, modifierFalgs: UInt) -> NSEvent? {
let shiftKey = NSEvent.ModifierFlags.shift.rawValue
if modifierFalgs == shiftKey {
handleIndent(inwards: true)
} else {
// Only allow tab to work if multiple lines are selected
guard multipleLinesHighlighted() else { return event }
handleIndent()
}
return nil
}
}