NCCollectionViewCommon.swift 36 KB

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