-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathViewController.swift
More file actions
363 lines (283 loc) · 12.1 KB
/
ViewController.swift
File metadata and controls
363 lines (283 loc) · 12.1 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//
// ViewController.swift
// BuildTimeAnalyzer
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var buildManager: BuildManager!
@IBOutlet weak var cancelButton: NSButton!
@IBOutlet weak var compileTimeTextField: NSTextField!
@IBOutlet weak var derivedDataTextField: NSTextField!
@IBOutlet weak var instructionsView: NSView!
@IBOutlet weak var leftButton: NSButton!
@IBOutlet weak var perFileButton: NSButton!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
@IBOutlet weak var projectSelection: ProjectSelection!
@IBOutlet weak var searchField: NSSearchField!
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var statusTextField: NSTextField!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var tableViewContainerView: NSScrollView!
private let dataSource = ViewControllerDataSource()
private var currentKey: String?
private var nextDatabase: XcodeDatabase?
private(set) var lastProcessedDatabaseSchemeName: String? = nil
{
didSet
{
(NSApp.delegate as? AppDelegate)?.canExport = lastProcessedDatabaseSchemeName != nil
}
}
private var processor = LogProcessor()
var processingState: ProcessingState = .waiting {
didSet {
updateViewForState()
}
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureLayout()
buildManager.delegate = self
projectSelection.delegate = self
projectSelection.listFolders()
tableView.tableColumns[0].sortDescriptorPrototype = NSSortDescriptor(key: CompileMeasure.Order.time.rawValue, ascending: true)
tableView.tableColumns[1].sortDescriptorPrototype = NSSortDescriptor(key: CompileMeasure.Order.filename.rawValue, ascending: true)
NotificationCenter.default.addObserver(self, selector: #selector(windowWillClose(notification:)), name: NSWindow.willCloseNotification, object: nil)
}
override func viewWillAppear() {
super.viewWillAppear()
// Set window level before view is displayed
makeWindowTopMost(topMost: UserSettings.windowShouldBeTopMost)
}
override func viewWillDisappear() {
super.viewWillDisappear()
// Reset window level before view is hidden
// Reference: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Concepts/WindowLevel.html
makeWindowTopMost(topMost: false)
}
@objc func windowWillClose(notification: NSNotification) {
guard let object = notification.object, !(object is NSPanel) else { return }
NotificationCenter.default.removeObserver(self)
processor.shouldCancel = true
NSApp.terminate(self)
}
// MARK: Layout
func configureLayout() {
updateTotalLabel(with: 0)
updateViewForState()
showInstructions(true)
derivedDataTextField.stringValue = UserSettings.derivedDataLocation
makeWindowTopMost(topMost: UserSettings.windowShouldBeTopMost)
}
func showInstructions(_ show: Bool) {
instructionsView.isHidden = !show
let views: [NSView] = [compileTimeTextField, leftButton, perFileButton, searchField, statusLabel, statusTextField, tableViewContainerView]
views.forEach{ $0.isHidden = show }
if show && processingState == .processing {
processor.shouldCancel = true
cancelButton.isHidden = true
progressIndicator.isHidden = true
}
}
func updateViewForState() {
switch processingState {
case .processing:
showInstructions(false)
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
statusTextField.stringValue = ProcessingState.processingString
cancelButton.isHidden = false
case .completed(_, let stateName):
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
statusTextField.stringValue = stateName
cancelButton.isHidden = true
case .waiting:
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
statusTextField.stringValue = ProcessingState.waitingForBuildString
cancelButton.isHidden = true
}
if instructionsView.isHidden {
searchField.isHidden = !cancelButton.isHidden
}
}
func makeWindowTopMost(topMost: Bool) {
if let window = NSApplication.shared.windows.first {
let level: CGWindowLevelKey = topMost ? .floatingWindow : .normalWindow
window.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(level)))
}
}
// MARK: Actions
@IBAction func perFileCheckboxClicked(_ sender: NSButton) {
dataSource.aggregateByFile = (sender.state.rawValue == 1)
tableView.reloadData()
}
@IBAction func clipboardButtonClicked(_ sender: AnyObject) {
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects(["-Xfrontend -debug-time-function-bodies" as NSPasteboardWriting])
}
@IBAction func visitDerivedData(_ sender: AnyObject) {
NSWorkspace.shared.openFile(derivedDataTextField.stringValue)
}
@IBAction func cancelButtonClicked(_ sender: AnyObject) {
processor.shouldCancel = true
}
@IBAction func leftButtonClicked(_ sender: NSButton) {
configureMenuItems(showBuildTimesMenuItem: true)
cancelProcessing()
showInstructions(true)
projectSelection.listFolders()
}
@IBAction func exportAsCSVClicked(_ sender: Any?) {
guard let keyWindow = NSApp.keyWindow, let scheme = lastProcessedDatabaseSchemeName else {
return
}
let exporter = CSVExporter()
let savePanel = NSSavePanel()
savePanel.title = "Exporting data as CSV…"
savePanel.message = "Pick location for CSV file to be exported:"
savePanel.prompt = "Export"
savePanel.allowedFileTypes = ["csv"]
savePanel.nameFieldStringValue = exporter.filename(with: scheme)
savePanel.beginSheetModal(for: keyWindow) { [dataSource] (response) in
guard response == NSApplication.ModalResponse.OK, let fileUrl = savePanel.url else {
return
}
do
{
try dataSource.exportProcessedData(using: exporter, to: fileUrl)
}
catch
{
NSAlert(error: error).runModal()
}
}
}
override func controlTextDidChange(_ obj: Notification) {
if let field = obj.object as? NSSearchField, field == searchField {
dataSource.filter = searchField.stringValue
tableView.reloadData()
} else if let field = obj.object as? NSTextField, field == derivedDataTextField {
buildManager.stopMonitoring()
UserSettings.derivedDataLocation = field.stringValue
projectSelection.listFolders()
buildManager.startMonitoring()
}
}
// MARK: Utilities
func cancelProcessing() {
guard processingState == .processing else { return }
processor.shouldCancel = true
cancelButton.isHidden = true
}
func configureMenuItems(showBuildTimesMenuItem: Bool) {
if let appDelegate = NSApp.delegate as? AppDelegate {
appDelegate.configureMenuItems(showBuildTimesMenuItem: showBuildTimesMenuItem)
}
}
func processLog(with database: XcodeDatabase) {
guard processingState != .processing else {
if let currentKey = currentKey, currentKey != database.key {
nextDatabase = database
processor.shouldCancel = true
}
return
}
configureMenuItems(showBuildTimesMenuItem: false)
processingState = .processing
currentKey = database.key
lastProcessedDatabaseSchemeName = database.schemeName
updateTotalLabel(with: database.buildTime)
processor.processDatabase(database: database) { [weak self] (result, didComplete, didCancel) in
self?.handleProcessorUpdate(result: result, didComplete: didComplete, didCancel: didCancel)
}
}
func handleProcessorUpdate(result: [CompileMeasure], didComplete: Bool, didCancel: Bool) {
dataSource.resetSourceData(newSourceData: result)
tableView.reloadData()
if didComplete {
completeProcessorUpdate(didCancel: didCancel)
}
}
func completeProcessorUpdate(didCancel: Bool) {
let didSucceed = !dataSource.isEmpty()
var stateName = ProcessingState.failedString
if didCancel {
stateName = ProcessingState.cancelledString
} else if didSucceed {
stateName = ProcessingState.completedString
}
processingState = .completed(didSucceed: didSucceed, stateName: stateName)
currentKey = nil
if let nextDatabase = nextDatabase {
self.nextDatabase = nil
processLog(with: nextDatabase)
}
if !didSucceed {
let text = "Ensure the Swift compiler flags has been added."
NSAlert.show(withMessage: ProcessingState.failedString, andInformativeText: text)
showInstructions(true)
configureMenuItems(showBuildTimesMenuItem: true)
}
}
func updateTotalLabel(with buildTime: Int) {
let text = "Build duration: " + (buildTime < 60 ? "\(buildTime)s" : "\(buildTime / 60)m \(buildTime % 60)s")
compileTimeTextField.stringValue = text
}
}
// MARK: NSTableViewDataSource
extension ViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return dataSource.count()
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
guard let item = dataSource.measure(index: row) else { return false }
NSWorkspace.shared.openFile(item.path)
let gotoLineScript =
"tell application \"Xcode\"\n" +
" activate\n" +
"end tell\n" +
"tell application \"System Events\"\n" +
" keystroke \"l\" using command down\n" +
" keystroke \"\(item.location)\"\n" +
" keystroke return\n" +
"end tell"
DispatchQueue.main.async {
if let script = NSAppleScript(source: gotoLineScript) {
script.executeAndReturnError(nil)
}
}
return true
}
}
// MARK: NSTableViewDelegate
extension ViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let tableColumn = tableColumn, let columnIndex = tableView.tableColumns.index(of: tableColumn) else { return nil }
guard let item = dataSource.measure(index: row) else { return nil }
let result = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell\(columnIndex)"), owner: self) as? NSTableCellView
result?.textField?.stringValue = item[columnIndex]
return result
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
dataSource.sortDescriptors = tableView.sortDescriptors
tableView.reloadData()
}
}
// MARK: BuildManagerDelegate
extension ViewController: BuildManagerDelegate {
func buildManager(_ buildManager: BuildManager, shouldParseLogWithDatabase database: XcodeDatabase) {
processLog(with: database)
}
func derivedDataDidChange() {
projectSelection.listFolders()
}
}
// MARK: ProjectSelectionDelegate
extension ViewController: ProjectSelectionDelegate {
func didSelectProject(with database: XcodeDatabase) {
processLog(with: database)
}
}