NCViewerPDF.swift 16 KB

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