NCViewerPDF.swift 27 KB

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