NCViewerPDF.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. NCActivityIndicator.shared.stop()
  268. if error == .success {
  269. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  270. pdfView.document = pdfDocument
  271. pdfView.layoutDocumentView()
  272. }
  273. }
  274. @objc func favoriteFile(_ notification: NSNotification) {
  275. guard let userInfo = notification.userInfo as NSDictionary?,
  276. let ocId = userInfo["ocId"] as? String,
  277. ocId == self.metadata?.ocId,
  278. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  279. else { return }
  280. self.metadata = metadata
  281. }
  282. @objc func deleteFile(_ notification: NSNotification) {
  283. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  284. if let ocId = userInfo["ocId"] as? [String],
  285. let ocId = ocId.first,
  286. metadata?.ocId == ocId {
  287. viewUnload()
  288. }
  289. }
  290. @objc func moveFile(_ notification: NSNotification) {
  291. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  292. if let ocIds = userInfo["ocId"] as? [String],
  293. let ocId = ocIds.first,
  294. let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  295. self.metadata = metadataNew
  296. }
  297. }
  298. @objc func renameFile(_ notification: NSNotification) {
  299. guard let userInfo = notification.userInfo as NSDictionary?,
  300. let ocId = userInfo["ocId"] as? String,
  301. ocId == self.metadata?.ocId,
  302. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  303. else { return }
  304. self.metadata = metadata
  305. navigationItem.title = metadata.fileNameView
  306. }
  307. @objc func searchText() {
  308. if let viewerPDFSearch = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateViewController(withIdentifier: "NCViewerPDFSearch") as? NCViewerPDFSearch {
  309. viewerPDFSearch.delegate = self
  310. viewerPDFSearch.pdfDocument = pdfDocument
  311. let navigaionController = UINavigationController(rootViewController: viewerPDFSearch)
  312. self.present(navigaionController, animated: true)
  313. }
  314. }
  315. @objc func goToPage() {
  316. guard let pdfDocument = pdfView.document else { return }
  317. let alertMessage = NSString(format: NSLocalizedString("_this_document_has_%@_pages_", comment: "") as NSString, "\(pdfDocument.pageCount)") as String
  318. let alertController = UIAlertController(title: NSLocalizedString("_go_to_page_", comment: ""), message: alertMessage, preferredStyle: .alert)
  319. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  320. alertController.addTextField(configurationHandler: { textField in
  321. textField.placeholder = NSLocalizedString("_page_", comment: "")
  322. textField.keyboardType = .decimalPad
  323. })
  324. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { [unowned self] _ in
  325. if let pageLabel = alertController.textFields?.first?.text {
  326. self.selectPage(with: pageLabel)
  327. }
  328. }))
  329. self.present(alertController, animated: true)
  330. }
  331. // MARK: - Action
  332. @objc func openMenuMore() {
  333. guard let metadata = self.metadata else { return }
  334. if imageIcon == nil {
  335. imageIcon = UIImage(named: "file_pdf")
  336. }
  337. NCViewer().toggleMenu(viewController: self, metadata: metadata, webView: false, imageIcon: imageIcon)
  338. }
  339. // MARK: - Gesture Recognizer
  340. @objc func tapPdfView(_ recognizer: UITapGestureRecognizer) {
  341. if pdfThumbnailScrollView.isHidden {
  342. if navigationController?.isNavigationBarHidden ?? false {
  343. navigationController?.setNavigationBarHidden(false, animated: true)
  344. } else {
  345. navigationController?.setNavigationBarHidden(true, animated: true)
  346. }
  347. }
  348. UIView.animate(withDuration: 0.0, animations: {
  349. self.pdfContainerTopAnchor?.isActive = false
  350. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  351. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.topAnchor)
  352. } else {
  353. self.pdfContainerTopAnchor = self.pdfContainer.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
  354. }
  355. self.pdfContainerTopAnchor?.isActive = true
  356. })
  357. handlePageChange()
  358. closePdfThumbnail()
  359. }
  360. @objc func gestureClosePdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  361. if recognizer.state == .recognized {
  362. closePdfThumbnail()
  363. }
  364. }
  365. @objc func gestureOpenPdfThumbnail(_ recognizer: UIScreenEdgePanGestureRecognizer) {
  366. guard let pdfDocument = pdfView.document, !pdfDocument.isLocked else { return }
  367. openPdfThumbnail()
  368. }
  369. // MARK: - OPEN / CLOSE Thumbnail
  370. func openPdfThumbnail() {
  371. if let tipView = self.tipView {
  372. tipView.dismiss()
  373. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  374. self.tipView = nil
  375. }
  376. self.pdfThumbnailScrollView.isHidden = false
  377. self.pdfThumbnailScrollViewWidthAnchor?.constant = thumbnailViewWidth + (window?.safeAreaInsets.right ?? 0)
  378. self.pdfThumbnailScrollViewTopAnchor?.isActive = false
  379. if let barHidden = self.navigationController?.isNavigationBarHidden, barHidden {
  380. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.view.topAnchor)
  381. } else {
  382. self.pdfThumbnailScrollViewTopAnchor = self.pdfThumbnailScrollView.topAnchor.constraint(equalTo: self.pdfContainer.safeAreaLayoutGuide.topAnchor)
  383. }
  384. self.pdfThumbnailScrollViewTopAnchor?.isActive = true
  385. UIView.animate(withDuration: animateDuration, animations: {
  386. self.pdfThumbnailScrollViewTrailingAnchor?.constant = 0
  387. self.pdfContainer.layoutIfNeeded()
  388. })
  389. }
  390. func closePdfThumbnail() {
  391. guard !self.pdfThumbnailScrollView.isHidden else { return }
  392. UIView.animate(withDuration: animateDuration) {
  393. self.pdfThumbnailScrollViewTrailingAnchor?.constant = self.thumbnailViewWidth + (self.window?.safeAreaInsets.right ?? 0)
  394. self.pdfContainer.layoutIfNeeded()
  395. } completion: { _ in
  396. self.pdfThumbnailScrollView.isHidden = true
  397. }
  398. }
  399. // MARK: -
  400. @objc func handlePageChange() {
  401. guard let curPage = pdfView.currentPage?.pageRef?.pageNumber else { pageView.alpha = 0; return }
  402. guard let totalPages = pdfView.document?.pageCount else { return }
  403. let visibleRect = CGRect(x: pdfThumbnailScrollView.contentOffset.x, y: pdfThumbnailScrollView.contentOffset.y, width: pdfThumbnailScrollView.bounds.size.width, height: pdfThumbnailScrollView.bounds.size.height)
  404. let centerPoint = CGPoint(x: visibleRect.size.width / 2, y: visibleRect.size.height / 2)
  405. let currentPageY = CGFloat(curPage) * thumbnailViewHeight + CGFloat(curPage) * thumbnailPadding
  406. var gotoY = currentPageY - centerPoint.y
  407. let startY = visibleRect.origin.y < 0 ? 0 : (visibleRect.origin.y + thumbnailViewHeight)
  408. let endY = visibleRect.origin.y + visibleRect.height
  409. if currentPageY < startY {
  410. if gotoY < 0 { gotoY = 0 }
  411. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  412. } else if currentPageY > endY {
  413. if gotoY > pdfThumbnailView.frame.height - visibleRect.height {
  414. gotoY = pdfThumbnailView.frame.height - visibleRect.height
  415. }
  416. pdfThumbnailScrollView.setContentOffset(CGPoint(x: 0, y: gotoY), animated: true)
  417. } else {
  418. print("visible")
  419. }
  420. pageView.alpha = 1
  421. pageViewLabel.text = String(curPage) + " " + NSLocalizedString("_of_", comment: "") + " " + String(totalPages)
  422. pageViewWidthAnchor?.constant = pageViewLabel.intrinsicContentSize.width + 10
  423. UIView.animate(withDuration: 1.0, delay: 2.5, animations: {
  424. self.pageView.alpha = 0
  425. })
  426. }
  427. func searchPdfSelection(_ pdfSelection: PDFSelection) {
  428. removeAllAnnotations()
  429. pdfSelection.pages.forEach { page in
  430. let highlight = PDFAnnotation(bounds: pdfSelection.bounds(for: page), forType: .highlight, withProperties: nil)
  431. highlight.endLineStyle = .square
  432. highlight.color = .systemBlue
  433. page.addAnnotation(highlight)
  434. }
  435. if let page = pdfSelection.pages.first {
  436. pdfView.go(to: page)
  437. }
  438. handlePageChange()
  439. }
  440. private func selectPage(with label: String) {
  441. guard let pdf = pdfView.document else { return }
  442. if let pageNr = Int(label) {
  443. if pageNr > 0 && pageNr <= pdf.pageCount {
  444. if let page = pdf.page(at: pageNr - 1) {
  445. self.pdfView.go(to: page)
  446. }
  447. } else {
  448. let alertController = UIAlertController(title: NSLocalizedString("_invalid_page_", comment: ""),
  449. message: NSLocalizedString("_the_entered_page_number_does_not_exist_", comment: ""),
  450. preferredStyle: .alert)
  451. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
  452. self.present(alertController, animated: true, completion: nil)
  453. }
  454. }
  455. }
  456. func removeAllAnnotations() {
  457. guard let document = pdfDocument else { return }
  458. for i in 0..<document.pageCount {
  459. if let page = document.page(at: i) {
  460. let annotations = page.annotations
  461. for annotation in annotations {
  462. page.removeAnnotation(annotation)
  463. }
  464. }
  465. }
  466. }
  467. }
  468. extension NCViewerPDF: UIGestureRecognizerDelegate {
  469. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  470. return true
  471. }
  472. }
  473. extension NCViewerPDF: EasyTipViewDelegate {
  474. func easyTipViewDidTap(_ tipView: EasyTipView) {
  475. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerPDFThumbnail)
  476. }
  477. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  478. }