NCCollectionViewCommon.swift 53 KB

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