NCViewerPDF.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate {
  26. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  27. var metadata = tableMetadata()
  28. var imageIcon: UIImage?
  29. private var pdfView = PDFView()
  30. private var thumbnailViewHeight: CGFloat = 40
  31. private var pdfThumbnailView = PDFThumbnailView()
  32. private var pdfDocument: PDFDocument?
  33. private let pageView = UIView()
  34. private let pageViewLabel = UILabel()
  35. private var pageViewWidthAnchor: NSLayoutConstraint?
  36. private var filePath = ""
  37. // MARK: - View Life Cycle
  38. required init?(coder aDecoder: NSCoder) {
  39. super.init(coder: aDecoder)
  40. }
  41. override func viewDidLoad() {
  42. filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  43. pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
  44. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  45. pdfView.document = pdfDocument
  46. pdfView.backgroundColor = NCBrandColor.shared.systemBackground
  47. pdfView.displayMode = .singlePageContinuous
  48. pdfView.autoScales = true
  49. pdfView.displayDirection = CCUtility.getPDFDisplayDirection()
  50. pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleBottomMargin]
  51. pdfView.usePageViewController(true, withViewOptions: nil)
  52. view.addSubview(pdfView)
  53. pdfThumbnailView.translatesAutoresizingMaskIntoConstraints = false
  54. pdfThumbnailView.pdfView = pdfView
  55. pdfThumbnailView.layoutMode = .horizontal
  56. pdfThumbnailView.thumbnailSize = CGSize(width: 40, height: thumbnailViewHeight)
  57. pdfThumbnailView.backgroundColor = .clear
  58. // pdfThumbnailView.layer.shadowOffset.height = -5
  59. // pdfThumbnailView.layer.shadowOpacity = 0.25
  60. view.addSubview(pdfThumbnailView)
  61. pdfThumbnailView.heightAnchor.constraint(equalToConstant: thumbnailViewHeight).isActive = true
  62. pdfThumbnailView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
  63. pdfThumbnailView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
  64. pdfThumbnailView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
  65. pageView.translatesAutoresizingMaskIntoConstraints = false
  66. pageView.layer.cornerRadius = 10
  67. pageView.backgroundColor = NCBrandColor.shared.systemBackground.withAlphaComponent(
  68. UIAccessibility.isReduceTransparencyEnabled ? 1 : 0.5
  69. )
  70. view.addSubview(pageView)
  71. pageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
  72. pageViewWidthAnchor = pageView.widthAnchor.constraint(equalToConstant: 10)
  73. pageViewWidthAnchor?.isActive = true
  74. pageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4).isActive = true
  75. pageView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 7).isActive = true
  76. pageViewLabel.translatesAutoresizingMaskIntoConstraints = false
  77. pageViewLabel.textAlignment = .center
  78. pageViewLabel.textColor = NCBrandColor.shared.label
  79. pageView.addSubview(pageViewLabel)
  80. pageViewLabel.leftAnchor.constraint(equalTo: pageView.leftAnchor).isActive = true
  81. pageViewLabel.rightAnchor.constraint(equalTo: pageView.rightAnchor).isActive = true
  82. pageViewLabel.topAnchor.constraint(equalTo: pageView.topAnchor).isActive = true
  83. pageViewLabel.bottomAnchor.constraint(equalTo: pageView.bottomAnchor).isActive = true
  84. pdfView.backgroundColor = NCBrandColor.shared.systemBackground
  85. pdfView.layoutIfNeeded()
  86. handlePageChange()
  87. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))
  88. tapGesture.numberOfTapsRequired = 1
  89. pdfView.addGestureRecognizer(tapGesture)
  90. // recognize single / double tap
  91. for gesture in pdfView.gestureRecognizers! {
  92. tapGesture.require(toFail: gesture)
  93. }
  94. }
  95. override func viewWillAppear(_ animated: Bool) {
  96. super.viewWillAppear(animated)
  97. appDelegate.activeViewController = self
  98. //
  99. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  100. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  101. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  102. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), 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.notificationCenterMenuDetailClose), 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(direction(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuPDFDisplayDirection), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(goToPage), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChange), name: Notification.Name.PDFViewPageChanged, object: nil)
  109. //
  110. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: NCBrandColor.shared.label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
  111. navigationController?.navigationBar.prefersLargeTitles = true
  112. navigationItem.title = metadata.fileNameView
  113. }
  114. override func viewWillDisappear(_ animated: Bool) {
  115. super.viewWillDisappear(animated)
  116. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  117. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  118. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  119. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  120. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  121. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  122. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuSearchTextPDF), object: nil)
  123. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuPDFDisplayDirection), object: nil)
  124. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuGotToPageInPDF), object: nil)
  125. NotificationCenter.default.removeObserver(self, name: Notification.Name.PDFViewPageChanged, object: nil)
  126. }
  127. @objc func viewUnload() {
  128. navigationController?.popViewController(animated: true)
  129. }
  130. // MARK: - NotificationCenter
  131. @objc func uploadedFile(_ notification: NSNotification) {
  132. if let userInfo = notification.userInfo as NSDictionary? {
  133. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId), let errorCode = userInfo["errorCode"] as? Int {
  134. if errorCode == 0 && metadata.ocId == self.metadata.ocId {
  135. pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath))
  136. pdfView.document = pdfDocument
  137. pdfView.layoutDocumentView()
  138. }
  139. }
  140. }
  141. }
  142. @objc func favoriteFile(_ notification: NSNotification) {
  143. if let userInfo = notification.userInfo as NSDictionary? {
  144. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  145. if metadata.ocId == self.metadata.ocId {
  146. self.metadata = metadata
  147. }
  148. }
  149. }
  150. }
  151. @objc func moveFile(_ notification: NSNotification) {
  152. if let userInfo = notification.userInfo as NSDictionary? {
  153. if let ocId = userInfo["ocId"] as? String, let ocIdNew = userInfo["ocIdNew"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId), let metadataNew = NCManageDatabase.shared.getMetadataFromOcId(ocIdNew) {
  154. if metadata.ocId == self.metadata.ocId {
  155. self.metadata = metadataNew
  156. }
  157. }
  158. }
  159. }
  160. @objc func deleteFile(_ notification: NSNotification) {
  161. if let userInfo = notification.userInfo as NSDictionary? {
  162. if let ocId = userInfo["OcId"] as? String {
  163. if ocId == self.metadata.ocId {
  164. viewUnload()
  165. }
  166. }
  167. }
  168. }
  169. @objc func renameFile(_ notification: NSNotification) {
  170. if let userInfo = notification.userInfo as NSDictionary? {
  171. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  172. if metadata.ocId == self.metadata.ocId {
  173. self.metadata = metadata
  174. navigationItem.title = metadata.fileNameView
  175. }
  176. }
  177. }
  178. }
  179. @objc func searchText() {
  180. let viewerPDFSearch = UIStoryboard(name: "NCViewerPDF", bundle: nil).instantiateViewController(withIdentifier: "NCViewerPDFSearch") as! NCViewerPDFSearch
  181. viewerPDFSearch.delegate = self
  182. viewerPDFSearch.pdfDocument = pdfDocument
  183. let navigaionController = UINavigationController(rootViewController: viewerPDFSearch)
  184. self.present(navigaionController, animated: true)
  185. }
  186. @objc func direction(_ notification: NSNotification) {
  187. if let userInfo = notification.userInfo as NSDictionary? {
  188. if let direction = userInfo["direction"] as? PDFDisplayDirection {
  189. pdfView.displayDirection = direction
  190. CCUtility.setPDFDisplayDirection(direction)
  191. handlePageChange()
  192. }
  193. }
  194. }
  195. @objc func goToPage() {
  196. guard let pdfDocument = pdfView.document else { return }
  197. let alertMessage = NSString(format: NSLocalizedString("_this_document_has_%@_pages_", comment: "") as NSString, "\(pdfDocument.pageCount)") as String
  198. let alertController = UIAlertController(title: NSLocalizedString("_go_to_page_", comment: ""), message: alertMessage, preferredStyle: .alert)
  199. alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  200. alertController.addTextField(configurationHandler: { textField in
  201. textField.placeholder = NSLocalizedString("_page_", comment: "")
  202. textField.keyboardType = .decimalPad
  203. })
  204. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { [unowned self] _ in
  205. if let pageLabel = alertController.textFields?.first?.text {
  206. self.selectPage(with: pageLabel)
  207. }
  208. }))
  209. self.present(alertController, animated: true)
  210. }
  211. // MARK: - Action
  212. @objc func openMenuMore() {
  213. if imageIcon == nil { imageIcon = UIImage(named: "file_pdf") }
  214. NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: false, imageIcon: imageIcon)
  215. }
  216. // MARK: - Gesture Recognizer
  217. @objc func didTap(_ recognizer: UITapGestureRecognizer) {
  218. if navigationController?.isNavigationBarHidden ?? false {
  219. navigationController?.setNavigationBarHidden(false, animated: false)
  220. pdfThumbnailView.isHidden = false
  221. pdfView.backgroundColor = NCBrandColor.shared.systemBackground
  222. } else {
  223. let point = recognizer.location(in: pdfView)
  224. if point.y > pdfView.frame.height - thumbnailViewHeight { return }
  225. navigationController?.setNavigationBarHidden(true, animated: false)
  226. pdfThumbnailView.isHidden = true
  227. pdfView.backgroundColor = .black
  228. }
  229. handlePageChange()
  230. }
  231. // MARK: -
  232. @objc func handlePageChange() {
  233. guard let curPage = pdfView.currentPage?.pageRef?.pageNumber else { pageView.alpha = 0; return }
  234. guard let totalPages = pdfView.document?.pageCount else { return }
  235. pageView.alpha = 1
  236. pageViewLabel.text = String(curPage) + " " + NSLocalizedString("_of_", comment: "") + " " + String(totalPages)
  237. pageViewWidthAnchor?.constant = pageViewLabel.intrinsicContentSize.width + 10
  238. UIView.animate(withDuration: 1.0, delay: 3.0, animations: {
  239. self.pageView.alpha = 0
  240. })
  241. }
  242. func searchPdfSelection(_ pdfSelection: PDFSelection) {
  243. pdfSelection.color = .yellow
  244. pdfView.currentSelection = pdfSelection
  245. pdfView.go(to: pdfSelection)
  246. }
  247. private func selectPage(with label: String) {
  248. guard let pdf = pdfView.document else { return }
  249. if let pageNr = Int(label) {
  250. if pageNr > 0 && pageNr <= pdf.pageCount {
  251. if let page = pdf.page(at: pageNr - 1) {
  252. self.pdfView.go(to: page)
  253. }
  254. } else {
  255. let alertController = UIAlertController(title: NSLocalizedString("_invalid_page_", comment: ""),
  256. message: NSLocalizedString("_the_entered_page_number_doesn't_exist_", comment: ""),
  257. preferredStyle: .alert)
  258. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
  259. self.present(alertController, animated: true, completion: nil)
  260. }
  261. }
  262. }
  263. }