NCViewerPDF.swift 25 KB

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