-
Notifications
You must be signed in to change notification settings - Fork 379
/
Copy pathAssetsViewController.swift
253 lines (207 loc) · 11 KB
/
AssetsViewController.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
// The MIT License (MIT)
//
// Copyright (c) 2019 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Photos
protocol AssetsViewControllerDelegate: class {
func assetsViewController(_ assetsViewController: AssetsViewController, didSelectAsset asset: PHAsset)
func assetsViewController(_ assetsViewController: AssetsViewController, didDeselectAsset asset: PHAsset)
func assetsViewController(_ assetsViewController: AssetsViewController, didLongPressCell cell: AssetCollectionViewCell, displayingAsset asset: PHAsset)
}
class AssetsViewController: UIViewController {
weak var delegate: AssetsViewControllerDelegate?
var settings: Settings! {
didSet { dataSource.settings = settings }
}
private let store: AssetStore
private let collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
private var fetchResult: PHFetchResult<PHAsset> = PHFetchResult<PHAsset>() {
didSet {
dataSource.fetchResult = fetchResult
}
}
private let dataSource: AssetsCollectionViewDataSource
private let selectionFeedback = UISelectionFeedbackGenerator()
init(store: AssetStore) {
self.store = store
dataSource = AssetsCollectionViewDataSource(fetchResult: fetchResult, store: store)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
PHPhotoLibrary.shared().register(self)
view = collectionView
// Set an empty title to get < back button
title = " "
collectionView.allowsMultipleSelection = true
collectionView.bounces = true
collectionView.alwaysBounceVertical = true
collectionView.backgroundColor = settings.theme.backgroundColor
collectionView.delegate = self
collectionView.dataSource = dataSource
collectionView.prefetchDataSource = dataSource
AssetsCollectionViewDataSource.registerCellIdentifiersForCollectionView(collectionView)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(AssetsViewController.collectionViewLongPressed(_:)))
longPressRecognizer.minimumPressDuration = 0.5
collectionView.addGestureRecognizer(longPressRecognizer)
syncSelections(store.assets)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCollectionViewLayout(for: traitCollection)
}
func showAssets(in album: PHAssetCollection) {
fetchResult = PHAsset.fetchAssets(in: album, options: settings.fetch.assets.options)
collectionView.reloadData()
let selections = self.store.assets
syncSelections(selections)
collectionView.setContentOffset(.zero, animated: false)
}
private func syncSelections(_ assets: [PHAsset]) {
collectionView.allowsMultipleSelection = true
// Unselect all
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
collectionView.deselectItem(at: indexPath, animated: false)
}
// Sync selections
for asset in assets {
let index = fetchResult.index(of: asset)
guard index != NSNotFound else { continue }
let indexPath = IndexPath(item: index, section: 0)
let numberOfItems = collectionView.numberOfItems(inSection: 0)
guard index + 1 <= numberOfItems else { continue }
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
updateSelectionIndexForCell(at: indexPath)
}
}
func unselect(asset: PHAsset) {
let index = fetchResult.index(of: asset)
guard index != NSNotFound else { return }
let indexPath = IndexPath(item: index, section: 0)
collectionView.deselectItem(at:indexPath, animated: false)
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
updateSelectionIndexForCell(at: indexPath)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateCollectionViewLayout(for: traitCollection)
}
@objc func collectionViewLongPressed(_ sender: UILongPressGestureRecognizer) {
guard settings.preview.enabled else { return }
guard sender.state == .began else { return }
selectionFeedback.selectionChanged()
// Calculate which index path long press came from
let location = sender.location(in: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: location) else { return }
guard let cell = collectionView.cellForItem(at: indexPath) as? AssetCollectionViewCell else { return }
let asset = fetchResult.object(at: indexPath.row)
delegate?.assetsViewController(self, didLongPressCell: cell, displayingAsset: asset)
}
private func updateCollectionViewLayout(for traitCollection: UITraitCollection) {
guard let collectionViewFlowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let itemSpacing = settings.list.spacing
let itemsPerRow = settings.list.cellsPerRow(traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass)
let itemWidth = (collectionView.bounds.width - CGFloat(itemsPerRow - 1) * itemSpacing) / CGFloat(itemsPerRow)
let itemSize = CGSize(width: itemWidth, height: itemWidth)
collectionViewFlowLayout.minimumLineSpacing = itemSpacing
collectionViewFlowLayout.minimumInteritemSpacing = itemSpacing
collectionViewFlowLayout.itemSize = itemSize
dataSource.imageSize = itemSize.resize(by: UIScreen.main.scale)
}
private func updateSelectionIndexForCell(at indexPath: IndexPath) {
guard settings.theme.selectionStyle == .numbered else { return }
guard let cell = collectionView.cellForItem(at: indexPath) as? AssetCollectionViewCell else { return }
let asset = fetchResult.object(at: indexPath.row)
cell.selectionIndex = store.index(of: asset)
}
}
extension AssetsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectionFeedback.selectionChanged()
let asset = fetchResult.object(at: indexPath.row)
store.append(asset)
delegate?.assetsViewController(self, didSelectAsset: asset)
updateSelectionIndexForCell(at: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
selectionFeedback.selectionChanged()
let asset = fetchResult.object(at: indexPath.row)
store.remove(asset)
delegate?.assetsViewController(self, didDeselectAsset: asset)
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
updateSelectionIndexForCell(at: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard store.count < settings.selection.max || settings.selection.unselectOnReachingMax else { return false }
selectionFeedback.prepare()
return true
}
}
extension AssetsViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
// Since we are gonna update UI, make sure we are on main
DispatchQueue.main.async {
guard let changes = changeInstance.changeDetails(for: self.fetchResult) else { return }
if changes.hasIncrementalChanges {
self.collectionView.performBatchUpdates({
self.fetchResult = changes.fetchResultAfterChanges
// For indexes to make sense, updates must be in this order:
// delete, insert, move
if let removed = changes.removedIndexes, removed.count > 0 {
let removedItems = removed.map { IndexPath(item: $0, section:0) }
let removedSelections = self.collectionView.indexPathsForSelectedItems?.filter { return removedItems.contains($0) }
removedSelections?.forEach {
let removedAsset = changes.fetchResultBeforeChanges.object(at: $0.row)
self.store.remove(removedAsset)
self.delegate?.assetsViewController(self, didDeselectAsset: removedAsset)
}
self.collectionView.deleteItems(at: removedItems)
}
if let inserted = changes.insertedIndexes, inserted.count > 0 {
self.collectionView.insertItems(at: inserted.map { IndexPath(item: $0, section:0) })
}
changes.enumerateMoves { fromIndex, toIndex in
self.collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0),
to: IndexPath(item: toIndex, section: 0))
}
})
// "Use these indices to reconfigure the corresponding cells after performBatchUpdates"
// https://developer.apple.com/documentation/photokit/phobjectchangedetails
if let changed = changes.changedIndexes, changed.count > 0 {
self.collectionView.reloadItems(at: changed.map { IndexPath(item: $0, section:0) })
}
} else {
self.fetchResult = changes.fetchResultAfterChanges
self.collectionView.reloadData()
}
// No matter if we have incremental changes or not, sync the selections
self.syncSelections(self.store.assets)
}
}
}