NCViewerPDF.swift 27 KB

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