NCViewerPDF.swift 26 KB

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