NCViewerPDF.swift 25 KB

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