diff --git a/CodeEdit/Features/Documents/CodeFileDocument/CodeFileDocument.swift b/CodeEdit/Features/Documents/CodeFileDocument/CodeFileDocument.swift index 23d23bbb8..afcfda12d 100644 --- a/CodeEdit/Features/Documents/CodeFileDocument/CodeFileDocument.swift +++ b/CodeEdit/Features/Documents/CodeFileDocument/CodeFileDocument.swift @@ -13,6 +13,7 @@ import CodeEditSourceEditor import CodeEditTextView import CodeEditLanguages import Combine +import OSLog enum CodeFileError: Error { case failedToDecode @@ -26,6 +27,8 @@ final class CodeFileDocument: NSDocument, ObservableObject { let cursorPositions: [CursorPosition] } + static let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "", category: "CodeFileDocument") + /// The text content of the document, stored as a text storage /// /// This is intentionally not a `@Published` variable. If it were published, SwiftUI would do a string @@ -121,6 +124,7 @@ final class CodeFileDocument: NSDocument, ObservableObject { override func data(ofType _: String) throws -> Data { guard let sourceEncoding, let data = (content?.string as NSString?)?.data(using: sourceEncoding.nsValue) else { + Self.logger.error("Failed to encode contents to \(self.sourceEncoding.debugDescription)") throw CodeFileError.failedToEncode } return data @@ -143,6 +147,8 @@ final class CodeFileDocument: NSDocument, ObservableObject { if let validEncoding = FileEncoding(rawEncoding), let nsString { self.sourceEncoding = validEncoding self.content = NSTextStorage(string: nsString as String) + } else { + Self.logger.error("Failed to read file from data using encoding: \(rawEncoding)") } } diff --git a/CodeEdit/Features/Editor/Views/CodeFileView.swift b/CodeEdit/Features/Editor/Views/CodeFileView.swift index 7e9054f14..627d96074 100644 --- a/CodeEdit/Features/Editor/Views/CodeFileView.swift +++ b/CodeEdit/Features/Editor/Views/CodeFileView.swift @@ -67,10 +67,23 @@ struct CodeFileView: View { codeFile .contentCoordinator .textUpdatePublisher - .debounce(for: 1.0, scheduler: DispatchQueue.main) .sink { _ in codeFile.updateChangeCount(.changeDone) - codeFile.autosave(withImplicitCancellability: false) { _ in } + } + .store(in: &cancellables) + + codeFile + .contentCoordinator + .textUpdatePublisher + .debounce(for: 1.0, scheduler: DispatchQueue.main) + .sink { _ in + codeFile.autosave(withImplicitCancellability: false) { error in + if let error { + CodeFileDocument.logger.error("Failed to autosave document, error: \(error)") + } else { + codeFile.updateChangeCount(.changeCleared) + } + } } .store(in: &cancellables)