NCSelect.swift 36 KB

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