-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathSCSHXPCService.swift
527 lines (450 loc) · 23.6 KB
/
SCSHXPCService.swift
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//
// SCSHXPCService.swift
// SCSHXPCService
//
// 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 Foundation
import OSLog
// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
class SCSHXPCService: SCSHBaseXPCService, SCSHXPCServiceProtocol {
// MARK: - Class properties
/// Return the folder for the application support files.
static var preferencesUrl: URL? {
return FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first?.appendingPathComponent("Preferences")
}
// MARK: - Initializers
override init() {
if let pref = SCSHXPCService.preferencesUrl {
/// Old settings name.
let url_old = pref.appendingPathComponent("org.sbarex.SourceCodeSyntaxHightlight.plist")
/// New settings name.
let url_new = pref.appendingPathComponent(type(of: self).XPCDomain + ".plist")
if FileManager.default.fileExists(atPath: url_old.path) && !FileManager.default.fileExists(atPath: url_new.path) {
// Rename old preferences to new name (typo fix).
try? FileManager.default.moveItem(at: url_old, to: url_new)
}
}
if let baseDir = SCSHXPCService.applicationSupportUrl, !FileManager.default.fileExists(atPath: baseDir.path) {
do {
try FileManager.default.createDirectory(at: baseDir, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
super.init()
migrate(settings: settings)
}
/// Migrate the stored settings to the current format.
@discardableResult
internal func migrate(settings: Settings) -> Bool {
guard settings.version < Settings.version else {
return false
}
let defaults = UserDefaults.standard
var defaultsDomain = defaults.persistentDomain(forName: type(of: self).XPCDomain) ?? [:]
if settings.version <= 2.1 {
for (_, uti_settings) in settings.utiSettings {
guard !uti_settings.isPreprocessorDefined, !uti_settings.preprocessor.isEmpty else {
continue
}
if uti_settings.preprocessor.range(of: #"(?<=\s|^)\$targetHL(?=\s|$)"#, options: .regularExpression, range: nil, locale: nil) == nil {
// Append the target placeholder at the end of the preprocessor command.
uti_settings.preprocessor = uti_settings.preprocessor.appending(" $targetHL")
}
}
}
if settings.version <= 2.3 && defaultsDomain[SettingsBase.Key.plainSettings] == nil {
settings.removeAllPlainSettings()
if #available(macOS 12.0, *) {
settings.insertPlainSettings(settings: PlainSettings(patternFile: "makefile", patternMime: "", isRegExp: false, isCaseInsensitive: true, UTI: "public.make-source", syntax: "makefile"))
} else {
settings.insertPlainSettings(settings: PlainSettings(patternFile: "makefile", patternMime: "", isRegExp: false, isCaseInsensitive: true, UTI: "org.n8gray.makefile", syntax: "makefile"))
}
}
if let c = defaultsDomain["rtf-background-color-light"] as? String {
settings.lightBackgroundColor = c
defaultsDomain.removeValue(forKey: "rtf-background-color-light")
}
if let c = defaultsDomain["rtf-background-color-dark"] as? String {
settings.darkBackgroundColor = c
defaultsDomain.removeValue(forKey: "rtf-background-color-dark")
}
if settings.version <= 2.2 {
defaultsDomain.removeValue(forKey: "highlight") // remove custom highlight path.
}
// "commands-toolbar" is not yet used.
defaultsDomain.removeValue(forKey: "commands-toolbar")
// "theme-light-is16" and "theme-dark-is16" are replaced by "base16/" prefix on theme name.
let migrateBase16 = { (settings: SettingsBase, defaultsDomain: inout [String: Any], UTI: String) -> Bool in
var changed = false
if let lightThemeIsBase16 = (UTI.isEmpty ? defaultsDomain : defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]![jsonDict: UTI]!)["theme-light-is16"] as? Bool {
if lightThemeIsBase16 && settings.isLightThemeNameDefined && !settings.lightThemeName.hasPrefix("base16") {
settings.lightThemeName = "base16/\(settings.lightThemeName)"
}
if UTI.isEmpty {
defaultsDomain.removeValue(forKey: "theme-light-is16")
} else {
defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]?[jsonDict: UTI]?.removeValue(forKey: "theme-light-is16")
}
changed = true
}
if let darkThemeIsBase16 = (UTI.isEmpty ? defaultsDomain : defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]![jsonDict: UTI]!)["theme-dark-is16"] as? Bool {
if darkThemeIsBase16 && settings.isDarkThemeNameDefined && !settings.darkThemeName.hasPrefix("base16") {
settings.darkThemeName = "base16/\(settings.darkThemeName)"
}
if UTI.isEmpty {
defaultsDomain.removeValue(forKey: "theme-dark-is16")
} else {
defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]?[jsonDict: UTI]?.removeValue(forKey: "theme-dark-is16")
}
changed = true
}
return changed
}
let CSSFolder = type(of: self).getCustomStylesUrl(createIfMissing: true)
// Custom CSS are saved on external files.
let migrateCSS = { (settings: SettingsCSS, defaultsDomain: inout [String: Any], UTI: String, CSSFolder: URL?) -> Bool in
guard let CSSFolder = CSSFolder else {
return false
}
var changed = false
if let customCSS = (!UTI.isEmpty ? defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]![jsonDict: UTI]! : defaultsDomain)["css"] as? String {
settings.css = customCSS
settings.isCSSDefined = !customCSS.isEmpty
do {
try settings.exportCSSFile(toFolder: CSSFolder)
if UTI.isEmpty {
defaultsDomain.removeValue(forKey: "css")
} else {
defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]?[jsonDict: UTI]?.removeValue(forKey: "css")
}
changed = true
} catch {
}
}
return changed
}
_ = migrateBase16(settings, &defaultsDomain, "")
_ = migrateCSS(settings, &defaultsDomain, "", CSSFolder)
if let custom_formats = defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings] {
for (uti, _) in custom_formats {
var utiDefaultsDomain = (defaultsDomain[SettingsBase.Key.customizedUTISettings] as! [String: [String: Any]])[uti]!
if let s = settings.utiSettings[uti] {
_ = migrateBase16(s, &defaultsDomain, uti)
_ = migrateCSS(s, &defaultsDomain, uti, CSSFolder)
if settings.version <= 2.1, let preprocessor = utiDefaultsDomain["preprocessor"] as? String, !preprocessor.isEmpty, preprocessor.range(of: #"(?<=\s|^)\$targetHL(?=\s|$)"#, options: .regularExpression, range: nil, locale: nil) == nil {
defaultsDomain[customizedTypes: SettingsBase.Key.customizedUTISettings]![uti]!["preprocessor"] = preprocessor.appending(" $targetHL")
}
if let c = defaultsDomain["rtf-background-color-light"] as? String {
s.lightBackgroundColor = c
utiDefaultsDomain.removeValue(forKey: "rtf-background-color-light")
}
if let c = defaultsDomain["rtf-background-color-dark"] as? String {
s.darkBackgroundColor = c
utiDefaultsDomain.removeValue(forKey: "rtf-background-color-dark")
}
}
}
}
// Update settings version.
settings.version = Settings.version
defaultsDomain[SettingsBase.Key.version] = SettingsBase.version
if let jsonSettings = settings.utiSettings["public.json"] {
// Drop the python beautify.
if jsonSettings.preprocessor.contains("python3 -m json.tool") {
jsonSettings.preprocessor = ""
jsonSettings.isPreprocessorDefined = false
}
}
// Store the converted settings.
settings.synchronize(domain: type(of: self).XPCDomain, CSSFolder: type(of: self).getCustomStylesUrl(createIfMissing: true))
return true
}
// MARK: - Colorize
override class func getColorizeArguments(url: URL, custom_settings: SettingsRendering, highlightBin: String, dataDir: String?, extraCss: URL?) throws -> ColorizeArguments {
var r = try super.getColorizeArguments(url: url, custom_settings: custom_settings, highlightBin: highlightBin, dataDir: dataDir, extraCss: extraCss)
if !custom_settings.themeLua.isEmpty {
r.inlineTheme = custom_settings.themeLua
//r.theme = inline_theme.name
//r.backgroundColor = inline_theme.backgroundColor
}
return r
}
/// Colorize a source file returning a formatted rtf code.
/// - parameters
/// - url: Url of source file to format.
/// - overrideSettings: List of settings that override the current preferences. Only elements defined inside the dict are overridden.
func colorize(url: URL, overrideSettings: NSDictionary? = nil, withReply reply: @escaping (Data, NSDictionary, Error?) -> Void) {
var custom_settings: SettingsRendering
// Get current settings.
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: settings.toDictionary())
}
// Override the settings.
custom_settings.override(fromDictionary: overrideSettings as? [String: AnyHashable])
colorize(url: url, settings: custom_settings.toDictionary() as NSDictionary, withReply: reply)
}
/// Colorize a source file returning a formatted rtf code.
/// - parameters:
/// - url: Url of source file to format.
/// - settings: Settings to use, is nil uses the current settings.
/// - data: Data returned by highlight.
/// - error: Error returned by the colorize process.
func colorize(url: URL, settings: NSDictionary? = nil, withReply reply: @escaping (_ data: Data, NSDictionary, _ error: Error?) -> Void) {
var custom_settings: SettingsRendering
if let s = settings as? [String : AnyHashable] {
custom_settings = SettingsRendering(settings: s)
} else {
// Get current settings.
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = self.settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: self.settings.toDictionary())
}
}
let logFile = Self.initLog(forSettings: self.settings)
defer {
Self.doneLog(logFile, forSettings: self.settings)
}
custom_settings.logFile = logFile
do {
var colorize = try ColorizeArguments(highlight: self.getEmbeddedHighlight(), dataDir: self.dataDir, url: url, custom_settings: custom_settings, extraCss: self.getGlobalCSS())
let result = try (type(of: self)).doColorize(url: url, custom_settings: custom_settings, colorize: &colorize, rsrcEsc: self.rsrcEsc, dos2unix: self.bundle.path(forResource: "dos2unix", ofType: nil), logOs: self.log)
reply(result.result.data, result.settings.toDictionary() as NSDictionary, nil)
} catch {
reply(error.localizedDescription.data(using: String.Encoding.utf8)!, custom_settings.toDictionary() as NSDictionary, error)
}
}
/// Colorize a source file returning a formatted html code.
/// - parameters:
/// - url: Url of source file to format.
/// - overrideSettings: List of settings that override the current preferences. Only elements defined inside the dict are overridden.
/// - html: The html output code.l
/// - settings: Render settings.
/// - error: Error returned by the colorize process.
func htmlColorize(url: URL, overrideSettings: NSDictionary? = nil, withReply reply: @escaping (_ html: String, _ settings: NSDictionary, _ error: Error?) -> Void) {
let custom_settings: SettingsRendering
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = self.settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: settings.toDictionary())
}
custom_settings.override(fromDictionary: overrideSettings as? [String: AnyHashable])
htmlColorize(url: url, settings: custom_settings.toDictionary() as NSDictionary, withReply: reply)
}
/// Colorize a source file returning a formatted html code.
/// - parameters:
/// - url: Url of source file to format.
/// - settings: Render settings.
/// - html: The html output code.
/// - settings: Render settings.
/// - error: Error returned by the colorize process.
func htmlColorize(url: URL, settings: NSDictionary? = nil, withReply reply: @escaping (_ html: String, _ settings: NSDictionary, _ error: Error?) -> Void) {
let custom_settings: SettingsRendering
if let s = settings as? [String: AnyHashable] {
custom_settings = SettingsRendering(settings: s)
} else {
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = self.settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: self.settings.toDictionary())
}
}
custom_settings.format = .html
self.colorize(url: url, settings: custom_settings.toDictionary() as NSDictionary) { data, settings, error in
reply(String(data: data, encoding: .utf8) ?? "ERROR", settings, error)
}
}
/// Colorize a source file returning a formatted rtf code.
/// - parameters:
/// - url: Url of source file to format.
/// - overrideSettings: List of settings that override the current preferences. Only elements defined inside the dict are overridden.
/// - rtfData: Data with the rtf code.
/// - settings: Render settings.
/// - error: Error returned by the colorize process.
func rtfColorize(url: URL, overrideSettings: NSDictionary? = nil, withReply reply: @escaping (_ rtfData: Data, _ settings: NSDictionary, _ error: Error?) -> Void) {
let custom_settings: SettingsRendering
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = self.settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: settings.toDictionary())
}
custom_settings.override(fromDictionary: overrideSettings as? [String: AnyHashable])
rtfColorize(url: url, settings: custom_settings.toDictionary() as NSDictionary, withReply: reply)
}
/// Colorize a source file returning a formatted rtf code.
/// - parameters:
/// - url: Url of source file to format.
/// - settings: Render settings.
/// - rtfData: Data with the rtf code.
/// - settings: Render settings.
/// - error: Error returned by the colorize process.
func rtfColorize(url: URL, settings: NSDictionary? = nil, withReply reply: @escaping (_ rtfData: Data, _ settings: NSDictionary, _ error: Error?) -> Void) {
let custom_settings: SettingsRendering
if let s = settings as? [String: AnyHashable] {
custom_settings = SettingsRendering(settings: s)
} else {
if let uti = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier {
custom_settings = self.settings.settings(forUTI: uti)
} else {
custom_settings = SettingsRendering(settings: self.settings.toDictionary())
}
}
custom_settings.format = .rtf
self.colorize(url: url, settings: custom_settings.toDictionary() as NSDictionary, withReply: reply)
}
// MARK: - Themes
func getCustomThemesFolder(createIfMissing: Bool = true, reply: @escaping (URL?)->Void) {
let u = type(of: self).getCustomThemesUrl(createIfMissing: createIfMissing)
reply(u)
}
/// Update the background color after a theme is saved.
/// - parameters:
/// - name: Name of the theme.
/// - reply:
/// - changed: True if the settings are changed.
func updateBGSettingsAfterThemeSaved(name: String, background: String, foreground: String, withReply reply: @escaping (_ changed: Bool) -> Void) {
// Search if any settings use the changed theme.
var changed = false
if settings.lightThemeName == name {
settings.lightBackgroundColor = background
settings.lightForegroundColor = foreground
changed = true
}
if settings.darkThemeName == name {
settings.darkBackgroundColor = background
settings.darkForegroundColor = foreground
changed = true
}
for (_, settings) in self.settings.utiSettings {
if settings.lightThemeName == name {
settings.lightBackgroundColor = background
settings.lightForegroundColor = foreground
changed = true
}
if settings.darkThemeName == name {
settings.darkBackgroundColor = background
settings.darkForegroundColor = foreground
changed = true
}
}
if changed {
// Save the changed settings.
settings.synchronize(domain: type(of: self).XPCDomain, CSSFolder: type(of: self).getCustomStylesUrl(createIfMissing: true))
}
reply(changed)
}
/// Delete a custom theme.
/// Any references of deleted theme in the settings are replaced with a default theme.
/// - parameters:
/// - name: Name of the theme. Is equal to the file name.
/// - reply:
/// - changed: True if the settings are changed.
func updateSettingsAfterThemeDeleted(name: String, withReply reply: @escaping (_ changed: Bool) -> Void) {
// Search if any settings use the deleted theme.
let name = "!\(name)"
var changed = false
if settings.lightThemeName == name {
settings.lightThemeName = "edit-kwrite"
changed = true
}
if settings.darkThemeName == name {
settings.darkThemeName = "edit-vim-dark"
changed = true
}
for (_, settings) in self.settings.utiSettings {
if settings.lightThemeName == name {
settings.lightThemeName = "edit-kwrite"
settings.isLightThemeNameDefined = false
changed = true
}
if settings.darkThemeName == name {
settings.darkThemeName = "edit-vim-dark"
settings.isDarkThemeNameDefined = false
changed = true
}
}
if changed {
// Save the changed settings.
settings.synchronize(domain: type(of: self).XPCDomain, CSSFolder: type(of: self).getCustomStylesUrl(createIfMissing: true))
}
reply(changed)
}
// MARK: - Custom styles
// MARK: - Settings
override internal class func initSettings() -> Settings {
let settings = super.initSettings()
if let dir = self.getCustomStylesUrl(createIfMissing: false) {
settings.populateUTIsCSS(cssFolder: dir)
}
return settings
}
/// Get settings.
func getSettings(reload: Bool, withReply reply: @escaping (NSDictionary) -> Void) {
if reload {
self.settings = type(of: self).initSettings()
}
reply(self.settings.toDictionary() as NSDictionary)
}
/// Set and store the settings.
func setSettings(_ settings: NSDictionary, reply: @escaping (Bool) -> Void) {
if let s = settings as? [String: AnyHashable] {
let new_settings = Settings(settings: s)
let CSSFolder = type(of: self).getCustomStylesUrl(createIfMissing: true)
if let CSSFolder = CSSFolder {
// Delete custom CSS for a not handled uti.
for uti in self.settings.utiSettings.keys.filter({ !new_settings.utiSettings.keys.contains($0) }) {
try? self.settings.utiSettings[uti]?.purgeCSS(inFolder: CSSFolder)
}
try? self.settings.purgeCSS(inFolder: CSSFolder)
}
self.settings = new_settings
reply(new_settings.synchronize(domain: type(of: self).XPCDomain, CSSFolder: CSSFolder))
} else {
reply(false)
}
}
func getSettingsURL(reply: @escaping (_ url: URL?)->Void) {
reply(type(of: self).preferencesUrl?.appendingPathComponent(type(of: self).XPCDomain + ".plist"))
}
/// Return the url of the application support folder that contains themes and custom css styles.
func getApplicationSupport(reply: @escaping (_ url: URL?)->Void) {
reply(type(of: self).applicationSupportUrl)
}
}
fileprivate extension Dictionary {
subscript(jsonDict key: Key) -> [String: Any]? {
get {
return self[key] as? [String: Any]
}
set {
self[key] = newValue as? Value
}
}
subscript(customizedTypes key: Key) -> [String: [String: Any]]? {
get {
return self[key] as? [String: [String: Any]]
}
set {
self[key] = newValue as? Value
}
}
}