NCCollectionViewCommon.swift 53 KB

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