NCViewerPDF.swift 24 KB

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