-
Notifications
You must be signed in to change notification settings - Fork 30
/
ImagePreviewViewController.swift
358 lines (310 loc) · 14.3 KB
/
ImagePreviewViewController.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
//
// ImagePreviewViewController.swift
// piwigo
//
// Created by Spencer Baker on 2/21/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5.3 by Eddy Lelièvre-Berna on 04/09/2021.
//
import AVKit
import UIKit
import piwigoKit
class ImagePreviewViewController: UIViewController
{
var imageIndex = 0
var imageLoaded = false
var imageData: Image!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var playImage: UIImageView!
@IBOutlet weak var descContainer: ImageDescriptionView!
@IBOutlet weak var progressView: PieProgressView!
var imageURL: URL?
private var serverID = ""
private let placeHolder = UIImage(named: "placeholderImage")!
private var userDidTapOnce: Bool = false // True if the user did tap the view
private var userDidRotateDevice: Bool = false // True if the user did rotate the device
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Retrieve server ID
serverID = imageData.server?.uuid ?? ""
if serverID.isEmpty {
// Configure the description view before layouting subviews
descContainer.configDescription(with: imageData.comment) {
self.configScrollView(with: self.placeHolder)
}
return
}
// Thumbnail image should be available in cache
let thumbSize = pwgImageSize(rawValue: AlbumVars.shared.defaultThumbnailSize) ?? .thumb
let cacheDir = DataDirectories.shared.cacheDirectory.appendingPathComponent(serverID)
let fileURL = cacheDir.appendingPathComponent(thumbSize.path)
.appendingPathComponent(String(imageData.pwgID))
// Configure the description view before layouting subviews
let thumbImage = UIImage(contentsOfFile: fileURL.path) ?? placeHolder
descContainer.configDescription(with: imageData.comment) {
self.configScrollView(with: thumbImage)
}
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
@objc func applyColorPalette() {
// Update description view colors if necessary
descContainer.setDescriptionColor()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set colors, fonts, etc.
applyColorPalette()
// Previewed image
imageView.layoutIfNeeded() // Ensure imageView in its final size
let cellSize = self.scrollView.bounds.size
let scale = self.scrollView.traitCollection.displayScale
progressView?.progress = 0
let previewSize = pwgImageSize(rawValue: ImageVars.shared.defaultImagePreviewSize) ?? .medium
imageURL = ImageUtilities.getURL(imageData, ofMinSize: previewSize)
if let imageURL = imageURL {
ImageSession.shared.getImage(withID: self.imageData.pwgID, ofSize: previewSize, atURL: imageURL,
fromServer: self.serverID, fileSize: self.imageData.fileSize,
placeHolder: self.placeHolder) { fractionCompleted in
DispatchQueue.main.async {
self.progressView.progress = fractionCompleted
}
} completion: { cachedImageURL in
let cachedImage = ImageUtilities.downsample(imageAt: cachedImageURL, to: cellSize, scale: scale)
if cachedImage == self.placeHolder {
// Image in cache is not appropriate
try? FileManager.default.removeItem(at: imageURL)
} else {
DispatchQueue.main.async {
self.progressView.progress = 1.0
self.configImage(cachedImage)
}
}
} failure: { _ in }
}
// Show/hide the description
guard let comment = imageData?.comment,
comment.string.isEmpty == false else {
descContainer.isHidden = true
return
}
descContainer.isHidden = navigationController?.isNavigationBarHidden ?? false
}
func configImage(_ image: UIImage) {
// Set image view content
self.configScrollView(with: image)
// Layout subviews
self.view.layoutIfNeeded()
// Hide progress view
self.imageLoaded = true
self.progressView.isHidden = true
// Display "play" button if video
self.playImage.isHidden = !self.imageData.isVideo
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if userDidTapOnce {
userDidTapOnce = false
return
}
// Configure scrollview after:
/// - configuring the description view
/// - loading the thumbnail image
/// - loading the high-resolution image
/// - rotating the device
configScrollView()
centerImageView()
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
// MARK: - Scroll View
private func configScrollView(with image: UIImage) {
imageView.image = image
imageView.frame = CGRect(origin: .zero, size: image.size)
imageViewWidthConstraint.constant = image.size.width
imageViewHeightConstraint.constant = image.size.height
}
/*
This method calculates the zoom scale for the scroll view.
A zoom scale of 1 indicates that the content displays at its normal size.
A zoom scale of less than 1 shows a zoomed-out version of the content,
and a zoom scale greater than 1 shows the content zoomed in.
*/
private func configScrollView() {
guard let image = imageView?.image else { return }
scrollView.isPagingEnabled = false
scrollView.bounds = view.bounds
scrollView.contentSize = image.size
// Don't adjust the insets when showing or hiding the navigation bar/toolbar
scrollView.contentInset = .zero
scrollView.contentInsetAdjustmentBehavior = .never
// Define the zoom scale range
let widthScale = view.bounds.size.width / image.size.width
let heightScale = view.bounds.size.height / image.size.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = max(pwgImageSize.maxZoomScale, 4 * minScale)
scrollView.zoomScale = minScale // Will trigger the scrollViewDidZoom() method
// debugPrint("=> scrollView: \(scrollView.bounds.size.width) x \(scrollView.bounds.size.height), imageView: \(imageView.frame.size.width) x \(imageView.frame.size.height), minScale: \(minScale)")
}
private func centerImageView() {
guard let image = imageView?.image else { return }
// Determine the orientation of the device
let orientation: UIInterfaceOrientation
if #available(iOS 14, *) {
orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? .portrait
} else {
orientation = UIApplication.shared.statusBarOrientation
}
// Determine if the toolbar is presented
var isToolbarRequired = false
if let viewControllers = navigationController?.viewControllers.filter({ $0.isKind(of: ImageViewController.self)}), let vc = viewControllers.first as? ImageViewController {
isToolbarRequired = vc.isToolbarRequired
}
// Determine the available spaces around the image
var spaceLeading: CGFloat = 0, spaceTrailing: CGFloat = 0
var spaceTop:CGFloat = 0, spaceBottom:CGFloat = 0
if let nav = navigationController {
// Remove the heights of the navigation bar and toolbar
spaceTop += nav.navigationBar.bounds.height
spaceBottom += isToolbarRequired ? nav.toolbar.bounds.height : 0
}
// Takes into account the safe area insets
if let root = topMostViewController()?.view?.window?.topMostViewController() {
spaceTop += orientation.isLandscape ? 0 : root.view.safeAreaInsets.top
spaceBottom += isToolbarRequired ? root.view.safeAreaInsets.bottom : 0
spaceLeading += orientation.isLandscape ? 0 : root.view.safeAreaInsets.left
spaceTrailing += orientation.isLandscape ? 0 : root.view.safeAreaInsets.right
}
// Horizontal constraints
let imageWidth = image.size.width * scrollView.zoomScale
let horizontalSpaceAvailable = view.bounds.width - (spaceLeading + imageWidth + spaceTrailing)
spaceLeading += horizontalSpaceAvailable/2
spaceTrailing += horizontalSpaceAvailable/2
// Vertical constraints
let imageHeight = image.size.height * scrollView.zoomScale
var verticalSpaceAvailable = view.bounds.height - (spaceTop + imageHeight + spaceBottom)
var descHeight: CGFloat = 0.0
if let comment = imageData?.comment, comment.string.isEmpty == false {
descHeight = descContainer.descHeight.constant + 8
}
if isToolbarRequired {
if verticalSpaceAvailable >= descHeight {
// Centre image between navigation bar and description/toolbar
verticalSpaceAvailable -= descHeight
spaceTop += verticalSpaceAvailable/2
spaceBottom += descHeight + verticalSpaceAvailable/2
} else if verticalSpaceAvailable >= 0 {
// Keep image glued to navigation bar
spaceBottom += verticalSpaceAvailable
} else {
// Centre image between navigation bar and toolbar
spaceTop += verticalSpaceAvailable/2
spaceBottom += verticalSpaceAvailable/2
}
} else {
if verticalSpaceAvailable >= descHeight {
// Centre image between navigation bar and bottom
verticalSpaceAvailable -= descHeight
spaceTop += verticalSpaceAvailable/2
spaceBottom += descHeight + verticalSpaceAvailable/2
} else if verticalSpaceAvailable >= 0 {
// Keep image glued to navigation bar
spaceBottom += verticalSpaceAvailable
} else if -verticalSpaceAvailable < spaceTop {
// Keep image glued to bottom
spaceTop += verticalSpaceAvailable
} else {
// Centre image between top and bottom
verticalSpaceAvailable += spaceTop
spaceTop = verticalSpaceAvailable/2
spaceBottom = verticalSpaceAvailable/2
}
}
// Center image horizontally in scrollview
scrollView.contentInset.left = max(0, spaceLeading)
scrollView.contentInset.right = max(0, spaceTrailing)
// Center image vertically in scrollview
scrollView.contentInset.top = max(0, spaceTop)
scrollView.contentInset.bottom = max(0, spaceBottom)
}
// MARK: - Image Metadata
func didTapOnce() {
// Remember that user did tap the view
userDidTapOnce = true
// Show/hide the description
guard let comment = imageData?.comment,
comment.string.isEmpty == false else {
descContainer.isHidden = true
return
}
descContainer.isHidden = navigationController?.isNavigationBarHidden ?? false
}
func didTapTwice(_ gestureRecognizer: UIGestureRecognizer) {
// Get current scale
let scale = min(scrollView.zoomScale * 1.5, scrollView.maximumZoomScale)
// Should we zoom in?
if scale != scrollView.zoomScale {
// Let's zoom in…
let point = gestureRecognizer.location(in: imageView)
let scrollSize = scrollView.frame.size
let size = CGSize(width: scrollSize.width / scale,
height: scrollSize.height / scale)
let origin = CGPoint(x: point.x - size.width / 2,
y: point.y - size.height / 2)
scrollView.zoom(to:CGRect(origin: origin, size: size), animated: true)
}
else {
// Let's zoom out…
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
}
}
func didRotateDevice() {
// Remember that user did tap the view
userDidRotateDevice = true
// Should we update the description?
if descContainer.descTextView.text.isEmpty {
self.view.layoutIfNeeded()
} else {
descContainer.configDescription(with: imageData.comment) { [unowned self] in
self.descContainer.setDescriptionColor()
self.view.layoutIfNeeded()
}
}
}
func updateImageMetadata(with data: Image) {
// Update image description
descContainer.configDescription(with: data.comment) {
self.view.layoutIfNeeded()
}
}
}
// MARK: - UIScrollViewDelegate Methods
/// https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/UIScrollView_pg/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008179-CH1-SW1
extension ImagePreviewViewController: UIScrollViewDelegate
{
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
centerImageView()
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
// Limit the zoom scale
if scale < scrollView.minimumZoomScale {
scrollView.zoomScale = scrollView.minimumZoomScale
centerImageView()
} else if scale > scrollView.maximumZoomScale {
scrollView.zoomScale = scrollView.maximumZoomScale
centerImageView()
}
}
}