NCSelect.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. //
  2. // NCSelect.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/11/2018.
  6. // Copyright © 2018 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 SwiftUI
  25. import NextcloudKit
  26. @objc protocol NCSelectDelegate {
  27. @objc func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool)
  28. }
  29. class NCSelect: UIViewController, UIGestureRecognizerDelegate, UIAdaptivePresentationControllerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCEmptyDataSetDelegate {
  30. @IBOutlet private var collectionView: UICollectionView!
  31. @IBOutlet private var buttonCancel: UIBarButtonItem!
  32. @IBOutlet private var bottomContraint: NSLayoutConstraint?
  33. private var selectCommandViewSelect: NCSelectCommandView?
  34. @objc enum selectType: Int {
  35. case select
  36. case selectCreateFolder
  37. case copyMove
  38. case nothing
  39. }
  40. // ------ external settings ------------------------------------
  41. @objc weak var delegate: NCSelectDelegate?
  42. @objc var typeOfCommandView: selectType = .select
  43. @objc var includeDirectoryE2EEncryption = false
  44. @objc var includeImages = false
  45. @objc var enableSelectFile = false
  46. @objc var type = ""
  47. @objc var items: [tableMetadata] = []
  48. var titleCurrentFolder = NCBrandOptions.shared.brand
  49. var serverUrl = ""
  50. // -------------------------------------------------------------
  51. private var emptyDataSet: NCEmptyDataSet?
  52. private let layoutKey = NCGlobal.shared.layoutViewMove
  53. private var serverUrlPush = ""
  54. private var metadataFolder = tableMetadata()
  55. private var isEditMode = false
  56. private var isSearching = false
  57. private var networkInProgress = false
  58. private var selectOcId: [String] = []
  59. private var overwrite = true
  60. private var dataSource = NCDataSource()
  61. internal var richWorkspaceText: String?
  62. private var layoutForView: NCDBLayoutForView?
  63. internal var headerMenu: NCSectionHeaderMenu?
  64. private var autoUploadFileName = ""
  65. private var autoUploadDirectory = ""
  66. private var listLayout: NCListLayout!
  67. private var gridLayout: NCGridLayout!
  68. private var backgroundImageView = UIImageView()
  69. private var activeAccount: tableAccount!
  70. private let window = UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.first { $0.isKeyWindow }
  71. // MARK: - View Life Cycle
  72. override func viewDidLoad() {
  73. super.viewDidLoad()
  74. self.navigationController?.navigationBar.prefersLargeTitles = true
  75. self.navigationController?.presentationController?.delegate = self
  76. view.backgroundColor = .systemBackground
  77. selectCommandViewSelect?.separatorView.backgroundColor = .separator
  78. activeAccount = NCManageDatabase.shared.getActiveAccount()
  79. // Cell
  80. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  81. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  82. // Header
  83. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  84. // Footer
  85. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  86. collectionView.alwaysBounceVertical = true
  87. collectionView.backgroundColor = .systemBackground
  88. listLayout = NCListLayout()
  89. gridLayout = NCGridLayout()
  90. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  91. bottomContraint?.constant = window?.rootViewController?.view.safeAreaInsets.bottom ?? 0
  92. // Empty
  93. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: NCGlobal.shared.heightButtonsView, delegate: self)
  94. // Type of command view
  95. if typeOfCommandView == .select || typeOfCommandView == .selectCreateFolder {
  96. if typeOfCommandView == .select {
  97. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect", owner: self, options: nil)?.first as? NCSelectCommandView
  98. } else {
  99. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect+CreateFolder", owner: self, options: nil)?.first as? NCSelectCommandView
  100. }
  101. self.view.addSubview(selectCommandViewSelect!)
  102. selectCommandViewSelect?.selectView = self
  103. selectCommandViewSelect?.translatesAutoresizingMaskIntoConstraints = false
  104. selectCommandViewSelect?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  105. selectCommandViewSelect?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  106. selectCommandViewSelect?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  107. selectCommandViewSelect?.heightAnchor.constraint(equalToConstant: 80).isActive = true
  108. bottomContraint?.constant = 80
  109. }
  110. if typeOfCommandView == .copyMove {
  111. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewCopyMove", owner: self, options: nil)?.first as? NCSelectCommandView
  112. self.view.addSubview(selectCommandViewSelect!)
  113. selectCommandViewSelect?.selectView = self
  114. selectCommandViewSelect?.translatesAutoresizingMaskIntoConstraints = false
  115. if items.contains(where: { $0.lock }) {
  116. selectCommandViewSelect?.moveButton?.isEnabled = false
  117. selectCommandViewSelect?.moveButton?.titleLabel?.isEnabled = false
  118. }
  119. selectCommandViewSelect?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  120. selectCommandViewSelect?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  121. selectCommandViewSelect?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  122. selectCommandViewSelect?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  123. bottomContraint?.constant = 150
  124. }
  125. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  126. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  127. }
  128. override func viewWillAppear(_ animated: Bool) {
  129. super.viewWillAppear(animated)
  130. self.navigationItem.title = titleCurrentFolder
  131. // set the serverUrl
  132. if serverUrl == "" {
  133. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId)
  134. }
  135. // get auto upload folder
  136. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  137. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, userId: activeAccount.userId, account: activeAccount.account)
  138. layoutForView = NCManageDatabase.shared.getLayoutForView(account: activeAccount.account, key: layoutKey, serverUrl: serverUrl)
  139. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  140. if layoutForView?.layout == NCGlobal.shared.layoutList {
  141. collectionView.collectionViewLayout = listLayout
  142. } else {
  143. collectionView.collectionViewLayout = gridLayout
  144. }
  145. loadDatasource(withLoadFolder: true)
  146. }
  147. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  148. super.viewWillTransition(to: size, with: coordinator)
  149. coordinator.animate(alongsideTransition: nil) { _ in
  150. self.collectionView?.collectionViewLayout.invalidateLayout()
  151. }
  152. }
  153. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  154. // Dismission
  155. }
  156. // MARK: - NotificationCenter
  157. @objc func createFolder(_ notification: NSNotification) {
  158. guard let userInfo = notification.userInfo as NSDictionary?,
  159. let ocId = userInfo["ocId"] as? String,
  160. let serverUrl = userInfo["serverUrl"] as? String,
  161. serverUrl == self.serverUrl,
  162. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  163. else { return }
  164. pushMetadata(metadata)
  165. }
  166. // MARK: - Empty
  167. func emptyDataSetView(_ view: NCEmptyView) {
  168. if networkInProgress {
  169. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  170. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  171. view.emptyDescription.text = ""
  172. } else {
  173. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  174. if includeImages {
  175. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  176. } else {
  177. view.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  178. }
  179. view.emptyDescription.text = ""
  180. }
  181. }
  182. // MARK: ACTION
  183. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  184. self.dismiss(animated: true, completion: nil)
  185. }
  186. func selectButtonPressed(_ sender: UIButton) {
  187. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: false, move: false)
  188. self.dismiss(animated: true, completion: nil)
  189. }
  190. func copyButtonPressed(_ sender: UIButton) {
  191. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: true, move: false)
  192. self.dismiss(animated: true, completion: nil)
  193. }
  194. func moveButtonPressed(_ sender: UIButton) {
  195. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: false, move: true)
  196. self.dismiss(animated: true, completion: nil)
  197. }
  198. func createFolderButtonPressed(_ sender: UIButton) {
  199. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, urlBase: activeAccount)
  200. self.present(alertController, animated: true, completion: nil)
  201. }
  202. @IBAction func valueChangedSwitchOverwrite(_ sender: UISwitch) {
  203. overwrite = sender.isOn
  204. }
  205. // MARK: TAP EVENT
  206. func tapButtonSwitch(_ sender: Any) {
  207. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  208. // list layout
  209. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  210. layoutForView?.layout = NCGlobal.shared.layoutList
  211. NCManageDatabase.shared.setLayoutForView(account: activeAccount.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  212. self.collectionView.reloadData()
  213. self.collectionView.collectionViewLayout.invalidateLayout()
  214. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  215. } else {
  216. // grid layout
  217. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  218. layoutForView?.layout = NCGlobal.shared.layoutGrid
  219. NCManageDatabase.shared.setLayoutForView(account: activeAccount.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  220. self.collectionView.reloadData()
  221. self.collectionView.collectionViewLayout.invalidateLayout()
  222. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  223. }
  224. }
  225. func tapButtonOrder(_ sender: Any) {
  226. let sortMenu = NCSortMenu()
  227. sortMenu.toggleMenu(viewController: self, account: activeAccount.account, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  228. }
  229. // MARK: - Push metadata
  230. func pushMetadata(_ metadata: tableMetadata) {
  231. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  232. guard let viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else { return }
  233. self.serverUrlPush = serverUrlPush
  234. viewController.delegate = delegate
  235. viewController.typeOfCommandView = typeOfCommandView
  236. viewController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  237. viewController.includeImages = includeImages
  238. viewController.enableSelectFile = enableSelectFile
  239. viewController.type = type
  240. viewController.overwrite = overwrite
  241. viewController.items = items
  242. viewController.titleCurrentFolder = metadata.fileNameView
  243. viewController.serverUrl = serverUrlPush
  244. self.navigationController?.pushViewController(viewController, animated: true)
  245. }
  246. }
  247. // MARK: - Collection View
  248. extension NCSelect: UICollectionViewDelegate {
  249. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  250. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  251. if isEditMode {
  252. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  253. selectOcId.remove(at: index)
  254. } else {
  255. selectOcId.append(metadata.ocId)
  256. }
  257. collectionView.reloadItems(at: [indexPath])
  258. return
  259. }
  260. if metadata.directory {
  261. pushMetadata(metadata)
  262. } else {
  263. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type, items: items, overwrite: overwrite, copy: false, move: false)
  264. self.dismiss(animated: true, completion: nil)
  265. }
  266. }
  267. }
  268. extension NCSelect: UICollectionViewDataSource {
  269. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  270. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  271. // Thumbnail
  272. if !metadata.directory {
  273. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  274. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  275. } else {
  276. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  277. }
  278. }
  279. // Avatar
  280. if metadata.ownerId.count > 0,
  281. metadata.ownerId != activeAccount.userId,
  282. activeAccount.account == metadata.account,
  283. let cell = cell as? NCCellProtocol {
  284. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  285. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  286. }
  287. }
  288. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  289. }
  290. func numberOfSections(in collectionView: UICollectionView) -> Int {
  291. return dataSource.numberOfSections()
  292. }
  293. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  294. let numberOfItems = dataSource.numberOfItemsInSection(section)
  295. emptyDataSet?.numberOfItemsInSection(numberOfItems, section: section)
  296. return numberOfItems
  297. }
  298. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  299. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  300. if layoutForView?.layout == NCGlobal.shared.layoutList {
  301. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  302. } else {
  303. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  304. }
  305. }
  306. var isShare = false
  307. var isMounted = false
  308. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  309. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  310. // LAYOUT LIST
  311. if layoutForView?.layout == NCGlobal.shared.layoutList {
  312. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  313. cell.delegate = self
  314. cell.fileObjectId = metadata.ocId
  315. cell.fileUser = metadata.ownerId
  316. cell.labelTitle.text = metadata.fileNameView
  317. cell.labelTitle.textColor = .label
  318. cell.imageSelect.image = nil
  319. cell.imageStatus.image = nil
  320. cell.imageLocal.image = nil
  321. cell.imageFavorite.image = nil
  322. cell.imageShared.image = nil
  323. cell.imageMore.image = nil
  324. cell.imageItem.image = nil
  325. cell.imageItem.backgroundColor = nil
  326. cell.progressView.progress = 0.0
  327. if metadata.directory {
  328. if metadata.e2eEncrypted {
  329. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  330. } else if isShare {
  331. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  332. } else if !metadata.shareType.isEmpty {
  333. metadata.shareType.contains(3) ?
  334. (cell.imageItem.image = NCBrandColor.cacheImages.folderPublic) :
  335. (cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe)
  336. } else if metadata.mountType == "group" {
  337. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  338. } else if isMounted {
  339. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  340. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  341. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  342. } else {
  343. cell.imageItem.image = NCBrandColor.cacheImages.folder
  344. }
  345. cell.imageItem.image = cell.imageItem.image?.colorizeFolder(metadata: metadata)
  346. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  347. } else {
  348. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  349. // image local
  350. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  351. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  352. } else if CCUtility.fileProviderStorageExists(metadata) {
  353. cell.imageLocal.image = NCBrandColor.cacheImages.local
  354. }
  355. }
  356. // image Favorite
  357. if metadata.favorite {
  358. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  359. }
  360. // Share image
  361. if isShare {
  362. cell.imageShared.image = NCBrandColor.cacheImages.shared
  363. } else if !metadata.shareType.isEmpty {
  364. metadata.shareType.contains(3) ?
  365. (cell.imageShared.image = NCBrandColor.cacheImages.shareByLink) :
  366. (cell.imageShared.image = NCBrandColor.cacheImages.shared)
  367. } else {
  368. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  369. }
  370. cell.imageSelect.isHidden = true
  371. cell.backgroundView = nil
  372. cell.hideButtonMore(true)
  373. cell.hideButtonShare(true)
  374. cell.selectMode(false)
  375. // Live Photo
  376. if metadata.livePhoto {
  377. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  378. }
  379. // Remove last separator
  380. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  381. cell.separator.isHidden = true
  382. } else {
  383. cell.separator.isHidden = false
  384. }
  385. // Add TAGS
  386. cell.setTags(tags: Array(metadata.tags))
  387. return cell
  388. }
  389. // LAYOUT GRID
  390. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  391. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  392. cell.delegate = self
  393. cell.fileObjectId = metadata.ocId
  394. cell.fileUser = metadata.ownerId
  395. cell.labelTitle.text = metadata.fileNameView
  396. cell.labelTitle.textColor = .label
  397. cell.imageSelect.image = nil
  398. cell.imageStatus.image = nil
  399. cell.imageLocal.image = nil
  400. cell.imageFavorite.image = nil
  401. cell.imageItem.image = nil
  402. cell.imageItem.backgroundColor = nil
  403. cell.progressView.progress = 0.0
  404. if metadata.directory {
  405. if metadata.e2eEncrypted {
  406. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  407. } else if isShare {
  408. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  409. } else if !metadata.shareType.isEmpty {
  410. metadata.shareType.contains(3) ?
  411. (cell.imageItem.image = NCBrandColor.cacheImages.folderPublic) :
  412. (cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe)
  413. } else if metadata.mountType == "group" {
  414. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  415. } else if isMounted {
  416. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  417. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  418. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  419. } else {
  420. cell.imageItem.image = NCBrandColor.cacheImages.folder
  421. }
  422. cell.imageItem.image = cell.imageItem.image?.colorizeFolder(metadata: metadata)
  423. } else {
  424. // image Local
  425. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  426. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  427. } else if CCUtility.fileProviderStorageExists(metadata) {
  428. cell.imageLocal.image = NCBrandColor.cacheImages.local
  429. }
  430. }
  431. // image Favorite
  432. if metadata.favorite {
  433. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  434. }
  435. cell.imageSelect.isHidden = true
  436. cell.backgroundView = nil
  437. cell.hideButtonMore(true)
  438. // Live Photo
  439. if metadata.livePhoto {
  440. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  441. }
  442. return cell
  443. }
  444. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  445. }
  446. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  447. if kind == UICollectionView.elementKindSectionHeader {
  448. if indexPath.section == 0 {
  449. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  450. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  451. self.headerMenu = header
  452. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  453. header.setImageSwitchList()
  454. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  455. } else {
  456. header.setImageSwitchGrid()
  457. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  458. }
  459. header.delegate = self
  460. header.setButtonsView(height: NCGlobal.shared.heightButtonsView)
  461. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  462. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  463. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  464. header.setRichWorkspaceText(richWorkspaceText)
  465. header.setViewTransfer(isHidden: true)
  466. header.setSectionHeight(heightHeaderSection)
  467. if heightHeaderSection == 0 {
  468. header.labelSection.text = ""
  469. } else {
  470. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  471. }
  472. header.labelSection.textColor = .label
  473. return header
  474. } else {
  475. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  476. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  477. header.labelSection.textColor = NCBrandColor.shared.brandElement
  478. return header
  479. }
  480. } else {
  481. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  482. let sections = dataSource.numberOfSections()
  483. let section = indexPath.section
  484. footer.setTitleLabel("")
  485. footer.separatorIsHidden(true)
  486. if sections == 1 || section == sections - 1 {
  487. let info = dataSource.getFooterInformationAllMetadatas()
  488. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  489. } else {
  490. footer.separatorIsHidden(false)
  491. }
  492. return footer
  493. }
  494. }
  495. }
  496. extension NCSelect: UICollectionViewDelegateFlowLayout {
  497. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  498. var headerRichWorkspace: CGFloat = 0
  499. if let richWorkspaceText = richWorkspaceText {
  500. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  501. if trimmed.count > 0 && !isSearching {
  502. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  503. }
  504. }
  505. if isSearching || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  506. if section == 0 {
  507. return (NCGlobal.shared.heightButtonsView, headerRichWorkspace, NCGlobal.shared.heightSection)
  508. } else {
  509. return (0, 0, NCGlobal.shared.heightSection)
  510. }
  511. } else {
  512. return (NCGlobal.shared.heightButtonsView, headerRichWorkspace, 0)
  513. }
  514. }
  515. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  516. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  517. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  518. return CGSize(width: collectionView.frame.width, height: heightHeader)
  519. }
  520. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  521. let sections = dataSource.numberOfSections()
  522. if section == sections - 1 {
  523. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.endHeightFooter)
  524. } else {
  525. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.heightFooter)
  526. }
  527. }
  528. }
  529. // MARK: -
  530. extension NCSelect {
  531. @objc func reloadDataSource() {
  532. loadDatasource(withLoadFolder: false)
  533. }
  534. @objc func loadDatasource(withLoadFolder: Bool) {
  535. var predicate: NSPredicate?
  536. var groupByField = "name"
  537. layoutForView = NCManageDatabase.shared.getLayoutForView(account: activeAccount.account, key: layoutKey, serverUrl: serverUrl)
  538. // set GroupField for Grid
  539. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  540. groupByField = "classFile"
  541. }
  542. if includeDirectoryE2EEncryption {
  543. if includeImages {
  544. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  545. } else {
  546. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl)
  547. }
  548. } else {
  549. if includeImages {
  550. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  551. } else if enableSelectFile {
  552. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false", activeAccount.account, serverUrl)
  553. } else {
  554. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", activeAccount.account, serverUrl)
  555. }
  556. }
  557. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: predicate!)
  558. self.dataSource = NCDataSource(metadatas: metadatas,
  559. account: activeAccount.account,
  560. sort: layoutForView?.sort,
  561. ascending: layoutForView?.ascending,
  562. directoryOnTop: layoutForView?.directoryOnTop,
  563. favoriteOnTop: true,
  564. filterLivePhoto: true,
  565. groupByField: groupByField)
  566. if withLoadFolder {
  567. loadFolder()
  568. }
  569. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, serverUrl))
  570. richWorkspaceText = directory?.richWorkspace
  571. DispatchQueue.main.async {
  572. self.collectionView.reloadData()
  573. }
  574. }
  575. func loadFolder() {
  576. networkInProgress = true
  577. collectionView.reloadData()
  578. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { _, _, _, _, _, _, error in
  579. if error != .success {
  580. NCContentPresenter.shared.showError(error: error)
  581. }
  582. self.networkInProgress = false
  583. self.loadDatasource(withLoadFolder: false)
  584. }
  585. }
  586. }
  587. // MARK: -
  588. class NCSelectCommandView: UIView {
  589. @IBOutlet weak var separatorView: UIView!
  590. @IBOutlet weak var createFolderButton: UIButton?
  591. @IBOutlet weak var selectButton: UIButton?
  592. @IBOutlet weak var copyButton: UIButton?
  593. @IBOutlet weak var moveButton: UIButton?
  594. @IBOutlet weak var overwriteSwitch: UISwitch?
  595. @IBOutlet weak var overwriteLabel: UILabel?
  596. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  597. var selectView: NCSelect?
  598. private let gradient: CAGradientLayer = CAGradientLayer()
  599. override func awakeFromNib() {
  600. separatorHeightConstraint.constant = 0.5
  601. separatorView.backgroundColor = .separator
  602. overwriteSwitch?.onTintColor = NCBrandColor.shared.brand
  603. overwriteLabel?.text = NSLocalizedString("_overwrite_", comment: "")
  604. selectButton?.layer.cornerRadius = 15
  605. selectButton?.layer.masksToBounds = true
  606. selectButton?.setTitle(NSLocalizedString("_select_", comment: ""), for: .normal)
  607. selectButton?.backgroundColor = NCBrandColor.shared.brand
  608. selectButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  609. selectButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  610. createFolderButton?.layer.cornerRadius = 15
  611. createFolderButton?.layer.masksToBounds = true
  612. createFolderButton?.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  613. createFolderButton?.backgroundColor = NCBrandColor.shared.brand
  614. createFolderButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  615. createFolderButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  616. copyButton?.layer.cornerRadius = 15
  617. copyButton?.layer.masksToBounds = true
  618. copyButton?.setTitle(NSLocalizedString("_copy_", comment: ""), for: .normal)
  619. copyButton?.backgroundColor = NCBrandColor.shared.brand
  620. copyButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  621. copyButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  622. moveButton?.layer.cornerRadius = 15
  623. moveButton?.layer.masksToBounds = true
  624. moveButton?.setTitle(NSLocalizedString("_move_", comment: ""), for: .normal)
  625. moveButton?.backgroundColor = NCBrandColor.shared.brand
  626. moveButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  627. moveButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  628. }
  629. @IBAction func createFolderButtonPressed(_ sender: UIButton) {
  630. selectView?.createFolderButtonPressed(sender)
  631. }
  632. @IBAction func selectButtonPressed(_ sender: UIButton) {
  633. selectView?.selectButtonPressed(sender)
  634. }
  635. @IBAction func copyButtonPressed(_ sender: UIButton) {
  636. selectView?.copyButtonPressed(sender)
  637. }
  638. @IBAction func moveButtonPressed(_ sender: UIButton) {
  639. selectView?.moveButtonPressed(sender)
  640. }
  641. @IBAction func valueChangedSwitchOverwrite(_ sender: UISwitch) {
  642. selectView?.valueChangedSwitchOverwrite(sender)
  643. }
  644. }
  645. // MARK: - UIViewControllerRepresentable
  646. struct NCSelectViewControllerRepresentable: UIViewControllerRepresentable {
  647. typealias UIViewControllerType = UINavigationController
  648. var delegate: NCSelectDelegate
  649. func makeUIViewController(context: Context) -> UINavigationController {
  650. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  651. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  652. let viewController = navigationController?.topViewController as? NCSelect
  653. viewController?.delegate = delegate
  654. viewController?.typeOfCommandView = .selectCreateFolder
  655. viewController?.includeDirectoryE2EEncryption = true
  656. return navigationController!
  657. }
  658. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  659. }
  660. struct SelectView: UIViewControllerRepresentable {
  661. typealias UIViewControllerType = UINavigationController
  662. @Binding var serverUrl: String
  663. class Coordinator: NSObject, NCSelectDelegate {
  664. var parent: SelectView
  665. init(_ parent: SelectView) {
  666. self.parent = parent
  667. }
  668. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  669. if let serverUrl = serverUrl {
  670. self.parent.serverUrl = serverUrl
  671. }
  672. }
  673. }
  674. func makeUIViewController(context: Context) -> UINavigationController {
  675. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  676. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  677. let viewController = navigationController?.topViewController as? NCSelect
  678. viewController?.delegate = context.coordinator
  679. viewController?.typeOfCommandView = .selectCreateFolder
  680. viewController?.includeDirectoryE2EEncryption = true
  681. return navigationController!
  682. }
  683. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  684. func makeCoordinator() -> Coordinator {
  685. Coordinator(self)
  686. }
  687. }