diff --git a/.gradle/7.3.3/checksums/checksums.lock b/.gradle/7.3.3/checksums/checksums.lock index bce98c5..f7ccf9d 100644 Binary files a/.gradle/7.3.3/checksums/checksums.lock and b/.gradle/7.3.3/checksums/checksums.lock differ diff --git a/.gradle/7.3.3/checksums/md5-checksums.bin b/.gradle/7.3.3/checksums/md5-checksums.bin index 5b81aeb..b555d08 100644 Binary files a/.gradle/7.3.3/checksums/md5-checksums.bin and b/.gradle/7.3.3/checksums/md5-checksums.bin differ diff --git a/.gradle/7.3.3/checksums/sha1-checksums.bin b/.gradle/7.3.3/checksums/sha1-checksums.bin index 00c40ac..9ae2745 100644 Binary files a/.gradle/7.3.3/checksums/sha1-checksums.bin and b/.gradle/7.3.3/checksums/sha1-checksums.bin differ diff --git a/.gradle/7.3.3/executionHistory/executionHistory.bin b/.gradle/7.3.3/executionHistory/executionHistory.bin index 5d35372..8e1e1bb 100644 Binary files a/.gradle/7.3.3/executionHistory/executionHistory.bin and b/.gradle/7.3.3/executionHistory/executionHistory.bin differ diff --git a/.gradle/7.3.3/executionHistory/executionHistory.lock b/.gradle/7.3.3/executionHistory/executionHistory.lock index d0fa88e..08b0d3e 100644 Binary files a/.gradle/7.3.3/executionHistory/executionHistory.lock and b/.gradle/7.3.3/executionHistory/executionHistory.lock differ diff --git a/.gradle/7.3.3/fileHashes/fileHashes.bin b/.gradle/7.3.3/fileHashes/fileHashes.bin index 2d26ea2..b67a4f3 100644 Binary files a/.gradle/7.3.3/fileHashes/fileHashes.bin and b/.gradle/7.3.3/fileHashes/fileHashes.bin differ diff --git a/.gradle/7.3.3/fileHashes/fileHashes.lock b/.gradle/7.3.3/fileHashes/fileHashes.lock index 6aef68d..39baa2b 100644 Binary files a/.gradle/7.3.3/fileHashes/fileHashes.lock and b/.gradle/7.3.3/fileHashes/fileHashes.lock differ diff --git a/.gradle/7.3.3/fileHashes/resourceHashesCache.bin b/.gradle/7.3.3/fileHashes/resourceHashesCache.bin index cbe4be6..fe2ecc0 100644 Binary files a/.gradle/7.3.3/fileHashes/resourceHashesCache.bin and b/.gradle/7.3.3/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock index efa6478..7def8ea 100644 Binary files a/.gradle/buildOutputCleanup/buildOutputCleanup.lock and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin index 0aba087..820e491 100644 Binary files a/.gradle/buildOutputCleanup/outputFiles.bin and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe index 5d5f9de..7de5302 100644 Binary files a/.gradle/file-system.probe and b/.gradle/file-system.probe differ diff --git a/app/build.gradle b/app/build.gradle index 60fd4bb..babb5ed 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -68,6 +68,9 @@ android { dependencies { + def nav_version = "2.5.1" + + implementation 'com.leinardi.android:speed-dial:3.1.1' // implementation 'com.luolc:emoji-rain:0.1.1' implementation 'me.zhanghai.android.fastscroll:library:1.1.8' // 语种切换框架:https://github.com/getActivity/MultiLanguages @@ -91,26 +94,24 @@ dependencies { implementation 'androidx.core:core-ktx:1.8.0' implementation 'com.github.deano2390:MaterialShowcaseView:1.3.4' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'com.github.yalantis:ucrop:2.2.6-native' + implementation 'com.github.yalantis:ucrop:2.2.8-native' implementation 'com.kongzue.stacklabel:stacklabelview:1.1.9' implementation 'io.github.Rosemoe.sora-editor:editor:0.16.5' implementation project(path: ':assistantCoreLibrary') - implementation project(path: ':turretsDragView') implementation project(path: ':dialog') implementation 'com.afollestad.material-dialogs:bottomsheets:3.3.0' implementation 'com.afollestad.material-dialogs:input:3.3.0' - implementation 'com.github.bumptech.glide:glide:4.11.0' implementation 'jp.wasabeef:glide-transformations:4.3.0' implementation 'com.github.florent37:glidepalette:2.1.2' implementation 'com.github.QuadFlask:colorpicker:0.0.15' implementation 'cat.ereza:customactivityoncrash:2.3.0' implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0" - implementation 'androidx.appcompat:appcompat:1.4.0' - implementation 'com.google.android.material:material:1.6.1' - implementation 'androidx.constraintlayout:constraintlayout:2.0.4' - implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5' - implementation 'androidx.navigation:navigation-ui-ktx:2.3.5' + implementation 'androidx.appcompat:appcompat:1.5.0' + implementation 'com.google.android.material:material:1.7.0-beta01' + implementation 'androidx.constraintlayout:constraintlayout:2.1.4' + implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" + implementation "androidx.navigation:navigation-ui-ktx:$nav_version" implementation 'androidx.preference:preference-ktx:1.2.0' testImplementation 'junit:junit:4.13.2' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b40c725..e303cdd 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -24,6 +24,9 @@ android:supportsRtl="true" android:theme="@style/Theme.rust.Concept" android:usesCleartextTraffic="true"> + @@ -262,9 +265,9 @@ + android:screenOrientation="portrait" + android:windowSoftInputMode="adjustResize" /> diff --git a/app/src/main/java/com/coldmint/rust/pro/AboutActivity.kt b/app/src/main/java/com/coldmint/rust/pro/AboutActivity.kt index 47fd0c4..35d936b 100644 --- a/app/src/main/java/com/coldmint/rust/pro/AboutActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/AboutActivity.kt @@ -4,10 +4,7 @@ import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.text.Html -import android.view.LayoutInflater -import android.view.Menu -import android.view.MenuItem -import android.view.View +import android.view.* import com.coldmint.rust.core.web.ServerConfiguration import com.coldmint.rust.pro.base.BaseActivity import com.coldmint.rust.pro.databinding.ActivityAboutBinding @@ -96,7 +93,7 @@ class AboutActivity : BaseActivity() { } - override fun onCreateOptionsMenu(menu: Menu?): Boolean { + override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_about, menu) return true } diff --git a/app/src/main/java/com/coldmint/rust/pro/ActivateActivity.kt b/app/src/main/java/com/coldmint/rust/pro/ActivateActivity.kt index 2ddac64..797e838 100644 --- a/app/src/main/java/com/coldmint/rust/pro/ActivateActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/ActivateActivity.kt @@ -86,7 +86,7 @@ class ActivateActivity : BaseActivity() { * @param menu Menu * @return Boolean */ - override fun onCreateOptionsMenu(menu: Menu?): Boolean { + override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_pay, menu) return true diff --git a/app/src/main/java/com/coldmint/rust/pro/BrowserActivity.kt b/app/src/main/java/com/coldmint/rust/pro/BrowserActivity.kt index 6de6881..b41a8a7 100644 --- a/app/src/main/java/com/coldmint/rust/pro/BrowserActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/BrowserActivity.kt @@ -63,10 +63,10 @@ class BrowserActivity : BaseActivity() { return super.onOptionsItemSelected(item) } - override fun onCreateOptionsMenu(menu: Menu?): Boolean { + override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_browser, menu) - return super.onCreateOptionsMenu(menu) + return true } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { diff --git a/app/src/main/java/com/coldmint/rust/pro/CustomizeEditTextActivity.kt b/app/src/main/java/com/coldmint/rust/pro/CustomizeEditTextActivity.kt new file mode 100644 index 0000000..026fdcb --- /dev/null +++ b/app/src/main/java/com/coldmint/rust/pro/CustomizeEditTextActivity.kt @@ -0,0 +1,403 @@ +package com.coldmint.rust.pro + +import android.content.Intent +import android.graphics.BitmapFactory +import android.graphics.Color +import android.net.Uri +import android.os.Bundle +import android.view.KeyEvent +import android.view.LayoutInflater +import android.view.MenuItem +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.isVisible +import androidx.palette.graphics.Palette +import com.afollestad.materialdialogs.utils.MDUtil.getWidthAndHeight +import com.bumptech.glide.Glide +import com.bumptech.glide.request.RequestOptions.bitmapTransform +import com.coldmint.dialog.CoreDialog +import com.coldmint.rust.core.tool.DebugHelper +import com.coldmint.rust.core.tool.FileOperator +import com.coldmint.rust.pro.base.BaseActivity +import com.coldmint.rust.pro.databinding.ActivityCustomizeEditTextBinding +import com.coldmint.rust.pro.tool.AppSettings +import com.coldmint.rust.pro.tool.GlobalMethod +import com.google.android.material.snackbar.Snackbar +import com.google.android.material.textfield.TextInputEditText +import com.yalantis.ucrop.UCrop +import jp.wasabeef.glide.transformations.BlurTransformation +import java.io.File + + +class CustomizeEditTextActivity : BaseActivity() { + + private lateinit var selectFile: ActivityResultLauncher + private var clipPath: String? = null + + override fun whenCreateActivity(savedInstanceState: Bundle?, canUseView: Boolean) { + setReturnButton() + title = getString(R.string.customize_edit_text) + readData() + loadAction() + + val enable = AppSettings.getValue( + AppSettings.Setting.CodeEditBackGroundEnable, + false + ) + if (enable) { + loadImage( + AppSettings.getValue(AppSettings.Setting.CodeEditBackGroundPath, ""), + AppSettings.getValue(AppSettings.Setting.BlurTransformationValue, 1) + ) + } + + selectFile = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { + val key = "选择文件" + if (it.resultCode == RESULT_OK) { + //选择了文件 + val intent = it.data + val path = intent?.getStringExtra("File") ?: "" + val file = File(path) + if (file.exists()) { + val type = FileOperator.getFileType(file) + if (type == "png" || type == "jpg") { + val bitmap = BitmapFactory.decodeFile(path) + val width = windowManager.getWidthAndHeight().first + val height = windowManager.getWidthAndHeight().second + val imageWidth = bitmap.width + val imageHeight = bitmap.height + if (width % imageWidth == 0 && height % imageHeight == 0) { + //可以被整除 + DebugHelper.printLog(key, "图像无需裁剪。") + } else { + clipPath = AppSettings.createNewCodeEditBackGroundFile() + val newFile = File(clipPath) + DebugHelper.printLog(key, "前往裁剪 输出路径:${newFile.absolutePath}") + UCrop.of( + Uri.parse(file.toURI().toString()), + Uri.parse(newFile.toURI().toString()) + ) + .withAspectRatio(width.toFloat(), height.toFloat()) + .start(this); + } + } else { + DebugHelper.printLog(key, "文件格式不合法", isError = true) + Snackbar.make( + viewBinding.button, + R.string.bad_file_type, + Snackbar.LENGTH_SHORT + ).show() + } + } else { + DebugHelper.printLog(key, "文件不存在", isError = true) + } + } + } + } + + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) { +// val resultUri = UCrop.getOutput(data!!) + if (clipPath != null) { + loadImage(clipPath!!) + } else { + Snackbar.make( + viewBinding.button, + R.string.bad_file_type, + Snackbar.LENGTH_SHORT + ).show() + } + } else if (resultCode == UCrop.RESULT_ERROR) { +// val cropError = UCrop.getError(data!!) + Snackbar.make( + viewBinding.button, + R.string.bad_file_type, + Snackbar.LENGTH_SHORT + ).show() + } + } + + /** + * 加载图像 + * @param filePath String + */ + fun loadImage(filePath: String, value: Int = 1) { + DebugHelper.printLog("加载文件", "加载了文件${filePath} 模糊度${value}", isError = true) + Glide.with(this).load(filePath).apply( + bitmapTransform( + BlurTransformation(value) + ) + ).into(viewBinding.imageView) + viewBinding.filePathInputEdit.setText(filePath) + viewBinding.imageCardView.isVisible = true + viewBinding.dimCardView.isVisible = true + viewBinding.autoGenerateColorSchemeButton.isVisible = true + viewBinding.slide.value = value.toFloat() + viewBinding.filePathInputLayout.endIconDrawable = + getDrawable(R.drawable.ic_outline_clear_24) + } + + /** + * 读取数据 + */ + fun readData() { + //读取内容 + setTextAndColor( + viewBinding.textColorEditText, + AppSettings.getValue(AppSettings.Setting.TextColor, "") + ) + setTextAndColor( + viewBinding.annotationColorEditText, + AppSettings.getValue(AppSettings.Setting.AnnotationColor, "") + ) + setTextAndColor( + viewBinding.keywordColorEditText, + AppSettings.getValue(AppSettings.Setting.KeywordColor, "") + ) + setTextAndColor( + viewBinding.sectionColorEditText, + AppSettings.getValue(AppSettings.Setting.SectionColor, "") + ) + } + + + /** + * 加载事件 + */ + fun loadAction() { + viewBinding.autoGenerateColorSchemeButton.setOnClickListener { + val bitmap = BitmapFactory.decodeFile(viewBinding.filePathInputEdit.text.toString()) + Palette.from(bitmap).generate { + //充满活力的 + setTextAndColor( + viewBinding.sectionColorEditText, + GlobalMethod.colorToString(it?.getVibrantColor(Color.RED) ?: Color.RED) + ) + + setTextAndColor( + viewBinding.annotationColorEditText, + GlobalMethod.colorToString(it?.getLightVibrantColor(Color.RED) ?: Color.RED) + ) + setTextAndColor( + viewBinding.textColorEditText, + GlobalMethod.colorToString(it?.getDarkMutedColor(Color.RED) ?: Color.RED) + ) + setTextAndColor( + viewBinding.keywordColorEditText, + GlobalMethod.colorToString(it?.getMutedColor(Color.RED) ?: Color.RED) + ) + + } + } + viewBinding.filePathInputLayout.setEndIconOnClickListener { + val oldFileData = viewBinding.filePathInputEdit.text.toString() + if (oldFileData.isBlank()) { + val intent = Intent(this, FileManagerActivity::class.java) + val bundle = Bundle() + bundle.putString("type", "selectFile") + intent.putExtra("data", bundle) + selectFile.launch(intent) + } else { + viewBinding.filePathInputEdit.setText("") + viewBinding.filePathInputLayout.endIconDrawable = getDrawable(R.drawable.file) + viewBinding.imageCardView.isVisible = false + viewBinding.dimCardView.isVisible = false + viewBinding.autoGenerateColorSchemeButton.isVisible = false + } + } + + viewBinding.slide.addOnChangeListener { slider, value, fromUser -> + val filePath = viewBinding.filePathInputEdit.text.toString() + Glide.with(this).load(filePath).apply( + bitmapTransform( + BlurTransformation(value.toInt()) + ) + ).into(viewBinding.imageView) + } + + viewBinding.keywordColorEditLayout.setEndIconOnClickListener { + GlobalMethod.showColorPickerDialog(this, true) { + setTextAndColor(viewBinding.keywordColorEditText, it) + } + } + + + viewBinding.textColorEditLayout.setEndIconOnClickListener { + GlobalMethod.showColorPickerDialog(this, true) { + setTextAndColor(viewBinding.textColorEditText, it) + } + } + + viewBinding.sectionColorEditLayout.setEndIconOnClickListener { + GlobalMethod.showColorPickerDialog(this, true) { + setTextAndColor(viewBinding.sectionColorEditText, it) + } + } + + + viewBinding.annotationColorEditLayout.setEndIconOnClickListener { + GlobalMethod.showColorPickerDialog(this, true) { + setTextAndColor(viewBinding.annotationColorEditText, it) + } + } + + viewBinding.resetButton.setOnClickListener { + setTextAndColor(viewBinding.keywordColorEditText, "#FF0031C2") + setTextAndColor(viewBinding.sectionColorEditText, "#FFE10000") + setTextAndColor(viewBinding.textColorEditText, "#FF000000") + setTextAndColor(viewBinding.annotationColorEditText, "#FF00AF2C") + } + + viewBinding.button.setOnClickListener { + saveData() + finish() + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + showSaveDialogIfNeed() + } + return super.onOptionsItemSelected(item) + } + + fun showSaveDialogIfNeed() { + val needSave = needSave() + if (needSave) { + CoreDialog(this).setTitle(R.string.customize_edit_text) + .setMessage(R.string.save_settings).setPositiveButton(R.string.dialog_ok) { + saveData() + finish() + }.setNegativeButton(R.string.dialog_cancel) { + finish() + }.setCancelable(false).show() + } else { + finish() + } + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) { + showSaveDialogIfNeed() + return true + } + return super.onKeyDown(keyCode, event) + } + + /** + * 是否需要保存 + * @return Boolean + */ + fun needSave(): Boolean { + val textColor = AppSettings.getValue( + AppSettings.Setting.TextColor, + "" + ) + if (viewBinding.textColorEditText.text.toString() != textColor) { + return true + } + + val annotationColor = AppSettings.getValue( + AppSettings.Setting.AnnotationColor, + "" + ) + if (viewBinding.annotationColorEditText.text.toString() != annotationColor) { + return true + } + val keywordColor = AppSettings.getValue( + AppSettings.Setting.KeywordColor, + "" + ) + if (viewBinding.keywordColorEditText.text.toString() != keywordColor) { + return true + } + + val sectionColor = AppSettings.getValue( + AppSettings.Setting.SectionColor, + "" + ) + if (viewBinding.sectionColorEditText.text.toString() != sectionColor) { + return true + } + val blurTransformationValue = AppSettings.getValue( + AppSettings.Setting.BlurTransformationValue, + 1 + ) + if (viewBinding.slide.value.toInt() != blurTransformationValue) { + return true + } + val codeEditBackGroundPath = + AppSettings.getValue(AppSettings.Setting.CodeEditBackGroundPath, "") + if (viewBinding.filePathInputEdit.text.toString() != codeEditBackGroundPath) { + return true + } + return false + } + + /** + * 保存用户数据 + */ + fun saveData() { + AppSettings.setValue( + AppSettings.Setting.TextColor, + viewBinding.textColorEditText.text.toString() + ) + AppSettings.setValue( + AppSettings.Setting.AnnotationColor, + viewBinding.annotationColorEditText.text.toString() + ) + AppSettings.setValue( + AppSettings.Setting.KeywordColor, + viewBinding.keywordColorEditText.text.toString() + ) + AppSettings.setValue( + AppSettings.Setting.SectionColor, + viewBinding.sectionColorEditText.text.toString() + ) + AppSettings.setValue( + AppSettings.Setting.BlurTransformationValue, + viewBinding.slide.value.toInt() + ) + val filePath = viewBinding.filePathInputEdit.text.toString() + val enable = if (filePath.isNullOrBlank()) { + false + } else { + val file = File(filePath) + if (file.exists()) { + val newPath = AppSettings.createNewCodeEditBackGroundFile() + val newFile = File(newPath) + FileOperator.copyFile(file, newFile) + AppSettings.setValue(AppSettings.Setting.CodeEditBackGroundPath, newPath) + true + } else { + false + } + } + //如果输入了文件路径那么启用 + AppSettings.setValue( + AppSettings.Setting.CodeEditBackGroundEnable, + enable + ) + + } + + /** + * 设置文本和颜色 + * @param textInputEditText TextInputEditText + */ + fun setTextAndColor(textInputEditText: TextInputEditText, color: String) { + try { + textInputEditText.setText(color) + textInputEditText.setTextColor(Color.parseColor(color)) + } catch (e: Exception) { + e.printStackTrace() + } + } + + override fun getViewBindingObject(layoutInflater: LayoutInflater): ActivityCustomizeEditTextBinding { + return ActivityCustomizeEditTextBinding.inflate(layoutInflater) + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/EditActivity.kt b/app/src/main/java/com/coldmint/rust/pro/EditActivity.kt index 3c3e392..6716ffc 100644 --- a/app/src/main/java/com/coldmint/rust/pro/EditActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/EditActivity.kt @@ -1,8 +1,10 @@ package com.coldmint.rust.pro import android.content.Intent +import android.graphics.Bitmap import android.graphics.Color import android.graphics.Typeface +import android.graphics.drawable.Drawable import android.os.Bundle import android.os.Handler import android.os.Looper @@ -25,6 +27,11 @@ import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.afollestad.materialdialogs.list.ItemListener import com.afollestad.materialdialogs.list.listItems +import com.bumptech.glide.Glide +import com.bumptech.glide.request.RequestOptions +import com.bumptech.glide.request.target.CustomTarget +import com.bumptech.glide.request.target.Target +import com.bumptech.glide.request.transition.Transition import com.coldmint.rust.core.AnalysisResult import com.coldmint.rust.core.CodeCompiler2 import com.coldmint.rust.core.ModClass @@ -62,6 +69,7 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import io.github.rosemoe.sora.lang.completion.CompletionItem import io.github.rosemoe.sora.widget.schemes.EditorColorScheme +import jp.wasabeef.glide.transformations.BlurTransformation import java.io.File import java.util.* import kotlin.collections.ArrayList @@ -211,10 +219,10 @@ class EditActivity : BaseActivity() { // if (temCodeInfo == null) { // // } else { -// val completionItemConverter = CompletionItemConverter.instance -// completionItemConverter.init(this) +// val CompletionItemConverter = CompletionItemConverter.instance +// CompletionItemConverter.init(this) // list.add( -// completionItemConverter.codeInfoToCompletionItem( +// CompletionItemConverter.codeInfoToCompletionItem( // temCodeInfo // ) // ) @@ -482,6 +490,7 @@ class EditActivity : BaseActivity() { initStartView() initEndView() showRenewalTip() + loadCustomStyle() } else { val thisIntent = intent val bundle = thisIntent.getBundleExtra("data") @@ -958,29 +967,9 @@ class EditActivity : BaseActivity() { codeToolAdapter.setItemEvent { i, codeToolItemBinding, viewHolder, item -> codeToolItemBinding.root.setOnClickListener { if (item == getString(R.string.symbol11)) { - ColorPickerDialogBuilder - .with(this@EditActivity) - .setTitle(getString(R.string.choose_color)) - .initialColor(Color.WHITE) - .wheelType(ColorPickerView.WHEEL_TYPE.FLOWER) - .density(12) - .setOnColorSelectedListener { - //toast("onColorSelected: 0x" + Integer.toHexString(selectedColor)); - } - .setPositiveButton(R.string.dialog_ok) { dialog, selectedColor, allColors -> - val r = Color.red(selectedColor) - val g = Color.green(selectedColor) - val b = Color.blue(selectedColor) - val builder = StringBuilder() - builder.append('#') - builder.append(viewModel.convertDigital(r)) - builder.append(viewModel.convertDigital(g)) - builder.append(viewModel.convertDigital(b)) - viewBinding.codeEditor.insertText(builder.toString(), builder.length) - } - .setNegativeButton(R.string.dialog_cancel) { dialog, which -> } - .build() - .show() + GlobalMethod.showColorPickerDialog(this) { + viewBinding.codeEditor.insertText(it, it.length) + } } else if (item == getString(R.string.code_table)) { viewModel.needCheckAutoSave = false startActivity(Intent(this@EditActivity, CodeTableActivity::class.java)) @@ -1065,11 +1054,11 @@ class EditActivity : BaseActivity() { // .findCodeByKeyFromSection(lineData, trueSection, number) // } // if (codeInfoList != null && codeInfoList.isNotEmpty()) { -// val completionItemConverter = +// val CompletionItemConverter = // CompletionItemConverter.instance.init(this) // codeInfoList.forEach { // list.add( -// completionItemConverter.codeInfoToCompletionItem( +// CompletionItemConverter.codeInfoToCompletionItem( // it // ) // ) @@ -1122,9 +1111,9 @@ class EditActivity : BaseActivity() { "JetBrainsMono-Regular.ttf" ) } - val language = - AppSettings.getValue(AppSettings.Setting.AppLanguage, Locale.getDefault().language) - rustLanguage = RustLanguage(this) +// val language = +// AppSettings.getValue(AppSettings.Setting.AppLanguage, Locale.getDefault().language) + rustLanguage = RustLanguage() rustLanguage.setCodeDataBase(CodeDataBase.getInstance(this)) rustLanguage.setFileDataBase( FileDataBase.getInstance( @@ -1134,25 +1123,53 @@ class EditActivity : BaseActivity() { ) // rustLanguage.setAnalyzerEnglishMode(viewModel.englishModeLiveData) rustLanguage.setCodeEditor(viewBinding.codeEditor) - val night = AppSettings.getValue(AppSettings.Setting.NightMode, false) + viewBinding.codeEditor.setAutoCompletionItemAdapter(RustCompletionAdapter()) + viewBinding.codeEditor.isVerticalScrollBarEnabled = false + val path = viewModel.modClass?.modFile?.absolutePath ?: "" + CompletionItemConverter.configurationFileConversion( + path, + "ROOT", + path + ) + viewBinding.codeEditor.setEditorLanguage(rustLanguage) + } + + + /** + * 加载自动 + */ + fun loadCustomStyle() { + val key = "加载自定义编辑框样式" val editorColorScheme = EditorColorScheme() - val backgroundColor = GlobalMethod.getThemeColor(this, android.R.attr.windowBackground) + val codeEditBackGroundEnable = + AppSettings.getValue(AppSettings.Setting.CodeEditBackGroundEnable, false) + val backgroundColor = + if (codeEditBackGroundEnable) { + DebugHelper.printLog(key, "启用背景图像,设置背景为透明。") + Color.TRANSPARENT + } else { + DebugHelper.printLog(key, "未启用背景图像,设置背景为窗口颜色。") + GlobalMethod.getThemeColor(this, android.R.attr.windowBackground) + } //代码(可识别的关键字) editorColorScheme.setColor( EditorColorScheme.KEYWORD, - GlobalMethod.getThemeColor(this, android.R.attr.colorSecondary) + Color.parseColor(AppSettings.getValue(AppSettings.Setting.KeywordColor, "")) ) //默认文本 - editorColorScheme.setColor(EditorColorScheme.TEXT_NORMAL, Color.rgb(169, 183, 198)) + editorColorScheme.setColor( + EditorColorScheme.TEXT_NORMAL, + Color.parseColor(AppSettings.getValue(AppSettings.Setting.TextColor, "")) + ) //注释 editorColorScheme.setColor( EditorColorScheme.COMMENT, - GlobalMethod.getThemeColor(this, android.R.attr.textColorTertiary) + Color.parseColor(AppSettings.getValue(AppSettings.Setting.AnnotationColor, "")) ) //节 editorColorScheme.setColor( EditorColorScheme.FUNCTION_NAME, - GlobalMethod.getColorPrimary(this) + Color.parseColor(AppSettings.getValue(AppSettings.Setting.SectionColor, "")) ) editorColorScheme.setColor( EditorColorScheme.WHOLE_BACKGROUND, @@ -1162,17 +1179,35 @@ class EditActivity : BaseActivity() { EditorColorScheme.LINE_NUMBER_BACKGROUND, backgroundColor ) - viewBinding.codeEditor.colorScheme = editorColorScheme - viewBinding.codeEditor.setAutoCompletionItemAdapter(RustCompletionAdapter()) - viewBinding.codeEditor.isVerticalScrollBarEnabled = false - val path = viewModel.modClass?.modFile?.absolutePath ?: "" -// rustLanguage.autoCompleteProvider.setConfigurationFileConversion( -// path, -// "ROOT", -// path -// ) - viewBinding.codeEditor.setEditorLanguage(rustLanguage) + editorColorScheme.setColor(EditorColorScheme.COMPLETION_WND_BACKGROUND, backgroundColor) + if (codeEditBackGroundEnable) { + //设置自定义背景图 + Glide.with(this) + .load(AppSettings.getValue(AppSettings.Setting.CodeEditBackGroundPath, "")).apply( + RequestOptions.bitmapTransform( + BlurTransformation( + AppSettings.getValue( + AppSettings.Setting.BlurTransformationValue, + 1 + ) + ) + ) + ).into(object : CustomTarget() { + override fun onResourceReady( + resource: Drawable, + transition: Transition? + ) { + window.setBackgroundDrawable(resource) + } + override fun onLoadCleared(placeholder: Drawable?) { + + } + + }) + + } + viewBinding.codeEditor.colorScheme = editorColorScheme } override fun onCreateOptionsMenu(menu: Menu): Boolean { diff --git a/app/src/main/java/com/coldmint/rust/pro/EditModInfoActivity.kt b/app/src/main/java/com/coldmint/rust/pro/EditModInfoActivity.kt index 98f503e..c89ac62 100644 --- a/app/src/main/java/com/coldmint/rust/pro/EditModInfoActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/EditModInfoActivity.kt @@ -6,6 +6,7 @@ import com.coldmint.rust.core.ModClass import android.annotation.SuppressLint import android.os.Bundle import android.content.Intent +import android.content.res.ColorStateList import com.bumptech.glide.Glide import android.graphics.BitmapFactory import com.yalantis.ucrop.UCrop @@ -92,6 +93,19 @@ class EditModInfoActivity : BaseActivity() { } } + /** + * 加载默认图像 + */ + fun loadDefaultImage() { + val drawable = getDrawable(R.drawable.image) + viewBinding.iconView.setImageDrawable( + GlobalMethod.tintDrawable( + drawable, + ColorStateList.valueOf(GlobalMethod.getColorPrimary(this)) + ) + ) + } + fun initData() { val name = mModClass.readValueFromInfoSection("title", "mod") @@ -103,8 +117,11 @@ class EditModInfoActivity : BaseActivity() { viewBinding.modDescribeEdit.setText(description) } val bitmap = mModClass.modIcon - if (bitmap != null) { - Glide.with(this@EditModInfoActivity).load(bitmap).apply(GlobalMethod.getRequestOptions()).into(viewBinding.iconView) + if (bitmap == null) { + loadDefaultImage() + } else { + Glide.with(this@EditModInfoActivity).load(bitmap) + .apply(GlobalMethod.getRequestOptions()).into(viewBinding.iconView) mNeedIcon = true } val musicSourceFolder = mModClass.readValueFromInfoSection("sourceFolder", "music") @@ -269,7 +286,7 @@ class EditModInfoActivity : BaseActivity() { iconFile.delete() mNeedIcon = false } - viewBinding.iconView.setImageResource(R.drawable.image) + loadDefaultImage() } false } @@ -356,7 +373,8 @@ class EditModInfoActivity : BaseActivity() { val bitmap = BitmapFactory.decodeFile(newIconFile.absolutePath) if (bitmap.height == bitmap.width) { if (FileOperator.copyFile(newIconFile, iconFile)) { - Glide.with(this@EditModInfoActivity).load(newIconFile).apply(GlobalMethod.getRequestOptions()) + Glide.with(this@EditModInfoActivity).load(newIconFile) + .apply(GlobalMethod.getRequestOptions()) .into(viewBinding.iconView) mNeedIcon = true } @@ -369,7 +387,8 @@ class EditModInfoActivity : BaseActivity() { } } else if (requestCode == UCrop.REQUEST_CROP) { val resultUri = UCrop.getOutput(data) - Glide.with(this@EditModInfoActivity).load(resultUri).apply(GlobalMethod.getRequestOptions()).into(viewBinding.iconView) + Glide.with(this@EditModInfoActivity).load(resultUri) + .apply(GlobalMethod.getRequestOptions()).into(viewBinding.iconView) mNeedIcon = true } } diff --git a/app/src/main/java/com/coldmint/rust/pro/FileManagerActivity.kt b/app/src/main/java/com/coldmint/rust/pro/FileManagerActivity.kt index d874fff..6d569a5 100644 --- a/app/src/main/java/com/coldmint/rust/pro/FileManagerActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/FileManagerActivity.kt @@ -15,6 +15,8 @@ import android.net.Uri import android.os.* import android.view.* import android.widget.* +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider import com.afollestad.materialdialogs.MaterialDialog @@ -23,8 +25,11 @@ import com.afollestad.materialdialogs.actions.setActionButtonEnabled import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.afollestad.materialdialogs.list.listItems +import com.afollestad.materialdialogs.utils.MDUtil.isLandscape +import com.bumptech.glide.Glide import com.coldmint.dialog.CoreDialog import com.coldmint.dialog.InputDialog +import com.coldmint.rust.core.tool.DebugHelper import com.coldmint.rust.core.tool.FileOperator import com.coldmint.rust.core.tool.LineParser import com.coldmint.rust.pro.adapters.FileAdapter @@ -38,173 +43,17 @@ import com.google.android.material.chip.Chip import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.SnackbarContentLayout import me.zhanghai.android.fastscroll.FastScrollerBuilder +import java.io.BufferedReader import java.io.File +import java.io.InputStreamReader import java.lang.Exception import java.util.* import java.util.concurrent.Executors import kotlin.collections.ArrayList class FileManagerActivity : BaseActivity() { - // private var directs = Environment.getExternalStorageDirectory() -// private var mRoot = directs -// var filePath = "" -// - // val executorService = Executors.newSingleThreadExecutor() -// -// //type可为默认default,选择文件夹selectDirectents,选择文件selectFile -// var mStartType: String? = "default" -// private var mFileAdapter: FileAdapter? = null -// private var mProcessFiles = false -// private var additionalData: String? = null -// private fun initView() { -// title = getString(R.string.file_manager) -// setReturnButton() -// viewBinding.fileList.layoutManager = LinearLayoutManager(this@FileManagerActivity) -// val intent = intent -// val bundle = intent.getBundleExtra("data") -// if (bundle == null) { -// showError("无效的请求。") -// finish() -// } else { -// mStartType = bundle.getString("type") -// when (mStartType) { -// "default" -> { -// } -// "selectDirectents" -> { -// setTitle(R.string.select_directents) -// viewBinding.fab.setIconResource(R.drawable.complete) -// viewBinding.fab.postDelayed({ -// viewBinding.fab.text = getString(R.string.select_directents) -// viewBinding.fab.extend() -// }, 300) -// } -// "exportFile" -> { -// setTitle(R.string.export_file) -// val additional = bundle.getString("additionalData") -// if (additional == null) { -// showError("请输入 additionalData") -// return -// } else { -// viewBinding.fab.setIconResource(R.drawable.complete) -// viewBinding.fab.postDelayed({ -// viewBinding.fab.text = getString(R.string.export_this) -// viewBinding.fab.extend() -// }, 300) -// } -// } -// "selectFile" -> { -// setTitle(R.string.select_file) -// viewBinding.fab.setIconResource(R.drawable.complete) -// viewBinding.fab.hide() -// } -// else -> { -// Toast.makeText(this, "意外的请求", Toast.LENGTH_SHORT).show() -// finish() -// } -// } -// if (bundle.containsKey("path")) { -// directs = File(bundle.getString("path")) -// } -// if (bundle.containsKey("rootpath")) { -// mRoot = File(bundle.getString("rootpath")) -// } -// if (bundle.containsKey("additionalData")) { -// additionalData = bundle.getString("additionalData") -// } -// } -// loadFiles(directs) -// } -// -// private fun tryOpenFile(file: File?) { -// if (file == null) { -// returnDirects() -// } else { -// if (file.isDirectory) { -// loadFiles(file) -// } else { -// when (mStartType) { -// "default" -> { -// when (FileOperator.getFileType(file)) { -// "ini", "txt", "template" -> { -// 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) -// } -// "json" -> { -// val openList = listOf( -// getString(R.string.edit_template), getString( -// R.string.open_action1 -// ) -// ) -// MaterialDialog(this).title(R.string.open_type) -// .listItems(items = openList) { dialog, offset, text -> -// when (text) { -// getString(R.string.edit_template) -> { -// editTemplate(file) -// } -// getString(R.string.open_action1) -> { -// editText(file) -// } -// } -// }.show() -// -// } -// "zip", "rwmod", "rar" -> { -// Toast.makeText( -// this@FileManagerActivity, -// "点击了压缩文件。", -// Toast.LENGTH_SHORT -// ).show() -// FileOperator.openFile(this@FileManagerActivity, file) -// } -// else -> { -// val ints = intArrayOf( -// R.string.open_action1, -// R.string.open_action4 -// ) -// val items = FileAdapter.conversionSymbol( -// this@FileManagerActivity, -// ints -// ) -// -// MaterialAlertDialogBuilder(this).setItems( -// items -// ) { dialog, which -> -// when (ints[which]) { -// R.string.open_action1 -> { -// editText(file) -// } -// R.string.open_action4 -> FileOperator.openFile( -// this@FileManagerActivity, -// file -// ) -// } -// }.show() -// } -// } -// viewBinding.fab.show() -// filePath = file.absolutePath -// } -// "selectFile" -> { -// viewBinding.fab.show() -// viewBinding.fab.postDelayed({ -// filePath = file.absolutePath -// viewBinding.fab.text = -// String.format(getString(R.string.select_file_ok), file.name) -// viewBinding.fab.extend() -// }, 300) -// -// } -// } -// } -// } -// } -// + // // /** // * 编辑模板 @@ -238,219 +87,7 @@ class FileManagerActivity : BaseActivity() { // intent.putExtra("data", bundle) // this@FileManagerActivity.startActivity(intent) // } -// -// //加载文件 -// fun loadFiles(file: File) { -// executorService.submit { -// if (!file.exists()) { -// runOnUiThread { -// viewBinding.fileList.isVisible = false -// viewBinding.progressBar.isVisible = false -// viewBinding.fileError.isVisible = true -// viewBinding.fileError.setText(R.string.unable_to_open_this_directory) -// viewBinding.fab.hide() -// } -// return@submit -// } -// -// if (file.isDirectory) { -// val files = file.listFiles() -// directs = file -// val fileArrayList: ArrayList = ArrayList(listOf(*files)) -// if (file.absolutePath != mRoot.absolutePath) { -// fileArrayList.add(0, null) -// } -// val finalFileAdapter: FileAdapter = -// if (mFileAdapter == null) { -// mFileAdapter = FileAdapter(this@FileManagerActivity, fileArrayList) -// mFileAdapter!! -// } else { -// mFileAdapter?.setNewDataList(fileArrayList) -// mFileAdapter!! -// } -// finalFileAdapter.setSortType(FileAdapter.SortType.FileName) -// finalFileAdapter.setItemEvent { i, fileItemBinding, viewHolder, itemFile -> -// fileItemBinding.root.setOnClickListener { -// tryOpenFile(itemFile) -// } -// fileItemBinding.more.setOnClickListener { -// if (itemFile == null) { -// return@setOnClickListener -// } -// val popupMenu = -// PopupMenu(this@FileManagerActivity, fileItemBinding.more) -// val cutBoardMenu = -// popupMenu.menu.addSubMenu(R.string.cut_board_operation) -// val fileMenu = popupMenu.menu.addSubMenu(R.string.file_operation) -// val bookmarksMenu = -// popupMenu.menu.addSubMenu(R.string.bookmarks_operation) -// cutBoardMenu.add(R.string.copy_file_name) -// cutBoardMenu.add(R.string.copy_file_path) -// fileMenu.add(R.string.copy) -// fileMenu.add(R.string.cut_off) -// fileMenu.add(R.string.mod_action9) -// fileMenu.add(R.string.delete_title) -// if (bookmarkManager.contains(file)) { -// bookmarksMenu.add(R.string.remove_bookmark) -// } else { -// bookmarksMenu.add(R.string.add_bookmark) -// } -// bookmarksMenu.add(R.string.bookmark_manager) -// addJumpBookMenu(bookmarksMenu) -// popupMenu.setOnMenuItemClickListener { item -> -// val title = item.title -// if (title == getText(R.string.copy_file_name)) { -// val name = itemFile.name -// GlobalMethod.copyText( -// this@FileManagerActivity, -// name, -// viewBinding.fab -// ) -// } else if (title == getText(R.string.copy_file_path)) { -// val path = itemFile.absolutePath -// GlobalMethod.copyText( -// this@FileManagerActivity, -// path, -// viewBinding.fab -// ) -// } else if (title == getText(R.string.delete_title)) { -// executorService.submit { -// FileOperator.delete_files(itemFile) -// runOnUiThread { -// loadFiles(directs) -// } -// } -// } else if (title == getText(R.string.copy)) { -// finalFileAdapter.setSelectPath(itemFile.absolutePath, true) -// } else if (title == getText(R.string.cut_off)) { -// finalFileAdapter.setSelectPath(itemFile.absolutePath, false) -// } else if (title == getText(R.string.mod_action9)) { -// val oldName = itemFile.name -// MaterialDialog(this@FileManagerActivity).show { -// title(R.string.mod_action9) -// input( -// maxLength = 255, -// waitForPositiveButton = false, prefill = oldName -// ) { dialog, text -> -// if (text.length in 1..255) { -// dialog.setActionButtonEnabled( -// WhichButton.POSITIVE, -// true -// ) -// } -// }.positiveButton(R.string.dialog_ok, null) { dialog -> -// val newName = dialog.getInputField().text.toString() -// if (!newName.isEmpty() || newName != oldName) { -// val reNameFile = File("$directs/$newName") -// itemFile.renameTo(reNameFile) -// loadFiles(directs) -// } -// }.negativeButton(R.string.dialog_close) -// } -// } else if (title == getString(R.string.remove_bookmark)) { -// val removeBookmark = -// bookmarkManager.removeBookmark(itemFile.absolutePath) -// if (removeBookmark) { -// Snackbar.make( -// viewBinding.fab, -// R.string.remove_bookmark_success, -// Snackbar.LENGTH_SHORT -// ).setAction(R.string.symbol10) { -// bookmarkManager.addBookmark( -// itemFile.absolutePath, -// FileOperator.getPrefixName(file) -// ) -// } -// .show() -// } else { -// Snackbar.make( -// viewBinding.fab, -// R.string.remove_bookmark_fail, -// Snackbar.LENGTH_SHORT -// ).show() -// } -// } else if (title == getString(R.string.add_bookmark)) { -// val addBookmark = bookmarkManager.addBookmark( -// itemFile.absolutePath, -// FileOperator.getPrefixName(file) -// ) -// if (addBookmark) { -// 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() -// } -// } else if (title == getString(R.string.bookmark_manager)) { -// bookmarkManager.save() -// startActivity( -// Intent( -// this@FileManagerActivity, -// BookmarkManagerActivity::class.java -// ) -// ) -// } else { -// loadBook(title) -// } -// false -// } -// popupMenu.show() -// } -// } -// runOnUiThread { -// viewBinding.fileList.adapter = finalFileAdapter -// viewBinding.fileList.isVisible = true -// viewBinding.fileError.isVisible = false -// viewBinding.progressBar.isVisible = false -// } -// } -// } -// } -// -// - // /** -// * 点击书签项目 -// */ -// fun loadBook(menuTitle: CharSequence) { -// if (bookmarkMap.containsKey(menuTitle)) { -// val path = bookmarkMap[menuTitle] -// if (path != null) { -// val rootPath = viewModel.getRootPath() -// if (path.startsWith(rootPath)) { -// val newFile = File(path) -// if (newFile.exists()) { -// if (newFile.isDirectory) { -// viewModel.loadFiles(newFile.absolutePath) -// } else { -//// tryOpenFile(newFile) -// } -// } else { -// Snackbar.make( -// viewBinding.fab, -// R.string.bookmark_jump_failed, -// Snackbar.LENGTH_SHORT -// ).show() -// } -// } else { -// Snackbar.make( -// viewBinding.fab, -// R.string.cannot_be_accessed_this_directory, -// Snackbar.LENGTH_SHORT -// ).show() -// } -// } -// -// } -// } -// -// // override fun onPause() { // viewModel.getBookmarkManager().save() // super.onPause() @@ -461,10 +98,7 @@ class FileManagerActivity : BaseActivity() { loadMineBookmarksMenu() super.onResume() } -// -// - // override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK) { @@ -474,20 +108,17 @@ class FileManagerActivity : BaseActivity() { val intent = Intent() intent.putExtra("File", path) setResult(RESULT_OK, intent) -// bookmarkManager.save() finish() } } else if (viewModel.startTypeData == FileManagerViewModel.StartType.SELECT_FILE && requestCode == 2) { - val path = viewModel.parseFilePath(this@FileManagerActivity, data) - if (path != null) { - val intent = Intent() - intent.putExtra("File", path) - setResult(RESULT_OK, intent) -// bookmarkManager.save() - finish() - } - } else { - Toast.makeText(this, "未设置的操作", Toast.LENGTH_SHORT).show() +// val path = viewModel.parseFilePath(this@FileManagerActivity, data) +// if (path != null) { +// val intent = Intent() +// intent.putExtra("File", path) +// setResult(RESULT_OK, intent) +//// bookmarkManager.save() +// finish() +// } } // else if (requestCode == 3) { //新建源文件 @@ -509,6 +140,11 @@ class FileManagerActivity : BaseActivity() { } } + lateinit var photoAlbumResultLauncher: ActivityResultLauncher + + lateinit var systemFileManagerResultLauncher: ActivityResultLauncher + + // override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId @@ -522,22 +158,22 @@ class FileManagerActivity : BaseActivity() { viewModel.loadFiles(viewModel.getCurrentPath()) return true } - 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 - } +// 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 +// } R.id.creteFolder -> { // createFolderAction() return true @@ -550,7 +186,6 @@ class FileManagerActivity : BaseActivity() { override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) { if (viewModel.getCurrentPath() == viewModel.getRootPath()) { -// bookmarkManager.save() finish() true } else { @@ -823,16 +458,6 @@ class FileManagerActivity : BaseActivity() { // return null // } // -// override fun getViewBindingObject(layoutInflater: LayoutInflater): ActivityFileBinding { -// return ActivityFileBinding.inflate(layoutInflater) -// } -// -// override fun whenCreateActivity(savedInstanceState: Bundle?, canUseView: Boolean) { -// if (canUseView) { -// initView() -// initAction() -// } -// } private lateinit var menuBinding: MenuBinding private val viewModel: FileManagerViewModel by lazy { ViewModelProvider(this).get(FileManagerViewModel::class.java) @@ -882,32 +507,59 @@ class FileManagerActivity : BaseActivity() { viewModel.loadFiles(viewModel.getCurrentPath()) viewBinding.swipeRefreshLayout.isRefreshing = false } + systemFileManagerResultLauncher = + registerForActivityResult(ActivityResultContracts.GetContent()) { + val path = viewModel.parseFilePath(this, it) + 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() + } + } FastScrollerBuilder(viewBinding.recyclerView).useMd2Style() .setPopupTextProvider(adapter).build() } else { val bundle = intent.getBundleExtra("data") - if (bundle == null) { - showError("无效的请求。") - finish() - return - } - if (bundle.containsKey("path")) { - viewModel.currentPathLiveData.value = bundle.getString("path") - } - if (bundle.containsKey("type")) { - val type = bundle.getString("type") - viewModel.startTypeData = when (type) { - "selectDirectents" -> { - FileManagerViewModel.StartType.SELECT_DIRECTORY - } - else -> { - FileManagerViewModel.StartType.DEFAULT + if (bundle != null) { + if (bundle.containsKey("path")) { + viewModel.currentPathLiveData.value = bundle.getString("path") + } + 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) { + finish() + }.setGestureInsetBottomIgnored(true).show() + FileManagerViewModel.StartType.SELECT_DIRECTORY + } + "selectFile" -> { + FileManagerViewModel.StartType.SELECT_FILE + } + else -> { + FileManagerViewModel.StartType.DEFAULT + } } } + if (bundle.containsKey("rootpath")) { + viewModel.setRootPath(bundle.getString("rootpath")) + } } - if (bundle.containsKey("rootpath")) { - viewModel.setRootPath(bundle.getString("rootpath")) - } + } } @@ -920,6 +572,10 @@ class FileManagerActivity : BaseActivity() { if (viewModel.startTypeData != FileManagerViewModel.StartType.SELECT_FILE) { menu.removeItem(R.id.selectFile) } + menuBinding.systemFileManagerItem.setOnMenuItemClickListener { + systemFileManagerResultLauncher.launch("*/*") + true + } menuBinding.actionSortByType.setOnMenuItemClickListener { viewModel.sortTypeLiveData.value = FileManagerViewModel.SortType.BY_TYPE true @@ -964,6 +620,16 @@ class FileManagerActivity : BaseActivity() { } } + /** + * 设置结果并结束界面 + */ + fun setResultAndFinish(path: String) { + val temIntent = Intent() + temIntent.putExtra("File", path) + setResult(RESULT_OK, temIntent) + finish() + } + /** * 加载观察者 @@ -989,6 +655,17 @@ class FileManagerActivity : BaseActivity() { } else { if (file.isDirectory) { viewModel.currentPathLiveData.value = file.absolutePath + } 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() + } } } } @@ -1098,8 +775,7 @@ class FileManagerActivity : BaseActivity() { } } viewModel.currentPathLiveData.observe(this) { - if (it==null) - { + if (it == null) { return@observe } val root = getString(R.string.root_path) diff --git a/app/src/main/java/com/coldmint/rust/pro/LibraryActivity.kt b/app/src/main/java/com/coldmint/rust/pro/LibraryActivity.kt index 39c3545..301233b 100644 --- a/app/src/main/java/com/coldmint/rust/pro/LibraryActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/LibraryActivity.kt @@ -19,6 +19,7 @@ class LibraryActivity : BaseActivity() { */ private fun getLibInfoList(): ArrayList { val libInfoArrayList = ArrayList() + libInfoArrayList.add( LibInfo( "Kotlin", @@ -27,6 +28,22 @@ class LibraryActivity : BaseActivity() { "Apache License 2.0" ) ) +// libInfoArrayList.add( +// LibInfo( +// "Light", +// "The usual Snackbar, but elegant", +// "https://github.com/TonnyL/Light", +// "MIT" +// ) +// ) + libInfoArrayList.add( + LibInfo( + "FloatingActionButtonSpeedDial", + "A Floating Action Button Speed Dial implementation for Android that follows the Material Design specification", + "https://github.com/leinardi/FloatingActionButtonSpeedDial", + "Apache License 2.0" + ) + ) libInfoArrayList.add( LibInfo( "Banner", diff --git a/app/src/main/java/com/coldmint/rust/pro/MainActivity.kt b/app/src/main/java/com/coldmint/rust/pro/MainActivity.kt index 75afcc5..944777e 100644 --- a/app/src/main/java/com/coldmint/rust/pro/MainActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/MainActivity.kt @@ -16,7 +16,10 @@ import androidx.core.view.GravityCompat import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController -import androidx.navigation.ui.* +import androidx.navigation.ui.AppBarConfiguration +import androidx.navigation.ui.navigateUp +import androidx.navigation.ui.setupActionBarWithNavController +import androidx.navigation.ui.setupWithNavController import com.afollestad.materialdialogs.MaterialDialog import com.bumptech.glide.Glide import com.coldmint.dialog.CoreDialog @@ -80,12 +83,14 @@ class MainActivity : BaseActivity() { navController.navInflater.inflate(R.navigation.main_nav).apply { val use = AppSettings.getValue(AppSettings.Setting.UseTheCommunityAsTheLaunchPage, true) - startDestination = if (use) { - viewBinding.mainButton.hide() - R.id.community_item - } else { - R.id.mod_item - } + this.setStartDestination( + if (use) { + viewBinding.mainButton.hide() + R.id.community_item + } else { + R.id.mod_item + } + ) navController.graph = this } setupActionBarWithNavController(navController, appBarConfiguration) @@ -448,7 +453,8 @@ class MainActivity : BaseActivity() { val compressionManager = CompressionManager.instance if (templateDirectory.exists()) { val gson = Gson() - val newInfoData = compressionManager.readEntry(formFile, LocalTemplatePackage.INFONAME) + val newInfoData = + compressionManager.readEntry(formFile, LocalTemplatePackage.INFONAME) if (newInfoData == null) { handler.post { Snackbar.make( diff --git a/app/src/main/java/com/coldmint/rust/pro/OptimizeActivity.kt b/app/src/main/java/com/coldmint/rust/pro/OptimizeActivity.kt index 6105e5d..28c3615 100644 --- a/app/src/main/java/com/coldmint/rust/pro/OptimizeActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/OptimizeActivity.kt @@ -10,13 +10,13 @@ import com.coldmint.rust.core.tool.LineParser import com.coldmint.rust.core.interfaces.LineParserEvent import android.text.SpannableString import android.text.style.ClickableSpan -import com.afollestad.materialdialogs.MaterialDialog import android.text.Spanned import android.os.Looper import android.view.LayoutInflater import android.view.View import android.widget.* import androidx.core.view.isVisible +import com.coldmint.dialog.CoreDialog import com.coldmint.rust.core.tool.FileOperator import com.coldmint.rust.pro.adapters.OptimizeAdapter import com.coldmint.rust.pro.databean.OptimizeGroup @@ -173,7 +173,7 @@ class OptimizeActivity : BaseActivity() { * @param file */ private fun analyzeFile(file: File) { - if (mFileSignatureCache!!.isChange(file)) { + if (mFileSignatureCache.isChange(file)) { hasError = false val type = FileOperator.getFileType(file) when (type) { @@ -237,22 +237,11 @@ class OptimizeActivity : BaseActivity() { spannableString.setSpan( object : ClickableSpan() { override fun onClick(widget: View) { - val materialDialog = MaterialDialog( - this@OptimizeActivity, - MaterialDialog.DEFAULT_BEHAVIOR - ) - materialDialog.title(R.string.details, null) - materialDialog.message( - null, - lineBuilder.toString(), - null - ) - materialDialog.positiveButton( - R.string.close, - null, - null - ) - materialDialog.show() + CoreDialog(this@OptimizeActivity).setTitle(R.string.details) + .setMessage(lineBuilder.toString()) + .setPositiveButton(R.string.close) { + + }.show() } }, tip.indexOf(action), @@ -278,41 +267,25 @@ class OptimizeActivity : BaseActivity() { spannableString.setSpan( object : ClickableSpan() { override fun onClick(widget: View) { - val materialDialog = MaterialDialog( - this@OptimizeActivity, - MaterialDialog.DEFAULT_BEHAVIOR - ) - materialDialog.title(R.string.details, null) - materialDialog.message( - null, - noteBuilder.toString(), - null - ) - materialDialog.negativeButton( - R.string.edit, - null - ) { materialDialog: MaterialDialog? -> - val bundle = Bundle() - bundle.putString("path", file.absolutePath) - bundle.putString( - "modPath", - FileOperator.getSuperDirectory(file) - ) - val intent = - Intent( - this@OptimizeActivity, - EditActivity::class.java + CoreDialog(this@OptimizeActivity).setTitle(R.string.details) + .setMessage(noteBuilder.toString()) + .setPositiveButton(R.string.edit) { + val bundle = Bundle() + bundle.putString("path", file.absolutePath) + bundle.putString( + "modPath", + FileOperator.getSuperDirectory(file) ) - intent.putExtra("data", bundle) - this@OptimizeActivity.startActivity(intent) - null - } - materialDialog.positiveButton( - R.string.close, - null, - null - ) - materialDialog.show() + val intent = + Intent( + this@OptimizeActivity, + EditActivity::class.java + ) + intent.putExtra("data", bundle) + this@OptimizeActivity.startActivity(intent) + }.setNegativeButton(R.string.close) { + + }.show() } }, tip.indexOf(action), @@ -342,7 +315,7 @@ class OptimizeActivity : BaseActivity() { } } if (!hasError) { - mFileSignatureCache!!.putFile(file) + mFileSignatureCache.putFile(file) } } } diff --git a/app/src/main/java/com/coldmint/rust/pro/ReleaseModActivity.kt b/app/src/main/java/com/coldmint/rust/pro/ReleaseModActivity.kt index 887d215..ab1ad04 100644 --- a/app/src/main/java/com/coldmint/rust/pro/ReleaseModActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/ReleaseModActivity.kt @@ -79,7 +79,7 @@ class ReleaseModActivity : BaseActivity() { override fun whenCreateActivity(savedInstanceState: Bundle?, canUseView: Boolean) { if (canUseView) { - viewBinding.toolbar.title = getText(R.string.release) + title = getText(R.string.release) setReturnButton() val layoutManager = LinearLayoutManager(this) layoutManager.orientation = RecyclerView.HORIZONTAL @@ -876,7 +876,6 @@ class ReleaseModActivity : BaseActivity() { apiCallBack = object : ApiCallBack { override fun onResponse(t: ApiResponse) { dialog.dismiss() - resetButton() if (t.code == ServerConfiguration.Success_Code) { val temModClass = modClass if (temModClass != null) { @@ -922,7 +921,6 @@ class ReleaseModActivity : BaseActivity() { override fun onFailure(e: Exception) { dialog.dismiss() showInternetError(viewBinding.releaseButton, e) - resetButton() } }, progressListener = object : ProgressListener { @@ -944,13 +942,6 @@ class ReleaseModActivity : BaseActivity() { } }) - viewBinding.releaseButton.text = getString(R.string.releaseing) - viewBinding.releaseButton.setBackgroundColor( - GlobalMethod.getThemeColor( - this, - R.attr.colorPrimaryVariant - ) - ) } @@ -989,7 +980,6 @@ class ReleaseModActivity : BaseActivity() { apiCallBack = object : ApiCallBack { override fun onResponse(t: ApiResponse) { dialog.dismiss() - resetButton() if (t.code == ServerConfiguration.Success_Code) { val temModClass = modClass if (temModClass != null) { @@ -1040,7 +1030,6 @@ class ReleaseModActivity : BaseActivity() { override fun onFailure(e: Exception) { dialog.dismiss() showInternetError(viewBinding.releaseButton, e) - resetButton() } }, progressListener = object : ProgressListener { @@ -1062,13 +1051,6 @@ class ReleaseModActivity : BaseActivity() { } }) - viewBinding.releaseButton.text = getString(R.string.releaseing) - viewBinding.releaseButton.setBackgroundColor( - GlobalMethod.getThemeColor( - this, - R.attr.colorPrimaryVariant - ) - ) } /** @@ -1120,15 +1102,6 @@ class ReleaseModActivity : BaseActivity() { } } - /** - * 重新设置按钮 - */ - fun resetButton() { - viewBinding.releaseButton.text = getString(R.string.release) - viewBinding.releaseButton.setBackgroundColor( - GlobalMethod.getColorPrimary(this) - ) - } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { diff --git a/app/src/main/java/com/coldmint/rust/pro/RustApplication.kt b/app/src/main/java/com/coldmint/rust/pro/RustApplication.kt index a9c0e16..dbf6130 100644 --- a/app/src/main/java/com/coldmint/rust/pro/RustApplication.kt +++ b/app/src/main/java/com/coldmint/rust/pro/RustApplication.kt @@ -7,6 +7,7 @@ import android.util.Log import cat.ereza.customactivityoncrash.config.CaocConfig import com.coldmint.rust.core.web.ServerConfiguration import com.coldmint.rust.pro.tool.AppSettings +import com.coldmint.rust.pro.tool.CompletionItemConverter import com.coldmint.rust.pro.tool.GlobalMethod import com.google.android.material.color.DynamicColors import com.google.android.material.color.DynamicColorsOptions @@ -28,6 +29,7 @@ class RustApplication : Application() { DynamicColors.isDynamicColorAvailable() ) }.build() + CompletionItemConverter.init(this) DynamicColors.applyToActivitiesIfAvailable(this, options) //程序崩溃 CaocConfig.Builder.create() diff --git a/app/src/main/java/com/coldmint/rust/pro/SettingsActivity.kt b/app/src/main/java/com/coldmint/rust/pro/SettingsActivity.kt index 6fc997d..d1543ce 100644 --- a/app/src/main/java/com/coldmint/rust/pro/SettingsActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/SettingsActivity.kt @@ -51,6 +51,13 @@ class SettingsActivity : BaseActivity() { val english_editing_mode = manager.findPreference(requireContext().getString(R.string.setting_english_editing_mode)) + val customizeEdit = manager.findPreference("customize_edit") + customizeEdit!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { + val intent = Intent(requireContext(), CustomizeEditTextActivity::class.java) + startActivity(intent) + true + } + val dynamicColor = manager.findPreference(requireContext().getString(R.string.setting_dynamic_color)) if (!DynamicColors.isDynamicColorAvailable()) { @@ -147,12 +154,12 @@ class SettingsActivity : BaseActivity() { val nightMode: SwitchPreference? = manager.findPreference(getString(R.string.setting_night_mode)) nightMode?.setOnPreferenceChangeListener { preference, newValue -> - val booleanValue = newValue as Boolean - if (booleanValue) { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) - } else { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) - } + val booleanValue = newValue as Boolean + if (booleanValue) { + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) + } else { + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) + } true } diff --git a/app/src/main/java/com/coldmint/rust/pro/TurretDesignActivity.kt b/app/src/main/java/com/coldmint/rust/pro/TurretDesignActivity.kt index a55d4d1..394e4e1 100644 --- a/app/src/main/java/com/coldmint/rust/pro/TurretDesignActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/TurretDesignActivity.kt @@ -9,10 +9,12 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.MotionEvent import android.view.View +import android.widget.Toast import com.bumptech.glide.Glide import com.coldmint.rust.core.ModClass import com.coldmint.rust.core.SourceFile import com.coldmint.rust.core.turret.TurretInstaller +import com.coldmint.rust.core.turret.TurretSketchpadView import com.coldmint.rust.pro.base.BaseActivity import com.coldmint.rust.pro.databinding.ActivityTurretDesignBinding import java.io.File @@ -22,9 +24,6 @@ import java.io.File */ class TurretDesignActivity : BaseActivity() { - lateinit var turretInstaller: TurretInstaller - - val scale = 5 override fun whenCreateActivity(savedInstanceState: Bundle?, canUseView: Boolean) { if (canUseView) { @@ -51,18 +50,25 @@ class TurretDesignActivity : BaseActivity() { return } else { val file = mainImage[0] - val bitmap = BitmapFactory.decodeFile(file.absolutePath) - viewBinding.mainImageView.setImageBitmap(bitmap) - val layoutParams = viewBinding.mainImageView.layoutParams - layoutParams.width = bitmap.width * scale - layoutParams.height = bitmap.height * scale + viewBinding.turretSketchpadView.setImage(file.absolutePath) +// viewBinding.toolbar.postDelayed({ +// Toast.makeText(this, "执行", Toast.LENGTH_SHORT).show() +// viewBinding.turretsDragView.setBaseImage(file.absolutePath) +// }, 1000) +// val bitmap = BitmapFactory.decodeFile(file.absolutePath) +// viewBinding.mainImageView.setImageBitmap(bitmap) +// val layoutParams = viewBinding.mainImageView.layoutParams +// layoutParams.width = bitmap.width * scale +// layoutParams.height = bitmap.height * scale } - - turretInstaller = - TurretInstaller(viewBinding.relativeLayout, sourceFile) - turretInstaller.setScale(scale) - turretInstaller.installAllTurrets() +// val sketchpadView = TurretSketchpadView(this) +// sketchpadView. +// viewBinding.frameLayout.addView(sketchpadView) + TurretInstaller.installerAllTurret(viewBinding.frameLayout, sourceFile) { + val game = viewBinding.turretSketchpadView.toGameCoordinate(it) +// viewBinding.textView.text = "坐标 x:${game.x} y:${game.y}" + } } } diff --git a/app/src/main/java/com/coldmint/rust/pro/base/BaseActivity.kt b/app/src/main/java/com/coldmint/rust/pro/base/BaseActivity.kt index a50cbd4..dbb3abd 100644 --- a/app/src/main/java/com/coldmint/rust/pro/base/BaseActivity.kt +++ b/app/src/main/java/com/coldmint/rust/pro/base/BaseActivity.kt @@ -18,6 +18,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.viewbinding.ViewBinding import com.afollestad.materialdialogs.MaterialDialog +import com.coldmint.dialog.CoreDialog import com.coldmint.rust.pro.R import com.google.android.material.appbar.MaterialToolbar import com.google.android.material.color.DynamicColors @@ -121,12 +122,8 @@ abstract class BaseActivity : * @param msg String 错误信息 */ protected fun showError(msg: String) { - MaterialDialog(this).show { - title(R.string.error).message(text = msg).cancelable(false) - .positiveButton(R.string.dialog_close) { - finish() - } - } + Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() + finish() } /** @@ -155,10 +152,10 @@ abstract class BaseActivity : "${msg}\n${exception}" } if (view == null) { - MaterialDialog(this).show { - title(R.string.details).message(text = thisMsg) - .positiveButton(R.string.dialog_ok) - } + CoreDialog(this).setTitle(R.string.details).setMessage(thisMsg) + .setPositiveButton(R.string.dialog_ok) { + + }.show() } else { Snackbar.make( view, diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustAnalyzer.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustAnalyzer.kt index 353b328..6237fe6 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustAnalyzer.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustAnalyzer.kt @@ -49,11 +49,11 @@ class RustAnalyzer() : EnglishMode { /** - * 语法分析器 - * @param content CharSequence - * @param colors TextAnalyzeResult - * @param delegate Delegate - */ +// * 语法分析器 +// * @param content CharSequence +// * @param colors TextAnalyzeResult +// * @param delegate Delegate +// */ // override fun analyze( // content: CharSequence, // colors: TextAnalyzeResult, diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoComplete.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoComplete.kt index 82b298e..fda954e 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoComplete.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoComplete.kt @@ -19,14 +19,15 @@ import java.util.ArrayList import java.util.concurrent.Executors /** + * * @author Cold Mint * @date 2022/1/25 17:32 */ +@Deprecated("") class RustAutoComplete(val context: Context) : EnglishMode { private val debugKey = "自动完成器" private var codeDataBase: CodeDataBase? = null - private val executorService = Executors.newCachedThreadPool() private var fileDataBase: FileDataBase? = null private var codeEditor: CodeEditor? = null @@ -41,16 +42,8 @@ class RustAutoComplete(val context: Context) : EnglishMode { AppSettings.getValue(AppSettings.Setting.IdentifiersPromptNumber, 40) } - //类型转换器 - private val completionItemConverter: CompletionItemConverter by lazy { - CompletionItemConverter.instance.init(context) - } - companion object { - var keyWord = "" - } - /** * 是否为英文模式 */ @@ -62,7 +55,7 @@ class RustAutoComplete(val context: Context) : EnglishMode { */ fun setSourceFolder(sourceFolder: String) { DebugHelper.printLog(debugKey, "已设置源文件目录" + sourceFolder, "设置源文件目录") - completionItemConverter.setSourceFilePath(sourceFolder) + CompletionItemConverter.setSourceFilePath(sourceFolder) } /** @@ -76,7 +69,7 @@ class RustAutoComplete(val context: Context) : EnglishMode { rootCodeName: String, modFolder: String ) { - completionItemConverter.configurationFileConversion(sourceFilePath, rootCodeName, modFolder) + CompletionItemConverter.configurationFileConversion(sourceFilePath, rootCodeName, modFolder) } /** @@ -149,277 +142,276 @@ class RustAutoComplete(val context: Context) : EnglishMode { return } - keyWord = prefix - val temCodeEditor: CodeEditor = codeEditor!! - val lineData = temCodeEditor.text.getLineString(line) - if (lineData.startsWith('[')) { - //搜索节 - val name = lineData.subSequence(1, lineData.length).toString() - val list = if (isEnglishMode) { - codeDataBase!!.getSectionDao() - .searchSectionInfoByCode(name, limitNum = identifiersPromptNumber) - } else { - codeDataBase!!.getSectionDao() - .searchSectionInfoByTranslate(name, limitNum = identifiersPromptNumber) - } - list?.forEach { - completionPublisher.addItem(completionItemConverter.sectionInfoToCompletionItem(it)) - } - } else { - val key = ":" - val keyIndex = lineData.lastIndexOf(key) - if (keyIndex > -1) { - //检查是否可响应变量 - val start = "\${" - val end = "}" - val startIndex = lineData.lastIndexOf(start) - if (startIndex > -1) { - val endIndex = lineData.lastIndexOf(end) - if (endIndex < startIndex) { - //如果}的位置小于${的位置,说明没有闭合 - val keyWord = - lineData.subSequence(startIndex + start.length, lineData.length) - .toString() - val previousText = - lineData.subSequence(keyIndex + key.length, startIndex).toString() - if (keyWord.isNotBlank()) { - RustAnalyzer.localVariableNameList.forEach { - if (it.name.contains(keyWord)) { - completionPublisher.addItem( - completionItemConverter.localVariableNameToCompletionItem( - it, previousText - ) - ) - } - } - } else { - RustAnalyzer.localVariableNameList.forEach { - completionPublisher.addItem( - completionItemConverter.localVariableNameToCompletionItem( - it, previousText - ) - ) - } - } - RustAutoComplete.keyWord = keyWord - return - } - } - -// val value = -// lineData.subSequence(keyIndex + key.length, lineData.length).toString().trim() -// Log.d("值", value) - //搜索值 - // frontIndex 前面冒号的位置 - val frontIndex = lineData.lastIndexOf(key, keyIndex - key.length) - val keyValue = if (frontIndex > -1) { - lineData.subSequence(frontIndex + key.length, keyIndex) - } else { - lineData.subSequence(0, keyIndex) - } - - val codeInfo = - if (isEnglishMode) { - codeDataBase!!.getCodeDao().findCodeByCode(keyValue.toString()) - } else { - codeDataBase!!.getCodeDao().findCodeByTranslate(keyValue.toString()) - } - DebugHelper.printLog( - debugKey, - "值[" + keyValue + "]英文模式[" + isEnglishMode + "]代码信息[" + codeInfo + "]关键字[" + prefix + "]", - "值检查" - ) - if (codeInfo != null) { - val typeInfo = completionItemConverter.getValueType(codeInfo.type) - //获取代码的关联列表 - if (typeInfo != null && typeInfo.list.isNotBlank()) { - DebugHelper.printLog( - debugKey, - "值类型[" + codeInfo.type + "]自动提示列表[" + typeInfo.list + "]", "关联提示" - ) - lineParser.text = typeInfo.list - lineParser.analyse { lineNum, lineData, isEnd -> - //分析关联提示项目 - val temCodeInfo = - codeDataBase!!.getCodeDao().findCodeByCode(lineData) - DebugHelper.printLog( - debugKey, - "值类型[" + codeInfo.type + "]项目[" + lineData + "]是代码[" + (temCodeInfo != null) + "]", - "关联提示列表分析" - ) - if (temCodeInfo == null) { - if (lineData.startsWith("@file(") && lineData.endsWith(")")) { - val fileType = lineData.subSequence( - lineData.indexOf('(') + 1, - lineData.indexOf(')') - ) - - val fileInfo = fileDataBase!!.getFileInfoDao() - .searchFileInfoByNameAndType( - prefix, - fileType.toString(), - identifiersPromptNumber - ) - DebugHelper.printLog( - debugKey, - "值类型[" + codeInfo.type + "]项目[" + lineData + "]搜索了[" + fileType + "]类型的文件,返回了[" + (fileInfo?.size - ?: -1) + "]个结果", - "关联提示列表分析" - ) - if (fileInfo != null && fileInfo.isNotEmpty()) { - for (fileTable in fileInfo) { - completionPublisher.addItem( - completionItemConverter.fileTableToCompletionItem( - fileTable - ) - ) - } - } - } else if (lineData.startsWith("@customType(") && lineData.endsWith( - ")" - ) - ) { - //用户自动值类型提示 - val customType = lineData.subSequence( - lineData.indexOf('(') + 1, - lineData.indexOf(')') - ).toString() - fileDataBase!!.getValueDao() - .searchValueByKey( - prefix, - customType, - identifiersPromptNumber - ) - ?.forEach { - completionPublisher.addItem( - completionItemConverter.valueTableToCompletionItem( - it - ) - ) - } - } else if (lineData.startsWith("@type(") && lineData.endsWith(")")) { - val type = lineData.subSequence( - lineData.indexOf('(') + 1, - lineData.indexOf(')') - ).toString() - val list = if (isEnglishMode - ) { - codeDataBase!!.getCodeDao().findCodeByCodeInType( - prefix, - type, - identifiersPromptNumber - ) - } else { - codeDataBase!!.getCodeDao().findCodeByTranslateInType( - prefix, - type, - identifiersPromptNumber - ) - } - DebugHelper.printLog( - debugKey, - "关联了值类型[" + type + "]获取[" + (list?.size ?: -1) + "]个结果", - "值类型引用" - ) - if (!list.isNullOrEmpty()) { - list.forEach { - completionPublisher.addItem( - completionItemConverter.codeInfoToCompletionItem( - it - ) - ) - } - } - } else if (lineData.startsWith("@section") && lineData.endsWith( - ")" - ) - ) { - val section = lineData.subSequence( - lineData.indexOf('(') + 1, - lineData.indexOf(')') - ).toString() -// codeEditor!!.textAnalyzeResult.navigation.forEach { -// if (section == getSectionType(it.label)) { -// result.add( -// completionItemConverter.navigationItemToCompletionItem( -// it -// ) -// ) -// } -// } - } else { - //无法分析的关联项目 -// result.add( -// CompletionItem( -// lineData, -// String.format( -// completionItemConverter.associatedTip, -// codeInfo.translate -// ) -// ) +// val temCodeEditor: CodeEditor = codeEditor!! +// val lineData = temCodeEditor.text.getLineString(line) +// if (lineData.startsWith('[')) { +// //搜索节 +// val name = lineData.subSequence(1, lineData.length).toString() +// val list = if (isEnglishMode) { +// codeDataBase!!.getSectionDao() +// .searchSectionInfoByCode(name, limitNum = identifiersPromptNumber) +// } else { +// codeDataBase!!.getSectionDao() +// .searchSectionInfoByTranslate(name, limitNum = identifiersPromptNumber) +// } +// list?.forEach { +// completionPublisher.addItem(CompletionItemConverter.sectionInfoToCompletionItem(it)) +// } +// } else { +// val key = ":" +// val keyIndex = lineData.lastIndexOf(key) +// if (keyIndex > -1) { +// //检查是否可响应变量 +// val start = "\${" +// val end = "}" +// val startIndex = lineData.lastIndexOf(start) +// if (startIndex > -1) { +// val endIndex = lineData.lastIndexOf(end) +// if (endIndex < startIndex) { +// //如果}的位置小于${的位置,说明没有闭合 +// val keyWord = +// lineData.subSequence(startIndex + start.length, lineData.length) +// .toString() +// val previousText = +// lineData.subSequence(keyIndex + key.length, startIndex).toString() +// if (keyWord.isNotBlank()) { +// RustAnalyzer.localVariableNameList.forEach { +// if (it.name.contains(keyWord)) { +// completionPublisher.addItem( +// CompletionItemConverter.localVariableNameToCompletionItem( +// it, previousText // ) - } - } else { - - val show = if (isEnglishMode) { - temCodeInfo.code.contains(prefix) - } else { - temCodeInfo.translate.contains(prefix) - } - DebugHelper.printLog( - debugKey, - "值类型[" + codeInfo.type + "]项目[" + lineData + "]是否包含" + prefix + "关键字[" + show + "]", - "关联提示列表分析" - ) - if (show) { - completionPublisher.addItem( - completionItemConverter.codeInfoToCompletionItem( - temCodeInfo - ) - ) - } - } - true - } - } - } - } else { - //如果不包含:搜索键 -// val navigationList = temCodeEditor.textAnalyzeResult.navigation -// var section: String? = null -// if (navigationList != null && navigationList.isNotEmpty()) { -// for (navigation in navigationList) { -// if (navigation.line > line) { -// break -// } else { -// section = navigation.label +// ) +// } +// } +// } else { +// RustAnalyzer.localVariableNameList.forEach { +// completionPublisher.addItem( +// CompletionItemConverter.localVariableNameToCompletionItem( +// it, previousText +// ) +// ) // } // } +// RustAutoComplete.keyWord = keyWord +// return // } -// //如果不在任何节内 -// if (section == null) { -// return@submit -// } -// val trueSection = getSectionType(section) -// val list = if (isEnglishMode) { -// codeDataBase!!.getCodeDao().findCodeByEnglishCodeKeyFromSection( -// prefix, -// trueSection, -// identifiersPromptNumber -// ) +// } +// +//// val value = +//// lineData.subSequence(keyIndex + key.length, lineData.length).toString().trim() +//// Log.d("值", value) +// //搜索值 +// // frontIndex 前面冒号的位置 +// val frontIndex = lineData.lastIndexOf(key, keyIndex - key.length) +// val keyValue = if (frontIndex > -1) { +// lineData.subSequence(frontIndex + key.length, keyIndex) +// } else { +// lineData.subSequence(0, keyIndex) +// } +// +// val codeInfo = +// if (isEnglishMode) { +// codeDataBase!!.getCodeDao().findCodeByCode(keyValue.toString()) // } else { -// codeDataBase!!.getCodeDao() -// .findCodeByKeyFromSection(prefix, trueSection, identifiersPromptNumber) +// codeDataBase!!.getCodeDao().findCodeByTranslate(keyValue.toString()) // } -// if (list != null && list.isNotEmpty()) { -// list.forEach { -// result.add( -// completionItemConverter.codeInfoToCompletionItem(it) +// DebugHelper.printLog( +// debugKey, +// "值[" + keyValue + "]英文模式[" + isEnglishMode + "]代码信息[" + codeInfo + "]关键字[" + prefix + "]", +// "值检查" +// ) +// if (codeInfo != null) { +// val typeInfo = CompletionItemConverter.getValueType(codeInfo.type) +// //获取代码的关联列表 +// if (typeInfo != null && typeInfo.list.isNotBlank()) { +// DebugHelper.printLog( +// debugKey, +// "值类型[" + codeInfo.type + "]自动提示列表[" + typeInfo.list + "]", "关联提示" +// ) +// lineParser.text = typeInfo.list +// lineParser.analyse { lineNum, lineData, isEnd -> +// //分析关联提示项目 +// val temCodeInfo = +// codeDataBase!!.getCodeDao().findCodeByCode(lineData) +// DebugHelper.printLog( +// debugKey, +// "值类型[" + codeInfo.type + "]项目[" + lineData + "]是代码[" + (temCodeInfo != null) + "]", +// "关联提示列表分析" // ) +// if (temCodeInfo == null) { +// if (lineData.startsWith("@file(") && lineData.endsWith(")")) { +// val fileType = lineData.subSequence( +// lineData.indexOf('(') + 1, +// lineData.indexOf(')') +// ) +// +// val fileInfo = fileDataBase!!.getFileInfoDao() +// .searchFileInfoByNameAndType( +// prefix, +// fileType.toString(), +// identifiersPromptNumber +// ) +// DebugHelper.printLog( +// debugKey, +// "值类型[" + codeInfo.type + "]项目[" + lineData + "]搜索了[" + fileType + "]类型的文件,返回了[" + (fileInfo?.size +// ?: -1) + "]个结果", +// "关联提示列表分析" +// ) +// if (fileInfo != null && fileInfo.isNotEmpty()) { +// for (fileTable in fileInfo) { +// completionPublisher.addItem( +// CompletionItemConverter.fileTableToCompletionItem( +// fileTable +// ) +// ) +// } +// } +// } else if (lineData.startsWith("@customType(") && lineData.endsWith( +// ")" +// ) +// ) { +// //用户自动值类型提示 +// val customType = lineData.subSequence( +// lineData.indexOf('(') + 1, +// lineData.indexOf(')') +// ).toString() +// fileDataBase!!.getValueDao() +// .searchValueByKey( +// prefix, +// customType, +// identifiersPromptNumber +// ) +// ?.forEach { +// completionPublisher.addItem( +// CompletionItemConverter.valueTableToCompletionItem( +// it +// ) +// ) +// } +// } else if (lineData.startsWith("@type(") && lineData.endsWith(")")) { +// val type = lineData.subSequence( +// lineData.indexOf('(') + 1, +// lineData.indexOf(')') +// ).toString() +// val list = if (isEnglishMode +// ) { +// codeDataBase!!.getCodeDao().findCodeByCodeInType( +// prefix, +// type, +// identifiersPromptNumber +// ) +// } else { +// codeDataBase!!.getCodeDao().findCodeByTranslateInType( +// prefix, +// type, +// identifiersPromptNumber +// ) +// } +// DebugHelper.printLog( +// debugKey, +// "关联了值类型[" + type + "]获取[" + (list?.size ?: -1) + "]个结果", +// "值类型引用" +// ) +// if (!list.isNullOrEmpty()) { +// list.forEach { +// completionPublisher.addItem( +// CompletionItemConverter.codeInfoToCompletionItem( +// it +// ) +// ) +// } +// } +// } else if (lineData.startsWith("@section") && lineData.endsWith( +// ")" +// ) +// ) { +// val section = lineData.subSequence( +// lineData.indexOf('(') + 1, +// lineData.indexOf(')') +// ).toString() +//// codeEditor!!.textAnalyzeResult.navigation.forEach { +//// if (section == getSectionType(it.label)) { +//// result.add( +//// CompletionItemConverter.navigationItemToCompletionItem( +//// it +//// ) +//// ) +//// } +//// } +// } else { +// //无法分析的关联项目 +//// result.add( +//// CompletionItem( +//// lineData, +//// String.format( +//// CompletionItemConverter.associatedTip, +//// codeInfo.translate +//// ) +//// ) +//// ) +// } +// } else { +// +// val show = if (isEnglishMode) { +// temCodeInfo.code.contains(prefix) +// } else { +// temCodeInfo.translate.contains(prefix) +// } +// DebugHelper.printLog( +// debugKey, +// "值类型[" + codeInfo.type + "]项目[" + lineData + "]是否包含" + prefix + "关键字[" + show + "]", +// "关联提示列表分析" +// ) +// if (show) { +// completionPublisher.addItem( +// CompletionItemConverter.codeInfoToCompletionItem( +// temCodeInfo +// ) +// ) +// } +// } +// true // } // } - } - } +// } +// } else { +// //如果不包含:搜索键 +//// val navigationList = temCodeEditor.textAnalyzeResult.navigation +//// var section: String? = null +//// if (navigationList != null && navigationList.isNotEmpty()) { +//// for (navigation in navigationList) { +//// if (navigation.line > line) { +//// break +//// } else { +//// section = navigation.label +//// } +//// } +//// } +//// //如果不在任何节内 +//// if (section == null) { +//// return@submit +//// } +//// val trueSection = getSectionType(section) +//// val list = if (isEnglishMode) { +//// codeDataBase!!.getCodeDao().findCodeByEnglishCodeKeyFromSection( +//// prefix, +//// trueSection, +//// identifiersPromptNumber +//// ) +//// } else { +//// codeDataBase!!.getCodeDao() +//// .findCodeByKeyFromSection(prefix, trueSection, identifiersPromptNumber) +//// } +//// if (list != null && list.isNotEmpty()) { +//// list.forEach { +//// result.add( +//// CompletionItemConverter.codeInfoToCompletionItem(it) +//// ) +//// } +//// } +// } +// } } override fun isEnglishMode(): Boolean { @@ -428,6 +420,5 @@ class RustAutoComplete(val context: Context) : EnglishMode { override fun setEnglish(englishMode: Boolean) { this.isEnglishMode = englishMode - completionItemConverter.setEnglish(englishMode) } } \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoCompleteProvider.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoCompleteProvider.kt new file mode 100644 index 0000000..a4463ed --- /dev/null +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustAutoCompleteProvider.kt @@ -0,0 +1,93 @@ +package com.coldmint.rust.pro.edit + +import android.os.Bundle +import com.coldmint.rust.core.tool.DebugHelper +import com.coldmint.rust.pro.edit.autoComplete.AutoCompleteJob +import io.github.rosemoe.sora.lang.completion.CompletionPublisher +import io.github.rosemoe.sora.text.CharPosition +import io.github.rosemoe.sora.text.ContentReference + +/** + * 自动完成信息提供者 + */ +class RustAutoCompleteProvider { + + private val key = "自动完成提供者" + private val jobList = ArrayList() + companion object{ + var keyWord = "" + } + + /** + * 添加任务 + * @param job AutoCompleteJob + */ + fun addJob(job: AutoCompleteJob): AutoCompleteJob { + jobList.add(job) + DebugHelper.printLog(key, "添加了新任务${job.getName()}") + return job + } + + + /** + * 移除任务 + */ + fun removeJob(job: AutoCompleteJob): AutoCompleteJob { + jobList.remove(job) + DebugHelper.printLog(key, "移除了任务${job.getName()}") + return job + } + + + /** + * 请求自动完成 + * @param contentReference ContentReference + * @param charPosition CharPosition + * @param completionPublisher CompletionPublisher + * @param bundle Bundle + */ + fun requireAutoComplete( + contentReference: ContentReference, + charPosition: CharPosition, + completionPublisher: CompletionPublisher, + bundle: Bundle + ) { + val requireKey = "请求自动完成" + if (jobList.isEmpty()) { + DebugHelper.printLog(key, "没有任务可执行。", requireKey, true) + } else { + //行内容 + val lineData = contentReference.getLine(charPosition.getLine()) + if (lineData.isBlank()) { + DebugHelper.printLog(requireKey, "行内容为空,无需提示。") + return + } + //光标前内容 + val cursorPrefix = lineData.subSequence(0, charPosition.getColumn()).toString() + val symbolIndex = cursorPrefix.lastIndexOf(':') + keyWord = if (symbolIndex > 0) { + //有冒号 + cursorPrefix.substring(symbolIndex + 1) + } else { + //无 + cursorPrefix + } + var executeNumber = 0 + jobList.forEach { + //如果需要执行 + if (it.needPerform(contentReference, charPosition)) { + executeNumber++ + it.requireAutoComplete( + contentReference, + charPosition, + completionPublisher, + lineData, keyWord + ) + } + } + DebugHelper.printLog(key, "执行了${executeNumber}个任务。", requireKey) + } + } + + +} \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionAdapter.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionAdapter.kt index 0e5dfa5..f0ab06c 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionAdapter.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionAdapter.kt @@ -42,18 +42,18 @@ class RustCompletionAdapter : EditorCompletionAdapter() { val editItem = EditItemBinding.inflate(layoutInflater, parent, false) val completionItem = getItem(position) as RustCompletionItem spannableStringBuilder.clear() - val label = completionItem.label.toString() + val label = completionItem.title spannableStringBuilder.append(label) //节补丁 - if (RustAutoComplete.keyWord.startsWith('[') && RustAutoComplete.keyWord.length > 1) { - RustAutoComplete.keyWord = - RustAutoComplete.keyWord.subSequence(1, RustAutoComplete.keyWord.length) + if (RustAutoCompleteProvider.keyWord.startsWith('[') && RustAutoCompleteProvider.keyWord.length > 1) { + RustAutoCompleteProvider.keyWord = + RustAutoCompleteProvider.keyWord.subSequence(1, RustAutoCompleteProvider.keyWord.length) .toString() } val start = label.lowercase(Locale.getDefault()) - .indexOf(RustAutoComplete.keyWord.lowercase(Locale.getDefault())) + .indexOf(RustAutoCompleteProvider.keyWord.lowercase(Locale.getDefault())) if (start > -1) { - val end = start + RustAutoComplete.keyWord.length + val end = start + RustAutoCompleteProvider.keyWord.length spannableStringBuilder.setSpan( colorSpan, start, diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionItem.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionItem.kt index 483c06e..c31c01b 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionItem.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustCompletionItem.kt @@ -48,7 +48,16 @@ class RustCompletionItem(var title: String) : CompletionItem(title) { * @param p2 Int * @param p3 Int */ - override fun performCompletion(p0: CodeEditor?, p1: Content?, p2: Int, p3: Int) { - + //CodeEditor editor, Content text, int line, int column + override fun performCompletion(editor: CodeEditor, text: Content, line: Int, column: Int) { + if (label == null) { + return + } + val keyOffset = RustAutoCompleteProvider.keyWord.length + if (keyOffset == 0) { + text.insert(line, column, label) + } else { + text.replace(line, column - keyOffset, line, column, label) + } } } \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustIncrementalAnalyzeManager.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustIncrementalAnalyzeManager.kt index 22ea5a6..5d2f416 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustIncrementalAnalyzeManager.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustIncrementalAnalyzeManager.kt @@ -90,7 +90,7 @@ class RustIncrementalAnalyzeManager : spans.add( Span.obtain( it.offset, - TextStyle.makeStyle(EditorColorScheme.COMMENT) + TextStyle.makeStyle(EditorColorScheme.TEXT_NORMAL) ) ) } @@ -98,7 +98,7 @@ class RustIncrementalAnalyzeManager : spans.add( Span.obtain( it.offset, - TextStyle.makeStyle(EditorColorScheme.COMMENT) + TextStyle.makeStyle(EditorColorScheme.TEXT_NORMAL) ) ) } diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/RustLanguage.kt b/app/src/main/java/com/coldmint/rust/pro/edit/RustLanguage.kt index 7544867..5494569 100644 --- a/app/src/main/java/com/coldmint/rust/pro/edit/RustLanguage.kt +++ b/app/src/main/java/com/coldmint/rust/pro/edit/RustLanguage.kt @@ -7,6 +7,7 @@ import com.coldmint.rust.core.database.code.CodeDataBase import com.coldmint.rust.core.database.file.FileDataBase import com.coldmint.rust.core.interfaces.EnglishMode import com.coldmint.rust.core.tool.DebugHelper +import com.coldmint.rust.pro.edit.autoComplete.CodeAutoCompleteJob import io.github.rosemoe.sora.lang.Language import io.github.rosemoe.sora.lang.analysis.AnalyzeManager import io.github.rosemoe.sora.lang.completion.CompletionPublisher @@ -20,23 +21,51 @@ import io.github.rosemoe.sora.text.ContentReference import io.github.rosemoe.sora.text.TextRange import io.github.rosemoe.sora.widget.CodeEditor import io.github.rosemoe.sora.widget.SymbolPairMatch +import java.util.* -class RustLanguage( - private val context: Context, -) : Language, EnglishMode { - private val mRustAnalyzer: RustAnalyzer by lazy { - RustAnalyzer() - } +class RustLanguage() : Language, EnglishMode { - private val autoComplete by lazy { - RustAutoComplete(context) - } - - // private val autoComplete: RustAutoComplete = RustAutoComplete(context) private var isEnglishMode = false private val rustAnalyzeManager by lazy { RustIncrementalAnalyzeManager() } + private val codeAutoCompleteJob: CodeAutoCompleteJob by lazy { + CodeAutoCompleteJob() + } + + private val newlineHandler: Array by lazy { + arrayOf(object : NewlineHandler { + override fun matchesRequirement(beforeText: String?, afterText: String?): Boolean { + return true + } + + override fun handleNewline( + beforeText: String, + afterText: String?, + tabSize: Int + ): NewlineHandleResult { + var text = "\n" + if (beforeText.startsWith("[")) { + if (beforeText.endsWith("_")) { + text = "name]" + } else if (!beforeText.endsWith("]")) { + text = "]" + } + } + val newlineHandleResult = NewlineHandleResult(text, 0) + return newlineHandleResult + } + + }) + } + + + private val autoCompleteProvider: RustAutoCompleteProvider by lazy { + val a = RustAutoCompleteProvider() + a.addJob(codeAutoCompleteJob) + a + } + private var codeDataBase: CodeDataBase? = null /** @@ -44,8 +73,8 @@ class RustLanguage( * @param codeDataBean CodeDataBase */ fun setCodeDataBase(codeDataBase: CodeDataBase) { - mRustAnalyzer.setCodeDataBase(codeDataBase) -// autoComplete.setCodeDataBase(codeDataBase) + this.codeDataBase = codeDataBase + this.codeAutoCompleteJob.setCodeDataBase(codeDataBase) } /** @@ -57,35 +86,10 @@ class RustLanguage( } fun setFileDataBase(fileDataBase: FileDataBase) { -// autoComplete.setFileDataBase(fileDataBase) + codeAutoCompleteJob.setFileDataBase(fileDataBase) } - //语法分析器 -// override fun getAnalyzer(): CodeAnalyzer { -// return mRustAnalyzer -// } - - //自动完成器 -// override fun getAutoCompleteProvider(): RustAutoComplete { -// return autoComplete -// } - - -// /** -// * 是否为自动完成字符 -// * -// * @param ch 字符 -// * @return 逻辑值 -// */ -// override fun isAutoCompleteChar(ch: Char): Boolean { -// return when (ch) { -// ':', '.', '_', ' ', ',' -> false -// else -> true -// } -// } - - override fun getAnalyzeManager(): AnalyzeManager { return rustAnalyzeManager } @@ -95,15 +99,17 @@ class RustLanguage( } override fun requireAutoComplete( - p0: ContentReference, - p1: CharPosition, - p2: CompletionPublisher, - p3: Bundle + contentReference: ContentReference, + charPosition: CharPosition, + completionPublisher: CompletionPublisher, + bundle: Bundle ) { - val line = p0.getLine(p1.getLine()) - p2.addItem(RustCompletionItem("121221")) - p2.updateList() -// autoComplete.requireAutoComplete(line,p2,p1.getLine(),p1.getColumn()) + autoCompleteProvider.requireAutoComplete( + contentReference, + charPosition, + completionPublisher, + bundle + ) } override fun getIndentAdvance(p0: ContentReference, p1: Int, p2: Int): Int { @@ -112,7 +118,7 @@ class RustLanguage( //用标签 override fun useTab(): Boolean { - return true + return false } override fun getFormatter(): Formatter { @@ -125,7 +131,7 @@ class RustLanguage( override fun getNewlineHandlers(): Array? { //行处理程序,按下回车时 - return null + return newlineHandler } @@ -137,7 +143,6 @@ class RustLanguage( } override fun setEnglish(englishMode: Boolean) { - mRustAnalyzer.setEnglish(englishMode) // autoComplete.setEnglish(englishMode) isEnglishMode = englishMode } diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/AutoCompleteJob.kt b/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/AutoCompleteJob.kt new file mode 100644 index 0000000..e1bc6dc --- /dev/null +++ b/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/AutoCompleteJob.kt @@ -0,0 +1,50 @@ +package com.coldmint.rust.pro.edit.autoComplete + +import android.os.Bundle +import com.coldmint.rust.pro.edit.RustAutoComplete +import com.coldmint.rust.pro.edit.RustCompletionItem +import io.github.rosemoe.sora.lang.completion.CompletionPublisher +import io.github.rosemoe.sora.text.CharPosition +import io.github.rosemoe.sora.text.ContentReference + + +/** + * 自动完成工作接口 + */ +interface AutoCompleteJob { + + + /** + * 获取工作名称 + */ + fun getName():String + + + /** + * 该任务是否需要执行(返回true则执行) + * @param contentReference ContentReference + * @param charPosition CharPosition + * @return String + */ + fun needPerform( + contentReference: ContentReference, + charPosition: CharPosition + ): Boolean + + /** + * 请求自动完成 + * @param contentReference ContentReference + * @param charPosition CharPosition + * @param completionPublisher CompletionPublisher + * @param bundle Bundle + * @return ArrayList + */ + fun requireAutoComplete( + contentReference: ContentReference, + charPosition: CharPosition, + completionPublisher: CompletionPublisher, + lineData: String, + keyWord:String + ) + +} \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/CodeAutoCompleteJob.kt b/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/CodeAutoCompleteJob.kt new file mode 100644 index 0000000..08f42d8 --- /dev/null +++ b/app/src/main/java/com/coldmint/rust/pro/edit/autoComplete/CodeAutoCompleteJob.kt @@ -0,0 +1,409 @@ +package com.coldmint.rust.pro.edit.autoComplete + +import android.os.Bundle +import com.coldmint.rust.core.SourceFile +import com.coldmint.rust.core.database.code.CodeDao +import com.coldmint.rust.core.database.code.CodeDataBase +import com.coldmint.rust.core.database.file.FileDataBase +import com.coldmint.rust.core.tool.DebugHelper +import com.coldmint.rust.core.tool.LineParser +import com.coldmint.rust.pro.edit.RustAnalyzer +import com.coldmint.rust.pro.edit.RustAutoComplete +import com.coldmint.rust.pro.edit.RustCompletionItem +import com.coldmint.rust.pro.tool.AppSettings +import com.coldmint.rust.pro.tool.CompletionItemConverter +import io.github.rosemoe.sora.lang.completion.CompletionPublisher +import io.github.rosemoe.sora.text.CharPosition +import io.github.rosemoe.sora.text.ContentReference +import io.github.rosemoe.sora.widget.CodeEditor + +/** + * 代码自动完成项目(来自数据库) + */ +class CodeAutoCompleteJob : AutoCompleteJob { + + private val debugKey = "代码自动完成(数据库)" + private var codeDataBase: CodeDataBase? = null + private var fileDataBase: FileDataBase? = null + private lateinit var codeDao: CodeDao + private val identifiersPromptNumber: Int by lazy { + AppSettings.getValue(AppSettings.Setting.IdentifiersPromptNumber, 40) + } + private var sectionNameMap: HashMap = HashMap() + + + private val lineParser by lazy { + val tem = LineParser() + tem.symbol = "," + tem + } + + /** + * 设置代码数据库 + * @param codeDataBase CodeDataBase + */ + fun setCodeDataBase(codeDataBase: CodeDataBase) { + DebugHelper.printLog(debugKey, "已链接数据库,数据库状态:${codeDataBase.isOpen}。") + this.codeDataBase = codeDataBase + this.codeDao = codeDataBase.getCodeDao() + } + + /** + * 设置文件数据库 + * @param fileDataBase FileDataBase + */ + fun setFileDataBase(fileDataBase: FileDataBase) { + DebugHelper.printLog(debugKey, "已链接文件数据库,数据库状态:${fileDataBase.isOpen}。") + this.fileDataBase = fileDataBase + } + + /** + * 是否为英文模式 + */ + private val isEnglishMode by lazy { + AppSettings.getValue(AppSettings.Setting.EnglishEditingMode, false) + } + + override fun getName(): String { + return debugKey + } + + + override fun needPerform( + contentReference: ContentReference, + charPosition: CharPosition + ): Boolean { + return true + } + + override fun requireAutoComplete( + contentReference: ContentReference, + charPosition: CharPosition, + completionPublisher: CompletionPublisher, + lineData: String, + keyWord: String + ) { + if (codeDataBase == null) { + DebugHelper.printLog(debugKey, "数据库为空,无法使用", isError = true) + return + } + DebugHelper.printLog( + debugKey, + "行内容[" + lineData + "]关键字[" + keyWord + "]", + "关联提示列表分析" + ) + if (lineData.startsWith('[')) { + //搜索节 + val name = lineData.subSequence(1, lineData.length).toString() + val list = if (isEnglishMode) { + codeDataBase!!.getSectionDao() + .searchSectionInfoByCode(name, limitNum = identifiersPromptNumber) + } else { + codeDataBase!!.getSectionDao() + .searchSectionInfoByTranslate(name, limitNum = identifiersPromptNumber) + } + list?.forEach { + completionPublisher.addItem(CompletionItemConverter.sectionInfoToCompletionItem(it)) + } + } else { + val key = ":" + val keyIndex = lineData.lastIndexOf(key) + if (keyIndex > -1) { + //检查是否可响应变量 + val start = "\${" + val end = "}" + val startIndex = lineData.lastIndexOf(start) + if (startIndex > -1) { + val endIndex = lineData.lastIndexOf(end) + if (endIndex < startIndex) { + //如果}的位置小于${的位置,说明没有闭合 + val keyWord = + lineData.subSequence(startIndex + start.length, lineData.length) + .toString() + val previousText = + lineData.subSequence(keyIndex + key.length, startIndex).toString() + if (keyWord.isNotBlank()) { + RustAnalyzer.localVariableNameList.forEach { + if (it.name.contains(keyWord)) { + completionPublisher.addItem( + CompletionItemConverter.localVariableNameToCompletionItem( + it, previousText + ) + ) + } + } + } else { + RustAnalyzer.localVariableNameList.forEach { + completionPublisher.addItem( + CompletionItemConverter.localVariableNameToCompletionItem( + it, previousText + ) + ) + } + } +// RustAutoComplete.keyWord = keyWord + return + } + } + +// val value = +// lineData.subSequence(keyIndex + key.length, lineData.length).toString().trim() +// Log.d("值", value) + //搜索值 + // frontIndex 前面冒号的位置 + val frontIndex = lineData.lastIndexOf(key, keyIndex - key.length) + val keyValue = if (frontIndex > -1) { + lineData.subSequence(frontIndex + key.length, keyIndex) + } else { + lineData.subSequence(0, keyIndex) + } + + val codeInfo = + if (isEnglishMode) { + codeDao.findCodeByCode(keyValue.toString()) + } else { + codeDao.findCodeByTranslate(keyValue.toString()) + } + DebugHelper.printLog( + debugKey, + "值[" + keyValue + "]英文模式[" + isEnglishMode + "]代码信息[" + codeInfo + "]关键字[" + keyWord + "]", + "值检查" + ) + if (codeInfo != null) { + val typeInfo = CompletionItemConverter.getValueType(codeInfo.type) + //获取代码的关联列表 + if (typeInfo != null && typeInfo.list.isNotBlank()) { + DebugHelper.printLog( + debugKey, + "值类型[" + codeInfo.type + "]自动提示列表[" + typeInfo.list + "]", "关联提示" + ) + lineParser.text = typeInfo.list + lineParser.analyse { lineNum, lineData, isEnd -> + //分析关联提示项目 + val temCodeInfo = + codeDao.findCodeByCode(lineData) + DebugHelper.printLog( + debugKey, + "值类型[" + codeInfo.type + "]项目[" + lineData + "]是代码[" + (temCodeInfo != null) + "]", + "关联提示列表分析" + ) + if (temCodeInfo == null) { + if (lineData.startsWith("@file(") && lineData.endsWith(")")) { + val fileType = lineData.subSequence( + lineData.indexOf('(') + 1, + lineData.indexOf(')') + ) + + val fileInfo = fileDataBase!!.getFileInfoDao() + .searchFileInfoByNameAndType( + keyWord, + fileType.toString(), + identifiersPromptNumber + ) + DebugHelper.printLog( + debugKey, + "值类型[" + codeInfo.type + "]项目[" + lineData + "]搜索了[" + fileType + "]类型的文件,返回了[" + (fileInfo?.size + ?: -1) + "]个结果", + "关联提示列表分析" + ) + if (fileInfo != null && fileInfo.isNotEmpty()) { + for (fileTable in fileInfo) { + completionPublisher.addItem( + CompletionItemConverter.fileTableToCompletionItem( + fileTable + ) + ) + } + } + } else if (lineData.startsWith("@customType(") && lineData.endsWith( + ")" + ) + ) { + //用户自动值类型提示 + val customType = lineData.subSequence( + lineData.indexOf('(') + 1, + lineData.indexOf(')') + ).toString() + fileDataBase!!.getValueDao() + .searchValueByKey( + keyWord, + customType, + identifiersPromptNumber + ) + ?.forEach { + completionPublisher.addItem( + CompletionItemConverter.valueTableToCompletionItem( + it + ) + ) + } + } else if (lineData.startsWith("@type(") && lineData.endsWith(")")) { + val type = lineData.subSequence( + lineData.indexOf('(') + 1, + lineData.indexOf(')') + ).toString() + val list = if (isEnglishMode + ) { + codeDao.findCodeByCodeInType( + keyWord, + type, + identifiersPromptNumber + ) + } else { + codeDao.findCodeByTranslateInType( + keyWord, + type, + identifiersPromptNumber + ) + } + DebugHelper.printLog( + debugKey, + "关联了值类型[" + type + "]获取[" + (list?.size ?: -1) + "]个结果", + "值类型引用" + ) + if (!list.isNullOrEmpty()) { + list.forEach { + completionPublisher.addItem( + CompletionItemConverter.codeInfoToCompletionItem( + it + ) + ) + } + } + } else if (lineData.startsWith("@section") && lineData.endsWith( + ")" + ) + ) { +// val section = lineData.subSequence( +// lineData.indexOf('(') + 1, +// lineData.indexOf(')') +// ).toString() +// codeEditor!!.textAnalyzeResult.navigation.forEach { +// if (section == getSectionType(it.label)) { +// result.add( +// CompletionItemConverter.navigationItemToCompletionItem( +// it +// ) +// ) +// } +// } + } else { + //无法分析的关联项目 +// result.add( +// CompletionItem( +// lineData, +// String.format( +// CompletionItemConverter.associatedTip, +// codeInfo.translate +// ) +// ) +// ) + } + } else { + val show = if (isEnglishMode) { + temCodeInfo.code.contains(keyWord) + } else { + temCodeInfo.translate.contains(keyWord) + } + DebugHelper.printLog( + debugKey, + "值类型[" + codeInfo.type + "]项目[" + lineData + "]是否包含" + keyWord + "关键字[" + show + "]", + "关联提示列表分析" + ) + if (show) { + completionPublisher.addItem( + CompletionItemConverter.codeInfoToCompletionItem( + temCodeInfo + ) + ) + } + } + true + } + } + } + } else { + //如果不包含:搜索键 + val lineNumber = charPosition.getLine() + val section = getSection(lineNumber, contentReference) + //如果不在任何节内 + if (section == null) { + DebugHelper.printLog(debugKey, "不在任何节内,无法提示。", isError = true) + return + } + val trueSection = getSectionType(section) + val list = if (isEnglishMode) { + codeDao.findCodeByEnglishCodeKeyFromSection( + keyWord, + trueSection, + identifiersPromptNumber + ) + } else { + codeDao + .findCodeByKeyFromSection(keyWord, trueSection, identifiersPromptNumber) + } + if (list != null && list.isNotEmpty()) { + list.forEach { + completionPublisher.addItem( + CompletionItemConverter.codeInfoToCompletionItem(it) + ) + } + } else { + DebugHelper.printLog( + debugKey, + "在${trueSection}节模糊搜索${keyWord}无结果。", + isError = true + ) + } + } + } + } + + + /** + * 获取光标前的节名 + * @param lineNumber Int + * @param contentReference ContentReference + * @return String? + */ + fun getSection(lineNumber: Int, contentReference: ContentReference): String? { + return if (lineNumber > 0) { + for (i in lineNumber downTo 0) { + val lineData = contentReference.getLine(i) + DebugHelper.printLog(debugKey, "检查第${i}行 ${lineData}", "获取光标前的节名") + if (lineData.startsWith("[") && lineData.endsWith("]")) { + val name = lineData.subSequence(1, lineData.length - 1).toString() + DebugHelper.printLog(debugKey, "返回 ${name}", "获取光标前的节名") + return name + } + } + DebugHelper.printLog(debugKey, "没有找到节。", "获取光标前的节名", isError = true) + null + } else { + DebugHelper.printLog(debugKey, "行号小于0无法获取。", "获取光标前的节名", isError = true) + null + } + } + + + /** + * 获取节类型(永远返回英文) + * @param section String + * @return String + */ + fun getSectionType(section: String): String { + if (sectionNameMap.containsKey(section)) { + return sectionNameMap[section] ?: SourceFile.getSectionType(section) + } + val result = if (isEnglishMode) { + SourceFile.getSectionType(section) + } else { + val sectionInfo = codeDataBase!!.getSectionDao() + .findSectionInfoByTranslate(SourceFile.getSectionType(section)) + sectionInfo?.code ?: SourceFile.getSectionType(section) + } + sectionNameMap[section] = result + return result + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/coldmint/rust/pro/tool/AppSettings.kt b/app/src/main/java/com/coldmint/rust/pro/tool/AppSettings.kt index ed5052c..1d700d1 100644 --- a/app/src/main/java/com/coldmint/rust/pro/tool/AppSettings.kt +++ b/app/src/main/java/com/coldmint/rust/pro/tool/AppSettings.kt @@ -9,6 +9,7 @@ import kotlin.Throws import android.os.Environment import android.util.Log import com.hjq.language.MultiLanguages +import java.io.File import java.lang.NullPointerException import java.util.* @@ -37,10 +38,24 @@ object AppSettings { } enum class Setting { - DatabaseDirectory, DatabasePath, TemplateDirectory, AppLanguage, DeveloperMode, CustomSymbol, AutoCreateNomedia, OnlyLoadConantLanguageTemple, NightMode, GamePackage, KeepRwmodFile, EnableRecoveryStation, RecoveryStationFileSaveDays, RecoveryStationFolder, IndependentFolder, SetGameStorage, PackDirectory, IdentifiersPromptNumber, UserName, UseJetBrainsMonoFont, AppID, Account, PassWord, ExpirationTime, CheckBetaUpdate, UpdateData, ShareTip, AgreePolicy, EnglishEditingMode, NightModeFollowSystem, UseMobileNetwork, MapFolder, ModFolder, UseTheCommunityAsTheLaunchPage, AutoSave, ServerAddress, Token, LoginStatus, DynamicColor, ExperiencePlan, FileSortType + DatabaseDirectory, DatabasePath, TemplateDirectory, AppLanguage, DeveloperMode, CustomSymbol, AutoCreateNomedia, OnlyLoadConantLanguageTemple, NightMode, GamePackage, KeywordColor, AnnotationColor, TextColor, SectionColor, KeepRwmodFile, EnableRecoveryStation, RecoveryStationFileSaveDays, RecoveryStationFolder, IndependentFolder, SetGameStorage, PackDirectory, IdentifiersPromptNumber, UserName, UseJetBrainsMonoFont, AppID, Account, PassWord, ExpirationTime, CheckBetaUpdate, UpdateData, ShareTip, AgreePolicy, EnglishEditingMode, NightModeFollowSystem, UseMobileNetwork, MapFolder, ModFolder, UseTheCommunityAsTheLaunchPage, AutoSave, ServerAddress, Token, LoginStatus, DynamicColor, ExperiencePlan, FileSortType, CodeEditBackGroundEnable, BlurTransformationValue, CodeEditBackGroundPath } + + /** + * 创建新的编辑器背景文件(返回文件目录) + * @return String + */ + fun createNewCodeEditBackGroundFile(): String { + val folderPath = mApplication.filesDir.absolutePath + "/CodeEditBackground/" + val folder = File(folderPath) + if (!folder.exists()) { + folder.mkdirs() + } + return folderPath + UUID.randomUUID().toString() + ".png" + } + private val map: HashMap = HashMap() /** @@ -127,6 +142,14 @@ object AppSettings { map[Setting.AgreePolicy] = "AgreePolicy" map[Setting.LoginStatus] = "LoginStatus" map[Setting.Token] = "Token" + map[Setting.BlurTransformationValue] = "BlurTransformationValue" + map[Setting.CodeEditBackGroundEnable] = "CodeEditBackGroundEnable" + map[Setting.CodeEditBackGroundPath] = "CodeEditBackGroundPath" + //KeywordColor, AnnotationColor, TextColor, SectionColor + map[Setting.KeywordColor] = mApplication.getString(R.string.setting_keyword_color) + map[Setting.AnnotationColor] = mApplication.getString(R.string.setting_annotation_color) + map[Setting.TextColor] = mApplication.getString(R.string.setting_text_color) + map[Setting.SectionColor] = mApplication.getString(R.string.setting_section_color) } /** diff --git a/app/src/main/java/com/coldmint/rust/pro/tool/CompletionItemConverter.kt b/app/src/main/java/com/coldmint/rust/pro/tool/CompletionItemConverter.kt index a2bd17a..d366240 100644 --- a/app/src/main/java/com/coldmint/rust/pro/tool/CompletionItemConverter.kt +++ b/app/src/main/java/com/coldmint/rust/pro/tool/CompletionItemConverter.kt @@ -33,13 +33,8 @@ import java.lang.StringBuilder * @property canUseFileConversion Boolean * @property valueTypeDao ValueTypeDao? */ -class CompletionItemConverter private constructor() : EnglishMode { +object CompletionItemConverter { - companion object { - val instance: CompletionItemConverter by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { - CompletionItemConverter() - } - } /** * 初始化 @@ -80,14 +75,7 @@ class CompletionItemConverter private constructor() : EnglishMode { HashMap() } private var isEnglishMode = false - - override fun isEnglishMode(): Boolean { - return isEnglishMode - } - - override fun setEnglish(englishMode: Boolean) { - this.isEnglishMode = englishMode - } + get() = AppSettings.getValue(AppSettings.Setting.EnglishEditingMode, false) /** @@ -135,7 +123,7 @@ class CompletionItemConverter private constructor() : EnglishMode { NullPointerException("没有初始化。") } val end = if (sectionInfo.needName) { - "_]" + "_" } else { "]" @@ -213,12 +201,12 @@ class CompletionItemConverter private constructor() : EnglishMode { codeInfo.description, boxDrawable ) } - val typeList = typeInfo?.list - if (typeList != null && typeList.isNotBlank()) { - val bundle = Bundle() - bundle.putString("list", typeList) +// val typeList = typeInfo?.list +// if (typeList != null && typeList.isNotBlank()) { +// val bundle = Bundle() +// bundle.putString("list", typeList) // completionItem.extrasData = bundle - } +// } val offset = typeInfo?.offset if (offset != null && offset.isNotBlank()) { //如果偏移不为空 diff --git a/app/src/main/java/com/coldmint/rust/pro/tool/GlobalMethod.kt b/app/src/main/java/com/coldmint/rust/pro/tool/GlobalMethod.kt index 63bf989..6b32fec 100644 --- a/app/src/main/java/com/coldmint/rust/pro/tool/GlobalMethod.kt +++ b/app/src/main/java/com/coldmint/rust/pro/tool/GlobalMethod.kt @@ -43,6 +43,7 @@ object GlobalMethod { const val DEBUG_SIGN = "963dfd616924b27f9247a35e45bc130a" const val RELEASE_SIGN = "5320b24894fe7ed449842a81a2dfceda" + /** * 获取主题色 * @@ -107,6 +108,87 @@ object GlobalMethod { return requestOptions } + + /** + * int颜色值转String + * @param color Int + * @param useARGB Boolean + * @return String + */ + fun colorToString(color: Int, useARGB: Boolean = true): String { + val builder = StringBuilder() + builder.append('#') + if (useARGB) { + builder.append(convertDigital(Color.alpha(color))) + } + builder.append(convertDigital(Color.red(color))) + builder.append(convertDigital(Color.green(color))) + builder.append(convertDigital(Color.blue(color))) + return builder.toString() + } + + /** + * 展示颜色选择对话框 + * @param context Context + * @param func Function1 + */ + fun showColorPickerDialog( + context: Context, + useARGB: Boolean = false, func: ((String) -> Unit) + ) { + ColorPickerDialogBuilder + .with(context).showAlphaSlider(useARGB) + .setTitle(context.getString(R.string.choose_color)) + .initialColor(Color.WHITE) + .wheelType(ColorPickerView.WHEEL_TYPE.FLOWER) + .density(12) + .setOnColorSelectedListener { + //toast("onColorSelected: 0x" + Integer.toHexString(selectedColor)); + } + .setPositiveButton(R.string.dialog_ok) { dialog, selectedColor, allColors -> + func.invoke(colorToString(selectedColor, useARGB)) + } + .setNegativeButton(R.string.dialog_cancel) { dialog, which -> } + .build() + .show() + } + + /** + * 转换为16进制 + * + * @param num 十进制整数 + * @return 16进制数 + */ + private fun convertDigital(num: Int): String { + return if (num > 255) { + "FF" + } else { + val builder = java.lang.StringBuilder() + val result = num / 16 + val remainder = num % 16 + when (result) { + 10 -> builder.append('A') + 11 -> builder.append('B') + 12 -> builder.append('C') + 13 -> builder.append('D') + 14 -> builder.append('E') + 15 -> builder.append('F') + else -> builder.append(result) + } + when (remainder) { + 10 -> builder.append('A') + 11 -> builder.append('B') + 12 -> builder.append('C') + 13 -> builder.append('D') + 14 -> builder.append('E') + 15 -> builder.append('F') + else -> builder.append(remainder) + } + builder.toString() + } + } + + /** * 显示更新日志 * @param context Context @@ -191,7 +273,6 @@ object GlobalMethod { } - //设置删除线 fun addDeleteLine(vararg textViews: TextView?) { for (textView in textViews) { diff --git a/app/src/main/java/com/coldmint/rust/pro/viewmodel/EditViewModel.kt b/app/src/main/java/com/coldmint/rust/pro/viewmodel/EditViewModel.kt index c60ecfb..1707e1f 100644 --- a/app/src/main/java/com/coldmint/rust/pro/viewmodel/EditViewModel.kt +++ b/app/src/main/java/com/coldmint/rust/pro/viewmodel/EditViewModel.kt @@ -17,6 +17,7 @@ import com.coldmint.rust.core.tool.FileOperator import com.coldmint.rust.pro.base.BaseAndroidViewModel import com.coldmint.rust.pro.livedata.OpenedSourceFileListLiveData import com.coldmint.rust.pro.tool.AppSettings +import com.coldmint.rust.pro.tool.CompletionItemConverter import com.coldmint.rust.pro.tool.GlobalMethod import java.io.File import java.lang.StringBuilder @@ -189,6 +190,7 @@ class EditViewModel(application: Application) : BaseAndroidViewModel(application } override fun onTranslateComplete(code: String) { + CompletionItemConverter.setSourceFilePath(path) val openedSourceFile = OpenedSourceFile(path) openedSourceFile.setTranslation(code) val index = openedSourceFileListLiveData.add(openedSourceFile) @@ -534,40 +536,7 @@ class EditViewModel(application: Application) : BaseAndroidViewModel(application } } - /** - * 转换为16进制 - * - * @param num 十进制整数 - * @return 16进制数 - */ - fun convertDigital(num: Int): String { - return if (num > 255) { - "FF" - } else { - val builder = StringBuilder() - val result = num / 16 - val remainder = num % 16 - when (result) { - 10 -> builder.append('A') - 11 -> builder.append('B') - 12 -> builder.append('C') - 13 -> builder.append('D') - 14 -> builder.append('E') - 15 -> builder.append('F') - else -> builder.append(result) - } - when (remainder) { - 10 -> builder.append('A') - 11 -> builder.append('B') - 12 -> builder.append('C') - 13 -> builder.append('D') - 14 -> builder.append('E') - 15 -> builder.append('F') - else -> builder.append(remainder) - } - builder.toString() - } - } + /** * 加载数据 diff --git a/app/src/main/java/com/coldmint/rust/pro/viewmodel/FileManagerViewModel.kt b/app/src/main/java/com/coldmint/rust/pro/viewmodel/FileManagerViewModel.kt index 077789a..57942ae 100644 --- a/app/src/main/java/com/coldmint/rust/pro/viewmodel/FileManagerViewModel.kt +++ b/app/src/main/java/com/coldmint/rust/pro/viewmodel/FileManagerViewModel.kt @@ -178,29 +178,26 @@ class FileManagerViewModel : BaseViewModel() { return rootPath } - // /** -// * 解析文件路径 -// * -// * @param context 上下文环境 -// * @param intent 意图 -// * @return 成功返回文件路径,失败返回null -// */ - fun parseFilePath(context: Context, intent: Intent?): String? { + /** + * 解析文件路径 + * + * @param context 上下文环境 + * @param uri 定位符 + * @return 成功返回文件路径,失败返回null + */ + fun parseFilePath(context: Context, uri: Uri?): String? { return try { - if (intent != null) { - val uri = intent.data - var chooseFilePath: String? = null - if ("file".equals(uri!!.scheme, ignoreCase = true)) { //使用第三方应用打开 - chooseFilePath = uri.path - return chooseFilePath - } - chooseFilePath = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后 - getPath(context, uri) - } else { //4.4以下下系统调用方法 - getRealPathFromURI(context, uri) - } + var chooseFilePath: String? = null + if ("file".equals(uri!!.scheme, ignoreCase = true)) { //使用第三方应用打开 + chooseFilePath = uri.path return chooseFilePath } + chooseFilePath = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后 + getPath(context, uri) + } else { //4.4以下下系统调用方法 + getRealPathFromURI(context, uri) + } + return chooseFilePath null } catch (e: Exception) { e.printStackTrace() @@ -239,7 +236,6 @@ class FileManagerViewModel : BaseViewModel() { return@launch } val arrayList = ArrayList() - Log.d("文件管理器", "当前路径" + path + "根路径" + rootPath + "添加返回" + (path != rootPath)) if (path != rootPath) { //如果不是根目录添加返回 arrayList.add(null) diff --git a/app/src/main/java/com/coldmint/rust/pro/viewmodel/StartViewModel.kt b/app/src/main/java/com/coldmint/rust/pro/viewmodel/StartViewModel.kt index 3e9f765..a6a5ae1 100644 --- a/app/src/main/java/com/coldmint/rust/pro/viewmodel/StartViewModel.kt +++ b/app/src/main/java/com/coldmint/rust/pro/viewmodel/StartViewModel.kt @@ -238,12 +238,23 @@ class StartViewModel(application: Application) : BaseAndroidViewModel(applicatio AppSettings.initSetting(AppSettings.Setting.AutoSave, true) AppSettings.initSetting(AppSettings.Setting.AgreePolicy, false) AppSettings.initSetting(AppSettings.Setting.LoginStatus, false) - AppSettings.initSetting(AppSettings.Setting.FileSortType,context.getString(R.string.setting_file_list_action_sort_by_name)) + AppSettings.initSetting( + AppSettings.Setting.FileSortType, + context.getString(R.string.setting_file_list_action_sort_by_name) + ) //如果启用动态颜色 AppSettings.initSetting( AppSettings.Setting.DynamicColor, DynamicColors.isDynamicColorAvailable() ) + AppSettings.initSetting(AppSettings.Setting.KeywordColor, "#FF0031C2") + AppSettings.initSetting(AppSettings.Setting.SectionColor, "#FFE10000") + AppSettings.initSetting(AppSettings.Setting.TextColor, "#FF000000") + AppSettings.initSetting(AppSettings.Setting.AnnotationColor, "#FF00AF2C") + AppSettings.initSetting(AppSettings.Setting.CodeEditBackGroundEnable, false) + AppSettings.initSetting(AppSettings.Setting.BlurTransformationValue, 1) + AppSettings.initSetting(AppSettings.Setting.CodeEditBackGroundPath, "") + } /** diff --git a/app/src/main/res/drawable/ic_baseline_color_lens_24.xml b/app/src/main/res/drawable/ic_baseline_color_lens_24.xml index c3d2c7b..42fe01e 100644 --- a/app/src/main/res/drawable/ic_baseline_color_lens_24.xml +++ b/app/src/main/res/drawable/ic_baseline_color_lens_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_baseline_link_24.xml b/app/src/main/res/drawable/ic_baseline_link_24.xml index ff57e07..8d19cef 100644 --- a/app/src/main/res/drawable/ic_baseline_link_24.xml +++ b/app/src/main/res/drawable/ic_baseline_link_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_outline_arrow_downward_24.xml b/app/src/main/res/drawable/ic_outline_arrow_downward_24.xml index dcfb784..91bee95 100644 --- a/app/src/main/res/drawable/ic_outline_arrow_downward_24.xml +++ b/app/src/main/res/drawable/ic_outline_arrow_downward_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_outline_bookmarks_24.xml b/app/src/main/res/drawable/ic_outline_bookmarks_24.xml index 24082d9..b846f5b 100644 --- a/app/src/main/res/drawable/ic_outline_bookmarks_24.xml +++ b/app/src/main/res/drawable/ic_outline_bookmarks_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_outline_clear_24.xml b/app/src/main/res/drawable/ic_outline_clear_24.xml new file mode 100644 index 0000000..061507a --- /dev/null +++ b/app/src/main/res/drawable/ic_outline_clear_24.xml @@ -0,0 +1,6 @@ + + + diff --git a/app/src/main/res/drawable/ic_outline_color_lens_24.xml b/app/src/main/res/drawable/ic_outline_color_lens_24.xml new file mode 100644 index 0000000..48f82e8 --- /dev/null +++ b/app/src/main/res/drawable/ic_outline_color_lens_24.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_outline_create_24.xml b/app/src/main/res/drawable/ic_outline_create_24.xml index 5b5fa7a..e10b511 100644 --- a/app/src/main/res/drawable/ic_outline_create_24.xml +++ b/app/src/main/res/drawable/ic_outline_create_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_outline_location_on_24.xml b/app/src/main/res/drawable/ic_outline_location_on_24.xml index d0da6c1..7be7fff 100644 --- a/app/src/main/res/drawable/ic_outline_location_on_24.xml +++ b/app/src/main/res/drawable/ic_outline_location_on_24.xml @@ -1,4 +1,4 @@ - diff --git a/app/src/main/res/drawable/ic_outline_save_24.xml b/app/src/main/res/drawable/ic_outline_save_24.xml index 714549a..ec1288d 100644 --- a/app/src/main/res/drawable/ic_outline_save_24.xml +++ b/app/src/main/res/drawable/ic_outline_save_24.xml @@ -1,5 +1,11 @@ - - + + diff --git a/app/src/main/res/drawable/ic_outline_send_24.xml b/app/src/main/res/drawable/ic_outline_send_24.xml new file mode 100644 index 0000000..eae5ec6 --- /dev/null +++ b/app/src/main/res/drawable/ic_outline_send_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_outline_shopping_cart_24.xml b/app/src/main/res/drawable/ic_outline_shopping_cart_24.xml index afd9dcf..d1a22cc 100644 --- a/app/src/main/res/drawable/ic_outline_shopping_cart_24.xml +++ b/app/src/main/res/drawable/ic_outline_shopping_cart_24.xml @@ -1,5 +1,11 @@ - - + + diff --git a/app/src/main/res/drawable/prize.xml b/app/src/main/res/drawable/prize.xml index 0b5d5ea..cfcd97e 100644 --- a/app/src/main/res/drawable/prize.xml +++ b/app/src/main/res/drawable/prize.xml @@ -1,6 +1,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +