Reflect sub-documents’ edited states to the close button

This commit is contained in:
1024jp 2024-05-20 17:30:43 +09:00
parent 77bba583bd
commit fb52f133f0
2 changed files with 29 additions and 0 deletions

View File

@ -47,6 +47,8 @@ import OSLog
private var documents: [Document] = []
private var windowController: DocumentWindowController? { self.windowControllers.first as? DocumentWindowController }
private var documentObserver: (any NSObjectProtocol)?
// MARK: Document Methods
@ -95,6 +97,16 @@ import OSLog
override func makeWindowControllers() {
self.addWindowController(DocumentWindowController(directoryDocument: self))
// observe document updates for the edited marker in the close button
if self.documentObserver == nil {
self.documentObserver = NotificationCenter.default.addObserver(forName: Document.didUpdateChange, object: nil, queue: .main) { [unowned self] _ in
MainActor.assumeIsolated {
let hasEditedDocuments = self.documents.contains { $0.isDocumentEdited }
self.windowController?.setDocumentEdited(hasEditedDocuments)
}
}
}
}
@ -150,6 +162,10 @@ import OSLog
for document in self.documents {
document.close()
}
if let documentObserver {
NotificationCenter.default.removeObserver(documentObserver)
}
}

View File

@ -44,6 +44,8 @@ extension Document: EditorSource {
@Observable final class Document: NSDocument, AdditionalDocumentPreparing, EncodingChanging {
nonisolated static let didUpdateChange = Notification.Name("didUpdateChange")
// MARK: Enums
private enum SerializationKey {
@ -719,6 +721,17 @@ extension Document: EditorSource {
self.isTransient = false
super.updateChangeCount(change)
NotificationCenter.default.post(name: Document.didUpdateChange, object: self)
}
override func updateChangeCount(withToken changeCountToken: Any, for saveOperation: NSDocument.SaveOperationType) {
// This method updates the values in the .isDocumentEdited and .hasUnautosavedChanges properties.
super.updateChangeCount(withToken: changeCountToken, for: saveOperation)
NotificationCenter.default.post(name: Document.didUpdateChange, object: self)
}