diff --git a/.gitignore b/.gitignore index 7b56132fae..41d29740e7 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,13 @@ autopush.sh /server local.properties +# personal ideas +current-idea.md + +# +information/ +.gitignore + # Crowdin crowdin.properties .idea/crowdin_settings.xml diff --git a/composite-builds/build-logic/common/src/main/java/com/tom/rv2ide/build/config/SigningKeyProperties.kt b/composite-builds/build-logic/common/src/main/java/com/tom/rv2ide/build/config/SigningKeyProperties.kt index 513c8a51f6..0f84883ba0 100644 --- a/composite-builds/build-logic/common/src/main/java/com/tom/rv2ide/build/config/SigningKeyProperties.kt +++ b/composite-builds/build-logic/common/src/main/java/com/tom/rv2ide/build/config/SigningKeyProperties.kt @@ -14,10 +14,10 @@ fun Project.loadSigningProperties(): SigningConfig? { localFile.inputStream().use { load(it) } } - val storeFile = props.getProperty("signing.storeFile") ?: return null - val storePassword = props.getProperty("signing.storePassword") ?: return null - val keyAlias = props.getProperty("signing.keyAlias") ?: return null - val keyPassword = props.getProperty("signing.keyPassword") ?: return null + val storeFile = props.getProperty("signing.storeFile")?.takeIf { it.isNotBlank() } ?: return null + val storePassword = props.getProperty("signing.storePassword")?.takeIf { it.isNotBlank() } ?: return null + val keyAlias = props.getProperty("signing.keyAlias")?.takeIf { it.isNotBlank() } ?: return null + val keyPassword = props.getProperty("signing.keyPassword")?.takeIf { it.isNotBlank() } ?: return null return SigningConfig(storeFile, storePassword, keyAlias, keyPassword) } diff --git a/composite-builds/build-logic/plugins/src/main/java/com/tom/rv2ide/plugins/SigningConfigPlugin.kt b/composite-builds/build-logic/plugins/src/main/java/com/tom/rv2ide/plugins/SigningConfigPlugin.kt index 38d261830f..4958696e90 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/tom/rv2ide/plugins/SigningConfigPlugin.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/tom/rv2ide/plugins/SigningConfigPlugin.kt @@ -68,7 +68,7 @@ class SigningConfigPlugin : Plugin { val envKeyPassword = System.getenv("SIGNING_KEY_PASSWORD") val envKeyAlias = System.getenv("SIGNING_KEY_ALIAS") ?: "AndroidCS" - if (envStorePassword != null && envKeyPassword != null) { + if (!envStorePassword.isNullOrBlank() && !envKeyPassword.isNullOrBlank()) { return SigningConfig( storeFile = envStoreFile, storePassword = envStorePassword, @@ -82,7 +82,7 @@ class SigningConfigPlugin : Plugin { val gradleKeyPassword = findProperty("signingKeyPassword") as? String val gradleKeyAlias = findProperty("signingKeyAlias") as? String ?: "AndroidCS" - if (gradleStorePassword != null && gradleKeyPassword != null) { + if (!gradleStorePassword.isNullOrBlank() && !gradleKeyPassword.isNullOrBlank()) { return SigningConfig( storeFile = gradleStoreFile, storePassword = gradleStorePassword, diff --git a/core/app/build.gradle.kts b/core/app/build.gradle.kts index 4f6ff47721..6ee1864fca 100755 --- a/core/app/build.gradle.kts +++ b/core/app/build.gradle.kts @@ -20,6 +20,7 @@ import com.tom.rv2ide.build.config.BuildConfig import com.tom.rv2ide.desugaring.utils.JavaIOReplacements.applyJavaIOReplacements import com.tom.rv2ide.plugins.AndroidIDEAssetsPlugin +import java.security.KeyStore import java.util.Properties plugins { @@ -74,19 +75,62 @@ android { experimentalProperties["android.experimental.enableGlobalSynthetics"] = true + val localProps = Properties().apply { + val file = rootProject.file("local.properties") + if (file.exists()) { + file.inputStream().use { load(it) } + } + } + val signingStorePassword = + System.getProperty("SIGNING_STORE_PASSWORD")?.takeIf { it.isNotBlank() } + ?: System.getenv("SIGNING_STORE_PASSWORD")?.takeIf { it.isNotBlank() } + ?: localProps.getProperty("signing.storePassword")?.takeIf { it.isNotBlank() } + val signingKeyPassword = + System.getProperty("SIGNING_KEY_PASSWORD")?.takeIf { it.isNotBlank() } + ?: System.getenv("SIGNING_KEY_PASSWORD")?.takeIf { it.isNotBlank() } + ?: localProps.getProperty("signing.keyPassword")?.takeIf { it.isNotBlank() } + val customKeyStoreFile = + localProps.getProperty("signing.storeFile") + ?.takeIf { it.isNotBlank() } + ?.let { rootProject.file(it) } + ?: rootProject.file("signing/signing-key.jks") + val customKeyAlias = + localProps.getProperty("signing.keyAlias")?.takeIf { it.isNotBlank() } ?: "androidcs" + val hasCustomSigning = + if (customKeyStoreFile.exists() && + !signingStorePassword.isNullOrBlank() && + !signingKeyPassword.isNullOrBlank() + ) { + try { + val ks = KeyStore.getInstance(customKeyStoreFile, signingStorePassword.toCharArray()) + val key = ks.getKey(customKeyAlias, signingKeyPassword.toCharArray()) + if (key == null) { + logger.warn( + "Key alias '$customKeyAlias' not found in ${customKeyStoreFile.name}; falling back to debug signing." + ) + false + } else { + true + } + } catch (e: Exception) { + logger.warn( + "Custom keystore ${customKeyStoreFile.name} rejected configured password (${e.message}); falling back to debug signing." + ) + false + } + } else { + false + } + signingConfigs { + if (hasCustomSigning) { create("custom") { - val keyStorePath = "${rootProject.projectDir}/signing/signing-key.jks" - val keyStoreFile = file(keyStorePath) - - val signing_storePassword = System.getProperty("SIGNING_STORE_PASSWORD") ?: "" - val signing_keyPassword = System.getProperty("SIGNING_KEY_PASSWORD") ?: "" - - storeFile = keyStoreFile - storePassword = signing_storePassword - keyAlias = "androidcs" - keyPassword = signing_keyPassword + storeFile = customKeyStoreFile + storePassword = signingStorePassword + keyAlias = customKeyAlias + keyPassword = signingKeyPassword } + } } androidResources { generateLocaleConfig = true } @@ -96,14 +140,18 @@ android { dataBinding = true } + val resolvedSigning = + if (hasCustomSigning) signingConfigs.getByName("custom") + else signingConfigs.getByName("debug") + buildTypes { debug { - signingConfig = signingConfigs.getByName("custom") + signingConfig = resolvedSigning } release { isShrinkResources = false - signingConfig = signingConfigs.getByName("custom") + signingConfig = resolvedSigning } } diff --git a/core/app/src/main/java/com/tom/rv2ide/activities/FileBrowserActivity.kt b/core/app/src/main/java/com/tom/rv2ide/activities/FileBrowserActivity.kt index f6e045bc30..e6bfcd87c1 100644 --- a/core/app/src/main/java/com/tom/rv2ide/activities/FileBrowserActivity.kt +++ b/core/app/src/main/java/com/tom/rv2ide/activities/FileBrowserActivity.kt @@ -31,9 +31,10 @@ import androidx.activity.viewModels import androidx.core.content.ContextCompat import com.tom.rv2ide.R import com.tom.rv2ide.app.EdgeToEdgeIDEActivity +import com.tom.rv2ide.fragments.FileBrowserFragment +import com.tom.rv2ide.utils.FileBrowserNavigationHelper import com.tom.rv2ide.viewmodel.MainViewModel import com.tom.rv2ide.viewmodel.MainViewModel.Companion.SCREEN_MAIN -import com.tom.rv2ide.fragments.FileBrowserFragment /** * @author Mohammed-baqer-null @ https://github.com/Mohammed-baqer-null @@ -45,21 +46,23 @@ class FileBrowserActivity : EdgeToEdgeIDEActivity() { private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean -> - if (isGranted) { - loadFileBrowserFragment() - } else { - Toast.makeText(this, "Permission denied to read storage", Toast.LENGTH_SHORT).show() + if (!isGranted) { + Toast.makeText( + this, + "Shared storage permission denied; private app storage remains accessible.", + Toast.LENGTH_SHORT + ).show() } } private val manageStoragePermissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - if (Environment.isExternalStorageManager()) { - loadFileBrowserFragment() - } else { - Toast.makeText(this, "Permission denied to manage storage", Toast.LENGTH_SHORT).show() - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) { + Toast.makeText( + this, + "All files access not granted; private app storage remains accessible.", + Toast.LENGTH_SHORT + ).show() } } @@ -68,36 +71,35 @@ class FileBrowserActivity : EdgeToEdgeIDEActivity() { viewModel.setScreen(SCREEN_MAIN) - checkAndRequestPermissions() + // Always open the file browser so $HOME and root navigation work even without external storage access + loadFileBrowserFragment() + checkAndRequestPermissionsIfNeeded() } - private fun checkAndRequestPermissions() { + private fun checkAndRequestPermissionsIfNeeded() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - if (Environment.isExternalStorageManager()) { - loadFileBrowserFragment() - } else { - val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) - val uri = Uri.fromParts("package", packageName, null) - intent.data = uri - manageStoragePermissionLauncher.launch(intent) - } - } else { - when { - ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == - PackageManager.PERMISSION_GRANTED -> { - loadFileBrowserFragment() - } - else -> { - requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) + if (!Environment.isExternalStorageManager()) { + runCatching { + val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { + data = Uri.fromParts("package", packageName, null) + } + manageStoragePermissionLauncher.launch(intent) } } + } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != + PackageManager.PERMISSION_GRANTED + ) { + requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } } private fun loadFileBrowserFragment() { if (supportFragmentManager.findFragmentById(R.id.fragment_container) == null) { supportFragmentManager.beginTransaction() - .replace(R.id.fragment_container, FileBrowserFragment.newInstance()) + .replace( + R.id.fragment_container, + FileBrowserFragment.newInstance(FileBrowserNavigationHelper.defaultStartPath()) + ) .commit() } } diff --git a/core/app/src/main/java/com/tom/rv2ide/activities/IdeConfigurations/net/ConnectionManager.kt b/core/app/src/main/java/com/tom/rv2ide/activities/IdeConfigurations/net/ConnectionManager.kt index e2691b3aee..235ee2c74d 100644 --- a/core/app/src/main/java/com/tom/rv2ide/activities/IdeConfigurations/net/ConnectionManager.kt +++ b/core/app/src/main/java/com/tom/rv2ide/activities/IdeConfigurations/net/ConnectionManager.kt @@ -20,8 +20,12 @@ package com.tom.rv2ide.activities.IdeConfigurations.net /** * @author Mohammed-baqer-null @ https://github.com/Mohammed-baqer-null */ import android.content.Context import android.net.ConnectivityManager +import android.net.NetworkCapabilities fun isOnline(context: Context): Boolean { - val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - return cm.activeNetworkInfo?.isConnected == true + val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager + ?: return false + val network = cm.activeNetwork ?: return false + val capabilities = cm.getNetworkCapabilities(network) ?: return false + return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } diff --git a/core/app/src/main/java/com/tom/rv2ide/activities/editor/BaseEditorActivity.kt b/core/app/src/main/java/com/tom/rv2ide/activities/editor/BaseEditorActivity.kt index efd084d6e8..a0f41aa582 100644 --- a/core/app/src/main/java/com/tom/rv2ide/activities/editor/BaseEditorActivity.kt +++ b/core/app/src/main/java/com/tom/rv2ide/activities/editor/BaseEditorActivity.kt @@ -53,7 +53,9 @@ import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.core.view.updatePaddingRelative +import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import com.blankj.utilcode.constant.MemoryConstants import com.blankj.utilcode.util.ConvertUtils.byte2MemorySize import com.blankj.utilcode.util.FileUtils @@ -126,7 +128,10 @@ import kotlin.math.roundToInt import kotlin.math.roundToLong import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -741,27 +746,44 @@ override fun onApplySystemBarInsets(insets: Insets) { } if (BuildPreferences.isKtIndexingNotificationEnabled) { - // Use IndexingBanner to show progress val indexingBanner = IndexingBanner(this) - - lifecycleScope.launch { - LogStream.outputFlow.collect { logMessage -> - if (Index.isIndexing() && !Initialization.isProjectInitializing.value) { - indexingBanner.updateMessage(logMessage) - } - } - } - + var dismissedForSession = false + indexingBanner.setOnDismissListener { dismissedForSession = true } + lifecycleScope.launch { - combine( - Initialization.isProjectInitializing, - Index.isProjectIndexing - ) { isInitializing, isIndexing -> - !isInitializing && isIndexing - }.collect { shouldShowIndexing -> - if (shouldShowIndexing) { - indexingBanner.show() - } else { + lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { + try { + coroutineScope { + launch { + LogStream.outputFlow.collect { logMessage -> + if (Index.isIndexing() && !Initialization.isProjectInitializing.value) { + indexingBanner.updateMessage(logMessage) + } + } + } + + // Debounce state transitions so rapid per-file/module LSP updates don't strobe the banner + combine( + Initialization.isProjectInitializing, + Index.isProjectIndexing, + ) { isInitializing, isIndexing -> + !isInitializing && isIndexing + } + .distinctUntilChanged() + .collectLatest { shouldShowIndexing -> + if (shouldShowIndexing) { + delay(350) + if (!dismissedForSession) { + indexingBanner.show() + } + } else { + delay(1200) + dismissedForSession = false + indexingBanner.hide() + } + } + } + } finally { indexingBanner.hide() } } @@ -1161,34 +1183,6 @@ override fun onApplySystemBarInsets(insets: Insets) { return filesTreeFragment } - private fun hasNativeFiles(projectRoot: File): Boolean { - val androidMkFile = File(projectRoot, "src/main/jni/Android.mk") - val cmakeListsFile = File(projectRoot, "src/main/jni/CMakeLists.txt") - return androidMkFile.exists() || cmakeListsFile.exists() - } - - private fun isNdkInstalled(): Boolean { - val ndkBuildFile = File(Environment.ANDROID_HOME, "ndk/28.2.13676358/ndk-build") - return ndkBuildFile.exists() - } - - private fun showNdkNotInstalledDialog(context: Context, onDismiss: () -> Unit = {}) { - MaterialAlertDialogBuilder(context) - .setTitle("NDK Not Found") - .setMessage( - "A compatible NDK (version 28.2.13676358) is not installed.\n\n" + - "Native code features will be disabled for this project.\n\n" + - "To enable native development, please install NDK version 28.2.13676358 " + - "open a terminal then run: 'idesetup -y -c -wn'." - ) - .setPositiveButton("OK") { dialog, _ -> - dialog.dismiss() - onDismiss() - } - .setCancelable(false) - .show() - } - fun doSetStatus(text: CharSequence, @GravityInt gravity: Int) { editorViewModel.statusText = text editorViewModel.statusGravity = gravity diff --git a/core/app/src/main/java/com/tom/rv2ide/activities/editor/ProjectHandlerActivity.kt b/core/app/src/main/java/com/tom/rv2ide/activities/editor/ProjectHandlerActivity.kt index 338a929db8..1dcb76c0e0 100644 --- a/core/app/src/main/java/com/tom/rv2ide/activities/editor/ProjectHandlerActivity.kt +++ b/core/app/src/main/java/com/tom/rv2ide/activities/editor/ProjectHandlerActivity.kt @@ -671,11 +671,23 @@ fun initializeProject(buildVariants: Map) { val msg = when (failure) { - PROJECT_DIRECTORY_INACCESSIBLE -> string.msg_project_dir_inaccessible - PROJECT_NOT_DIRECTORY -> string.msg_file_is_not_dir - PROJECT_NOT_FOUND -> string.msg_project_dir_doesnt_exist + PROJECT_DIRECTORY_INACCESSIBLE -> getString(string.msg_project_dir_inaccessible) + PROJECT_NOT_DIRECTORY -> getString(string.msg_file_is_not_dir) + PROJECT_NOT_FOUND -> getString(string.msg_project_dir_doesnt_exist) + TaskExecutionResult.Failure.BUILD_FAILED -> "Gradle configuration/build failed" + TaskExecutionResult.Failure.UNSUPPORTED_GRADLE_VERSION -> + "Unsupported Gradle version" + TaskExecutionResult.Failure.UNSUPPORTED_CONFIGURATION -> + "Unsupported Gradle configuration" + TaskExecutionResult.Failure.UNSUPPORTED_BUILD_ARGUMENT -> + "Unsupported build argument" + TaskExecutionResult.Failure.CONNECTION_ERROR -> + "Could not connect to Gradle daemon" + TaskExecutionResult.Failure.CONNECTION_CLOSED -> + "Gradle tooling connection closed" + TaskExecutionResult.Failure.BUILD_CANCELLED -> "Initialization cancelled" else -> null - }?.let { "$initFailed: ${getString(it)}" } + }?.let { "$initFailed: $it" } flashError(msg ?: initFailed) diff --git a/core/app/src/main/java/com/tom/rv2ide/configurations/FBProperties.kt b/core/app/src/main/java/com/tom/rv2ide/configurations/FBProperties.kt index 9b406d0bf2..5875883aa8 100644 --- a/core/app/src/main/java/com/tom/rv2ide/configurations/FBProperties.kt +++ b/core/app/src/main/java/com/tom/rv2ide/configurations/FBProperties.kt @@ -23,5 +23,9 @@ import com.tom.rv2ide.projects.internal.ProjectManagerImpl */ object FBProperties { - val userProject: String = ProjectManagerImpl.getInstance().projectDir.absolutePath.toString() + val userProject: String + get() = ProjectManagerImpl.getInstance().projectDir.absolutePath + + val userProjectOrNull: String? + get() = runCatching { ProjectManagerImpl.getInstance().projectDir.absolutePath }.getOrNull() } diff --git a/core/app/src/main/java/com/tom/rv2ide/configurations/GCProperties.kt b/core/app/src/main/java/com/tom/rv2ide/configurations/GCProperties.kt index e6b69cd56e..07d91d9794 100644 --- a/core/app/src/main/java/com/tom/rv2ide/configurations/GCProperties.kt +++ b/core/app/src/main/java/com/tom/rv2ide/configurations/GCProperties.kt @@ -23,6 +23,9 @@ import com.tom.rv2ide.projects.internal.ProjectManagerImpl */ object GCProperties { - // user project - val userProject = ProjectManagerImpl.getInstance().projectDir.absolutePath.toString() + val userProject: String + get() = ProjectManagerImpl.getInstance().projectDir.absolutePath + + val userProjectOrNull: String? + get() = runCatching { ProjectManagerImpl.getInstance().projectDir.absolutePath }.getOrNull() } diff --git a/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserDialogFragment.kt b/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserDialogFragment.kt index 8f58442ca8..c6311fc3d9 100644 --- a/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserDialogFragment.kt +++ b/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserDialogFragment.kt @@ -29,8 +29,10 @@ import com.tom.rv2ide.adapter.FileAdapter import com.tom.rv2ide.databinding.DialogFileBrowserBinding import com.tom.rv2ide.R import com.tom.rv2ide.models.FileItem -import com.tom.rv2ide.utils.PathPreferences +import com.tom.rv2ide.utils.Environment as IdeEnvironment +import com.tom.rv2ide.utils.FileBrowserNavigationHelper import com.tom.rv2ide.utils.FileIconManager +import com.tom.rv2ide.utils.PathPreferences import java.io.File import java.io.FileInputStream import java.io.FileOutputStream @@ -55,8 +57,8 @@ class FileBrowserDialogFragment : DialogFragment() { private var operationType: OperationType = OperationType.COPY private var onOperationCompleteListener: (() -> Unit)? = null - private val rootPath: String by lazy { - Environment.getExternalStorageDirectory().path + private val rootPath: String by lazy { + FileBrowserNavigationHelper.defaultStartPath() } private var currentPath: String = "" @@ -73,13 +75,12 @@ class FileBrowserDialogFragment : DialogFragment() { requireArguments().getString(ARG_OPERATION_TYPE, OperationType.COPY.name) ) setStyle(STYLE_NORMAL, android.R.style.Theme_Translucent_NoTitleBar) - - // Initialize currentPath here, BEFORE onViewCreated + val argInitialPath = arguments?.getString(ARG_INITIAL_PATH) - currentPath = when { - argInitialPath != null && File(argInitialPath).exists() -> argInitialPath - else -> PathPreferences.getDialogPath(requireContext(), rootPath) - } + currentPath = FileBrowserNavigationHelper.resolveInitialPath( + argInitialPath ?: PathPreferences.getDialogPath(requireContext(), rootPath), + rootPath + ) } override fun onCreateView( @@ -98,13 +99,20 @@ class FileBrowserDialogFragment : DialogFragment() { setupFab() setupBackPressedHandler() setupCancelOnTouchOutside() - listFiles(currentPath) - animateDialogEntry() binding.gotoMyProj.setOnClickListener { - listFiles(FBProperties.userProject) + listFiles(FBProperties.userProjectOrNull ?: IdeEnvironment.PROJECTS_DIR.absolutePath) + } + binding.tvCurrentPathDialog.setOnClickListener { showQuickJump() } + binding.btnDialogAppHome.setOnClickListener { + IdeEnvironment.HOME?.absolutePath?.let(::listFiles) + } + binding.btnDialogGoPath.setOnClickListener { + FileBrowserNavigationHelper.showGoToPathDialog(requireContext(), currentPath, ::listFiles) } + listFiles(currentPath) + animateDialogEntry() } private fun setupCancelOnTouchOutside() { @@ -138,6 +146,24 @@ class FileBrowserDialogFragment : DialogFragment() { binding.toolbarDialog.setNavigationOnClickListener { handleBackPress() } + + binding.toolbarDialog.menu.add("Quick Jump").apply { + setIcon(R.drawable.ic_folder) + setShowAsAction(android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM) + setOnMenuItemClickListener { + showQuickJump() + true + } + } + } + + private fun showQuickJump() { + FileBrowserNavigationHelper.showQuickJumpDialog( + requireContext(), + currentPath, + FBProperties.userProjectOrNull, + ::listFiles + ) } private fun setupBackPressedHandler() { @@ -185,13 +211,9 @@ class FileBrowserDialogFragment : DialogFragment() { } private fun handleBackPress() { - if (currentPath != rootPath) { - val parent = File(currentPath).parent - if (parent != null) { - listFiles(parent) - } else { - animateDialogExit() - } + val parent = FileBrowserNavigationHelper.parentPath(currentPath) + if (parent != null) { + listFiles(parent) } else { animateDialogExit() } @@ -281,6 +303,11 @@ class FileBrowserDialogFragment : DialogFragment() { return } + if (!destinationDir.canWrite()) { + Toast.makeText(requireContext(), "Destination folder is not writable without root", Toast.LENGTH_SHORT).show() + return + } + if (destinationFile.exists()) { Toast.makeText( requireContext(), @@ -300,7 +327,9 @@ class FileBrowserDialogFragment : DialogFragment() { } // Check if trying to move a directory into itself - if (sourceFile.isDirectory && destinationFile.absolutePath.startsWith(sourceFile.absolutePath)) { + if (sourceFile.isDirectory && + (destinationDir.absolutePath == sourceFile.absolutePath || + destinationDir.absolutePath.startsWith("${sourceFile.absolutePath}${File.separator}"))) { Toast.makeText( requireContext(), "Cannot move a folder into itself", @@ -363,6 +392,11 @@ class FileBrowserDialogFragment : DialogFragment() { return } + if (!destinationDir.canWrite()) { + Toast.makeText(requireContext(), "Destination folder is not writable without root", Toast.LENGTH_SHORT).show() + return + } + if (destinationFile.exists()) { Toast.makeText( requireContext(), @@ -441,68 +475,64 @@ class FileBrowserDialogFragment : DialogFragment() { } } - private fun listFiles(path: String) { + private fun listFiles(rawPath: String) { + val path = FileBrowserNavigationHelper.normalizePath(rawPath) currentPath = path binding.tvCurrentPathDialog.text = path - + val gotoMyProj: MaterialButton = binding.gotoMyProj - - if (currentPath != FBProperties.userProject) { + val targetProjectPath = FBProperties.userProjectOrNull ?: IdeEnvironment.PROJECTS_DIR.absolutePath + gotoMyProj.text = if (FBProperties.userProjectOrNull != null) "Goto My project" else "ACS Projects" + + if (currentPath != targetProjectPath) { if (gotoMyProj.visibility != View.VISIBLE) { gotoMyProj.apply { alpha = 0f visibility = View.VISIBLE animate() - .alpha(1f) - .setDuration(200) - .start() + .alpha(1f) + .setDuration(200) + .start() } } - } else { - if (gotoMyProj.visibility == View.VISIBLE) { - gotoMyProj.animate() + } else if (gotoMyProj.visibility == View.VISIBLE) { + gotoMyProj.animate() .alpha(0f) .setDuration(200) - .withEndAction { - gotoMyProj.visibility = View.GONE - } + .withEndAction { gotoMyProj.visibility = View.GONE } .start() - } } - - // Save the current path + PathPreferences.saveDialogPath(requireContext(), path) - binding.toolbarDialog.navigationIcon = if (path == rootPath) { + binding.toolbarDialog.navigationIcon = if (path == "/") { null } else { ContextCompat.getDrawable(requireContext(), R.drawable.ic_arrow_back) } - val file = File(path) - - if (!file.exists()) { - Toast.makeText(requireContext(), "Directory doesn't exist: ${file.name}", Toast.LENGTH_SHORT).show() - return - } - - if (!file.canRead()) { - Toast.makeText(requireContext(), "Cannot read directory: ${file.name}", Toast.LENGTH_SHORT).show() - return - } - - val filesAndFolders = file.listFiles() - - if (filesAndFolders == null) { - Toast.makeText(requireContext(), "Cannot access folder", Toast.LENGTH_SHORT).show() - return + when (val result = FileBrowserNavigationHelper.readDirectory(path)) { + is FileBrowserNavigationHelper.DirectoryListing.Accessible -> { + fileAdapter.updateData(result.items) + binding.rvFilesDialog.visibility = View.VISIBLE + binding.emptyStateContainerDialog.visibility = View.GONE + } + is FileBrowserNavigationHelper.DirectoryListing.EmptyReadable -> { + fileAdapter.updateData(emptyList()) + binding.rvFilesDialog.visibility = View.GONE + binding.emptyStateContainerDialog.visibility = View.VISIBLE + binding.emptyStateTitleDialog.text = "Folder is Empty" + binding.emptyStateMessageDialog.text = "No items inside $path." + } + is FileBrowserNavigationHelper.DirectoryListing.RestrictedWithoutRoot -> { + fileAdapter.updateData(emptyList()) + binding.rvFilesDialog.visibility = View.GONE + binding.emptyStateContainerDialog.visibility = View.VISIBLE + binding.emptyStateTitleDialog.text = "Protected Directory (No Root)" + binding.emptyStateMessageDialog.text = result.message + } } - val fileItems = filesAndFolders.map { - FileItem(it.name, it.path, it.isDirectory) - }.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) - - fileAdapter.updateData(fileItems) binding.rvFilesDialog.scrollToPosition(0) } diff --git a/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserFragment.kt b/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserFragment.kt index 95ddead4fe..87bd9fe6cd 100644 --- a/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserFragment.kt +++ b/core/app/src/main/java/com/tom/rv2ide/fragments/FileBrowserFragment.kt @@ -44,8 +44,10 @@ import com.tom.rv2ide.models.ExtensionFilter import com.tom.rv2ide.models.FileFilter import com.tom.rv2ide.models.FileItem import com.tom.rv2ide.models.FilterPreferences -import com.tom.rv2ide.utils.PathPreferences +import com.tom.rv2ide.utils.Environment as IdeEnvironment +import com.tom.rv2ide.utils.FileBrowserNavigationHelper import com.tom.rv2ide.utils.FileIconManager +import com.tom.rv2ide.utils.PathPreferences import java.io.File import com.google.android.material.button.MaterialButton @@ -59,10 +61,13 @@ class FileBrowserFragment : Fragment() { private val binding get() = _binding!! private lateinit var fileAdapter: FileAdapter - private val rootPath: String by lazy { - arguments?.getString(ARG_ROOT_PATH) ?: Environment.getExternalStorageDirectory().path + private val rootPath: String by lazy { + FileBrowserNavigationHelper.normalizePath( + arguments?.getString(ARG_ROOT_PATH) ?: FileBrowserNavigationHelper.defaultStartPath() + ) } private var currentPath: String = "" + private var restrictedMessage: String? = null private val filterPrefs = FilterPreferences() private var allFileItems: List = emptyList() @@ -73,21 +78,15 @@ class FileBrowserFragment : Fragment() { val activity = requireActivity() val searchItem = activity.findViewById(R.id.action_search) if (searchItem != null && searchItem.isShown) { - // SearchView is handling the back press, let it collapse isEnabled = false activity.onBackPressedDispatcher.onBackPressed() isEnabled = true return } - - if (currentPath != rootPath) { - val parent = File(currentPath).parent - if (parent != null) { - listFiles(parent) - } else { - isEnabled = false - requireActivity().onBackPressedDispatcher.onBackPressed() - } + + val parent = FileBrowserNavigationHelper.parentPath(currentPath) + if (parent != null) { + listFiles(parent) } else { isEnabled = false requireActivity().onBackPressedDispatcher.onBackPressed() @@ -97,7 +96,10 @@ class FileBrowserFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - currentPath = PathPreferences.getMainPath(requireContext(), rootPath) + currentPath = FileBrowserNavigationHelper.resolveInitialPath( + PathPreferences.getMainPath(requireContext(), rootPath), + rootPath + ) } override fun onCreateView( @@ -111,16 +113,25 @@ class FileBrowserFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - + setupToolbar() setupRecyclerView() setupMenu() setupBackButton() - listFiles(currentPath) - + binding.gotoMyProj.setOnClickListener { - listFiles(FBProperties.userProject) + listFiles(FBProperties.userProjectOrNull ?: IdeEnvironment.PROJECTS_DIR.absolutePath) + } + binding.tvCurrentPath.setOnClickListener { showQuickJump() } + binding.btnEmptyGoUp.setOnClickListener { + FileBrowserNavigationHelper.parentPath(currentPath)?.let(::listFiles) + } + binding.btnEmptyAppHome.setOnClickListener { + IdeEnvironment.HOME?.absolutePath?.let(::listFiles) } + binding.btnEmptyGoPath.setOnClickListener { showGoToPath() } + + listFiles(currentPath) } private fun setupToolbar() { @@ -174,18 +185,16 @@ class FileBrowserFragment : Fragment() { } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { - // Handle home/up button (back arrow) + // Allow stepping up all the way to filesystem root "/" if (menuItem.itemId == android.R.id.home) { - if (currentPath != rootPath) { - val parent = File(currentPath).parent - if (parent != null) { - listFiles(parent) - return true - } + val parent = FileBrowserNavigationHelper.parentPath(currentPath) + if (parent != null) { + listFiles(parent) + return true } return false } - + return handleMenuItemSelected(menuItem) } }, viewLifecycleOwner, Lifecycle.State.RESUMED) @@ -214,6 +223,14 @@ class FileBrowserFragment : Fragment() { private fun handleMenuItemSelected(item: MenuItem): Boolean { return when (item.itemId) { + R.id.action_quick_jump -> { + showQuickJump() + true + } + R.id.action_go_to_path -> { + showGoToPath() + true + } // File type filters R.id.filter_all -> { filterPrefs.fileFilter = FileFilter.ALL @@ -370,7 +387,24 @@ class FileBrowserFragment : Fragment() { fileAdapter.updateData(filteredList) if (filteredList.isEmpty()) { - Toast.makeText(requireContext(), "No files match the filters", Toast.LENGTH_SHORT).show() + binding.rvFiles.visibility = View.GONE + binding.emptyStateContainer.visibility = View.VISIBLE + binding.btnEmptyGoUp.visibility = + if (FileBrowserNavigationHelper.parentPath(currentPath) != null) View.VISIBLE else View.GONE + val restricted = restrictedMessage + if (restricted != null) { + binding.emptyStateTitle.text = "Protected Directory (No Root)" + binding.emptyStateMessage.text = restricted + } else if (allFileItems.isEmpty()) { + binding.emptyStateTitle.text = "Folder is Empty" + binding.emptyStateMessage.text = "No files or folders inside $currentPath." + } else { + binding.emptyStateTitle.text = "No Matching Files" + binding.emptyStateMessage.text = "Try clearing the search query or active filters." + } + } else { + binding.rvFiles.visibility = View.VISIBLE + binding.emptyStateContainer.visibility = View.GONE } } @@ -517,13 +551,29 @@ class FileBrowserFragment : Fragment() { requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, backPressedCallback) } - fun listFiles(path: String) { + private fun showQuickJump() { + FileBrowserNavigationHelper.showQuickJumpDialog( + requireContext(), + currentPath, + FBProperties.userProjectOrNull, + ::listFiles + ) + } + + private fun showGoToPath() { + FileBrowserNavigationHelper.showGoToPathDialog(requireContext(), currentPath, ::listFiles) + } + + fun listFiles(rawPath: String) { + val path = FileBrowserNavigationHelper.normalizePath(rawPath) currentPath = path binding.tvCurrentPath.text = path - + val goToMyProj: MaterialButton = binding.gotoMyProj - - if (currentPath != FBProperties.userProject) { + val targetProjectPath = FBProperties.userProjectOrNull ?: IdeEnvironment.PROJECTS_DIR.absolutePath + goToMyProj.text = if (FBProperties.userProjectOrNull != null) "Goto my project" else "ACS Projects" + + if (currentPath != targetProjectPath) { if (goToMyProj.visibility != View.VISIBLE) { goToMyProj.apply { alpha = 0f @@ -534,22 +584,17 @@ class FileBrowserFragment : Fragment() { .start() } } - } else { - if (goToMyProj.visibility == View.VISIBLE) { - goToMyProj.animate() - .alpha(0f) - .setDuration(200) - .withEndAction { - goToMyProj.visibility = View.GONE - } - .start() - } + } else if (goToMyProj.visibility == View.VISIBLE) { + goToMyProj.animate() + .alpha(0f) + .setDuration(200) + .withEndAction { goToMyProj.visibility = View.GONE } + .start() } - // Save the current path + PathPreferences.saveMainPath(requireContext(), path) - // Update navigation icon and handle clicks - if (path == rootPath) { + if (path == "/") { (requireActivity() as? androidx.appcompat.app.AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(false) } else { (requireActivity() as? androidx.appcompat.app.AppCompatActivity)?.supportActionBar?.apply { @@ -558,18 +603,21 @@ class FileBrowserFragment : Fragment() { } } - val file = File(path) - val filesAndFolders = file.listFiles() - - if (filesAndFolders == null) { - Toast.makeText(requireContext(), "Cannot access this folder", Toast.LENGTH_SHORT).show() - return + when (val result = FileBrowserNavigationHelper.readDirectory(path)) { + is FileBrowserNavigationHelper.DirectoryListing.Accessible -> { + restrictedMessage = null + allFileItems = result.items + } + is FileBrowserNavigationHelper.DirectoryListing.EmptyReadable -> { + restrictedMessage = null + allFileItems = emptyList() + } + is FileBrowserNavigationHelper.DirectoryListing.RestrictedWithoutRoot -> { + restrictedMessage = result.message + allFileItems = emptyList() + } } - allFileItems = filesAndFolders - .map { FileItem(it.name, it.path, it.isDirectory) } - .sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) - applyFilters() binding.rvFiles.scrollToPosition(0) } diff --git a/core/app/src/main/java/com/tom/rv2ide/fragments/InitFragment.kt b/core/app/src/main/java/com/tom/rv2ide/fragments/InitFragment.kt index eb6cd950bb..d11e23a68c 100644 --- a/core/app/src/main/java/com/tom/rv2ide/fragments/InitFragment.kt +++ b/core/app/src/main/java/com/tom/rv2ide/fragments/InitFragment.kt @@ -73,7 +73,12 @@ class InitFragment : Fragment() { } binding.buttonOpenRepo.setOnClickListener { - viewModel.openExistingRepository(GCProperties.userProject) + val projectPath = GCProperties.userProjectOrNull + if (projectPath != null) { + viewModel.openExistingRepository(projectPath) + } else { + Snackbar.make(binding.root, "No project directory is open", Snackbar.LENGTH_SHORT).show() + } } } @@ -84,7 +89,11 @@ class InitFragment : Fragment() { // Repository is ready, MainActivity will handle navigation } RepositoryStatus.ERROR -> { - Snackbar.make(binding.root, "Failed to initialize repository", Snackbar.LENGTH_LONG).show() + val reason = viewModel.operationResult.value + ?.takeIf { !it.success } + ?.message + ?: "Failed to initialize repository" + Snackbar.make(binding.root, reason, Snackbar.LENGTH_LONG).show() } else -> {} } @@ -127,7 +136,7 @@ class InitFragment : Fragment() { # Binary files should be left untouched *.jar binary """.trimIndent() - val userProject = GCProperties.userProject + val userProject = GCProperties.userProjectOrNull ?: return val files = arrayOf("${userProject}/.gitignore", "${userProject}/.gitattributes") val content = arrayOf(ctGitIgnore, ctGitAttributes) @@ -137,26 +146,36 @@ class InitFragment : Fragment() { } private fun showInitializeDialog() { + val projectPath = GCProperties.userProjectOrNull + if (projectPath == null) { + Snackbar.make(binding.root, "No project directory is open", Snackbar.LENGTH_SHORT).show() + return + } val dialogView = layoutInflater.inflate(R.layout.dialog_branch_name, null) val editText = dialogView.findViewById(R.id.editTextBranchName) editText.setText("main") MaterialAlertDialogBuilder(requireContext()) .setTitle("Initialize Repository") - .setMessage("Initialize a new Git repository at:\n${GCProperties.userProject}\n\nChoose initial branch name:") + .setMessage("Initialize a new Git repository at:\n$projectPath\n\nChoose initial branch name:") .setView(dialogView) .setPositiveButton("Initialize") { _, _ -> val branchName = editText.text.toString().trim() val finalBranchName = if (branchName.isBlank()) "main" else branchName createGitIgnoreAndOthers() - viewModel.initializeRepository(GCProperties.userProject, finalBranchName) + viewModel.initializeRepository(projectPath, finalBranchName) } .setNegativeButton("Cancel", null) .show() } private fun showCloneDialog() { + val projectPath = GCProperties.userProjectOrNull + if (projectPath == null) { + Snackbar.make(binding.root, "No project directory is open", Snackbar.LENGTH_SHORT).show() + return + } val dialogView = layoutInflater.inflate(R.layout.dialog_clone, null) val editTextUrl = dialogView.findViewById(R.id.editTextCloneUrl) val editTextUsername = dialogView.findViewById(R.id.editTextCloneUsername) @@ -164,15 +183,15 @@ class InitFragment : Fragment() { MaterialAlertDialogBuilder(requireContext()) .setTitle("Clone Repository") - .setMessage("Clone to: ${GCProperties.userProject}") + .setMessage("Clone to: $projectPath") .setView(dialogView) .setPositiveButton("Clone") { _, _ -> - val url = editTextUrl.text.toString() - val username = editTextUsername.text.toString().takeIf { it.isNotBlank() } - val password = editTextPassword.text.toString().takeIf { it.isNotBlank() } + val url = editTextUrl.text?.toString()?.trim().orEmpty() + val username = editTextUsername.text?.toString()?.trim()?.takeIf { it.isNotBlank() } + val password = editTextPassword.text?.toString()?.takeIf { it.isNotBlank() } if (url.isNotBlank()) { - viewModel.cloneRepository(url, GCProperties.userProject, username, password) + viewModel.cloneRepository(url, projectPath, username, password) } else { Snackbar.make(binding.root, "URL cannot be empty", Snackbar.LENGTH_SHORT).show() } diff --git a/core/app/src/main/java/com/tom/rv2ide/fragments/MainFragment.kt b/core/app/src/main/java/com/tom/rv2ide/fragments/MainFragment.kt index 9604f1f0be..58da7e7f54 100644 --- a/core/app/src/main/java/com/tom/rv2ide/fragments/MainFragment.kt +++ b/core/app/src/main/java/com/tom/rv2ide/fragments/MainFragment.kt @@ -160,34 +160,7 @@ class MainFragment : BaseFragment() { recyclerView.layoutManager = LinearLayoutManager(requireContext()) - val projectDirProjects = - GeneralFileUtils.listDirsInDirectory(Environment.PROJECTS_DIR).filter { - isValidAndroidProject(it) - } - - val recentProjectPaths = WizardPreferences.getRecentProjects(requireContext()) - val recentProjectFiles = - recentProjectPaths.mapNotNull { path -> - val file = File(path) - if (file.exists() && file.isDirectory && isValidAndroidProject(file)) file else null - } - - val allProjectsMap = mutableMapOf() - - recentProjectFiles.forEach { file -> allProjectsMap[file.absolutePath] = file } - - projectDirProjects.forEach { file -> allProjectsMap[file.absolutePath] = file } - - val projectDirs = - allProjectsMap.values - .toList() - .sortedWith( - compareBy { project -> - val recentIndex = recentProjectPaths.indexOf(project.absolutePath) - if (recentIndex >= 0) recentIndex else Int.MAX_VALUE - } - .thenByDescending { it.lastModified() } - ) + val projectDirs = loadAvailableProjects() var adapter: ProjectsListAdapter? = null @@ -207,39 +180,7 @@ class MainFragment : BaseFragment() { }, onProjectLongClick = { project -> showProjectOptionsDialog(project) { - val updatedProjectDirProjects = - GeneralFileUtils.listDirsInDirectory(Environment.PROJECTS_DIR).filter { - isValidAndroidProject(it) - } - val updatedRecentProjectPaths = - WizardPreferences.getRecentProjects(requireContext()) - val updatedRecentProjectFiles = - updatedRecentProjectPaths.mapNotNull { path -> - val file = File(path) - if (file.exists() && file.isDirectory && isValidAndroidProject(file)) file - else null - } - - val updatedAllProjectsMap = mutableMapOf() - updatedRecentProjectFiles.forEach { file -> - updatedAllProjectsMap[file.absolutePath] = file - } - updatedProjectDirProjects.forEach { file -> - updatedAllProjectsMap[file.absolutePath] = file - } - - val updatedDirs = - updatedAllProjectsMap.values - .toList() - .sortedWith( - compareBy { proj -> - val recentIndex = - updatedRecentProjectPaths.indexOf(proj.absolutePath) - if (recentIndex >= 0) recentIndex else Int.MAX_VALUE - } - .thenByDescending { it.lastModified() } - ) - + val updatedDirs = loadAvailableProjects() adapter?.updateProjects(updatedDirs) if (updatedDirs.isEmpty()) { @@ -636,6 +577,39 @@ class MainFragment : BaseFragment() { bottomSheet.show() } + private fun loadAvailableProjects(): List { + val ctx = requireContext() + val recentPaths = WizardPreferences.getRecentProjects(ctx) + val recentByCanonical = mutableMapOf() + val deduped = linkedMapOf() + + fun canonicalKey(file: File): String = + runCatching { file.canonicalPath }.getOrDefault(file.absolutePath) + + recentPaths.forEachIndexed { index, path -> + val file = File(path) + if (file.exists() && file.isDirectory && isValidAndroidProject(file)) { + val key = canonicalKey(file) + recentByCanonical.putIfAbsent(key, index) + deduped.putIfAbsent(key, file) + } + } + + // Scan private ACSProjects first, then legacy shared AndroidIDEProjects so older projects stay visible + listOfNotNull(Environment.PROJECTS_DIR, Environment.LEGACY_PROJECTS_DIR) + .filter { it.exists() && it.isDirectory } + .forEach { root -> + GeneralFileUtils.listDirsInDirectory(root) + .filter { isValidAndroidProject(it) } + .forEach { dir -> deduped.putIfAbsent(canonicalKey(dir), dir) } + } + + return deduped.values.sortedWith( + compareBy { recentByCanonical[canonicalKey(it)] ?: Int.MAX_VALUE } + .thenByDescending { it.lastModified() } + ) + } + private fun doClone(repo: String?, branch: String? = null, options: List = emptyList()) { if (repo.isNullOrBlank()) { log.warn("Unable to clone repo. Invalid repo URL : {}'", repo) @@ -643,24 +617,45 @@ class MainFragment : BaseFragment() { return } - var url = repo.trim() + val cleanedInput = repo.trim().trimEnd('/') + if (cleanedInput.isBlank()) { + flashError(string.git_clone_invalid_url) + return + } + + var url = cleanedInput if (!url.endsWith(".git")) { url += ".git" } + val repoName = url.removeSuffix(".git").substringAfterLast('/') + if (repoName.isBlank() || repoName == "." || repoName == "..") { + flashError(string.git_clone_invalid_url) + return + } + + val projectsRoot = Environment.mkdirIfNotExits(Environment.PROJECTS_DIR) + val targetDir = File(projectsRoot, repoName) + if (targetDir.exists() && !targetDir.listFiles().isNullOrEmpty()) { + showCloneError( + IllegalStateException( + "Destination folder already exists and is not empty:\n${targetDir.absolutePath}" + ) + ) + return + } + val builder = DialogUtils.newMaterialDialogBuilder(requireContext()) val binding = LayoutDialogProgressBinding.inflate(layoutInflater) binding.message.visibility = View.VISIBLE builder.setTitle(string.git_clone_in_progress) - builder.setMessage(url) + builder.setMessage("$url\n-> ${targetDir.absolutePath}") builder.setView(binding.root) builder.setCancelable(false) - val repoName = url.substringAfterLast('/').substringBeforeLast(".git") - val targetDir = File(Environment.PROJECTS_DIR, repoName) - + val dirExistedBefore = targetDir.exists() val progress = GitCloneProgressMonitor(binding.progress, binding.message) val coroutineScope = (activity as? BaseIDEActivity?)?.activityScope ?: viewLifecycleScope @@ -690,8 +685,11 @@ class MainFragment : BaseFragment() { cloneCommand.call() } catch (err: Throwable) { + if (!dirExistedBefore && targetDir.exists()) { + targetDir.deleteRecursively() + } if (!progress.isCancelled) { - err.printStackTrace() + log.error("Failed to clone repository {}", url, err) withContext(Dispatchers.Main) { getDialog?.invoke()?.also { if (it.isShowing) it.dismiss() } showCloneError(err) @@ -704,7 +702,13 @@ class MainFragment : BaseFragment() { git?.close() } finally { val success = git != null + if (success) { + Environment.trySymlinkToLegacyProjects(targetDir) + } withContext(Dispatchers.Main) { + if (success) { + WizardPreferences.addRecentProject(requireContext(), targetDir.absolutePath) + } getDialog?.invoke()?.also { dialog -> if (dialog.isShowing) dialog.dismiss() if (success) flashSuccess(string.git_clone_success) @@ -729,9 +733,13 @@ class MainFragment : BaseFragment() { return } + val message = + error.localizedMessage?.takeIf { it.isNotBlank() } + ?: error.message?.takeIf { it.isNotBlank() } + ?: error.javaClass.simpleName val builder = DialogUtils.newMaterialDialogBuilder(requireContext()) builder.setTitle(string.git_clone_failed) - builder.setMessage(error.localizedMessage) + builder.setMessage(message) builder.setPositiveButton(android.R.string.ok, null) builder.show() } diff --git a/core/app/src/main/java/com/tom/rv2ide/fragments/TerminalFragment.kt b/core/app/src/main/java/com/tom/rv2ide/fragments/TerminalFragment.kt index 6495db16f2..10115e2f9e 100644 --- a/core/app/src/main/java/com/tom/rv2ide/fragments/TerminalFragment.kt +++ b/core/app/src/main/java/com/tom/rv2ide/fragments/TerminalFragment.kt @@ -23,6 +23,7 @@ import com.google.android.material.tabs.TabLayout import com.tom.rv2ide.R import com.tom.rv2ide.fragments.terminal.* import com.termux.app.TermuxService +import com.termux.shared.interact.ShareUtils import com.termux.shared.logger.Logger import com.termux.terminal.TerminalEmulator import com.termux.terminal.TerminalSession @@ -71,18 +72,19 @@ class TerminalFragment : Fragment() { override fun onScale(scale: Float) = scale.coerceIn(0.5f, 2.0f) override fun onSingleTapUp(e: MotionEvent?) { if (sessionManager.currentSession != null) { + terminalView?.requestFocus() (requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .showSoftInput(terminalView, InputMethodManager.SHOW_IMPLICIT) } } override fun shouldBackButtonBeMappedToEscape() = false - override fun shouldEnforceCharBasedInput() = true + override fun shouldEnforceCharBasedInput() = false override fun shouldUseCtrlSpaceWorkaround() = false override fun isTerminalViewSelected() = true override fun copyModeChanged(copyMode: Boolean) {} override fun onKeyDown(keyCode: Int, e: KeyEvent?, session: TerminalSession?) = false override fun onKeyUp(keyCode: Int, e: KeyEvent?) = false - override fun onLongPress(event: MotionEvent?) = true + override fun onLongPress(event: MotionEvent?) = false override fun readControlKey() = extraKeysHandler.isCtrlPressed() override fun readAltKey() = extraKeysHandler.isAltPressed() override fun readShiftKey() = false @@ -115,8 +117,21 @@ class TerminalFragment : Fragment() { sessionManager.onSessionFinished(finishedSession, termuxService) } - override fun onCopyTextToClipboard(session: TerminalSession, text: String) {} - override fun onPasteTextFromClipboard(session: TerminalSession?) {} + override fun onCopyTextToClipboard(session: TerminalSession, text: String) { + val ctx = context ?: return + if (text.isNotEmpty()) { + ShareUtils.copyTextToClipboard(ctx, text) + } + } + + override fun onPasteTextFromClipboard(session: TerminalSession?) { + val ctx = context ?: return + val emulator = terminalView?.mEmulator ?: return + val text = ShareUtils.getTextStringFromClipboardIfSet(ctx, true) + if (!text.isNullOrEmpty()) { + emulator.paste(text) + } + } override fun onBell(session: TerminalSession) {} override fun onColorsChanged(session: TerminalSession) {} override fun onTerminalCursorStateChange(state: Boolean) {} diff --git a/core/app/src/main/java/com/tom/rv2ide/git/GitManager.kt b/core/app/src/main/java/com/tom/rv2ide/git/GitManager.kt index 3768bb3fe1..5f83d74fac 100644 --- a/core/app/src/main/java/com/tom/rv2ide/git/GitManager.kt +++ b/core/app/src/main/java/com/tom/rv2ide/git/GitManager.kt @@ -508,19 +508,37 @@ class GitManager(private val projectPath: String) { } } + @Volatile + var lastError: String? = null + private set + fun clone(remoteUrl: String, localPath: String, username: String? = null, password: String? = null): Boolean { + lastError = null + val url = remoteUrl.trim() + if (url.isEmpty()) { + lastError = "Repository URL cannot be empty" + return false + } + val targetDir = File(localPath) + val existingEntries = targetDir.listFiles()?.filter { it.name != ".gitignore" && it.name != ".gitattributes" } + if (targetDir.exists() && !existingEntries.isNullOrEmpty()) { + lastError = "Target directory is not empty: ${targetDir.absolutePath}" + return false + } return try { val cloneCommand = Git.cloneRepository() - cloneCommand.setURI(remoteUrl) - cloneCommand.setDirectory(File(localPath)) - - cloneCommand.setCredentialsProvider( - org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider( - username ?: "", - password ?: "" + cloneCommand.setURI(url) + cloneCommand.setDirectory(targetDir) + + if (!username.isNullOrBlank() || !password.isNullOrBlank()) { + cloneCommand.setCredentialsProvider( + org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider( + username ?: "", + password ?: "" + ) ) - ) - + } + git = cloneCommand.call() repository = git?.repository loadGitIgnore() @@ -528,6 +546,7 @@ class GitManager(private val projectPath: String) { true } catch (e: Exception) { e.printStackTrace() + lastError = e.localizedMessage?.takeIf { it.isNotBlank() } ?: e.message ?: "Clone failed" false } } diff --git a/core/app/src/main/java/com/tom/rv2ide/handlers/EditorBuildEventListener.kt b/core/app/src/main/java/com/tom/rv2ide/handlers/EditorBuildEventListener.kt index 2e55222a35..deef15ec49 100644 --- a/core/app/src/main/java/com/tom/rv2ide/handlers/EditorBuildEventListener.kt +++ b/core/app/src/main/java/com/tom/rv2ide/handlers/EditorBuildEventListener.kt @@ -30,6 +30,7 @@ import com.tom.rv2ide.preferences.internal.GeneralPreferences import com.tom.rv2ide.projects.IProjectManager import com.tom.rv2ide.resources.R.string import com.tom.rv2ide.services.builder.GradleBuildService +import com.tom.rv2ide.setup.Setup import com.tom.rv2ide.tooling.api.messages.result.BuildInfo import com.tom.rv2ide.tooling.events.ProgressEvent import com.tom.rv2ide.tooling.events.configuration.ProjectConfigurationStartEvent @@ -51,6 +52,7 @@ class EditorBuildEventListener : GradleBuildService.EventListener { private var enabled = true private var activityReference: WeakReference = WeakReference(null) private var ndkCheckPerformed = false + private val detectedMissingTools = LinkedHashSet() companion object { @@ -67,16 +69,19 @@ class EditorBuildEventListener : GradleBuildService.EventListener { this.activityReference = WeakReference(activity) this.enabled = true this.ndkCheckPerformed = false // Reset NDK check when activity is set + this.detectedMissingTools.clear() } fun release() { activityReference.clear() this.enabled = false this.ndkCheckPerformed = false + this.detectedMissingTools.clear() } override fun prepareBuild(buildInfo: BuildInfo) { checkActivity("prepareBuild") ?: return + detectedMissingTools.clear() val isFirstBuild = GeneralPreferences.isFirstBuild activity.setStatus( @@ -128,15 +133,29 @@ class EditorBuildEventListener : GradleBuildService.EventListener { activity.editorViewModel.isBuildInProgress = false activity.flashError(R.string.build_status_failed) + + val missingTools = detectedMissingTools.toList() + detectedMissingTools.clear() + val hostActivity = _activity + if (missingTools.isNotEmpty() && hostActivity != null && !hostActivity.isFinishing && !hostActivity.isDestroyed) { + Setup(hostActivity).promptMissingTools(missingTools) { installed -> + if (installed) { + hostActivity.flashSuccess("Missing build dependencies installed. Run the build again.") + } + } + } } override fun onOutput(line: String?) { checkActivity("onOutput") ?: return - line?.let { activity.appendBuildOutput(it) } - // TODO This can be handled better when ProgressEvents are received from Tooling API server - if (line!!.contains("BUILD SUCCESSFUL") || line.contains("BUILD FAILED")) { - activity.setStatus(line) + line?.let { + Setup.detectMissingToolCommand(it)?.let { cmd -> detectedMissingTools.add(cmd) } + activity.appendBuildOutput(it) + // TODO This can be handled better when ProgressEvents are received from Tooling API server + if (it.contains("BUILD SUCCESSFUL") || it.contains("BUILD FAILED")) { + activity.setStatus(it) + } } } @@ -168,20 +187,16 @@ class EditorBuildEventListener : GradleBuildService.EventListener { } /** Check if NDK is installed */ - private fun isNdkInstalled(): Boolean { - val ndkBuildFile = File(Environment.ANDROID_HOME, "ndk/28.2.13676358/ndk-build") - return ndkBuildFile.exists() - } + private fun isNdkInstalled(): Boolean = Environment.isNdkInstalled() /** Show dialog when NDK is not installed but required */ private fun showNdkNotInstalledDialog(context: Context, onDismiss: () -> Unit = {}) { MaterialAlertDialogBuilder(context) .setTitle("NDK Not Found") .setMessage( - "A compatible NDK (version 28.2.13676358) is not installed.\n\n" + + "No installed Android NDK was found under ${File(Environment.ANDROID_HOME, "ndk").absolutePath}.\n\n" + "Native code features will be disabled for this project.\n\n" + - "To enable native development, please install NDK version 28.2.13676358 " + - "open a terminal then run: 'idesetup -y -c -wn'." + "To enable native development, install an NDK via IDE Configurations or open a terminal and run 'idesetup -y -c -wn'." ) .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() diff --git a/core/app/src/main/java/com/tom/rv2ide/handlers/system/installer/IPackageInstaller.kt b/core/app/src/main/java/com/tom/rv2ide/handlers/system/installer/IPackageInstaller.kt index 6959177107..3b4454d9f2 100644 --- a/core/app/src/main/java/com/tom/rv2ide/handlers/system/installer/IPackageInstaller.kt +++ b/core/app/src/main/java/com/tom/rv2ide/handlers/system/installer/IPackageInstaller.kt @@ -28,6 +28,7 @@ class IPackageInstaller { companion object { private const val TAG = "IPackageInstaller" + private const val MAX_LOG_LINES = 40 } @Throws(IOException::class, IllegalArgumentException::class) @@ -43,16 +44,16 @@ class IPackageInstaller { throw IllegalArgumentException("Path is not a file: $xzFilePath") } + var createdOutputDir = false if (!outputDirectory.exists()) { - val created = outputDirectory.mkdirs() - Log.d(TAG, "Created output directory: $created") + createdOutputDir = outputDirectory.mkdirs() + Log.d(TAG, "Created output directory: $createdOutputDir") } if (!outputDirectory.isDirectory) { throw IllegalArgumentException("Output path is not a directory: $outputDir") } - // Check if output directory is writable if (!outputDirectory.canWrite()) { throw IllegalArgumentException("Output directory is not writable: $outputDir") } @@ -72,7 +73,7 @@ class IPackageInstaller { val processBuilder = ProcessBuilder( tarBinary.absolutePath, - "-xvf", // verbose to see what's happening + "-xf", xzFile.absolutePath, "-C", outputDirectory.absolutePath, @@ -88,29 +89,25 @@ class IPackageInstaller { val process = processBuilder.start() - val outputLines = mutableListOf() - val errorLines = mutableListOf() + // Keep only recent diagnostic lines so huge archives (like the NDK) don't bloat memory + val recentOutput = ArrayDeque(MAX_LOG_LINES) + val recentErrors = ArrayDeque(MAX_LOG_LINES) - // Capture stdout val outputReader = Thread { try { process.inputStream.bufferedReader().useLines { lines -> - lines.forEach { line -> - outputLines.add(line) - Log.d(TAG, "tar stdout: $line") - } + lines.forEach { line -> appendBounded(recentOutput, line) } } } catch (e: Exception) { Log.e(TAG, "Error reading stdout", e) } } - // Capture stderr val errorReader = Thread { try { process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line -> - errorLines.add(line) + appendBounded(recentErrors, line) Log.e(TAG, "tar stderr: $line") } } @@ -124,30 +121,39 @@ class IPackageInstaller { val exitCode = process.waitFor() - outputReader.join(5000) // Wait max 5 seconds + outputReader.join(5000) errorReader.join(5000) - // List what's in the output directory val extractedFiles = outputDirectory.listFiles() - Log.d(TAG, "Files in output directory: ${extractedFiles?.size ?: 0}") - extractedFiles?.forEach { file -> - Log.d(TAG, " - ${file.name} (${if (file.isDirectory) "dir" else "file"})") - } - if (exitCode != 0) { + if (createdOutputDir && extractedFiles.isNullOrEmpty()) { + outputDirectory.delete() + } val errorMsg = "tar extraction failed with exit code: $exitCode\n" + - "stdout: ${outputLines.joinToString("\n")}\n" + - "stderr: ${errorLines.joinToString("\n")}" + "stdout: ${recentOutput.joinToString("\n")}\n" + + "stderr: ${recentErrors.joinToString("\n")}" Log.e(TAG, errorMsg) throw IOException(errorMsg) } if (extractedFiles.isNullOrEmpty()) { + if (createdOutputDir) { + outputDirectory.delete() + } throw IOException("Extraction completed but no files found in output directory") } - Log.d(TAG, "Extraction successful!") + Log.d(TAG, "Extraction completed (${extractedFiles.size} top-level entries)") + } + + private fun appendBounded(buffer: ArrayDeque, line: String) { + synchronized(buffer) { + if (buffer.size >= MAX_LOG_LINES) { + buffer.removeFirst() + } + buffer.addLast(line) + } } fun extractXzArchiveSimple(xzFilePath: String, outputDir: String): Boolean { diff --git a/core/app/src/main/java/com/tom/rv2ide/indexing/views/IndexingBanner.kt b/core/app/src/main/java/com/tom/rv2ide/indexing/views/IndexingBanner.kt index 95f1914930..c42c06b401 100644 --- a/core/app/src/main/java/com/tom/rv2ide/indexing/views/IndexingBanner.kt +++ b/core/app/src/main/java/com/tom/rv2ide/indexing/views/IndexingBanner.kt @@ -19,12 +19,18 @@ package com.tom.rv2ide.indexing.views import android.animation.ObjectAnimator import android.app.Activity +import android.os.Handler +import android.os.Looper +import android.view.Gravity import android.view.LayoutInflater +import android.view.View import android.view.ViewGroup +import android.widget.FrameLayout import androidx.annotation.DrawableRes import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.fragment.app.Fragment +import com.tom.rv2ide.R import com.tom.rv2ide.databinding.LayoutIndexingBannerBinding /* @@ -40,102 +46,107 @@ class IndexingBanner private constructor( private var binding: LayoutIndexingBannerBinding? = null private var isShowing = false + private var onDismissListener: (() -> Unit)? = null + private val mainHandler = Handler(Looper.getMainLooper()) + private val activeAnimators = mutableListOf() + private var pendingHideRunnable: Runnable? = null // Backward compatibility: Constructor for existing usage constructor(activity: Activity) : this(activity, null, null, null) + fun setOnDismissListener(listener: (() -> Unit)?) { + onDismissListener = listener + } + /** - * Show the indexing banner with slide-down animation + * Show the indexing banner cleanly below the editor toolbar so toolbar actions stay clickable. * @param autoHideAfterMillis Optional duration in milliseconds after which banner will auto-hide. Pass null to disable auto-hide. */ fun show(autoHideAfterMillis: Long? = null) { - if (isShowing) return + if (activity.isFinishing || activity.isDestroyed) return + + // Cancel any in-flight hide animation before deciding whether we are already visible + cancelAnimations() + if (isShowing && binding != null) { + scheduleAutoHide(autoHideAfterMillis) + return + } - val rootView = activity.findViewById(android.R.id.content) + val rootView = activity.findViewById(android.R.id.content) ?: return + removeFromParent(binding?.root) - // Inflate layout with data binding - binding = LayoutIndexingBannerBinding.inflate(LayoutInflater.from(activity)).apply { + val newBinding = LayoutIndexingBannerBinding.inflate(LayoutInflater.from(activity)).apply { title = initialTitle ?: "Indexing project..." message = initialMessage ?: "Preparing..." - - // Set icon manually + this@IndexingBanner.iconResId?.let { iconImageView.setImageResource(it) - iconImageView.visibility = android.view.View.VISIBLE + iconImageView.visibility = View.VISIBLE } ?: run { - iconImageView.visibility = android.view.View.GONE + iconImageView.visibility = View.GONE + } + + // Allow dismissing immediately by tapping the banner + bannerContainer.setOnClickListener { + hide() + onDismissListener?.invoke() } } + binding = newBinding - // Add to root view with proper layout params - val layoutParams = ViewGroup.LayoutParams( + val sideMargin = dpToPx(16) + val layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT - ) - rootView.addView(binding?.root, 0, layoutParams) - - // Get status bar height and apply padding after view is added - binding?.bannerContainer?.post { - ViewCompat.getRootWindowInsets(rootView)?.let { insets -> - val statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top - binding?.bannerContainer?.setPadding( - binding?.bannerContainer?.paddingLeft ?: 0, - (binding?.bannerContainer?.paddingTop ?: 0) + statusBarHeight, - binding?.bannerContainer?.paddingRight ?: 0, - binding?.bannerContainer?.paddingBottom ?: 0 - ) - } + ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.TOP + ).apply { + marginStart = sideMargin + marginEnd = sideMargin + topMargin = computeSafeTopMargin(rootView) } + rootView.addView(newBinding.root, layoutParams) - // Dynamic Island style animation - elastic drop down - binding?.bannerContainer?.apply { - // Start from collapsed (scaled down) - scaleY = 0f - scaleX = 0.95f - alpha = 0f - translationY = -100f - pivotY = 0f - pivotX = width / 2f - - post { - // Animate scale Y (drop down effect) - ObjectAnimator.ofFloat(this, "scaleY", 0f, 1.1f, 0.95f, 1f).apply { - duration = 300 - interpolator = android.view.animation.OvershootInterpolator(1.2f) - start() - } - - // Animate scale X (slight width bounce) - ObjectAnimator.ofFloat(this, "scaleX", 0.95f, 1.02f, 1f).apply { - duration = 200 - interpolator = android.view.animation.DecelerateInterpolator() - start() - } - - // Animate translation (smooth drop) - ObjectAnimator.ofFloat(this, "translationY", -50f, 10f, 0f).apply { - duration = 250 - interpolator = android.view.animation.OvershootInterpolator(0.8f) - start() - } - - // Animate alpha (fade in) - ObjectAnimator.ofFloat(this, "alpha", 0f, 1f).apply { - duration = 200 - interpolator = android.view.animation.DecelerateInterpolator() - start() + isShowing = true + + val banner = newBinding.bannerContainer + banner.scaleY = 0f + banner.scaleX = 0.95f + banner.alpha = 0f + banner.translationY = -40f + banner.pivotY = 0f + + banner.post { + if (binding !== newBinding || !isShowing) return@post + + // Refresh top margin once layout bounds of editor_toolbar are guaranteed + (newBinding.root.layoutParams as? ViewGroup.MarginLayoutParams)?.let { lp -> + val updatedTop = computeSafeTopMargin(rootView) + if (lp.topMargin != updatedTop) { + lp.topMargin = updatedTop + newBinding.root.layoutParams = lp } } - } - isShowing = true - - // Auto-hide if duration specified - autoHideAfterMillis?.let { duration -> - binding?.root?.postDelayed({ - hide() - }, duration) + banner.pivotX = banner.width / 2f + startAnimator(ObjectAnimator.ofFloat(banner, "scaleY", 0f, 1.05f, 1f).apply { + duration = 250 + interpolator = android.view.animation.OvershootInterpolator(1.0f) + }) + startAnimator(ObjectAnimator.ofFloat(banner, "scaleX", 0.95f, 1f).apply { + duration = 200 + interpolator = android.view.animation.DecelerateInterpolator() + }) + startAnimator(ObjectAnimator.ofFloat(banner, "translationY", -30f, 0f).apply { + duration = 220 + interpolator = android.view.animation.DecelerateInterpolator() + }) + startAnimator(ObjectAnimator.ofFloat(banner, "alpha", 0f, 1f).apply { + duration = 180 + interpolator = android.view.animation.DecelerateInterpolator() + }) } + + scheduleAutoHide(autoHideAfterMillis) } /** @@ -159,9 +170,9 @@ class IndexingBanner private constructor( binding?.iconImageView?.let { imageView -> if (iconResId != null && iconResId != 0) { imageView.setImageResource(iconResId) - imageView.visibility = android.view.View.VISIBLE + imageView.visibility = View.VISIBLE } else { - imageView.visibility = android.view.View.GONE + imageView.visibility = View.GONE } } } @@ -170,48 +181,90 @@ class IndexingBanner private constructor( * Hide the banner with slide-up animation */ fun hide() { - if (!isShowing || binding == null) return + val activeBinding = binding ?: run { + isShowing = false + return + } + if (!isShowing) return - val banner = binding?.bannerContainer ?: return - val rootView = activity.findViewById(android.R.id.content) + isShowing = false + cancelAnimations() + + val banner = activeBinding.bannerContainer + val viewToRemove = activeBinding.root + // Detach reference immediately so a fast subsequent show() cannot collide with removal + binding = null banner.pivotY = 0f banner.pivotX = banner.width / 2f - - // Animate scale Y (collapse up) - ObjectAnimator.ofFloat(banner, "scaleY", 1f, 1.05f, 0f).apply { - duration = 200 - interpolator = android.view.animation.AnticipateInterpolator(1.5f) - start() - } - - // Animate scale X (slight squeeze) - ObjectAnimator.ofFloat(banner, "scaleX", 1f, 0.98f, 0.95f).apply { - duration = 200 + + startAnimator(ObjectAnimator.ofFloat(banner, "scaleY", banner.scaleY, 0f).apply { + duration = 180 interpolator = android.view.animation.AccelerateInterpolator() - start() - } - - // Animate translation (pull up) - ObjectAnimator.ofFloat(banner, "translationY", 0f, -20f, -60f).apply { - duration = 200 - interpolator = android.view.animation.AccelerateInterpolator(1.2f) - start() - } - - // Animate alpha (fade out) - ObjectAnimator.ofFloat(banner, "alpha", 1f, 0.7f, 0f).apply { - duration = 200 + }) + startAnimator(ObjectAnimator.ofFloat(banner, "scaleX", banner.scaleX, 0.95f).apply { + duration = 180 + interpolator = android.view.animation.AccelerateInterpolator() + }) + startAnimator(ObjectAnimator.ofFloat(banner, "translationY", banner.translationY, -40f).apply { + duration = 180 interpolator = android.view.animation.AccelerateInterpolator() - start() - - // Remove from view hierarchy after animation - banner.postDelayed({ - rootView.removeView(binding?.root) - binding = null - isShowing = false - }, 500) + }) + startAnimator(ObjectAnimator.ofFloat(banner, "alpha", banner.alpha, 0f).apply { + duration = 180 + interpolator = android.view.animation.AccelerateInterpolator() + }) + + val hideTask = Runnable { + removeFromParent(viewToRemove) + pendingHideRunnable = null + } + pendingHideRunnable = hideTask + mainHandler.postDelayed(hideTask, 190) + } + + private fun computeSafeTopMargin(rootView: ViewGroup): Int { + val statusBarHeight = ViewCompat.getRootWindowInsets(rootView) + ?.getInsets(WindowInsetsCompat.Type.statusBars())?.top ?: 0 + val toolbar = activity.findViewById(R.id.editor_toolbar) + if (toolbar != null && toolbar.isShown && toolbar.height > 0) { + val toolbarLoc = IntArray(2) + val rootLoc = IntArray(2) + toolbar.getLocationInWindow(toolbarLoc) + rootView.getLocationInWindow(rootLoc) + val belowToolbar = (toolbarLoc[1] - rootLoc[1]) + toolbar.height + dpToPx(8) + if (belowToolbar > statusBarHeight) { + return belowToolbar + } } + return statusBarHeight + dpToPx(8) + } + + private fun scheduleAutoHide(autoHideAfterMillis: Long?) { + autoHideAfterMillis ?: return + val task = Runnable { hide() } + pendingHideRunnable = task + mainHandler.postDelayed(task, autoHideAfterMillis) + } + + private fun startAnimator(animator: ObjectAnimator) { + activeAnimators.add(animator) + animator.start() + } + + private fun cancelAnimations() { + pendingHideRunnable?.let { mainHandler.removeCallbacks(it) } + pendingHideRunnable = null + activeAnimators.forEach { it.cancel() } + activeAnimators.clear() + } + + private fun removeFromParent(view: View?) { + (view?.parent as? ViewGroup)?.removeView(view) + } + + private fun dpToPx(dp: Int): Int { + return (dp * activity.resources.displayMetrics.density).toInt() } /** diff --git a/core/app/src/main/java/com/tom/rv2ide/provider/IDEDocumentsProvider.java b/core/app/src/main/java/com/tom/rv2ide/provider/IDEDocumentsProvider.java index ee823e6e85..d3370ff79a 100644 --- a/core/app/src/main/java/com/tom/rv2ide/provider/IDEDocumentsProvider.java +++ b/core/app/src/main/java/com/tom/rv2ide/provider/IDEDocumentsProvider.java @@ -186,8 +186,11 @@ public Cursor queryChildDocuments(String parentDocumentId, String[] projection, final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); final File parent = getFileForDocId(parentDocumentId); - for (File file : parent.listFiles()) { - includeFile(result, null, file); + final File[] children = parent.listFiles(); + if (children != null) { + for (File file : children) { + includeFile(result, null, file); + } } return result; } @@ -220,7 +223,10 @@ public Cursor querySearchDocuments(String rootId, String query, String[] project } if (isInsideHome) { if (file.isDirectory()) { - Collections.addAll(pending, file.listFiles()); + final File[] children = file.listFiles(); + if (children != null) { + Collections.addAll(pending, children); + } } else { if (file.getName().toLowerCase(Locale.ROOT).contains(query)) { includeFile(result, null, file); diff --git a/core/app/src/main/java/com/tom/rv2ide/services/builder/GradleBuildService.kt b/core/app/src/main/java/com/tom/rv2ide/services/builder/GradleBuildService.kt index fa30ece555..94d9478744 100644 --- a/core/app/src/main/java/com/tom/rv2ide/services/builder/GradleBuildService.kt +++ b/core/app/src/main/java/com/tom/rv2ide/services/builder/GradleBuildService.kt @@ -119,6 +119,9 @@ class GradleBuildService : val gradlew = File(projectRoot, "gradlew") val gradleWrapperJar = File(projectRoot, "gradle/wrapper/gradle-wrapper.jar") val gradleWrapperProps = File(projectRoot, "gradle/wrapper/gradle-wrapper.properties") + if (gradlew.exists() && !gradlew.canExecute()) { + gradlew.setExecutable(true, false) + } return gradlew.exists() && gradleWrapperJar.exists() && gradleWrapperProps.exists() } @@ -326,6 +329,9 @@ class GradleBuildService : override fun onServerExited(exitCode: Int) { log.warn("Tooling API process terminated with exit code: {}", exitCode) + isToolingServerStarted = false + isBuildInProgress = false + server = null stopForeground(STOP_FOREGROUND_REMOVE) } @@ -387,6 +393,10 @@ class GradleBuildService : } // Override AAPT2 binary + if (!Environment.AAPT2.exists() || !Environment.AAPT2.canExecute()) { + log.warn("AAPT2 binary unavailable at {}", Environment.AAPT2.absolutePath) + logOutput("Warning: AAPT2 binary missing or not executable at ${Environment.AAPT2.absolutePath}") + } extraArgs.add("-Pandroid.aapt2FromMavenOverride=" + Environment.AAPT2.absolutePath) extraArgs.add("-P${PROPERTY_LOGSENDER_ENABLED}=${DevOpsPreferences.logsenderEnabled}") @@ -452,6 +462,10 @@ class GradleBuildService : val projectDir = ProjectManagerImpl.getInstance().projectDir val files = ZipUtils.unzipFile(extracted, projectDir) if (files != null && files.isNotEmpty()) { + val gradlew = File(projectDir, "gradlew") + if (gradlew.exists()) { + gradlew.setExecutable(true, false) + } return GradleWrapperCheckResult(true) } } catch (e: IOException) { @@ -499,7 +513,10 @@ class GradleBuildService : private fun performBuildTasks(future: CompletableFuture): CompletableFuture { return CompletableFuture.runAsync(this::onPrepareBuildRequest) - .handleAsync { _, _ -> + .handleAsync { _, prepError -> + if (prepError != null) { + throw CompletionException(prepError) + } try { return@handleAsync future.get() } catch (e: Throwable) { @@ -528,6 +545,7 @@ class GradleBuildService : private fun ensureTmpdir() { Environment.mkdirIfNotExits(Environment.TMP_DIR) + Environment.mkdirIfNotExits(Environment.GRADLE_USER_HOME) } private fun logBuildInProgress() { diff --git a/core/app/src/main/java/com/tom/rv2ide/services/builder/ToolingServerRunner.kt b/core/app/src/main/java/com/tom/rv2ide/services/builder/ToolingServerRunner.kt index 26449e1708..985a5c36e7 100644 --- a/core/app/src/main/java/com/tom/rv2ide/services/builder/ToolingServerRunner.kt +++ b/core/app/src/main/java/com/tom/rv2ide/services/builder/ToolingServerRunner.kt @@ -20,6 +20,7 @@ package com.tom.rv2ide.services.builder import android.util.Log import ch.qos.logback.core.CoreConstants import com.termux.shared.reflection.ReflectionUtils +import com.tom.rv2ide.managers.ToolsManager import com.tom.rv2ide.shell.executeProcessAsync import com.tom.rv2ide.tasks.cancelIfActive import com.tom.rv2ide.tasks.ifCancelledOrInterrupted @@ -73,8 +74,21 @@ internal class ToolingServerRunner( fun startAsync(envs: Map) = runnerScope .launch { - var process: Process? + var process: Process? = null + var notifiedExit = false try { + ToolsManager.awaitInitialized() + if (!Environment.JAVA.exists() || !Environment.JAVA.canExecute()) { + throw IllegalStateException( + "Java executable missing or not executable: ${Environment.JAVA.absolutePath}" + ) + } + if (!Environment.TOOLING_API_JAR.exists()) { + throw IllegalStateException( + "Tooling API JAR missing: ${Environment.TOOLING_API_JAR.absolutePath}" + ) + } + log.info("Starting tooling API server...") val command = listOf( @@ -126,11 +140,14 @@ internal class ToolingServerRunner( launch(Dispatchers.IO) { try { process?.waitFor() - log.info( - "Tooling API process exited with code : {}", - process?.exitValue() ?: "", - ) + val exitCode = process?.exitValue() ?: -1 + log.info("Tooling API process exited with code : {}", exitCode) + isStarted = false process = null + if (!notifiedExit) { + notifiedExit = true + observer?.onServerExited(exitCode) + } } finally { log.info("Destroying Tooling API process...") process?.destroyForcibly() @@ -194,6 +211,11 @@ internal class ToolingServerRunner( if (e !is CancellationException) { log.error("Unable to start tooling API server", e) Log.e("ToolingServerRunner", "Unable to start tooling API server", e) + isStarted = false + if (!notifiedExit) { + notifiedExit = true + observer?.onServerExited(-1) + } } } } diff --git a/core/app/src/main/java/com/tom/rv2ide/services/builder/util.kt b/core/app/src/main/java/com/tom/rv2ide/services/builder/util.kt index a6d502641e..51060ef1f6 100644 --- a/core/app/src/main/java/com/tom/rv2ide/services/builder/util.kt +++ b/core/app/src/main/java/com/tom/rv2ide/services/builder/util.kt @@ -19,13 +19,15 @@ package com.tom.rv2ide.services.builder import com.tom.rv2ide.preferences.internal.BuildPreferences import com.tom.rv2ide.tooling.api.messages.GradleDistributionParams +import com.tom.rv2ide.utils.Environment /** The distribution params. This considers [gradleInstallationDir] preference as well. */ val gradleDistributionParams: GradleDistributionParams get() { - if (BuildPreferences.gradleInstallationDir.isBlank()) { + val installDir = BuildPreferences.gradleInstallationDir.trim() + if (installDir.isEmpty()) { return GradleDistributionParams.WRAPPER } - return GradleDistributionParams.forInstallationDir(BuildPreferences.gradleInstallationDir) + return GradleDistributionParams.forInstallationDir(Environment.expandHomePath(installDir)) } diff --git a/core/app/src/main/java/com/tom/rv2ide/templates/AtcWizardDialog.kt b/core/app/src/main/java/com/tom/rv2ide/templates/AtcWizardDialog.kt index 2a95e15f38..bca806ba71 100644 --- a/core/app/src/main/java/com/tom/rv2ide/templates/AtcWizardDialog.kt +++ b/core/app/src/main/java/com/tom/rv2ide/templates/AtcWizardDialog.kt @@ -277,9 +277,10 @@ class AtcWizardDialog : BottomSheetDialogFragment() { val selectedIdx = minSdkDisplay.indexOf(binding.minSdkInput.text?.toString()).coerceAtLeast(0) val sdkApi = Options.OPT_MIN_SDK ?: 21 - val savePath = + val rawSavePath = binding.saveLocationInput.text?.toString()?.trim().takeUnless { it.isNullOrBlank() } ?: Environment.PROJECTS_DIR.absolutePath + val savePath = Environment.expandHomePath(rawSavePath) val projectDir = File(savePath, proj) if (projectDir.exists()) { @@ -290,10 +291,7 @@ class AtcWizardDialog : BottomSheetDialogFragment() { return } - if ( - Options.OPT_IS_NATIVE_GAME_ACTIVITY == true && - WizardPreferences.getLastSaveLocation(ctx) != Environment.AT_ACSHOME_PROJECTS.toString() - ) { + if (Options.OPT_IS_NATIVE_GAME_ACTIVITY == true && !isInsidePrivateHome(savePath)) { requireAcsHomeProjectsDir() return } @@ -306,11 +304,39 @@ class AtcWizardDialog : BottomSheetDialogFragment() { lang = LanguageType.KOTLIN } + val wrappedListener = object : AtcInterface.TemplateCreationListener { + override fun onTemplateSelected(templateName: String) { + listener?.onTemplateSelected(templateName) + } + + override fun onCreationCancelled() { + listener?.onCreationCancelled() + } + + override fun onTemplateCreated(success: Boolean, message: String) { + if (success) { + Environment.trySymlinkToLegacyProjects(projectDir) + } + listener?.onTemplateCreated(success, message) + } + + override fun onTemplateCreated( + success: Boolean, + message: String, + createdDir: File?, + ) { + if (success) { + Environment.trySymlinkToLegacyProjects(createdDir ?: projectDir) + } + listener?.onTemplateCreated(success, message, createdDir) + } + } + CoroutineScope(Dispatchers.Main).launch { try { t.create( ctx, - listener, + wrappedListener, TemplateOptions(proj, pkg, lang, sdkApi, Options.OPT_USE_GRADLE_KTS, File(savePath)), ) } catch (e: Exception) { @@ -322,23 +348,31 @@ class AtcWizardDialog : BottomSheetDialogFragment() { dismiss() } + private fun isInsidePrivateHome(path: String): Boolean { + return runCatching { + val homeCanonical = Environment.HOME.canonicalPath + val targetCanonical = File(path).canonicalPath + targetCanonical == homeCanonical || + targetCanonical.startsWith("$homeCanonical${File.separator}") + }.getOrDefault(false) + } + private fun requireAcsHomeProjectsDir() { showAlert( "Invalid Save Location", - "Game projects must be saved in the Android Code Studio home directory to work correctly.", + "Native Game projects must be saved inside private app storage (${Environment.HOME.absolutePath}) so binaries can execute.", "Automatically switch", ) { - binding.saveLocationInput.setText(Environment.AT_ACSHOME_PROJECTS.toString()) - WizardPreferences.setLastSaveLocation( - requireContext(), - Environment.AT_ACSHOME_PROJECTS.toString(), - ) + val defaultDir = Environment.PROJECTS_DIR.absolutePath + binding.saveLocationInput.setText(defaultDir) + WizardPreferences.setLastSaveLocation(requireContext(), defaultDir) } } private fun validateProjectName() { val projectName = binding.projectNameInput.text?.toString()?.trim().orEmpty() - val saveLocation = binding.saveLocationInput.text?.toString()?.trim().orEmpty() + val saveLocation = + Environment.expandHomePath(binding.saveLocationInput.text?.toString()?.trim().orEmpty()) if (projectName.isEmpty()) { binding.projectNameLayout.error = null diff --git a/core/app/src/main/java/com/tom/rv2ide/templates/preferences/WizardPreferences.kt b/core/app/src/main/java/com/tom/rv2ide/templates/preferences/WizardPreferences.kt index 7e34d09c64..fa371be9d9 100644 --- a/core/app/src/main/java/com/tom/rv2ide/templates/preferences/WizardPreferences.kt +++ b/core/app/src/main/java/com/tom/rv2ide/templates/preferences/WizardPreferences.kt @@ -19,6 +19,7 @@ package com.tom.rv2ide.templates.preferences import android.content.Context import android.content.SharedPreferences +import com.tom.rv2ide.utils.Environment /* * @author Mohammed-baqer-null @ https://github.com/Mohammed-baqer-null @@ -35,7 +36,14 @@ object WizardPreferences { } fun getLastSaveLocation(context: Context): String? { - return getPrefs(context).getString(KEY_LAST_SAVE_LOCATION, null) + val saved = getPrefs(context).getString(KEY_LAST_SAVE_LOCATION, null)?.takeIf { it.isNotBlank() } + ?: return null + if (Environment.isLegacyProjectsPath(saved)) { + val migrated = Environment.PROJECTS_DIR.absolutePath + setLastSaveLocation(context, migrated) + return migrated + } + return saved } fun setLastSaveLocation(context: Context, path: String) { diff --git a/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt b/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt new file mode 100644 index 0000000000..ffa440d591 --- /dev/null +++ b/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt @@ -0,0 +1,195 @@ +/* + * This file is part of AndroidCodeStudio. + * + * AndroidCodeStudio is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidCodeStudio is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidCodeStudio. If not, see . + */ + +package com.tom.rv2ide.utils + +import android.content.Context +import android.os.Environment as AndroidEnvironment +import android.widget.EditText +import android.widget.LinearLayout +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.tom.rv2ide.models.FileItem +import java.io.File + +/** + * Shared directory listing, protected-path messaging, and Quick Jump navigation + * helpers used by both [com.tom.rv2ide.fragments.FileBrowserFragment] and + * [com.tom.rv2ide.fragments.FileBrowserDialogFragment]. + */ +object FileBrowserNavigationHelper { + + sealed class DirectoryListing { + data class Accessible(val items: List) : DirectoryListing() + + data object EmptyReadable : DirectoryListing() + + data class RestrictedWithoutRoot(val path: String, val message: String) : DirectoryListing() + } + + data class QuickJumpDestination(val label: String, val path: String) + + fun defaultStartPath(): String { + val ext = AndroidEnvironment.getExternalStorageDirectory() + if (ext != null && ext.exists() && ext.canRead() && ext.listFiles() != null) { + return ext.absolutePath + } + return Environment.HOME?.absolutePath ?: "/" + } + + fun resolveInitialPath(candidate: String?, fallback: String): String { + val trimmed = candidate?.trim()?.takeIf { it.isNotEmpty() } ?: return fallback + val dir = File(trimmed) + return if (dir.exists() && dir.isDirectory) dir.absolutePath else fallback + } + + fun parentPath(path: String): String? { + val normalized = normalizePath(path) + if (normalized == "/") return null + return File(normalized).parent ?: "/" + } + + fun normalizePath(path: String): String { + val expanded = Environment.expandHomePath(path) + if (expanded.isEmpty()) return "/" + return if (expanded.length > 1) expanded.trimEnd('/') else expanded + } + + fun readDirectory(path: String): DirectoryListing { + val normalized = normalizePath(path) + val dir = File(normalized) + if (!dir.exists() || !dir.isDirectory) { + return DirectoryListing.RestrictedWithoutRoot( + path = normalized, + message = "This directory is unavailable or does not exist:\n$normalized", + ) + } + + val children = dir.listFiles() + if (children == null) { + val homePath = Environment.HOME?.absolutePath ?: "/data/data/com.tom.rv2ide/files/home" + val msg = + if (isProtectedSystemPath(normalized)) { + "Android blocks directory listing inside '$normalized' without root permissions.\n\n" + + "You can still jump directly into your executable app private storage ($homePath) or enter a known subfolder path manually." + } else { + "Cannot list '$normalized' because read/storage permission is missing." + } + return DirectoryListing.RestrictedWithoutRoot(normalized, msg) + } + + if (children.isEmpty()) { + return DirectoryListing.EmptyReadable + } + + val items = + children + .map { FileItem(it.name, it.path, it.isDirectory) } + .sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) + return DirectoryListing.Accessible(items) + } + + private fun isProtectedSystemPath(path: String): Boolean { + return path == "/data" || + path.startsWith("/data/data") || + path.startsWith("/data/user") || + path.startsWith("/root") || + path.startsWith("/proc") || + path.startsWith("/sys") + } + + fun quickJumpDestinations(projectPath: String?): List { + val list = mutableListOf() + if (!projectPath.isNullOrBlank() && File(projectPath).exists()) { + list += QuickJumpDestination("Current Project (${File(projectPath).name})", projectPath) + } + Environment.HOME?.let { home -> + list += QuickJumpDestination("App Home (\$HOME)", home.absolutePath) + } + Environment.PROJECTS_DIR?.let { projDir -> + list += QuickJumpDestination("ACS Projects (Private)", projDir.absolutePath) + } + Environment.LEGACY_PROJECTS_DIR?.takeIf { it.exists() }?.let { legacyDir -> + list += QuickJumpDestination("Shared Projects (Legacy)", legacyDir.absolutePath) + } + AndroidEnvironment.getExternalStorageDirectory()?.let { ext -> + list += QuickJumpDestination("Internal Storage (/storage/emulated/0)", ext.absolutePath) + } + list += QuickJumpDestination("Filesystem Root (/)", "/") + return list + } + + fun showQuickJumpDialog( + context: Context, + currentPath: String, + projectPath: String?, + onNavigate: (String) -> Unit, + ) { + val destinations = quickJumpDestinations(projectPath) + val labels = (destinations.map { it.label } + "Go to custom path...").toTypedArray() + + MaterialAlertDialogBuilder(context) + .setTitle("Quick Jump") + .setItems(labels) { _, index -> + if (index == destinations.size) { + showGoToPathDialog(context, currentPath, onNavigate) + } else { + onNavigate(destinations[index].path) + } + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + fun showGoToPathDialog( + context: Context, + currentPath: String, + onNavigate: (String) -> Unit, + ) { + val density = context.resources.displayMetrics.density + val padH = (20 * density).toInt() + val padV = (8 * density).toInt() + val container = + LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + setPadding(padH, padV, padH, 0) + } + val input = + EditText(context).apply { + setText(currentPath) + setSingleLine(true) + hint = Environment.HOME?.absolutePath ?: "/data/data/com.tom.rv2ide/files/home" + setSelection(text.length) + } + container.addView(input) + + MaterialAlertDialogBuilder(context) + .setTitle("Go to Path") + .setMessage("Enter any directory path (including App Home under /data/data/...):") + .setView(container) + .setPositiveButton("Open") { _, _ -> + val target = input.text?.toString()?.trim().orEmpty() + if (target.isNotEmpty()) { + onNavigate(normalizePath(target)) + } + } + .setNeutralButton("App Home") { _, _ -> + Environment.HOME?.absolutePath?.let(onNavigate) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } +} diff --git a/core/app/src/main/java/com/tom/rv2ide/viewmodel/GitViewModel.kt b/core/app/src/main/java/com/tom/rv2ide/viewmodel/GitViewModel.kt index 0b3577981d..1536c88b19 100644 --- a/core/app/src/main/java/com/tom/rv2ide/viewmodel/GitViewModel.kt +++ b/core/app/src/main/java/com/tom/rv2ide/viewmodel/GitViewModel.kt @@ -363,7 +363,7 @@ class GitViewModel : ViewModel() { _operationResult.postValue( OperationResult( success = false, - message = "Failed to clone repository" + message = gitManager?.lastError ?: "Failed to clone repository" ) ) } diff --git a/core/app/src/main/res/drawable/bg_indexing_banner.xml b/core/app/src/main/res/drawable/bg_indexing_banner.xml index 635eab6777..f632866ebf 100644 --- a/core/app/src/main/res/drawable/bg_indexing_banner.xml +++ b/core/app/src/main/res/drawable/bg_indexing_banner.xml @@ -21,11 +21,7 @@ - - + + \ No newline at end of file diff --git a/core/app/src/main/res/layout/dialog_file_browser.xml b/core/app/src/main/res/layout/dialog_file_browser.xml index dc26a7cfc5..31a3b70551 100644 --- a/core/app/src/main/res/layout/dialog_file_browser.xml +++ b/core/app/src/main/res/layout/dialog_file_browser.xml @@ -31,22 +31,81 @@ + tools:text="/storage/emulated/0/" /> - + android:layout_height="0dp" + android:layout_weight="1"> + + + + + + + + + + + + + + + + + + + + diff --git a/core/app/src/main/res/layout/fragment_file_browser.xml b/core/app/src/main/res/layout/fragment_file_browser.xml index 8a96e1c222..ebc65f0348 100644 --- a/core/app/src/main/res/layout/fragment_file_browser.xml +++ b/core/app/src/main/res/layout/fragment_file_browser.xml @@ -25,21 +25,99 @@ + android:drawablePadding="8dp" + tools:text="/storage/emulated/0/" /> - + android:layout_height="0dp" + android:layout_weight="1"> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/app/src/main/res/layout/layout_indexing_banner.xml b/core/app/src/main/res/layout/layout_indexing_banner.xml index 9656953b45..2b5a003b61 100644 --- a/core/app/src/main/res/layout/layout_indexing_banner.xml +++ b/core/app/src/main/res/layout/layout_indexing_banner.xml @@ -35,10 +35,13 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" - android:paddingStart="24dp" - android:paddingEnd="32dp" - android:paddingBottom="24dp" - android:elevation="12dp" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:paddingTop="10dp" + android:paddingBottom="10dp" + android:elevation="6dp" + android:clickable="true" + android:focusable="true" android:gravity="center_vertical" android:background="@drawable/bg_indexing_banner"> diff --git a/core/app/src/main/res/menu/menu_main.xml b/core/app/src/main/res/menu/menu_main.xml index 3c31c919ce..731b52f5a6 100644 --- a/core/app/src/main/res/menu/menu_main.xml +++ b/core/app/src/main/res/menu/menu_main.xml @@ -2,6 +2,17 @@ + + + + initFuture; + + public static void awaitInitialized() { + final var future = initFuture; + if (future == null) { + return; + } + try { + future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.warn("Interrupted while waiting for tools extraction", e); + } catch (Throwable err) { + LOG.warn("Tools extraction completed with error", err); + } + } public static void init(@NonNull BaseApplication app, Runnable onFinish) { @@ -56,27 +72,31 @@ public static void init(@NonNull BaseApplication app, Runnable onFinish) { return; } - CompletableFuture.runAsync(() -> { - // Load installed JDK distributions - IJdkDistributionProvider.getInstance().loadDistributions(); - - writeNoMediaFile(); - extractAapt2(); - extractToolingApi(); - extractAndroidJar(); - extractColorScheme(app); - writeInitScript(); - - deleteIdeenv(); - }).whenComplete((__, error) -> { - if (error != null) { - LOG.error("Error extracting tools", error); - } - - if (onFinish != null) { - onFinish.run(); - } - }); + initFuture = + CompletableFuture.runAsync( + () -> { + // Load installed JDK distributions + IJdkDistributionProvider.getInstance().loadDistributions(); + + writeNoMediaFile(); + extractAapt2(); + extractToolingApi(); + extractAndroidJar(); + extractColorScheme(app); + writeInitScript(); + + deleteIdeenv(); + }) + .whenComplete( + (__, error) -> { + if (error != null) { + LOG.error("Error extracting tools", error); + } + + if (onFinish != null) { + onFinish.run(); + } + }); } private static void extractColorScheme(final BaseApplication app) { @@ -180,29 +200,49 @@ public static String getCommonAsset(String name) { } private static void extractAapt2() { - if (!Environment.AAPT2.exists()) { + if (!Environment.AAPT2.exists() || Environment.AAPT2.length() == 0) { final var context = BaseApplication.getBaseInstance(); final var nativeLibraryDir = context.getApplicationInfo().nativeLibraryDir; final var sourceAapt2 = new File(nativeLibraryDir, "libaapt2.so"); if (sourceAapt2.exists() && sourceAapt2.isFile()) { FilesKt.copyTo(sourceAapt2, Environment.AAPT2, true, ConstantsKt.DEFAULT_BUFFER_SIZE); } else { - LOG.error("{} file does not exist! This can be problematic.", sourceAapt2); + LOG.error("{} does not exist; resource compilation will fail", sourceAapt2); + return; } } if (!Environment.AAPT2.canExecute() && !Environment.AAPT2.setExecutable(true)) { - LOG.error("Cannot set executable permissions to AAPT2 binary"); + LOG.error("Cannot set executable permissions on AAPT2 binary: {}", Environment.AAPT2); } } private static void extractToolingApi() { - if (Environment.TOOLING_API_JAR.exists()) { - FileUtils.delete(Environment.TOOLING_API_JAR); + final var tempJar = + new File( + Environment.TOOLING_API_JAR.getParentFile(), + Environment.TOOLING_API_JAR.getName() + ".tmp"); + if (tempJar.exists()) { + FileUtils.delete(tempJar); } - ResourceUtils.copyFileFromAssets(getCommonAsset("tooling-api-all.jar"), - Environment.TOOLING_API_JAR.getAbsolutePath()); + if (ResourceUtils.copyFileFromAssets( + getCommonAsset("tooling-api-all.jar"), tempJar.getAbsolutePath()) + && tempJar.exists() + && tempJar.length() > 0) { + if (Environment.TOOLING_API_JAR.exists()) { + FileUtils.delete(Environment.TOOLING_API_JAR); + } + if (!tempJar.renameTo(Environment.TOOLING_API_JAR)) { + FilesKt.copyTo(tempJar, Environment.TOOLING_API_JAR, true, ConstantsKt.DEFAULT_BUFFER_SIZE); + FileUtils.delete(tempJar); + } + } else { + FileUtils.delete(tempJar); + } + if (!Environment.TOOLING_API_JAR.exists() || Environment.TOOLING_API_JAR.length() == 0) { + LOG.error("Failed to extract tooling-api-all.jar to {}", Environment.TOOLING_API_JAR); + } } private static void writeInitScript() { diff --git a/core/common/src/main/java/com/tom/rv2ide/utils/Environment.java b/core/common/src/main/java/com/tom/rv2ide/utils/Environment.java index afd3c407cb..8493dee4f0 100755 --- a/core/common/src/main/java/com/tom/rv2ide/utils/Environment.java +++ b/core/common/src/main/java/com/tom/rv2ide/utils/Environment.java @@ -18,8 +18,10 @@ import android.annotation.SuppressLint; import android.content.Context; +import android.system.Os; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.blankj.utilcode.util.FileUtils; @@ -27,13 +29,17 @@ import org.slf4j.LoggerFactory; import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.UUID; @SuppressLint("SdCardPath") public final class Environment { - public static final String PROJECTS_FOLDER = "AndroidIDEProjects"; + public static final String PROJECTS_FOLDER = "ACSProjects"; + public static final String LEGACY_PROJECTS_FOLDER = "AndroidIDEProjects"; private static final Logger LOG = LoggerFactory.getLogger(Environment.class); public static File ROOT; public static File PREFIX; @@ -48,6 +54,7 @@ public final class Environment { public static File LIB_DIR; public static File AT_ACSHOME_PROJECTS; public static File PROJECTS_DIR; + public static File LEGACY_PROJECTS_DIR; public static File REALM_DB_DIR; /** Used by Java LSP until the project is initialized. */ @@ -79,8 +86,9 @@ public static void init(Context context) { TMP_DIR = mkdirIfNotExits(new File(PREFIX, "tmp")); BIN_DIR = mkdirIfNotExits(new File(PREFIX, "bin")); LIB_DIR = mkdirIfNotExits(new File(PREFIX, "lib")); - PROJECTS_DIR = mkdirIfNotExits(new File(FileUtil.getExternalStorageDir(), PROJECTS_FOLDER)); - AT_ACSHOME_PROJECTS = mkdirIfNotExits(new File(HOME, "ACSProjects")); + AT_ACSHOME_PROJECTS = mkdirIfNotExits(new File(HOME, PROJECTS_FOLDER)); + PROJECTS_DIR = AT_ACSHOME_PROJECTS; + LEGACY_PROJECTS_DIR = new File(FileUtil.getExternalStorageDir(), LEGACY_PROJECTS_FOLDER); ANDROID_JAR = mkdirIfNotExits(new File(ANDROIDIDE_HOME, "android.jar")); TOOLING_API_JAR = new File(mkdirIfNotExits(new File(ANDROIDIDE_HOME, "tooling-api")), "tooling-api-all.jar"); @@ -169,6 +177,120 @@ public static File getProjectCacheDir(File projectDir) { return new File(projectDir, ".acside"); } + /** + * Best-effort symlink inside shared storage pointing to a private-storage project. + * Android FUSE/sdcardfs mounts usually reject symlinks with EPERM/EOPNOTSUPP, so + * failures are safely ignored while keeping SAF and IDE discovery working. + */ + public static void trySymlinkToLegacyProjects(@NonNull File projectDir) { + if (LEGACY_PROJECTS_DIR == null || !projectDir.exists()) { + return; + } + try { + if (!LEGACY_PROJECTS_DIR.exists() && !LEGACY_PROJECTS_DIR.mkdirs()) { + return; + } + File link = new File(LEGACY_PROJECTS_DIR, projectDir.getName()); + if (!link.exists()) { + Os.symlink(projectDir.getAbsolutePath(), link.getAbsolutePath()); + } + } catch (Throwable err) { + LOG.debug("Skipping shared storage symlink for {} ({})", + projectDir.getName(), err.getMessage()); + } + } + + public static boolean isLegacyProjectsPath(@Nullable String path) { + if (path == null || path.trim().isEmpty() || LEGACY_PROJECTS_DIR == null) { + return false; + } + try { + return new File(path).getCanonicalPath().equals(LEGACY_PROJECTS_DIR.getCanonicalPath()); + } catch (Exception e) { + return new File(path).getAbsolutePath().equals(LEGACY_PROJECTS_DIR.getAbsolutePath()); + } + } + + @NonNull + public static List getInstalledNdkVersions() { + if (ANDROID_HOME == null) { + return Collections.emptyList(); + } + File ndkRoot = new File(ANDROID_HOME, "ndk"); + File[] entries = ndkRoot.listFiles(); + if (entries == null || entries.length == 0) { + return Collections.emptyList(); + } + List versions = new ArrayList<>(); + for (File dir : entries) { + if (dir.isDirectory() && isValidNdkDir(dir)) { + versions.add(dir.getName()); + } + } + Collections.sort(versions, Environment::compareNumericVersionsDescending); + return versions; + } + + public static boolean isNdkInstalled() { + return !getInstalledNdkVersions().isEmpty(); + } + + @Nullable + public static String getHighestInstalledNdkVersion() { + List versions = getInstalledNdkVersions(); + return versions.isEmpty() ? null : versions.get(0); + } + + @NonNull + public static String expandHomePath(@Nullable String path) { + if (path == null) { + return ""; + } + String trimmed = path.trim(); + if (HOME == null) { + return trimmed; + } + if ("~".equals(trimmed)) { + return HOME.getAbsolutePath(); + } + if (trimmed.startsWith("~/")) { + return new File(HOME, trimmed.substring(2)).getAbsolutePath(); + } + return trimmed; + } + + private static boolean isValidNdkDir(@NonNull File ndkDir) { + return new File(ndkDir, "ndk-build").exists() + || new File(ndkDir, "source.properties").exists() + || new File(ndkDir, "toolchains/llvm/prebuilt").isDirectory(); + } + + private static int compareNumericVersionsDescending(String a, String b) { + String[] partsA = a.split("\\."); + String[] partsB = b.split("\\."); + int len = Math.max(partsA.length, partsB.length); + for (int i = 0; i < len; i++) { + String pa = i < partsA.length ? partsA[i] : "0"; + String pb = i < partsB.length ? partsB[i] : "0"; + Integer na = parseIntOrNull(pa); + Integer nb = parseIntOrNull(pb); + int cmp = (na != null && nb != null) ? Integer.compare(nb, na) : pb.compareTo(pa); + if (cmp != 0) { + return cmp; + } + } + return 0; + } + + @Nullable + private static Integer parseIntOrNull(String value) { + try { + return Integer.valueOf(value); + } catch (NumberFormatException e) { + return null; + } + } + @NonNull public static File createTempFile() { var file = newTempFile(); diff --git a/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/Setup.kt b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/Setup.kt index 8e3ce18bae..c23dd1ec76 100644 --- a/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/Setup.kt +++ b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/Setup.kt @@ -6,7 +6,7 @@ * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * AndroidCodeStudio is distributed in the hope that it will be useful, + * AndroidIDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. @@ -23,233 +23,500 @@ import android.content.Context import android.view.LayoutInflater import android.view.View import android.widget.Toast +import com.google.android.material.button.MaterialButton import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.progressindicator.CircularProgressIndicator import com.google.android.material.textview.MaterialTextView -import com.google.android.material.button.MaterialButton +import com.tom.rv2ide.editor.ui.IDEEditor +import com.tom.rv2ide.models.Position +import com.tom.rv2ide.models.Range +import com.tom.rv2ide.resources.R.string as CoreStrings import com.tom.rv2ide.setup.R -import com.tom.rv2ide.resources.R.string +import com.tom.rv2ide.setup.servers.AptPackageInstaller import com.tom.rv2ide.setup.servers.ILanguageServerInstaller -import com.tom.rv2ide.models.Range -import com.tom.rv2ide.models.Position +import com.tom.rv2ide.setup.servers.clang.Clang +import com.tom.rv2ide.setup.servers.kotlin.Kotlin +import com.tom.rv2ide.utils.Environment +import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import java.io.File /** + * Scans projects for required languages/tools and offers guided IDE installation + * (supporting both language servers and Termux CLI build dependencies). + * * @author Mohammed-baqer-null @ https://github.com/Mohammed-baqer-null */ - class Setup(private val context: Context) { - - private val cppExtensions = setOf("c", "cpp", "cc", "cxx", "h", "hpp", "hh", "hxx") - private val kotlinExtensions = setOf("kt", "kts") + + private data class ToolSpec( + val id: String, + val displayName: String, + val promptMessage: String, + val isLspServer: Boolean = false, + val installerFactory: (Context) -> ILanguageServerInstaller, + ) + + private data class PendingInstall( + val spec: ToolSpec, + val message: String, + ) + + companion object { + private val cppExtensions = setOf("c", "cpp", "cc", "cxx", "h", "hpp", "hh", "hxx") + private val kotlinExtensions = setOf("kt", "kts") + private val pythonExtensions = setOf("py", "pyw", "pyi") + private val rustExtensions = setOf("rs") + private val goExtensions = setOf("go") + private val autotoolsFiles = setOf("configure.ac", "configure.in", "makefile.am", "autogen.sh") + private val ignoredScanDirs = + setOf(".git", ".gradle", ".idea", ".androidide", ".cxx", "build", "node_modules") + + private val missingCommandPatterns = + listOf( + Regex("""starting process 'command '([^']+)''"""), + Regex("""FileNotFoundError:.*'([^']+)'"""), + Regex("""Cannot run program "([^"]+)".*(?:error=2|No such file)"""), + Regex( + """(?:sh|bash|zsh|dash|env|make)(?::\s*[^:\n]+)?:\s*['"]?([A-Za-z0-9._+-]+)['"]?:\s*(?:not found|command not found|No such file)""" + ), + Regex("""([A-Za-z0-9._+-]+): command not found"""), + ) + + private val commandToToolId = + mapOf( + "clang" to "clang", + "clang++" to "clang", + "clangd" to "clang", + "gcc" to "clang", + "g++" to "clang", + "python" to "python", + "python3" to "python", + "pip" to "python", + "pip3" to "python", + "autoreconf" to "autotools", + "autoconf" to "autotools", + "autoheader" to "autotools", + "automake" to "autotools", + "aclocal" to "autotools", + "libtoolize" to "autotools", + "libtool" to "autotools", + "m4" to "autotools", + "cmake" to "cmake", + "ninja" to "ninja", + "make" to "make", + "pkg-config" to "pkg-config", + "rustc" to "rust", + "cargo" to "rust", + "node" to "nodejs", + "npm" to "nodejs", + "npx" to "nodejs", + "go" to "golang", + "perl" to "perl", + "ruby" to "ruby", + "gettext" to "gettext", + "autopoint" to "gettext", + "msgfmt" to "gettext", + "bison" to "bison", + "flex" to "flex", + "patch" to "patch", + "git" to "git", + "nasm" to "nasm", + "yasm" to "yasm", + "meson" to "meson", + "swig" to "swig", + ) + + private fun aptSpec( + id: String, + displayName: String, + packages: List, + binaries: List = packages, + prompt: String = + "Your project requires $displayName. Would you like to install it now?", + ): ToolSpec { + return ToolSpec( + id = id, + displayName = displayName, + promptMessage = prompt, + isLspServer = false, + installerFactory = { ctx -> + AptPackageInstaller(ctx, packages, binaries, displayName) + }, + ) + } + + private val toolSpecs: Map = + listOf( + ToolSpec( + id = "clang", + displayName = "Clang Language Server", + promptMessage = "", + isLspServer = true, + installerFactory = { ctx -> Clang(ctx) }, + ), + ToolSpec( + id = "kotlin", + displayName = "Kotlin Language Server", + promptMessage = "", + isLspServer = true, + installerFactory = { ctx -> Kotlin(ctx) }, + ), + aptSpec( + id = "python", + displayName = "Python", + packages = listOf("python"), + binaries = listOf("python3"), + prompt = + "Your project contains Python files or scripts. Would you like to install Python?", + ), + aptSpec( + id = "autotools", + displayName = "Autotools (autoconf, automake, libtool, make, pkg-config)", + packages = + listOf("autoconf", "automake", "libtool", "m4", "make", "pkg-config"), + binaries = listOf("autoreconf", "autoconf", "automake", "libtoolize"), + prompt = + "Your project uses Autotools (autoreconf/autoconf). Would you like to install the Autotools toolchain?", + ), + aptSpec( + id = "cmake", + displayName = "CMake & Ninja", + packages = listOf("cmake", "ninja"), + binaries = listOf("cmake"), + ), + aptSpec("ninja", "Ninja", listOf("ninja")), + aptSpec("make", "GNU Make", listOf("make")), + aptSpec("pkg-config", "pkg-config", listOf("pkg-config")), + aptSpec( + id = "rust", + displayName = "Rust (rustc & cargo)", + packages = listOf("rust"), + binaries = listOf("rustc", "cargo"), + ), + aptSpec( + id = "nodejs", + displayName = "Node.js & npm", + packages = listOf("nodejs"), + binaries = listOf("node", "npm"), + ), + aptSpec( + id = "golang", + displayName = "Go", + packages = listOf("golang"), + binaries = listOf("go"), + ), + aptSpec("perl", "Perl", listOf("perl")), + aptSpec("ruby", "Ruby", listOf("ruby")), + aptSpec( + id = "gettext", + displayName = "GNU Gettext", + packages = listOf("gettext"), + binaries = listOf("autopoint", "msgfmt"), + ), + aptSpec("bison", "Bison", listOf("bison")), + aptSpec("flex", "Flex", listOf("flex")), + aptSpec("patch", "Patch", listOf("patch")), + aptSpec("git", "Git", listOf("git")), + aptSpec("nasm", "NASM", listOf("nasm")), + aptSpec("yasm", "YASM", listOf("yasm")), + aptSpec("meson", "Meson", listOf("meson")), + aptSpec("swig", "SWIG", listOf("swig")), + ) + .associateBy { it.id } + + fun detectMissingToolCommand(line: String): String? { + for (pattern in missingCommandPatterns) { + val raw = + pattern.find(line)?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() } + ?: continue + val binary = raw.substringAfterLast('/') + val key = binary.lowercase() + if (commandToToolId.containsKey(key)) { + return key + } + } + return null + } + } + private val scope = CoroutineScope(Dispatchers.Main) - + fun scanProjectForLanguageServers(projectDir: File, onComplete: ((Boolean) -> Unit)? = null) { scope.launch { - withContext(Dispatchers.IO) { - val serversToInstall = mutableListOf>() - - val hasCppFiles = checkForFiles(projectDir, cppExtensions) - if (hasCppFiles && !isServerInstalled("clang")) { - serversToInstall.add("clang" to context.getString(R.string.project_contians_clang_title)) + val pending = withContext(Dispatchers.IO) { detectProjectTools(projectDir) } + if (pending.isNotEmpty()) { + showToolPrompts(pending, 0, anyLspInstalled = false, anyInstalled = false) { lspInstalled, _ -> + onComplete?.invoke(lspInstalled) } - - val hasKotlinFiles = checkForFiles(projectDir, kotlinExtensions) - if (hasKotlinFiles && !isServerInstalled("kotlin")) { - serversToInstall.add("kotlin" to context.getString(R.string.project_contians_kotlin_title)) - } - - serversToInstall - }.let { servers -> - if (servers.isNotEmpty()) { - showLanguageServerDialogs(servers, 0, false, onComplete) - } else { - onComplete?.invoke(false) + } else { + onComplete?.invoke(false) + } + } + } + + fun promptMissingTools(commands: Collection, onComplete: ((Boolean) -> Unit)? = null) { + scope.launch { + val pending = + withContext(Dispatchers.IO) { + val seenIds = LinkedHashSet() + val items = mutableListOf() + for (rawCmd in commands) { + val cmd = rawCmd.lowercase() + val toolId = commandToToolId[cmd] ?: continue + if (!seenIds.add(toolId)) continue + val spec = toolSpecs[toolId] ?: continue + if (!isSpecInstalled(spec)) { + items.add( + PendingInstall( + spec = spec, + message = + "Build failed because '$rawCmd' was not found.\n\nWould you like to install ${spec.displayName}?", + ) + ) + } + } + items + } + + if (pending.isNotEmpty()) { + showToolPrompts(pending, 0, anyLspInstalled = false, anyInstalled = false) { _, anyInstalled -> + onComplete?.invoke(anyInstalled) } + } else { + onComplete?.invoke(false) } } } - - private fun checkForFiles(directory: File, extensions: Set): Boolean { + + private fun detectProjectTools(directory: File): List { if (!directory.exists() || !directory.isDirectory) { - return false + return emptyList() } - - return directory.walkTopDown().any { file -> - file.isFile && extensions.contains(file.extension.lowercase()) + + val detectedIds = LinkedHashSet() + directory + .walkTopDown() + .onEnter { dir -> dir.name !in ignoredScanDirs } + .forEach { file -> + if (!file.isFile) return@forEach + val ext = file.extension.lowercase() + val nameLower = file.name.lowercase() + when { + ext in cppExtensions -> detectedIds.add("clang") + ext in kotlinExtensions -> detectedIds.add("kotlin") + ext in pythonExtensions || nameLower == "requirements.txt" || nameLower == "pyproject.toml" -> + detectedIds.add("python") + ext in rustExtensions || nameLower == "cargo.toml" -> detectedIds.add("rust") + ext in goExtensions || nameLower == "go.mod" -> detectedIds.add("golang") + nameLower == "package.json" -> detectedIds.add("nodejs") + nameLower in autotoolsFiles -> detectedIds.add("autotools") + nameLower == "cmakelists.txt" && !hasAndroidSdkCmake() -> detectedIds.add("cmake") + } + } + + return detectedIds.mapNotNull { id -> + val spec = toolSpecs[id] ?: return@mapNotNull null + if (isSpecInstalled(spec)) return@mapNotNull null + val msg = + when (id) { + "clang" -> context.getString(CoreStrings.project_contians_clang_title) + "kotlin" -> context.getString(CoreStrings.project_contians_kotlin_title) + else -> spec.promptMessage + } + PendingInstall(spec, msg) } } - - private fun isServerInstalled(serverId: String): Boolean { + + private fun hasAndroidSdkCmake(): Boolean { + val cmakeRoot = File(Environment.ANDROID_HOME ?: return false, "cmake") + return cmakeRoot.isDirectory && !(cmakeRoot.listFiles().isNullOrEmpty()) + } + + private fun isSpecInstalled(spec: ToolSpec): Boolean { return try { - val installer = getLanguageServerInstaller(serverId) - installer.isInstalled() - } catch (e: Exception) { + spec.installerFactory(context).isInstalled() + } catch (_: Exception) { false } } - - private fun showLanguageServerDialogs( - servers: List>, - index: Int, - anyInstalled: Boolean, - onComplete: ((Boolean) -> Unit)? + + private fun showToolPrompts( + items: List, + index: Int, + anyLspInstalled: Boolean, + anyInstalled: Boolean, + onDone: (Boolean, Boolean) -> Unit, ) { - if (index >= servers.size) { - onComplete?.invoke(anyInstalled) + if (index >= items.size) { + onDone(anyLspInstalled, anyInstalled) return } - - val (serverId, message) = servers[index] - showLanguageServerDialog(serverId, message) { isSuccessful -> - showLanguageServerDialogs(servers, index + 1, anyInstalled || isSuccessful, onComplete) + + val item = items[index] + showSetupPromptDialog(item) { success -> + showToolPrompts( + items = items, + index = index + 1, + anyLspInstalled = anyLspInstalled || (success && item.spec.isLspServer), + anyInstalled = anyInstalled || success, + onDone = onDone, + ) } } - - private fun showLanguageServerDialog(serverId: String, message: String, onComplete: ((Boolean) -> Unit)?) { - val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_language_server_setup, null) - - dialogView.findViewById(R.id.tv_message).text = message - - val dialog = MaterialAlertDialogBuilder(context) - .setView(dialogView) - .setCancelable(true) - .setOnDismissListener { - onComplete?.invoke(false) - } - .create() - + + private fun isHostUiUnavailable(): Boolean { + val activity = context as? android.app.Activity ?: return false + return activity.isFinishing || activity.isDestroyed + } + + private fun showSetupPromptDialog(item: PendingInstall, onComplete: (Boolean) -> Unit) { + if (isHostUiUnavailable()) { + onComplete(false) + return + } + val dialogView = + LayoutInflater.from(context).inflate(R.layout.dialog_language_server_setup, null) + + dialogView.findViewById(R.id.tv_title).text = + if (item.spec.isLspServer) { + context.getString(CoreStrings.lsp_setup_str) + } else { + "Install ${item.spec.displayName}" + } + dialogView.findViewById(R.id.tv_message).text = item.message + + val dialog = + MaterialAlertDialogBuilder(context) + .setView(dialogView) + .setCancelable(true) + .setOnDismissListener { onComplete(false) } + .create() + dialogView.findViewById(R.id.btn_install).setOnClickListener { dialog.setOnDismissListener(null) dialog.dismiss() - installLanguageServer(serverId, onComplete) + installToolSpec(item.spec, onComplete) } - + dialogView.findViewById(R.id.btn_cancel).setOnClickListener { dialog.setOnDismissListener(null) dialog.dismiss() - onComplete?.invoke(false) + onComplete(false) } - + dialog.show() } - - private fun installLanguageServer(serverId: String, onComplete: ((Boolean) -> Unit)?) { - val progressView = LayoutInflater.from(context).inflate(R.layout.dialog_installation_progress, null) - - val progressIndicator = progressView.findViewById(R.id.progress_indicator) - val outputText = progressView.findViewById(R.id.tv_output) + + private fun installToolSpec(spec: ToolSpec, onComplete: (Boolean) -> Unit) { + val progressView = + LayoutInflater.from(context).inflate(R.layout.dialog_installation_progress, null) + + val titleView = progressView.findViewById(R.id.tv_title) + val progressIndicator = + progressView.findViewById(R.id.progress_indicator) + val outputText = progressView.findViewById(R.id.tv_output) val copyButton = progressView.findViewById(R.id.btn_copy) val closeButton = progressView.findViewById(R.id.btn_close) - - val progressDialog = MaterialAlertDialogBuilder(context) - .setView(progressView) - .setCancelable(false) - .create() - + + titleView.text = + if (spec.isLspServer) { + context.getString(CoreStrings.installing_lsp) + } else { + "Installing ${spec.displayName}" + } + + val progressDialog = + MaterialAlertDialogBuilder(context).setView(progressView).setCancelable(false).create() + val outputBuilder = StringBuilder() - val installationResult = arrayOf(false) - + var installSucceeded = false + copyButton.visibility = View.GONE closeButton.visibility = View.GONE - outputText.setTextSize(8f) - + copyButton.setOnClickListener { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Installation Output", outputBuilder.toString()) clipboard.setPrimaryClip(clip) Toast.makeText(context, "Output copied to clipboard", Toast.LENGTH_SHORT).show() } - + closeButton.setOnClickListener { progressDialog.dismiss() - onComplete?.invoke(installationResult[0]) + onComplete(installSucceeded) } - + progressDialog.show() - + scope.launch { try { - val installer = getLanguageServerInstaller(serverId) - installationResult[0] = withContext(Dispatchers.IO) { - installer.install { output -> - scope.launch(Dispatchers.Main) { - outputBuilder.append(output).append("\n") - val text = outputBuilder.toString() - outputText.setText(text) - // Move cursor to the end of the text - val lineCount = outputText.lineCount - if (lineCount > 0) { - val lastLine = lineCount - 1 - val lastLineLength = outputText.text.getLine(lastLine).length - outputText.setSelection(Range( - Position(lastLine, lastLineLength, -1), - Position(lastLine, lastLineLength, -1) - )) + val installer = spec.installerFactory(context) + installSucceeded = + withContext(Dispatchers.IO) { + installer.install { line -> + scope.launch(Dispatchers.Main) { + if (!isHostUiUnavailable()) { + appendEditorOutput(outputText, outputBuilder, line) + } + } } } - } - } - + progressIndicator.visibility = View.GONE - if (installationResult[0]) { - outputBuilder.append("\nInstallation completed successfully!") - showSuccessfullyInstalledDialog(context) + if (installSucceeded) { + appendEditorOutput(outputText, outputBuilder, "\nInstallation completed successfully!") + if (!isHostUiUnavailable()) { + showSuccessfullyInstalledDialog(context, spec.displayName) + } } else { - outputBuilder.append("\nInstallation failed. Please check the output above.") + appendEditorOutput( + outputText, + outputBuilder, + "\nInstallation failed. Please check the output above.", + ) copyButton.visibility = View.VISIBLE } - val text = outputBuilder.toString() - outputText.setText(text) - val lineCount = outputText.lineCount - if (lineCount > 0) { - val lastLine = lineCount - 1 - val lastLineLength = outputText.text.getLine(lastLine).length - outputText.setSelection(Range( - Position(lastLine, lastLineLength, -1), - Position(lastLine, lastLineLength, -1) - )) - } closeButton.visibility = View.VISIBLE - } catch (e: Exception) { - installationResult[0] = false + installSucceeded = false progressIndicator.visibility = View.GONE - outputBuilder.append("\nError: ${e.message}") - val text = outputBuilder.toString() - outputText.setText(text) - val lineCount = outputText.lineCount - if (lineCount > 0) { - val lastLine = lineCount - 1 - val lastLineLength = outputText.text.getLine(lastLine).length - outputText.setSelection(Range( - Position(lastLine, lastLineLength, -1), - Position(lastLine, lastLineLength, -1) - )) - } + appendEditorOutput(outputText, outputBuilder, "\nError: ${e.message}") copyButton.visibility = View.VISIBLE closeButton.visibility = View.VISIBLE e.printStackTrace() } } } - - private fun showSuccessfullyInstalledDialog(ctx: Context) { - MaterialAlertDialogBuilder(ctx) - .setTitle(ctx.getString(R.string.lsp_installed_title)) - .setMessage(ctx.getString(R.string.lsp_installed_summary)) - .setPositiveButton(ctx.getString(R.string.lsp_ok_button), null) - .show() + + private fun appendEditorOutput( + outputText: IDEEditor, + outputBuilder: StringBuilder, + line: String, + ) { + outputBuilder.append(line).append("\n") + outputText.setText(outputBuilder.toString()) + val lineCount = outputText.lineCount + if (lineCount > 0) { + val lastLine = lineCount - 1 + val lastLineLength = outputText.text.getLine(lastLine).length + outputText.setSelection( + Range( + Position(lastLine, lastLineLength, -1), + Position(lastLine, lastLineLength, -1), + ) + ) + } } - - private fun getLanguageServerInstaller(serverId: String): ILanguageServerInstaller { - val className = "com.tom.rv2ide.setup.servers.${serverId}.${serverId.capitalize()}" - val clazz = Class.forName(className) - val constructor = clazz.getDeclaredConstructor(Context::class.java) - return constructor.newInstance(context) as ILanguageServerInstaller + + private fun showSuccessfullyInstalledDialog(ctx: Context, displayName: String) { + MaterialAlertDialogBuilder(ctx) + .setTitle(ctx.getString(CoreStrings.lsp_installed_title)) + .setMessage("$displayName has been installed and is ready to use.") + .setPositiveButton(ctx.getString(CoreStrings.lsp_ok_button), null) + .show() } -} \ No newline at end of file +} diff --git a/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/AptPackageInstaller.kt b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/AptPackageInstaller.kt new file mode 100644 index 0000000000..3f46df1d1e --- /dev/null +++ b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/AptPackageInstaller.kt @@ -0,0 +1,185 @@ +/* + * This file is part of AndroidCodeStudio. + * + * AndroidCodeStudio is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidCodeStudio is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidCodeStudio. If not, see . + */ + +package com.tom.rv2ide.setup.servers + +import android.content.Context +import com.tom.rv2ide.shell.executeProcessAsync +import com.tom.rv2ide.utils.Environment +import java.io.BufferedReader +import java.io.File +import java.io.InputStreamReader + +/** + * Shared Termux APT package installer used for language toolchains (Clang, Python, Rust, etc.) + * and external build tools (Autotools, CMake, Ninja, Make). + */ +open class AptPackageInstaller( + protected val context: Context, + private val packages: List, + private val requiredBinaries: List, + private val displayName: String, +) : ILanguageServerInstaller { + + private var hasOverwriteError = false + private var hasUnmetDependencies = false + + override fun isInstalled(): Boolean { + return requiredBinaries.all { File(Environment.BIN_DIR, it).exists() } + } + + override fun install(onOutput: (String) -> Unit): Boolean { + return try { + val env = mutableMapOf() + Environment.putEnvironment(env, false) + + hasOverwriteError = false + hasUnmetDependencies = false + + if (!checkPackagingBinaries(onOutput)) { + onOutput("\nWarning: Packaging helpers missing from PATH, continuing anyway...") + } + + onOutput("\nRunning dpkg --configure -a...") + val dpkgExit = runAptTool("dpkg", listOf("--configure", "-a"), env, onOutput) + onOutput("\ndpkg --configure -a completed (exit code: $dpkgExit)") + + if (dpkgExit != 0 && hasOverwriteError) { + onOutput("\nDetected package conflict. Retrying with --force-overwrite...") + runAptTool("dpkg", listOf("--force-overwrite", "--configure", "-a"), env, onOutput) + } + + onOutput("\nUpdating package lists (apt --fix-missing update)...") + runAptTool("apt", listOf("--fix-missing", "update"), env, onOutput) + + val packageListLabel = packages.joinToString(" ") + onOutput("\nInstalling $displayName ($packageListLabel)...") + hasOverwriteError = false + hasUnmetDependencies = false + + val installExit = runAptTool("apt", listOf("install", "-y") + packages, env, onOutput) + onOutput("\n$displayName installation exited with code $installExit") + + if (installExit == 0 && isInstalled()) { + onOutput("\n$displayName installed successfully!") + return true + } + + if (hasOverwriteError || hasUnmetDependencies) { + onOutput("\nDetected package conflicts. Retrying with --force-overwrite...") + return installWithRecovery(env, onOutput) + } + + onOutput("\nRunning apt --fix-broken install...") + runAptTool("apt", listOf("--fix-broken", "install", "-y"), env, onOutput) + if (isInstalled()) { + onOutput("\n$displayName binaries found after recovery!") + return true + } + + onOutput("\n$displayName binaries not found after installation.") + false + } catch (e: Exception) { + onOutput("\nError during installation: ${e.message}") + false + } + } + + private fun installWithRecovery( + env: Map, + onOutput: (String) -> Unit, + ): Boolean { + val forceOpts = listOf("-o", "Dpkg::Options::=--force-overwrite") + runAptTool("apt", forceOpts + listOf("--fix-broken", "install", "-y"), env, onOutput) + if (isInstalled()) { + onOutput("\n$displayName binaries found after fix-broken!") + return true + } + + val retryExit = + runAptTool("apt", forceOpts + listOf("install", "-y") + packages, env, onOutput) + onOutput("\nForce installation completed (exit code: $retryExit)") + if (isInstalled()) { + onOutput("\n$displayName installed successfully!") + return true + } + + runAptTool("apt", forceOpts + listOf("install", "-f", "-y"), env, onOutput) + return isInstalled() + } + + private fun runAptTool( + toolName: String, + args: List, + env: Map, + onOutput: (String) -> Unit, + ): Int { + val process = executeProcessAsync { + command = listOf(File(Environment.BIN_DIR, toolName).absolutePath) + args + environment = env + workingDirectory = Environment.HOME + redirectErrorStream = true + } + readProcessOutput(process, onOutput) + return process.waitFor() + } + + private fun checkPackagingBinaries(onOutput: (String) -> Unit): Boolean { + return try { + onOutput("Checking system PATH...") + val sbinDir = File(Environment.PREFIX, "sbin") + if (!sbinDir.exists()) { + sbinDir.mkdirs() + } + if (!File(Environment.BIN_DIR, "dpkg-deb").exists()) { + onOutput("dpkg-deb not found in ${Environment.BIN_DIR.absolutePath}") + } + if (!File(Environment.BIN_DIR, "start-stop-daemon").exists()) { + onOutput("start-stop-daemon not found in ${Environment.BIN_DIR.absolutePath}") + } + true + } catch (e: Exception) { + onOutput("Error checking PATH: ${e.message}") + false + } + } + + private fun readProcessOutput(process: Process, onOutput: (String) -> Unit) { + BufferedReader(InputStreamReader(process.inputStream)).useLines { lines -> + var lineCount = 0 + lines.forEach { line -> + onOutput(line) + if ( + line.contains("trying to overwrite", ignoreCase = true) || + line.contains("which is also in package", ignoreCase = true) + ) { + hasOverwriteError = true + } + if ( + line.contains("Unmet dependencies", ignoreCase = true) || + line.contains("fix-broken install", ignoreCase = true) + ) { + hasUnmetDependencies = true + } + lineCount++ + if (lineCount % 5 == 0) { + Thread.sleep(10) + } + } + } + } +} diff --git a/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/clang/Clang.kt b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/clang/Clang.kt index a05d6dcfb7..c4e4fe4bfa 100644 --- a/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/clang/Clang.kt +++ b/java/lsp-setup/src/main/java/com/tom/rv2ide/setup/servers/clang/Clang.kt @@ -13,343 +13,20 @@ * * You should have received a copy of the GNU General Public License * along with AndroidCodeStudio. If not, see . -*/ + */ package com.tom.rv2ide.setup.servers.clang import android.content.Context -import com.tom.rv2ide.setup.servers.ILanguageServerInstaller -import com.tom.rv2ide.shell.executeProcessAsync -import com.tom.rv2ide.utils.Environment -import java.io.BufferedReader -import java.io.InputStreamReader -import java.io.File -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import kotlinx.coroutines.yield +import com.tom.rv2ide.setup.servers.AptPackageInstaller /** * @author Mohammed-baqer-null @ https://github.com/Mohammed-baqer-null */ - -class Clang(private val context: Context) : ILanguageServerInstaller { - - private var hasOverwriteError = false - private var hasUnmetDependencies = false - private val errorPatterns = listOf( - "trying to overwrite", - "which is also in package", - "returned an error code", - "Unmet dependencies" - ) - - override fun isInstalled(): Boolean { - val clangBinary = File(Environment.BIN_DIR, "clang") - val clangdBinary = File(Environment.BIN_DIR, "clangd") - return clangBinary.exists() && clangdBinary.exists() - } - - override fun install(onOutput: (String) -> Unit): Boolean { - return try { - val env = mutableMapOf() - Environment.putEnvironment(env, false) - - // Reset error flags - hasOverwriteError = false - hasUnmetDependencies = false - - // Fix PATH issues first - if (!fixSystemPath(env, onOutput)) { - onOutput("\nWarning: Could not fix PATH issues, continuing anyway...") - } - - onOutput("\nRunning dpkg --configure -a...") - - val dpkgProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/dpkg", - "--configure", - "-a" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(dpkgProcess, onOutput) - val dpkgExitCode = dpkgProcess.waitFor() - onOutput("\ndpkg --configure -a completed (exit code: $dpkgExitCode)") - - // If configure failed with overwrite error, try to fix it - if (dpkgExitCode != 0 && hasOverwriteError) { - onOutput("\nDetected package conflict. Attempting to resolve with --force-overwrite...") - forceConfigurePackages(env, onOutput) - } - - onOutput("\nRunning apt --fix-missing update...") - - val fixMissingProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/apt", - "--fix-missing", - "update" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(fixMissingProcess, onOutput) - fixMissingProcess.waitFor() - onOutput("\nApt --fix-missing update completed") - - // Try standard installation first - onOutput("\nInstalling clang...") - hasOverwriteError = false - hasUnmetDependencies = false - - val installProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/apt", - "install", - "clang", - "-y" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(installProcess, onOutput) - val installExitCode = installProcess.waitFor() - onOutput("\nClang installation command completed (exit code: $installExitCode)") - - // Check if installation was successful - if (installExitCode == 0 && isInstalled()) { - onOutput("\nClang installation successful!") - return true - } - - // If there's an overwrite error or unmet dependencies, use force-overwrite - if (hasOverwriteError || hasUnmetDependencies) { - onOutput("\nDetected package conflicts. Installing with --force-overwrite...") - return installWithForceOverwrite(env, onOutput) - } - - // Try fix-broken install - onOutput("\nInstallation incomplete. Running apt --fix-broken install...") - if (fixBrokenInstall(env, onOutput)) { - if (isInstalled()) { - onOutput("\nClang binaries found after fix!") - return true - } - } - - // Final check - onOutput("\nFinal check for clang binaries...") - if (isInstalled()) { - onOutput("Clang binaries found!") - true - } else { - onOutput("Clang binaries not found. Installation failed.") - onOutput("Please check the error messages above for details.") - false - } - } catch (e: Exception) { - onOutput("\nError during installation: ${e.message}") - e.printStackTrace() - false - } - } - - private fun fixSystemPath( - env: MutableMap, - onOutput: (String) -> Unit - ): Boolean { - return try { - onOutput("Checking system PATH...") - - // Ensure dpkg-deb and start-stop-daemon symlinks exist - val binDir = File(Environment.BIN_DIR.absolutePath) - val sbinDir = File(Environment.HOME, "usr/sbin") - - if (!sbinDir.exists()) { - sbinDir.mkdirs() - onOutput("Created sbin directory") - } - - val dpkgDeb = File(binDir, "dpkg-deb") - val startStopDaemon = File(binDir, "start-stop-daemon") - - if (!dpkgDeb.exists()) { - onOutput("dpkg-deb not found in PATH") - } - - if (!startStopDaemon.exists()) { - onOutput("start-stop-daemon not found in PATH") - } - - true - } catch (e: Exception) { - onOutput("Error checking PATH: ${e.message}") - false - } - } - - private fun forceConfigurePackages( - env: Map, - onOutput: (String) -> Unit - ): Boolean { - return try { - val forceDpkgProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/dpkg", - "--force-overwrite", - "--configure", - "-a" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(forceDpkgProcess, onOutput) - val exitCode = forceDpkgProcess.waitFor() - onOutput("\nForce configure completed (exit code: $exitCode)") - exitCode == 0 - } catch (e: Exception) { - onOutput("\nError during force configure: ${e.message}") - false - } - } - - private fun installWithForceOverwrite( - env: Map, - onOutput: (String) -> Unit - ): Boolean { - return try { - onOutput("\nAttempting installation with force-overwrite option...") - - // First, try to fix broken packages with force-overwrite - val fixBrokenProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/apt", - "-o", - "Dpkg::Options::=--force-overwrite", - "--fix-broken", - "install", - "-y" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(fixBrokenProcess, onOutput) - val fixExitCode = fixBrokenProcess.waitFor() - onOutput("\nFix broken installation completed (exit code: $fixExitCode)") - - // Check if binaries exist now - if (isInstalled()) { - onOutput("\nClang binaries found after fix-broken!") - return true - } - - // If not installed yet, try direct installation with force-overwrite - onOutput("\nRetrying clang installation with force-overwrite...") - - val forceInstallProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/apt", - "-o", - "Dpkg::Options::=--force-overwrite", - "install", - "clang", - "-y" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(forceInstallProcess, onOutput) - val installExitCode = forceInstallProcess.waitFor() - onOutput("\nForce installation completed (exit code: $installExitCode)") - - // Final check - val installed = isInstalled() - if (installed) { - onOutput("\nClang installation successful!") - } else { - onOutput("\nClang binaries still not found.") - - // One last attempt with install -f - onOutput("\nRunning final fix attempt...") - fixBrokenInstall(env, onOutput) - - return isInstalled() - } - - installed - } catch (e: Exception) { - onOutput("\nError during force installation: ${e.message}") - e.printStackTrace() - false - } - } - - private fun fixBrokenInstall( - env: Map, - onOutput: (String) -> Unit - ): Boolean { - return try { - val fixProcess = executeProcessAsync { - command = listOf( - Environment.BIN_DIR.absolutePath + "/apt", - "-o", - "Dpkg::Options::=--force-overwrite", - "install", - "-f", - "-y" - ) - environment = env - workingDirectory = Environment.HOME - redirectErrorStream = true - } - - readProcessOutput(fixProcess, onOutput) - val exitCode = fixProcess.waitFor() - onOutput("\nApt install -f completed (exit code: $exitCode)") - exitCode == 0 - } catch (e: Exception) { - onOutput("\nError during fix-broken install: ${e.message}") - false - } - } - - private fun readProcessOutput(process: Process, onOutput: (String) -> Unit) { - val reader = BufferedReader(InputStreamReader(process.inputStream)) - var lineCount = 0 - reader.useLines { lines -> - lines.forEach { line -> - onOutput(line) - - // Check for error patterns - if (line.contains("trying to overwrite", ignoreCase = true) || - line.contains("which is also in package", ignoreCase = true)) { - hasOverwriteError = true - } - - if (line.contains("Unmet dependencies", ignoreCase = true) || - line.contains("fix-broken install", ignoreCase = true)) { - hasUnmetDependencies = true - } - - lineCount++ - if (lineCount % 5 == 0) { - Thread.sleep(10) - } - } - } - } -} \ No newline at end of file +class Clang(context: Context) : + AptPackageInstaller( + context = context, + packages = listOf("clang"), + requiredBinaries = listOf("clang", "clangd"), + displayName = "Clang", + ) diff --git a/java/lsp-setup/src/main/res/layout/dialog_installation_progress.xml b/java/lsp-setup/src/main/res/layout/dialog_installation_progress.xml index 6cbe8fe8c1..24b182018b 100644 --- a/java/lsp-setup/src/main/res/layout/dialog_installation_progress.xml +++ b/java/lsp-setup/src/main/res/layout/dialog_installation_progress.xml @@ -14,6 +14,7 @@ android:padding="24dp"> = 34 + ? new Api34TerminalInputConnection() + : new TerminalInputConnection(); + } - @Override - public boolean finishComposingText() { - if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) mClient.logInfo(LOG_TAG, "IME: finishComposingText()"); - super.finishComposingText(); + /** + * Detect multi-line, tab, or control-sequence commits coming from keyboard clipboard + * paste while letting single "\n" Enter key presses and normal word commits pass through. + */ + static boolean shouldPasteCommittedText(@Nullable CharSequence text) { + if (text == null || text.length() <= 1) { + return false; + } + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '\n' || c == '\r' || c == '\t' || c == '\u001B' || (c >= 0x80 && c <= 0x9F)) { + return true; + } + } + return false; + } - sendTextToTerminal(getEditable()); - getEditable().clear(); + private boolean handlePasteMenuAction(int id) { + if (id == android.R.id.paste || id == android.R.id.pasteAsPlainText) { + if (mTermSession != null) { + mTermSession.onPasteTextFromClipboard(); return true; } + } + return false; + } - @Override - public boolean commitText(CharSequence text, int newCursorPosition) { - if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { - mClient.logInfo(LOG_TAG, "IME: commitText(\"" + text + "\", " + newCursorPosition + ")"); - } - super.commitText(text, newCursorPosition); + private class TerminalInputConnection extends BaseInputConnection { - if (mEmulator == null) return true; + TerminalInputConnection() { + super(TerminalView.this, true); + } - Editable content = getEditable(); - sendTextToTerminal(content); - content.clear(); + @Override + public boolean finishComposingText() { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) mClient.logInfo(LOG_TAG, "IME: finishComposingText()"); + super.finishComposingText(); + + sendTextToTerminal(getEditable()); + getEditable().clear(); + return true; + } + + @Override + public boolean commitText(CharSequence text, int newCursorPosition) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "IME: commitText(\"" + text + "\", " + newCursorPosition + ")"); + } + super.commitText(text, newCursorPosition); + + if (mEmulator == null) return true; + + Editable content = getEditable(); + sendTextToTerminal(content); + content.clear(); + return true; + } + + @Override + public boolean performContextMenuAction(int id) { + if (handlePasteMenuAction(id)) { return true; } + return super.performContextMenuAction(id); + } - @Override - public boolean deleteSurroundingText(int leftLength, int rightLength) { - if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { - mClient.logInfo(LOG_TAG, "IME: deleteSurroundingText(" + leftLength + ", " + rightLength + ")"); - } - // The stock Samsung keyboard with 'Auto check spelling' enabled sends leftLength > 1. - KeyEvent deleteKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL); - for (int i = 0; i < leftLength; i++) sendKeyEvent(deleteKey); - return super.deleteSurroundingText(leftLength, rightLength); + @Override + public boolean deleteSurroundingText(int leftLength, int rightLength) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "IME: deleteSurroundingText(" + leftLength + ", " + rightLength + ")"); } + // The stock Samsung keyboard with 'Auto check spelling' enabled sends leftLength > 1. + KeyEvent deleteKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL); + for (int i = 0; i < leftLength; i++) sendKeyEvent(deleteKey); + return super.deleteSurroundingText(leftLength, rightLength); + } - void sendTextToTerminal(CharSequence text) { - stopTextSelectionMode(); - final int textLengthInChars = text.length(); - for (int i = 0; i < textLengthInChars; i++) { - char firstChar = text.charAt(i); - int codePoint; - if (Character.isHighSurrogate(firstChar)) { - if (++i < textLengthInChars) { - codePoint = Character.toCodePoint(firstChar, text.charAt(i)); - } else { - // At end of string, with no low surrogate following the high: - codePoint = TerminalEmulator.UNICODE_REPLACEMENT_CHAR; - } + void sendTextToTerminal(CharSequence text) { + stopTextSelectionMode(); + if (mEmulator != null && shouldPasteCommittedText(text)) { + mEmulator.paste(text.toString()); + return; + } + final int textLengthInChars = text.length(); + for (int i = 0; i < textLengthInChars; i++) { + char firstChar = text.charAt(i); + int codePoint; + if (Character.isHighSurrogate(firstChar)) { + if (++i < textLengthInChars) { + codePoint = Character.toCodePoint(firstChar, text.charAt(i)); } else { - codePoint = firstChar; + // At end of string, with no low surrogate following the high: + codePoint = TerminalEmulator.UNICODE_REPLACEMENT_CHAR; } + } else { + codePoint = firstChar; + } - // Check onKeyDown() for details. - if (mClient.readShiftKey()) - codePoint = Character.toUpperCase(codePoint); - - boolean ctrlHeld = false; - if (codePoint <= 31 && codePoint != 27) { - if (codePoint == '\n') { - // The AOSP keyboard and descendants seems to send \n as text when the enter key is pressed, - // instead of a key event like most other keyboard apps. A terminal expects \r for the enter - // key (although when icrnl is enabled this doesn't make a difference - run 'stty -icrnl' to - // check the behaviour). - codePoint = '\r'; - } - - // E.g. penti keyboard for ctrl input. - ctrlHeld = true; - switch (codePoint) { - case 31: - codePoint = '_'; - break; - case 30: - codePoint = '^'; - break; - case 29: - codePoint = ']'; - break; - case 28: - codePoint = '\\'; - break; - default: - codePoint += 96; - break; - } + // Check onKeyDown() for details. + if (mClient.readShiftKey()) + codePoint = Character.toUpperCase(codePoint); + + boolean ctrlHeld = false; + if (codePoint <= 31 && codePoint != 27) { + if (codePoint == '\n') { + // The AOSP keyboard and descendants seems to send \n as text when the enter key is pressed, + // instead of a key event like most other keyboard apps. A terminal expects \r for the enter + // key (although when icrnl is enabled this doesn't make a difference - run 'stty -icrnl' to + // check the behaviour). + codePoint = '\r'; } - inputCodePoint(KEY_EVENT_SOURCE_SOFT_KEYBOARD, codePoint, ctrlHeld, false); + // E.g. penti keyboard for ctrl input. + ctrlHeld = true; + switch (codePoint) { + case 31: + codePoint = '_'; + break; + case 30: + codePoint = '^'; + break; + case 29: + codePoint = ']'; + break; + case 28: + codePoint = '\\'; + break; + default: + codePoint += 96; + break; + } } + + inputCodePoint(KEY_EVENT_SOURCE_SOFT_KEYBOARD, codePoint, ctrlHeld, false); + } + } + } + + /** Separate subclass avoids loading API 34 TextAttribute on older Android runtimes. */ + @RequiresApi(api = 34) + private final class Api34TerminalInputConnection extends TerminalInputConnection { + @Override + public boolean replaceText( + int start, + int end, + @NonNull CharSequence text, + int newCursorPosition, + @Nullable TextAttribute textAttribute) { + if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) { + mClient.logInfo(LOG_TAG, "IME: replaceText(\"" + text + "\")"); + } + if (mEmulator == null) { + return super.replaceText(start, end, text, newCursorPosition, textAttribute); } - }; + Editable content = getEditable(); + if (start >= 0 && end >= start && end <= content.length()) { + super.replaceText(start, end, text, newCursorPosition, textAttribute); + sendTextToTerminal(content); + content.clear(); + } else { + // TerminalView keeps an ephemeral Editable, so forward text directly if indices exceed it. + content.clear(); + sendTextToTerminal(text); + } + return true; + } } @Override @@ -740,8 +819,20 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } else if (event.isSystem() && (!mClient.shouldBackButtonBeMappedToEscape() || keyCode != KeyEvent.KEYCODE_BACK)) { return super.onKeyDown(keyCode, event); + } else if (keyCode == KeyEvent.KEYCODE_PASTE) { + if (mTermSession != null) { + mTermSession.onPasteTextFromClipboard(); + return true; + } } else if (event.getAction() == KeyEvent.ACTION_MULTIPLE && keyCode == KeyEvent.KEYCODE_UNKNOWN) { - mTermSession.write(event.getCharacters()); + String chars = event.getCharacters(); + if (chars != null) { + if (shouldPasteCommittedText(chars)) { + mEmulator.paste(chars); + } else { + mTermSession.write(chars); + } + } return true; } diff --git a/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/Main.kt b/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/Main.kt index 1405588188..d86c1f3d65 100644 --- a/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/Main.kt +++ b/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/Main.kt @@ -28,8 +28,10 @@ import com.tom.rv2ide.tooling.api.util.ToolingApiLauncher import com.tom.rv2ide.tooling.impl.internal.ProjectImpl import com.tom.rv2ide.tooling.impl.progress.ForwardingProgressListener import java.io.ByteArrayInputStream +import java.io.File import java.nio.charset.StandardCharsets import java.util.Locale +import java.util.Properties import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import java.util.concurrent.Future @@ -46,11 +48,19 @@ object Main { @Volatile var future: Future? = null + @Volatile var activeProjectDir: File? = null + @JvmStatic fun main(args: Array) { // disable the JVM std.err appender System.setProperty(JvmStdErrAppender.PROP_JVM_STDERR_APPENDER_ENABLED, "false") + // Align OpenJDK user.home and tmpdir with Termux/IDE env instead of getpwuid or /tmp fallbacks + System.getenv("HOME")?.takeIf { it.isNotBlank() }?.let { System.setProperty("user.home", it) } + System.getenv("TMPDIR")?.takeIf { it.isNotBlank() }?.let { + System.setProperty("java.io.tmpdir", it) + } + // Force encoding/locale as early as possible in this JVM System.setProperty("file.encoding", "UTF-8") System.setProperty("sun.jnu.encoding", "UTF-8") @@ -133,26 +143,9 @@ object Main { launcher.setStandardOutput(out) launcher.setStandardInput(ByteArrayInputStream("NoOp".toByteArray(StandardCharsets.UTF_8))) - // Ensure JVM platform encoding and locale are initialized before Gradle starts - launcher.setJvmArguments( - "-Dfile.encoding=UTF-8", - "-Dsun.jnu.encoding=UTF-8", - "-Duser.language=en", - "-Duser.country=US", - "-Dsun.stdout.encoding=UTF-8", - "-Dsun.stderr.encoding=UTF-8", - "-Dnative.encoding=UTF-8", - "-Dorg.gradle.daemon.idletimeout=10800000", // 3 hours in milliseconds - - ) - - // Also enforce via environment for any forked JVM - val env: MutableMap = HashMap() - env["JAVA_TOOL_OPTIONS"] = - "-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -Duser.language=en -Duser.country=US" - env["GRADLE_OPTS"] = "-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8" - env["LANG"] = "en_US.UTF-8" - env["LC_ALL"] = "en_US.UTF-8" + val env = buildDaemonEnvironment() + val jvmArgs = buildDaemonJvmArguments(activeProjectDir, env) + launcher.setJvmArguments(*jvmArgs.toTypedArray()) // Inject proxy if server started one and exposed its port var proxyPort: String? = System.getenv("ANDROIDIDE_PROXY_PORT") @@ -177,14 +170,6 @@ object Main { } launcher.setEnvironmentVariables(env) - // launcher.addArguments("--no-daemon") - // launcher.setJvmArguments( - // "-Xmx4g", - // "-XX:+UseG1GC", - // "-Dfile.encoding=UTF-8", - // "-Dkotlin.daemon.jvm.options=-Xmx2g" - // ); - launcher.addProgressListener(ForwardingProgressListener(), progressUpdateTypes()) client?.let { c -> @@ -199,6 +184,145 @@ object Main { } } + private fun buildDaemonEnvironment(): MutableMap { + // Preserve Termux/IDE env (ANDROID_HOME, GRADLE_USER_HOME, HOME, TMPDIR, PATH, JAVA_HOME) + val env: MutableMap = HashMap(System.getenv()) + + val home = env["HOME"]?.takeIf { it.isNotBlank() } + if (home != null && env["GRADLE_USER_HOME"].isNullOrBlank()) { + env["GRADLE_USER_HOME"] = File(home, ".gradle").absolutePath + } + + val androidHome = env["ANDROID_HOME"]?.takeIf { it.isNotBlank() } + val androidSdkRoot = env["ANDROID_SDK_ROOT"]?.takeIf { it.isNotBlank() } + if (androidHome != null && androidSdkRoot == null) { + env["ANDROID_SDK_ROOT"] = androidHome + } else if (androidSdkRoot != null && androidHome == null) { + env["ANDROID_HOME"] = androidSdkRoot + } + + env["JAVA_TOOL_OPTIONS"] = + mergeJvmOptString( + env["JAVA_TOOL_OPTIONS"], + listOf( + "-Dfile.encoding=UTF-8", + "-Dsun.jnu.encoding=UTF-8", + "-Duser.language=en", + "-Duser.country=US", + ), + ) + env["GRADLE_OPTS"] = + mergeJvmOptString( + env["GRADLE_OPTS"], + listOf("-Dfile.encoding=UTF-8", "-Dsun.jnu.encoding=UTF-8"), + ) + env["LANG"] = env["LANG"]?.takeIf { it.isNotBlank() } ?: "en_US.UTF-8" + env["LC_ALL"] = env["LC_ALL"]?.takeIf { it.isNotBlank() } ?: "en_US.UTF-8" + return env + } + + private fun buildDaemonJvmArguments(projectDir: File?, env: Map): List { + // setJvmArguments overrides gradle.properties, so merge org.gradle.jvmargs explicitly + val args = ArrayList() + val configured = readConfiguredGradleJvmArgs(projectDir, env) + if (!configured.isNullOrBlank()) { + args.addAll(splitJvmArgs(configured)) + } + + val required = + mutableListOf( + "-Dfile.encoding=UTF-8", + "-Dsun.jnu.encoding=UTF-8", + "-Duser.language=en", + "-Duser.country=US", + "-Dsun.stdout.encoding=UTF-8", + "-Dsun.stderr.encoding=UTF-8", + "-Dnative.encoding=UTF-8", + "-Dorg.gradle.daemon.idletimeout=10800000", + ) + env["HOME"]?.takeIf { it.isNotBlank() }?.let { required.add("-Duser.home=$it") } + env["TMPDIR"]?.takeIf { it.isNotBlank() }?.let { required.add("-Djava.io.tmpdir=$it") } + + appendMissingJvmArgs(args, args, required) + return args + } + + private fun readConfiguredGradleJvmArgs(projectDir: File?, env: Map): String? { + val candidates = ArrayList(2) + if (projectDir != null) { + candidates.add(File(projectDir, "gradle.properties")) + } + val gradleUserHome = + env["GRADLE_USER_HOME"]?.takeIf { it.isNotBlank() } + ?: env["HOME"]?.takeIf { it.isNotBlank() }?.let { File(it, ".gradle").absolutePath } + if (gradleUserHome != null) { + candidates.add(File(gradleUserHome, "gradle.properties")) + } + for (file in candidates) { + if (!file.isFile) continue + try { + val props = Properties() + file.inputStream().use { props.load(it) } + val jvmArgs = props.getProperty("org.gradle.jvmargs")?.trim() + if (!jvmArgs.isNullOrEmpty()) { + return jvmArgs + } + } catch (_: Throwable) {} + } + return null + } + + private fun mergeJvmOptString(existing: String?, required: List): String { + val trimmed = existing?.trim().orEmpty() + val parsed: List = if (trimmed.isEmpty()) emptyList() else splitJvmArgs(trimmed) + val missing = ArrayList() + appendMissingJvmArgs(missing, parsed, required) + if (trimmed.isEmpty()) return missing.joinToString(" ") + if (missing.isEmpty()) return trimmed + return "$trimmed ${missing.joinToString(" ")}" + } + + private fun appendMissingJvmArgs( + target: MutableList, + existing: List, + required: List, + ) { + for (arg in required) { + val keyPrefix = + if (arg.startsWith("-D") && arg.contains('=')) arg.substringBefore('=') + "=" else null + val alreadyPresent = + existing.any { it == arg || (keyPrefix != null && it.startsWith(keyPrefix)) } + if (!alreadyPresent) { + target.add(arg) + } + } + } + + private fun splitJvmArgs(raw: String): MutableList { + val result = ArrayList() + val current = StringBuilder() + var quoteChar: Char? = null + for (ch in raw) { + when { + quoteChar != null -> { + if (ch == quoteChar) quoteChar = null else current.append(ch) + } + ch == '"' || ch == '\'' -> quoteChar = ch + ch.isWhitespace() -> { + if (current.isNotEmpty()) { + result.add(current.toString()) + current.setLength(0) + } + } + else -> current.append(ch) + } + } + if (current.isNotEmpty()) { + result.add(current.toString()) + } + return result + } + fun progressUpdateTypes(): Set { val types = HashSet() // AndroidIDE currently does not handle any other type of events diff --git a/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/ToolingApiServerImpl.kt b/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/ToolingApiServerImpl.kt index 8818dfcb50..2534f02735 100644 --- a/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/ToolingApiServerImpl.kt +++ b/tooling/impl/src/main/java/com/tom/rv2ide/tooling/impl/ToolingApiServerImpl.kt @@ -51,6 +51,7 @@ import com.tom.rv2ide.tooling.impl.sync.RootModelBuilder import com.tom.rv2ide.tooling.impl.sync.RootProjectModelBuilderParams import com.tom.rv2ide.utils.StopWatch import java.io.File +import java.util.Properties import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionException import java.util.concurrent.locks.ReentrantLock @@ -137,8 +138,10 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling return@runBuild InitializeResult(false, failureReason) } - // Ensure Gradle sees UTF-8/locale early via project gradle.properties + Main.activeProjectDir = projectDirectory + // Ensure Gradle sees UTF-8/locale and valid Android SDK early via project properties ensureProjectGradleProperties(projectDirectory) + ensureProjectLocalProperties(projectDirectory) val stopWatch = StopWatch("Connection to project") val isReinitializing = connector != null && connection != null && params == lastInitParams @@ -214,6 +217,7 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling return@runBuild InitializeResult(true) } catch (err: Throwable) { log.error("Failed to initialize project", err) + logFailureToClient("Failed to initialize project", err) notifyBuildFailure(emptyList()) return@runBuild InitializeResult(false, getTaskFailureType(err)) } @@ -223,7 +227,7 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling private fun ensureProjectGradleProperties(projectDir: File) { try { val propsFile = File(projectDir, "gradle.properties") - val props = java.util.Properties() + val props = Properties() if (propsFile.exists()) propsFile.inputStream().use { props.load(it) } val jvmArgsKey = "org.gradle.jvmargs" @@ -255,6 +259,51 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling } } + private fun ensureProjectLocalProperties(projectDir: File) { + val sdkPath = + System.getenv("ANDROID_HOME")?.takeIf { it.isNotBlank() } + ?: System.getenv("ANDROID_SDK_ROOT")?.takeIf { it.isNotBlank() } + ?: return + val sdkDir = File(sdkPath) + if (!sdkDir.isDirectory) { + return + } + try { + val localPropsFile = File(projectDir, "local.properties") + val props = Properties() + if (localPropsFile.exists()) { + localPropsFile.inputStream().use { props.load(it) } + } + val existingSdkDir = props.getProperty("sdk.dir")?.trim().orEmpty() + if (existingSdkDir.isEmpty() || !File(existingSdkDir).isDirectory) { + props.setProperty("sdk.dir", sdkDir.absolutePath) + localPropsFile.outputStream().use { out -> + props.store(out, "AndroidCS: generated local SDK location") + } + } + } catch (_: Throwable) { + // best-effort; ignore + } + } + + private fun logFailureToClient(prefix: String, error: Throwable) { + val c = client ?: return + val messages = LinkedHashSet() + var current: Throwable? = error + var depth = 0 + while (current != null && depth < 8) { + val msg = current.message?.trim() + if (!msg.isNullOrEmpty()) { + messages.add("${current.javaClass.simpleName}: $msg") + } else { + messages.add(current.javaClass.simpleName) + } + current = current.cause + depth++ + } + c.logOutput("$prefix: ${messages.joinToString(" <- ")}") + } + private fun validateProjectDirectory(projectDirectory: File) = when { !projectDirectory.exists() -> PROJECT_NOT_FOUND @@ -322,6 +371,7 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling notifyBuildSuccess(message.tasks) return@runBuild TaskExecutionResult.SUCCESS } catch (error: Throwable) { + logFailureToClient("Task execution failed", error) notifyBuildFailure(message.tasks) return@runBuild TaskExecutionResult(false, getTaskFailureType(error)) } @@ -332,13 +382,18 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling connector: GradleConnector, params: GradleDistributionParams, ) { + resolveGradleUserHomeDir()?.let { gradleUserHome -> + connector.useGradleUserHomeDir(gradleUserHome) + } + when (params.type) { GradleDistributionType.GRADLE_WRAPPER -> { log.info("Using Gradle wrapper for build...") } GradleDistributionType.GRADLE_INSTALLATION -> { - val file = File(params.value) + val resolvedPath = expandHomePrefix(params.value) + val file = File(resolvedPath) if (!file.exists() || !file.isDirectory) { log.error("Specified Gradle installation does not exist: {}", params) return @@ -355,6 +410,28 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling } } + private fun resolveGradleUserHomeDir(): File? { + val path = + System.getenv("GRADLE_USER_HOME")?.takeIf { it.isNotBlank() } + ?: System.getenv("HOME")?.takeIf { it.isNotBlank() }?.let { File(it, ".gradle").absolutePath } + ?: return null + val dir = File(path) + if (!dir.exists()) { + dir.mkdirs() + } + return dir.takeIf { it.isDirectory } + } + + private fun expandHomePrefix(path: String): String { + val home = System.getenv("HOME")?.takeIf { it.isNotBlank() } ?: return path + val trimmed = path.trim() + return when { + trimmed == "~" -> home + trimmed.startsWith("~/") -> File(home, trimmed.removePrefix("~/")).absolutePath + else -> trimmed + } + } + private fun notifyBuildFailure(tasks: List) { client?.onBuildFailed(BuildResult((tasks))) } @@ -418,6 +495,7 @@ internal class ToolingApiServerImpl(private val project: ProjectImpl) : ITooling this.client = null this.buildCancellationToken = null // connector.disconnect() cancels any running builds this.lastInitParams = null + Main.activeProjectDir = null Main.future = null Main.client = null diff --git a/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/base.kt b/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/base.kt index 2f052d2c97..88b25822c5 100644 --- a/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/base.kt +++ b/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/base.kt @@ -72,8 +72,15 @@ internal fun getLastSaveLocation(context: Context?): String { val props = java.util.Properties() acsideFile.inputStream().use { props.load(it) } val savedLocation = props.getProperty(ACSIDE_KEY_LAST_SAVE_LOCATION) - if (savedLocation != null && File(savedLocation).exists()) { - return savedLocation + if (savedLocation != null) { + if (Environment.isLegacyProjectsPath(savedLocation)) { + val migrated = Environment.PROJECTS_DIR.absolutePath + saveLastSaveLocation(context, migrated) + return migrated + } + if (File(savedLocation).exists()) { + return savedLocation + } } } catch (e: Exception) { e.printStackTrace() diff --git a/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/modules/android/buildGradle.kt b/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/modules/android/buildGradle.kt index a2e931475b..01c734f03c 100644 --- a/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/modules/android/buildGradle.kt +++ b/utilities/templates-api/src/main/java/com/tom/rv2ide/templates/base/modules/android/buildGradle.kt @@ -212,19 +212,15 @@ private fun AndroidModuleTemplateBuilder.hasNativeFiles(): Boolean { return androidMkFile.exists() || cmakeListsFile.exists() } -private fun AndroidModuleTemplateBuilder.isNdkInstalled(): Boolean { - val ndkBuildFile = File(Environment.ANDROID_HOME, "ndk/28.2.13676358/ndk-build") - return ndkBuildFile.exists() -} +private fun AndroidModuleTemplateBuilder.isNdkInstalled(): Boolean = Environment.isNdkInstalled() private fun AndroidModuleTemplateBuilder.showNdkNotInstalledDialog(context: Context) { MaterialAlertDialogBuilder(context) .setTitle("NDK Not Found") .setMessage( - "A compatible NDK (version 28.2.13676358) is not installed.\n\n" + + "No installed Android NDK was found under ${File(Environment.ANDROID_HOME, "ndk").absolutePath}.\n\n" + "Native code features will be disabled for this project.\n\n" + - "To enable native development, please install NDK version 28.2.13676358 " + - "open a terminal then run: 'idesetup -y -c -wn'." + "To enable native development, install an NDK via IDE Configurations or open a terminal and run 'idesetup -y -c -wn'." ) .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() } .setCancelable(false) @@ -234,7 +230,8 @@ private fun AndroidModuleTemplateBuilder.showNdkNotInstalledDialog(context: Cont private fun AndroidModuleTemplateBuilder.buildGradleSrcKts(isComposeModule: Boolean): String { val shouldUseNdk = data.useNdk val hasNative = hasNativeFiles() || shouldUseNdk - val ndkInstalled = isNdkInstalled() + val installedNdkVersion = Environment.getHighestInstalledNdkVersion() + val ndkInstalled = installedNdkVersion != null // Calculate compileSdk value first val compileSdkValue = if (isComposeModule) 36 else data.versions.compileSdk.api @@ -250,7 +247,7 @@ plugins { android { namespace = "${data.packageName}" compileSdk = $compileSdkValue - ${if (hasNative && ndkInstalled) """ndkVersion = "28.2.13676358"""" else ""} + ${if (hasNative && ndkInstalled) """ndkVersion = "$installedNdkVersion"""" else ""} defaultConfig { applicationId = "${data.packageName}" @@ -302,7 +299,8 @@ ${dependencies()} private fun AndroidModuleTemplateBuilder.buildGradleSrcGroovy(isComposeModule: Boolean): String { val shouldUseNdk = data.useNdk val hasNative = hasNativeFiles() || shouldUseNdk - val ndkInstalled = isNdkInstalled() + val installedNdkVersion = Environment.getHighestInstalledNdkVersion() + val ndkInstalled = installedNdkVersion != null // Calculate compileSdk value first val compileSdkValue = if (isComposeModule) 36 else data.versions.compileSdk.api @@ -319,7 +317,7 @@ plugins { android { namespace '${data.packageName}' compileSdk $compileSdkValue - ${if (hasNative && ndkInstalled) """ndkVersion '28.2.13676358'""" else ""} + ${if (hasNative && ndkInstalled) """ndkVersion '$installedNdkVersion'""" else ""} defaultConfig { applicationId "${data.packageName}"