NCCollectionViewCommon.swift 35 KB

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