NCCollectionViewCommon.swift 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. internal let refreshControl = UIRefreshControl()
  29. internal var searchController: UISearchController?
  30. internal var emptyDataSet: NCEmptyDataSet?
  31. internal var serverUrl: String = ""
  32. internal var isEncryptedFolder = false
  33. internal var isEditMode = false
  34. internal var selectOcId: [String] = []
  35. internal var metadatasSource: [tableMetadata] = []
  36. internal var metadataFolder: tableMetadata?
  37. internal var metadataTouch: tableMetadata?
  38. internal var dataSource = NCDataSource()
  39. internal var richWorkspaceText: String?
  40. internal var layout = ""
  41. internal var sort: String = ""
  42. internal var ascending: Bool = true
  43. internal var directoryOnTop: Bool = true
  44. internal var groupBy = ""
  45. internal var titleButton = ""
  46. internal var itemForLine = 0
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var listLayout: NCListLayout!
  50. internal var gridLayout: NCGridLayout!
  51. private let headerHeight: CGFloat = 50
  52. private var headerRichWorkspaceHeight: CGFloat = 0
  53. private let footerHeight: CGFloat = 100
  54. private var timerInputSearch: Timer?
  55. internal var literalSearch: String?
  56. internal var isSearching: Bool = false
  57. internal var isReloadDataSourceNetworkInProgress: Bool = false
  58. var selectedIndexPath: IndexPath!
  59. // DECLARE
  60. internal var layoutKey = ""
  61. internal var titleCurrentFolder = ""
  62. internal var enableSearchBar: Bool = false
  63. internal var emptyImage: UIImage?
  64. internal var emptyTitle: String = ""
  65. internal var emptyDescription: String = ""
  66. required init?(coder aDecoder: NSCoder) {
  67. super.init(coder: aDecoder)
  68. }
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. self.navigationController?.presentationController?.delegate = self
  72. if enableSearchBar {
  73. searchController = UISearchController(searchResultsController: nil)
  74. searchController?.searchResultsUpdater = self
  75. searchController?.obscuresBackgroundDuringPresentation = false
  76. searchController?.delegate = self
  77. searchController?.searchBar.delegate = self
  78. navigationItem.searchController = searchController
  79. navigationItem.hidesSearchBarWhenScrolling = false
  80. }
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  84. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  85. // Header
  86. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  87. // Footer
  88. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  89. collectionView.alwaysBounceVertical = true
  90. listLayout = NCListLayout()
  91. gridLayout = NCGridLayout()
  92. // Refresh Control
  93. collectionView.addSubview(refreshControl)
  94. refreshControl.tintColor = .gray
  95. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  96. // Empty
  97. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  98. // Long Press on CollectionView
  99. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  100. longPressedGesture.minimumPressDuration = 0.5
  101. longPressedGesture.delegate = self
  102. longPressedGesture.delaysTouchesBegan = true
  103. collectionView.addGestureRecognizer(longPressedGesture)
  104. // Notification
  105. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitializeMain), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  124. changeTheming()
  125. }
  126. override func viewWillAppear(_ animated: Bool) {
  127. super.viewWillAppear(animated)
  128. appDelegate.activeViewController = self
  129. if serverUrl == "" {
  130. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  131. } else {
  132. appDelegate.activeServerUrl = serverUrl
  133. }
  134. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  135. gridLayout.itemForLine = CGFloat(itemForLine)
  136. if layout == NCGlobal.shared.layoutList {
  137. collectionView?.collectionViewLayout = listLayout
  138. } else {
  139. collectionView?.collectionViewLayout = gridLayout
  140. }
  141. navigationController?.navigationBar.prefersLargeTitles = true
  142. navigationController?.setNavigationBarHidden(false, animated: true)
  143. setNavigationItem()
  144. reloadDataSource()
  145. }
  146. override func viewDidAppear(_ animated: Bool) {
  147. super.viewDidAppear(animated)
  148. reloadDataSourceNetwork()
  149. }
  150. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  151. let viewController = presentationController.presentedViewController
  152. if viewController is NCViewerRichWorkspaceWebView {
  153. closeRichWorkspaceWebView()
  154. } else if viewController is UINavigationController {
  155. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  156. appDelegate.activeFileViewInFolder = nil
  157. }
  158. }
  159. }
  160. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  161. super.viewWillTransition(to: size, with: coordinator)
  162. coordinator.animate(alongsideTransition: nil) { _ in
  163. self.collectionView?.collectionViewLayout.invalidateLayout()
  164. }
  165. }
  166. override var canBecomeFirstResponder: Bool {
  167. return true
  168. }
  169. func setNavigationItem() {
  170. if isEditMode {
  171. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  172. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  173. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  174. } else {
  175. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  176. navigationItem.leftBarButtonItem = nil
  177. navigationItem.title = titleCurrentFolder
  178. // PROFILE BUTTON
  179. if layoutKey == NCGlobal.shared.layoutViewFiles {
  180. let profileButton = UIButton.init(type: .custom)
  181. profileButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
  182. profileButton.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  183. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  184. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + appDelegate.user + ".png"
  185. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  186. image = userImage
  187. }
  188. UIGraphicsBeginImageContextWithOptions(profileButton.bounds.size, false, 3.0)
  189. UIBezierPath.init(roundedRect: profileButton.bounds, cornerRadius: profileButton.bounds.size.height).addClip()
  190. image.draw(in: profileButton.bounds)
  191. image = UIGraphicsGetImageFromCurrentImageContext() ?? NCUtility.shared.loadImage(named: "person.crop.circle")
  192. UIGraphicsEndImageContext()
  193. profileButton.setImage(image, for: .normal)
  194. profileButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
  195. profileButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
  196. navigationItem.setLeftBarButton(UIBarButtonItem(customView: profileButton), animated: true)
  197. }
  198. }
  199. }
  200. // MARK: - NotificationCenter
  201. @objc func initializeMain() {
  202. if appDelegate.account == "" { return }
  203. if searchController?.isActive ?? false {
  204. searchController?.isActive = false
  205. }
  206. // set active serverUrl
  207. if self.view?.window != nil {
  208. if serverUrl == "" {
  209. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  210. } else {
  211. appDelegate.activeServerUrl = serverUrl
  212. }
  213. }
  214. if self is NCFiles || self is NCFavorite || self is NCOffline {
  215. self.navigationController?.popToRootViewController(animated: false)
  216. }
  217. appDelegate.listFilesVC.removeAll()
  218. appDelegate.listFavoriteVC.removeAll()
  219. appDelegate.listOfflineVC.removeAll()
  220. selectOcId.removeAll()
  221. setNavigationItem()
  222. reloadDataSource()
  223. }
  224. @objc func changeTheming() {
  225. view.backgroundColor = NCBrandColor.shared.backgroundView
  226. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  227. collectionView.reloadData()
  228. }
  229. @objc func reloadDataSource(_ notification: NSNotification) {
  230. if self.view?.window == nil { return }
  231. reloadDataSource()
  232. }
  233. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  234. if self.view?.window == nil { return }
  235. if let userInfo = notification.userInfo as NSDictionary? {
  236. if let serverUrl = userInfo["serverUrl"] as? String {
  237. if serverUrl == self.serverUrl {
  238. reloadDataSourceNetwork(forced: true)
  239. }
  240. }
  241. } else {
  242. reloadDataSourceNetwork(forced: true)
  243. }
  244. }
  245. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  246. if self.view?.window == nil { return }
  247. reloadDataSource()
  248. }
  249. @objc func closeRichWorkspaceWebView() {
  250. if self.view?.window == nil { return }
  251. reloadDataSourceNetwork()
  252. }
  253. @objc func deleteFile(_ notification: NSNotification) {
  254. if self.view?.window == nil { return }
  255. if let userInfo = notification.userInfo as NSDictionary? {
  256. if let ocId = userInfo["ocId"] as? String, let fileNameView = userInfo["fileNameView"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  257. if onlyLocal {
  258. reloadDataSource()
  259. } else if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  260. reloadDataSourceNetwork(forced: true)
  261. } else {
  262. if let row = dataSource.deleteMetadata(ocId: ocId) {
  263. let indexPath = IndexPath(row: row, section: 0)
  264. collectionView?.performBatchUpdates({
  265. collectionView?.deleteItems(at: [indexPath])
  266. }, completion: { (_) in
  267. self.collectionView?.reloadData()
  268. })
  269. }
  270. }
  271. }
  272. }
  273. }
  274. @objc func moveFile(_ notification: NSNotification) {
  275. if self.view?.window == nil { return }
  276. if let userInfo = notification.userInfo as NSDictionary? {
  277. if let ocId = userInfo["ocId"] as? String, let serverUrlFrom = userInfo["serverUrlFrom"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  278. // DEL
  279. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  280. if let row = dataSource.deleteMetadata(ocId: ocId) {
  281. let indexPath = IndexPath(row: row, section: 0)
  282. collectionView?.performBatchUpdates({
  283. collectionView?.deleteItems(at: [indexPath])
  284. }, completion: { (_) in
  285. self.collectionView?.reloadData()
  286. })
  287. }
  288. // ADD
  289. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  290. if let row = dataSource.addMetadata(metadata) {
  291. let indexPath = IndexPath(row: row, section: 0)
  292. collectionView?.performBatchUpdates({
  293. collectionView?.insertItems(at: [indexPath])
  294. }, completion: { (_) in
  295. self.collectionView?.reloadData()
  296. })
  297. }
  298. }
  299. }
  300. }
  301. }
  302. @objc func copyFile(_ notification: NSNotification) {
  303. if self.view?.window == nil { return }
  304. if let userInfo = notification.userInfo as NSDictionary? {
  305. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  306. if serverUrlTo == self.serverUrl {
  307. reloadDataSource()
  308. }
  309. }
  310. }
  311. }
  312. @objc func renameFile(_ notification: NSNotification) {
  313. if self.view?.window == nil { return }
  314. reloadDataSource()
  315. }
  316. @objc func createFolder(_ notification: NSNotification) {
  317. if self.view?.window == nil { return }
  318. if let userInfo = notification.userInfo as NSDictionary? {
  319. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  320. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  321. if let row = dataSource.addMetadata(metadata) {
  322. let indexPath = IndexPath(row: row, section: 0)
  323. collectionView?.performBatchUpdates({
  324. collectionView?.insertItems(at: [indexPath])
  325. }, completion: { (_) in
  326. self.collectionView?.reloadData()
  327. })
  328. }
  329. }
  330. }
  331. } else {
  332. reloadDataSourceNetwork()
  333. }
  334. }
  335. @objc func favoriteFile(_ notification: NSNotification) {
  336. if self.view?.window == nil { return }
  337. if let userInfo = notification.userInfo as NSDictionary? {
  338. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  339. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  340. reloadDataSource()
  341. }
  342. }
  343. }
  344. }
  345. @objc func downloadStartFile(_ notification: NSNotification) {
  346. if self.view?.window == nil { return }
  347. if let userInfo = notification.userInfo as NSDictionary? {
  348. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  349. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  350. let indexPath = IndexPath(row: row, section: 0)
  351. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  352. collectionView?.reloadItems(at: [indexPath])
  353. }
  354. }
  355. }
  356. }
  357. }
  358. @objc func downloadedFile(_ notification: NSNotification) {
  359. if self.view?.window == nil { return }
  360. if let userInfo = notification.userInfo as NSDictionary? {
  361. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  362. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  363. let indexPath = IndexPath(row: row, section: 0)
  364. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  365. collectionView?.reloadItems(at: [indexPath])
  366. }
  367. }
  368. }
  369. }
  370. }
  371. @objc func downloadCancelFile(_ notification: NSNotification) {
  372. if self.view?.window == nil { return }
  373. if let userInfo = notification.userInfo as NSDictionary? {
  374. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  375. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  376. let indexPath = IndexPath(row: row, section: 0)
  377. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  378. collectionView?.reloadItems(at: [indexPath])
  379. }
  380. }
  381. }
  382. }
  383. }
  384. @objc func uploadStartFile(_ notification: NSNotification) {
  385. if self.view?.window == nil { return }
  386. if let userInfo = notification.userInfo as NSDictionary? {
  387. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  388. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  389. dataSource.addMetadata(metadata)
  390. self.collectionView?.reloadData()
  391. }
  392. }
  393. }
  394. }
  395. @objc func uploadedFile(_ notification: NSNotification) {
  396. if self.view?.window == nil { return }
  397. if let userInfo = notification.userInfo as NSDictionary? {
  398. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  399. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  400. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  401. collectionView?.reloadData()
  402. }
  403. }
  404. }
  405. }
  406. @objc func uploadCancelFile(_ notification: NSNotification) {
  407. if self.view?.window == nil { return }
  408. if let userInfo = notification.userInfo as NSDictionary? {
  409. if let ocId = userInfo["ocId"] as? String, let serverUrl = userInfo["serverUrl"] as? String, let account = userInfo["account"] as? String {
  410. if serverUrl == self.serverUrl && account == appDelegate.account {
  411. if let row = dataSource.deleteMetadata(ocId: ocId) {
  412. let indexPath = IndexPath(row: row, section: 0)
  413. collectionView?.performBatchUpdates({
  414. collectionView?.deleteItems(at: [indexPath])
  415. }, completion: { (_) in
  416. self.collectionView?.reloadData()
  417. })
  418. } else {
  419. self.reloadDataSource()
  420. }
  421. }
  422. }
  423. }
  424. }
  425. @objc func triggerProgressTask(_ notification: NSNotification) {
  426. if self.view?.window == nil { return }
  427. if let userInfo = notification.userInfo as NSDictionary? {
  428. if let ocId = userInfo["ocId"] as? String {
  429. let _ = userInfo["account"] as? String ?? ""
  430. let _ = userInfo["serverUrl"] as? String ?? ""
  431. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  432. let progress = progressNumber.floatValue
  433. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  434. let totalBytes = userInfo["totalBytes"] as? Int64 ?? 0
  435. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64 ?? 0
  436. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  437. appDelegate.listProgress[ocId] = progressType
  438. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  439. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  440. if cell is NCListCell {
  441. let cell = cell as! NCListCell
  442. if progress > 0 {
  443. cell.progressView?.isHidden = false
  444. cell.progressView?.progress = progress
  445. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  446. if status == NCGlobal.shared.metadataStatusInDownload {
  447. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  448. } else if status == NCGlobal.shared.metadataStatusInUpload {
  449. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  450. }
  451. }
  452. } else if cell is NCTransferCell {
  453. let cell = cell as! NCTransferCell
  454. if progress > 0 {
  455. cell.progressView?.isHidden = false
  456. cell.progressView?.progress = progress
  457. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  458. if status == NCGlobal.shared.metadataStatusInDownload {
  459. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  460. } else if status == NCGlobal.shared.metadataStatusInUpload {
  461. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  462. }
  463. }
  464. } else if cell is NCGridCell {
  465. let cell = cell as! NCGridCell
  466. if progress > 0 {
  467. cell.progressView.isHidden = false
  468. cell.progressView.progress = progress
  469. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  470. }
  471. }
  472. }
  473. }
  474. }
  475. }
  476. }
  477. // MARK: - Empty
  478. func emptyDataSetView(_ view: NCEmptyView) {
  479. if searchController?.isActive ?? false {
  480. view.emptyImage.image = UIImage.init(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  481. if isReloadDataSourceNetworkInProgress {
  482. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  483. } else {
  484. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  485. }
  486. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  487. } else if isReloadDataSourceNetworkInProgress {
  488. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  489. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  490. view.emptyDescription.text = ""
  491. } else {
  492. if serverUrl == "" {
  493. view.emptyImage.image = emptyImage
  494. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  495. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  496. } else {
  497. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  498. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  499. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  500. }
  501. }
  502. }
  503. // MARK: - SEARCH
  504. func updateSearchResults(for searchController: UISearchController) {
  505. timerInputSearch?.invalidate()
  506. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  507. literalSearch = searchController.searchBar.text
  508. collectionView?.reloadData()
  509. }
  510. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  511. isSearching = true
  512. metadatasSource.removeAll()
  513. reloadDataSource()
  514. }
  515. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  516. isSearching = false
  517. literalSearch = ""
  518. reloadDataSource()
  519. }
  520. // MARK: - TAP EVENT
  521. @objc func tapSelect(sender: Any) {
  522. isEditMode = !isEditMode
  523. selectOcId.removeAll()
  524. setNavigationItem()
  525. self.collectionView.reloadData()
  526. }
  527. @objc func profileButtonTapped(sender: Any) {
  528. let accounts = NCManageDatabase.shared.getAllAccount()
  529. if accounts.count > 1 {
  530. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  531. vcAccountRequest.accounts = accounts
  532. vcAccountRequest.enableTimerProgress = false
  533. vcAccountRequest.enableAddAccount = true
  534. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  535. let numberCell = accounts.count + 1
  536. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 65), screenHeighMax)
  537. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  538. popup.backgroundAlpha = 0.8
  539. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  540. }
  541. }
  542. }
  543. func tapSwitchHeader(sender: Any) {
  544. if collectionView.collectionViewLayout == gridLayout {
  545. // list layout
  546. UIView.animate(withDuration: 0.0, animations: {
  547. self.collectionView.collectionViewLayout.invalidateLayout()
  548. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  549. self.collectionView.reloadData()
  550. })
  551. })
  552. layout = NCGlobal.shared.layoutList
  553. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  554. } else {
  555. // grid layout
  556. UIView.animate(withDuration: 0.0, animations: {
  557. self.collectionView.collectionViewLayout.invalidateLayout()
  558. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  559. self.collectionView.reloadData()
  560. })
  561. })
  562. layout = NCGlobal.shared.layoutGrid
  563. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  564. }
  565. }
  566. func tapOrderHeader(sender: Any) {
  567. let sortMenu = NCSortMenu()
  568. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  569. }
  570. @objc func tapSelectMenu(sender: Any) {
  571. guard let tabBarController = self.tabBarController else { return }
  572. toggleMenuSelect(viewController: tabBarController, selectOcId: selectOcId)
  573. }
  574. func tapMoreHeader(sender: Any) { }
  575. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  576. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  577. }
  578. func tapShareListItem(with objectId: String, sender: Any) {
  579. if isEditMode { return }
  580. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  581. NCFunctionCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  582. }
  583. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  584. if isEditMode { return }
  585. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  586. if namedButtonMore == NCGlobal.shared.buttonMoreMore {
  587. toggleMenu(viewController: self, metadata: metadata, image: image)
  588. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  589. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  590. }
  591. }
  592. func tapRichWorkspace(sender: Any) {
  593. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  594. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  595. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  596. viewerRichWorkspace.serverUrl = serverUrl
  597. navigationController.modalPresentationStyle = .fullScreen
  598. self.present(navigationController, animated: true, completion: nil)
  599. }
  600. }
  601. }
  602. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  603. }
  604. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  605. }
  606. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  607. }
  608. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  609. }
  610. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  611. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  612. /*
  613. if #available(iOS 13.0, *) {
  614. let interaction = UIContextMenuInteraction(delegate: self)
  615. self.view.addInteraction(interaction)
  616. }
  617. */
  618. }
  619. @available(iOS 13.0, *)
  620. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  621. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  622. return nil
  623. }, actionProvider: { suggestedActions in
  624. //let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  625. //}
  626. //return UIMenu(title: "Main Menu", children: [share])
  627. return nil
  628. })
  629. }
  630. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  631. if gestureRecognizer.state != .began { return }
  632. if serverUrl == "" { return }
  633. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  634. metadataTouch = metadata
  635. } else {
  636. metadataTouch = nil
  637. }
  638. var listMenuItems: [UIMenuItem] = []
  639. let touchPoint = gestureRecognizer.location(in: collectionView)
  640. becomeFirstResponder()
  641. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  642. if listMenuItems.count > 0 {
  643. UIMenuController.shared.menuItems = listMenuItems
  644. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  645. UIMenuController.shared.setMenuVisible(true, animated: true)
  646. }
  647. }
  648. // MARK: - Menu Item
  649. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  650. if (#selector(pasteFilesMenu) == action) {
  651. if UIPasteboard.general.items.count > 0 {
  652. return true
  653. }
  654. }
  655. return false
  656. }
  657. @objc func pasteFilesMenu() {
  658. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  659. }
  660. // MARK: - DataSource + NC Endpoint
  661. @objc func reloadDataSource() {
  662. if appDelegate.account == "" { return }
  663. // Get richWorkspace Text
  664. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  665. richWorkspaceText = directory?.richWorkspace
  666. // E2EE
  667. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  668. // get auto upload folder
  669. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  670. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  671. // get layout for view
  672. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  673. }
  674. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  675. @objc func reloadDataSourceNetworkRefreshControl() {
  676. reloadDataSourceNetwork(forced: true)
  677. }
  678. @objc func networkSearch() {
  679. if appDelegate.account == "" { return }
  680. if literalSearch?.count ?? 0 > 1 {
  681. isReloadDataSourceNetworkInProgress = true
  682. collectionView?.reloadData()
  683. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  684. if self.searchController?.isActive ?? false && errorCode == 0 {
  685. self.metadatasSource = metadatas!
  686. }
  687. self.refreshControl.endRefreshing()
  688. self.isReloadDataSourceNetworkInProgress = false
  689. self.reloadDataSource()
  690. }
  691. } else {
  692. self.refreshControl.endRefreshing()
  693. }
  694. }
  695. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  696. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  697. if errorCode == 0 {
  698. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  699. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  700. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  701. if errorCode == 0 {
  702. self.metadataFolder = metadataFolder
  703. // E2EE
  704. if let metadataFolder = metadataFolder {
  705. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  706. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  707. if errorCode == 0 && e2eMetadata != nil {
  708. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  709. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  710. } else {
  711. self.reloadDataSource()
  712. }
  713. } else if errorCode != NCGlobal.shared.ErrorResourceNotFound {
  714. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  715. }
  716. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  717. }
  718. } else {
  719. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  720. }
  721. } else {
  722. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  723. }
  724. } else {
  725. completion(nil, nil, errorCode, errorDescription)
  726. }
  727. }
  728. } else {
  729. completion(nil, nil, 0, "")
  730. }
  731. } else {
  732. completion(nil, nil, errorCode, errorDescription)
  733. }
  734. }
  735. }
  736. }
  737. // MARK: - Collection View
  738. extension NCCollectionViewCommon: UICollectionViewDelegate {
  739. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  740. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  741. metadataTouch = metadata
  742. selectedIndexPath = indexPath
  743. if isEditMode {
  744. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  745. selectOcId.remove(at: index)
  746. } else {
  747. selectOcId.append(metadata.ocId)
  748. }
  749. collectionView.reloadItems(at: [indexPath])
  750. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  751. return
  752. }
  753. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  754. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorE2EENotEnabled, forced: true)
  755. return
  756. }
  757. if metadata.directory {
  758. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  759. // FILES
  760. if layoutKey == NCGlobal.shared.layoutViewFiles {
  761. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  762. if viewController.isViewLoaded {
  763. self.navigationController?.pushViewController(viewController, animated: true)
  764. }
  765. } else {
  766. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  767. vcFiles.isRoot = false
  768. vcFiles.serverUrl = serverUrlPush
  769. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  770. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  771. self.navigationController?.pushViewController(vcFiles, animated: true)
  772. }
  773. }
  774. // FAVORITE
  775. if layoutKey == NCGlobal.shared.layoutViewFavorite {
  776. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  777. if viewController.isViewLoaded {
  778. self.navigationController?.pushViewController(viewController, animated: true)
  779. }
  780. } else {
  781. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  782. vcFavorite.serverUrl = serverUrlPush
  783. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  784. appDelegate.listFavoriteVC[serverUrlPush] = vcFavorite
  785. self.navigationController?.pushViewController(vcFavorite, animated: true)
  786. }
  787. }
  788. // OFFLINE
  789. if layoutKey == NCGlobal.shared.layoutViewOffline {
  790. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  791. if viewController.isViewLoaded {
  792. self.navigationController?.pushViewController(viewController, animated: true)
  793. }
  794. } else {
  795. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  796. vcOffline.serverUrl = serverUrlPush
  797. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  798. appDelegate.listOfflineVC[serverUrlPush] = vcOffline
  799. self.navigationController?.pushViewController(vcOffline, animated: true)
  800. }
  801. }
  802. // RECENT ( for push use Files ... he he he )
  803. if layoutKey == NCGlobal.shared.layoutViewRecent {
  804. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  805. if viewController.isViewLoaded {
  806. self.navigationController?.pushViewController(viewController, animated: true)
  807. }
  808. } else {
  809. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  810. vcFiles.isRoot = false
  811. vcFiles.serverUrl = serverUrlPush
  812. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  813. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  814. self.navigationController?.pushViewController(vcFiles, animated: true)
  815. }
  816. }
  817. //VIEW IN FOLDER
  818. if layoutKey == NCGlobal.shared.layoutViewViewInFolder {
  819. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  820. vcFileViewInFolder.serverUrl = serverUrlPush
  821. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  822. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  823. }
  824. // SHARES ( for push use Files ... he he he )
  825. if layoutKey == NCGlobal.shared.layoutViewShares {
  826. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  827. if viewController.isViewLoaded {
  828. self.navigationController?.pushViewController(viewController, animated: true)
  829. }
  830. } else {
  831. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  832. vcFiles.isRoot = false
  833. vcFiles.serverUrl = serverUrlPush
  834. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  835. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  836. self.navigationController?.pushViewController(vcFiles, animated: true)
  837. }
  838. }
  839. } else {
  840. guard let metadataTouch = metadataTouch else { return }
  841. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  842. var metadatas: [tableMetadata] = []
  843. for metadata in dataSource.metadatas {
  844. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  845. metadatas.append(metadata)
  846. }
  847. }
  848. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  849. return
  850. }
  851. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  852. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  853. } else if NCCommunication.shared.isNetworkReachable() {
  854. NCNetworking.shared.download(metadata: metadataTouch, activityIndicator: false, selector: NCGlobal.shared.selectorLoadFileView) { (_) in }
  855. } else {
  856. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorOffline, forced: true)
  857. }
  858. }
  859. }
  860. func collectionViewSelectAll() {
  861. selectOcId.removeAll()
  862. for metadata in metadatasSource {
  863. selectOcId.append(metadata.ocId)
  864. }
  865. collectionView.reloadData()
  866. }
  867. @available(iOS 13.0, *)
  868. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  869. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  870. metadataTouch = metadata
  871. let identifier = indexPath as NSCopying
  872. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  873. return NCViewerProviderContextMenu(metadata: metadata)
  874. }, actionProvider: { suggestedActions in
  875. return NCFunctionCenter.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: true, enableViewInFolder: false)
  876. })
  877. }
  878. @available(iOS 13.0, *)
  879. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  880. animator.addCompletion {
  881. if let indexPath = configuration.identifier as? IndexPath {
  882. self.collectionView(collectionView, didSelectItemAt: indexPath)
  883. }
  884. }
  885. }
  886. }
  887. extension NCCollectionViewCommon: UICollectionViewDataSource {
  888. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  889. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  890. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  891. }
  892. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  893. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  894. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  895. }
  896. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  897. if kind == UICollectionView.elementKindSectionHeader {
  898. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  899. if collectionView.collectionViewLayout == gridLayout {
  900. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  901. } else {
  902. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  903. }
  904. header.delegate = self
  905. header.setStatusButton(count: dataSource.metadatas.count)
  906. header.setTitleSorted(datasourceTitleButton: titleButton)
  907. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  908. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  909. return header
  910. } else {
  911. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  912. let info = dataSource.getFilesInformation()
  913. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  914. return footer
  915. }
  916. }
  917. func numberOfSections(in collectionView: UICollectionView) -> Int {
  918. return 1
  919. }
  920. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  921. let numberItems = dataSource.numberOfItems()
  922. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  923. return numberItems
  924. }
  925. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  926. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  927. if layout == NCGlobal.shared.layoutList {
  928. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  929. } else {
  930. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  931. }
  932. }
  933. var tableShare: tableShare?
  934. var isShare = false
  935. var isMounted = false
  936. if metadataFolder != nil {
  937. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  938. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  939. }
  940. if dataSource.metadataShare[metadata.ocId] != nil {
  941. tableShare = dataSource.metadataShare[metadata.ocId]
  942. }
  943. //
  944. // LAYOUT LIST
  945. //
  946. if layout == NCGlobal.shared.layoutList {
  947. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  948. cell.delegate = self
  949. cell.objectId = metadata.ocId
  950. cell.indexPath = indexPath
  951. cell.labelTitle.text = metadata.fileNameView
  952. cell.labelTitle.textColor = NCBrandColor.shared.textView
  953. cell.separator.backgroundColor = NCBrandColor.shared.separator
  954. cell.imageSelect.image = nil
  955. cell.imageStatus.image = nil
  956. cell.imageLocal.image = nil
  957. cell.imageFavorite.image = nil
  958. cell.imageShared.image = nil
  959. cell.imageShared.clearLayerMask()
  960. cell.imageMore.image = nil
  961. cell.imageItem.image = nil
  962. cell.imageItem.backgroundColor = nil
  963. cell.progressView.progress = 0.0
  964. if metadata.directory {
  965. if metadata.e2eEncrypted {
  966. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  967. } else if isShare {
  968. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  969. } else if (tableShare != nil && tableShare?.shareType != 3) {
  970. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  971. } else if (tableShare != nil && tableShare?.shareType == 3) {
  972. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  973. } else if metadata.mountType == "group" {
  974. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  975. } else if isMounted {
  976. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  977. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  978. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  979. } else {
  980. cell.imageItem.image = NCBrandColor.cacheImages.folder
  981. }
  982. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  983. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  984. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  985. // Local image: offline
  986. if tableDirectory != nil && tableDirectory!.offline {
  987. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  988. }
  989. } else {
  990. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  991. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  992. } else {
  993. if metadata.hasPreview {
  994. cell.imageItem.backgroundColor = .lightGray
  995. } else {
  996. if metadata.iconName.count > 0 {
  997. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  998. } else {
  999. cell.imageItem.image = NCBrandColor.cacheImages.file
  1000. }
  1001. }
  1002. }
  1003. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1004. // image local
  1005. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1006. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1007. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1008. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1009. }
  1010. }
  1011. // image Favorite
  1012. if metadata.favorite {
  1013. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1014. }
  1015. // Share image
  1016. if (isShare) {
  1017. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1018. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1019. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1020. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1021. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1022. } else {
  1023. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1024. }
  1025. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userId {
  1026. var fileNameUser = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId
  1027. fileNameUser = fileNameUser + ".png"
  1028. if FileManager.default.fileExists(atPath: fileNameUser) {
  1029. cell.imageShared.avatar()
  1030. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1031. } else {
  1032. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  1033. if errorCode == 0 && account == self.appDelegate.account {
  1034. cell.imageShared.avatar()
  1035. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1036. }
  1037. }
  1038. }
  1039. }
  1040. // Transfer
  1041. var progress: Float = 0.0
  1042. var totalBytes: Int64 = 0
  1043. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1044. progress = progressType.progress
  1045. totalBytes = progressType.totalBytes
  1046. }
  1047. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1048. cell.progressView.isHidden = false
  1049. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1050. } else {
  1051. cell.progressView.isHidden = true
  1052. cell.progressView.progress = progress
  1053. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1054. }
  1055. // Write status on Label Info
  1056. switch metadata.status {
  1057. case NCGlobal.shared.metadataStatusWaitDownload:
  1058. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1059. break
  1060. case NCGlobal.shared.metadataStatusInDownload:
  1061. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1062. break
  1063. case NCGlobal.shared.metadataStatusDownloading:
  1064. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1065. break
  1066. case NCGlobal.shared.metadataStatusWaitUpload:
  1067. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1068. break
  1069. case NCGlobal.shared.metadataStatusInUpload:
  1070. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1071. break
  1072. case NCGlobal.shared.metadataStatusUploading:
  1073. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1074. break
  1075. default:
  1076. break
  1077. }
  1078. // Live Photo
  1079. if metadata.livePhoto {
  1080. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1081. }
  1082. // E2EE
  1083. if metadata.e2eEncrypted || isEncryptedFolder {
  1084. cell.hideButtonShare(true)
  1085. } else {
  1086. cell.hideButtonShare(false)
  1087. }
  1088. // Remove last separator
  1089. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1090. cell.separator.isHidden = true
  1091. } else {
  1092. cell.separator.isHidden = false
  1093. }
  1094. // Edit mode
  1095. if isEditMode {
  1096. cell.selectMode(true)
  1097. if selectOcId.contains(metadata.ocId) {
  1098. cell.selected(true)
  1099. } else {
  1100. cell.selected(false)
  1101. }
  1102. } else {
  1103. cell.selectMode(false)
  1104. }
  1105. // Disable Share Button
  1106. if appDelegate.disableSharesView {
  1107. cell.hideButtonShare(true)
  1108. }
  1109. return cell
  1110. }
  1111. //
  1112. // LAYOUT GRID
  1113. //
  1114. if layout == NCGlobal.shared.layoutGrid {
  1115. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1116. cell.delegate = self
  1117. cell.objectId = metadata.ocId
  1118. cell.indexPath = indexPath
  1119. cell.labelTitle.text = metadata.fileNameView
  1120. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1121. cell.imageSelect.image = nil
  1122. cell.imageStatus.image = nil
  1123. cell.imageLocal.image = nil
  1124. cell.imageFavorite.image = nil
  1125. cell.imageItem.image = nil
  1126. cell.imageItem.backgroundColor = nil
  1127. cell.progressView.progress = 0.0
  1128. if metadata.directory {
  1129. if metadata.e2eEncrypted {
  1130. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1131. } else if isShare {
  1132. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1133. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1134. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1135. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1136. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1137. } else if metadata.mountType == "group" {
  1138. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1139. } else if isMounted {
  1140. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1141. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1142. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1143. } else {
  1144. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1145. }
  1146. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1147. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1148. // Local image: offline
  1149. if tableDirectory != nil && tableDirectory!.offline {
  1150. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1151. }
  1152. } else {
  1153. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1154. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1155. } else {
  1156. if metadata.hasPreview {
  1157. cell.imageItem.backgroundColor = .lightGray
  1158. } else {
  1159. if metadata.iconName.count > 0 {
  1160. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1161. } else {
  1162. cell.imageItem.image = NCBrandColor.cacheImages.file
  1163. }
  1164. }
  1165. }
  1166. // image Local
  1167. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1168. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1169. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1170. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1171. }
  1172. }
  1173. // image Favorite
  1174. if metadata.favorite {
  1175. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1176. }
  1177. // Transfer
  1178. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1179. cell.progressView.isHidden = false
  1180. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1181. } else {
  1182. cell.progressView.isHidden = true
  1183. cell.progressView.progress = 0.0
  1184. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1185. }
  1186. // Live Photo
  1187. if metadata.livePhoto {
  1188. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1189. }
  1190. // Edit mode
  1191. if isEditMode {
  1192. cell.selectMode(true)
  1193. if selectOcId.contains(metadata.ocId) {
  1194. cell.selected(true)
  1195. } else {
  1196. cell.selected(false)
  1197. }
  1198. } else {
  1199. cell.selectMode(false)
  1200. }
  1201. return cell
  1202. }
  1203. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1204. }
  1205. }
  1206. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1207. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1208. headerRichWorkspaceHeight = 0
  1209. if let richWorkspaceText = richWorkspaceText {
  1210. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1211. if trimmed.count > 0 && !isSearching {
  1212. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1213. }
  1214. }
  1215. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1216. }
  1217. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1218. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1219. }
  1220. }