NCCollectionViewCommon.swift 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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. vcAccountRequest.viewController = self
  535. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  536. let numberCell = accounts.count + 1
  537. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 65), screenHeighMax)
  538. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  539. popup.backgroundAlpha = 0.8
  540. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  541. }
  542. }
  543. }
  544. func tapSwitchHeader(sender: Any) {
  545. if collectionView.collectionViewLayout == gridLayout {
  546. // list layout
  547. UIView.animate(withDuration: 0.0, animations: {
  548. self.collectionView.collectionViewLayout.invalidateLayout()
  549. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  550. self.collectionView.reloadData()
  551. })
  552. })
  553. layout = NCGlobal.shared.layoutList
  554. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  555. } else {
  556. // grid layout
  557. UIView.animate(withDuration: 0.0, animations: {
  558. self.collectionView.collectionViewLayout.invalidateLayout()
  559. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  560. self.collectionView.reloadData()
  561. })
  562. })
  563. layout = NCGlobal.shared.layoutGrid
  564. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  565. }
  566. }
  567. func tapOrderHeader(sender: Any) {
  568. let sortMenu = NCSortMenu()
  569. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  570. }
  571. @objc func tapSelectMenu(sender: Any) {
  572. guard let tabBarController = self.tabBarController else { return }
  573. toggleMenuSelect(viewController: tabBarController, selectOcId: selectOcId)
  574. }
  575. func tapMoreHeader(sender: Any) { }
  576. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  577. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  578. }
  579. func tapShareListItem(with objectId: String, sender: Any) {
  580. if isEditMode { return }
  581. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  582. NCFunctionCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  583. }
  584. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  585. if isEditMode { return }
  586. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  587. if namedButtonMore == NCGlobal.shared.buttonMoreMore {
  588. toggleMenu(viewController: self, metadata: metadata, image: image)
  589. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  590. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  591. }
  592. }
  593. func tapRichWorkspace(sender: Any) {
  594. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  595. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  596. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  597. viewerRichWorkspace.serverUrl = serverUrl
  598. navigationController.modalPresentationStyle = .fullScreen
  599. self.present(navigationController, animated: true, completion: nil)
  600. }
  601. }
  602. }
  603. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  604. }
  605. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  606. }
  607. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  608. }
  609. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  610. }
  611. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  612. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  613. /*
  614. if #available(iOS 13.0, *) {
  615. let interaction = UIContextMenuInteraction(delegate: self)
  616. self.view.addInteraction(interaction)
  617. }
  618. */
  619. }
  620. @available(iOS 13.0, *)
  621. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  622. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  623. return nil
  624. }, actionProvider: { suggestedActions in
  625. //let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  626. //}
  627. //return UIMenu(title: "Main Menu", children: [share])
  628. return nil
  629. })
  630. }
  631. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  632. if gestureRecognizer.state != .began { return }
  633. if serverUrl == "" { return }
  634. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  635. metadataTouch = metadata
  636. } else {
  637. metadataTouch = nil
  638. }
  639. var listMenuItems: [UIMenuItem] = []
  640. let touchPoint = gestureRecognizer.location(in: collectionView)
  641. becomeFirstResponder()
  642. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  643. if listMenuItems.count > 0 {
  644. UIMenuController.shared.menuItems = listMenuItems
  645. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  646. UIMenuController.shared.setMenuVisible(true, animated: true)
  647. }
  648. }
  649. // MARK: - Menu Item
  650. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  651. if (#selector(pasteFilesMenu) == action) {
  652. if UIPasteboard.general.items.count > 0 {
  653. return true
  654. }
  655. }
  656. return false
  657. }
  658. @objc func pasteFilesMenu() {
  659. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  660. }
  661. // MARK: - DataSource + NC Endpoint
  662. @objc func reloadDataSource() {
  663. if appDelegate.account == "" { return }
  664. // Get richWorkspace Text
  665. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  666. richWorkspaceText = directory?.richWorkspace
  667. // E2EE
  668. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  669. // get auto upload folder
  670. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  671. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  672. // get layout for view
  673. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  674. }
  675. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  676. @objc func reloadDataSourceNetworkRefreshControl() {
  677. reloadDataSourceNetwork(forced: true)
  678. }
  679. @objc func networkSearch() {
  680. if appDelegate.account == "" { return }
  681. if literalSearch?.count ?? 0 > 1 {
  682. isReloadDataSourceNetworkInProgress = true
  683. collectionView?.reloadData()
  684. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  685. if self.searchController?.isActive ?? false && errorCode == 0 {
  686. self.metadatasSource = metadatas!
  687. }
  688. self.refreshControl.endRefreshing()
  689. self.isReloadDataSourceNetworkInProgress = false
  690. self.reloadDataSource()
  691. }
  692. } else {
  693. self.refreshControl.endRefreshing()
  694. }
  695. }
  696. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  697. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  698. if errorCode == 0 {
  699. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  700. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  701. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  702. if errorCode == 0 {
  703. self.metadataFolder = metadataFolder
  704. // E2EE
  705. if let metadataFolder = metadataFolder {
  706. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  707. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  708. if errorCode == 0 && e2eMetadata != nil {
  709. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  710. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  711. } else {
  712. self.reloadDataSource()
  713. }
  714. } else if errorCode != NCGlobal.shared.ErrorResourceNotFound {
  715. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  716. }
  717. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  718. }
  719. } else {
  720. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  721. }
  722. } else {
  723. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  724. }
  725. } else {
  726. completion(nil, nil, errorCode, errorDescription)
  727. }
  728. }
  729. } else {
  730. completion(nil, nil, 0, "")
  731. }
  732. } else {
  733. completion(nil, nil, errorCode, errorDescription)
  734. }
  735. }
  736. }
  737. }
  738. // MARK: - Collection View
  739. extension NCCollectionViewCommon: UICollectionViewDelegate {
  740. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  741. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  742. metadataTouch = metadata
  743. selectedIndexPath = indexPath
  744. if isEditMode {
  745. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  746. selectOcId.remove(at: index)
  747. } else {
  748. selectOcId.append(metadata.ocId)
  749. }
  750. collectionView.reloadItems(at: [indexPath])
  751. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  752. return
  753. }
  754. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  755. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorE2EENotEnabled, forced: true)
  756. return
  757. }
  758. if metadata.directory {
  759. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  760. // FILES
  761. if layoutKey == NCGlobal.shared.layoutViewFiles {
  762. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  763. if viewController.isViewLoaded {
  764. self.navigationController?.pushViewController(viewController, animated: true)
  765. }
  766. } else {
  767. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  768. vcFiles.isRoot = false
  769. vcFiles.serverUrl = serverUrlPush
  770. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  771. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  772. self.navigationController?.pushViewController(vcFiles, animated: true)
  773. }
  774. }
  775. // FAVORITE
  776. if layoutKey == NCGlobal.shared.layoutViewFavorite {
  777. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  778. if viewController.isViewLoaded {
  779. self.navigationController?.pushViewController(viewController, animated: true)
  780. }
  781. } else {
  782. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  783. vcFavorite.serverUrl = serverUrlPush
  784. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  785. appDelegate.listFavoriteVC[serverUrlPush] = vcFavorite
  786. self.navigationController?.pushViewController(vcFavorite, animated: true)
  787. }
  788. }
  789. // OFFLINE
  790. if layoutKey == NCGlobal.shared.layoutViewOffline {
  791. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  792. if viewController.isViewLoaded {
  793. self.navigationController?.pushViewController(viewController, animated: true)
  794. }
  795. } else {
  796. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  797. vcOffline.serverUrl = serverUrlPush
  798. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  799. appDelegate.listOfflineVC[serverUrlPush] = vcOffline
  800. self.navigationController?.pushViewController(vcOffline, animated: true)
  801. }
  802. }
  803. // RECENT ( for push use Files ... he he he )
  804. if layoutKey == NCGlobal.shared.layoutViewRecent {
  805. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  806. if viewController.isViewLoaded {
  807. self.navigationController?.pushViewController(viewController, animated: true)
  808. }
  809. } else {
  810. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  811. vcFiles.isRoot = false
  812. vcFiles.serverUrl = serverUrlPush
  813. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  814. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  815. self.navigationController?.pushViewController(vcFiles, animated: true)
  816. }
  817. }
  818. //VIEW IN FOLDER
  819. if layoutKey == NCGlobal.shared.layoutViewViewInFolder {
  820. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  821. vcFileViewInFolder.serverUrl = serverUrlPush
  822. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  823. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  824. }
  825. // SHARES ( for push use Files ... he he he )
  826. if layoutKey == NCGlobal.shared.layoutViewShares {
  827. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  828. if viewController.isViewLoaded {
  829. self.navigationController?.pushViewController(viewController, animated: true)
  830. }
  831. } else {
  832. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  833. vcFiles.isRoot = false
  834. vcFiles.serverUrl = serverUrlPush
  835. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  836. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  837. self.navigationController?.pushViewController(vcFiles, animated: true)
  838. }
  839. }
  840. } else {
  841. guard let metadataTouch = metadataTouch else { return }
  842. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  843. var metadatas: [tableMetadata] = []
  844. for metadata in dataSource.metadatas {
  845. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  846. metadatas.append(metadata)
  847. }
  848. }
  849. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  850. return
  851. }
  852. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  853. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  854. } else if NCCommunication.shared.isNetworkReachable() {
  855. NCNetworking.shared.download(metadata: metadataTouch, activityIndicator: false, selector: NCGlobal.shared.selectorLoadFileView) { (_) in }
  856. } else {
  857. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorOffline, forced: true)
  858. }
  859. }
  860. }
  861. func collectionViewSelectAll() {
  862. selectOcId.removeAll()
  863. for metadata in metadatasSource {
  864. selectOcId.append(metadata.ocId)
  865. }
  866. collectionView.reloadData()
  867. }
  868. @available(iOS 13.0, *)
  869. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  870. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  871. metadataTouch = metadata
  872. let identifier = indexPath as NSCopying
  873. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  874. return NCViewerProviderContextMenu(metadata: metadata)
  875. }, actionProvider: { suggestedActions in
  876. return NCFunctionCenter.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: true, enableViewInFolder: false)
  877. })
  878. }
  879. @available(iOS 13.0, *)
  880. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  881. animator.addCompletion {
  882. if let indexPath = configuration.identifier as? IndexPath {
  883. self.collectionView(collectionView, didSelectItemAt: indexPath)
  884. }
  885. }
  886. }
  887. }
  888. extension NCCollectionViewCommon: UICollectionViewDataSource {
  889. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  890. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  891. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  892. }
  893. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  894. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  895. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  896. }
  897. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  898. if kind == UICollectionView.elementKindSectionHeader {
  899. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  900. if collectionView.collectionViewLayout == gridLayout {
  901. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  902. } else {
  903. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  904. }
  905. header.delegate = self
  906. header.setStatusButton(count: dataSource.metadatas.count)
  907. header.setTitleSorted(datasourceTitleButton: titleButton)
  908. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  909. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  910. return header
  911. } else {
  912. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  913. let info = dataSource.getFilesInformation()
  914. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  915. return footer
  916. }
  917. }
  918. func numberOfSections(in collectionView: UICollectionView) -> Int {
  919. return 1
  920. }
  921. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  922. let numberItems = dataSource.numberOfItems()
  923. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  924. return numberItems
  925. }
  926. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  927. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  928. if layout == NCGlobal.shared.layoutList {
  929. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  930. } else {
  931. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  932. }
  933. }
  934. var tableShare: tableShare?
  935. var isShare = false
  936. var isMounted = false
  937. if metadataFolder != nil {
  938. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  939. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  940. }
  941. if dataSource.metadataShare[metadata.ocId] != nil {
  942. tableShare = dataSource.metadataShare[metadata.ocId]
  943. }
  944. //
  945. // LAYOUT LIST
  946. //
  947. if layout == NCGlobal.shared.layoutList {
  948. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  949. cell.delegate = self
  950. cell.objectId = metadata.ocId
  951. cell.indexPath = indexPath
  952. cell.labelTitle.text = metadata.fileNameView
  953. cell.labelTitle.textColor = NCBrandColor.shared.textView
  954. cell.separator.backgroundColor = NCBrandColor.shared.separator
  955. cell.imageSelect.image = nil
  956. cell.imageStatus.image = nil
  957. cell.imageLocal.image = nil
  958. cell.imageFavorite.image = nil
  959. cell.imageShared.image = nil
  960. cell.imageShared.clearLayerMask()
  961. cell.imageMore.image = nil
  962. cell.imageItem.image = nil
  963. cell.imageItem.backgroundColor = nil
  964. cell.progressView.progress = 0.0
  965. if metadata.directory {
  966. if metadata.e2eEncrypted {
  967. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  968. } else if isShare {
  969. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  970. } else if (tableShare != nil && tableShare?.shareType != 3) {
  971. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  972. } else if (tableShare != nil && tableShare?.shareType == 3) {
  973. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  974. } else if metadata.mountType == "group" {
  975. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  976. } else if isMounted {
  977. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  978. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  979. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  980. } else {
  981. cell.imageItem.image = NCBrandColor.cacheImages.folder
  982. }
  983. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  984. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  985. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  986. // Local image: offline
  987. if tableDirectory != nil && tableDirectory!.offline {
  988. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  989. }
  990. } else {
  991. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  992. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  993. } else {
  994. if metadata.hasPreview {
  995. cell.imageItem.backgroundColor = .lightGray
  996. } else {
  997. if metadata.iconName.count > 0 {
  998. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  999. } else {
  1000. cell.imageItem.image = NCBrandColor.cacheImages.file
  1001. }
  1002. }
  1003. }
  1004. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1005. // image local
  1006. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1007. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1008. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1009. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1010. }
  1011. }
  1012. // image Favorite
  1013. if metadata.favorite {
  1014. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1015. }
  1016. // Share image
  1017. if (isShare) {
  1018. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1019. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1020. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1021. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1022. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1023. } else {
  1024. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1025. }
  1026. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userId {
  1027. var fileNameUser = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId
  1028. fileNameUser = fileNameUser + ".png"
  1029. if FileManager.default.fileExists(atPath: fileNameUser) {
  1030. cell.imageShared.avatar()
  1031. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1032. } else {
  1033. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  1034. if errorCode == 0 && account == self.appDelegate.account {
  1035. cell.imageShared.avatar()
  1036. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1037. }
  1038. }
  1039. }
  1040. }
  1041. // Transfer
  1042. var progress: Float = 0.0
  1043. var totalBytes: Int64 = 0
  1044. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1045. progress = progressType.progress
  1046. totalBytes = progressType.totalBytes
  1047. }
  1048. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1049. cell.progressView.isHidden = false
  1050. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1051. } else {
  1052. cell.progressView.isHidden = true
  1053. cell.progressView.progress = progress
  1054. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1055. }
  1056. // Write status on Label Info
  1057. switch metadata.status {
  1058. case NCGlobal.shared.metadataStatusWaitDownload:
  1059. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1060. break
  1061. case NCGlobal.shared.metadataStatusInDownload:
  1062. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1063. break
  1064. case NCGlobal.shared.metadataStatusDownloading:
  1065. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1066. break
  1067. case NCGlobal.shared.metadataStatusWaitUpload:
  1068. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1069. break
  1070. case NCGlobal.shared.metadataStatusInUpload:
  1071. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1072. break
  1073. case NCGlobal.shared.metadataStatusUploading:
  1074. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1075. break
  1076. default:
  1077. break
  1078. }
  1079. // Live Photo
  1080. if metadata.livePhoto {
  1081. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1082. }
  1083. // E2EE
  1084. if metadata.e2eEncrypted || isEncryptedFolder {
  1085. cell.hideButtonShare(true)
  1086. } else {
  1087. cell.hideButtonShare(false)
  1088. }
  1089. // Remove last separator
  1090. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1091. cell.separator.isHidden = true
  1092. } else {
  1093. cell.separator.isHidden = false
  1094. }
  1095. // Edit mode
  1096. if isEditMode {
  1097. cell.selectMode(true)
  1098. if selectOcId.contains(metadata.ocId) {
  1099. cell.selected(true)
  1100. } else {
  1101. cell.selected(false)
  1102. }
  1103. } else {
  1104. cell.selectMode(false)
  1105. }
  1106. // Disable Share Button
  1107. if appDelegate.disableSharesView {
  1108. cell.hideButtonShare(true)
  1109. }
  1110. return cell
  1111. }
  1112. //
  1113. // LAYOUT GRID
  1114. //
  1115. if layout == NCGlobal.shared.layoutGrid {
  1116. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1117. cell.delegate = self
  1118. cell.objectId = metadata.ocId
  1119. cell.indexPath = indexPath
  1120. cell.labelTitle.text = metadata.fileNameView
  1121. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1122. cell.imageSelect.image = nil
  1123. cell.imageStatus.image = nil
  1124. cell.imageLocal.image = nil
  1125. cell.imageFavorite.image = nil
  1126. cell.imageItem.image = nil
  1127. cell.imageItem.backgroundColor = nil
  1128. cell.progressView.progress = 0.0
  1129. if metadata.directory {
  1130. if metadata.e2eEncrypted {
  1131. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1132. } else if isShare {
  1133. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1134. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1135. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1136. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1137. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1138. } else if metadata.mountType == "group" {
  1139. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1140. } else if isMounted {
  1141. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1142. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1143. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1144. } else {
  1145. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1146. }
  1147. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1148. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1149. // Local image: offline
  1150. if tableDirectory != nil && tableDirectory!.offline {
  1151. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1152. }
  1153. } else {
  1154. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1155. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1156. } else {
  1157. if metadata.hasPreview {
  1158. cell.imageItem.backgroundColor = .lightGray
  1159. } else {
  1160. if metadata.iconName.count > 0 {
  1161. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1162. } else {
  1163. cell.imageItem.image = NCBrandColor.cacheImages.file
  1164. }
  1165. }
  1166. }
  1167. // image Local
  1168. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1169. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1170. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1171. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1172. }
  1173. }
  1174. // image Favorite
  1175. if metadata.favorite {
  1176. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1177. }
  1178. // Transfer
  1179. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1180. cell.progressView.isHidden = false
  1181. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1182. } else {
  1183. cell.progressView.isHidden = true
  1184. cell.progressView.progress = 0.0
  1185. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1186. }
  1187. // Live Photo
  1188. if metadata.livePhoto {
  1189. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1190. }
  1191. // Edit mode
  1192. if isEditMode {
  1193. cell.selectMode(true)
  1194. if selectOcId.contains(metadata.ocId) {
  1195. cell.selected(true)
  1196. } else {
  1197. cell.selected(false)
  1198. }
  1199. } else {
  1200. cell.selectMode(false)
  1201. }
  1202. return cell
  1203. }
  1204. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1205. }
  1206. }
  1207. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1208. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1209. headerRichWorkspaceHeight = 0
  1210. if let richWorkspaceText = richWorkspaceText {
  1211. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1212. if trimmed.count > 0 && !isSearching {
  1213. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1214. }
  1215. }
  1216. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1217. }
  1218. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1219. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1220. }
  1221. }