NCCollectionViewCommon.swift 51 KB

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