-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathEditController.swift
304 lines (247 loc) · 9.8 KB
/
EditController.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
//
// EditController.swift
// OpenInPlace
//
// This view controller shows how to
// 1) read contents in coordinated manner from a remote file from iCloud Drive
// or another document providers:
// loadContent()
//
// 2) write back content in coordinated manner:
// writeContentIfNeeded() and writeContentUpdatingUI()
//
// 3) observe changes and coordinate with other processes accessing file:
// appMovedToBackground(), appMovedToForeground() and NSFilePresenter delegate methods
//
// 4) auto-save changes:
// textViewDidChange() and appMovedToBackground()
//
// 5) use WorkingCopyUrlService file-provider SDK to get file status and compose
// x-callback-url for initiating commit:
// loadStatusWithService() and statusTapped()
//
// If you are using UIDocument you mostly get all this for free.
//
//
// Created by Anders Borum on 21/06/2017.
// Copyright © 2017 Applied Phasor. All rights reserved.
//
import UIKit
class EditController: UIViewController, UITextViewDelegate, NSFilePresenter {
@IBOutlet var textView: UITextView!
@IBOutlet var statusButton: UIBarButtonItem!
private func loadContent() {
// do not load unless we have both url and view loaded
guard isViewLoaded else { return }
guard url != nil else {
self.navigationItem.title = "<DELETED>"
self.textView.text = ""
return
}
navigationItem.title = _url?.lastPathComponent
let coordinator = NSFileCoordinator(filePresenter: self)
url!.coordinatedRead(coordinator, callback: { (text, error) in
DispatchQueue.main.async {
if(error != nil) {
self.showError(error!)
} else {
self.textView.text = text
}
}
})
}
private var urlService: WorkingCopyUrlService?
private func loadStatusWithService(_ service: WorkingCopyUrlService) {
service.fetchStatus(completionHandler: {
(linesAdded, linesDeleted, error) in
self.statusButton.isEnabled = true
switch (linesAdded, linesDeleted) {
case (UInt(NSNotFound), _):
// modified binary file
self.statusButton.title = "binary"
case (0,0):
// file is current
self.statusButton.title = ""
self.statusButton.isEnabled = false
case (0, _):
// modified text file
self.statusButton.title = "-\(linesDeleted)"
case (_, 0):
// modified text file
self.statusButton.title = "+\(linesAdded)"
default:
// modified text file
self.statusButton.title = "-\(linesDeleted)+\(linesAdded)"
}
})
}
@IBAction func statusTapped(_ sender: Any) {
guard let service = urlService else { return }
// request deep link
service.determineDeepLink(completionHandler: { (url, error) in
if let error = error {
self.showError(error)
}
guard let url = url else { return }
// we escape everything outside urlQueryAllowed but also & that starts next url parameter
let allowChars = CharacterSet.urlQueryAllowed.intersection(CharacterSet(charactersIn: "&").inverted)
guard let escaped = url.absoluteString.addingPercentEncoding(withAllowedCharacters: allowChars) else { return }
guard let callbackUrl = URL(string: "working-copy://x-callback-url/commit?url=\(escaped)&x-cancel=open-in-place://&x-success=open-in-place://") else { return }
UIApplication.shared.open(callbackUrl)
})
}
private func loadStatus() {
guard isViewLoaded else { return }
guard let url = url else { return }
if #available(iOS 11.0, *) {
// try to use existing service instance
if let service = urlService {
loadStatusWithService(service)
return
}
// Try to get file provider icon from Working Copy service.
WorkingCopyUrlService.getFor(url, completionHandler: { (service, error) in
// the service might very well be missing if you are picking from some other
// Location than Working Copy or the version of Working Copy isn't new enough
guard let service = service else { return }
self.urlService = service
self.loadStatusWithService(service)
})
}
}
private var unwrittenChanges = false
private func writeContentIfNeeded(callback: @escaping ((Error?) -> ())) {
guard unwrittenChanges else {
callback(nil)
return
}
unwrittenChanges = false
guard url != nil else {
callback(nil)
return
}
let coordinator = NSFileCoordinator(filePresenter: self)
url!.coordinatedWrite(textView.text, coordinator, callback: callback)
}
// calls writeContentIfNeeded(callback:) showing errors
@objc private func writeContentUpdatingUI() {
writeContentIfNeeded(callback: { error in
DispatchQueue.main.async {
if let error = error {
self.showError(error)
} else {
self.loadStatus()
}
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
loadContent()
loadStatus()
let notifications = NotificationCenter.default
notifications.addObserver(self, selector: #selector(appMovedToBackground),
name: UIApplication.willResignActiveNotification, object: nil)
notifications.addObserver(self, selector: #selector(appMovedToForeground),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// clean up when removed
if url != nil && self.isMovingFromParent {
url = nil
}
}
private var securityScoped = false
private var _url: URL?
private var isFilePresenting = false
public var url: URL? {
set {
if(_url != nil) {
if securityScoped {
_url!.stopAccessingSecurityScopedResource()
securityScoped = false
}
if(isFilePresenting) {
NSFileCoordinator.removeFilePresenter(self)
isFilePresenting = false
}
}
_url = newValue
urlService = nil
if(_url != nil) {
securityScoped = _url!.startAccessingSecurityScopedResource()
NSFileCoordinator.addFilePresenter(self)
isFilePresenting = true
}
loadContent()
loadStatus()
}
get {
return _url
}
}
//MARK: - NSFilePresenter
var presentedItemURL: URL? {
return url
}
private var presenterQueue : OperationQueue?
var presentedItemOperationQueue: OperationQueue {
if(presenterQueue == nil) {
presenterQueue = OperationQueue()
}
return presenterQueue!
}
// file was changed by someone else and we want to reload
func presentedItemDidChange() {
loadContent()
}
// someone wants to read the file and we make sure pending changes are written
func relinquishPresentedItem(toReader reader: @escaping ((() -> Void)?) -> Void) {
writeContentIfNeeded(callback: { error in
reader(nil)
})
}
// someone wants to write the file and we make sure pending changes are written
func relinquishPresentedItem(toWriter writer: @escaping ((() -> Void)?) -> Void) {
writeContentIfNeeded(callback: { error in
writer(nil)
})
}
// file is being renamed by someone else and we keep work in new file location
func presentedItemDidMove(to newURL: URL) {
url = newURL
}
// file is being deleted and we stop tracking it
func accommodatePresentedItemDeletion(completionHandler: @escaping (Error?) -> Void) {
url = nil
completionHandler(nil)
}
@objc func appMovedToBackground() {
// it can lead to deadlocks to present files in the background and we back off
if(isFilePresenting) {
NSFileCoordinator.removeFilePresenter(self)
isFilePresenting = false
}
// write if anything is pending
writeContentUpdatingUI()
}
@objc func appMovedToForeground() {
// we are back after being in the background and listen again and refresh from file
if(!isFilePresenting && url != nil) {
NSFileCoordinator.addFilePresenter(self)
isFilePresenting = true
}
loadContent()
loadStatus()
}
//MARK: - UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
// we want to write changes, but not after every keystroke and wait for a
// whole second without changes
unwrittenChanges = true
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(writeContentUpdatingUI), object: nil)
perform(#selector(writeContentUpdatingUI), with: nil, afterDelay: 1.0)
}
//MARK: -
}