-
-
Notifications
You must be signed in to change notification settings - Fork 433
/
Document.swift
1313 lines (942 loc) · 49.8 KB
/
Document.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Document.swift
//
// CotEditor
// https://coteditor.com
//
// Created by nakamuxu on 2004-12-08.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2019 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
private struct SerializationKey {
static let readingEncoding = "readingEncoding"
static let syntaxStyle = "syntaxStyle"
static let autosaveIdentifier = "autosaveIdentifier"
static let isVerticalText = "isVerticalText"
static let isTransient = "isTransient"
}
private let uniqueFileIDLength = 13
// MARK: -
final class Document: NSDocument, AdditionalDocumentPreparing, EncodingHolder {
// MARK: Notification Names
static let didChangeEncodingNotification = Notification.Name("DocumentDidChangeEncoding")
static let didChangeLineEndingNotification = Notification.Name("DocumentDidChangeLineEnding")
static let didChangeSyntaxStyleNotification = Notification.Name("DocumentDidChangeSyntaxStyle")
// MARK: Public Properties
var isVerticalText = false
var isTransient = false // untitled & empty document that was created automatically
// MARK: Readonly Properties
let textStorage = NSTextStorage()
let syntaxParser: SyntaxParser
private(set) var encoding: String.Encoding
private(set) var hasUTF8BOM = false
private(set) var lineEnding: LineEnding
private(set) var fileAttributes: [FileAttributeKey: Any]?
private(set) lazy var selection = TextSelection(document: self)
private(set) lazy var analyzer = DocumentAnalyzer(document: self)
private(set) lazy var incompatibleCharacterScanner = IncompatibleCharacterScanner(document: self)
// MARK: Private Properties
private lazy var printPanelAccessoryController = PrintPanelAccessoryController.instantiate(storyboard: "PrintPanelAccessory")
private lazy var savePanelAccessoryController = NSViewController.instantiate(storyboard: "SaveDocumentAccessory")
private var readingEncoding: String.Encoding // encoding to read document file
private var isExternalUpdateAlertShown = false
private var fileData: Data?
private var shouldSaveXattr = true
private var autosaveIdentifier: String
@objc private dynamic var isExecutable = false // bind in save panel accessory view
private var lastSavedData: Data? // temporal data used only within saving process
// MARK: -
// MARK: Lifecycle
override init() {
// [caution] This method may be called from a background thread due to concurrent-opening.
let uuid = UUID().uuidString
self.autosaveIdentifier = String(uuid.prefix(uniqueFileIDLength))
let encoding = String.Encoding(rawValue: UserDefaults.standard[.encodingInNew])
self.encoding = String.availableStringEncodings.contains(encoding) ? encoding : .utf8
if self.encoding == .utf8 {
self.hasUTF8BOM = UserDefaults.standard[.saveUTF8BOM]
}
self.lineEnding = LineEnding(index: UserDefaults.standard[.lineEndCharCode]) ?? .lf
self.syntaxParser = SyntaxParser(textStorage: self.textStorage)
self.syntaxParser.style = SyntaxManager.shared.setting(name: UserDefaults.standard[.syntaxStyle]!) ?? SyntaxStyle()
// use the encoding user selected in open panel, if exists
if let accessorySelectedEncoding = (DocumentController.shared as! DocumentController).accessorySelectedEncoding {
self.readingEncoding = accessorySelectedEncoding
} else {
self.readingEncoding = String.Encoding(rawValue: UserDefaults.standard[.encodingInOpen])
}
super.init()
self.hasUndoManager = true
// observe sytnax style update
NotificationCenter.default.addObserver(self, selector: #selector(syntaxDidUpdate), name: didUpdateSettingNotification, object: SyntaxManager.shared)
}
/// store internal document state
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(Int(self.encoding.rawValue), forKey: SerializationKey.readingEncoding)
coder.encode(self.autosaveIdentifier, forKey: SerializationKey.autosaveIdentifier)
coder.encode(self.syntaxParser.style.name, forKey: SerializationKey.syntaxStyle)
coder.encode(self.isVerticalText, forKey: SerializationKey.isVerticalText)
coder.encode(self.isTransient, forKey: SerializationKey.isTransient)
super.encodeRestorableState(with: coder)
}
/// resume UI state
override func restoreState(with coder: NSCoder) {
super.restoreState(with: coder)
if coder.containsValue(forKey: SerializationKey.readingEncoding) {
let encoding = String.Encoding(rawValue: UInt(coder.decodeInteger(forKey: SerializationKey.readingEncoding)))
if String.availableStringEncodings.contains(encoding) {
self.readingEncoding = encoding
}
}
if let identifier = coder.decodeObject(forKey: SerializationKey.autosaveIdentifier) as? String {
self.autosaveIdentifier = identifier
}
if let styleName = coder.decodeObject(forKey: SerializationKey.syntaxStyle) as? String {
if self.syntaxParser.style.name != styleName {
self.setSyntaxStyle(name: styleName)
}
}
if coder.containsValue(forKey: SerializationKey.isVerticalText) {
self.isVerticalText = coder.decodeBool(forKey: SerializationKey.isVerticalText)
}
if coder.containsValue(forKey: SerializationKey.isTransient) {
self.isTransient = coder.decodeBool(forKey: SerializationKey.isTransient)
}
}
// MARK: Document Methods
/// enable Autosave in Place
override class var autosavesInPlace: Bool {
// avoid changing the value while the application is running
struct InitialValue { static let autosavesInPlace = UserDefaults.standard[.enablesAutosaveInPlace] }
return InitialValue.autosavesInPlace
}
/// whether documents use iCloud storage
override class var usesUbiquitousStorage: Bool {
// pretend as if iCloud storage is disabled to let system give up opening the open panel on launch (2018-02 macOS 10.13)
if NSAppleEventManager.shared().isOpenEvent {
guard UserDefaults.standard[.noDocumentOnLaunchBehavior] == .openPanel else { return false }
}
return super.usesUbiquitousStorage
}
/// can read document on a background thread?
override class func canConcurrentlyReadDocuments(ofType: String) -> Bool {
return true
}
/// enable asynchronous saving
override func canAsynchronouslyWrite(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) -> Bool {
// -> Async-saving may cause an occasional crash. (2017-10 macOS 10.13 SDK)
return UserDefaults.standard.bool(forKey: "enablesAsynchronousSaving")
}
/// make custom windowControllers
override func makeWindowControllers() {
defer {
self.applyContentToWindow()
}
// a transient document has already one
guard self.windowControllers.isEmpty else { return }
let windowController = NSWindowController.instantiate(storyboard: "DocumentWindow")
self.addWindowController(windowController)
}
/// URL of document file
override var fileURL: URL? {
didSet {
guard self.fileURL != oldValue else { return }
DispatchQueue.main.async { [weak self] in
self?.analyzer.invalidateFileInfo()
}
}
}
/// return preferred file extension corresponding to the current syntax style
override func fileNameExtension(forType typeName: String, saveOperation: NSDocument.SaveOperationType) -> String? {
if let pathExtension = self.fileURL?.pathExtension {
return pathExtension
}
return self.syntaxParser.style.extensions.first
}
/// revert to saved file contents
override func revert(toContentsOf url: URL, ofType typeName: String) throws {
assert(Thread.isMainThread)
// once force-close all sheets
// -> Presented errors will be displayed again after the revert automatically (since OS X 10.10).
self.windowForSheet?.sheets.forEach { $0.close() }
// store current selections
let lastString = self.textStorage.string
let editorStates = self.textStorage.layoutManagers
.compactMap { $0.textViewForBeginningOfSelection }
.map { (textView: $0, ranges: $0.selectedRanges as! [NSRange]) }
try super.revert(toContentsOf: url, ofType: typeName)
// apply to UI
self.applyContentToWindow()
// select previous ranges again
// -> Taking performance issue into consideration,
// the selection ranges will be adjusted only when the content size is enough small.
let string = self.textStorage.string
let maxLength = 50_000 // takes ca. 1.3 sec. with MacBook Pro 13-inch late 2016 (3.3 GHz)
let considersDiff = min(lastString.count, string.count) < maxLength
for state in editorStates {
state.textView.selectedRanges = {
guard considersDiff else {
// just cut extra ranges off
return state.ranges
.map { $0.intersection(string.nsRange) ?? NSRange(location: string.nsRange.upperBound, length: 0) }
.map { $0 as NSValue }
}
return string.equivalentRanges(to: state.ranges, in: lastString) as [NSValue]
}()
}
}
/// setup duplicated document
override func duplicate() throws -> NSDocument {
let document = try super.duplicate() as! Document
document.setSyntaxStyle(name: self.syntaxParser.style.name)
document.lineEnding = self.lineEnding
document.encoding = self.encoding
document.hasUTF8BOM = self.hasUTF8BOM
document.isVerticalText = self.isVerticalText
document.isExecutable = self.isExecutable
return document
}
/// load document from file and return whether it succeeded
override func read(from url: URL, ofType typeName: String) throws {
// [caution] This method may be called from a background thread due to concurrent-opening.
let file = try DocumentFile(fileURL: url, readingEncoding: self.readingEncoding) // FILE_READ
// store file data in order to check the file content identity in `presentedItemDidChange()`
self.fileData = file.data
// use file attributes only if `fileURL` exists
// -> The passed-in `url` in this method can point to a file that isn't the real document file,
// for example on resuming an unsaved document.
if self.fileURL != nil {
self.fileAttributes = file.attributes
let permissions = FilePermissions(mask: (file.attributes[.posixPermissions] as? UInt16) ?? 0)
self.isExecutable = permissions.user.contains(.execute)
}
// do not save `com.apple.TextEncoding` extended attribute if it doesn't exists
self.shouldSaveXattr = (file.xattrEncoding != nil)
// set text orientation state
// -> Ignore if no metadata found to avoid restoring to the horizontal layout while editing unwantedly.
if UserDefaults.standard[.savesTextOrientation], file.isVerticalText {
self.isVerticalText = true
}
// set read values
self.encoding = file.encoding
self.hasUTF8BOM = file.hasUTF8BOM
self.lineEnding = file.lineEnding ?? self.lineEnding // keep default if no line endings are found
// notify
DispatchQueue.main.async { [weak self] in
NotificationCenter.default.post(name: Document.didChangeEncodingNotification, object: self)
NotificationCenter.default.post(name: Document.didChangeLineEndingNotification, object: self)
}
// standardize line endings to LF
// -> Line endings replacemement by other text modifications is processed in
// `EditorTextViewController.textView(_:shouldChangeTextInRange:replacementString:)`.
let string = file.string.replacingLineEndings(with: .lf)
// update textStorage
assert(self.textStorage.layoutManagers.isEmpty || Thread.isMainThread)
self.textStorage.replaceCharacters(in: self.textStorage.string.nsRange, with: string)
// determine syntax style (only on the first file open)
if self.windowForSheet == nil {
let styleName = SyntaxManager.shared.settingName(documentFileName: url.lastPathComponent, content: string)
self.setSyntaxStyle(name: styleName, isInitial: true)
}
}
/// create Data object to save
override func data(ofType typeName: String) throws -> Data {
// [caution] This method may be called from a background thread due to async-saving.
let encoding = self.encoding
let needsUTF8BOM = (encoding == .utf8) && self.hasUTF8BOM
// convert Yen sign in consideration of the current encoding
let string = self.string.convertingYenSign(for: encoding)
// unblock the user interface, since fetching current document state has been done here
self.unblockUserInteraction()
// get data from string to save
guard var data = string.data(using: encoding, allowLossyConversion: true) else {
throw CocoaError.error(.fileWriteInapplicableStringEncoding,
userInfo: [NSStringEncodingErrorKey: encoding.rawValue])
}
// add UTF-8 BOM if needed
if needsUTF8BOM {
data = data.addingUTF8BOM
}
// keep to swap later with `fileData`, but only when succeed
self.lastSavedData = data
return data
}
/// save or autosave the document contents to a file
override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, completionHandler: @escaping (Error?) -> Void) {
// trim trailing whitespace if needed
assert(Thread.isMainThread)
if UserDefaults.standard[.trimsTrailingWhitespaceOnSave] {
let trimsWhitespaceOnlyLines = UserDefaults.standard[.trimsWhitespaceOnlyLines]
let keepsEditingPoint = (saveOperation == .autosaveInPlaceOperation || saveOperation == .autosaveElsewhereOperation)
let textView = self.textStorage.layoutManagers.lazy
.compactMap { $0.textViewForBeginningOfSelection }
.first { !keepsEditingPoint || $0.window?.firstResponder == $0 }
textView?.trimTrailingWhitespace(ignoresEmptyLines: !trimsWhitespaceOnlyLines,
keepingEditingPoint: keepsEditingPoint)
}
// break undo grouping
for layoutManager in self.textStorage.layoutManagers {
layoutManager.textViewForBeginningOfSelection?.breakUndoCoalescing()
}
// modify place to create backup file
// -> save backup file always in `~/Library/Autosaved Information/` directory
// (The default backup URL is the same directory as the fileURL.)
let newURL: URL = {
guard
saveOperation == .autosaveElsewhereOperation,
let fileURL = self.fileURL
else { return url }
let autosaveDirectoryURL = (DocumentController.shared as! DocumentController).autosaveDirectoryURL
let baseFileName = fileURL.deletingPathExtension().lastPathComponent
.replacingOccurrences(of: ".", with: "", options: .anchored) // avoid file to be hidden
// append a unique string to avoid overwriting another backup file with the same file name.
let fileName = baseFileName + " (" + self.autosaveIdentifier + ")"
return autosaveDirectoryURL.appendingPathComponent(fileName).appendingPathExtension(fileURL.pathExtension)
}()
super.save(to: newURL, ofType: typeName, for: saveOperation) { [unowned self] (error: Error?) in
defer {
completionHandler(error)
}
guard error == nil else { return }
assert(Thread.isMainThread)
// apply syntax style that is inferred from the file name or the shebang
if saveOperation == .saveAsOperation {
let fileName = url.lastPathComponent
if let styleName = SyntaxManager.shared.settingName(documentFileName: fileName)
?? SyntaxManager.shared.settingName(documentContent: self.string)
// -> Due to the async-saving, self.string can be changed from the actual saved contents.
// But we don't care about that.
{
self.setSyntaxStyle(name: styleName)
}
}
switch saveOperation {
case .saveOperation, .saveAsOperation, .saveToOperation:
self.analyzer.invalidateFileInfo()
ScriptManager.shared.dispatchEvent(documentSaved: self)
case .autosaveAsOperation, .autosaveElsewhereOperation, .autosaveInPlaceOperation: break
}
}
}
/// write file metadata to the new file (invoked in file saving process)
override func writeSafely(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) throws {
// [caution] This method may be called from a background thread due to async-saving.
// store current state here, since the main thread will already be unblocked after `data(ofType:)`
let encoding = self.encoding
let isVerticalText = self.isVerticalText
try super.writeSafely(to: url, ofType: typeName, for: saveOperation)
// save document state to the extended file attributes
if self.shouldSaveXattr {
try url.setExtendedAttribute(data: encoding.xattrEncodingData, for: FileExtendedAttributeName.encoding)
}
if UserDefaults.standard[.savesTextOrientation] {
try url.setExtendedAttribute(data: isVerticalText ? Data(bytes: [1]) : nil, for: FileExtendedAttributeName.verticalText)
}
if saveOperation != .autosaveElsewhereOperation {
// get the latest file attributes
self.fileAttributes = try FileManager.default.attributesOfItem(atPath: url.path) // FILE_READ
// store file data in order to check the file content identity in `presentedItemDidChange()`
self.fileData = self.lastSavedData
// store file encoding for revert
self.readingEncoding = encoding
}
}
/// customize document's file attributes
override func fileAttributesToWrite(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws -> [String: Any] {
// [caution] This method may be called from a background thread due to async-saving.
var attributes = try super.fileAttributesToWrite(to: url, ofType: typeName, for: saveOperation, originalContentsURL: absoluteOriginalContentsURL)
// give the execute permission if user requested
if self.isExecutable, (saveOperation == .saveOperation || saveOperation == .saveAsOperation) {
let permissions: UInt16 = (self.fileAttributes?[.posixPermissions] as? UInt16) ?? 0o644 // ???: Is the default permission really always 644?
attributes[FileAttributeKey.posixPermissions.rawValue] = permissions | S_IXUSR
}
return attributes
}
/// avoid let system add the standard save panel accessory (pop-up menu for document type change)
override var shouldRunSavePanelWithAccessoryView: Bool {
return false
}
/// prepare save panel
override func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool {
// disable hide extension checkbox
// -> Because it doesn't work.
savePanel.isExtensionHidden = false
savePanel.canSelectHiddenExtension = false
// set default file extension in a hacky way (2018-02 on macOS 10.13 SDK for macOS 10.11 - 10.13)
savePanel.allowedFileTypes = nil // nil allows setting any extension
if let fileType = self.fileType,
let pathExtension = self.fileNameExtension(forType: fileType, saveOperation: .saveOperation) {
// set once allowedFileTypes, so that initial filename selection excludes the file extension
savePanel.allowedFileTypes = [pathExtension]
// disable immediately in the next runloop to allow set other extensions
DispatchQueue.main.async {
savePanel.allowedFileTypes = nil
}
}
// set accessory view
self.savePanelAccessoryController = self.savePanelAccessoryController.storyboard!.instantiateInitialController() as! NSViewController
self.savePanelAccessoryController.representedObject = self
savePanel.accessoryView = self.savePanelAccessoryController.view
return super.prepareSavePanel(savePanel)
}
/// display dialogs about save before closing document
override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
var shouldClose = false
// disable save dialog if content is empty and not saved explicitly
if (self.isDraft || self.fileURL == nil), self.textStorage.string.isEmpty {
self.updateChangeCount(.changeCleared)
// remove auto-saved file if exists
if let url = self.fileURL {
var deletionError: NSError?
NSFileCoordinator(filePresenter: self).coordinate(writingItemAt: url, options: .forDeleting, error: &deletionError) { (url) in // FILE_READ
do {
try FileManager.default.removeItem(at: url)
} catch {
// do nothing and let super's `.canClose(withDelegate:shouldClose:contextInfo:)` handle the stuff
Swift.print("Failed empty file deletion: \(error)")
return
}
shouldClose = true
self.fileURL = nil
}
}
}
// manually call delegate but only when you wanna modify `shouldClose` flag
guard
shouldClose,
let selector = shouldCloseSelector,
let context = contextInfo,
let object = delegate as? NSObject,
let objcClass = objc_getClass(object.className) as? AnyClass,
let method = class_getMethodImplementation(objcClass, selector)
else {
return super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
}
typealias Signature = @convention(c) (NSObject, Selector, NSDocument, Bool, UnsafeMutableRawPointer) -> Void
let function = unsafeBitCast(method, to: Signature.self)
function(object, selector, self, shouldClose, context)
}
/// close document
override func close() {
self.syntaxParser.invalidateCurrentParse()
super.close()
}
/// setup print setting including print panel
override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey: Any]) throws -> NSPrintOperation {
let viewController = self.viewController!
// create printView
let printView = PrintTextView()
printView.setLayoutOrientation(viewController.verticalLayoutOrientation ? .vertical : .horizontal)
printView.documentName = self.displayName
printView.filePath = self.fileURL?.path
printView.syntaxParser.style = self.syntaxParser.style
printView.documentShowsInvisibles = viewController.showsInvisibles
printView.documentShowsLineNumber = viewController.showsLineNumber
printView.baseWritingDirection = viewController.writingDirection
// set font for printing
printView.font = {
if UserDefaults.standard[.setPrintFont] { // == use printing font
return NSFont(name: UserDefaults.standard[.printFontName]!,
size: UserDefaults.standard[.printFontSize])
}
return viewController.font
}()
// [caution] need to set string after setting other properties
printView.string = self.textStorage.string
// create print operation
let printOperation = NSPrintOperation(view: printView, printInfo: self.printInfo)
printOperation.printInfo.dictionary().addEntries(from: printSettings)
printOperation.showsProgressPanel = true
printOperation.canSpawnSeparateThread = true // display print progress panel as a sheet
// setup print panel
printOperation.printPanel.addAccessoryController(self.printPanelAccessoryController)
printOperation.printPanel.options.formUnion([.showsPaperSize, .showsOrientation, .showsScaling])
return printOperation
}
/// printing information associated with the document
override var printInfo: NSPrintInfo {
get {
let printInfo = super.printInfo
printInfo.horizontalPagination = .fit
printInfo.isHorizontallyCentered = false
printInfo.isVerticallyCentered = false
printInfo.leftMargin = PrintTextView.horizontalPrintMargin
printInfo.rightMargin = PrintTextView.horizontalPrintMargin
printInfo.topMargin = PrintTextView.verticalPrintMargin
printInfo.bottomMargin = PrintTextView.verticalPrintMargin
printInfo.dictionary()[NSPrintInfo.AttributeKey.headerAndFooter] = true
return printInfo
}
set {
super.printInfo = newValue
}
}
/// document was updated
override func updateChangeCount(_ change: NSDocument.ChangeType) {
self.isTransient = false
super.updateChangeCount(change)
}
// MARK: Protocols
/// file has been modified by an external process
override func presentedItemDidChange() {
// [caution] This method can be called from any thread.
// [caution] DO NOT invoke `super.presentedItemDidChange()` that reverts document automatically if autosavesInPlace is enable.
// super.presentedItemDidChange()
let option = UserDefaults.standard[.documentConflictOption]
guard
option != .ignore,
!self.isExternalUpdateAlertShown, // don't check twice if already notified
let fileURL = self.fileURL
else { return }
var didChange = false
var fileModificationDate: Date?
NSFileCoordinator(filePresenter: self).coordinate(readingItemAt: fileURL, options: .withoutChanges, error: nil) { (newURL) in // FILE_READ
// ignore if file's modificationDate is the same as document's modificationDate
fileModificationDate = (try? FileManager.default.attributesOfItem(atPath: newURL.path))?[.modificationDate] as? Date
guard fileModificationDate != self.fileModificationDate else { return }
// check if file contents was changed from the stored file data
let data = try? Data(contentsOf: newURL)
didChange = (data != self.fileData)
}
guard didChange else {
// update the document's fileModificationDate for a workaround (2014-03 by 1024jp)
// If not, an alert shows up when user saves the file.
DispatchQueue.main.async { [weak self] in
guard
let lastModificationDate = self?.fileModificationDate,
let fileModificationDate = fileModificationDate,
lastModificationDate < fileModificationDate
else { return }
self?.fileModificationDate = fileModificationDate
}
return
}
// notify about external file update
DispatchQueue.main.async { [weak self] in
switch option {
case .ignore:
assertionFailure()
case .notify:
self?.showUpdatedByExternalProcessAlert()
case .revert:
self?.revertWithoutAsking()
}
}
}
/// apply current state to menu items
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(changeEncoding(_:))?:
let encodingTag = self.hasUTF8BOM ? -Int(self.encoding.rawValue) : Int(self.encoding.rawValue)
menuItem.state = (menuItem.tag == encodingTag) ? .on : .off
case #selector(changeLineEnding(_:))?:
menuItem.state = (LineEnding(index: menuItem.tag) == self.lineEnding) ? .on : .off
case #selector(changeSyntaxStyle(_:))?:
let name = self.syntaxParser.style.name
menuItem.state = (menuItem.title == name) ? .on : .off
default: break
}
return super.validateMenuItem(menuItem)
}
/// open existing document file (alternative methods for `init(contentsOf:ofType:)`)
func didMakeDocumentForExisitingFile(url: URL) {
// [caution] This method may be called from a background thread due to concurrent-opening.
// This method won't be invoked on Resume. (2015-01-26)
ScriptManager.shared.dispatchEvent(documentOpened: self)
}
// MARK: Notifications
/// set a flag of syntax highlight update if corresponded style has been updated
@objc private func syntaxDidUpdate(_ notification: Notification) {
guard
let oldName = notification.userInfo?[Notification.UserInfoKey.old] as? String,
oldName == self.syntaxParser.style.name else { return }
let newName = (notification.userInfo?[Notification.UserInfoKey.new] as? String) ?? BundledStyleName.none
self.setSyntaxStyle(name: newName)
}
// MARK: Public Methods
/// Return whole string in the current text storage which document's line endings are already applied to.
///
/// - Note: The internal text storage has always LF for its line ending.
var string: String {
let editorString = self.textStorage.string.immutable // line ending is always LF
if self.lineEnding == .lf {
return editorString
}
return editorString.replacingLineEndings(with: self.lineEnding)
}
/// return document window's editor wrapper
var viewController: DocumentViewController? {
return (self.windowControllers.first?.contentViewController as? WindowContentViewController)?.documentViewController
}
/// reinterpret file with the desired encoding
func reinterpret(encoding: String.Encoding) throws {
guard let fileURL = self.fileURL else {
throw ReinterpretationError(kind: .noFile, encoding: encoding)
}
// do nothing if given encoding is the same as current one
if encoding == self.encoding { return }
// reinterpret
self.readingEncoding = encoding
do {
try self.revert(toContentsOf: fileURL, ofType: self.fileType!)
} catch {
self.readingEncoding = self.encoding
throw ReinterpretationError(kind: .reinterpretationFailed(fileURL: fileURL), encoding: encoding)
}
}
/// change file encoding registering process to the undo manager
///
/// - Throws: `EncodingError` (Kind.lossyConversion) can be thorwn but only if `lossy` flag is `true`.
func changeEncoding(to encoding: String.Encoding, withUTF8BOM: Bool, lossy: Bool) throws {
assert(Thread.isMainThread)
guard encoding != self.encoding || withUTF8BOM != self.hasUTF8BOM else { return }
// check if conversion is lossy
guard lossy || self.string.canBeConverted(to: encoding) else {
throw EncodingError(kind: .lossyConversion, encoding: encoding, withUTF8BOM: withUTF8BOM, attempter: self)
}
// register undo
if let undoManager = self.undoManager {
let encodingName = String.localizedName(of: encoding, withUTF8BOM: withUTF8BOM)
undoManager.registerUndo(withTarget: self) { [currentEncoding = self.encoding, currentHasUTF8BOM = self.hasUTF8BOM] target in
try? target.changeEncoding(to: currentEncoding, withUTF8BOM: currentHasUTF8BOM, lossy: lossy)
}
undoManager.setActionName(String(format: "Encoding to “%@”".localized, encodingName))
}
// update encoding
self.encoding = encoding
self.hasUTF8BOM = withUTF8BOM
// notify
NotificationCenter.default.post(name: Document.didChangeEncodingNotification, object: self)
// update UI
self.incompatibleCharacterScanner.scan()
self.analyzer.invalidateModeInfo()
}
/// change line endings registering process to the undo manager
func changeLineEnding(to lineEnding: LineEnding) {
assert(Thread.isMainThread)
guard lineEnding != self.lineEnding else { return }
// register undo
if let undoManager = self.undoManager {
undoManager.registerUndo(withTarget: self) { [currentLineEnding = self.lineEnding] target in
target.changeLineEnding(to: currentLineEnding)
}
undoManager.setActionName(String(format: "Line Endings to “%@”".localized, lineEnding.name))
}
// update line ending
self.lineEnding = lineEnding
// notify
NotificationCenter.default.post(name: Document.didChangeLineEndingNotification, object: self)
// update UI
self.analyzer.invalidateModeInfo()
self.analyzer.invalidateEditorInfo()
}
/// change syntax style with style name
func setSyntaxStyle(name: String, isInitial: Bool = false) {
guard
let syntaxStyle = SyntaxManager.shared.setting(name: name),
syntaxStyle != self.syntaxParser.style
else { return }
// update
self.syntaxParser.invalidateCurrentParse()
self.syntaxParser.style = syntaxStyle
// skip notification when initial style was set on file open
// to avoid redundant highlight parse due to async notification.
guard !isInitial else { return }
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
NotificationCenter.default.post(name: Document.didChangeSyntaxStyleNotification, object: self)
}
}
// MARK: Action Messages
/// save document
@IBAction override func save(_ sender: Any?) {
self.askSavingSafety { (continuesSaving: Bool) in
guard continuesSaving else { return }
super.save(sender)
}
}
/// save document with new name
@IBAction override func saveAs(_ sender: Any?) {
self.askSavingSafety { (continuesSaving: Bool) in
guard continuesSaving else { return }
super.saveAs(sender)
}
}
/// change line ending with sender's tag
@IBAction func changeLineEnding(_ sender: NSMenuItem) {
guard let lineEnding = LineEnding(index: sender.tag) else { return }
self.changeLineEnding(to: lineEnding)
}
/// change document file encoding
@IBAction func changeEncoding(_ sender: NSMenuItem) {
let encoding = String.Encoding(rawValue: UInt(abs(sender.tag)))
let withUTF8BOM = (sender.tag == -Int(String.Encoding.utf8.rawValue))
guard encoding != self.encoding || withUTF8BOM != self.hasUTF8BOM else { return }
// change encoding interactively
self.performActivity(withSynchronousWaiting: true) { [unowned self] (activityCompletionHandler) in
let completionHandler = { (didChange: Bool) in
if !didChange {
// reset toolbar selection for in case if the operation was invoked from the toolbar popup
NotificationCenter.default.post(name: Document.didChangeEncodingNotification, object: self)
}
activityCompletionHandler()
}
// change encoding immediately if there is nothing to worry about
if self.fileURL == nil ||
self.textStorage.string.isEmpty ||
(encoding == .utf8 && self.encoding == .utf8) {
do {
try self.changeEncoding(to: encoding, withUTF8BOM: withUTF8BOM, lossy: false)
completionHandler(true)
} catch {
self.presentErrorAsSheet(error, recoveryHandler: completionHandler)
}
return
}
// ask whether just change the encoding or reinterpret docuemnt file
let encodingName = String.localizedName(of: encoding, withUTF8BOM: withUTF8BOM)
let alert = NSAlert()
alert.messageText = "File encoding".localized
alert.informativeText = String(format: "Do you want to convert or reinterpret this document using “%@”?".localized, encodingName)
alert.addButton(withTitle: "Convert".localized)
alert.addButton(withTitle: "Reinterpret".localized)
alert.addButton(withTitle: "Cancel".localized)
let documentWindow = self.windowForSheet!
alert.beginSheetModal(for: documentWindow) { [unowned self] (returnCode: NSApplication.ModalResponse) in
switch returnCode {
case .alertFirstButtonReturn: // = Convert
do {
try self.changeEncoding(to: encoding, withUTF8BOM: withUTF8BOM, lossy: false)