forked from sbarex/SourceCodeSyntaxHighlight
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
226 lines (195 loc) · 8.51 KB
/
Copy pathAppDelegate.swift
File metadata and controls
226 lines (195 loc) · 8.51 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
//
// AppDelegate.swift
// SyntaxHighlight
//
// Created by sbarex on 15/10/2019.
// Copyright © 2019 sbarex. All rights reserved.
//
//
// This file is part of SyntaxHighlight.
// SyntaxHighlight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SyntaxHighlight is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SyntaxHighlight. If not, see <http://www.gnu.org/licenses/>.
import Cocoa
import Sparkle
import Syntax_Highlight_XPC_Service
typealias ExampleItem = (url: URL, title: String, uti: String, standalone: Bool)
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
@IBOutlet weak var advancedSettingsMenu: NSMenuItem!
var userDriver: SPUStandardUserDriver?
var updater: SPUUpdater?
var isAdvancedSettingsVisible: Bool = false {
didSet {
advancedSettingsMenu.state = isAdvancedSettingsVisible ? .on : .off
guard oldValue != isAdvancedSettingsVisible else {
return
}
UserDefaults.standard.setValue(isAdvancedSettingsVisible, forKey: "advanced-settings")
NotificationCenter.default.post(name: .AdvancedSettings, object: isAdvancedSettingsVisible)
}
}
@IBAction func handleAdvancedSettings(_ sender: Any) {
isAdvancedSettingsVisible = !isAdvancedSettingsVisible
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
return SCSHWrapper.shared.applicationShouldTerminate()
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
let utis = handledUTIs
DispatchQueue.global(qos: .userInitiated).async() {
for uti in utis {
uti.initLazyVars(async: false)
uti.fetchIcon(async: false)
}
}
// Insert code here to initialize your application
if #available(OSX 10.12.2, *) {
NSApplication.shared.isAutomaticCustomizeTouchBarMenuItemEnabled = true
}
if let state = UserDefaults.standard.object(forKey: "advanced-settings") as? Bool {
isAdvancedSettingsVisible = state
} else {
isAdvancedSettingsVisible = false
}
let hostBundle = Bundle.main
let applicationBundle = hostBundle;
self.userDriver = SPUStandardUserDriver(hostBundle: hostBundle, delegate: nil)
self.updater = SPUUpdater(hostBundle: hostBundle, applicationBundle: applicationBundle, userDriver: self.userDriver!, delegate: nil)
do {
try self.updater!.start()
} catch {
print("Failed to start updater with error: \(error)")
let alert = NSAlert()
alert.messageText = "Updater Error"
alert.informativeText = "The Updater failed to start. For detailed error information, check the Console.app log."
alert.addButton(withTitle: "OK")
alert.runModal()
}
}
@IBAction func checkForUpdates(_ sender: Any)
{
self.updater?.checkForUpdates()
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool
{
if menuItem.action == #selector(self.checkForUpdates(_:)) {
return self.userDriver?.canCheckForUpdates ?? false
}
return true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
SCSHWrapper.connection.invalidate()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
/// Get the url of the quicklook extension.
func getQLAppexUrl() -> URL? {
guard let base_url = Bundle.main.builtInPlugInsURL else {
return nil
}
do {
for url in try FileManager.default.contentsOfDirectory(at: base_url, includingPropertiesForKeys: nil, options: []) {
// Suppose only one appex on the plugin dir.
if url.pathExtension == "appex" {
return url
}
}
} catch {
return nil
}
return nil
}
lazy var handledUTIs: [UTI] = {
// Get the list of all uti supported by the quicklook extension.
guard let url = getQLAppexUrl(), let bundle = Bundle(url: url), let extensionInfo = bundle.object(forInfoDictionaryKey: "NSExtension") as? [String: Any], let attributes = extensionInfo["NSExtensionAttributes"] as? [String: Any], let supportedTypes = attributes["QLSupportedContentTypes"] as? [String] else {
return []
}
var fileTypes: [UTI] = []
for type in supportedTypes {
let uti = UTI(type)
if uti.isValid {
fileTypes.append(uti)
} else {
print("Ignoring `\(type)` uti because it has no mime or file extension associated.")
}
}
// Sort alphabetically.
fileTypes.sort { (a, b) -> Bool in
return a.description.lowercased() < b.description.lowercased()
}
return fileTypes
}()
fileprivate var allExamples: [ExampleItem]?
/// Get the list of available source file example.
func getAvailableExamples() -> [ExampleItem] {
if let allExamples = self.allExamples {
return allExamples
}
// Populate the example files list.
var examples: [ExampleItem] = []
if let examplesDirURL = Bundle.main.url(forResource: "examples", withExtension: nil) {
let fileManager = FileManager.default
if let files = try? fileManager.contentsOfDirectory(at: examplesDirURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) {
for file in files {
let title: String
if let uti = UTI(URL: file) {
title = uti.description + " (." + file.pathExtension + ")"
examples.append((url: file, title: title, uti: uti.UTI, standalone: true))
} else {
title = file.lastPathComponent
examples.append((url: file, title: title, uti: "", standalone: true))
}
}
examples.sort { (a, b) -> Bool in
a.title < b.title
}
}
}
self.allExamples = examples
return examples
}
@IBAction func openApplicationSupportFolder(_ sender: Any) {
SCSHWrapper.service?.getApplicationSupport(reply: { (url) in
if let u = url, FileManager.default.fileExists(atPath: u.path) {
// Open the Finder to the application support folder.
NSWorkspace.shared.activateFileViewerSelecting([u])
} else {
let alert = NSAlert()
alert.window.title = "Attention"
alert.messageText = "Application support folder does not exist"
alert.informativeText = "You probably haven't created any custom themes or style sheets yet."
alert.addButton(withTitle: "Close")
alert.alertStyle = .informational
alert.runModal()
}
})
}
@IBAction func selectSettingsFile(_ sender: Any) {
SCSHWrapper.service?.getSettingsURL(reply: { (url) in
if let u = url, FileManager.default.fileExists(atPath: u.path) {
// Open the Finder to the settings file.
NSWorkspace.shared.activateFileViewerSelecting([u])
} else {
let alert = NSAlert()
alert.window.title = "Attention"
alert.messageText = "Settings not found"
alert.informativeText = "You probably haven't customize the standard settings."
alert.addButton(withTitle: "Close")
alert.alertStyle = .informational
alert.runModal()
}
})
}
}