NCViewerPDF.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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 url: URL?
  31. var titleView: String?
  32. var imageIcon: UIImage?
  33. private var filePath = ""
  34. private var pdfView = PDFView()
  35. private var pdfThumbnailScrollView = UIScrollView()
  36. private var pdfThumbnailView = PDFThumbnailView()
  37. private var pdfDocument: PDFDocument?
  38. private let pageView = UIView()
  39. private let pageViewLabel = UILabel()
  40. private var tipView: EasyTipView?
  41. private let thumbnailViewHeight: CGFloat = 70
  42. private let thumbnailViewWidth: CGFloat = 80
  43. private let thumbnailPadding: CGFloat = 2
  44. private let animateDuration: TimeInterval = 0.3
  45. private let window = UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.first { $0.isKeyWindow }
  46. private var defaultBackgroundColor: UIColor = .clear
  47. private var pdfContainerTopAnchor: NSLayoutConstraint?
  48. private var pdfThumbnailScrollViewTopAnchor: NSLayoutConstraint?
  49. private var pdfThumbnailScrollViewTrailingAnchor: NSLayoutConstraint?
  50. private var pdfThumbnailScrollViewWidthAnchor: NSLayoutConstraint?
  51. private var pageViewWidthAnchor: NSLayoutConstraint?
  52. // MARK: - View Life Cycle
  53. required init?(coder aDecoder: NSCoder) {
  54. super.init(coder: aDecoder)
  55. }
  56. override func viewDidLoad() {
  57. if let url = self.url {
  58. pdfDocument = PDFDocument(url: url)
  59. } else if let metadata = self.metadata {
  60. filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  61. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  62. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
  63. }
  64. defaultBackgroundColor = pdfView.backgroundColor
  65. view.backgroundColor = defaultBackgroundColor
  66. navigationController?.navigationBar.prefersLargeTitles = false
  67. navigationItem.title = titleView
  68. // TIP
  69. var preferences = EasyTipView.Preferences()
  70. preferences.drawing.foregroundColor = .white
  71. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  72. preferences.drawing.textAlignment = .left
  73. preferences.drawing.arrowPosition = .right
  74. preferences.drawing.cornerRadius = 10
  75. preferences.positioning.bubbleInsets.right = window?.safeAreaInsets.right ?? 0
  76. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  77. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  78. preferences.animating.showInitialAlpha = 0
  79. preferences.animating.showDuration = 1.5
  80. preferences.animating.dismissDuration = 1.5
  81. tipView = EasyTipView(text: NSLocalizedString("_tip_pdf_thumbnails_", comment: ""), preferences: preferences, delegate: self)
  82. // PDF CONTAINER
  83. pdfContainer.translatesAutoresizingMaskIntoConstraints = false
  84. pdfContainerTopAnchor = pdfContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
  85. pdfContainerTopAnchor?.isActive = true
  86. NSLayoutConstraint.activate([
  87. pdfContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  88. pdfContainer.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
  89. pdfContainer.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  90. ])
  91. // PDF VIEW
  92. pdfView.translatesAutoresizingMaskIntoConstraints = false
  93. pdfView.document = pdfDocument
  94. pdfView.document?.page(at: 0)?.annotations.forEach({
  95. $0.isReadOnly = true
  96. })
  97. pdfView.autoScales = true
  98. pdfView.displayMode = .singlePageContinuous
  99. pdfView.displayDirection = .vertical
  100. pdfContainer.addSubview(pdfView)
  101. NSLayoutConstraint.activate([
  102. pdfView.topAnchor.constraint(equalTo: pdfContainer.topAnchor),
  103. pdfView.leadingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.leadingAnchor),
  104. pdfView.trailingAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.trailingAnchor),
  105. pdfView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
  106. ])
  107. // MODAL
  108. if self.navigationController?.presentingViewController != nil {
  109. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_close_", comment: ""), style: .plain, target: self, action: #selector(viewDismiss))
  110. }
  111. // NOTIFIFICATION
  112. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(searchText), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(goToPage), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChange), name: Notification.Name.PDFViewPageChanged, object: nil)
  122. }
  123. deinit {
  124. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  125. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  126. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  127. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  128. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  129. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  130. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  131. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  132. NotificationCenter.default.removeObserver(self, name: Notification.Name.PDFViewPageChanged, object: nil)
  133. }
  134. override func viewWillAppear(_ animated: Bool) {
  135. super.viewWillAppear(animated)
  136. // PDF THUMBNAIL
  137. pdfThumbnailScrollView.translatesAutoresizingMaskIntoConstraints = false
  138. pdfThumbnailScrollView.backgroundColor = defaultBackgroundColor
  139. pdfThumbnailScrollView.showsVerticalScrollIndicator = false
  140. pdfContainer.addSubview(pdfThumbnailScrollView)
  141. NSLayoutConstraint.activate([
  142. pdfThumbnailScrollView.bottomAnchor.constraint(equalTo: pdfContainer.bottomAnchor)
  143. ])
  144. pdfThumbnailScrollViewTopAnchor = pdfThumbnailScrollView.topAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.topAnchor)
  145. pdfThumbnailScrollViewTopAnchor?.isActive = true
  146. pdfThumbnailScrollViewTrailingAnchor = pdfThumbnailScrollView.trailingAnchor.constraint(equalTo: pdfContainer.trailingAnchor, constant: thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0))
  147. pdfThumbnailScrollViewTrailingAnchor?.isActive = true
  148. pdfThumbnailScrollViewWidthAnchor = pdfThumbnailScrollView.widthAnchor.constraint(equalToConstant: thumbnailViewWidth)
  149. pdfThumbnailScrollViewWidthAnchor?.isActive = true
  150. pdfThumbnailView.translatesAutoresizingMaskIntoConstraints = false
  151. pdfThumbnailView.pdfView = pdfView
  152. pdfThumbnailView.layoutMode = .vertical
  153. pdfThumbnailView.thumbnailSize = CGSize(width: thumbnailViewHeight, height: thumbnailViewHeight)
  154. pdfThumbnailView.backgroundColor = .clear
  155. pdfThumbnailScrollView.isHidden = true
  156. pdfThumbnailScrollView.addSubview(pdfThumbnailView)
  157. NSLayoutConstraint.activate([
  158. pdfThumbnailView.topAnchor.constraint(equalTo: pdfThumbnailScrollView.topAnchor),
  159. pdfThumbnailView.bottomAnchor.constraint(equalTo: pdfThumbnailScrollView.bottomAnchor),
  160. pdfThumbnailView.leadingAnchor.constraint(equalTo: pdfThumbnailScrollView.leadingAnchor),
  161. pdfThumbnailView.leadingAnchor.constraint(equalTo: pdfThumbnailScrollView.trailingAnchor, constant: (window?.safeAreaInsets.left ?? 0)),
  162. pdfThumbnailView.widthAnchor.constraint(equalToConstant: thumbnailViewWidth)
  163. ])
  164. let contentViewCenterY = pdfThumbnailView.centerYAnchor.constraint(equalTo: pdfThumbnailScrollView.centerYAnchor)
  165. contentViewCenterY.priority = .defaultLow
  166. let pageCount = CGFloat(pdfDocument?.pageCount ?? 0)
  167. let contentViewHeight = pdfThumbnailView.heightAnchor.constraint(equalToConstant: CGFloat(pageCount * thumbnailViewHeight) + CGFloat(pageCount * thumbnailPadding) + 30)
  168. contentViewHeight.priority = .defaultLow
  169. NSLayoutConstraint.activate([
  170. contentViewCenterY,
  171. contentViewHeight
  172. ])
  173. // COUNTER PDF PAGE VIEW
  174. pageView.translatesAutoresizingMaskIntoConstraints = false
  175. pageView.layer.cornerRadius = 10
  176. pageView.backgroundColor = .systemBackground.withAlphaComponent(
  177. UIAccessibility.isReduceTransparencyEnabled ? 1 : 0.5
  178. )
  179. pdfContainer.addSubview(pageView)
  180. NSLayoutConstraint.activate([
  181. pageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15),
  182. pageView.heightAnchor.constraint(equalToConstant: 30),
  183. pageView.leftAnchor.constraint(equalTo: pdfContainer.safeAreaLayoutGuide.leftAnchor, constant: 10)
  184. ])
  185. pageViewWidthAnchor = pageView.widthAnchor.constraint(equalToConstant: 10)
  186. pageViewWidthAnchor?.isActive = true
  187. pageViewLabel.translatesAutoresizingMaskIntoConstraints = false
  188. pageViewLabel.textAlignment = .center
  189. pageViewLabel.textColor = .label
  190. pageView.addSubview(pageViewLabel)
  191. NSLayoutConstraint.activate([
  192. pageViewLabel.topAnchor.constraint(equalTo: pageView.topAnchor),
  193. pageViewLabel.leftAnchor.constraint(equalTo: pageView.leftAnchor),
  194. pageViewLabel.rightAnchor.constraint(equalTo: pageView.rightAnchor),
  195. pageViewLabel.bottomAnchor.constraint(equalTo: pageView.bottomAnchor)
  196. ])
  197. // GESTURE
  198. let tapPdfView = UITapGestureRecognizer(target: self, action: #selector(tapPdfView))
  199. tapPdfView.numberOfTapsRequired = 1
  200. pdfView.addGestureRecognizer(tapPdfView)
  201. // recognize single / double tap
  202. for gesture in pdfView.gestureRecognizers! {
  203. tapPdfView.require(toFail: gesture)
  204. }
  205. let swipePdfView = UISwipeGestureRecognizer(target: self, action: #selector(gestureClosePdfThumbnail))
  206. swipePdfView.direction = .right
  207. swipePdfView.delegate = self
  208. pdfView.addGestureRecognizer(swipePdfView)
  209. let edgePdfView = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(gestureOpenPdfThumbnail))
  210. edgePdfView.edges = .right
  211. edgePdfView.delegate = self
  212. pdfView.addGestureRecognizer(edgePdfView)
  213. let swipePdfThumbnailScrollView = UISwipeGestureRecognizer(target: self, action: #selector(gestureClosePdfThumbnail))
  214. swipePdfThumbnailScrollView.direction = .right
  215. pdfThumbnailScrollView.addGestureRecognizer(swipePdfThumbnailScrollView)
  216. handlePageChange()
  217. }
  218. override func viewDidAppear(_ animated: Bool) {
  219. super.viewDidAppear(animated)
  220. showTip()
  221. }
  222. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  223. super.viewWillTransition(to: size, with: coordinator)
  224. tipView?.dismiss()
  225. coordinator.animate(alongsideTransition: { context in
  226. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  227. self.pdfThumbnailScrollView.isHidden = true
  228. }, completion: { context in
  229. self.pdfView.autoScales = true
  230. })
  231. }
  232. @objc func viewUnload() {
  233. navigationController?.popViewController(animated: true)
  234. }
  235. @objc func viewDismiss() {
  236. self.dismiss(animated: true)
  237. }
  238. // MARK: - Tip
  239. func showTip() {
  240. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  241. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCViewerPDFThumbnail) {
  242. self.tipView?.show(forView: self.pdfThumbnailScrollView, withinSuperview: self.pdfContainer)
  243. }
  244. }
  245. }
  246. // MARK: - NotificationCenter
  247. @objc func uploadStartFile(_ notification: NSNotification) {
  248. guard let userInfo = notification.userInfo as NSDictionary?,
  249. let serverUrl = userInfo["serverUrl"] as? String,
  250. serverUrl == self.metadata?.serverUrl,
  251. let fileName = userInfo["fileName"] as? String,
  252. fileName == self.metadata?.fileName
  253. else { return }
  254. NCActivityIndicator.shared.start()
  255. }
  256. @objc func uploadedFile(_ notification: NSNotification) {
  257. guard let userInfo = notification.userInfo as NSDictionary?,
  258. let serverUrl = userInfo["serverUrl"] as? String,
  259. serverUrl == self.metadata?.serverUrl,
  260. let fileName = userInfo["fileName"] as? String,
  261. fileName == self.metadata?.fileName,
  262. let error = userInfo["error"] as? NKError
  263. else {
  264. return
  265. }
  266. NCActivityIndicator.shared.stop()
  267. if error == .success {
  268. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  269. pdfView.document = pdfDocument
  270. pdfView.layoutDocumentView()
  271. }
  272. }
  273. @objc func favoriteFile(_ notification: NSNotification) {
  274. guard let userInfo = notification.userInfo as NSDictionary?,
  275. let ocId = userInfo["ocId"] as? String,
  276. ocId == self.metadata?.ocId,
  277. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  278. else { return }
  279. self.metadata = metadata
  280. }
  281. @objc func moveFile(_ notification: NSNotification) {
  282. guard let userInfo = notification.userInfo as NSDictionary?,
  283. let ocId = userInfo["ocId"] as? String,
  284. ocId == self.metadata?.ocId,
  285. let ocIdNew = userInfo["ocIdNew"] as? String,
  286. let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocIdNew)
  287. else { return }
  288. self.metadata = metadataNew
  289. }
  290. @objc func deleteFile(_ notification: NSNotification) {
  291. guard let userInfo = notification.userInfo as NSDictionary?,
  292. let ocId = userInfo["ocId"] as? [String],
  293. let error = userInfo["error"] as? NKError
  294. else { return }
  295. if error == .success,
  296. let ocId = ocId.first,
  297. metadata?.ocId == ocId {
  298. viewUnload()
  299. }
  300. }
  301. @objc func renameFile(_ notification: NSNotification) {
  302. guard let userInfo = notification.userInfo as NSDictionary?,
  303. let ocId = userInfo["ocId"] as? String,
  304. ocId == self.metadata?.ocId,
  305. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  306. else { return }
  307. self.metadata = metadata
  308. navigationItem.title = metadata.fileNameView
  309. }
  310. @objc func searchText() {
  311. let viewerPDFSearch = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateViewController(withIdentifier: "NCViewerPDFSearch") as! NCViewerPDFSearch
  312. viewerPDFSearch.delegate = self
  313. viewerPDFSearch.pdfDocument = pdfDocument
  314. let navigaionController = UINavigationController(rootViewController: viewerPDFSearch)
  315. self.present(navigaionController, animated: true)
  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.shared.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. }