NCCollectionViewCommon.swift 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  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 UIKit
  24. import Realm
  25. import NCCommunication
  26. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate, NCAccountRequestDelegate, NCBackgroundImageColorDelegate, NCSelectableNavigationView {
  27. @IBOutlet weak var collectionView: UICollectionView!
  28. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. internal let refreshControl = UIRefreshControl()
  30. internal var searchController: UISearchController?
  31. internal var emptyDataSet: NCEmptyDataSet?
  32. internal var backgroundImageView = UIImageView()
  33. internal var serverUrl: String = ""
  34. internal var isEncryptedFolder = false
  35. internal var isEditMode = false
  36. internal var selectOcId: [String] = []
  37. internal var metadatasSource: [tableMetadata] = []
  38. internal var metadataFolder: tableMetadata?
  39. internal var dataSource = NCDataSource()
  40. internal var richWorkspaceText: String?
  41. internal var headerMenu: NCSectionHeaderMenu?
  42. internal var layoutForView: NCGlobal.layoutForViewType?
  43. internal var selectableDataSource: [RealmSwiftObject] { dataSource.metadatasSource }
  44. private var autoUploadFileName = ""
  45. private var autoUploadDirectory = ""
  46. internal var groupByField = "name"
  47. internal var providers: [NCCSearchProvider]?
  48. internal var listLayout: NCListLayout!
  49. internal var gridLayout: NCGridLayout!
  50. internal var literalSearch: String?
  51. internal var isSearching: Bool = false
  52. internal var isReloadDataSourceNetworkInProgress: Bool = false
  53. private var pushed: Bool = false
  54. // DECLARE
  55. internal var layoutKey = ""
  56. internal var titleCurrentFolder = ""
  57. internal var enableSearchBar: Bool = false
  58. internal var headerMenuButtonsCommand: Bool = true
  59. internal var headerMenuButtonsView: Bool = true
  60. internal var headerRichWorkspaceDisable:Bool = false
  61. internal var emptyImage: UIImage?
  62. internal var emptyTitle: String = ""
  63. internal var emptyDescription: String = ""
  64. // MARK: - View Life Cycle
  65. required init?(coder aDecoder: NSCoder) {
  66. super.init(coder: aDecoder)
  67. }
  68. override func viewDidLoad() {
  69. super.viewDidLoad()
  70. self.navigationController?.presentationController?.delegate = self
  71. collectionView.alwaysBounceVertical = true
  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. searchController?.searchBar.autocapitalizationType = .none
  79. navigationItem.searchController = searchController
  80. navigationItem.hidesSearchBarWhenScrolling = false
  81. }
  82. // Cell
  83. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  84. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  85. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  86. // Header
  87. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  88. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  89. // Footer
  90. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  91. listLayout = NCListLayout()
  92. gridLayout = NCGridLayout()
  93. // Refresh Control
  94. collectionView.addSubview(refreshControl)
  95. refreshControl.action(for: .valueChanged) { _ in
  96. self.reloadDataSourceNetwork(forced: true)
  97. }
  98. // Empty
  99. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: getHeaderHeight(), delegate: self)
  100. // Long Press on CollectionView
  101. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  102. longPressedGesture.minimumPressDuration = 0.5
  103. longPressedGesture.delegate = self
  104. longPressedGesture.delaysTouchesBegan = true
  105. collectionView.addGestureRecognizer(longPressedGesture)
  106. // Notification
  107. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  109. changeTheming()
  110. }
  111. override func viewWillAppear(_ animated: Bool) {
  112. super.viewWillAppear(animated)
  113. // ACTIVE
  114. appDelegate.activeViewController = self
  115. //
  116. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(setNavigationItem), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  125. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  126. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  127. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  128. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  129. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  130. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  131. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  132. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  133. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  134. if serverUrl == "" {
  135. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
  136. } else {
  137. appDelegate.activeServerUrl = serverUrl
  138. }
  139. navigationController?.navigationBar.prefersLargeTitles = true
  140. navigationController?.setNavigationBarHidden(false, animated: true)
  141. setNavigationItem()
  142. changeTheming()
  143. reloadDataSource()
  144. }
  145. override func viewDidAppear(_ animated: Bool) {
  146. super.viewDidAppear(animated)
  147. if !isSearching {
  148. reloadDataSourceNetwork()
  149. }
  150. }
  151. override func viewWillDisappear(_ animated: Bool) {
  152. super.viewWillDisappear(animated)
  153. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  154. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  155. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  156. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  157. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  158. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  159. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  160. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  161. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  162. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  163. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  164. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  165. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  166. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  167. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  168. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  169. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  170. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  171. pushed = false
  172. // REQUEST
  173. NCNetworking.shared.cancelUnifiedSearchFiles()
  174. }
  175. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  176. let viewController = presentationController.presentedViewController
  177. if viewController is NCViewerRichWorkspaceWebView {
  178. closeRichWorkspaceWebView()
  179. }
  180. }
  181. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  182. super.viewWillTransition(to: size, with: coordinator)
  183. coordinator.animate(alongsideTransition: nil) { _ in
  184. self.collectionView?.collectionViewLayout.invalidateLayout()
  185. }
  186. }
  187. override var canBecomeFirstResponder: Bool {
  188. return true
  189. }
  190. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  191. super.traitCollectionDidChange(previousTraitCollection)
  192. changeTheming()
  193. }
  194. // MARK: - NotificationCenter
  195. @objc func initialize() {
  196. if appDelegate.account == "" { return }
  197. // Search
  198. if searchController?.isActive ?? false {
  199. searchController?.isActive = false
  200. }
  201. // Select
  202. if isEditMode {
  203. isEditMode = !isEditMode
  204. selectOcId.removeAll()
  205. }
  206. if self.view?.window != nil {
  207. if serverUrl == "" {
  208. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account)
  209. } else {
  210. appDelegate.activeServerUrl = serverUrl
  211. }
  212. appDelegate.listFilesVC.removeAll()
  213. appDelegate.listFavoriteVC.removeAll()
  214. appDelegate.listOfflineVC.removeAll()
  215. }
  216. if serverUrl != "" {
  217. self.navigationController?.popToRootViewController(animated: false)
  218. }
  219. setNavigationItem()
  220. reloadDataSource()
  221. changeTheming()
  222. }
  223. @objc func changeTheming() {
  224. view.backgroundColor = NCBrandColor.shared.systemBackground
  225. collectionView.backgroundColor = NCBrandColor.shared.systemBackground
  226. refreshControl.tintColor = .gray
  227. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  228. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  229. if layoutForView?.layout == NCGlobal.shared.layoutList {
  230. collectionView?.collectionViewLayout = listLayout
  231. } else {
  232. collectionView?.collectionViewLayout = gridLayout
  233. }
  234. // IMAGE BACKGROUND
  235. if layoutForView?.imageBackgroud != "" {
  236. let imagePath = CCUtility.getDirectoryGroup().appendingPathComponent(NCGlobal.shared.appBackground).path + "/" + layoutForView!.imageBackgroud
  237. do {
  238. let data = try Data(contentsOf: URL(fileURLWithPath: imagePath))
  239. if let image = UIImage(data: data) {
  240. backgroundImageView.image = image
  241. backgroundImageView.contentMode = .scaleToFill
  242. collectionView.backgroundView = backgroundImageView
  243. }
  244. } catch { }
  245. } else {
  246. backgroundImageView.image = nil
  247. collectionView.backgroundView = nil
  248. }
  249. // COLOR BACKGROUND
  250. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  251. if traitCollection.userInterfaceStyle == .dark {
  252. if activeAccount?.darkColorBackground != "" {
  253. collectionView.backgroundColor = UIColor(hex: activeAccount?.darkColorBackground ?? "")
  254. } else {
  255. collectionView.backgroundColor = NCBrandColor.shared.systemBackground
  256. }
  257. } else {
  258. if activeAccount?.lightColorBackground != "" {
  259. collectionView.backgroundColor = UIColor(hex: activeAccount?.lightColorBackground ?? "")
  260. } else {
  261. collectionView.backgroundColor = NCBrandColor.shared.systemBackground
  262. }
  263. }
  264. collectionView.reloadData()
  265. }
  266. @objc func reloadDataSource(_ notification: NSNotification) {
  267. reloadDataSource()
  268. }
  269. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  270. guard let userInfo = notification.userInfo as NSDictionary?,
  271. let serverUrl = userInfo["serverUrl"] as? String,
  272. serverUrl == self.serverUrl
  273. else {
  274. return
  275. }
  276. reloadDataSourceNetwork(forced: true)
  277. }
  278. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  279. reloadDataSource()
  280. }
  281. @objc func closeRichWorkspaceWebView() {
  282. reloadDataSourceNetwork()
  283. }
  284. @objc func deleteFile(_ notification: NSNotification) {
  285. guard let userInfo = notification.userInfo as NSDictionary?,
  286. let ocId = userInfo["ocId"] as? String,
  287. let fileNameView = userInfo["fileNameView"] as? String,
  288. let serverUrl = userInfo["serverUrl"] as? String,
  289. let account = userInfo["account"] as? String,
  290. (serverUrl == serverUrl && account == appDelegate.account)
  291. else {
  292. return
  293. }
  294. if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  295. reloadDataSourceNetwork(forced: true)
  296. } else {
  297. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  298. if let indexPath = indexPath {
  299. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  300. collectionView?.performBatchUpdates({
  301. collectionView?.deleteItems(at: [indexPath])
  302. }, completion: { _ in
  303. self.collectionView?.reloadData()
  304. })
  305. } else {
  306. self.collectionView?.reloadData()
  307. }
  308. } else {
  309. reloadDataSource()
  310. }
  311. }
  312. }
  313. @objc func moveFile(_ notification: NSNotification) {
  314. guard let userInfo = notification.userInfo as NSDictionary?,
  315. let ocId = userInfo["ocId"] as? String,
  316. let serverUrlFrom = userInfo["serverUrlFrom"] as? String,
  317. serverUrlFrom == self.serverUrl
  318. else {
  319. return
  320. }
  321. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  322. if let indexPath = indexPath {
  323. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  324. collectionView?.performBatchUpdates({
  325. collectionView?.deleteItems(at: [indexPath])
  326. }, completion: { _ in
  327. self.collectionView?.reloadData()
  328. })
  329. } else {
  330. self.collectionView?.reloadData()
  331. }
  332. } else {
  333. reloadDataSource()
  334. }
  335. }
  336. @objc func copyFile(_ notification: NSNotification) {
  337. guard let userInfo = notification.userInfo as NSDictionary?,
  338. let serverUrlTo = userInfo["serverUrlTo"] as? String,
  339. serverUrlTo == self.serverUrl
  340. else {
  341. return
  342. }
  343. reloadDataSource()
  344. }
  345. @objc func renameFile(_ notification: NSNotification) {
  346. reloadDataSource()
  347. }
  348. @objc func createFolder(_ notification: NSNotification) {
  349. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId), (metadata.serverUrl == serverUrl && metadata.account == appDelegate.account ) {
  350. pushMetadata(metadata)
  351. } else {
  352. reloadDataSourceNetwork()
  353. }
  354. }
  355. @objc func favoriteFile(_ notification: NSNotification) {
  356. guard let userInfo = notification.userInfo as NSDictionary?,
  357. let ocId = userInfo["ocId"] as? String
  358. else {
  359. reloadDataSource()
  360. return
  361. }
  362. dataSource.reloadMetadata(ocId: ocId)
  363. collectionView?.reloadData()
  364. }
  365. @objc func downloadStartFile(_ notification: NSNotification) {
  366. guard let userInfo = notification.userInfo as NSDictionary?,
  367. let ocId = userInfo["ocId"] as? String
  368. else {
  369. reloadDataSource()
  370. return
  371. }
  372. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  373. if let indexPath = indexPath {
  374. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  375. collectionView?.reloadItems(at: [indexPath])
  376. } else {
  377. self.collectionView?.reloadData()
  378. }
  379. } else {
  380. reloadDataSource()
  381. }
  382. }
  383. @objc func downloadedFile(_ notification: NSNotification) {
  384. guard let userInfo = notification.userInfo as NSDictionary?,
  385. let ocId = userInfo["ocId"] as? String
  386. else {
  387. reloadDataSource()
  388. return
  389. }
  390. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  391. if let indexPath = indexPath {
  392. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  393. collectionView?.reloadItems(at: [indexPath])
  394. } else {
  395. self.collectionView?.reloadData()
  396. }
  397. } else {
  398. reloadDataSource()
  399. }
  400. }
  401. @objc func downloadCancelFile(_ notification: NSNotification) {
  402. guard let userInfo = notification.userInfo as NSDictionary?,
  403. let ocId = userInfo["ocId"] as? String
  404. else {
  405. reloadDataSource()
  406. return
  407. }
  408. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  409. if let indexPath = indexPath {
  410. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  411. collectionView?.reloadItems(at: [indexPath])
  412. } else {
  413. self.collectionView?.reloadData()
  414. }
  415. } else {
  416. reloadDataSource()
  417. }
  418. }
  419. @objc func uploadStartFile(_ notification: NSNotification) {
  420. guard let userInfo = notification.userInfo as NSDictionary?,
  421. let ocId = userInfo["ocId"] as? String,
  422. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId),
  423. (metadata.serverUrl == serverUrl && metadata.account == appDelegate.account)
  424. else {
  425. return
  426. }
  427. dataSource.addMetadata(metadata)
  428. self.collectionView?.reloadData()
  429. }
  430. @objc func uploadedFile(_ notification: NSNotification) {
  431. guard let userInfo = notification.userInfo as NSDictionary?,
  432. let ocId = userInfo["ocId"] as? String,
  433. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  434. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId),
  435. (metadata.serverUrl == serverUrl && metadata.account == appDelegate.account)
  436. else {
  437. return
  438. }
  439. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  440. if let indexPath = indexPath {
  441. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  442. collectionView?.performBatchUpdates({
  443. collectionView?.reloadItems(at: [indexPath])
  444. }, completion: { _ in
  445. self.collectionView?.reloadData()
  446. })
  447. } else {
  448. self.collectionView?.reloadData()
  449. }
  450. } else {
  451. reloadDataSource()
  452. }
  453. }
  454. @objc func uploadCancelFile(_ notification: NSNotification) {
  455. guard let userInfo = notification.userInfo as NSDictionary?,
  456. let ocId = userInfo["ocId"] as? String,
  457. let serverUrl = userInfo["serverUrl"] as? String,
  458. let account = userInfo["account"] as? String,
  459. (serverUrl == self.serverUrl && account == appDelegate.account)
  460. else {
  461. return
  462. }
  463. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  464. if let indexPath = indexPath {
  465. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  466. collectionView?.performBatchUpdates({
  467. collectionView?.deleteItems(at: [indexPath])
  468. }, completion: { _ in
  469. self.collectionView?.reloadData()
  470. })
  471. } else {
  472. self.collectionView?.reloadData()
  473. }
  474. } else {
  475. reloadDataSource()
  476. }
  477. }
  478. @objc func triggerProgressTask(_ notification: NSNotification) {
  479. guard let userInfo = notification.userInfo as NSDictionary?,
  480. let progressNumber = userInfo["progress"] as? NSNumber,
  481. let totalBytes = userInfo["totalBytes"] as? Int64,
  482. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  483. let ocId = userInfo["ocId"] as? String,
  484. let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: ocId) as? (IndexPath, NCMetadatasForSection?)
  485. else {
  486. return
  487. }
  488. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  489. if let cell = collectionView?.cellForItem(at: indexPath) {
  490. if var cell = cell as? NCCellProtocol {
  491. if progressNumber.floatValue == 1 {
  492. cell.progress?.isHidden = true
  493. cell.progress?.progress = .zero
  494. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  495. cell.info = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  496. } else {
  497. cell.info = ""
  498. }
  499. } else {
  500. cell.progress?.isHidden = false
  501. cell.progress?.progress = progressNumber.floatValue
  502. if status == NCGlobal.shared.metadataStatusInDownload {
  503. cell.info = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  504. } else if status == NCGlobal.shared.metadataStatusInUpload {
  505. cell.info = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  506. }
  507. }
  508. }
  509. /*
  510. if cell is NCListCell {
  511. let cell = cell as! NCListCell
  512. if progressNumber.floatValue == 1 {
  513. cell.progressView?.isHidden = true
  514. cell.progressView?.progress = .zero
  515. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  516. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  517. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  518. } else {
  519. cell.labelInfo.text = ""
  520. }
  521. } else if progressNumber.floatValue > 0 {
  522. cell.progressView?.isHidden = false
  523. cell.progressView?.progress = progressNumber.floatValue
  524. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  525. if status == NCGlobal.shared.metadataStatusInDownload {
  526. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  527. } else if status == NCGlobal.shared.metadataStatusInUpload {
  528. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  529. }
  530. }
  531. } else if cell is NCGridCell {
  532. let cell = cell as! NCGridCell
  533. if progressNumber.floatValue == 1 {
  534. cell.progressView.isHidden = true
  535. cell.progressView.progress = .zero
  536. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  537. } else if progressNumber.floatValue > 0 {
  538. cell.progressView.isHidden = false
  539. cell.progressView.progress = progressNumber.floatValue
  540. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  541. }
  542. }
  543. */
  544. }
  545. }
  546. // MARK: - Layout
  547. @objc func setNavigationItem() {
  548. self.setNavigationHeader()
  549. guard !isEditMode, layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  550. // PROFILE BUTTON
  551. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  552. let image = NCUtility.shared.loadUserImage(
  553. for: appDelegate.user,
  554. displayName: activeAccount?.displayName,
  555. userBaseUrl: appDelegate)
  556. let button = UIButton(type: .custom)
  557. button.setImage(image, for: .normal)
  558. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
  559. var titleButton = " "
  560. if getNavigationTitle() == activeAccount?.alias {
  561. titleButton = ""
  562. } else {
  563. titleButton += activeAccount?.displayName ?? ""
  564. }
  565. button.setTitle(titleButton, for: .normal)
  566. button.setTitleColor(.systemBlue, for: .normal)
  567. }
  568. button.semanticContentAttribute = .forceLeftToRight
  569. button.sizeToFit()
  570. button.action(for: .touchUpInside) { _ in
  571. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  572. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  573. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  574. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  575. vcAccountRequest.accounts = accounts
  576. vcAccountRequest.enableTimerProgress = false
  577. vcAccountRequest.enableAddAccount = true
  578. vcAccountRequest.delegate = self
  579. vcAccountRequest.dismissDidEnterBackground = true
  580. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  581. let numberCell = accounts.count + 1
  582. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  583. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  584. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  585. }
  586. }
  587. }
  588. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  589. navigationItem.leftItemsSupplementBackButton = true
  590. }
  591. func getNavigationTitle() -> String {
  592. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  593. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  594. return NCBrandOptions.shared.brand
  595. }
  596. return userAlias
  597. }
  598. // MARK: - BackgroundImageColor Delegate
  599. func colorPickerCancel() {
  600. changeTheming()
  601. }
  602. func colorPickerWillChange(color: UIColor) {
  603. collectionView.backgroundColor = color
  604. }
  605. func colorPickerDidChange(lightColor: String, darkColor: String) {
  606. NCManageDatabase.shared.setAccountColorFiles(lightColorBackground: lightColor, darkColorBackground: darkColor)
  607. changeTheming()
  608. }
  609. // MARK: - Empty
  610. func emptyDataSetView(_ view: NCEmptyView) {
  611. if isSearching {
  612. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  613. if isReloadDataSourceNetworkInProgress {
  614. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  615. } else {
  616. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  617. }
  618. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  619. } else if isReloadDataSourceNetworkInProgress {
  620. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  621. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  622. view.emptyDescription.text = ""
  623. } else {
  624. if serverUrl == "" {
  625. view.emptyImage.image = emptyImage
  626. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  627. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  628. } else {
  629. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  630. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  631. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  632. }
  633. }
  634. }
  635. // MARK: - SEARCH
  636. func updateSearchResults(for searchController: UISearchController) {
  637. self.literalSearch = searchController.searchBar.text
  638. }
  639. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  640. self.isSearching = true
  641. self.providers?.removeAll()
  642. self.metadatasSource.removeAll()
  643. self.dataSource.clearDataSource()
  644. self.collectionView.reloadData()
  645. }
  646. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  647. if self.isSearching && self.literalSearch?.count ?? 0 >= 2 {
  648. reloadDataSourceNetwork()
  649. }
  650. }
  651. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  652. NCNetworking.shared.cancelUnifiedSearchFiles()
  653. self.isSearching = false
  654. self.literalSearch = ""
  655. self.providers?.removeAll()
  656. reloadDataSource()
  657. }
  658. // MARK: - TAP EVENT
  659. func accountRequestChangeAccount(account: String) {
  660. NCManageDatabase.shared.setAccountActive(account)
  661. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  662. NCOperationQueue.shared.cancelAllQueue()
  663. NCNetworking.shared.cancelAllTask()
  664. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  665. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  666. }
  667. }
  668. func accountRequestAddAccount() {
  669. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  670. }
  671. func tapButtonSwitch(_ sender: Any) {
  672. if collectionView.collectionViewLayout == gridLayout {
  673. // list layout
  674. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  675. UIView.animate(withDuration: 0.0, animations: {
  676. self.collectionView.collectionViewLayout.invalidateLayout()
  677. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { _ in
  678. self.collectionView.reloadData()
  679. })
  680. })
  681. layoutForView?.layout = NCGlobal.shared.layoutList
  682. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  683. } else {
  684. // grid layout
  685. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  686. UIView.animate(withDuration: 0.0, animations: {
  687. self.collectionView.collectionViewLayout.invalidateLayout()
  688. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { _ in
  689. self.collectionView.reloadData()
  690. })
  691. })
  692. layoutForView?.layout = NCGlobal.shared.layoutGrid
  693. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  694. }
  695. reloadDataSource()
  696. }
  697. func tapButtonOrder(_ sender: Any) {
  698. let sortMenu = NCSortMenu()
  699. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  700. }
  701. func tapButton1(_ sender: Any) {
  702. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: self) { hasPermission in
  703. if hasPermission {
  704. NCPhotosPickerViewController.init(viewController: self, maxSelectedAssets: 0, singleSelectedMode: false)
  705. }
  706. }
  707. }
  708. func tapButton2(_ sender: Any) {
  709. guard !appDelegate.activeServerUrl.isEmpty else { return }
  710. let alertController = UIAlertController.createFolder(serverUrl: appDelegate.activeServerUrl, urlBase: appDelegate)
  711. appDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
  712. }
  713. func tapButton3(_ sender: Any) {
  714. if #available(iOS 13.0, *) {
  715. if let viewController = appDelegate.window?.rootViewController {
  716. NCCreateScanDocument.shared.openScannerDocument(viewController: viewController)
  717. }
  718. }
  719. }
  720. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  721. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  722. }
  723. func tapShareListItem(with objectId: String, sender: Any) {
  724. if isEditMode { return }
  725. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  726. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  727. }
  728. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  729. if isEditMode { return }
  730. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  731. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  732. toggleMenu(metadata: metadata, imageIcon: image)
  733. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  734. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  735. }
  736. }
  737. func tapRichWorkspace(_ sender: Any) {
  738. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  739. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  740. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  741. viewerRichWorkspace.serverUrl = serverUrl
  742. navigationController.modalPresentationStyle = .fullScreen
  743. self.present(navigationController, animated: true, completion: nil)
  744. }
  745. }
  746. }
  747. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  748. }
  749. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  750. }
  751. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  752. }
  753. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  754. }
  755. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  756. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  757. /*
  758. if #available(iOS 13.0, *) {
  759. let interaction = UIContextMenuInteraction(delegate: self)
  760. self.view.addInteraction(interaction)
  761. }
  762. */
  763. }
  764. @available(iOS 13.0, *)
  765. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  766. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  767. return nil
  768. }, actionProvider: { _ in
  769. // let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  770. // }
  771. // return UIMenu(title: "Main Menu", children: [share])
  772. return nil
  773. })
  774. }
  775. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  776. if gestureRecognizer.state != .began { return }
  777. var listMenuItems: [UIMenuItem] = []
  778. let touchPoint = gestureRecognizer.location(in: collectionView)
  779. becomeFirstResponder()
  780. if serverUrl != "" {
  781. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  782. }
  783. if #available(iOS 13.0, *) {
  784. if !NCBrandOptions.shared.disable_background_color {
  785. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_background_", comment: ""), action: #selector(backgroundFilesMenu)))
  786. }
  787. }
  788. if listMenuItems.count > 0 {
  789. UIMenuController.shared.menuItems = listMenuItems
  790. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  791. UIMenuController.shared.setMenuVisible(true, animated: true)
  792. }
  793. }
  794. // MARK: - Menu Item
  795. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  796. if #selector(pasteFilesMenu) == action {
  797. if UIPasteboard.general.items.count > 0 {
  798. return true
  799. }
  800. }
  801. if #selector(backgroundFilesMenu) == action {
  802. return true
  803. }
  804. return false
  805. }
  806. @objc func pasteFilesMenu() {
  807. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  808. }
  809. @objc func backgroundFilesMenu() {
  810. if let vcBackgroundImageColor = UIStoryboard(name: "NCBackgroundImageColor", bundle: nil).instantiateInitialViewController() as? NCBackgroundImageColor {
  811. vcBackgroundImageColor.delegate = self
  812. vcBackgroundImageColor.setupColor = collectionView.backgroundColor
  813. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  814. vcBackgroundImageColor.lightColor = activeAccount.lightColorBackground
  815. vcBackgroundImageColor.darkColor = activeAccount.darkColorBackground
  816. }
  817. let popup = NCPopupViewController(contentController: vcBackgroundImageColor, popupWidth: vcBackgroundImageColor.width, popupHeight: vcBackgroundImageColor.height)
  818. popup.backgroundAlpha = 0
  819. self.present(popup, animated: true)
  820. }
  821. }
  822. // MARK: - DataSource + NC Endpoint
  823. @objc func reloadDataSource() {
  824. if appDelegate.account == "" { return }
  825. // Get richWorkspace Text
  826. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  827. richWorkspaceText = directory?.richWorkspace
  828. // E2EE
  829. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  830. // get auto upload folder
  831. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  832. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  833. // get layout for view
  834. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  835. // set GroupField for Grid
  836. if !self.isSearching && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  837. groupByField = "classFile"
  838. } else {
  839. groupByField = "name"
  840. }
  841. }
  842. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  843. @objc func networkSearch() {
  844. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  845. else {
  846. DispatchQueue.main.async { self.refreshControl.endRefreshing() }
  847. return
  848. }
  849. let completionHandler: ([tableMetadata]?, Int, String) -> Void = { metadatas, errorCode, errorDescription in
  850. DispatchQueue.main.async {
  851. if self.searchController?.isActive == true, errorCode == 0, let metadatas = metadatas {
  852. self.metadatasSource = metadatas
  853. }
  854. self.refreshControl.endRefreshing()
  855. self.isReloadDataSourceNetworkInProgress = false
  856. self.reloadDataSource()
  857. }
  858. }
  859. isReloadDataSourceNetworkInProgress = true
  860. self.metadatasSource.removeAll()
  861. self.dataSource.clearDataSource()
  862. collectionView?.reloadData()
  863. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  864. if serverVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  865. self.refreshControl.beginRefreshing()
  866. NCNetworking.shared.unifiedSearchFiles(urlBase: appDelegate, literal: literalSearch) { allProviders in
  867. self.providers = allProviders
  868. } update: { metadatas in
  869. guard let metadatas = metadatas, metadatas.count > 0 else { return }
  870. DispatchQueue.main.async {
  871. if self.searchController?.isActive == true {
  872. self.metadatasSource = metadatas
  873. self.dataSource = NCDataSource(metadatasSource: self.metadatasSource,
  874. account: self.appDelegate.account,
  875. sort: self.layoutForView?.sort,
  876. ascending: self.layoutForView?.ascending,
  877. directoryOnTop: self.layoutForView?.directoryOnTop,
  878. favoriteOnTop: true,
  879. filterLivePhoto: true,
  880. providers: self.providers)
  881. self.collectionView.reloadData()
  882. }
  883. }
  884. } completion: { metadatas, errorCode, errorDescription in
  885. completionHandler(metadatas, errorCode, errorDescription)
  886. }
  887. } else {
  888. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch, completion: completionHandler)
  889. }
  890. }
  891. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  892. var tableDirectory: tableDirectory?
  893. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, errorCode, errorDescription) in
  894. if errorCode == 0 {
  895. if let metadataFolder = metadataFolder {
  896. tableDirectory = NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: self.serverUrl, account: account)
  897. }
  898. if forced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  899. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, errorCode, errorDescription in
  900. if errorCode == 0 {
  901. self.metadataFolder = metadataFolder
  902. // E2EE
  903. if let metadataFolder = metadataFolder {
  904. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  905. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, errorCode, errorDescription in
  906. if errorCode == 0 && e2eMetadata != nil {
  907. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  908. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  909. } else {
  910. self.reloadDataSource()
  911. }
  912. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  913. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  914. }
  915. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  916. }
  917. } else {
  918. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  919. }
  920. } else {
  921. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  922. }
  923. } else {
  924. completion(tableDirectory, nil, nil, nil, errorCode, errorDescription)
  925. }
  926. }
  927. } else {
  928. completion(tableDirectory, nil, nil, nil, 0, "")
  929. }
  930. } else {
  931. completion(nil, nil, nil, nil, errorCode, errorDescription)
  932. }
  933. }
  934. }
  935. // MARK: - Push metadata
  936. func pushMetadata(_ metadata: tableMetadata) {
  937. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  938. appDelegate.activeMetadata = metadata
  939. // FILES
  940. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  941. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  942. if viewController.isViewLoaded {
  943. pushViewController(viewController: viewController)
  944. }
  945. } else {
  946. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  947. viewController.isRoot = false
  948. viewController.serverUrl = serverUrlPush
  949. viewController.titleCurrentFolder = metadata.fileNameView
  950. appDelegate.listFilesVC[serverUrlPush] = viewController
  951. pushViewController(viewController: viewController)
  952. }
  953. }
  954. }
  955. // FAVORITE
  956. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  957. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  958. if viewController.isViewLoaded {
  959. pushViewController(viewController: viewController)
  960. }
  961. } else {
  962. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  963. viewController.serverUrl = serverUrlPush
  964. viewController.titleCurrentFolder = metadata.fileNameView
  965. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  966. pushViewController(viewController: viewController)
  967. }
  968. }
  969. }
  970. // OFFLINE
  971. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  972. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  973. if viewController.isViewLoaded {
  974. pushViewController(viewController: viewController)
  975. }
  976. } else {
  977. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  978. viewController.serverUrl = serverUrlPush
  979. viewController.titleCurrentFolder = metadata.fileNameView
  980. appDelegate.listOfflineVC[serverUrlPush] = viewController
  981. pushViewController(viewController: viewController)
  982. }
  983. }
  984. }
  985. // RECENT ( for push use Files ... he he he )
  986. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  987. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  988. if viewController.isViewLoaded {
  989. pushViewController(viewController: viewController)
  990. }
  991. } else {
  992. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  993. viewController.isRoot = false
  994. viewController.serverUrl = serverUrlPush
  995. viewController.titleCurrentFolder = metadata.fileNameView
  996. appDelegate.listFilesVC[serverUrlPush] = viewController
  997. pushViewController(viewController: viewController)
  998. }
  999. }
  1000. }
  1001. // VIEW IN FOLDER
  1002. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  1003. if let viewController: NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  1004. viewController.serverUrl = serverUrlPush
  1005. viewController.titleCurrentFolder = metadata.fileNameView
  1006. pushViewController(viewController: viewController)
  1007. }
  1008. }
  1009. // SHARES ( for push use Files ... he he he )
  1010. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  1011. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  1012. if viewController.isViewLoaded {
  1013. pushViewController(viewController: viewController)
  1014. }
  1015. } else {
  1016. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1017. viewController.isRoot = false
  1018. viewController.serverUrl = serverUrlPush
  1019. viewController.titleCurrentFolder = metadata.fileNameView
  1020. appDelegate.listFilesVC[serverUrlPush] = viewController
  1021. pushViewController(viewController: viewController)
  1022. }
  1023. }
  1024. }
  1025. }
  1026. }
  1027. // MARK: - Collection View
  1028. extension NCCollectionViewCommon: UICollectionViewDelegate {
  1029. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  1030. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1031. appDelegate.activeMetadata = metadata
  1032. if isEditMode {
  1033. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  1034. selectOcId.remove(at: index)
  1035. } else {
  1036. selectOcId.append(metadata.ocId)
  1037. }
  1038. collectionView.reloadItems(at: [indexPath])
  1039. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatasSource.count)"
  1040. return
  1041. }
  1042. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1043. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled)
  1044. return
  1045. }
  1046. if metadata.directory {
  1047. pushMetadata(metadata)
  1048. } else if !(self is NCFileViewInFolder) {
  1049. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1050. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1051. var metadatas: [tableMetadata] = []
  1052. for metadata in dataSource.metadatasSource {
  1053. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1054. metadatas.append(metadata)
  1055. }
  1056. }
  1057. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1058. return
  1059. }
  1060. if CCUtility.fileProviderStorageExists(metadata) {
  1061. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1062. } else if NCCommunication.shared.isNetworkReachable() {
  1063. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _ in }
  1064. } else {
  1065. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline)
  1066. }
  1067. }
  1068. }
  1069. func pushViewController(viewController: UIViewController) {
  1070. if pushed { return }
  1071. pushed = true
  1072. navigationController?.pushViewController(viewController, animated: true)
  1073. }
  1074. @available(iOS 13.0, *)
  1075. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1076. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1077. if isEditMode || metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue { return nil }
  1078. let identifier = indexPath as NSCopying
  1079. var image: UIImage?
  1080. let cell = collectionView.cellForItem(at: indexPath)
  1081. if cell is NCListCell {
  1082. image = (cell as! NCListCell).imageItem.image
  1083. } else if cell is NCGridCell {
  1084. image = (cell as! NCGridCell).imageItem.image
  1085. }
  1086. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1087. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1088. }, actionProvider: { _ in
  1089. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  1090. })
  1091. }
  1092. @available(iOS 13.0, *)
  1093. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1094. animator.addCompletion {
  1095. if let indexPath = configuration.identifier as? IndexPath {
  1096. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1097. }
  1098. }
  1099. }
  1100. }
  1101. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1102. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1103. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1104. // Thumbnail
  1105. if !metadata.directory {
  1106. if metadata.name == NCGlobal.shared.appName {
  1107. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1108. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1109. } else {
  1110. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1111. }
  1112. } else {
  1113. // Unified search
  1114. switch metadata.iconName {
  1115. case let str where str.contains("contacts"):
  1116. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1117. case let str where str.contains("conversation"):
  1118. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1119. case let str where str.contains("calendar"):
  1120. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1121. case let str where str.contains("deck"):
  1122. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1123. case let str where str.contains("mail"):
  1124. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1125. case let str where str.contains("talk"):
  1126. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1127. case let str where str.contains("confirm"):
  1128. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1129. case let str where str.contains("pages"):
  1130. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1131. default:
  1132. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1133. }
  1134. //var urlString: String = ""
  1135. if !metadata.iconUrl.isEmpty {
  1136. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1137. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1138. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1139. }
  1140. /*
  1141. if metadata.iconUrl.starts(with: "/apps") {
  1142. //urlString = metadata.urlBase + metadata.iconUrl
  1143. } else if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  1144. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  1145. var found:Bool = false
  1146. var ownerId: String = ""
  1147. for item in splitIconUrl {
  1148. if found {
  1149. ownerId = item
  1150. break
  1151. }
  1152. if item == "avatar" { found = true}
  1153. }
  1154. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1155. if let cell = cell as? NCCellProtocol {
  1156. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1157. }
  1158. }
  1159. // NCCommunication.shared.downloadContent(serverUrl: urlString) { _, data, errorCode, _ in
  1160. // if errorCode == 0, let data = data, let image = UIImage(data: data) {
  1161. // (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1162. // }
  1163. // }
  1164. */
  1165. }
  1166. }
  1167. }
  1168. // Avatar
  1169. if metadata.ownerId.count > 0,
  1170. metadata.ownerId != appDelegate.userId,
  1171. appDelegate.account == metadata.account,
  1172. let cell = cell as? NCCellProtocol {
  1173. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1174. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1175. }
  1176. }
  1177. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1178. }
  1179. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1180. return dataSource.numberOfSections()
  1181. }
  1182. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1183. let numberItems = dataSource.numberOfItemsInSection(section)
  1184. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1185. return numberItems
  1186. }
  1187. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1188. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1189. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1190. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1191. } else {
  1192. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1193. }
  1194. }
  1195. var isShare = false
  1196. var isMounted = false
  1197. if metadataFolder != nil {
  1198. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1199. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1200. }
  1201. let tableShare = dataSource.metadatasForSection[indexPath.section].metadataShare[metadata.ocId]
  1202. //
  1203. // LAYOUT LIST
  1204. //
  1205. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1206. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1207. cell.delegate = self
  1208. cell.fileObjectId = metadata.ocId
  1209. cell.fileUser = metadata.ownerId
  1210. cell.labelTitle.textColor = NCBrandColor.shared.label
  1211. cell.labelInfo.textColor = NCBrandColor.shared.systemGray
  1212. cell.titleInfoTrailingDefault()
  1213. if isSearching {
  1214. cell.labelTitle.text = metadata.fileName
  1215. cell.labelTitle.lineBreakMode = .byTruncatingTail
  1216. if metadata.name == NCGlobal.shared.appName {
  1217. cell.labelInfo.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(metadata: metadata, withFileName: false)
  1218. } else {
  1219. cell.labelInfo.text = metadata.subline
  1220. cell.titleInfoTrailingFull()
  1221. }
  1222. if let literalSearch = self.literalSearch {
  1223. let longestWordRange = (metadata.fileName.lowercased() as NSString).range(of: literalSearch)
  1224. let attributedString = NSMutableAttributedString(string: metadata.fileName, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1225. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)], range: longestWordRange)
  1226. cell.labelTitle.attributedText = attributedString
  1227. }
  1228. } else {
  1229. cell.labelTitle.text = metadata.fileNameView
  1230. cell.labelTitle.lineBreakMode = .byTruncatingMiddle
  1231. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1232. }
  1233. cell.imageSelect.image = nil
  1234. cell.imageStatus.image = nil
  1235. cell.imageLocal.image = nil
  1236. cell.imageFavorite.image = nil
  1237. cell.imageShared.image = nil
  1238. cell.imageMore.image = nil
  1239. cell.imageItem.image = nil
  1240. cell.imageItem.backgroundColor = nil
  1241. cell.hideButtonShare(false)
  1242. cell.hideButtonMore(false)
  1243. // Progress
  1244. var progress: Float = 0.0
  1245. var totalBytes: Int64 = 0
  1246. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1247. progress = progressType.progress
  1248. totalBytes = progressType.totalBytes
  1249. }
  1250. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1251. cell.progressView.isHidden = false
  1252. cell.progressView.progress = progress
  1253. } else {
  1254. cell.progressView.isHidden = true
  1255. cell.progressView.progress = 0.0
  1256. }
  1257. var a11yValues: [String] = []
  1258. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1259. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1260. }
  1261. if metadata.directory {
  1262. if metadata.e2eEncrypted {
  1263. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1264. } else if isShare {
  1265. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1266. } else if tableShare != nil && tableShare?.shareType != 3 {
  1267. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1268. } else if tableShare != nil && tableShare?.shareType == 3 {
  1269. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1270. } else if metadata.mountType == "group" {
  1271. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1272. } else if isMounted {
  1273. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1274. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1275. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1276. cell.labelTitle.text = (cell.labelTitle.text ?? "") + " - " + NSLocalizedString("_auto_upload_folder_", comment: "")
  1277. } else {
  1278. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1279. }
  1280. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1281. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1282. // Local image: offline
  1283. if tableDirectory != nil && tableDirectory!.offline {
  1284. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1285. }
  1286. } else {
  1287. // image local
  1288. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1289. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1290. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1291. } else if CCUtility.fileProviderStorageExists(metadata) {
  1292. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1293. }
  1294. }
  1295. // image Favorite
  1296. if metadata.favorite {
  1297. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1298. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1299. }
  1300. // Share image
  1301. if isShare {
  1302. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1303. } else if tableShare != nil && tableShare?.shareType == 3 {
  1304. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1305. } else if tableShare != nil && tableShare?.shareType != 3 {
  1306. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1307. } else {
  1308. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1309. }
  1310. if appDelegate.account != metadata.account {
  1311. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1312. }
  1313. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1314. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1315. } else if metadata.lock == true {
  1316. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1317. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1318. } else {
  1319. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1320. }
  1321. // Write status on Label Info
  1322. switch metadata.status {
  1323. case NCGlobal.shared.metadataStatusWaitDownload:
  1324. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1325. break
  1326. case NCGlobal.shared.metadataStatusInDownload:
  1327. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1328. break
  1329. case NCGlobal.shared.metadataStatusDownloading:
  1330. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1331. break
  1332. case NCGlobal.shared.metadataStatusWaitUpload:
  1333. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1334. break
  1335. case NCGlobal.shared.metadataStatusInUpload:
  1336. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1337. break
  1338. case NCGlobal.shared.metadataStatusUploading:
  1339. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1340. break
  1341. case NCGlobal.shared.metadataStatusUploadError:
  1342. if metadata.sessionError != "" {
  1343. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1344. } else {
  1345. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1346. }
  1347. break
  1348. default:
  1349. break
  1350. }
  1351. cell.accessibilityLabel = metadata.fileNameView + ", " + (cell.labelInfo.text ?? "")
  1352. // Live Photo
  1353. if metadata.livePhoto {
  1354. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1355. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1356. }
  1357. // E2EE
  1358. if metadata.e2eEncrypted || isEncryptedFolder {
  1359. cell.hideButtonShare(true)
  1360. }
  1361. // URL
  1362. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1363. cell.imageLocal.image = nil
  1364. cell.hideButtonShare(true)
  1365. cell.hideButtonMore(true)
  1366. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1367. cell.fileUser = ownerId
  1368. }
  1369. }
  1370. // Disable Share Button
  1371. if appDelegate.disableSharesView {
  1372. cell.hideButtonShare(true)
  1373. }
  1374. // Separator
  1375. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearching {
  1376. cell.separator.isHidden = true
  1377. } else {
  1378. cell.separator.isHidden = false
  1379. }
  1380. // Edit mode
  1381. if isEditMode {
  1382. cell.selectMode(true)
  1383. if selectOcId.contains(metadata.ocId) {
  1384. cell.selected(true)
  1385. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1386. } else {
  1387. cell.selected(false)
  1388. }
  1389. } else {
  1390. cell.selectMode(false)
  1391. }
  1392. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1393. return cell
  1394. }
  1395. //
  1396. // LAYOUT GRID
  1397. //
  1398. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1399. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1400. cell.delegate = self
  1401. cell.fileObjectId = metadata.ocId
  1402. cell.fileUser = metadata.ownerId
  1403. cell.labelTitle.text = metadata.fileNameView
  1404. cell.labelTitle.textColor = NCBrandColor.shared.label
  1405. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1406. cell.labelInfo.textColor = NCBrandColor.shared.systemGray
  1407. if isSearching, let literalSearch = self.literalSearch {
  1408. let longestWordRange = (metadata.fileName.lowercased() as NSString).range(of: literalSearch)
  1409. let attributedString = NSMutableAttributedString(string: metadata.fileName, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1410. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)], range: longestWordRange)
  1411. cell.labelTitle.attributedText = attributedString
  1412. }
  1413. cell.imageSelect.image = nil
  1414. cell.imageStatus.image = nil
  1415. cell.imageLocal.image = nil
  1416. cell.imageFavorite.image = nil
  1417. cell.imageItem.image = nil
  1418. cell.imageItem.backgroundColor = nil
  1419. cell.hideButtonMore(false)
  1420. // Progress
  1421. var progress: Float = 0.0
  1422. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1423. progress = progressType.progress
  1424. }
  1425. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1426. cell.progressView.isHidden = false
  1427. cell.progressView.progress = progress
  1428. cell.accessibilityLabel = metadata.fileNameView + ", \(Int(progress * 100))%"
  1429. } else {
  1430. cell.progressView.isHidden = true
  1431. cell.progressView.progress = 0.0
  1432. cell.accessibilityLabel = metadata.fileNameView
  1433. }
  1434. var a11yValues: [String] = []
  1435. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1436. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1437. }
  1438. if metadata.directory {
  1439. if metadata.e2eEncrypted {
  1440. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1441. } else if isShare {
  1442. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1443. } else if tableShare != nil && tableShare!.shareType != 3 {
  1444. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1445. } else if tableShare != nil && tableShare!.shareType == 3 {
  1446. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1447. } else if metadata.mountType == "group" {
  1448. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1449. } else if isMounted {
  1450. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1451. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1452. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1453. } else {
  1454. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1455. }
  1456. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1457. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1458. // Local image: offline
  1459. if tableDirectory != nil && tableDirectory!.offline {
  1460. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1461. }
  1462. } else {
  1463. // image Local
  1464. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1465. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1466. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1467. } else if CCUtility.fileProviderStorageExists(metadata) {
  1468. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1469. }
  1470. }
  1471. // image Favorite
  1472. if metadata.favorite {
  1473. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1474. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1475. }
  1476. // Transfer
  1477. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1478. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1479. } else if metadata.lock == true {
  1480. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1481. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1482. } else {
  1483. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1484. }
  1485. // Live Photo
  1486. if metadata.livePhoto {
  1487. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1488. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1489. }
  1490. // URL
  1491. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1492. cell.imageLocal.image = nil
  1493. cell.hideButtonMore(true)
  1494. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1495. cell.fileUser = ownerId
  1496. }
  1497. }
  1498. // Edit mode
  1499. if isEditMode {
  1500. cell.selectMode(true)
  1501. if selectOcId.contains(metadata.ocId) {
  1502. cell.selected(true)
  1503. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1504. } else {
  1505. cell.selected(false)
  1506. }
  1507. } else {
  1508. cell.selectMode(false)
  1509. }
  1510. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1511. return cell
  1512. }
  1513. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1514. }
  1515. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1516. if kind == UICollectionView.elementKindSectionHeader {
  1517. if indexPath.section == 0 {
  1518. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1519. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1520. self.headerMenu = header
  1521. if collectionView.collectionViewLayout == gridLayout {
  1522. header.setImageSwitchList()
  1523. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1524. } else {
  1525. header.setImageSwitchGrid()
  1526. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1527. }
  1528. header.delegate = self
  1529. if headerMenuButtonsCommand && !isSearching {
  1530. header.setButtonsCommand(heigt: NCGlobal.shared.heightButtonsCommand, imageButton1: UIImage(named: "buttonAddImage"), titleButton1: NSLocalizedString("_upload_", comment: ""), imageButton2: UIImage(named: "buttonAddFolder"), titleButton2: NSLocalizedString("_folder_", comment: ""), imageButton3: UIImage(named: "buttonAddScan"), titleButton3: NSLocalizedString("_scan_", comment: ""))
  1531. } else {
  1532. header.setButtonsCommand(heigt: 0)
  1533. }
  1534. if headerMenuButtonsView {
  1535. header.setStatusButtonsView(enable: !dataSource.metadatasSource.isEmpty)
  1536. header.setButtonsView(heigt: NCGlobal.shared.heightButtonsView)
  1537. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1538. } else {
  1539. header.setButtonsView(heigt: 0)
  1540. }
  1541. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1542. header.setRichWorkspaceText(richWorkspaceText)
  1543. header.setSectionHeight(heightHeaderSection)
  1544. header.labelSection.text = NSLocalizedString(self.dataSource.getSectionValue(indexPath: indexPath), comment: "").lowercased().firstUppercased
  1545. header.labelSection.textColor = NCBrandColor.shared.label
  1546. return header
  1547. } else {
  1548. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1549. header.labelSection.text = NSLocalizedString(self.dataSource.getSectionValue(indexPath: indexPath), comment: "").lowercased().firstUppercased
  1550. header.labelSection.textColor = NCBrandColor.shared.label
  1551. return header
  1552. }
  1553. } else {
  1554. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1555. let sections = dataSource.numberOfSections()
  1556. let section = indexPath.section
  1557. footer.setTitleLabel(text: "")
  1558. footer.separatorIsHidden(true)
  1559. if isSearching {
  1560. if sections > 1 && section != sections - 1 {
  1561. footer.separatorIsHidden(false)
  1562. }
  1563. } else {
  1564. if sections == 1 || section == sections - 1 {
  1565. let info = dataSource.getFooterInformation()
  1566. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1567. } else {
  1568. footer.separatorIsHidden(false)
  1569. }
  1570. }
  1571. return footer
  1572. }
  1573. }
  1574. }
  1575. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1576. func getHeaderHeight() -> CGFloat {
  1577. var size: CGFloat = 0
  1578. if headerMenuButtonsCommand && !isSearching {
  1579. size += NCGlobal.shared.heightButtonsCommand
  1580. }
  1581. if headerMenuButtonsView {
  1582. size += NCGlobal.shared.heightButtonsView
  1583. }
  1584. return size
  1585. }
  1586. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1587. var headerRichWorkspace: CGFloat = 0
  1588. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1589. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1590. if trimmed.count > 0 && !isSearching {
  1591. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1592. }
  1593. }
  1594. if section == 0 && dataSource.numberOfSections() > 1 {
  1595. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1596. } else if section == 0 && dataSource.numberOfSections() == 1 {
  1597. if collectionView.collectionViewLayout == gridLayout {
  1598. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1599. } else {
  1600. return (getHeaderHeight(), headerRichWorkspace, 0)
  1601. }
  1602. } else if section > 0 && dataSource.numberOfSections() > 1 {
  1603. return (0, 0, NCGlobal.shared.heightSection)
  1604. } else {
  1605. return (0, 0, 0)
  1606. }
  1607. }
  1608. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1609. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1610. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1611. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1612. }
  1613. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1614. let sections = dataSource.numberOfSections()
  1615. if section == sections - 1 {
  1616. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.endHeightFooter)
  1617. } else {
  1618. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.heightFooter)
  1619. }
  1620. }
  1621. }