Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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) {
Expand All @@ -1362,7 +1366,7 @@ abstract class BaseEditorActivity :
}

editorView.onEditorSelected()
editorViewModel.setCurrentFile(fileIndex, editorView.file)
editorViewModel.selectFile(fileIndex, editorView.file)
refreshSymbolInput(editorView)
invalidateOptionsMenu()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ open class EditorHandlerActivity :
if (tabPosition >= 0) {
this.content.editorContainer.displayedChild = tabPosition
}
EditorEvents.notifyFileChanged(editorViewModel.getCurrentFile())
EditorEvents.notifyFileChanged(editorViewModel.displayedFile())
Comment thread
davidschachterADFA marked this conversation as resolved.
Resolved
}

pluginEditorProvider =
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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(
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String>()
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<Pair<File, File?>>,
modifiedAt: Int = -1,
events: MutableList<String>? = null,
onModifiedCheck: () -> Unit = {},
): EditorHandlerActivity {
val activity = Robolectric.buildActivity(EditorHandlerActivity::class.java, Intent()).get()
var saved = false
val editors =
tabs
.mapIndexed { i, (_, editorFile) ->
mockk<CodeEditorView>(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<TabLayout>(relaxed = true) { every { tabCount } answers { editors.size } }
val container =
mockk<ViewFlipper>(relaxed = true) {
every { childCount } answers { editors.size }
every { getChildAt(any()) } answers { editors.getOrNull(firstArg()) }
every { removeViewAt(any()) } answers {
events?.add("removeViewAt:${firstArg<Int>()}")
editors.removeAt(firstArg<Int>())
}
every { setDisplayedChild(any()) } answers { events?.add("displayedChild:${firstArg<Int>()}") }
}
// The binding's views are public Java fields, which mockk cannot stub.
val content = mockk<ContentEditorBinding>(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<ActivityEditorBinding>(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
}
}
Loading
Loading