NCViewerPDF.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //
  2. // NCViewerPDF.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/02/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  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. import UIKit
  24. import PDFKit
  25. import EasyTipView
  26. import NextcloudKit
  27. class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
  28. @IBOutlet weak var pdfContainer: UIView!
  29. var metadata = tableMetadata()
  30. var imageIcon: UIImage?
  31. private var filePath = ""
  32. private var pdfView = PDFView()
  33. private var pdfThumbnailScrollView = UIScrollView()
  34. private var pdfThumbnailView = PDFThumbnailView()
  35. private var pdfDocument: PDFDocument?
  36. private let pageView = UIView()
  37. private let pageViewLabel = UILabel()
  38. private var tipView: EasyTipView?
  39. private let thumbnailViewHeight: CGFloat = 70
  40. private let thumbnailViewWidth: CGFloat = 80
  41. private let thumbnailPadding: CGFloat = 2
  42. private let animateDuration: TimeInterval = 0.3
  43. private let window = UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.first { $0.isKeyWindow }
  44. private var defaultBackgroundColor: UIColor = .clear
  45. private var pdfContainerTopAnchor: NSLayoutConstraint?
  46. private var pdfThumbnailScrollViewTopAnchor: NSLayoutConstraint?
  47. private var pdfThumbnailScrollViewTrailingAnchor: NSLayoutConstraint?
  48. private var pdfThumbnailScrollViewWidthAnchor: NSLayoutConstraint?
  49. private var pageViewWidthAnchor: NSLayoutConstraint?
  50. // MARK: - View Life Cycle
  51. required init?(coder aDecoder: NSCoder) {
  52. super.init(coder: aDecoder)
  53. }
  54. override func viewDidLoad() {
  55. filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  56. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  57. defaultBackgroundColor = pdfView.backgroundColor
  58. view.backgroundColor = defaultBackgroundColor
  59. navigationController?.navigationBar.prefersLargeTitles = false
  60. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
  61. navigationItem.title = metadata.fileNameView
  62. // TIP
  63. var preferences = EasyTipView.Preferences()
  64. preferences.drawing.foregroundColor = .white
  65. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  66. preferences.drawing.textAlignment = .left
  67. preferences.drawing.arrowPosition = .right
  68. preferences.drawing.cornerRadius = 10
  69. preferences.positioning.bubbleInsets.right = window?.safeAreaInsets.right ?? 0
  70. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  71. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  72. preferences.animating.showInitialAlpha = 0
  73. preferences.animating.showDuration = 1.5
  74. preferences.animating.dismissDuration = 1.5
  75. tipView = EasyTipView(text: NSLocalizedString("_tip_pdf_thumbnails_", comment: ""), preferences: preferences, delegate: self)
  76. // PDF CONTAINER
  77. pdfContainer.translatesAutoresizingMaskIntoConstraints = false
  78. pdfContainerTopAnchor = pdfContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
  79. pdfContainerTopAnchor?.isActive = true
  80. NSLayoutConstraint.activate([
  81. pdfContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  82. pdfContainer.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
  83. pdfContainer.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  84. ])
  85. // PDF VIEW
  86. pdfView.translatesAutoresizingMaskIntoConstraints = false
  87. pdfView.document = pdfDocument
  88. pdfView.document?.page(at: 0)?.annotations.forEach({
  89. $0.isReadOnly = true
  90. })
  91. pdfView.autoScales = true
  92. pdfView.displayMode = .singlePageContinuous
  93. pdfView.displayDirection = .vertical
  94. pdfContainer.addSubview(pdfView)
  95. NSLayoutConstraint.activate([
  96. pdfView.topAnchor.constraint(equalTo: pdfContainer.topAnchor),
  97. pdfView.leadingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.leadingAnchor),
  98. pdfView.trailingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.trailingAnchor),
  99. pdfView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
  100. ])
  101. // NOTIFIFICATION
  102. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  103. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(searchText), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(goToPage), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChange), name: Notification.Name.PDFViewPageChanged, object: nil)
  112. }
  113. deinit {
  114. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  115. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  116. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  117. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  118. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  119. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  120. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  121. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  122. NotificationCenter.default.removeObserver(self, name: Notification.Name.PDFViewPageChanged, object: nil)
  123. }
  124. override func viewDidAppear(_ animated: Bool) {
  125. super.viewDidAppear(animated)
  126. // PDF THUMBNAIL
  127. pdfThumbnailScrollView.translatesAutoresizingMaskIntoConstraints = false
  128. pdfThumbnailScrollView.backgroundColor = defaultBackgroundColor
  129. pdfThumbnailScrollView.showsVerticalScrollIndicator = false
  130. pdfContainer.addSubview(pdfThumbnailScrollView)
  131. NSLayoutConstraint.activate([
  132. pdfThumbnailScrollView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
  133. ])
  134. pdfThumbnailScrollViewTopAnchor = pdfThumbnailScrollView.topAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.topAnchor)
  135. pdfThumbnailScrollViewTopAnchor?.isActive = true
  136. pdfThumbnailScrollViewTrailingAnchor = pdfThumbnailScrollView.trailingAnchor.constraint(equalTo: pdfContainer.trailingAnchor)
  137. pdfThumbnailScrollViewTrailingAnchor?.isActive = true
  138. pdfThumbnailScrollViewWidthAnchor = pdfThumbnailScrollView.widthAnchor.constraint(equalToConstant: thumbnailViewWidth)
  139. pdfThumbnailScrollViewWidthAnchor?.isActive = true
  140. pdfThumbnailView.translatesAutoresizingMaskIntoConstraints = false
  141. pdfThumbnailView.pdfView = pdfView
  142. pdfThumbnailView.layoutMode = .vertical
  143. pdfThumbnailView.thumbnailSize = CGSize(width: thumbnailViewHeight, height: thumbnailViewHeight)
  144. pdfThumbnailView.backgroundColor = .clear
  145. pdfThumbnailScrollView.isHidden = true
  146. pdfThumbnailScrollView.addSubview(pdfThumbnailView)
  147. NSLayoutConstraint.activate([
  148. pdfThumbnailView.topAnchor.constraint(equalTo: pdfThumbnailScrollView.topAnchor),
  149. pdfThumbnailView.bottomAnchor.constraint(equalTo: pdfThumbnailScrollView.bottomAnchor),
  150. pdfThumbnailView.leadingAnchor.constraint(equalTo: pdfThumbnailScrollView.leadingAnchor),
  151. pdfThumbnailView.leadingAnchor.constraint(equalTo: pdfThumbnailScrollView.trailingAnchor, constant: (window?.safeAreaInsets.left ?? 0)),
  152. pdfThumbnailView.widthAnchor.constraint(equalToConstant: thumbnailViewWidth)
  153. ])
  154. let contentViewCenterY = pdfThumbnailView.centerYAnchor.constraint(equalTo: pdfThumbnailScrollView.centerYAnchor)
  155. contentViewCenterY.priority = .defaultLow
  156. let pageCount = CGFloat(pdfDocument?.pageCount ?? 0)
  157. let contentViewHeight = pdfThumbnailView.heightAnchor.constraint(equalToConstant: CGFloat(pageCount * thumbnailViewHeight) + CGFloat(pageCount * thumbnailPadding) + 30)
  158. contentViewHeight.priority = .defaultLow
  159. NSLayoutConstraint.activate([
  160. contentViewCenterY,
  161. contentViewHeight
  162. ])
  163. // COUNTER PDF PAGE VIEW
  164. pageView.translatesAutoresizingMaskIntoConstraints = false
  165. pageView.layer.cornerRadius = 10
  166. pageView.backgroundColor = .systemBackground.withAlphaComponent(
  167. UIAccessibility.isReduceTransparencyEnabled ? 1 : 0.5
  168. )
  169. pdfContainer.addSubview(pageView)
  170. NSLayoutConstraint.activate([
  171. pageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15),
  172. pageView.heightAnchor.constraint(equalToConstant: 30),
  173. pageView.leftAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.leftAnchor, constant: 10)
  174. ])
  175. pageViewWidthAnchor = pageView.widthAnchor.constraint(equalToConstant: 10)
  176. pageViewWidthAnchor?.isActive = true
  177. pageViewLabel.translatesAutoresizingMaskIntoConstraints = false
  178. pageViewLabel.textAlignment = .center
  179. pageViewLabel.textColor = .label
  180. pageView.addSubview(pageViewLabel)
  181. NSLayoutConstraint.activate([
  182. pageViewLabel.topAnchor.constraint(equalTo: pageView.topAnchor),
  183. pageViewLabel.leftAnchor.constraint(equalTo: pageView.leftAnchor),
  184. pageViewLabel.rightAnchor.constraint(equalTo: pageView.rightAnchor),
  185. pageViewLabel.bottomAnchor.constraint(equalTo: pageView.bottomAnchor)
  186. ])
  187. // GESTURE
  188. let tapPdfView = UITapGestureRecognizer(target: self, action: #selector(tapPdfView))
  189. tapPdfView.numberOfTapsRequired = 1
  190. pdfView.addGestureRecognizer(tapPdfView)
  191. // recognize single / double tap
  192. for gesture in pdfView.gestureRecognizers! {
  193. tapPdfView.require(toFail: gesture)
  194. }
  195. let swipePdfView = UISwipeGestureRecognizer(target: self, action: #selector(gestureClosePdfThumbnail))
  196. swipePdfView.direction = .right
  197. swipePdfView.delegate = self
  198. pdfView.addGestureRecognizer(swipePdfView)
  199. let edgePdfView = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(gestureOpenPdfThumbnail))
  200. edgePdfView.edges = .right
  201. edgePdfView.delegate = self
  202. pdfView.addGestureRecognizer(edgePdfView)
  203. let swipePdfThumbnailScrollView = UISwipeGestureRecognizer(target: self, action: #selector(gestureClosePdfThumbnail))
  204. swipePdfThumbnailScrollView.direction = .right
  205. pdfThumbnailScrollView.addGestureRecognizer(swipePdfThumbnailScrollView)
  206. // FUNC
  207. setThumbnailConstraints()
  208. handlePageChange()
  209. showTip()
  210. }
  211. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  212. super.viewWillTransition(to: size, with: coordinator)
  213. tipView?.dismiss()
  214. coordinator.animate(alongsideTransition: { context in
  215. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  216. self.pdfThumbnailScrollView.isHidden = true
  217. }, completion: { context in
  218. self.setThumbnailConstraints()
  219. self.showTip()
  220. })
  221. }
  222. @objc func viewUnload() {
  223. navigationController?.popViewController(animated: true)
  224. }
  225. // MARK: - Tip
  226. func showTip() {
  227. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  228. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCViewerPDFThumbnail) {
  229. self.tipView?.show(forView: self.pdfThumbnailScrollView, withinSuperview: self.pdfContainer)
  230. }
  231. }
  232. }
  233. // MARK: - NotificationCenter
  234. @objc func uploadStartFile(_ notification: NSNotification) {
  235. guard let userInfo = notification.userInfo as NSDictionary?,
  236. let serverUrl = userInfo["serverUrl"] as? String,
  237. serverUrl == self.metadata.serverUrl,
  238. let fileName = userInfo["fileName"] as? String,
  239. fileName == self.metadata.fileName
  240. else { return }
  241. NCActivityIndicator.shared.start()
  242. }
  243. @objc func uploadedFile(_ notification: NSNotification) {
  244. guard let userInfo = notification.userInfo as NSDictionary?,
  245. let serverUrl = userInfo["serverUrl"] as? String,
  246. serverUrl == self.metadata.serverUrl,
  247. let fileName = userInfo["fileName"] as? String,
  248. fileName == self.metadata.fileName,
  249. let error = userInfo["error"] as? NKError
  250. else {
  251. return
  252. }
  253. NCActivityIndicator.shared.stop()
  254. if error == .success {
  255. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  256. pdfView.document = pdfDocument
  257. pdfView.layoutDocumentView()
  258. }
  259. }
  260. @objc func favoriteFile(_ notification: NSNotification) {
  261. guard let userInfo = notification.userInfo as NSDictionary?,
  262. let ocId = userInfo["ocId"] as? String,
  263. ocId == self.metadata.ocId,
  264. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  265. else { return }
  266. self.metadata = metadata
  267. }
  268. @objc func moveFile(_ notification: NSNotification) {
  269. guard let userInfo = notification.userInfo as NSDictionary?,
  270. let ocId = userInfo["ocId"] as? String,
  271. ocId == self.metadata.ocId,
  272. let ocIdNew = userInfo["ocIdNew"] as? String,
  273. let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocIdNew)
  274. else { return }
  275. self.metadata = metadataNew
  276. }
  277. @objc func deleteFile(_ notification: NSNotification) {
  278. guard let userInfo = notification.userInfo as NSDictionary?,
  279. let ocId = userInfo["ocId"] as? [String],
  280. let error = userInfo["error"] as? NKError
  281. else { return }
  282. if error == .success, let ocId = ocId.first, metadata.ocId == ocId {
  283. viewUnload()
  284. }
  285. }
  286. @objc func renameFile(_ notification: NSNotification) {
  287. guard let userInfo = notification.userInfo as NSDictionary?,
  288. let ocId = userInfo["ocId"] as? String,
  289. ocId == self.metadata.ocId,
  290. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  291. else { return }
  292. self.metadata = metadata
  293. navigationItem.title = metadata.fileNameView
  294. }
  295. @objc func searchText() {
  296. let viewerPDFSearch = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateViewController(withIdentifier: "NCViewerPDFSearch") as! NCViewerPDFSearch
  297. viewerPDFSearch.delegate = self
  298. viewerPDFSearch.pdfDocument = pdfDocument
  299. let navigaionController = UINavigationController(rootViewController: viewerPDFSearch)
  300. self.present(navigaionController, animated: true)
  301. }
  302. @objc func goToPage() {
  303. guard let pdfDocument = pdfView.document else { return }
  304. let alertMessage = NSString(format: NSLocalizedString("_this_document_has_%@_pages_", comment: "") as NSString, "\(pdfDocument.pageCount)") as String
  305. let alertController = UIAlertController(title: NSLocalizedString("_go_to_page_", comment: ""), message: alertMessage, preferredStyle: .alert)
  306. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  307. alertController.addTextField(configurationHandler: { textField in
  308. textField.placeholder = NSLocalizedString("_page_", comment: "")
  309. textField.keyboardType = .decimalPad
  310. })
  311. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { [unowned self] _ in
  312. if let pageLabel = alertController.textFields?.first?.text {
  313. self.selectPage(with: pageLabel)
  314. }
  315. }))
  316. self.present(alertController, animated: true)
  317. }
  318. // MARK: - Action
  319. @objc func openMenuMore() {
  320. if imageIcon == nil { imageIcon = UIImage(named: "file_pdf") }
  321. NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: false, imageIcon: imageIcon)
  322. }
  323. // MARK: - Gesture Recognizer
  324. @objc func tapPdfView(_ recognizer: UITapGestureRecognizer) {
  325. if pdfThumbnailScrollView.isHidden {
  326. self.pdfContainerTopAnchor?.isActive = false
  327. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  328. navigationController?.setNavigationBarHidden(false, animated: true)
  329. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.topAnchor)
  330. } else {
  331. navigationController?.setNavigationBarHidden(true, animated: true)
  332. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
  333. }
  334. self.pdfContainerTopAnchor?.isActive = true
  335. }
  336. handlePageChange()
  337. closePdfThumbnail()
  338. }
  339. @objc func gestureClosePdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  340. if recognizer.state == .recognized {
  341. closePdfThumbnail()
  342. }
  343. }
  344. @objc func gestureOpenPdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  345. guard let pdfDocument = pdfView.document, !pdfDocument.isLocked else { return }
  346. OpenPdfThumbnail()
  347. }
  348. // MARK: - OPEN / CLOSE Thumbnail
  349. func OpenPdfThumbnail() {
  350. if let tipView = self.tipView {
  351. tipView.dismiss()
  352. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  353. self.tipView = nil
  354. }
  355. self.pdfThumbnailScrollView.isHidden = false
  356. self.pdfThumbnailScrollViewWidthAnchor?.constant = thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0)
  357. self.pdfThumbnailScrollViewTopAnchor?.isActive = false
  358. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  359. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.view.topAnchor)
  360. } else {
  361. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.pdfContainer.safeAreaLayoutGuide.topAnchor)
  362. }
  363. self.pdfThumbnailScrollViewTopAnchor?.isActive = true
  364. UIView.animate(withDuration: animateDuration, animations: {
  365. self.pdfThumbnailScrollViewTrailingAnchor?.constant = 0
  366. self.pdfContainer.layoutIfNeeded()
  367. })
  368. }
  369. func closePdfThumbnail() {
  370. guard !self.pdfThumbnailScrollView.isHidden else { return }
  371. UIView.animate(withDuration: animateDuration) {
  372. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  373. self.pdfContainer.layoutIfNeeded()
  374. } completion: { _ in
  375. self.pdfThumbnailScrollView.isHidden = true
  376. }
  377. }
  378. // MARK: -
  379. func setThumbnailConstraints() {
  380. let widthThumbnail = thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0)
  381. UIView.animate(withDuration: animateDuration, animations: {
  382. // Close
  383. self.pdfThumbnailScrollView.isHidden = true
  384. self.pdfThumbnailScrollViewTrailingAnchor?.constant = widthThumbnail
  385. self.pdfThumbnailScrollViewWidthAnchor?.constant = widthThumbnail
  386. self.pdfContainer.layoutIfNeeded()
  387. self.pdfView.autoScales = true
  388. })
  389. }
  390. @objc func handlePageChange() {
  391. guard let curPage = pdfView.currentPage?.pageRef?.pageNumber else { pageView.alpha = 0; return }
  392. guard let totalPages = pdfView.document?.pageCount else { return }
  393. let visibleRect = CGRect(x: pdfThumbnailScrollView.contentOffset.x, y: pdfThumbnailScrollView.contentOffset.y, width: pdfThumbnailScrollView.bounds.size.width, height: pdfThumbnailScrollView.bounds.size.height)
  394. let centerPoint = CGPoint(x: visibleRect.size.width/2, y: visibleRect.size.height/2)
  395. let currentPageY = CGFloat(curPage) * thumbnailViewHeight + CGFloat(curPage) * thumbnailPadding
  396. var gotoY = currentPageY - centerPoint.y
  397. let startY = visibleRect.origin.y < 0 ? 0 : (visibleRect.origin.y + thumbnailViewHeight)
  398. let endY = visibleRect.origin.y + visibleRect.height
  399. if currentPageY < startY {
  400. if gotoY < 0 { gotoY = 0 }
  401. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  402. } else if currentPageY > endY {
  403. if gotoY > pdfThumbnailView.frame.height - visibleRect.height {
  404. gotoY = pdfThumbnailView.frame.height - visibleRect.height
  405. }
  406. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  407. } else {
  408. print("visible")
  409. }
  410. pageView.alpha = 1
  411. pageViewLabel.text = String(curPage) + " " + NSLocalizedString("_of_", comment: "") + " " + String(totalPages)
  412. pageViewWidthAnchor?.constant = pageViewLabel.intrinsicContentSize.width + 10
  413. UIView.animate(withDuration: 1.0, delay: 2.5, animations: {
  414. self.pageView.alpha = 0
  415. })
  416. }
  417. func searchPdfSelection(_ pdfSelection: PDFSelection) {
  418. removeAllAnnotations()
  419. pdfSelection.pages.forEach { page in
  420. let highlight = PDFAnnotation(bounds: pdfSelection.bounds(for: page), forType: .highlight, withProperties: nil)
  421. highlight.endLineStyle = .square
  422. highlight.color = .systemBlue
  423. page.addAnnotation(highlight)
  424. }
  425. if let page = pdfSelection.pages.first {
  426. pdfView.go(to: page)
  427. }
  428. handlePageChange()
  429. }
  430. private func selectPage(with label: String) {
  431. guard let pdf = pdfView.document else { return }
  432. if let pageNr = Int(label) {
  433. if pageNr > 0 && pageNr <= pdf.pageCount {
  434. if let page = pdf.page(at: pageNr - 1) {
  435. self.pdfView.go(to: page)
  436. }
  437. } else {
  438. let alertController = UIAlertController(title: NSLocalizedString("_invalid_page_", comment: ""),
  439. message: NSLocalizedString("_the_entered_page_number_does_not_exist_", comment: ""),
  440. preferredStyle: .alert)
  441. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
  442. self.present(alertController, animated: true, completion: nil)
  443. }
  444. }
  445. }
  446. func removeAllAnnotations() {
  447. guard let document = pdfDocument else { return }
  448. for i in 0..<document.pageCount {
  449. if let page = document.page(at: i) {
  450. let annotations = page.annotations
  451. for annotation in annotations {
  452. page.removeAnnotation(annotation)
  453. }
  454. }
  455. }
  456. }
  457. }
  458. extension NCViewerPDF: UIGestureRecognizerDelegate {
  459. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  460. return true
  461. }
  462. }
  463. extension NCViewerPDF: EasyTipViewDelegate {
  464. func easyTipViewDidTap(_ tipView: EasyTipView) {
  465. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  466. }
  467. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  468. }