NCViewerPDF.swift 25 KB

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