NCViewerPDF.swift 25 KB

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