NCCollectionViewCommon.swift 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  522. if metadataTouch != nil {
  523. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  524. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  525. if !NCBrandOptions.sharedInstance.disable_openin_file {
  526. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  527. }
  528. }
  529. if listMenuItems.count > 0 {
  530. UIMenuController.shared.menuItems = listMenuItems
  531. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  532. UIMenuController.shared.setMenuVisible(true, animated: true)
  533. }
  534. }
  535. // MARK: - Menu Item
  536. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  537. if (#selector(pasteFilesMenu(_:)) == action) {
  538. if UIPasteboard.general.items.count > 0 {
  539. return true
  540. }
  541. }
  542. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  543. guard let metadata = metadataTouch else { return false }
  544. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  545. return true
  546. }
  547. }
  548. return false
  549. }
  550. @objc func copyFileMenu(_ notification: Any) {
  551. var metadatas: [tableMetadata] = []
  552. var items = [[String : Any]]()
  553. if isEditMode {
  554. for ocId in selectOcId {
  555. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  556. metadatas.append(metadata)
  557. }
  558. }
  559. } else {
  560. guard let metadata = metadataTouch else { return }
  561. metadatas.append(metadata)
  562. }
  563. for metadata in metadatas {
  564. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  565. do {
  566. let data = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  567. items.append([k_metadataKeyedUnarchiver:data])
  568. } catch {
  569. print("error")
  570. }
  571. } else {
  572. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  573. }
  574. }
  575. UIPasteboard.general.setItems(items, options: [:])
  576. if isEditMode {
  577. tapSelect(sender: self)
  578. }
  579. }
  580. @objc func pasteFilesMenu(_ notification: Any) {
  581. var listData: [String] = []
  582. for item in UIPasteboard.general.items {
  583. for object in item {
  584. let contentType = object.key
  585. let data = object.value
  586. if contentType == k_metadataKeyedUnarchiver {
  587. do {
  588. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  589. uploadPasteOcId(ocId)
  590. }
  591. } catch {
  592. print("error")
  593. }
  594. continue
  595. }
  596. if data is String {
  597. if listData.contains(data as! String) {
  598. continue
  599. } else {
  600. listData.append(data as! String)
  601. }
  602. }
  603. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  604. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  605. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  606. }
  607. }
  608. }
  609. }
  610. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  611. do {
  612. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  613. let ocId = UUID().uuidString
  614. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  615. if data is UIImage {
  616. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  617. } else if data is Data {
  618. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  619. } else if data is String {
  620. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  621. } else {
  622. return
  623. }
  624. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  625. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  626. metadataForUpload.sessionSelector = selectorUploadFile
  627. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  628. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  629. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  630. } catch { }
  631. }
  632. private func uploadPasteOcId(_ ocId: String) {
  633. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  634. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  635. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  636. let ocId = NSUUID().uuidString
  637. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  638. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  639. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  640. metadataForUpload.sessionSelector = selectorUploadFile
  641. metadataForUpload.size = metadata.size
  642. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  643. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  644. }
  645. }
  646. }
  647. @objc func openQuickLookMenu(_ notification: Any) {
  648. guard let metadata = metadataTouch else { return }
  649. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  650. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  651. } else {
  652. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  653. }
  654. }
  655. @objc func openInMenu(_ notification: Any) {
  656. guard let metadata = metadataTouch else { return }
  657. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  658. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  659. } else {
  660. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  661. }
  662. }
  663. // MARK: - SEGUE
  664. @objc func segue(metadata: tableMetadata) {
  665. self.metadataTouch = metadata
  666. performSegue(withIdentifier: "segueDetail", sender: self)
  667. }
  668. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  669. let photoDataSource: NSMutableArray = []
  670. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  671. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  672. photoDataSource.add(metadata)
  673. }
  674. }
  675. if let segueNavigationController = segue.destination as? UINavigationController {
  676. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  677. segueViewController.metadata = metadataTouch
  678. }
  679. }
  680. }
  681. // MARK: - DataSource + NC Endpoint
  682. @objc func reloadDataSource() {
  683. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  684. richWorkspaceText = directory?.richWorkspace
  685. // get auto upload folder
  686. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  687. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  688. }
  689. @objc func reloadDataSource(_ notification: NSNotification) { }
  690. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  691. @objc func reloadDataSourceNetworkRefreshControl() {
  692. reloadDataSourceNetwork(forced: true)
  693. }
  694. @objc func networkSearch() {
  695. if literalSearch?.count ?? 0 > 1 {
  696. isReloadDataSourceNetworkInProgress = true
  697. collectionView?.reloadData()
  698. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  699. if self.searchController?.isActive ?? false && errorCode == 0 {
  700. self.metadatasSource = metadatas!
  701. }
  702. self.isReloadDataSourceNetworkInProgress = false
  703. self.reloadDataSource()
  704. }
  705. }
  706. }
  707. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  708. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  709. if errorCode == 0 {
  710. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  711. if forced || directory?.etag != metadata?.etag {
  712. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  713. if errorCode == 0 {
  714. self.metadataFolder = metadataFolder
  715. }
  716. completion(metadatas, errorCode, errorDescription)
  717. }
  718. } else {
  719. completion(nil, 0, "")
  720. }
  721. } else {
  722. completion(nil, errorCode, errorDescription)
  723. }
  724. }
  725. }
  726. }
  727. // MARK: - 3D Touch peek and pop
  728. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  729. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  730. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  731. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  732. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  733. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  734. viewController.metadata = metadata
  735. if layout == k_layout_grid {
  736. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  737. previewingContext.sourceRect = cell.frame
  738. viewController.imageFile = cell.imageItem.image
  739. } else {
  740. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  741. previewingContext.sourceRect = cell.frame
  742. viewController.imageFile = cell.imageItem.image
  743. }
  744. viewController.showOpenIn = true
  745. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  746. viewController.showShare = false
  747. return viewController
  748. }
  749. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  750. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  751. collectionView(collectionView, didSelectItemAt: indexPath)
  752. }
  753. }
  754. // MARK: - Collection View
  755. extension NCCollectionViewCommon: UICollectionViewDelegate {
  756. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  757. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return }
  758. metadataTouch = metadata
  759. if isEditMode {
  760. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  761. selectOcId.remove(at: index)
  762. } else {
  763. selectOcId.append(metadata.ocId)
  764. }
  765. collectionView.reloadItems(at: [indexPath])
  766. return
  767. }
  768. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  769. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  770. return
  771. }
  772. if metadata.directory {
  773. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  774. if layoutKey == k_layout_view_favorite {
  775. let ncFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  776. ncFavorite.serverUrl = serverUrlPush
  777. ncFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  778. self.navigationController?.pushViewController(ncFavorite, animated: true)
  779. }
  780. if layoutKey == k_layout_view_offline {
  781. let ncOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  782. ncOffline.serverUrl = serverUrlPush
  783. ncOffline.titleCurrentFolder = metadataTouch!.fileNameView
  784. self.navigationController?.pushViewController(ncOffline, animated: true)
  785. }
  786. } else {
  787. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  788. if NCCommunication.shared.isNetworkReachable() {
  789. performSegue(withIdentifier: "segueDetail", sender: self)
  790. } else {
  791. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  792. }
  793. return
  794. }
  795. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  796. if NCCommunication.shared.isNetworkReachable() {
  797. performSegue(withIdentifier: "segueDetail", sender: self)
  798. } else {
  799. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  800. }
  801. return
  802. }
  803. if CCUtility.fileProviderStorageExists(metadataTouch?.ocId, fileNameView: metadataTouch?.fileNameView) {
  804. performSegue(withIdentifier: "segueDetail", sender: self)
  805. } else {
  806. NCNetworking.shared.download(metadata: metadataTouch!, selector: selectorLoadFileView) { (_) in }
  807. }
  808. }
  809. }
  810. func collectionViewSelectAll() {
  811. selectOcId.removeAll()
  812. for metadata in metadatasSource {
  813. selectOcId.append(metadata.ocId)
  814. }
  815. collectionView.reloadData()
  816. }
  817. }
  818. extension NCCollectionViewCommon: UICollectionViewDataSource {
  819. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  820. if kind == UICollectionView.elementKindSectionHeader {
  821. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  822. if collectionView.collectionViewLayout == gridLayout {
  823. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  824. } else {
  825. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  826. }
  827. header.delegate = self
  828. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  829. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  830. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  831. header.setTitleSorted(datasourceTitleButton: titleButton)
  832. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  833. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  834. return header
  835. } else {
  836. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  837. let info = dataSource?.getFilesInformation()
  838. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  839. return footer
  840. }
  841. }
  842. func numberOfSections(in collectionView: UICollectionView) -> Int {
  843. return 1
  844. }
  845. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  846. return dataSource?.numberOfItems() ?? 0
  847. }
  848. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  849. let cell: UICollectionViewCell
  850. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  851. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  852. }
  853. if layout == k_layout_grid {
  854. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  855. } else {
  856. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  857. }
  858. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  859. 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)
  860. return cell
  861. }
  862. }
  863. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  864. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  865. if richWorkspaceText?.count ?? 0 == 0 {
  866. headerRichWorkspaceHeight = 0
  867. } else {
  868. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  869. }
  870. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  871. }
  872. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  873. return CGSize(width: collectionView.frame.width, height: footerHeight)
  874. }
  875. }