RustAssistant/app/src/main/java/com/coldmint/rust/pro/FileManagerActivity.kt

974 lines
42 KiB
Kotlin
Raw Normal View History

2022-04-04 14:03:10 +00:00
package com.coldmint.rust.pro
import com.coldmint.rust.pro.base.BaseActivity
import com.coldmint.rust.pro.tool.BookmarkManager
import androidx.recyclerview.widget.LinearLayoutManager
import android.content.Intent
import com.coldmint.rust.pro.tool.GlobalMethod
import com.google.android.material.snackbar.Snackbar
import android.provider.MediaStore
import android.provider.DocumentsContract
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.*
import android.view.*
import android.widget.*
2022-09-04 07:49:29 +00:00
import android.widget.Toast.makeText
2022-08-19 06:51:28 +00:00
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
2022-04-04 14:03:10 +00:00
import androidx.core.view.isVisible
2022-07-18 23:59:32 +00:00
import androidx.lifecycle.ViewModelProvider
2022-08-19 06:51:28 +00:00
import com.bumptech.glide.Glide
2022-08-10 09:27:38 +00:00
import com.coldmint.dialog.CoreDialog
import com.coldmint.dialog.InputDialog
2022-08-19 06:51:28 +00:00
import com.coldmint.rust.core.tool.DebugHelper
2022-04-04 14:03:10 +00:00
import com.coldmint.rust.core.tool.FileOperator
2022-08-10 09:27:38 +00:00
import com.coldmint.rust.core.tool.LineParser
2022-04-04 14:03:10 +00:00
import com.coldmint.rust.pro.adapters.FileAdapter
2022-08-10 09:27:38 +00:00
import com.coldmint.rust.pro.adapters.FileTabAdapter
import com.coldmint.rust.pro.databean.FileTab
2022-04-04 14:03:10 +00:00
import com.coldmint.rust.pro.databinding.ActivityFileBinding
import com.coldmint.rust.pro.interfaces.BookmarkListener
import com.coldmint.rust.pro.tool.AppSettings
2023-02-21 11:33:06 +00:00
import com.coldmint.rust.pro.ui.StableLinearLayoutManager
2022-07-18 23:59:32 +00:00
import com.coldmint.rust.pro.viewmodel.FileManagerViewModel
2022-08-10 09:27:38 +00:00
import com.google.android.material.chip.Chip
2022-04-04 14:03:10 +00:00
import com.google.android.material.dialog.MaterialAlertDialogBuilder
2022-08-10 09:27:38 +00:00
import com.google.android.material.snackbar.SnackbarContentLayout
2022-09-04 07:49:29 +00:00
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
2022-07-19 14:32:02 +00:00
import me.zhanghai.android.fastscroll.FastScrollerBuilder
2022-08-19 06:51:28 +00:00
import java.io.BufferedReader
2022-04-04 14:03:10 +00:00
import java.io.File
2022-08-19 06:51:28 +00:00
import java.io.InputStreamReader
2022-04-04 14:03:10 +00:00
import java.lang.Exception
import java.util.*
import java.util.concurrent.Executors
2022-09-04 07:49:29 +00:00
import javax.sql.CommonDataSource
2022-04-04 14:03:10 +00:00
import kotlin.collections.ArrayList
class FileManagerActivity : BaseActivity<ActivityFileBinding>() {
2022-08-10 09:27:38 +00:00
2022-08-19 06:51:28 +00:00
2022-07-18 23:59:32 +00:00
//
// /**
// * 编辑模板
// * @param file File
// */
// fun editTemplate(file: File) {
// val intent = Intent(this, TemplateMakerActivity::class.java)
// val bundle = Bundle()
// intent.putExtra("data", bundle)
// bundle.putString("path", file.absolutePath)
// bundle.putBoolean("loadTemplate", true)
// bundle.putString("templatePath", additionalData)
// startActivity(intent)
// }
//
// /**
// * 编辑文本
// * @param file File
// */
// fun editText(file: File) {
// val bundle = Bundle()
// bundle.putString("path", file.absolutePath)
// bundle.putString(
// "modPath",
// FileOperator.getSuperDirectory(file)
// )
// val intent = Intent(
// this@FileManagerActivity,
// EditActivity::class.java
// )
// intent.putExtra("data", bundle)
// this@FileManagerActivity.startActivity(intent)
// }
2022-08-10 09:27:38 +00:00
2022-07-18 23:59:32 +00:00
// override fun onPause() {
2022-08-10 09:27:38 +00:00
// viewModel.getBookmarkManager().save()
2022-07-18 23:59:32 +00:00
// super.onPause()
// }
2022-08-10 09:27:38 +00:00
override fun onResume() {
viewModel.getBookmarkManager().load()
loadMineBookmarksMenu()
super.onResume()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (viewModel.startTypeData == FileManagerViewModel.StartType.SELECT_FILE && requestCode == 1) {
2022-08-26 13:51:15 +00:00
// val path = FileOperator.parsePicturePath(this@FileManagerActivity, data)
// if (path != null) {
// val intent = Intent()
// intent.putExtra("File", path)
// setResult(RESULT_OK, intent)
// finish()
// }
2022-08-10 09:27:38 +00:00
} else if (viewModel.startTypeData == FileManagerViewModel.StartType.SELECT_FILE && requestCode == 2) {
2022-08-19 06:51:28 +00:00
// val path = viewModel.parseFilePath(this@FileManagerActivity, data)
// if (path != null) {
// val intent = Intent()
// intent.putExtra("File", path)
// setResult(RESULT_OK, intent)
//// bookmarkManager.save()
// finish()
// }
2022-08-10 09:27:38 +00:00
}
// else if (requestCode == 3) {
//新建源文件
2022-07-18 23:59:32 +00:00
// loadFiles(directs)
// } else if (requestCode == 4) {
// val file = File(data!!.getStringExtra("File"))
// val copyResult =
// FileOperator.copyFile(file, File(directs.toString() + "/" + file.name))
// if (!copyResult) {
// Snackbar.make(
// viewBinding.fab,
// getText(R.string.copy_file_error),
// Snackbar.LENGTH_SHORT
// ).show()
// } else {
// loadFiles(directs)
// }
// }
2022-08-10 09:27:38 +00:00
}
}
2022-08-19 06:51:28 +00:00
lateinit var photoAlbumResultLauncher: ActivityResultLauncher<Intent>
lateinit var systemFileManagerResultLauncher: ActivityResultLauncher<String>
2022-08-10 09:27:38 +00:00
//
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
android.R.id.home -> {
2022-07-18 23:59:32 +00:00
// bookmarkManager.save()
2022-08-10 09:27:38 +00:00
finish()
return true
}
R.id.reloadFile -> {
viewModel.loadFiles(viewModel.getCurrentPath())
return true
}
2022-08-19 06:51:28 +00:00
// R.id.photo_album -> {
// this@FileManagerActivity.startActivityForResult(
// Intent(
// Intent.ACTION_PICK,
// MediaStore.Images.Media.EXTERNAL_CONTENT_URI
// ), 1
// )
// return true
// }
// R.id.system_file_manager -> {
// val intent = Intent(Intent.ACTION_GET_CONTENT)
// intent.type = "*/*"
// intent.addCategory(Intent.CATEGORY_OPENABLE)
// this@FileManagerActivity.startActivityForResult(intent, 2)
// return true
// }
2022-08-10 09:27:38 +00:00
}
2022-07-18 23:59:32 +00:00
// loadBook(item.title)
2022-08-10 09:27:38 +00:00
return super.onOptionsItemSelected(item)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
if (viewModel.getCurrentPath() == viewModel.getRootPath()) {
finish()
true
} else {
viewModel.returnDirects()
false
}
} else super.onKeyDown(keyCode, event)
}
fun initAction() {
viewBinding.fab.setOnClickListener {
val startType = viewModel.startTypeData
when (startType) {
2022-07-18 23:59:32 +00:00
// "exportFile" -> {
// val oldFile = File(additionalData)
// val result = FileOperator.copyFile(
// oldFile,
// File(directs.absolutePath + "/" + oldFile.name)
// )
// if (result) {
// setResult(RESULT_OK)
// }
// finish()
// }
// "selectDirectents" -> {
// intent.putExtra("Directents", directs.absolutePath)
// setResult(RESULT_OK, intent)
// bookmarkManager.save()
// finish()
// }
// "selectFile" -> {
// intent.putExtra("File", filePath)
// setResult(RESULT_OK, intent)
// bookmarkManager.save()
// finish()
// }
2022-08-10 09:27:38 +00:00
2022-08-26 13:51:15 +00:00
// FileManagerViewModel.StartType.SELECT_FILE -> {
//
// }
FileManagerViewModel.StartType.DEFAULT, FileManagerViewModel.StartType.SELECT_FILE, FileManagerViewModel.StartType.SELECT_DIRECTORY -> {
var popupMenu = GlobalMethod.createPopMenu(viewBinding.fab)
2022-09-04 07:49:29 +00:00
if (adapter != null) {
val selectPath = adapter!!.selectPath
if (selectPath != null) {
if (adapter!!.isCopyFile) {
popupMenu.menu.add(R.string.copy_to_this)
} else {
popupMenu.menu.add(R.string.cut_to_this)
}
}
}
2022-08-10 09:27:38 +00:00
popupMenu.menu.add(R.string.create_unit)
popupMenu.menu.add(R.string.create_folder)
popupMenu.menu.add(R.string.select_file)
popupMenu.setOnMenuItemClickListener { item ->
val title = item.title
2022-07-18 23:59:32 +00:00
// val handler = Handler(Looper.getMainLooper())
2022-08-10 09:27:38 +00:00
when (title) {
getText(R.string.create_unit) -> {
val intent =
Intent(this@FileManagerActivity, CreateUnitActivity::class.java)
val bundle = Bundle()
bundle.putString("modPath", viewModel.getCurrentPath())
bundle.putString("createPath", viewModel.getCurrentPath())
intent.putExtra("data", bundle)
startActivityForResult(intent, 3)
}
getText(R.string.select_file) -> {
val bundle = Bundle()
val intent =
Intent(
this@FileManagerActivity,
FileManagerActivity::class.java
)
bundle.putString("type", "selectFile")
//bundle.putString("path", modClass.getModFile().getAbsolutePath());
intent.putExtra("data", bundle)
startActivityForResult(intent, 4)
}
getText(R.string.create_folder) -> {
createFolderAction()
}
2022-09-04 07:49:29 +00:00
getText(R.string.copy_to_this) -> {
val job = Job()
val handler = Handler(Looper.getMainLooper())
val scope = CoroutineScope(job)
scope.launch {
val oldFile = File(adapter!!.selectPath)
val newFile =
File(viewModel.getCurrentPath() + "/" + oldFile.name)
DebugHelper.printLog(
"文件管理器",
"复制文件 旧文件${oldFile.absolutePath} 新文件${newFile.absolutePath}"
)
adapter!!.cleanSelectPath()
if (FileOperator.copyFiles(oldFile, newFile)) {
handler.post {
viewModel.loadFiles(viewModel.getCurrentPath())
}
} else {
handler.post {
Snackbar.make(
viewBinding.fab,
getText(R.string.copy_failed),
Snackbar.LENGTH_SHORT
).show()
}
}
}
}
getText(R.string.cut_to_this) -> {
val job = Job()
val handler = Handler(Looper.getMainLooper())
val scope = CoroutineScope(job)
scope.launch {
val oldFile = File(adapter!!.selectPath)
val newFile =
File(viewModel.getCurrentPath() + "/" + oldFile.name)
DebugHelper.printLog(
"文件管理器",
"移动文件 旧文件${oldFile.absolutePath} 新文件${newFile.absolutePath}"
)
adapter!!.cleanSelectPath()
if (FileOperator.removeFiles(oldFile, newFile)) {
handler.post {
viewModel.loadFiles(viewModel.getCurrentPath())
}
} else {
handler.post {
Snackbar.make(
viewBinding.fab,
getText(R.string.cut_failed),
Snackbar.LENGTH_SHORT
).show()
}
}
}
}
2022-08-10 09:27:38 +00:00
}
false
}
popupMenu.show()
}
else -> {
}
}
}
}
2022-07-18 23:59:32 +00:00
//
// /**
// * 创建文件夹活动
// */
// private fun createFolderAction() {
// MaterialDialog(this).show {
// title(R.string.create_folder)
// input(
// maxLength = 255,
// waitForPositiveButton = false
// ) { dialog, text ->
// if (text.length in 1..255) {
// dialog.setActionButtonEnabled(WhichButton.POSITIVE, true)
// }
// }.positiveButton(R.string.dialog_ok, null) { dialog ->
// val string = dialog.getInputField().text.toString()
// val file = File("$directs/$string")
// if (file.exists()) {
// Toast.makeText(
// this@FileManagerActivity,
// R.string.folder_error,
// Toast.LENGTH_SHORT
// ).show()
// } else {
// file.mkdirs()
// loadFiles(directs)
// }
// }.negativeButton(R.string.dialog_close)
// }
// }
//
//
2022-08-10 09:27:38 +00:00
//
2022-07-18 23:59:32 +00:00
// private fun getPath(context: Context, uri: Uri?): String? {
// val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
//
// // DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// // ExternalStorageProvider
// if (isExternalStorageDocument(uri)) {
// val docId = DocumentsContract.getDocumentId(uri)
// val split = docId.split(":").toTypedArray()
// val type = split[0]
// if ("primary".equals(type, ignoreCase = true)) {
// return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
// }
// } else if (isDownloadsDocument(uri)) {
// val id = DocumentsContract.getDocumentId(uri)
// val contentUri = ContentUris.withAppendedId(
// Uri.parse("content://downloads/public_downloads"),
// java.lang.Long.valueOf(id)
// )
// return getDataColumn(context, contentUri, null, null)
// } else if (isMediaDocument(uri)) {
// val docId = DocumentsContract.getDocumentId(uri)
// val split = docId.split(":").toTypedArray()
// val type = split[0]
// var contentUri: Uri? = null
// if ("image" == type) {
// contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
// } else if ("video" == type) {
// contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
// } else if ("audio" == type) {
// contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
// }
// val selection = "_id=?"
// val selectionArgs = arrayOf(split[1])
// return getDataColumn(context, contentUri, selection, selectionArgs)
// }
// } else if ("content".equals(uri!!.scheme, ignoreCase = true)) {
// return getDataColumn(context, uri, null, null)
// } else if ("file".equals(uri.scheme, ignoreCase = true)) {
// uri.path
// }
// return null
// }
//
// private fun isMediaDocument(uri: Uri?): Boolean {
// return "com.android.providers.media.documents" == uri!!.authority
// }
//
// private fun isExternalStorageDocument(uri: Uri?): Boolean {
// return "com.android.externalstorage.documents" == uri!!.authority
// }
//
// private fun isDownloadsDocument(uri: Uri?): Boolean {
// return "com.android.providers.downloads.documents" == uri!!.authority
// }
//
// private fun getDataColumn(
// context: Context,
// uri: Uri?,
// selection: String?,
// selectionArgs: Array<String>?
// ): String? {
// var cursor: Cursor? = null
// val column = "_data"
// val projection = arrayOf(column)
// try {
// cursor = context.contentResolver.query(
// uri!!, projection, selection, selectionArgs,
// null
// )
// if (cursor != null && cursor.moveToFirst()) {
// val column_index = cursor.getColumnIndexOrThrow(column)
// return cursor.getString(column_index)
// }
// } finally {
// cursor?.close()
// }
// return null
// }
//
2022-07-19 14:32:02 +00:00
private lateinit var menuBinding: MenuBinding
2022-07-18 23:59:32 +00:00
private val viewModel: FileManagerViewModel by lazy {
ViewModelProvider(this).get(FileManagerViewModel::class.java)
}
2022-04-04 14:03:10 +00:00
2022-08-10 09:27:38 +00:00
/**
* 创建文件夹活动
*/
fun createFolderAction() {
InputDialog(this).setTitle(R.string.create_folder).setHint(R.string.file_name)
.setCancelable(false).setInputCanBeEmpty(false).setMaxNumber(255)
.setErrorTip { s, textInputLayout ->
val newFolder = File(viewModel.getCurrentPath() + "/" + s)
if (newFolder.exists()) {
textInputLayout.error = getString(R.string.folder_error)
} else {
textInputLayout.isErrorEnabled = false
}
}.setPositiveButton(R.string.dialog_ok) { i ->
val newFolder = File(viewModel.getCurrentPath() + "/" + i)
val res = newFolder.mkdirs()
adapter?.addItem(newFolder)
res
}.setNegativeButton(R.string.dialog_cancel) {
}.show()
}
2022-07-18 23:59:32 +00:00
private var adapter: FileAdapter? = null
2022-04-04 14:03:10 +00:00
2022-08-26 13:51:15 +00:00
/**
* 使用系统文件选择器选择回调
* @param uri Uri
*/
2022-09-04 07:49:29 +00:00
fun selectFileCallback(uri: Uri?) {
2022-08-26 13:51:15 +00:00
val path = viewModel.parseFilePath(this, uri)
if (path != null) {
CoreDialog(this).setTitle(R.string.system_file_manager).setMessage(path)
.setPositiveButton(R.string.select_file) {
setResultAndFinish(path)
}.setNegativeButton(R.string.dialog_cancel) {
}.setCancelable(false).show()
} else {
Snackbar.make(
viewBinding.fab,
R.string.bad_file_type,
Snackbar.LENGTH_SHORT
).show()
}
}
2022-07-18 23:59:32 +00:00
override fun whenCreateActivity(savedInstanceState: Bundle?, canUseView: Boolean) {
if (canUseView) {
setReturnButton()
2023-02-21 11:33:06 +00:00
viewBinding.recyclerView.layoutManager = StableLinearLayoutManager(this@FileManagerActivity)
val linearLayoutManager = StableLinearLayoutManager(this)
2022-08-10 09:27:38 +00:00
linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
viewBinding.fileTabNav.layoutManager = linearLayoutManager
2022-07-18 23:59:32 +00:00
loadTitle()
loadObserve()
2022-08-10 09:27:38 +00:00
initAction()
2022-08-14 02:43:53 +00:00
viewModel.initBookmarkManager(this)
viewModel.loadFiles()
viewModel.loadSortType(this)
2022-07-19 14:32:02 +00:00
viewBinding.swipeRefreshLayout.setOnRefreshListener {
viewModel.loadFiles(viewModel.getCurrentPath())
viewBinding.swipeRefreshLayout.isRefreshing = false
}
2022-08-26 13:51:15 +00:00
photoAlbumResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
selectFileCallback(it?.data?.data)
}
2022-08-19 06:51:28 +00:00
systemFileManagerResultLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) {
2022-09-04 07:49:29 +00:00
selectFileCallback(it)
2022-08-19 06:51:28 +00:00
}
2022-08-14 02:43:53 +00:00
FastScrollerBuilder(viewBinding.recyclerView).useMd2Style()
.setPopupTextProvider(adapter).build()
2022-04-04 14:03:10 +00:00
} else {
2022-07-18 23:59:32 +00:00
val bundle = intent.getBundleExtra("data")
2022-08-19 06:51:28 +00:00
if (bundle != null) {
if (bundle.containsKey("path")) {
viewModel.currentPathLiveData.value = bundle.getString("path")
}
2022-08-26 13:51:15 +00:00
viewModel.additionalData = bundle.getString("additionalData")
2022-08-19 06:51:28 +00:00
if (bundle.containsKey("type")) {
val type = bundle.getString("type")
viewModel.startTypeData = when (type) {
"selectDirectents" -> {
Snackbar.make(
viewBinding.fab,
R.string.select_directents,
Snackbar.LENGTH_INDEFINITE
).setAction(R.string.dialog_ok) {
2022-08-26 13:51:15 +00:00
intent.putExtra("Directents", viewModel.getCurrentPath())
setResult(RESULT_OK, intent)
2022-08-19 06:51:28 +00:00
finish()
}.setGestureInsetBottomIgnored(true).show()
FileManagerViewModel.StartType.SELECT_DIRECTORY
}
2022-08-26 13:51:15 +00:00
"exportFile" -> {
Snackbar.make(
viewBinding.fab,
R.string.export_file,
Snackbar.LENGTH_INDEFINITE
).setAction(R.string.dialog_ok) {
val oldFile = File(viewModel.additionalData)
val result = FileOperator.copyFile(
oldFile,
File(viewModel.getCurrentPath() + "/" + oldFile.name)
)
if (result) {
setResult(RESULT_OK)
}
finish()
}.setGestureInsetBottomIgnored(true).show()
FileManagerViewModel.StartType.EXPORT_FILE
}
2022-08-19 06:51:28 +00:00
"selectFile" -> {
FileManagerViewModel.StartType.SELECT_FILE
}
else -> {
FileManagerViewModel.StartType.DEFAULT
}
2022-08-10 09:27:38 +00:00
}
}
2022-08-19 06:51:28 +00:00
if (bundle.containsKey("rootpath")) {
viewModel.setRootPath(bundle.getString("rootpath"))
}
2022-08-10 09:27:38 +00:00
}
2022-08-19 06:51:28 +00:00
2022-04-04 14:03:10 +00:00
}
}
2022-07-19 14:32:02 +00:00
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuBinding = MenuBinding.inflate(menu, menuInflater)
val value = viewModel.sortTypeLiveData.value
if (value != null) {
setSortType(value)
}
2022-08-10 09:27:38 +00:00
if (viewModel.startTypeData != FileManagerViewModel.StartType.SELECT_FILE) {
menu.removeItem(R.id.selectFile)
}
2022-08-19 06:51:28 +00:00
menuBinding.systemFileManagerItem.setOnMenuItemClickListener {
systemFileManagerResultLauncher.launch("*/*")
true
2022-08-26 13:51:15 +00:00
}
menuBinding.photoAlbumItem.setOnMenuItemClickListener {
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
photoAlbumResultLauncher.launch(intent)
true
2022-08-19 06:51:28 +00:00
}
2022-07-30 13:53:14 +00:00
menuBinding.actionSortByType.setOnMenuItemClickListener {
viewModel.sortTypeLiveData.value = FileManagerViewModel.SortType.BY_TYPE
true
}
menuBinding.actionSortByName.setOnMenuItemClickListener {
viewModel.sortTypeLiveData.value = FileManagerViewModel.SortType.BY_NAME
true
}
menuBinding.actionSortBySize.setOnMenuItemClickListener {
viewModel.sortTypeLiveData.value = FileManagerViewModel.SortType.BY_SIZE
true
}
menuBinding.actionSortByLastModified.setOnMenuItemClickListener {
viewModel.sortTypeLiveData.value = FileManagerViewModel.SortType.BY_LAST_MODIFIED
true
}
2022-08-10 09:27:38 +00:00
loadMineBookmarksMenu()
menuBinding.bookmarkManagerItem.setOnMenuItemClickListener {
val intent = Intent(this, BookmarkManagerActivity::class.java)
startActivity(intent)
true
}
2022-07-19 14:32:02 +00:00
return true
}
2022-08-10 09:27:38 +00:00
/**
* 加载我的书签列表
*/
fun loadMineBookmarksMenu() {
if (this::menuBinding.isInitialized) {
menuBinding.mineBookmarksMenu.subMenu.clear()
viewModel.getBookmarkManager().fromList(object : BookmarkListener {
override fun find(path: String, name: String) {
val item = menuBinding.mineBookmarksMenu.subMenu.add(name)
item.setOnMenuItemClickListener {
viewModel.currentPathLiveData.value = path
true
}
}
})
}
}
2022-08-19 06:51:28 +00:00
/**
* 设置结果并结束界面
*/
fun setResultAndFinish(path: String) {
val temIntent = Intent()
temIntent.putExtra("File", path)
setResult(RESULT_OK, temIntent)
finish()
}
2022-08-10 09:27:38 +00:00
2022-04-04 14:03:10 +00:00
/**
2022-07-18 23:59:32 +00:00
* 加载观察者
2022-04-04 14:03:10 +00:00
*/
2022-07-18 23:59:32 +00:00
fun loadObserve() {
viewModel.loadStateLiveData.observe(this) {
2022-08-10 09:27:38 +00:00
viewBinding.fileTabNav.isVisible = !it
2022-07-18 23:59:32 +00:00
viewBinding.swipeRefreshLayout.isVisible = !it
viewBinding.fileError.isVisible = it
viewBinding.progressBar.isVisible = it
}
viewModel.sortTypeLiveData.observe(this) {
setSortType(it)
}
2022-07-18 23:59:32 +00:00
viewModel.fileListLiveData.observe(this) {
if (adapter == null) {
//创建实例(设置适配器)
adapter = FileAdapter(this, it)
adapter?.setItemEvent { i, fileItemBinding, viewHolder, file ->
2022-04-04 14:03:10 +00:00
fileItemBinding.root.setOnClickListener {
2022-07-18 23:59:32 +00:00
if (file == null) {
viewModel.returnDirects()
2022-04-04 14:03:10 +00:00
} else {
2022-07-18 23:59:32 +00:00
if (file.isDirectory) {
viewModel.currentPathLiveData.value = file.absolutePath
2022-08-19 06:51:28 +00:00
} else {
//文件点击事件
if (viewModel.startTypeData == FileManagerViewModel.StartType.SELECT_FILE) {
Snackbar.make(
viewBinding.fab,
R.string.select_file,
Snackbar.LENGTH_SHORT
).setAction(R.string.dialog_ok) {
setResultAndFinish(file.absolutePath)
}.setGestureInsetBottomIgnored(true).show()
2022-09-04 07:49:29 +00:00
} else if (viewModel.startTypeData == FileManagerViewModel.StartType.DEFAULT) {
val type = FileOperator.getFileType(file)
val data = AppSettings.getValue(
AppSettings.Setting.SourceFileType,
"ini,template"
)
2022-10-01 10:31:54 +00:00
val line = LineParser(data)
var isSourceFile = false
line.symbol = ","
line.analyse { lineNum, lineData, isEnd ->
if (type == lineData) {
2022-10-01 10:31:54 +00:00
isSourceFile = true
return@analyse false
}
true
}
if (isSourceFile) {
2022-09-04 07:49:29 +00:00
val intent = Intent(this, EditActivity::class.java)
val bundle = Bundle()
bundle.putString("path", file.absolutePath)
bundle.putString(
"modPath",
FileOperator.getSuperDirectory(file)
)
intent.putExtra("data", bundle)
startActivity(intent)
} else {
Snackbar.make(
viewBinding.fab, String.format(
getString(R.string.an_unsupported_file_type),
type
), Snackbar.LENGTH_SHORT
).show()
}
2022-08-19 06:51:28 +00:00
}
2022-08-10 09:27:38 +00:00
}
}
}
fileItemBinding.more.setOnClickListener {
if (file == null) {
return@setOnClickListener
}
val finalFile = file
val popupMenu = GlobalMethod.createPopMenu(fileItemBinding.more)
2022-08-10 09:27:38 +00:00
popupMenu.inflate(R.menu.menu_files_actions)
val bookAction = popupMenu.menu.findItem(R.id.bookmarkAction)
bookAction.title = if (viewModel.getBookmarkManager().contains(finalFile)) {
getString(R.string.remove_bookmark)
} else {
getString(R.string.add_bookmark)
}
popupMenu.show()
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.bookmarkAction -> {
if (viewModel.getBookmarkManager().contains(finalFile)) {
val remove =
viewModel.getBookmarkManager()
.removeBookmark(finalFile.absolutePath)
if (remove) {
Snackbar.make(
viewBinding.fab,
R.string.remove_bookmark_success,
Snackbar.LENGTH_SHORT
).show()
} else {
Snackbar.make(
viewBinding.fab,
R.string.remove_bookmark_fail,
Snackbar.LENGTH_SHORT
).show()
}
} else {
val add =
viewModel.getBookmarkManager()
.addBookmark(finalFile.absolutePath, finalFile.name)
if (add) {
Snackbar.make(
viewBinding.fab,
R.string.add_bookmark_success,
Snackbar.LENGTH_SHORT
).show()
} else {
Snackbar.make(
viewBinding.fab,
R.string.add_bookmark_fail,
Snackbar.LENGTH_SHORT
).show()
}
}
viewModel.getBookmarkManager().save()
loadMineBookmarksMenu()
}
R.id.renameAction -> {
val finalFile =
adapter!!.getItemData(viewHolder.absoluteAdapterPosition)
val oldname = finalFile!!.name
InputDialog(this).setInputCanBeEmpty(false)
.setTitle(R.string.rename).setMaxNumber(255)
.setHint(R.string.file_name).setText(oldname)
.setPositiveButton(R.string.dialog_ok) { string ->
if (string.isNotEmpty() && string != oldname) {
val newFile =
File(FileOperator.getSuperDirectory(finalFile) + "/" + string)
finalFile.renameTo(newFile)
adapter?.replaceItem(
newFile,
viewHolder.absoluteAdapterPosition
)
}
true
}.setNegativeButton(R.string.dialog_cancel) {
}.setCancelable(false).show()
}
R.id.deleteAction -> {
val finalFile =
adapter!!.getItemData(viewHolder.absoluteAdapterPosition)
val tip = String.format(
getString(R.string.delete_prompt),
finalFile!!.name
)
CoreDialog(this).setTitle(R.string.delete_title)
.setMessage(tip)
.setPositiveButton(R.string.delete_title) {
val delete = FileOperator.delete_files(finalFile)
if (delete) {
adapter?.removeItem(i)
}
}.setNegativeButton(R.string.dialog_cancel) {
}.show()
2022-08-06 13:59:24 +00:00
}
2022-09-04 07:49:29 +00:00
R.id.copyAction -> {
val finalFile =
adapter!!.getItemData(viewHolder.absoluteAdapterPosition)
adapter!!.setSelectPath(finalFile!!.absolutePath, true)
}
R.id.cutOffAction -> {
val finalFile =
adapter!!.getItemData(viewHolder.absoluteAdapterPosition)
adapter!!.setSelectPath(finalFile!!.absolutePath, false)
}
2022-04-04 14:03:10 +00:00
}
2022-08-10 09:27:38 +00:00
true
2022-04-04 14:03:10 +00:00
}
}
}
2022-07-18 23:59:32 +00:00
viewBinding.recyclerView.adapter = adapter
} else {
adapter?.setNewDataList(it)
2022-04-04 14:03:10 +00:00
}
}
2022-07-19 14:32:02 +00:00
viewModel.currentPathLiveData.observe(this) {
2022-08-19 06:51:28 +00:00
if (it == null) {
2022-08-14 02:43:53 +00:00
return@observe
}
2022-08-10 09:27:38 +00:00
val root = getString(R.string.root_path)
val rootLength = viewModel.getRootPath().length
val nowLength = it.length
val path = if (rootLength < nowLength) {
root + it.substring(rootLength)
} else {
it
}
2022-08-10 09:27:38 +00:00
val lineParser = LineParser(path)
lineParser.symbol = "/"
lineParser.parserSymbol = true
val fileTabList = ArrayList<FileTab>()
val stringBuilder = StringBuilder()
lineParser.analyse { lineNum, lineData, isEnd ->
stringBuilder.append(lineData)
if (lineData.isNotBlank() && lineData != lineParser.symbol) {
val tab = FileTab(
lineData,
viewModel.getRootPath() + stringBuilder.toString().substring(root.length)
)
fileTabList.add(tab)
}
true
}
val adapter = FileTabAdapter(this, fileTabList)
adapter.setItemEvent { i, itemFileTabBinding, viewHolder, fileTab ->
itemFileTabBinding.button.setOnClickListener {
viewModel.currentPathLiveData.value = fileTab.path
}
}
val manager = viewBinding.fileTabNav.layoutManager as LinearLayoutManager
manager.scrollToPosition(fileTabList.size - 1)
viewBinding.fileTabNav.adapter = adapter
2022-07-18 23:59:32 +00:00
viewModel.loadFiles(it)
2022-04-04 14:03:10 +00:00
}
}
/**
* 设置排序方式
* @param sortType SortType
*/
fun setSortType(sortType: FileManagerViewModel.SortType) {
if (this::menuBinding.isInitialized) {
when (sortType) {
FileManagerViewModel.SortType.BY_NAME -> {
menuBinding.actionSortByName.isChecked = true
}
FileManagerViewModel.SortType.BY_SIZE -> {
menuBinding.actionSortBySize.isChecked = true
}
FileManagerViewModel.SortType.BY_LAST_MODIFIED -> {
menuBinding.actionSortByLastModified.isChecked = true
}
FileManagerViewModel.SortType.BY_TYPE -> {
menuBinding.actionSortByType.isChecked = true
}
else -> {
menuBinding.actionSortByName.isChecked = true
}
}
adapter?.setSort(sortType)
viewModel.loadFiles(viewModel.getCurrentPath())
2022-07-30 13:53:14 +00:00
viewModel.saveSortType(this)
}
}
2022-04-04 14:03:10 +00:00
/**
2022-07-18 23:59:32 +00:00
* 加载页面标题
2022-04-04 14:03:10 +00:00
*/
2022-07-18 23:59:32 +00:00
fun loadTitle() {
title = when (viewModel.startTypeData) {
FileManagerViewModel.StartType.DEFAULT -> {
getString(R.string.file_manager)
2022-04-04 14:03:10 +00:00
}
2022-07-18 23:59:32 +00:00
else -> {
getString(R.string.file_manager)
2022-04-04 14:03:10 +00:00
}
}
}
2022-08-14 02:43:53 +00:00
override fun getViewBindingObject(layoutInflater: LayoutInflater): ActivityFileBinding {
2022-04-04 14:03:10 +00:00
return ActivityFileBinding.inflate(layoutInflater)
}
2022-07-19 14:32:02 +00:00
class MenuBinding private constructor(
val menu: Menu,
val reloadFileItem: MenuItem,
val photoAlbumItem: MenuItem,
val systemFileManagerItem: MenuItem,
val actionSortByName: MenuItem,
val actionSortByType: MenuItem,
2022-08-10 09:27:38 +00:00
val actionSortBySize: MenuItem,
val actionSortByLastModified: MenuItem,
val bookmarkItem: MenuItem,
val bookmarkManagerItem: MenuItem, val mineBookmarksMenu: MenuItem
2022-07-19 14:32:02 +00:00
) {
companion object {
//填充
fun inflate(menu: Menu, inflater: MenuInflater): MenuBinding {
inflater.inflate(R.menu.menu_files, menu)
return MenuBinding(
menu,
menu.findItem(R.id.reloadFile),
menu.findItem(R.id.photo_album),
menu.findItem(R.id.system_file_manager),
menu.findItem(R.id.action_sort_by_name),
menu.findItem(R.id.action_sort_by_type),
menu.findItem(R.id.action_sort_by_size),
2022-08-10 09:27:38 +00:00
menu.findItem(R.id.action_sort_by_last_modified),
menu.findItem(R.id.action_bookmark),
menu.findItem(R.id.bookmark_manager),
menu.findItem(R.id.mine_bookmarks)
2022-07-19 14:32:02 +00:00
)
}
}
}
2022-04-04 14:03:10 +00:00
}