NCViewerPDF.swift 25 KB

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