diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt index 812c443225..bcde992290 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/BaseEditorActivity.kt @@ -1328,6 +1328,8 @@ abstract class BaseEditorActivity : if (this is EditorHandlerActivity && isPluginTab(position)) { val pluginTabId = getPluginTabId(position) if (pluginTabId != null) { + // No file is shown: listeners hear null, as when a plugin tab is first added. + editorViewModel.displayedFileIndex = -1 val tabManager = PluginEditorTabManager.getInstance() tabManager.onTabSelected(pluginTabId) invalidateOptionsMenu() @@ -1347,7 +1349,9 @@ abstract class BaseEditorActivity : return } - editorViewModel.displayedFileIndex = fileIndex + // With the current file, not the index alone: plugins hear the switch as the index is set, and + // may ask for the current file. + editorViewModel.selectFile(fileIndex) val editorView = if (this is EditorHandlerActivity) { @@ -1362,7 +1366,7 @@ abstract class BaseEditorActivity : } editorView.onEditorSelected() - editorViewModel.setCurrentFile(fileIndex, editorView.file) + editorViewModel.selectFile(fileIndex, editorView.file) refreshSymbolInput(editorView) invalidateOptionsMenu() } diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index eb62c37071..13f3d6ece3 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -356,7 +356,7 @@ open class EditorHandlerActivity : if (tabPosition >= 0) { this.content.editorContainer.displayedChild = tabPosition } - EditorEvents.notifyFileChanged(editorViewModel.getCurrentFile()) + EditorEvents.notifyFileChanged(editorViewModel.displayedFile()) } pluginEditorProvider = @@ -1151,7 +1151,7 @@ open class EditorHandlerActivity : if (fileIndex < 0) return@withContext null editorViewModel.startDrawerOpened = false - editorViewModel.displayedFileIndex = fileIndex + editorViewModel.setCurrentFile(fileIndex, file) val tabPosition = getTabPositionForFileIndex(fileIndex) val tab = content.tabs.getTabAt(tabPosition) @@ -1760,12 +1760,12 @@ open class EditorHandlerActivity : } val tabPosition = getTabPositionForFileIndex(index) - editorViewModel.removeFile(index) - - if (tabPosition >= 0) { - content.tabs.removeTabAt(tabPosition) - content.editorContainer.removeViewAt(tabPosition) - shiftPluginIndices(tabPosition + 1, -1) + editorViewModel.removeFile(index) { + if (tabPosition >= 0) { + content.tabs.removeTabAt(tabPosition) + content.editorContainer.removeViewAt(tabPosition) + shiftPluginIndices(tabPosition + 1, -1) + } } editorViewModel.areFilesModified = hasUnsavedFiles() @@ -1791,21 +1791,25 @@ open class EditorHandlerActivity : val file = editorViewModel.getCurrentFile() var index = 0 + // Set when a close waits for the unsaved-changes dialog; that close carries on once answered. + var waiting = false // keep closing the file at index 0 // if openedFiles[0] == file, then keep closing files at index 1 while (editorViewModel.getOpenedFileCount() != 1) { - val editor = getEditorAtIndex(index) - - if (editor == null) { - log.error("Unable to save file at index {}", index) - continue - } - // Index of files changes as we keep close files - // So we compare the files instead of index - if (file != editor.file) { - closeFile(index) + // So we compare the files instead of index. The opened file, not the editor's: an + // editor's file is null until its text has loaded, or for good if the read failed, + // while the current file is set from the opened file as soon as its tab is shown. + if (file != editorViewModel.getOpenedFile(index)) { + val openedBefore = editorViewModel.getOpenedFileCount() + closeFile(index) { if (waiting) closeOthers() } + // closeFile can return without closing, as when it asks about unsaved changes; trying + // again would spin on the main thread. + if (editorViewModel.getOpenedFileCount() == openedBefore) { + waiting = true + break + } } else { index = 1 } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt index e8d602b5a4..700d5396d7 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt @@ -399,19 +399,49 @@ class EditorViewModel : ViewModel() { } /** - * Remove the file at the given index from the list of opened files. + * Remove the file at the given index from the list of opened files. The current and shown + * indexes keep pointing at the same files when an earlier tab is removed. + * + * The shift waits for [removeViews]: the displayed-index observer maps the index through the tab + * bar and the editor container, so shifting while the closed tab's view still exists would show + * the wrong view. * * @param index The index of the closed file. + * @param removeViews Removes the closed file's tab and editor view. Runs after the `files` + * observers and before the indexes shift. */ - fun removeFile(index: Int) = + fun removeFile( + index: Int, + removeViews: () -> Unit = {}, + ) { updateFiles { files -> files.removeAt(index) if (files.isEmpty()) { - mCurrentFile.value = null + // As removeAllFiles does: no tab is left to select, so nothing else would tell the + // displayed-file observers that no file is shown. + setCurrentFile(-1, null) } } + removeViews() + + if (this.files.isEmpty()) { + return + } + + // The tab bar fires no selection event when a tab before the selected one closes. + // Closing the shown tab itself is left to the tab selected next. + // Current file first, as setCurrentFile does: displayed-index observers may read it. + val current = mCurrentFile.value + if (current != null && index < current.first) { + mCurrentFile.value = (current.first - 1) to current.second + } + if (index < displayedFileIndex) { + displayedFileIndex -= 1 + } + } + fun removeAllFiles() = updateFiles { files -> files.clear() @@ -422,8 +452,10 @@ class EditorViewModel : ViewModel() { index: Int, file: File?, ) { - displayedFileIndex = index + // The current file first: observers of the displayed index run as it is set, and the plugins + // they notify may ask for the current file. mCurrentFile.value = index to file + displayedFileIndex = index } fun updateFile( @@ -472,6 +504,24 @@ class EditorViewModel : ViewModel() { fun getCurrentFile(): File? = mCurrentFile.value?.second + /** + * The file at [displayedFileIndex], or null when there is none there: -1 (a plugin tab just + * added, or no file open), or briefly an index past the end while a tab is added or closed. + * Observers of the displayed index read this rather than [getCurrentFile], which a new plugin + * tab leaves at the last file. + */ + fun displayedFile(): File? = files.getOrNull(displayedFileIndex) + + /** + * Shows the opened file at [index], as a selected tab does. [editorFile] is the tab's editor's + * own file, null until a new editor has loaded its text; the opened file stands in until then, + * so the current file is never null while a file is shown. + */ + fun selectFile( + index: Int, + editorFile: File? = null, + ) = setCurrentFile(index, editorFile ?: files.getOrNull(index)) + /** * Get the [OpenedFilesCache] if it is already loaded, otherwise read the cache from the file system * and invoke the given callback. diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/CloseOthersTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/CloseOthersTest.kt new file mode 100644 index 0000000000..f1f35d4040 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/CloseOthersTest.kt @@ -0,0 +1,170 @@ +package com.itsaky.androidide.activities.editor + +import android.content.DialogInterface +import android.content.Intent +import android.os.Looper +import android.widget.ViewFlipper +import androidx.appcompat.app.AlertDialog +import com.google.android.material.tabs.TabLayout +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.databinding.ActivityEditorBinding +import com.itsaky.androidide.databinding.ContentEditorBinding +import com.itsaky.androidide.ui.CodeEditorView +import io.mockk.every +import io.mockk.mockk +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowDialog +import java.io.File + +/** + * "Close others" keeps the shown file (ADFA-7141). The current file is set from the opened file + * as soon as a tab is shown, while its editor's own file stays null until the text has loaded, or + * for good if the read failed. Comparing against the editor's file closed the shown tab instead. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = CloseOthersTest.TestApp::class) +class CloseOthersTest { + open class TestApp : BaseApplication() + + private val shown = File("/project/Shown.kt") + private val a = File("/project/A.kt") + private val b = File("/project/B.kt") + private val t = File("/project/T.kt") + + @Test + fun closeOthersKeepsAShownFileWhoseEditorHasNotLoaded() { + val activity = activityWithTabs(listOf(shown to null, a to a, b to b)) + activity.editorViewModel.selectFile(0) + + activity.closeOthers() + + assertThat(activity.editorViewModel.getOpenedFiles()).containsExactly(shown) + } + + @Test + fun closeOthersKeepsALoadedShownFileInTheMiddle() { + val activity = activityWithTabs(listOf(a to a, shown to shown, b to b)) + activity.editorViewModel.selectFile(1, shown) + + activity.closeOthers() + + assertThat(activity.editorViewModel.getOpenedFiles()).containsExactly(shown) + } + + // A's editor has unsaved changes but no file yet, so the check before the loop misses it, and + // closing it stops at the unsaved-changes dialog without closing anything. + @Test + fun closeOthersStopsWhenACloseAsksAboutUnsavedChanges() { + var checks = 0 + val activity = + activityWithTabs(listOf(shown to shown, a to null, b to b), modifiedAt = 1) { + check(++checks <= 20) { "closeOthers kept trying to close the same tab" } + } + activity.editorViewModel.selectFile(0, shown) + + activity.closeOthers() + + assertThat(checks).isEqualTo(1) + assertThat(activity.editorViewModel.getOpenedFiles()).containsExactly(shown, a, b).inOrder() + } + + @Test + fun closeOthersCarriesOnOnceTheUnsavedChangesAreDiscarded() { + val activity = activityWithTabs(listOf(shown to shown, a to null, b to b), modifiedAt = 1) + activity.editorViewModel.selectFile(0, shown) + activity.closeOthers() + + // "No": discard the changes and close. The dialog delivers the click through the main looper. + (ShadowDialog.getLatestDialog() as AlertDialog).getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + + assertThat(activity.editorViewModel.getOpenedFiles()).containsExactly(shown) + } + + // ViewAnimator shows the child at displayedChild, and removeViewAt leaves the shown child alone. + // So the editor shows the wrong file unless the closed tab's view is gone before the shown + // index moves. + @Test + fun closingAnEarlierTabRemovesItsViewBeforeTheShownIndexMoves() { + val events = mutableListOf() + val activity = activityWithTabs(listOf(a to a, b to b, shown to shown, t to t), events = events) + activity.editorViewModel.selectFile(2, shown) + events.clear() + + activity.closeFile(0) + + assertThat(events.first()).isEqualTo("removeViewAt:0") + assertThat(events.last()).isEqualTo("displayedChild:1") + assertThat(activity.editorViewModel.displayedFile()).isEqualTo(shown) + } + + /** + * An editor activity, built but not created as in the other activity tests here, whose tab + * strip and editor container follow its opened files. Each pair is an opened file and the file + * its editor reports: null while the editor loads. The editor at [modifiedAt], if any, has + * unsaved changes until it is marked saved, and [onModifiedCheck] runs each time that is asked. + * With [events], the container's removeViewAt and displayedChild calls are recorded in it, and + * the displayed-index observer onCreate would register is stood in for: it sets displayedChild + * to the index, as there are no plugin tabs here. + */ + private fun activityWithTabs( + tabs: List>, + modifiedAt: Int = -1, + events: MutableList? = null, + onModifiedCheck: () -> Unit = {}, + ): EditorHandlerActivity { + val activity = Robolectric.buildActivity(EditorHandlerActivity::class.java, Intent()).get() + var saved = false + val editors = + tabs + .mapIndexed { i, (_, editorFile) -> + mockk(relaxed = true) { + every { file } returns editorFile + every { isModified } answers { + if (i == modifiedAt) onModifiedCheck() + i == modifiedAt && !saved + } + every { markAsSaved() } answers { if (i == modifiedAt) saved = true } + } + }.toMutableList() + val tabStrip = mockk(relaxed = true) { every { tabCount } answers { editors.size } } + val container = + mockk(relaxed = true) { + every { childCount } answers { editors.size } + every { getChildAt(any()) } answers { editors.getOrNull(firstArg()) } + every { removeViewAt(any()) } answers { + events?.add("removeViewAt:${firstArg()}") + editors.removeAt(firstArg()) + } + every { setDisplayedChild(any()) } answers { events?.add("displayedChild:${firstArg()}") } + } + // The binding's views are public Java fields, which mockk cannot stub. + val content = mockk(relaxed = true) + ContentEditorBinding::class.java + .getDeclaredField("tabs") + .apply { isAccessible = true } + .set(content, tabStrip) + ContentEditorBinding::class.java + .getDeclaredField("editorContainer") + .apply { isAccessible = true } + .set(content, container) + val binding = mockk(relaxed = true) + ActivityEditorBinding::class.java + .getDeclaredField("content") + .apply { isAccessible = true } + .set(binding, content) + activity._binding = binding + + tabs.forEach { (opened, _) -> activity.editorViewModel.addFile(opened) } + if (events != null) { + activity.editorViewModel._displayedFile.observeForever { container.displayedChild = it } + } + return activity + } +} diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTabSelectionTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTabSelectionTest.kt new file mode 100644 index 0000000000..a33fc30096 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTabSelectionTest.kt @@ -0,0 +1,65 @@ +package com.itsaky.androidide.activities.editor + +import android.content.Intent +import android.widget.ViewFlipper +import com.google.android.material.tabs.TabLayout +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.databinding.ActivityEditorBinding +import com.itsaky.androidide.databinding.ContentEditorBinding +import io.mockk.every +import io.mockk.mockk +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +/** + * Selecting a plugin tab that is already open shows no file (ADFA-7141), as adding one does, so + * listeners hear null rather than keep the file shown before it. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = PluginTabSelectionTest.TestApp::class) +class PluginTabSelectionTest { + open class TestApp : BaseApplication() + + @Test + fun selectingAnOpenPluginTabShowsNoFile() { + val activity = Robolectric.buildActivity(EditorHandlerActivity::class.java, Intent()).get() + val content = mockk(relaxed = true) + // The binding's views are public Java fields, which mockk cannot stub. + ContentEditorBinding::class.java + .getDeclaredField("tabs") + .apply { isAccessible = true } + .set(content, mockk(relaxed = true) { every { tabCount } returns 3 }) + ContentEditorBinding::class.java + .getDeclaredField("editorContainer") + .apply { isAccessible = true } + .set(content, mockk(relaxed = true)) + val binding = mockk(relaxed = true) + ActivityEditorBinding::class.java + .getDeclaredField("content") + .apply { isAccessible = true } + .set(binding, content) + activity._binding = binding + // Two file tabs, then a plugin's tab at position 2. + @Suppress("UNCHECKED_CAST") + val pluginTabs = + EditorHandlerActivity::class.java + .getDeclaredField("tabIndexToPluginId") + .apply { isAccessible = true } + .get(activity) as MutableMap + pluginTabs[2] = "some.plugin.tab" + val a = File("/project/A.kt") + activity.editorViewModel.addFile(a) + activity.editorViewModel.addFile(File("/project/B.kt")) + activity.editorViewModel.selectFile(0, a) + + activity.onTabSelected(mockk { every { position } returns 2 }) + + assertThat(activity.editorViewModel.displayedFileIndex).isEqualTo(-1) + assertThat(activity.editorViewModel.displayedFile()).isNull() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/viewmodel/EditorViewModelDisplayedFileTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodel/EditorViewModelDisplayedFileTest.kt new file mode 100644 index 0000000000..647d1244bd --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/viewmodel/EditorViewModelDisplayedFileTest.kt @@ -0,0 +1,190 @@ +package com.itsaky.androidide.viewmodel + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TestRule +import java.io.File + +/** + * What plugins hear as the active file (ADFA-7141). EditorHandlerActivity reports + * [EditorViewModel.displayedFile] each time the displayed index changes, and plugins may read the + * current file in that callback; both used to name the tab being left. + */ +class EditorViewModelDisplayedFileTest { + @get:Rule + val rule: TestRule = InstantTaskExecutorRule() + + private val a = File("/project/A.kt") + private val b = File("/project/B.kt") + private val s = File("/project/S.kt") + private val t = File("/project/T.kt") + private lateinit var viewModel: EditorViewModel + private val heard = mutableListOf() + + // What a plugin reads with IdeEditorService.getCurrentFile() inside its callback. + private val currentInCallback = mutableListOf() + + @Before + fun setUp() { + viewModel = EditorViewModel() + // The activity's observer, reduced to what it reports. + viewModel._displayedFile.observeForever { + heard += viewModel.displayedFile() + currentInCallback += viewModel.getCurrentFile() + } + heard.clear() + currentInCallback.clear() + } + + private fun open(file: File) { + viewModel.addFile(file) + viewModel.setCurrentFile(viewModel.getOpenedFileCount() - 1, file) + } + + @Test + fun openingAFileReportsThatFile() { + open(a) + open(b) + + assertThat(heard).containsExactly(a, b).inOrder() + } + + @Test + fun switchingTabsReportsTheTabSwitchedTo() { + open(a) + open(b) + heard.clear() + + currentInCallback.clear() + + // What BaseEditorActivity.onTabSelected does: select the index, then again with the editor's file. + viewModel.selectFile(0) + viewModel.selectFile(0, a) + + assertThat(heard).containsExactly(a, a) + assertThat(currentInCallback).containsExactly(a, a) + } + + @Test + fun aTabWhoseEditorHasNotLoadedKeepsTheOpenedFileCurrent() { + open(a) + open(b) + + // A new editor knows its file only once its text has loaded. + viewModel.selectFile(0) + viewModel.selectFile(0, editorFile = null) + + assertThat(viewModel.getCurrentFile()).isEqualTo(a) + } + + @Test + fun aListenerReadingTheCurrentFileGetsTheShownFile() { + open(a) + open(b) + currentInCallback.clear() + + viewModel.setCurrentFile(0, a) + + assertThat(currentInCallback).containsExactly(a) + } + + @Test + fun aPluginTabReportsNoFile() { + open(a) + heard.clear() + + viewModel.displayedFileIndex = -1 + + assertThat(heard).containsExactly(null) + } + + @Test + fun closingTheLastFileReportsNoFile() { + open(a) + heard.clear() + + viewModel.removeFile(0) + + assertThat(heard).containsExactly(null) + assertThat(viewModel.getCurrentFile()).isNull() + } + + @Test + fun closingAllFilesReportsNoFile() { + open(a) + open(b) + heard.clear() + + viewModel.removeAllFiles() + + assertThat(heard).containsExactly(null) + } + + @Test + fun closingEarlierTabsKeepsTheShownFileCurrent() { + open(a) + open(b) + open(s) + + viewModel.removeFile(0) + viewModel.removeFile(0) + + assertThat(viewModel.displayedFile()).isEqualTo(s) + assertThat(viewModel.displayedFileIndex).isEqualTo(0) + assertThat(viewModel.getCurrentFileIndex()).isEqualTo(0) + assertThat(viewModel.getCurrentFile()).isEqualTo(s) + } + + @Test + fun closingAnEarlierTabDoesNotShowTheNextFile() { + open(a) + open(b) + open(s) + open(t) + viewModel.setCurrentFile(2, s) + + viewModel.removeFile(0) + + assertThat(viewModel.displayedFile()).isEqualTo(s) + assertThat(viewModel.displayedFileIndex).isEqualTo(1) + assertThat(viewModel.getCurrentFileIndex()).isEqualTo(1) + } + + @Test + fun closingALaterTabLeavesTheIndexesAlone() { + open(a) + open(s) + open(b) + viewModel.setCurrentFile(1, s) + + viewModel.removeFile(2) + + assertThat(viewModel.displayedFile()).isEqualTo(s) + assertThat(viewModel.displayedFileIndex).isEqualTo(1) + assertThat(viewModel.getCurrentFileIndex()).isEqualTo(1) + } + + // The activity's observer maps the shown index to a tab and a view, so the index must not move + // while the closed tab's view still exists. + @Test + fun theShownIndexChangesOnlyAfterTheClosedTabsViewIsGone() { + open(a) + open(b) + open(s) + open(t) + viewModel.setCurrentFile(2, s) + var viewsRemoved = false + val removedAtEachFiring = mutableListOf() + viewModel._displayedFile.observeForever { removedAtEachFiring += viewsRemoved } + removedAtEachFiring.clear() + + viewModel.removeFile(0) { viewsRemoved = true } + + assertThat(removedAtEachFiring).isNotEmpty() + assertThat(removedAtEachFiring).doesNotContain(false) + assertThat(viewModel.displayedFile()).isEqualTo(s) + } +}