NCCollectionViewCommon.swift 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. //
  2. // NCCollectionViewCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/09/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 Foundation
  24. import NCCommunication
  25. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. internal let refreshControl = UIRefreshControl()
  28. internal var searchController: UISearchController?
  29. @objc var serverUrl: String = ""
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. internal var isEditMode = false
  32. internal var selectOcId: [String] = []
  33. internal var metadatasSource: [tableMetadata] = []
  34. internal var metadataFolder: tableMetadata?
  35. internal var metadataTouch: tableMetadata?
  36. internal var dataSource: NCDataSource?
  37. internal var richWorkspaceText: String?
  38. internal var layout = ""
  39. internal var groupBy = ""
  40. internal var titleButton = ""
  41. internal var itemForLine = 0
  42. private var autoUploadFileName = ""
  43. private var autoUploadDirectory = ""
  44. private var listLayout: NCListLayout!
  45. private var gridLayout: NCGridLayout!
  46. private let headerHeight: CGFloat = 50
  47. private var headerRichWorkspaceHeight: CGFloat = 0
  48. private let footerHeight: CGFloat = 50
  49. private var timerInputSearch: Timer?
  50. internal var literalSearch: String?
  51. internal var isSearching: Bool = false
  52. internal var isReloadDataSourceNetworkInProgress: Bool = false
  53. // DECLARE
  54. internal var layoutKey = ""
  55. internal var titleCurrentFolder = ""
  56. internal var enableSearchBar: Bool = false
  57. internal var DZNimage: UIImage?
  58. internal var DZNtitle: String = ""
  59. internal var DZNdescription: String = ""
  60. required init?(coder aDecoder: NSCoder) {
  61. super.init(coder: aDecoder)
  62. }
  63. override func viewDidLoad() {
  64. super.viewDidLoad()
  65. self.navigationController?.navigationBar.prefersLargeTitles = true
  66. if enableSearchBar {
  67. searchController = UISearchController(searchResultsController: nil)
  68. searchController?.searchResultsUpdater = self
  69. self.navigationItem.searchController = searchController
  70. searchController?.dimsBackgroundDuringPresentation = false
  71. searchController?.delegate = self
  72. searchController?.searchBar.delegate = self
  73. navigationItem.hidesSearchBarWhenScrolling = false
  74. }
  75. // Cell
  76. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  77. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  78. // Header
  79. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  80. // Footer
  81. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  82. collectionView.alwaysBounceVertical = true
  83. listLayout = NCListLayout()
  84. gridLayout = NCGridLayout()
  85. // Refresh Control
  86. collectionView.addSubview(refreshControl)
  87. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  88. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  89. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  90. // empty Data Source
  91. self.collectionView.emptyDataSetDelegate = self
  92. self.collectionView.emptyDataSetSource = self
  93. // 3D Touch peek and pop
  94. if traitCollection.forceTouchCapability == .available {
  95. registerForPreviewing(with: self, sourceView: view)
  96. }
  97. // Long Press on CollectionView
  98. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  99. longPressedGesture.minimumPressDuration = 0.5
  100. longPressedGesture.delegate = self
  101. longPressedGesture.delaysTouchesBegan = true
  102. collectionView.addGestureRecognizer(longPressedGesture)
  103. // Notification
  104. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  121. changeTheming()
  122. }
  123. override func viewWillAppear(_ animated: Bool) {
  124. super.viewWillAppear(animated)
  125. appDelegate.activeViewController = self
  126. self.navigationItem.title = titleCurrentFolder
  127. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  128. gridLayout.itemForLine = CGFloat(itemForLine)
  129. if layout == k_layout_list {
  130. collectionView?.collectionViewLayout = listLayout
  131. } else {
  132. collectionView?.collectionViewLayout = gridLayout
  133. }
  134. setNavigationItem()
  135. reloadDataSource()
  136. }
  137. override func viewDidAppear(_ animated: Bool) {
  138. super.viewDidAppear(animated)
  139. reloadDataSourceNetwork()
  140. }
  141. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  142. super.viewWillTransition(to: size, with: coordinator)
  143. coordinator.animate(alongsideTransition: nil) { _ in
  144. self.collectionView?.collectionViewLayout.invalidateLayout()
  145. }
  146. }
  147. override var canBecomeFirstResponder: Bool {
  148. return true
  149. }
  150. func setNavigationItem() {
  151. if isEditMode {
  152. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  153. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  154. } else {
  155. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  156. self.navigationItem.leftBarButtonItem = nil
  157. }
  158. }
  159. // MARK: - NotificationCenter
  160. @objc func initializeMain() {
  161. self.navigationController?.popToRootViewController(animated: false)
  162. appDelegate.listFavoriteVC.removeAllObjects()
  163. appDelegate.listOfflineVC.removeAllObjects()
  164. }
  165. @objc func changeTheming() {
  166. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  167. }
  168. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  169. if self.view?.window == nil { return }
  170. reloadDataSource()
  171. }
  172. @objc func deleteFile(_ notification: NSNotification) {
  173. if self.view?.window == nil { return }
  174. if let userInfo = notification.userInfo as NSDictionary? {
  175. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  176. if onlyLocal {
  177. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  178. let indexPath = IndexPath(row: row, section: 0)
  179. collectionView?.reloadItems(at: [indexPath])
  180. }
  181. } else {
  182. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  183. let indexPath = IndexPath(row: row, section: 0)
  184. collectionView?.performBatchUpdates({
  185. collectionView?.deleteItems(at: [indexPath])
  186. }, completion: { (_) in
  187. self.collectionView?.reloadData()
  188. })
  189. }
  190. }
  191. }
  192. }
  193. }
  194. @objc func moveFile(_ notification: NSNotification) {
  195. if self.view?.window == nil { return }
  196. if let userInfo = notification.userInfo as NSDictionary? {
  197. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  198. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  199. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  200. let indexPath = IndexPath(row: row, section: 0)
  201. collectionView?.performBatchUpdates({
  202. collectionView?.deleteItems(at: [indexPath])
  203. }, completion: { (_) in
  204. self.collectionView?.reloadData()
  205. })
  206. }
  207. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  208. if let row = dataSource?.addMetadata(metadataNew) {
  209. let indexPath = IndexPath(row: row, section: 0)
  210. collectionView?.performBatchUpdates({
  211. collectionView?.insertItems(at: [indexPath])
  212. }, completion: { (_) in
  213. self.collectionView?.reloadData()
  214. })
  215. }
  216. }
  217. }
  218. }
  219. }
  220. @objc func copyFile(_ notification: NSNotification) {
  221. if self.view?.window == nil { return }
  222. if let userInfo = notification.userInfo as NSDictionary? {
  223. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  224. if serverUrlTo == self.serverUrl {
  225. self.reloadDataSource()
  226. }
  227. }
  228. }
  229. }
  230. @objc func renameFile(_ notification: NSNotification) {
  231. if self.view?.window == nil { return }
  232. if let userInfo = notification.userInfo as NSDictionary? {
  233. if let metadata = userInfo["metadata"] as? tableMetadata {
  234. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  235. let indexPath = IndexPath(row: row, section: 0)
  236. collectionView?.performBatchUpdates({
  237. collectionView?.reloadItems(at: [indexPath])
  238. }, completion: { (_) in
  239. self.collectionView?.reloadData()
  240. })
  241. }
  242. }
  243. }
  244. }
  245. @objc func createFolder(_ notification: NSNotification) {
  246. if self.view?.window == nil { return }
  247. if let userInfo = notification.userInfo as NSDictionary? {
  248. if let metadata = userInfo["metadata"] as? tableMetadata {
  249. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  250. if let row = dataSource?.addMetadata(metadata) {
  251. let indexPath = IndexPath(row: row, section: 0)
  252. collectionView?.performBatchUpdates({
  253. collectionView?.insertItems(at: [indexPath])
  254. }, completion: { (_) in
  255. self.collectionView?.reloadData()
  256. })
  257. }
  258. }
  259. }
  260. } else {
  261. self.reloadDataSourceNetwork()
  262. }
  263. }
  264. @objc func favoriteFile(_ notification: NSNotification) {
  265. if self.view?.window == nil { return }
  266. if let userInfo = notification.userInfo as NSDictionary? {
  267. if let metadata = userInfo["metadata"] as? tableMetadata {
  268. if dataSource?.getIndexMetadata(ocId: metadata.ocId) != nil {
  269. self.reloadDataSource()
  270. }
  271. }
  272. }
  273. }
  274. @objc func downloadStartFile(_ notification: NSNotification) {
  275. if self.view?.window == nil { return }
  276. if let userInfo = notification.userInfo as NSDictionary? {
  277. if let metadata = userInfo["metadata"] as? tableMetadata {
  278. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  279. let indexPath = IndexPath(row: row, section: 0)
  280. collectionView?.reloadItems(at: [indexPath])
  281. }
  282. }
  283. }
  284. }
  285. @objc func downloadedFile(_ notification: NSNotification) {
  286. if self.view?.window == nil { return }
  287. if let userInfo = notification.userInfo as NSDictionary? {
  288. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  289. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  290. let indexPath = IndexPath(row: row, section: 0)
  291. collectionView?.reloadItems(at: [indexPath])
  292. }
  293. }
  294. }
  295. }
  296. @objc func downloadCancelFile(_ notification: NSNotification) {
  297. if self.view?.window == nil { return }
  298. if let userInfo = notification.userInfo as NSDictionary? {
  299. if let metadata = userInfo["metadata"] as? tableMetadata {
  300. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  301. let indexPath = IndexPath(row: row, section: 0)
  302. collectionView?.reloadItems(at: [indexPath])
  303. }
  304. }
  305. }
  306. }
  307. @objc func uploadStartFile(_ notification: NSNotification) {
  308. if self.view?.window == nil { return }
  309. if let userInfo = notification.userInfo as NSDictionary? {
  310. if let metadata = userInfo["metadata"] as? tableMetadata {
  311. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  312. if let row = dataSource?.addMetadata(metadata) {
  313. let indexPath = IndexPath(row: row, section: 0)
  314. collectionView?.performBatchUpdates({
  315. collectionView?.insertItems(at: [indexPath])
  316. }, completion: { (_) in
  317. self.collectionView?.reloadData()
  318. })
  319. }
  320. }
  321. }
  322. }
  323. }
  324. @objc func uploadedFile(_ notification: NSNotification) {
  325. if self.view?.window == nil { return }
  326. if let userInfo = notification.userInfo as NSDictionary? {
  327. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  328. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  329. dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  330. collectionView?.reloadData()
  331. }
  332. }
  333. }
  334. }
  335. @objc func uploadCancelFile(_ notification: NSNotification) {
  336. if self.view?.window == nil { return }
  337. if let userInfo = notification.userInfo as NSDictionary? {
  338. if let metadata = userInfo["metadata"] as? tableMetadata {
  339. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  340. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  341. let indexPath = IndexPath(row: row, section: 0)
  342. collectionView?.performBatchUpdates({
  343. collectionView?.deleteItems(at: [indexPath])
  344. }, completion: { (_) in
  345. self.collectionView?.reloadData()
  346. })
  347. } else {
  348. self.reloadDataSource()
  349. }
  350. }
  351. }
  352. }
  353. }
  354. @objc func triggerProgressTask(_ notification: NSNotification) {
  355. if self.view?.window == nil { return }
  356. if let userInfo = notification.userInfo as NSDictionary? {
  357. if let ocId = userInfo["ocId"] as? String {
  358. let _ = userInfo["account"] as? String ?? ""
  359. let _ = userInfo["serverUrl"] as? String ?? ""
  360. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  361. let progress = progressNumber.floatValue
  362. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  363. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  364. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  365. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  366. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  367. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  368. if cell is NCListCell {
  369. let cell = cell as! NCListCell
  370. if progress > 0 {
  371. cell.progressView?.isHidden = false
  372. cell.progressView?.progress = progress
  373. cell.setButtonMore(named: "stop")
  374. if status == k_metadataStatusInDownload {
  375. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  376. } else if status == k_metadataStatusInUpload {
  377. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  378. }
  379. }
  380. } else if cell is NCGridCell {
  381. let cell = cell as! NCGridCell
  382. if progress > 0 {
  383. cell.progressView.isHidden = false
  384. cell.progressView.progress = progress
  385. cell.setButtonMore(named: "stop")
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. }
  393. // MARK: - DZNEmpty
  394. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  395. return NCBrandColor.sharedInstance.backgroundView
  396. }
  397. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  398. if searchController?.isActive ?? false {
  399. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: NCBrandColor.sharedInstance.yellowFavorite)
  400. }
  401. return DZNimage
  402. }
  403. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  404. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  405. if searchController?.isActive ?? false {
  406. if isReloadDataSourceNetworkInProgress {
  407. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  408. } else {
  409. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  410. }
  411. }
  412. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  413. return NSAttributedString.init(string: text, attributes: attributes)
  414. }
  415. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  416. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  417. if searchController?.isActive ?? false {
  418. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  419. }
  420. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  421. return NSAttributedString.init(string: text, attributes: attributes)
  422. }
  423. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  424. return true
  425. }
  426. // MARK: - SEARCH
  427. func updateSearchResults(for searchController: UISearchController) {
  428. timerInputSearch?.invalidate()
  429. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  430. literalSearch = searchController.searchBar.text
  431. collectionView?.reloadData()
  432. }
  433. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  434. isSearching = true
  435. metadatasSource.removeAll()
  436. reloadDataSource()
  437. }
  438. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  439. isSearching = false
  440. literalSearch = ""
  441. reloadDataSource()
  442. }
  443. // MARK: - TAP EVENT
  444. @objc func tapSelect(sender: Any) {
  445. isEditMode = !isEditMode
  446. selectOcId.removeAll()
  447. setNavigationItem()
  448. self.collectionView.reloadData()
  449. }
  450. func tapSwitchHeader(sender: Any) {
  451. if collectionView.collectionViewLayout == gridLayout {
  452. // list layout
  453. UIView.animate(withDuration: 0.0, animations: {
  454. self.collectionView.collectionViewLayout.invalidateLayout()
  455. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  456. self.collectionView.reloadData()
  457. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  458. })
  459. })
  460. layout = k_layout_list
  461. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  462. } else {
  463. // grid layout
  464. UIView.animate(withDuration: 0.0, animations: {
  465. self.collectionView.collectionViewLayout.invalidateLayout()
  466. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  467. self.collectionView.reloadData()
  468. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  469. })
  470. })
  471. layout = k_layout_grid
  472. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  473. }
  474. }
  475. func tapOrderHeader(sender: Any) {
  476. let sortMenu = NCSortMenu()
  477. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  478. }
  479. @objc func tapSelectMenu(sender: Any) {
  480. guard let tabBarController = self.tabBarController else { return }
  481. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  482. }
  483. func tapMoreHeader(sender: Any) { }
  484. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  485. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  486. }
  487. func tapShareListItem(with objectId: String, sender: Any) {
  488. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  489. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  490. }
  491. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  492. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  493. guard let tabBarController = self.tabBarController else { return }
  494. if namedButtonMore == "more" {
  495. toggleMoreMenu(viewController: tabBarController, metadata: metadata)
  496. } else if namedButtonMore == "stop" {
  497. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  498. }
  499. }
  500. func tapRichWorkspace(sender: Any) {
  501. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  502. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  503. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  504. viewerRichWorkspace.serverUrl = serverUrl
  505. navigationController.modalPresentationStyle = .fullScreen
  506. self.present(navigationController, animated: true, completion: nil)
  507. }
  508. }
  509. }
  510. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  511. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  512. metadataTouch = metadata
  513. longPressCollecationView(gestureRecognizer)
  514. }
  515. }
  516. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  517. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  518. metadataTouch = metadata
  519. longPressCollecationView(gestureRecognizer)
  520. }
  521. }
  522. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  523. }
  524. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  525. }
  526. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  527. if gestureRecognizer.state != .began { return }
  528. if serverUrl == "" { return }
  529. var listMenuItems: [UIMenuItem] = []
  530. let touchPoint = gestureRecognizer.location(in: collectionView)
  531. becomeFirstResponder()
  532. if metadataTouch != nil {
  533. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  534. }
  535. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  536. if metadataTouch != nil {
  537. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  538. if !NCBrandOptions.sharedInstance.disable_openin_file {
  539. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  540. }
  541. }
  542. if listMenuItems.count > 0 {
  543. UIMenuController.shared.menuItems = listMenuItems
  544. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  545. UIMenuController.shared.setMenuVisible(true, animated: true)
  546. }
  547. }
  548. // MARK: - Menu Item
  549. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  550. if (#selector(pasteFilesMenu(_:)) == action) {
  551. if UIPasteboard.general.items.count > 0 {
  552. return true
  553. }
  554. }
  555. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  556. guard let metadata = metadataTouch else { return false }
  557. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  558. return true
  559. }
  560. }
  561. return false
  562. }
  563. @objc func copyFileMenu(_ notification: Any) {
  564. var metadatas: [tableMetadata] = []
  565. var items = [[String : Any]]()
  566. if isEditMode {
  567. for ocId in selectOcId {
  568. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  569. metadatas.append(metadata)
  570. }
  571. }
  572. } else {
  573. guard let metadata = metadataTouch else { return }
  574. metadatas.append(metadata)
  575. }
  576. for metadata in metadatas {
  577. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  578. do {
  579. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  580. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  581. } catch {
  582. print("error")
  583. }
  584. } else {
  585. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  586. }
  587. }
  588. UIPasteboard.general.setItems(items, options: [:])
  589. if isEditMode {
  590. tapSelect(sender: self)
  591. }
  592. }
  593. @objc func pasteFilesMenu(_ notification: Any) {
  594. var listData: [String] = []
  595. for item in UIPasteboard.general.items {
  596. for object in item {
  597. let contentType = object.key
  598. let data = object.value
  599. if contentType == k_metadataKeyedUnarchiver {
  600. do {
  601. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  602. uploadPasteOcId(ocId)
  603. }
  604. } catch {
  605. print("error")
  606. }
  607. continue
  608. }
  609. if data is String {
  610. if listData.contains(data as! String) {
  611. continue
  612. } else {
  613. listData.append(data as! String)
  614. }
  615. }
  616. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  617. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  618. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  619. }
  620. }
  621. }
  622. }
  623. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  624. do {
  625. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  626. let ocId = UUID().uuidString
  627. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  628. if data is UIImage {
  629. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  630. } else if data is Data {
  631. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  632. } else if data is String {
  633. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  634. } else {
  635. return
  636. }
  637. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  638. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  639. metadataForUpload.sessionSelector = selectorUploadFile
  640. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  641. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  642. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  643. } catch { }
  644. }
  645. private func uploadPasteOcId(_ ocId: String) {
  646. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  647. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  648. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  649. let ocId = NSUUID().uuidString
  650. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  651. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  652. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  653. metadataForUpload.sessionSelector = selectorUploadFile
  654. metadataForUpload.size = metadata.size
  655. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  656. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  657. }
  658. }
  659. }
  660. @objc func openQuickLookMenu(_ notification: Any) {
  661. guard let metadata = metadataTouch else { return }
  662. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  663. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  664. } else {
  665. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  666. }
  667. }
  668. @objc func openInMenu(_ notification: Any) {
  669. guard let metadata = metadataTouch else { return }
  670. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  671. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  672. } else {
  673. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  674. }
  675. }
  676. // MARK: - SEGUE
  677. @objc func segue(metadata: tableMetadata) {
  678. self.metadataTouch = metadata
  679. performSegue(withIdentifier: "segueDetail", sender: self)
  680. }
  681. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  682. let photoDataSource: NSMutableArray = []
  683. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  684. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  685. photoDataSource.add(metadata)
  686. }
  687. }
  688. if let segueNavigationController = segue.destination as? UINavigationController {
  689. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  690. segueViewController.metadata = metadataTouch
  691. }
  692. }
  693. }
  694. // MARK: - DataSource + NC Endpoint
  695. @objc func reloadDataSource() {
  696. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  697. richWorkspaceText = directory?.richWorkspace
  698. // get auto upload folder
  699. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  700. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  701. }
  702. @objc func reloadDataSource(_ notification: NSNotification) { }
  703. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  704. @objc func reloadDataSourceNetworkRefreshControl() {
  705. reloadDataSourceNetwork(forced: true)
  706. }
  707. @objc func networkSearch() {
  708. if literalSearch?.count ?? 0 > 1 {
  709. isReloadDataSourceNetworkInProgress = true
  710. collectionView?.reloadData()
  711. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  712. if self.searchController?.isActive ?? false && errorCode == 0 {
  713. self.metadatasSource = metadatas!
  714. }
  715. self.isReloadDataSourceNetworkInProgress = false
  716. self.reloadDataSource()
  717. }
  718. }
  719. }
  720. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  721. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  722. if errorCode == 0 {
  723. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  724. if forced || directory?.etag != metadata?.etag {
  725. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  726. if errorCode == 0 {
  727. self.metadataFolder = metadataFolder
  728. }
  729. completion(metadatas, errorCode, errorDescription)
  730. }
  731. } else {
  732. completion(nil, 0, "")
  733. }
  734. } else {
  735. completion(nil, errorCode, errorDescription)
  736. }
  737. }
  738. }
  739. }
  740. // MARK: - 3D Touch peek and pop
  741. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  742. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  743. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  744. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  745. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  746. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  747. viewController.metadata = metadata
  748. if layout == k_layout_grid {
  749. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  750. previewingContext.sourceRect = cell.frame
  751. viewController.imageFile = cell.imageItem.image
  752. } else {
  753. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  754. previewingContext.sourceRect = cell.frame
  755. viewController.imageFile = cell.imageItem.image
  756. }
  757. viewController.showOpenIn = true
  758. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  759. viewController.showShare = false
  760. return viewController
  761. }
  762. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  763. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  764. collectionView(collectionView, didSelectItemAt: indexPath)
  765. }
  766. }
  767. // MARK: - Collection View
  768. extension NCCollectionViewCommon: UICollectionViewDelegate {
  769. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  770. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return }
  771. metadataTouch = metadata
  772. if isEditMode {
  773. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  774. selectOcId.remove(at: index)
  775. } else {
  776. selectOcId.append(metadata.ocId)
  777. }
  778. collectionView.reloadItems(at: [indexPath])
  779. return
  780. }
  781. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  782. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  783. return
  784. }
  785. if metadata.directory {
  786. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  787. // FAVORITE
  788. if layoutKey == k_layout_view_favorite {
  789. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  790. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  791. if vcFavorite.isViewLoaded {
  792. self.navigationController?.pushViewController(vcFavorite, animated: true)
  793. }
  794. } else {
  795. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  796. vcFavorite.serverUrl = serverUrlPush
  797. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  798. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  799. self.navigationController?.pushViewController(vcFavorite, animated: true)
  800. }
  801. }
  802. // OFFLINE
  803. if layoutKey == k_layout_view_offline {
  804. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  805. guard let vcOffline = (viewController as? NCOffline) else { return }
  806. if vcOffline.isViewLoaded {
  807. self.navigationController?.pushViewController(vcOffline, animated: true)
  808. }
  809. } else {
  810. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  811. vcOffline.serverUrl = serverUrlPush
  812. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  813. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  814. self.navigationController?.pushViewController(vcOffline, animated: true)
  815. }
  816. }
  817. } else {
  818. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  819. if NCCommunication.shared.isNetworkReachable() {
  820. performSegue(withIdentifier: "segueDetail", sender: self)
  821. } else {
  822. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  823. }
  824. return
  825. }
  826. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  827. if NCCommunication.shared.isNetworkReachable() {
  828. performSegue(withIdentifier: "segueDetail", sender: self)
  829. } else {
  830. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  831. }
  832. return
  833. }
  834. if CCUtility.fileProviderStorageExists(metadataTouch?.ocId, fileNameView: metadataTouch?.fileNameView) {
  835. performSegue(withIdentifier: "segueDetail", sender: self)
  836. } else {
  837. NCNetworking.shared.download(metadata: metadataTouch!, selector: selectorLoadFileView) { (_) in }
  838. }
  839. }
  840. }
  841. func collectionViewSelectAll() {
  842. selectOcId.removeAll()
  843. for metadata in metadatasSource {
  844. selectOcId.append(metadata.ocId)
  845. }
  846. collectionView.reloadData()
  847. }
  848. }
  849. extension NCCollectionViewCommon: UICollectionViewDataSource {
  850. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  851. if kind == UICollectionView.elementKindSectionHeader {
  852. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  853. if collectionView.collectionViewLayout == gridLayout {
  854. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  855. } else {
  856. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  857. }
  858. header.delegate = self
  859. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  860. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  861. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  862. header.setTitleSorted(datasourceTitleButton: titleButton)
  863. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  864. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  865. return header
  866. } else {
  867. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  868. let info = dataSource?.getFilesInformation()
  869. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  870. return footer
  871. }
  872. }
  873. func numberOfSections(in collectionView: UICollectionView) -> Int {
  874. return 1
  875. }
  876. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  877. return dataSource?.numberOfItems() ?? 0
  878. }
  879. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  880. let cell: UICollectionViewCell
  881. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  882. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  883. }
  884. if layout == k_layout_grid {
  885. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  886. } else {
  887. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  888. }
  889. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  890. NCCollectionCommon.shared.cellForItemAt(indexPath: indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: metadataFolder, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectocId: selectOcId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self, dataSource: dataSource)
  891. return cell
  892. }
  893. }
  894. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  895. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  896. if richWorkspaceText?.count ?? 0 == 0 {
  897. headerRichWorkspaceHeight = 0
  898. } else {
  899. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  900. }
  901. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  902. }
  903. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  904. return CGSize(width: collectionView.frame.width, height: footerHeight)
  905. }
  906. }