NCCollectionViewCommon.swift 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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. import NCCommunication
  25. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. internal let refreshControl = UIRefreshControl()
  28. internal var searchController: UISearchController?
  29. @objc var serverUrl: String = ""
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. internal var isEncryptedFolder = false
  32. internal var isEditMode = false
  33. internal var selectOcId: [String] = []
  34. internal var metadatasSource: [tableMetadata] = []
  35. internal var metadataFolder: tableMetadata?
  36. internal var metadataTouch: tableMetadata?
  37. internal var dataSource: NCDataSource?
  38. internal var richWorkspaceText: String?
  39. internal var layout = ""
  40. internal var groupBy = ""
  41. internal var titleButton = ""
  42. internal var itemForLine = 0
  43. private var autoUploadFileName = ""
  44. private var autoUploadDirectory = ""
  45. private var listLayout: NCListLayout!
  46. private var gridLayout: NCGridLayout!
  47. private let headerHeight: CGFloat = 50
  48. private var headerRichWorkspaceHeight: CGFloat = 0
  49. private let footerHeight: CGFloat = 50
  50. private var timerInputSearch: Timer?
  51. internal var literalSearch: String?
  52. internal var isSearching: Bool = false
  53. internal var isReloadDataSourceNetworkInProgress: Bool = false
  54. // DECLARE
  55. internal var layoutKey = ""
  56. internal var titleCurrentFolder = ""
  57. internal var enableSearchBar: Bool = false
  58. internal var DZNimage: UIImage?
  59. internal var DZNtitle: String = ""
  60. internal var DZNdescription: String = ""
  61. required init?(coder aDecoder: NSCoder) {
  62. super.init(coder: aDecoder)
  63. }
  64. override func viewDidLoad() {
  65. super.viewDidLoad()
  66. self.navigationController?.navigationBar.prefersLargeTitles = true
  67. if enableSearchBar {
  68. searchController = UISearchController(searchResultsController: nil)
  69. searchController?.searchResultsUpdater = self
  70. searchController?.dimsBackgroundDuringPresentation = false
  71. searchController?.delegate = self
  72. searchController?.searchBar.delegate = self
  73. navigationItem.searchController = searchController
  74. navigationItem.hidesSearchBarWhenScrolling = false
  75. }
  76. // Cell
  77. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  78. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  79. // Header
  80. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  81. // Footer
  82. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  83. collectionView.alwaysBounceVertical = true
  84. listLayout = NCListLayout()
  85. gridLayout = NCGridLayout()
  86. // Refresh Control
  87. collectionView.addSubview(refreshControl)
  88. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  89. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  90. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  91. // empty Data Source
  92. self.collectionView.emptyDataSetDelegate = self
  93. self.collectionView.emptyDataSetSource = self
  94. // 3D Touch peek and pop
  95. if traitCollection.forceTouchCapability == .available {
  96. registerForPreviewing(with: self, sourceView: view)
  97. }
  98. // Long Press on CollectionView
  99. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  100. longPressedGesture.minimumPressDuration = 0.5
  101. longPressedGesture.delegate = self
  102. longPressedGesture.delaysTouchesBegan = true
  103. collectionView.addGestureRecognizer(longPressedGesture)
  104. // Notification
  105. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  122. changeTheming()
  123. }
  124. override func viewWillAppear(_ animated: Bool) {
  125. super.viewWillAppear(animated)
  126. appDelegate.activeViewController = self
  127. self.navigationItem.title = titleCurrentFolder
  128. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  129. gridLayout.itemForLine = CGFloat(itemForLine)
  130. if layout == k_layout_list {
  131. collectionView?.collectionViewLayout = listLayout
  132. } else {
  133. collectionView?.collectionViewLayout = gridLayout
  134. }
  135. setNavigationItem()
  136. reloadDataSource()
  137. }
  138. override func viewDidAppear(_ animated: Bool) {
  139. super.viewDidAppear(animated)
  140. reloadDataSourceNetwork()
  141. }
  142. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  143. super.viewWillTransition(to: size, with: coordinator)
  144. coordinator.animate(alongsideTransition: nil) { _ in
  145. self.collectionView?.collectionViewLayout.invalidateLayout()
  146. }
  147. }
  148. override var canBecomeFirstResponder: Bool {
  149. return true
  150. }
  151. func setNavigationItem() {
  152. if isEditMode {
  153. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  154. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  155. } else {
  156. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  157. self.navigationItem.leftBarButtonItem = nil
  158. }
  159. }
  160. // MARK: - NotificationCenter
  161. @objc func initializeMain() {
  162. if searchController?.isActive ?? false {
  163. searchController?.isActive = false
  164. }
  165. self.navigationController?.popToRootViewController(animated: false)
  166. appDelegate.listFavoriteVC.removeAllObjects()
  167. appDelegate.listOfflineVC.removeAllObjects()
  168. reloadDataSource()
  169. }
  170. @objc func changeTheming() {
  171. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  172. }
  173. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  174. if self.view?.window == nil { return }
  175. reloadDataSource()
  176. }
  177. @objc func deleteFile(_ notification: NSNotification) {
  178. if self.view?.window == nil { return }
  179. if let userInfo = notification.userInfo as NSDictionary? {
  180. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  181. if onlyLocal {
  182. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  183. let indexPath = IndexPath(row: row, section: 0)
  184. collectionView?.reloadItems(at: [indexPath])
  185. }
  186. } else {
  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. self.collectionView?.reloadData()
  193. })
  194. }
  195. }
  196. }
  197. }
  198. }
  199. @objc func moveFile(_ notification: NSNotification) {
  200. if self.view?.window == nil { return }
  201. if let userInfo = notification.userInfo as NSDictionary? {
  202. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  203. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  204. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  205. let indexPath = IndexPath(row: row, section: 0)
  206. collectionView?.performBatchUpdates({
  207. collectionView?.deleteItems(at: [indexPath])
  208. }, completion: { (_) in
  209. self.collectionView?.reloadData()
  210. })
  211. }
  212. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  213. if let row = dataSource?.addMetadata(metadataNew) {
  214. let indexPath = IndexPath(row: row, section: 0)
  215. collectionView?.performBatchUpdates({
  216. collectionView?.insertItems(at: [indexPath])
  217. }, completion: { (_) in
  218. self.collectionView?.reloadData()
  219. })
  220. }
  221. }
  222. }
  223. }
  224. }
  225. @objc func copyFile(_ notification: NSNotification) {
  226. if self.view?.window == nil { return }
  227. if let userInfo = notification.userInfo as NSDictionary? {
  228. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  229. if serverUrlTo == self.serverUrl {
  230. self.reloadDataSource()
  231. }
  232. }
  233. }
  234. }
  235. @objc func renameFile(_ notification: NSNotification) {
  236. if self.view?.window == nil { return }
  237. if let userInfo = notification.userInfo as NSDictionary? {
  238. if let metadata = userInfo["metadata"] as? tableMetadata {
  239. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  240. let indexPath = IndexPath(row: row, section: 0)
  241. collectionView?.performBatchUpdates({
  242. collectionView?.reloadItems(at: [indexPath])
  243. }, completion: { (_) in
  244. self.collectionView?.reloadData()
  245. })
  246. }
  247. }
  248. }
  249. }
  250. @objc func createFolder(_ notification: NSNotification) {
  251. if self.view?.window == nil { return }
  252. if let userInfo = notification.userInfo as NSDictionary? {
  253. if let metadata = userInfo["metadata"] as? tableMetadata {
  254. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  255. if let row = dataSource?.addMetadata(metadata) {
  256. let indexPath = IndexPath(row: row, section: 0)
  257. collectionView?.performBatchUpdates({
  258. collectionView?.insertItems(at: [indexPath])
  259. }, completion: { (_) in
  260. self.collectionView?.reloadData()
  261. })
  262. }
  263. }
  264. }
  265. } else {
  266. self.reloadDataSourceNetwork()
  267. }
  268. }
  269. @objc func favoriteFile(_ notification: NSNotification) {
  270. if self.view?.window == nil { return }
  271. if let userInfo = notification.userInfo as NSDictionary? {
  272. if let metadata = userInfo["metadata"] as? tableMetadata {
  273. if dataSource?.getIndexMetadata(ocId: metadata.ocId) != nil {
  274. self.reloadDataSource()
  275. }
  276. }
  277. }
  278. }
  279. @objc func downloadStartFile(_ 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 downloadedFile(_ 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, let _ = userInfo["errorCode"] as? Int {
  294. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  295. let indexPath = IndexPath(row: row, section: 0)
  296. collectionView?.reloadItems(at: [indexPath])
  297. }
  298. }
  299. }
  300. }
  301. @objc func downloadCancelFile(_ notification: NSNotification) {
  302. if self.view?.window == nil { return }
  303. if let userInfo = notification.userInfo as NSDictionary? {
  304. if let metadata = userInfo["metadata"] as? tableMetadata {
  305. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  306. let indexPath = IndexPath(row: row, section: 0)
  307. collectionView?.reloadItems(at: [indexPath])
  308. }
  309. }
  310. }
  311. }
  312. @objc func uploadStartFile(_ notification: NSNotification) {
  313. if self.view?.window == nil { return }
  314. if let userInfo = notification.userInfo as NSDictionary? {
  315. if let metadata = userInfo["metadata"] as? tableMetadata {
  316. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  317. if let row = dataSource?.addMetadata(metadata) {
  318. let indexPath = IndexPath(row: row, section: 0)
  319. collectionView?.performBatchUpdates({
  320. collectionView?.insertItems(at: [indexPath])
  321. }, completion: { (_) in
  322. self.collectionView?.reloadData()
  323. })
  324. }
  325. }
  326. }
  327. }
  328. }
  329. @objc func uploadedFile(_ notification: NSNotification) {
  330. if self.view?.window == nil { return }
  331. if let userInfo = notification.userInfo as NSDictionary? {
  332. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  333. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  334. dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  335. collectionView?.reloadData()
  336. }
  337. }
  338. }
  339. }
  340. @objc func uploadCancelFile(_ notification: NSNotification) {
  341. if self.view?.window == nil { return }
  342. if let userInfo = notification.userInfo as NSDictionary? {
  343. if let metadata = userInfo["metadata"] as? tableMetadata {
  344. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  345. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  346. let indexPath = IndexPath(row: row, section: 0)
  347. collectionView?.performBatchUpdates({
  348. collectionView?.deleteItems(at: [indexPath])
  349. }, completion: { (_) in
  350. self.collectionView?.reloadData()
  351. })
  352. } else {
  353. self.reloadDataSource()
  354. }
  355. }
  356. }
  357. }
  358. }
  359. @objc func triggerProgressTask(_ notification: NSNotification) {
  360. if self.view?.window == nil { return }
  361. if let userInfo = notification.userInfo as NSDictionary? {
  362. if let ocId = userInfo["ocId"] as? String {
  363. let _ = userInfo["account"] as? String ?? ""
  364. let _ = userInfo["serverUrl"] as? String ?? ""
  365. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  366. let progress = progressNumber.floatValue
  367. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  368. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  369. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  370. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  371. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  372. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  373. if cell is NCListCell {
  374. let cell = cell as! NCListCell
  375. if progress > 0 {
  376. cell.progressView?.isHidden = false
  377. cell.progressView?.progress = progress
  378. cell.setButtonMore(named: "stop")
  379. if status == k_metadataStatusInDownload {
  380. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  381. } else if status == k_metadataStatusInUpload {
  382. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  383. }
  384. }
  385. } else if cell is NCGridCell {
  386. let cell = cell as! NCGridCell
  387. if progress > 0 {
  388. cell.progressView.isHidden = false
  389. cell.progressView.progress = progress
  390. cell.setButtonMore(named: "stop")
  391. }
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. // MARK: - DZNEmpty
  399. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  400. return NCBrandColor.sharedInstance.backgroundView
  401. }
  402. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  403. if searchController?.isActive ?? false {
  404. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: NCBrandColor.sharedInstance.yellowFavorite)
  405. }
  406. return DZNimage
  407. }
  408. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  409. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  410. if searchController?.isActive ?? false {
  411. if isReloadDataSourceNetworkInProgress {
  412. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  413. } else {
  414. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  415. }
  416. }
  417. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  418. return NSAttributedString.init(string: text, attributes: attributes)
  419. }
  420. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  421. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  422. if searchController?.isActive ?? false {
  423. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  424. }
  425. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  426. return NSAttributedString.init(string: text, attributes: attributes)
  427. }
  428. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  429. return true
  430. }
  431. // MARK: - SEARCH
  432. func updateSearchResults(for searchController: UISearchController) {
  433. timerInputSearch?.invalidate()
  434. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  435. literalSearch = searchController.searchBar.text
  436. collectionView?.reloadData()
  437. }
  438. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  439. isSearching = true
  440. metadatasSource.removeAll()
  441. reloadDataSource()
  442. }
  443. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  444. isSearching = false
  445. literalSearch = ""
  446. reloadDataSource()
  447. }
  448. // MARK: - TAP EVENT
  449. @objc func tapSelect(sender: Any) {
  450. isEditMode = !isEditMode
  451. selectOcId.removeAll()
  452. setNavigationItem()
  453. self.collectionView.reloadData()
  454. }
  455. func tapSwitchHeader(sender: Any) {
  456. if collectionView.collectionViewLayout == gridLayout {
  457. // list layout
  458. UIView.animate(withDuration: 0.0, animations: {
  459. self.collectionView.collectionViewLayout.invalidateLayout()
  460. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  461. self.collectionView.reloadData()
  462. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  463. })
  464. })
  465. layout = k_layout_list
  466. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  467. } else {
  468. // grid layout
  469. UIView.animate(withDuration: 0.0, animations: {
  470. self.collectionView.collectionViewLayout.invalidateLayout()
  471. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  472. self.collectionView.reloadData()
  473. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  474. })
  475. })
  476. layout = k_layout_grid
  477. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  478. }
  479. }
  480. func tapOrderHeader(sender: Any) {
  481. let sortMenu = NCSortMenu()
  482. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  483. }
  484. @objc func tapSelectMenu(sender: Any) {
  485. guard let tabBarController = self.tabBarController else { return }
  486. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  487. }
  488. func tapMoreHeader(sender: Any) { }
  489. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  490. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  491. }
  492. func tapShareListItem(with objectId: String, sender: Any) {
  493. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  494. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  495. }
  496. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  497. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  498. guard let tabBarController = self.tabBarController else { return }
  499. if namedButtonMore == "more" {
  500. toggleMoreMenu(viewController: tabBarController, metadata: metadata)
  501. } else if namedButtonMore == "stop" {
  502. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  503. }
  504. }
  505. func tapRichWorkspace(sender: Any) {
  506. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  507. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  508. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  509. viewerRichWorkspace.serverUrl = serverUrl
  510. navigationController.modalPresentationStyle = .fullScreen
  511. self.present(navigationController, animated: true, completion: nil)
  512. }
  513. }
  514. }
  515. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  516. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  517. metadataTouch = metadata
  518. longPressCollecationView(gestureRecognizer)
  519. }
  520. }
  521. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  522. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  523. metadataTouch = metadata
  524. longPressCollecationView(gestureRecognizer)
  525. }
  526. }
  527. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  528. }
  529. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  530. }
  531. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  532. if gestureRecognizer.state != .began { return }
  533. if serverUrl == "" { return }
  534. var listMenuItems: [UIMenuItem] = []
  535. let touchPoint = gestureRecognizer.location(in: collectionView)
  536. becomeFirstResponder()
  537. if metadataTouch != nil {
  538. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  539. }
  540. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  541. if metadataTouch != nil {
  542. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  543. if !NCBrandOptions.sharedInstance.disable_openin_file {
  544. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  545. }
  546. }
  547. if listMenuItems.count > 0 {
  548. UIMenuController.shared.menuItems = listMenuItems
  549. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  550. UIMenuController.shared.setMenuVisible(true, animated: true)
  551. }
  552. }
  553. // MARK: - Menu Item
  554. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  555. if (#selector(pasteFilesMenu(_:)) == action) {
  556. if UIPasteboard.general.items.count > 0 {
  557. return true
  558. }
  559. }
  560. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  561. guard let metadata = metadataTouch else { return false }
  562. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  563. return true
  564. }
  565. }
  566. return false
  567. }
  568. @objc func copyFileMenu(_ notification: Any) {
  569. var metadatas: [tableMetadata] = []
  570. var items = [[String : Any]]()
  571. if isEditMode {
  572. for ocId in selectOcId {
  573. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  574. metadatas.append(metadata)
  575. }
  576. }
  577. } else {
  578. guard let metadata = metadataTouch else { return }
  579. metadatas.append(metadata)
  580. }
  581. for metadata in metadatas {
  582. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  583. do {
  584. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  585. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  586. } catch {
  587. print("error")
  588. }
  589. } else {
  590. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  591. }
  592. }
  593. UIPasteboard.general.setItems(items, options: [:])
  594. if isEditMode {
  595. tapSelect(sender: self)
  596. }
  597. }
  598. @objc func pasteFilesMenu(_ notification: Any) {
  599. var listData: [String] = []
  600. for item in UIPasteboard.general.items {
  601. for object in item {
  602. let contentType = object.key
  603. let data = object.value
  604. if contentType == k_metadataKeyedUnarchiver {
  605. do {
  606. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  607. uploadPasteOcId(ocId)
  608. }
  609. } catch {
  610. print("error")
  611. }
  612. continue
  613. }
  614. if data is String {
  615. if listData.contains(data as! String) {
  616. continue
  617. } else {
  618. listData.append(data as! String)
  619. }
  620. }
  621. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  622. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  623. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  624. }
  625. }
  626. }
  627. }
  628. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  629. do {
  630. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  631. let ocId = UUID().uuidString
  632. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  633. if data is UIImage {
  634. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  635. } else if data is Data {
  636. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  637. } else if data is String {
  638. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  639. } else {
  640. return
  641. }
  642. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  643. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  644. metadataForUpload.sessionSelector = selectorUploadFile
  645. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  646. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  647. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  648. } catch { }
  649. }
  650. private func uploadPasteOcId(_ ocId: String) {
  651. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  652. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  653. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  654. let ocId = NSUUID().uuidString
  655. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  656. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  657. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  658. metadataForUpload.sessionSelector = selectorUploadFile
  659. metadataForUpload.size = metadata.size
  660. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  661. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  662. }
  663. }
  664. }
  665. @objc func openQuickLookMenu(_ notification: Any) {
  666. guard let metadata = metadataTouch else { return }
  667. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  668. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  669. } else {
  670. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  671. }
  672. }
  673. @objc func openInMenu(_ notification: Any) {
  674. guard let metadata = metadataTouch else { return }
  675. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  676. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  677. } else {
  678. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  679. }
  680. }
  681. // MARK: - SEGUE
  682. @objc func segue(metadata: tableMetadata) {
  683. self.metadataTouch = metadata
  684. performSegue(withIdentifier: "segueDetail", sender: self)
  685. }
  686. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  687. let photoDataSource: NSMutableArray = []
  688. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  689. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  690. photoDataSource.add(metadata)
  691. }
  692. }
  693. if let segueNavigationController = segue.destination as? UINavigationController {
  694. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  695. segueViewController.metadata = metadataTouch
  696. }
  697. }
  698. }
  699. // MARK: - DataSource + NC Endpoint
  700. @objc func reloadDataSource() {
  701. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  702. richWorkspaceText = directory?.richWorkspace
  703. // E2EE
  704. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  705. // get auto upload folder
  706. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  707. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  708. }
  709. @objc func reloadDataSource(_ notification: NSNotification) { }
  710. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  711. @objc func reloadDataSourceNetworkRefreshControl() {
  712. reloadDataSourceNetwork(forced: true)
  713. }
  714. @objc func networkSearch() {
  715. if literalSearch?.count ?? 0 > 1 {
  716. isReloadDataSourceNetworkInProgress = true
  717. collectionView?.reloadData()
  718. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  719. if self.searchController?.isActive ?? false && errorCode == 0 {
  720. self.metadatasSource = metadatas!
  721. }
  722. self.isReloadDataSourceNetworkInProgress = false
  723. self.reloadDataSource()
  724. }
  725. }
  726. }
  727. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  728. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  729. if errorCode == 0 {
  730. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  731. if forced || directory?.etag != metadata?.etag {
  732. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  733. if errorCode == 0 {
  734. self.metadataFolder = metadataFolder
  735. }
  736. completion(metadatas, errorCode, errorDescription)
  737. }
  738. } else {
  739. completion(nil, 0, "")
  740. }
  741. } else {
  742. completion(nil, errorCode, errorDescription)
  743. }
  744. }
  745. }
  746. }
  747. // MARK: - 3D Touch peek and pop
  748. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  749. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  750. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  751. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  752. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  753. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  754. viewController.metadata = metadata
  755. if layout == k_layout_grid {
  756. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  757. previewingContext.sourceRect = cell.frame
  758. viewController.imageFile = cell.imageItem.image
  759. } else {
  760. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  761. previewingContext.sourceRect = cell.frame
  762. viewController.imageFile = cell.imageItem.image
  763. }
  764. viewController.showOpenIn = true
  765. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  766. viewController.showShare = false
  767. return viewController
  768. }
  769. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  770. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  771. collectionView(collectionView, didSelectItemAt: indexPath)
  772. }
  773. }
  774. // MARK: - Collection View
  775. extension NCCollectionViewCommon: UICollectionViewDelegate {
  776. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  777. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return }
  778. metadataTouch = metadata
  779. if isEditMode {
  780. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  781. selectOcId.remove(at: index)
  782. } else {
  783. selectOcId.append(metadata.ocId)
  784. }
  785. collectionView.reloadItems(at: [indexPath])
  786. return
  787. }
  788. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  789. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  790. return
  791. }
  792. if metadata.directory {
  793. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  794. // FAVORITE
  795. if layoutKey == k_layout_view_favorite {
  796. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  797. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  798. if vcFavorite.isViewLoaded {
  799. self.navigationController?.pushViewController(vcFavorite, animated: true)
  800. }
  801. } else {
  802. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  803. vcFavorite.serverUrl = serverUrlPush
  804. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  805. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  806. self.navigationController?.pushViewController(vcFavorite, animated: true)
  807. }
  808. }
  809. // OFFLINE
  810. if layoutKey == k_layout_view_offline {
  811. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  812. guard let vcOffline = (viewController as? NCOffline) else { return }
  813. if vcOffline.isViewLoaded {
  814. self.navigationController?.pushViewController(vcOffline, animated: true)
  815. }
  816. } else {
  817. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  818. vcOffline.serverUrl = serverUrlPush
  819. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  820. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  821. self.navigationController?.pushViewController(vcOffline, animated: true)
  822. }
  823. }
  824. } else {
  825. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  826. if NCCommunication.shared.isNetworkReachable() {
  827. performSegue(withIdentifier: "segueDetail", sender: self)
  828. } else {
  829. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  830. }
  831. return
  832. }
  833. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  834. if NCCommunication.shared.isNetworkReachable() {
  835. performSegue(withIdentifier: "segueDetail", sender: self)
  836. } else {
  837. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  838. }
  839. return
  840. }
  841. if CCUtility.fileProviderStorageExists(metadataTouch?.ocId, fileNameView: metadataTouch?.fileNameView) {
  842. performSegue(withIdentifier: "segueDetail", sender: self)
  843. } else {
  844. NCNetworking.shared.download(metadata: metadataTouch!, selector: selectorLoadFileView) { (_) in }
  845. }
  846. }
  847. }
  848. func collectionViewSelectAll() {
  849. selectOcId.removeAll()
  850. for metadata in metadatasSource {
  851. selectOcId.append(metadata.ocId)
  852. }
  853. collectionView.reloadData()
  854. }
  855. }
  856. extension NCCollectionViewCommon: UICollectionViewDataSource {
  857. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  858. if kind == UICollectionView.elementKindSectionHeader {
  859. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  860. if collectionView.collectionViewLayout == gridLayout {
  861. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  862. } else {
  863. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  864. }
  865. header.delegate = self
  866. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  867. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  868. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  869. header.setTitleSorted(datasourceTitleButton: titleButton)
  870. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  871. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  872. return header
  873. } else {
  874. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  875. let info = dataSource?.getFilesInformation()
  876. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  877. return footer
  878. }
  879. }
  880. func numberOfSections(in collectionView: UICollectionView) -> Int {
  881. return 1
  882. }
  883. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  884. return dataSource?.numberOfItems() ?? 0
  885. }
  886. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  887. let cell: UICollectionViewCell
  888. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  889. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  890. }
  891. if layout == k_layout_grid {
  892. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  893. } else {
  894. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  895. }
  896. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  897. NCCollectionCommon.shared.cellForItemAt(indexPath: indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: metadataFolder, serverUrl: metadata.serverUrl, isEditMode: isEditMode, isEncryptedFolder: isEncryptedFolder, selectocId: selectOcId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self, dataSource: dataSource)
  898. return cell
  899. }
  900. }
  901. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  902. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  903. if richWorkspaceText?.count ?? 0 == 0 {
  904. headerRichWorkspaceHeight = 0
  905. } else {
  906. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  907. }
  908. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  909. }
  910. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  911. return CGSize(width: collectionView.frame.width, height: footerHeight)
  912. }
  913. }