NCViewerPDF.swift 25 KB

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