NCCollectionViewCommon.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. //
  2. // NCCollectionViewCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/09/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  25. @IBOutlet weak var collectionView: UICollectionView!
  26. internal let refreshControl = UIRefreshControl()
  27. internal var searchController: UISearchController?
  28. @objc var serverUrl: String?
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. internal var isEditMode = false
  31. internal var selectOcId: [String] = []
  32. internal var metadatasSource: [tableMetadata] = []
  33. internal var metadataFolder: tableMetadata?
  34. internal var metadataPush: tableMetadata?
  35. internal var dataSource: NCDataSource?
  36. internal var richWorkspaceText: String?
  37. internal var layout = ""
  38. internal var groupBy = ""
  39. internal var titleButton = ""
  40. internal var itemForLine = 0
  41. private var autoUploadFileName = ""
  42. private var autoUploadDirectory = ""
  43. private var listLayout: NCListLayout!
  44. private var gridLayout: NCGridLayout!
  45. private let headerHeight: CGFloat = 50
  46. private var headerRichWorkspaceHeight: CGFloat = 0
  47. private let footerHeight: CGFloat = 50
  48. private var timerInputSearch: Timer?
  49. internal var literalSearch: String?
  50. internal var isSearching: Bool = false
  51. internal var isReloadDataSourceNetworkInProgress: Bool = false
  52. // DECLARE
  53. internal var layoutKey = ""
  54. internal var titleCurrentFolder = ""
  55. internal var enableSearchBar: Bool = false
  56. internal var DZNimage: UIImage?
  57. internal var DZNtitle: String = ""
  58. internal var DZNdescription: String = ""
  59. required init?(coder aDecoder: NSCoder) {
  60. super.init(coder: aDecoder)
  61. }
  62. override func viewDidLoad() {
  63. super.viewDidLoad()
  64. self.navigationController?.navigationBar.prefersLargeTitles = true
  65. if enableSearchBar {
  66. searchController = UISearchController(searchResultsController: nil)
  67. searchController?.searchResultsUpdater = self
  68. self.navigationItem.searchController = searchController
  69. searchController?.dimsBackgroundDuringPresentation = false
  70. searchController?.delegate = self
  71. searchController?.searchBar.delegate = self
  72. }
  73. // Cell
  74. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  75. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  76. // Header
  77. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  78. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  79. // Footer
  80. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  81. collectionView.alwaysBounceVertical = true
  82. listLayout = NCListLayout()
  83. gridLayout = NCGridLayout()
  84. // Refresh Control
  85. collectionView.addSubview(refreshControl)
  86. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  87. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  88. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetwork), for: .valueChanged)
  89. // empty Data Source
  90. self.collectionView.emptyDataSetDelegate = self
  91. self.collectionView.emptyDataSetSource = self
  92. // 3D Touch peek and pop
  93. if traitCollection.forceTouchCapability == .available {
  94. registerForPreviewing(with: self, sourceView: view)
  95. }
  96. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  97. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  99. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  100. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  101. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  102. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  103. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  111. changeTheming()
  112. }
  113. override func viewWillAppear(_ animated: Bool) {
  114. super.viewWillAppear(animated)
  115. self.navigationItem.title = titleCurrentFolder
  116. // get auto upload folder
  117. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  118. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  119. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  120. gridLayout.itemForLine = CGFloat(itemForLine)
  121. if layout == k_layout_list {
  122. collectionView?.collectionViewLayout = listLayout
  123. } else {
  124. collectionView?.collectionViewLayout = gridLayout
  125. }
  126. if serverUrl == nil {
  127. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  128. } else {
  129. appDelegate.activeServerUrl = self.serverUrl
  130. }
  131. reloadDataSource()
  132. }
  133. override func viewDidAppear(_ animated: Bool) {
  134. super.viewDidAppear(animated)
  135. reloadDataSourceNetwork()
  136. }
  137. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  138. super.viewWillTransition(to: size, with: coordinator)
  139. coordinator.animate(alongsideTransition: nil) { _ in
  140. self.collectionView?.collectionViewLayout.invalidateLayout()
  141. }
  142. }
  143. // MARK: - Utility
  144. @objc func minCharTextFieldDidChange(sender: UITextField) {
  145. guard let alertController = self.presentedViewController as? UIAlertController else { return }
  146. guard let password = alertController.textFields?.first else { return }
  147. guard let ok = alertController.actions.last else { return }
  148. ok.isEnabled = password.text?.count ?? 0 >= 8
  149. }
  150. // MARK: - NotificationCenter
  151. @objc func changeTheming() {
  152. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  153. }
  154. @objc func deleteFile(_ notification: NSNotification) {
  155. if self.view?.window == nil { return }
  156. if let userInfo = notification.userInfo as NSDictionary? {
  157. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  158. if onlyLocal {
  159. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  160. let indexPath = IndexPath(row: row, section: 0)
  161. collectionView?.reloadItems(at: [indexPath])
  162. }
  163. } else {
  164. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  165. let indexPath = IndexPath(row: row, section: 0)
  166. collectionView?.performBatchUpdates({
  167. collectionView?.deleteItems(at: [indexPath])
  168. }, completion: { (_) in
  169. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  170. self.collectionView?.reloadData()
  171. }
  172. })
  173. }
  174. }
  175. }
  176. }
  177. }
  178. @objc func moveFile(_ notification: NSNotification) {
  179. if self.view?.window == nil { return }
  180. if let userInfo = notification.userInfo as NSDictionary? {
  181. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["metadataNew"] as? tableMetadata {
  182. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  183. let indexPath = IndexPath(row: row, section: 0)
  184. collectionView?.performBatchUpdates({
  185. collectionView?.deleteItems(at: [indexPath])
  186. }, completion: { (_) in
  187. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  188. self.collectionView?.reloadData()
  189. }
  190. })
  191. }
  192. }
  193. }
  194. }
  195. @objc func copyFile(_ notification: NSNotification) {
  196. if self.view?.window == nil { return }
  197. if let userInfo = notification.userInfo as NSDictionary? {
  198. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  199. if serverUrlTo == self.serverUrl {
  200. self.reloadDataSource()
  201. }
  202. }
  203. }
  204. }
  205. @objc func renameFile(_ notification: NSNotification) {
  206. if self.view?.window == nil { return }
  207. if let userInfo = notification.userInfo as NSDictionary? {
  208. if let metadata = userInfo["metadata"] as? tableMetadata {
  209. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  210. let indexPath = IndexPath(row: row, section: 0)
  211. collectionView?.performBatchUpdates({
  212. collectionView?.reloadItems(at: [indexPath])
  213. }, completion: { (_) in
  214. self.collectionView?.reloadData()
  215. })
  216. }
  217. }
  218. }
  219. }
  220. @objc func createFolder(_ notification: NSNotification) {
  221. if self.view?.window == nil { return }
  222. if let userInfo = notification.userInfo as NSDictionary? {
  223. if let metadata = userInfo["metadata"] as? tableMetadata {
  224. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  225. if let row = dataSource?.addMetadata(metadata) {
  226. let indexPath = IndexPath(row: row, section: 0)
  227. collectionView?.performBatchUpdates({
  228. collectionView?.insertItems(at: [indexPath])
  229. }, completion: { (_) in
  230. self.collectionView?.reloadData()
  231. })
  232. }
  233. }
  234. }
  235. } else {
  236. self.reloadDataSourceNetwork()
  237. }
  238. }
  239. @objc func favoriteFile(_ notification: NSNotification) {
  240. if self.view?.window == nil { return }
  241. if let userInfo = notification.userInfo as NSDictionary? {
  242. if let metadata = userInfo["metadata"] as? tableMetadata {
  243. if dataSource?.getIndexMetadata(ocId: metadata.ocId) != nil {
  244. self.reloadDataSource()
  245. }
  246. }
  247. }
  248. }
  249. @objc func downloadStartFile(_ notification: NSNotification) {
  250. if self.view?.window == nil { return }
  251. if let userInfo = notification.userInfo as NSDictionary? {
  252. if let metadata = userInfo["metadata"] as? tableMetadata {
  253. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  254. let indexPath = IndexPath(row: row, section: 0)
  255. collectionView?.reloadItems(at: [indexPath])
  256. }
  257. }
  258. }
  259. }
  260. @objc func downloadedFile(_ notification: NSNotification) {
  261. if self.view?.window == nil { return }
  262. if let userInfo = notification.userInfo as NSDictionary? {
  263. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  264. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  265. let indexPath = IndexPath(row: row, section: 0)
  266. collectionView?.reloadItems(at: [indexPath])
  267. }
  268. }
  269. }
  270. }
  271. @objc func downloadCancelFile(_ notification: NSNotification) {
  272. if self.view?.window == nil { return }
  273. if let userInfo = notification.userInfo as NSDictionary? {
  274. if let metadata = userInfo["metadata"] as? tableMetadata {
  275. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  276. let indexPath = IndexPath(row: row, section: 0)
  277. collectionView?.reloadItems(at: [indexPath])
  278. }
  279. }
  280. }
  281. }
  282. @objc func uploadStartFile(_ notification: NSNotification) {
  283. if self.view?.window == nil { return }
  284. if let userInfo = notification.userInfo as NSDictionary? {
  285. if let metadata = userInfo["metadata"] as? tableMetadata {
  286. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  287. if let row = dataSource?.addMetadata(metadata) {
  288. let indexPath = IndexPath(row: row, section: 0)
  289. collectionView?.performBatchUpdates({
  290. collectionView?.insertItems(at: [indexPath])
  291. }, completion: { (_) in
  292. self.collectionView?.reloadData()
  293. })
  294. }
  295. }
  296. }
  297. }
  298. }
  299. @objc func uploadedFile(_ notification: NSNotification) {
  300. if self.view?.window == nil { return }
  301. if let userInfo = notification.userInfo as NSDictionary? {
  302. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  303. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  304. dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  305. collectionView?.reloadData()
  306. }
  307. }
  308. }
  309. }
  310. @objc func uploadCancelFile(_ notification: NSNotification) {
  311. if self.view?.window == nil { return }
  312. if let userInfo = notification.userInfo as NSDictionary? {
  313. if let metadata = userInfo["metadata"] as? tableMetadata {
  314. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  315. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  316. let indexPath = IndexPath(row: row, section: 0)
  317. collectionView?.performBatchUpdates({
  318. collectionView?.deleteItems(at: [indexPath])
  319. }, completion: { (_) in
  320. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  321. self.collectionView?.reloadData()
  322. }
  323. })
  324. } else {
  325. self.reloadDataSource()
  326. }
  327. }
  328. }
  329. }
  330. }
  331. @objc func triggerProgressTask(_ notification: NSNotification) {
  332. if self.view?.window == nil { return }
  333. if let userInfo = notification.userInfo as NSDictionary? {
  334. if let ocId = userInfo["ocId"] as? String {
  335. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  336. let progress = progressNumber.floatValue
  337. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  338. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  339. if cell is NCListCell {
  340. let cell = cell as! NCListCell
  341. if progress > 0 {
  342. cell.progressView?.isHidden = false
  343. cell.progressView?.progress = progress
  344. cell.setButtonMore(named: "stop")
  345. }
  346. } else if cell is NCGridCell {
  347. let cell = cell as! NCGridCell
  348. if progress > 0 {
  349. cell.progressView.isHidden = false
  350. cell.progressView.progress = progress
  351. cell.setButtonMore(named: "stop")
  352. }
  353. }
  354. }
  355. }
  356. }
  357. }
  358. }
  359. // MARK: DZNEmpty
  360. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  361. return NCBrandColor.sharedInstance.backgroundView
  362. }
  363. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  364. if searchController?.isActive ?? false {
  365. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: NCBrandColor.sharedInstance.yellowFavorite)
  366. }
  367. return DZNimage
  368. }
  369. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  370. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  371. if searchController?.isActive ?? false {
  372. if isReloadDataSourceNetworkInProgress {
  373. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  374. } else {
  375. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  376. }
  377. }
  378. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  379. return NSAttributedString.init(string: text, attributes: attributes)
  380. }
  381. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  382. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  383. if searchController?.isActive ?? false {
  384. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  385. }
  386. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  387. return NSAttributedString.init(string: text, attributes: attributes)
  388. }
  389. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  390. return true
  391. }
  392. // MARK: SEARCH
  393. func updateSearchResults(for searchController: UISearchController) {
  394. timerInputSearch?.invalidate()
  395. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  396. literalSearch = searchController.searchBar.text
  397. collectionView?.reloadData()
  398. }
  399. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  400. isSearching = true
  401. metadatasSource.removeAll()
  402. reloadDataSource()
  403. }
  404. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  405. isSearching = false
  406. literalSearch = ""
  407. reloadDataSource()
  408. }
  409. // MARK: TAP EVENT
  410. func tapSwitchHeader(sender: Any) {
  411. if collectionView.collectionViewLayout == gridLayout {
  412. // list layout
  413. UIView.animate(withDuration: 0.0, animations: {
  414. self.collectionView.collectionViewLayout.invalidateLayout()
  415. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  416. self.collectionView.reloadData()
  417. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  418. })
  419. })
  420. layout = k_layout_list
  421. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  422. } else {
  423. // grid layout
  424. UIView.animate(withDuration: 0.0, animations: {
  425. self.collectionView.collectionViewLayout.invalidateLayout()
  426. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  427. self.collectionView.reloadData()
  428. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  429. })
  430. })
  431. layout = k_layout_grid
  432. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  433. }
  434. }
  435. func tapOrderHeader(sender: Any) {
  436. let sortMenu = NCSortMenu()
  437. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  438. }
  439. func tapMoreHeader(sender: Any) {
  440. }
  441. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  442. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  443. }
  444. func tapShareListItem(with objectId: String, sender: Any) {
  445. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else {
  446. return
  447. }
  448. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  449. }
  450. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  451. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  452. guard let tabBarController = self.tabBarController else { return }
  453. if namedButtonMore == "more" {
  454. toggleMoreMenu(viewController: tabBarController, metadata: metadata, selectOcId: selectOcId)
  455. } else if namedButtonMore == "stop" {
  456. NCMainCommon.shared.cancelTransferMetadata(metadata, uploadStatusForcedStart: false)
  457. }
  458. }
  459. func tapRichWorkspace(sender: Any) {
  460. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  461. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  462. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  463. viewerRichWorkspace.serverUrl = appDelegate.activeServerUrl
  464. navigationController.modalPresentationStyle = .fullScreen
  465. self.present(navigationController, animated: true, completion: nil)
  466. }
  467. }
  468. }
  469. // MARK: SEGUE
  470. @objc func segue(metadata: tableMetadata) {
  471. self.metadataPush = metadata
  472. performSegue(withIdentifier: "segueDetail", sender: self)
  473. }
  474. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  475. let photoDataSource: NSMutableArray = []
  476. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  477. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  478. photoDataSource.add(metadata)
  479. }
  480. }
  481. if let segueNavigationController = segue.destination as? UINavigationController {
  482. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  483. segueViewController.metadata = metadataPush
  484. }
  485. }
  486. }
  487. // MARK: - NC API & Algorithm
  488. @objc func reloadDataSource() {
  489. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, appDelegate.activeServerUrl))
  490. richWorkspaceText = directory?.richWorkspace
  491. }
  492. @objc func reloadDataSourceNetwork() { }
  493. @objc func networkSearch() {
  494. if literalSearch?.count ?? 0 > 1 {
  495. isReloadDataSourceNetworkInProgress = true
  496. collectionView?.reloadData()
  497. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  498. if self.searchController?.isActive ?? false && errorCode == 0 {
  499. self.metadatasSource = metadatas!
  500. }
  501. self.isReloadDataSourceNetworkInProgress = false
  502. self.reloadDataSource()
  503. }
  504. }
  505. }
  506. }
  507. // MARK: - 3D Touch peek and pop
  508. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  509. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  510. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  511. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  512. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  513. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  514. viewController.metadata = metadata
  515. if layout == k_layout_grid {
  516. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  517. previewingContext.sourceRect = cell.frame
  518. viewController.imageFile = cell.imageItem.image
  519. } else {
  520. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  521. previewingContext.sourceRect = cell.frame
  522. viewController.imageFile = cell.imageItem.image
  523. }
  524. viewController.showOpenIn = true
  525. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  526. viewController.showShare = false
  527. return viewController
  528. }
  529. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  530. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  531. collectionView(collectionView, didSelectItemAt: indexPath)
  532. }
  533. }
  534. // MARK: - Collection View
  535. extension NCCollectionViewCommon: UICollectionViewDelegate {
  536. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { }
  537. }
  538. extension NCCollectionViewCommon: UICollectionViewDataSource {
  539. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  540. if kind == UICollectionView.elementKindSectionHeader {
  541. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  542. if collectionView.collectionViewLayout == gridLayout {
  543. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  544. } else {
  545. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  546. }
  547. header.delegate = self
  548. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  549. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  550. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  551. header.setTitleSorted(datasourceTitleButton: titleButton)
  552. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  553. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  554. return header
  555. } else {
  556. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  557. let info = dataSource?.getFilesInformation()
  558. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  559. return footer
  560. }
  561. }
  562. func numberOfSections(in collectionView: UICollectionView) -> Int {
  563. return 1
  564. }
  565. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  566. return dataSource?.numberOfItemsInSection(section: section) ?? 1
  567. }
  568. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  569. let cell: UICollectionViewCell
  570. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  571. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  572. }
  573. if layout == k_layout_grid {
  574. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  575. } else {
  576. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  577. }
  578. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  579. NCCollectionCommon.shared.cellForItemAt(indexPath: indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: metadataFolder, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectocId: selectOcId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self, dataSource: dataSource)
  580. return cell
  581. }
  582. }
  583. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  584. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  585. if richWorkspaceText?.count ?? 0 == 0 {
  586. headerRichWorkspaceHeight = 0
  587. } else {
  588. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  589. }
  590. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  591. }
  592. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  593. return CGSize(width: collectionView.frame.width, height: footerHeight)
  594. }
  595. }