NCViewerPDF.swift 24 KB

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