From 58b95eb232d8dddf3a9ed7a9c16ccfc103e73c25 Mon Sep 17 00:00:00 2001 From: IQ-HARRY7 Date: Mon, 30 Nov 2026 10:37:50 +0000 Subject: [PATCH 1/5] fix: private storage projects, unrestricted file browser, terminal paste, and build safeguards --- .gitignore | 3 + .../rv2ide/activities/FileBrowserActivity.kt | 62 ++--- .../net/ConnectionManager.kt | 8 +- .../activities/editor/BaseEditorActivity.kt | 28 -- .../tom/rv2ide/configurations/FBProperties.kt | 6 +- .../tom/rv2ide/configurations/GCProperties.kt | 7 +- .../fragments/FileBrowserDialogFragment.kt | 148 ++++++----- .../rv2ide/fragments/FileBrowserFragment.kt | 156 +++++++---- .../com/tom/rv2ide/fragments/InitFragment.kt | 39 ++- .../com/tom/rv2ide/fragments/MainFragment.kt | 144 ++++++----- .../tom/rv2ide/fragments/TerminalFragment.kt | 23 +- .../java/com/tom/rv2ide/git/GitManager.kt | 37 ++- .../handlers/EditorBuildEventListener.kt | 10 +- .../system/installer/IPackageInstaller.kt | 52 ++-- .../rv2ide/provider/IDEDocumentsProvider.java | 12 +- .../services/builder/GradleBuildService.kt | 12 +- .../services/builder/ToolingServerRunner.kt | 30 ++- .../tom/rv2ide/templates/AtcWizardDialog.kt | 54 +++- .../preferences/WizardPreferences.kt | 10 +- .../utils/FileBrowserNavigationHelper.kt | 195 ++++++++++++++ .../com/tom/rv2ide/viewmodel/GitViewModel.kt | 2 +- .../main/res/layout/dialog_file_browser.xml | 79 +++++- .../main/res/layout/fragment_file_browser.xml | 98 ++++++- core/app/src/main/res/menu/menu_main.xml | 11 + .../com/tom/rv2ide/managers/ToolsManager.java | 13 +- .../com/tom/rv2ide/utils/Environment.java | 110 +++++++- .../java/com/termux/app/TerminalFragment.java | 15 +- .../src/main/res/layout/activity_termux.xml | 1 - .../src/main/res/layout/frag_terminal.xml | 1 - .../com/termux/terminal/TerminalEmulator.java | 1 + .../java/com/termux/view/TerminalView.java | 243 ++++++++++++------ .../com/tom/rv2ide/templates/base/base.kt | 11 +- .../base/modules/android/buildGradle.kt | 20 +- 33 files changed, 1201 insertions(+), 440 deletions(-) create mode 100644 core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt diff --git a/.gitignore b/.gitignore index 7b56132fae..0298dd1e58 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,9 @@ autopush.sh /server local.properties +# personal ideas +current-idea.md + # Crowdin crowdin.properties .idea/crowdin_settings.xml 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..bc3d46fa57 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 @@ -1161,34 +1161,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/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..1bc57b15de 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 @@ -168,20 +168,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/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..40b260276b 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 @@ -326,6 +326,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 +390,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}") @@ -499,7 +506,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) { 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..1566dd165c 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 @@ -73,8 +73,20 @@ internal class ToolingServerRunner( fun startAsync(envs: Map) = runnerScope .launch { - var process: Process? + var process: Process? = null + var notifiedExit = false try { + 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 +138,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 +209,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/templates/AtcWizardDialog.kt b/core/app/src/main/java/com/tom/rv2ide/templates/AtcWizardDialog.kt index 2a95e15f38..2e86a498b6 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 @@ -290,10 +290,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 +303,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,17 +347,24 @@ 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) } } 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..a733fc451b --- /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 trimmed = path.trim() + if (trimmed.isEmpty()) return "/" + return if (trimmed.length > 1) trimmed.trimEnd('/') else trimmed + } + + 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/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/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 @@ + + + + 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); + } + + 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/termux/application/src/main/java/com/termux/app/TerminalFragment.java b/termux/application/src/main/java/com/termux/app/TerminalFragment.java index 1b28777b78..e521374e98 100644 --- a/termux/application/src/main/java/com/termux/app/TerminalFragment.java +++ b/termux/application/src/main/java/com/termux/app/TerminalFragment.java @@ -50,6 +50,7 @@ import com.termux.shared.android.PermissionUtils; import com.termux.shared.data.DataUtils; import com.termux.shared.data.IntentUtils; +import com.termux.shared.interact.ShareUtils; import com.termux.shared.logger.Logger; import com.termux.shared.termux.TermuxConstants; import com.termux.shared.termux.TermuxUtils; @@ -98,6 +99,15 @@ public class TerminalFragment extends Fragment implements ServiceConnection { protected TermuxSessionsListViewController mTermuxSessionListViewController; protected Toast mLastToast; protected boolean mIsVisible; + + protected void pasteFromClipboard() { + Context ctx = getContext(); + if (ctx == null || mTerminalView == null || mTerminalView.mEmulator == null) return; + String text = ShareUtils.getTextStringFromClipboardIfSet(ctx, true); + if (text != null && !text.isEmpty()) { + mTerminalView.mEmulator.paste(text); + } + } protected boolean mIsInvalidState; protected int mNavBarHeight; protected float mTerminalToolbarDefaultHeight; @@ -1190,8 +1200,7 @@ public void setTerminalShellPid(@NonNull TerminalSession terminalSession, int pi @Override public void onPasteTextFromClipboard(@Nullable TerminalSession session) { - // Simplified - skip clipboard paste for now - // This would require clipboard access in the fragment + mFragment.pasteFromClipboard(); } @Override @@ -1396,7 +1405,7 @@ public void onTerminalExtraKeyButtonClick(View view, String key, boolean ctrlDow } else if ("DRAWER".equals(key)) { // Simplified - no drawer in standalone mode } else if ("PASTE".equals(key)) { - // Simplified - skip paste for now + mFragment.pasteFromClipboard(); } else if ("SCROLL".equals(key)) { if (mFragment.mTerminalView != null && mFragment.mTerminalView.mEmulator != null) { mFragment.mTerminalView.mEmulator.toggleAutoScrollDisabled(); diff --git a/termux/application/src/main/res/layout/activity_termux.xml b/termux/application/src/main/res/layout/activity_termux.xml index 61e5eee1c7..51daed03db 100644 --- a/termux/application/src/main/res/layout/activity_termux.xml +++ b/termux/application/src/main/res/layout/activity_termux.xml @@ -31,7 +31,6 @@ android:scrollbarThumbVertical="@drawable/terminal_scroll_shape" android:scrollbars="vertical" android:importantForAutofill="no" - android:autofillHints="password" tools:ignore="UnusedAttribute" /> = 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/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}" From e9284b379810205019c3c6f433f9433e3e32a7b3 Mon Sep 17 00:00:00 2001 From: IQ-HARRY7 Date: Mon, 30 Nov 2026 11:01:02 +0000 Subject: [PATCH 2/5] fix: fall back to debug signing when custom keystore passwords are missing --- core/app/build.gradle.kts | 50 +++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/core/app/build.gradle.kts b/core/app/build.gradle.kts index 4f6ff47721..1eae07712b 100755 --- a/core/app/build.gradle.kts +++ b/core/app/build.gradle.kts @@ -74,19 +74,41 @@ 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 = + customKeyStoreFile.exists() && + !signingStorePassword.isNullOrBlank() && + !signingKeyPassword.isNullOrBlank() + 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 +118,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 } } From 59670129686c77cf854097f146dface8c5330112 Mon Sep 17 00:00:00 2001 From: IQ-HARRY7 Date: Mon, 30 Nov 2026 11:24:41 +0000 Subject: [PATCH 3/5] fix: validate custom keystore credentials before using custom signing --- .../build/config/SigningKeyProperties.kt | 8 +++--- .../tom/rv2ide/plugins/SigningConfigPlugin.kt | 4 +-- core/app/build.gradle.kts | 27 ++++++++++++++++++- 3 files changed, 32 insertions(+), 7 deletions(-) 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 1eae07712b..a37301999b 100755 --- a/core/app/build.gradle.kts +++ b/core/app/build.gradle.kts @@ -96,9 +96,34 @@ android { val customKeyAlias = localProps.getProperty("signing.keyAlias")?.takeIf { it.isNotBlank() } ?: "androidcs" val hasCustomSigning = - customKeyStoreFile.exists() && + if (customKeyStoreFile.exists() && !signingStorePassword.isNullOrBlank() && !signingKeyPassword.isNullOrBlank() + ) { + try { + val ks = + java.security.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) { From 6ecb52d5313599d570cf08ea8a4df20785ad17fa Mon Sep 17 00:00:00 2001 From: IQ-HARRY7 Date: Mon, 30 Nov 2026 11:32:22 +0000 Subject: [PATCH 4/5] fix: import KeyStore explicitly in core/app/build.gradle.kts --- core/app/build.gradle.kts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/core/app/build.gradle.kts b/core/app/build.gradle.kts index a37301999b..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 { @@ -101,11 +102,7 @@ android { !signingKeyPassword.isNullOrBlank() ) { try { - val ks = - java.security.KeyStore.getInstance( - customKeyStoreFile, - signingStorePassword.toCharArray(), - ) + val ks = KeyStore.getInstance(customKeyStoreFile, signingStorePassword.toCharArray()) val key = ks.getKey(customKeyAlias, signingKeyPassword.toCharArray()) if (key == null) { logger.warn( From c20bb74596c84e32a9dd07562126bc7bfb75646d Mon Sep 17 00:00:00 2001 From: IQ-HARRY7 Date: Mon, 30 Nov 2026 13:12:08 +0000 Subject: [PATCH 5/5] fix: preserve Gradle tooling env, SDK resolution, and ~ home handling --- .gitignore | 4 + .../editor/ProjectHandlerActivity.kt | 20 +- .../handlers/EditorBuildEventListener.kt | 10 +- .../services/builder/GradleBuildService.kt | 8 + .../services/builder/ToolingServerRunner.kt | 2 + .../com/tom/rv2ide/services/builder/util.kt | 6 +- .../tom/rv2ide/templates/AtcWizardDialog.kt | 6 +- .../utils/FileBrowserNavigationHelper.kt | 6 +- .../com/tom/rv2ide/managers/ToolsManager.java | 87 ++++++--- .../com/tom/rv2ide/utils/Environment.java | 18 ++ .../java/com/tom/rv2ide/tooling/impl/Main.kt | 180 +++++++++++++++--- .../tooling/impl/ToolingApiServerImpl.kt | 81 +++++++- 12 files changed, 357 insertions(+), 71 deletions(-) diff --git a/.gitignore b/.gitignore index 0298dd1e58..41d29740e7 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,10 @@ local.properties # personal ideas current-idea.md +# +information/ +.gitignore + # Crowdin crowdin.properties .idea/crowdin_settings.xml 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/handlers/EditorBuildEventListener.kt b/core/app/src/main/java/com/tom/rv2ide/handlers/EditorBuildEventListener.kt index 1bc57b15de..88d1557b3b 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 @@ -133,10 +133,12 @@ class EditorBuildEventListener : GradleBuildService.EventListener { 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 { + 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) + } } } 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 40b260276b..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() } @@ -459,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) { @@ -538,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 1566dd165c..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 @@ -76,6 +77,7 @@ internal class ToolingServerRunner( 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}" 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 2e86a498b6..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()) { @@ -370,7 +371,8 @@ class AtcWizardDialog : BottomSheetDialogFragment() { 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/utils/FileBrowserNavigationHelper.kt b/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt index a733fc451b..ffa440d591 100644 --- a/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt +++ b/core/app/src/main/java/com/tom/rv2ide/utils/FileBrowserNavigationHelper.kt @@ -63,9 +63,9 @@ object FileBrowserNavigationHelper { } fun normalizePath(path: String): String { - val trimmed = path.trim() - if (trimmed.isEmpty()) return "/" - return if (trimmed.length > 1) trimmed.trimEnd('/') else trimmed + val expanded = Environment.expandHomePath(path) + if (expanded.isEmpty()) return "/" + return if (expanded.length > 1) expanded.trimEnd('/') else expanded } fun readDirectory(path: String): DirectoryListing { diff --git a/core/common/src/main/java/com/tom/rv2ide/managers/ToolsManager.java b/core/common/src/main/java/com/tom/rv2ide/managers/ToolsManager.java index a5d8248e63..2e033f696e 100755 --- a/core/common/src/main/java/com/tom/rv2ide/managers/ToolsManager.java +++ b/core/common/src/main/java/com/tom/rv2ide/managers/ToolsManager.java @@ -48,6 +48,22 @@ public class ToolsManager { private static final Logger LOG = LoggerFactory.getLogger(ToolsManager.class); public static String COMMON_ASSET_DATA_DIR = "data/common"; + private static volatile CompletableFuture 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) { @@ -198,13 +218,28 @@ private static void extractAapt2() { } 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); } 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 d9e0e6ec30..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 @@ -241,6 +241,24 @@ public static String getHighestInstalledNdkVersion() { 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() 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..5ce3dc69f4 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..3b00200d4e 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 @@ -137,8 +137,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 +216,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)) } @@ -255,6 +258,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 +370,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 +381,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 +409,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 +494,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