NCViewerPDF.swift 26 KB

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