NCViewerPDF.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. // NOTIFIFICATION
  86. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  87. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  88. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  89. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  90. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  91. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  92. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  93. NotificationCenter.default.addObserver(self, selector: #selector(searchText), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  94. NotificationCenter.default.addObserver(self, selector: #selector(goToPage), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  95. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChange), name: Notification.Name.PDFViewPageChanged, object: nil)
  96. }
  97. deinit {
  98. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  99. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  100. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  101. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  102. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  103. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  104. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  105. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  106. NotificationCenter.default.removeObserver(self, name: Notification.Name.PDFViewPageChanged, object: nil)
  107. }
  108. override func viewDidAppear(_ animated: Bool) {
  109. super.viewDidAppear(animated)
  110. // PDF VIEW
  111. pdfView.translatesAutoresizingMaskIntoConstraints = false
  112. pdfView.document = pdfDocument
  113. pdfView.document?.page(at: 0)?.annotations.forEach({
  114. $0.isReadOnly = true
  115. })
  116. pdfView.autoScales = true
  117. pdfView.displayMode = .singlePageContinuous
  118. pdfView.displayDirection = .vertical
  119. pdfContainer.addSubview(pdfView)
  120. NSLayoutConstraint.activate([
  121. pdfView.topAnchor.constraint(equalTo: pdfContainer.topAnchor),
  122. pdfView.leadingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.leadingAnchor),
  123. pdfView.trailingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.trailingAnchor),
  124. pdfView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
  125. ])
  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. // FUNC
  207. setThumbnailConstraints()
  208. handlePageChange()
  209. showTip()
  210. }
  211. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  212. super.viewWillTransition(to: size, with: coordinator)
  213. tipView?.dismiss()
  214. coordinator.animate(alongsideTransition: { context in
  215. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  216. self.pdfThumbnailScrollView.isHidden = true
  217. }, completion: { context in
  218. self.setThumbnailConstraints()
  219. self.showTip()
  220. })
  221. }
  222. @objc func viewUnload() {
  223. navigationController?.popViewController(animated: true)
  224. }
  225. // MARK: - Tip
  226. func showTip() {
  227. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  228. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCViewerPDFThumbnail) {
  229. self.tipView?.show(forView: self.pdfThumbnailScrollView, withinSuperview: self.pdfContainer)
  230. }
  231. }
  232. }
  233. // MARK: - NotificationCenter
  234. @objc func uploadStartFile(_ notification: NSNotification) {
  235. guard let userInfo = notification.userInfo as NSDictionary?,
  236. let serverUrl = userInfo["serverUrl"] as? String,
  237. serverUrl == self.metadata.serverUrl,
  238. let fileName = userInfo["fileName"] as? String,
  239. fileName == self.metadata.fileName
  240. else { return }
  241. NCActivityIndicator.shared.start()
  242. }
  243. @objc func uploadedFile(_ notification: NSNotification) {
  244. guard let userInfo = notification.userInfo as NSDictionary?,
  245. let serverUrl = userInfo["serverUrl"] as? String,
  246. serverUrl == self.metadata.serverUrl,
  247. let fileName = userInfo["fileName"] as? String,
  248. fileName == self.metadata.fileName,
  249. let error = userInfo["error"] as? NKError
  250. else {
  251. return
  252. }
  253. NCActivityIndicator.shared.stop()
  254. if error == .success {
  255. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  256. pdfView.document = pdfDocument
  257. pdfView.layoutDocumentView()
  258. }
  259. }
  260. @objc func favoriteFile(_ notification: NSNotification) {
  261. guard let userInfo = notification.userInfo as NSDictionary?,
  262. let ocId = userInfo["ocId"] as? String,
  263. ocId == self.metadata.ocId,
  264. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  265. else { return }
  266. self.metadata = metadata
  267. }
  268. @objc func moveFile(_ notification: NSNotification) {
  269. guard let userInfo = notification.userInfo as NSDictionary?,
  270. let ocId = userInfo["ocId"] as? String,
  271. ocId == self.metadata.ocId,
  272. let ocIdNew = userInfo["ocIdNew"] as? String,
  273. let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocIdNew)
  274. else { return }
  275. self.metadata = metadataNew
  276. }
  277. @objc func deleteFile(_ notification: NSNotification) {
  278. guard let userInfo = notification.userInfo as NSDictionary?,
  279. let ocId = userInfo["ocId"] as? [String],
  280. let error = userInfo["error"] as? NKError
  281. else { return }
  282. if error == .success, let ocId = ocId.first, metadata.ocId == ocId {
  283. viewUnload()
  284. }
  285. }
  286. @objc func renameFile(_ notification: NSNotification) {
  287. guard let userInfo = notification.userInfo as NSDictionary?,
  288. let ocId = userInfo["ocId"] as? String,
  289. ocId == self.metadata.ocId,
  290. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  291. else { return }
  292. self.metadata = metadata
  293. navigationItem.title = metadata.fileNameView
  294. }
  295. @objc func searchText() {
  296. let viewerPDFSearch = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateViewController(withIdentifier: "NCViewerPDFSearch") as! NCViewerPDFSearch
  297. viewerPDFSearch.delegate = self
  298. viewerPDFSearch.pdfDocument = pdfDocument
  299. let navigaionController = UINavigationController(rootViewController: viewerPDFSearch)
  300. self.present(navigaionController, animated: true)
  301. }
  302. @objc func goToPage() {
  303. guard let pdfDocument = pdfView.document else { return }
  304. let alertMessage = NSString(format: NSLocalizedString("_this_document_has_%@_pages_", comment: "") as NSString, "\(pdfDocument.pageCount)") as String
  305. let alertController = UIAlertController(title: NSLocalizedString("_go_to_page_", comment: ""), message: alertMessage, preferredStyle: .alert)
  306. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  307. alertController.addTextField(configurationHandler: { textField in
  308. textField.placeholder = NSLocalizedString("_page_", comment: "")
  309. textField.keyboardType = .decimalPad
  310. })
  311. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { [unowned self] _ in
  312. if let pageLabel = alertController.textFields?.first?.text {
  313. self.selectPage(with: pageLabel)
  314. }
  315. }))
  316. self.present(alertController, animated: true)
  317. }
  318. // MARK: - Action
  319. @objc func openMenuMore() {
  320. if imageIcon == nil { imageIcon = UIImage(named: "file_pdf") }
  321. NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: false, imageIcon: imageIcon)
  322. }
  323. // MARK: - Gesture Recognizer
  324. @objc func tapPdfView(_ recognizer: UITapGestureRecognizer) {
  325. if pdfThumbnailScrollView.isHidden {
  326. if navigationController?.isNavigationBarHidden ?? false {
  327. navigationController?.setNavigationBarHidden(false, animated: true)
  328. } else {
  329. navigationController?.setNavigationBarHidden(true, animated: true)
  330. }
  331. }
  332. UIView.animate(withDuration: animateDuration) {
  333. self.pdfContainerTopAnchor?.isActive = false
  334. } completion: { _ in
  335. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  336. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.topAnchor)
  337. } else {
  338. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
  339. }
  340. self.pdfContainerTopAnchor?.isActive = true
  341. }
  342. handlePageChange()
  343. closePdfThumbnail()
  344. }
  345. @objc func gestureClosePdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  346. if recognizer.state == .recognized {
  347. closePdfThumbnail()
  348. }
  349. }
  350. @objc func gestureOpenPdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  351. guard let pdfDocument = pdfView.document, !pdfDocument.isLocked else { return }
  352. OpenPdfThumbnail()
  353. }
  354. // MARK: - OPEN / CLOSE Thumbnail
  355. func OpenPdfThumbnail() {
  356. if let tipView = self.tipView {
  357. tipView.dismiss()
  358. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  359. self.tipView = nil
  360. }
  361. self.pdfThumbnailScrollView.isHidden = false
  362. self.pdfThumbnailScrollViewWidthAnchor?.constant = thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0)
  363. self.pdfThumbnailScrollViewTopAnchor?.isActive = false
  364. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  365. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.view.topAnchor)
  366. } else {
  367. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.pdfContainer.safeAreaLayoutGuide.topAnchor)
  368. }
  369. self.pdfThumbnailScrollViewTopAnchor?.isActive = true
  370. UIView.animate(withDuration: animateDuration, animations: {
  371. self.pdfThumbnailScrollViewTrailingAnchor?.constant = 0
  372. self.pdfContainer.layoutIfNeeded()
  373. })
  374. }
  375. func closePdfThumbnail() {
  376. guard !self.pdfThumbnailScrollView.isHidden else { return }
  377. UIView.animate(withDuration: animateDuration) {
  378. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  379. self.pdfContainer.layoutIfNeeded()
  380. } completion: { _ in
  381. self.pdfThumbnailScrollView.isHidden = true
  382. }
  383. }
  384. // MARK: -
  385. func setThumbnailConstraints() {
  386. let widthThumbnail = thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0)
  387. UIView.animate(withDuration: animateDuration, animations: {
  388. // Close
  389. self.pdfThumbnailScrollView.isHidden = true
  390. self.pdfThumbnailScrollViewTrailingAnchor?.constant = widthThumbnail
  391. self.pdfThumbnailScrollViewWidthAnchor?.constant = widthThumbnail
  392. self.pdfContainer.layoutIfNeeded()
  393. self.pdfView.autoScales = true
  394. })
  395. }
  396. @objc func handlePageChange() {
  397. guard let curPage = pdfView.currentPage?.pageRef?.pageNumber else { pageView.alpha = 0; return }
  398. guard let totalPages = pdfView.document?.pageCount else { return }
  399. let visibleRect = CGRect(x: pdfThumbnailScrollView.contentOffset.x, y: pdfThumbnailScrollView.contentOffset.y, width: pdfThumbnailScrollView.bounds.size.width, height: pdfThumbnailScrollView.bounds.size.height)
  400. let centerPoint = CGPoint(x: visibleRect.size.width/2, y: visibleRect.size.height/2)
  401. let currentPageY = CGFloat(curPage) * thumbnailViewHeight + CGFloat(curPage) * thumbnailPadding
  402. var gotoY = currentPageY - centerPoint.y
  403. let startY = visibleRect.origin.y < 0 ? 0 : (visibleRect.origin.y + thumbnailViewHeight)
  404. let endY = visibleRect.origin.y + visibleRect.height
  405. if currentPageY < startY {
  406. if gotoY < 0 { gotoY = 0 }
  407. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  408. } else if currentPageY > endY {
  409. if gotoY > pdfThumbnailView.frame.height - visibleRect.height {
  410. gotoY = pdfThumbnailView.frame.height - visibleRect.height
  411. }
  412. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  413. } else {
  414. print("visible")
  415. }
  416. pageView.alpha = 1
  417. pageViewLabel.text = String(curPage) + " " + NSLocalizedString("_of_", comment: "") + " " + String(totalPages)
  418. pageViewWidthAnchor?.constant = pageViewLabel.intrinsicContentSize.width + 10
  419. UIView.animate(withDuration: 1.0, delay: 2.5, animations: {
  420. self.pageView.alpha = 0
  421. })
  422. }
  423. func searchPdfSelection(_ pdfSelection: PDFSelection) {
  424. removeAllAnnotations()
  425. pdfSelection.pages.forEach { page in
  426. let highlight = PDFAnnotation(bounds: pdfSelection.bounds(for: page), forType: .highlight, withProperties: nil)
  427. highlight.endLineStyle = .square
  428. highlight.color = .systemBlue
  429. page.addAnnotation(highlight)
  430. }
  431. if let page = pdfSelection.pages.first {
  432. pdfView.go(to: page)
  433. }
  434. handlePageChange()
  435. }
  436. private func selectPage(with label: String) {
  437. guard let pdf = pdfView.document else { return }
  438. if let pageNr = Int(label) {
  439. if pageNr > 0 && pageNr <= pdf.pageCount {
  440. if let page = pdf.page(at: pageNr - 1) {
  441. self.pdfView.go(to: page)
  442. }
  443. } else {
  444. let alertController = UIAlertController(title: NSLocalizedString("_invalid_page_", comment: ""),
  445. message: NSLocalizedString("_the_entered_page_number_does_not_exist_", comment: ""),
  446. preferredStyle: .alert)
  447. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
  448. self.present(alertController, animated: true, completion: nil)
  449. }
  450. }
  451. }
  452. func removeAllAnnotations() {
  453. guard let document = pdfDocument else { return }
  454. for i in 0..<document.pageCount {
  455. if let page = document.page(at: i) {
  456. let annotations = page.annotations
  457. for annotation in annotations {
  458. page.removeAnnotation(annotation)
  459. }
  460. }
  461. }
  462. }
  463. }
  464. extension NCViewerPDF: UIGestureRecognizerDelegate {
  465. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  466. return true
  467. }
  468. }
  469. extension NCViewerPDF: EasyTipViewDelegate {
  470. func easyTipViewDidTap(_ tipView: EasyTipView) {
  471. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  472. }
  473. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  474. }