NCViewerPDF.swift 25 KB

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