NCViewerImageViewController.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. //
  2. // NCViewerImageViewController.swift
  3. // Nextcloud
  4. //
  5. // Created by Suraj Thomas K on 7/10/18 Copyright © 2018 Al Tayer Group LLC..
  6. // Modify for Nextcloud by Marino Faggiana on 04/03/2020.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. protocol NCViewerImageViewControllerDataSource: class {
  24. func numberOfItems(in viewerImageViewController: NCViewerImageViewController) -> Int
  25. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, imageAt index: Int, completion: @escaping (_ index: Int, _ image: UIImage?, _ metadata: tableMetadata, _ zoomScale: ZoomScale?, _ error: Error?) -> Void)
  26. func targetFrameForDismissal(_ viewerImageViewController: NCViewerImageViewController) -> CGRect?
  27. }
  28. extension NCViewerImageViewControllerDataSource {
  29. public func targetFrameForDismissal(_ viewerImageViewController: NCViewerImageViewController) -> CGRect? { return nil }
  30. }
  31. // MARK: - NCViewerImageViewControllerDelegate protocol
  32. protocol NCViewerImageViewControllerDelegate: class {
  33. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, willChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata)
  34. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, didChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata)
  35. func viewerImageViewControllerTap(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata)
  36. func viewerImageViewControllerLongPressBegan(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata)
  37. func viewerImageViewControllerLongPressEnded(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata)
  38. func viewerImageViewControllerDismiss()
  39. }
  40. extension NCViewerImageViewControllerDelegate {
  41. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, didChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata) {}
  42. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, willChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata) {}
  43. }
  44. public class NCViewerImageViewController: UIViewController {
  45. // MARK: - Exposed Enumerations
  46. public enum GestureDirection {
  47. // Horizontal (left - right) gestures.
  48. case horizontal
  49. // Vertical (up - down) gestures.
  50. case vertical
  51. }
  52. public enum BrowserStyle {
  53. // Linear browser with *0* as first index and *numItems-1* as last index.
  54. case linear
  55. // Carousel browser. The media items are repeated in a circular fashion.
  56. case carousel
  57. }
  58. public enum ContentDrawOrder {
  59. // In this mode, media items are rendered in [previous]-[current]-[next] order.
  60. case previousToNext
  61. // In this mode, media items are rendered in [next]-[current]-[previous] order.
  62. case nextToPrevious
  63. }
  64. // MARK: - Exposed variables
  65. weak var dataSource: NCViewerImageViewControllerDataSource?
  66. weak var delegate: NCViewerImageViewControllerDelegate?
  67. var gestureDirection: GestureDirection = .horizontal
  68. var contentTransformer: NCViewerImageContentTransformer = NCViewerImageDefaultContentTransformers.horizontalMoveInOut {
  69. didSet {
  70. NCViewerImageContentView.contentTransformer = contentTransformer
  71. contentViews.forEach({ $0.updateTransform() })
  72. }
  73. }
  74. var drawOrder: ContentDrawOrder = .previousToNext {
  75. didSet {
  76. if oldValue != drawOrder {
  77. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  78. }
  79. }
  80. }
  81. var browserStyle: BrowserStyle = .carousel
  82. // Gap between consecutive media items. Default is `50.0`.
  83. var gapBetweenMediaViews: CGFloat = Constants.gapBetweenContents {
  84. didSet {
  85. NCViewerImageContentView.interItemSpacing = gapBetweenMediaViews
  86. contentViews.forEach({ $0.updateTransform() })
  87. }
  88. }
  89. // Enable or disable interactive dismissal. Default is enabled.
  90. var enableInteractiveDismissal: Bool = true
  91. // Item index of the current item. In range `0..<numMediaItems`
  92. var currentItemIndex: Int {
  93. return sanitizeIndex(index)
  94. }
  95. // MARK: - Private Enumerations
  96. private enum Constants {
  97. static let gapBetweenContents: CGFloat = 50.0
  98. static let minimumVelocity: CGFloat = 15.0
  99. static let minimumTranslation: CGFloat = 0.1
  100. static let animationDuration = 0.3
  101. static let updateFrameRate: CGFloat = 60.0
  102. static let bounceFactor: CGFloat = 0.1
  103. enum PageControl {
  104. static let bottom: CGFloat = -10.0
  105. static let tintColor: UIColor = .lightGray
  106. static let selectedTintColor: UIColor = .white
  107. }
  108. }
  109. // MARK: - Private variables
  110. private(set) var index: Int = 0 {
  111. didSet {
  112. pageControl.currentPage = index
  113. }
  114. }
  115. public var contentViews: [NCViewerImageContentView] = []
  116. lazy private var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
  117. let gesture = UITapGestureRecognizer()
  118. gesture.numberOfTapsRequired = 1
  119. gesture.numberOfTouchesRequired = 1
  120. gesture.delegate = self
  121. gesture.addTarget(self, action: #selector(tapGestureEvent(_:)))
  122. return gesture
  123. }()
  124. lazy private var longtapGestureRecognizer: UILongPressGestureRecognizer = { [unowned self] in
  125. let gesture = UILongPressGestureRecognizer()
  126. gesture.delaysTouchesBegan = true
  127. gesture.minimumPressDuration = 0.3
  128. gesture.delegate = self
  129. gesture.addTarget(self, action: #selector(longpressGestureEvent(_:)))
  130. return gesture
  131. }()
  132. private var previousTranslation: CGPoint = .zero
  133. private var timer: Timer?
  134. private var distanceToMove: CGFloat = 0.0
  135. lazy private var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
  136. let gesture = UIPanGestureRecognizer()
  137. gesture.minimumNumberOfTouches = 1
  138. gesture.maximumNumberOfTouches = 1
  139. gesture.delegate = self
  140. gesture.addTarget(self, action: #selector(panGestureEvent(_:)))
  141. return gesture
  142. }()
  143. lazy internal private(set) var mediaContainerView: UIView = { [unowned self] in
  144. let container = UIView()
  145. container.backgroundColor = .clear
  146. return container
  147. }()
  148. lazy var statusView: UIImageView = {
  149. let statusView = UIImageView()
  150. statusView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  151. statusView.contentMode = .scaleAspectFit
  152. statusView.clipsToBounds = true
  153. return statusView
  154. }()
  155. lazy private var pageControl: UIPageControl = { [unowned self] in
  156. let pageControl = UIPageControl()
  157. pageControl.hidesForSinglePage = true
  158. pageControl.numberOfPages = numMediaItems
  159. pageControl.currentPageIndicatorTintColor = Constants.PageControl.selectedTintColor
  160. pageControl.tintColor = Constants.PageControl.tintColor
  161. pageControl.currentPage = index
  162. return pageControl
  163. }()
  164. private var numMediaItems = 0
  165. private lazy var dismissController = NCViewerImageDismissAnimationController(
  166. gestureDirection: gestureDirection,
  167. viewController: self
  168. )
  169. // MARK: - Public methods
  170. public func reloadContentViews() {
  171. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  172. for contentView in contentViews {
  173. updateContents(of: contentView)
  174. }
  175. }
  176. // MARK: - Initializers
  177. init(
  178. index: Int = 0,
  179. dataSource: NCViewerImageViewControllerDataSource,
  180. delegate: NCViewerImageViewControllerDelegate? = nil
  181. ) {
  182. self.index = index
  183. self.dataSource = dataSource
  184. self.delegate = delegate
  185. super.init(nibName: nil, bundle: nil)
  186. initialize()
  187. }
  188. public required init?(coder aDecoder: NSCoder) {
  189. super.init(coder: aDecoder)
  190. initialize()
  191. }
  192. private func initialize() {
  193. view.backgroundColor = .clear
  194. modalPresentationStyle = .custom
  195. modalTransitionStyle = .crossDissolve
  196. }
  197. public func changeInViewSize(to size: CGSize) {
  198. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  199. }
  200. }
  201. // MARK: - View Lifecycle and Events
  202. extension NCViewerImageViewController {
  203. override public var prefersStatusBarHidden: Bool {
  204. return true
  205. }
  206. override public func viewDidLoad() {
  207. super.viewDidLoad()
  208. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  209. populateContentViews()
  210. view.addGestureRecognizer(panGestureRecognizer)
  211. view.addGestureRecognizer(tapGestureRecognizer)
  212. view.addGestureRecognizer(longtapGestureRecognizer)
  213. }
  214. override public func viewDidAppear(_ animated: Bool) {
  215. super.viewDidAppear(animated)
  216. contentViews.forEach({ $0.updateTransform() })
  217. }
  218. override public func viewWillDisappear(_ animated: Bool) {
  219. super.viewWillDisappear(animated)
  220. }
  221. public override func viewWillTransition(
  222. to size: CGSize,
  223. with coordinator: UIViewControllerTransitionCoordinator
  224. ) {
  225. coordinator.animate(alongsideTransition: { context in
  226. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  227. }, completion: nil)
  228. super.viewWillTransition(to: size, with: coordinator)
  229. }
  230. private func populateContentViews() {
  231. view.addSubview(mediaContainerView)
  232. mediaContainerView.translatesAutoresizingMaskIntoConstraints = false
  233. NSLayoutConstraint.activate([
  234. mediaContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  235. mediaContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  236. mediaContainerView.topAnchor.constraint(equalTo: view.topAnchor),
  237. mediaContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  238. ])
  239. view.addSubview(statusView)
  240. statusView.translatesAutoresizingMaskIntoConstraints = false
  241. if #available(iOS 11, *) {
  242. NSLayoutConstraint.activate([
  243. statusView.widthAnchor.constraint(equalToConstant: 30),
  244. statusView.heightAnchor.constraint(equalToConstant: 30),
  245. statusView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 2),
  246. statusView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 2)
  247. ])
  248. } else {
  249. NSLayoutConstraint.activate([
  250. statusView.widthAnchor.constraint(equalToConstant: 30),
  251. statusView.heightAnchor.constraint(equalToConstant: 30),
  252. statusView.topAnchor.constraint(equalTo: view.topAnchor, constant: 2),
  253. statusView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 2)
  254. ])
  255. }
  256. statusView.setNeedsLayout()
  257. statusView.layoutIfNeeded()
  258. NCViewerImageContentView.interItemSpacing = gapBetweenMediaViews
  259. NCViewerImageContentView.contentTransformer = contentTransformer
  260. contentViews.forEach({ $0.removeFromSuperview() })
  261. contentViews.removeAll()
  262. for i in -1...1 {
  263. let mediaView = NCViewerImageContentView(
  264. index: i + index,
  265. position: CGFloat(i),
  266. frame: view.bounds
  267. )
  268. mediaContainerView.addSubview(mediaView)
  269. mediaView.translatesAutoresizingMaskIntoConstraints = false
  270. NSLayoutConstraint.activate([
  271. mediaView.leadingAnchor.constraint(equalTo: mediaContainerView.leadingAnchor),
  272. mediaView.trailingAnchor.constraint(equalTo: mediaContainerView.trailingAnchor),
  273. mediaView.topAnchor.constraint(equalTo: mediaContainerView.topAnchor),
  274. mediaView.bottomAnchor.constraint(equalTo: mediaContainerView.bottomAnchor)
  275. ])
  276. contentViews.append(mediaView)
  277. if numMediaItems > 0 {
  278. updateContents(of: mediaView)
  279. }
  280. }
  281. if drawOrder == .nextToPrevious {
  282. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  283. }
  284. }
  285. }
  286. // MARK: - Gesture Recognizers
  287. extension NCViewerImageViewController {
  288. @objc private func panGestureEvent(_ recognizer: UIPanGestureRecognizer) {
  289. if dismissController.interactionInProgress {
  290. dismissController.handleInteractiveTransition(recognizer)
  291. return
  292. }
  293. guard numMediaItems > 0 else {
  294. return
  295. }
  296. let translation = recognizer.translation(in: view)
  297. switch recognizer.state {
  298. case .began:
  299. previousTranslation = translation
  300. distanceToMove = 0.0
  301. timer?.invalidate()
  302. timer = nil
  303. case .changed:
  304. moveViews(by: CGPoint(x: translation.x - previousTranslation.x, y: translation.y - previousTranslation.y))
  305. case .ended, .failed, .cancelled:
  306. let velocity = recognizer.velocity(in: view)
  307. var viewsCopy = contentViews
  308. let previousView = viewsCopy.removeFirst()
  309. let middleView = viewsCopy.removeFirst()
  310. let nextView = viewsCopy.removeFirst()
  311. var toMove: CGFloat = 0.0
  312. let directionalVelocity = gestureDirection == .horizontal ? velocity.x : velocity.y
  313. if abs(directionalVelocity) < Constants.minimumVelocity &&
  314. abs(middleView.position) < Constants.minimumTranslation {
  315. toMove = -middleView.position
  316. } else if directionalVelocity < 0.0 {
  317. if middleView.position >= 0.0 {
  318. toMove = -middleView.position
  319. } else {
  320. toMove = -nextView.position
  321. }
  322. } else {
  323. if middleView.position <= 0.0 {
  324. toMove = -middleView.position
  325. } else {
  326. toMove = -previousView.position
  327. }
  328. }
  329. if browserStyle == .linear || numMediaItems <= 1 {
  330. if (middleView.index == 0 && ((middleView.position + toMove) > 0.0)) ||
  331. (middleView.index == (numMediaItems - 1) && (middleView.position + toMove) < 0.0) {
  332. toMove = -middleView.position
  333. }
  334. }
  335. distanceToMove = toMove
  336. if timer == nil {
  337. timer = Timer.scheduledTimer(
  338. timeInterval: 1.0/Double(Constants.updateFrameRate),
  339. target: self,
  340. selector: #selector(update(_:)),
  341. userInfo: nil,
  342. repeats: true
  343. )
  344. }
  345. default:
  346. break
  347. }
  348. previousTranslation = translation
  349. }
  350. @objc private func tapGestureEvent(_ recognizer: UITapGestureRecognizer) {
  351. guard !dismissController.interactionInProgress else { return }
  352. guard let mediaView = self.mediaView(at: 1) else { return }
  353. mediaView.zoomScaleOne()
  354. self.delegate?.viewerImageViewControllerTap(self, metadata: mediaView.metadata)
  355. }
  356. @objc private func longpressGestureEvent(_ recognizer: UITapGestureRecognizer) {
  357. guard !dismissController.interactionInProgress else { return }
  358. guard let mediaView = self.mediaView(at: 1) else { return }
  359. if recognizer.state == UIGestureRecognizer.State.began {
  360. mediaView.zoomScaleOne()
  361. self.delegate?.viewerImageViewControllerLongPressBegan(self, metadata: mediaView.metadata)
  362. }
  363. if recognizer.state == UIGestureRecognizer.State.ended {
  364. self.delegate?.viewerImageViewControllerLongPressEnded(self, metadata: mediaView.metadata)
  365. }
  366. }
  367. }
  368. // MARK: - Updating View Positions
  369. extension NCViewerImageViewController {
  370. @objc private func update(_ timeInterval: TimeInterval) {
  371. guard distanceToMove != 0.0 else {
  372. timer?.invalidate()
  373. timer = nil
  374. return
  375. }
  376. let distance = distanceToMove / (Constants.updateFrameRate * 0.1)
  377. distanceToMove -= distance
  378. moveViewsNormalized(by: CGPoint(x: distance, y: distance))
  379. let translation = CGPoint(
  380. x: distance * (view.frame.size.width + gapBetweenMediaViews),
  381. y: distance * (view.frame.size.height + gapBetweenMediaViews)
  382. )
  383. let directionalTranslation = (gestureDirection == .horizontal) ? translation.x : translation.y
  384. if abs(directionalTranslation) < 0.1 {
  385. moveViewsNormalized(by: CGPoint(x: distanceToMove, y: distanceToMove))
  386. distanceToMove = 0.0
  387. timer?.invalidate()
  388. timer = nil
  389. }
  390. }
  391. private func moveViews(by translation: CGPoint) {
  392. let viewSizeIncludingGap = CGSize(
  393. width: view.frame.size.width + gapBetweenMediaViews,
  394. height: view.frame.size.height + gapBetweenMediaViews
  395. )
  396. let normalizedTranslation = calculateNormalizedTranslation(
  397. translation: translation,
  398. viewSize: viewSizeIncludingGap
  399. )
  400. moveViewsNormalized(by: normalizedTranslation)
  401. }
  402. private func moveViewsNormalized(by normalizedTranslation: CGPoint) {
  403. let isGestureHorizontal = (gestureDirection == .horizontal)
  404. contentViews.forEach({
  405. $0.position += isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  406. })
  407. var viewsCopy = contentViews
  408. let previousView = viewsCopy.removeFirst()
  409. let middleView = viewsCopy.removeFirst()
  410. let nextView = viewsCopy.removeFirst()
  411. let viewSizeIncludingGap = CGSize(
  412. width: view.frame.size.width + gapBetweenMediaViews,
  413. height: view.frame.size.height + gapBetweenMediaViews
  414. )
  415. let viewSize = isGestureHorizontal ? viewSizeIncludingGap.width : viewSizeIncludingGap.height
  416. let normalizedGap = gapBetweenMediaViews/viewSize
  417. let normalizedCenter = (middleView.frame.size.width / viewSize) * 0.5
  418. let viewCount = contentViews.count
  419. if middleView.position < -(normalizedGap + normalizedCenter) {
  420. index = sanitizeIndex(index + 1)
  421. // Previous item is taken and placed on right/down most side
  422. previousView.position += CGFloat(viewCount)
  423. previousView.index += viewCount
  424. updateContents(of: previousView)
  425. contentViews.removeFirst()
  426. contentViews.append(previousView)
  427. switch drawOrder {
  428. case .previousToNext:
  429. mediaContainerView.bringSubviewToFront(previousView)
  430. case .nextToPrevious:
  431. mediaContainerView.sendSubviewToBack(previousView)
  432. }
  433. delegate?.viewerImageViewController(self, willChangeFocusTo: index, view: nextView, metadata: nextView.metadata)
  434. } else if middleView.position > (1 + normalizedGap - normalizedCenter) {
  435. index = sanitizeIndex(index - 1)
  436. // Next item is taken and placed on left/top most side
  437. nextView.position -= CGFloat(viewCount)
  438. nextView.index -= viewCount
  439. updateContents(of: nextView)
  440. contentViews.removeLast()
  441. contentViews.insert(nextView, at: 0)
  442. switch drawOrder {
  443. case .previousToNext:
  444. mediaContainerView.sendSubviewToBack(nextView)
  445. case .nextToPrevious:
  446. mediaContainerView.bringSubviewToFront(nextView)
  447. }
  448. delegate?.viewerImageViewController(self, willChangeFocusTo: index, view: previousView, metadata: previousView.metadata)
  449. } else if middleView.position == 0 {
  450. delegate?.viewerImageViewController(self, didChangeFocusTo: index, view: middleView, metadata: middleView.metadata)
  451. }
  452. }
  453. private func calculateNormalizedTranslation(translation: CGPoint, viewSize: CGSize) -> CGPoint {
  454. guard let middleView = mediaView(at: 1) else {
  455. return .zero
  456. }
  457. var normalizedTranslation = CGPoint(
  458. x: (translation.x)/viewSize.width,
  459. y: (translation.y)/viewSize.height
  460. )
  461. if browserStyle != .carousel || numMediaItems <= 1 {
  462. let isGestureHorizontal = (gestureDirection == .horizontal)
  463. let directionalTranslation = isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  464. if (middleView.index == 0 && ((middleView.position + directionalTranslation) > 0.0)) ||
  465. (middleView.index == (numMediaItems - 1) && (middleView.position + directionalTranslation) < 0.0) {
  466. if isGestureHorizontal {
  467. normalizedTranslation.x *= Constants.bounceFactor
  468. } else {
  469. normalizedTranslation.y *= Constants.bounceFactor
  470. }
  471. }
  472. }
  473. return normalizedTranslation
  474. }
  475. private func updateContents(of contentView: NCViewerImageContentView) {
  476. contentView.image = nil
  477. let convertedIndex = sanitizeIndex(contentView.index)
  478. contentView.isLoading = true
  479. dataSource?.viewerImageViewController(
  480. self,
  481. imageAt: convertedIndex,
  482. completion: { [weak self] (index, image, metadata, zoom, _) in
  483. guard let strongSelf = self else {
  484. return
  485. }
  486. if index == strongSelf.sanitizeIndex(contentView.index) {
  487. if image != nil {
  488. contentView.image = image
  489. contentView.metadata = metadata
  490. contentView.zoomLevels = zoom
  491. }
  492. contentView.isLoading = false
  493. }
  494. }
  495. )
  496. }
  497. private func sanitizeIndex(_ index: Int) -> Int {
  498. let newIndex = index % numMediaItems
  499. if newIndex < 0 {
  500. return newIndex + numMediaItems
  501. }
  502. return newIndex
  503. }
  504. private func sourceImage() -> UIImage? {
  505. return mediaView(at: 1)?.image
  506. }
  507. private func mediaView(at index: Int) -> NCViewerImageContentView? {
  508. guard index < contentViews.count else {
  509. assertionFailure("Content views does not have this many views. : \(index)")
  510. return nil
  511. }
  512. return contentViews[index]
  513. }
  514. }
  515. // MARK: - UIGestureRecognizerDelegate
  516. extension NCViewerImageViewController: UIGestureRecognizerDelegate {
  517. public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  518. guard enableInteractiveDismissal else {
  519. return true
  520. }
  521. let middleView = mediaView(at: 1)
  522. if middleView?.zoomScale == middleView?.zoomLevels?.minimumZoomScale,
  523. let recognizer = gestureRecognizer as? UIPanGestureRecognizer {
  524. let translation = recognizer.translation(in: recognizer.view)
  525. if gestureDirection == .horizontal {
  526. dismissController.interactionInProgress = abs(translation.y) > abs(translation.x)
  527. } else {
  528. dismissController.interactionInProgress = abs(translation.x) > abs(translation.y)
  529. }
  530. if dismissController.interactionInProgress {
  531. dismissController.image = sourceImage()
  532. }
  533. }
  534. return true
  535. }
  536. public func gestureRecognizer(
  537. _ gestureRecognizer: UIGestureRecognizer,
  538. shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
  539. ) -> Bool {
  540. if gestureRecognizer is UIPanGestureRecognizer,
  541. let scrollView = otherGestureRecognizer.view as? NCViewerImageContentView {
  542. return scrollView.zoomScale == 1.0
  543. }
  544. return false
  545. }
  546. public func gestureRecognizer(
  547. _ gestureRecognizer: UIGestureRecognizer,
  548. shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer
  549. ) -> Bool {
  550. if gestureRecognizer is UITapGestureRecognizer {
  551. return otherGestureRecognizer.view is NCViewerImageContentView
  552. }
  553. return false
  554. }
  555. }