NCCollectionViewCommon.swift 35 KB

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