NCCollectionViewCommon.swift 46 KB

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