NCViewerPDF.swift 26 KB

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