Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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 @@ -1334,6 +1334,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 @@ -1353,7 +1355,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 @@ -1368,7 +1372,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 @@ -353,7 +353,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 @@ -1161,7 +1161,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 @@ -1805,21 +1805,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 @@ -408,7 +408,9 @@ class EditorViewModel : ViewModel() {
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)
}
}

Expand All @@ -422,8 +424,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 +476,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,198 @@
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 com.itsaky.androidide.ui.EditorBottomSheet
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()
// Selects as TabLayout does when a tab is removed, for syncSelectedTab after each close (ADFA-7144).
// Until the first removal, the selected tab is the shown file's, as the tests set it.
var selected: Int? = null

fun selectedTab() = selected ?: activity.editorViewModel.displayedFileIndex
val tabStrip =
mockk<TabLayout>(relaxed = true) {
every { tabCount } answers { editors.size }
every { selectedTabPosition } answers { selectedTab() }
every { getTabAt(any()) } answers {
val at = firstArg<Int>()
if (at in editors.indices) mockk<TabLayout.Tab>(relaxed = true) { every { position } returns at } else null
}
every { removeTabAt(any()) } answers {
val removed = firstArg<Int>()
val current = selectedTab()
selected =
when {
removed < current -> current - 1
removed == current -> maxOf(0, removed - 1)
else -> current
}
}
}
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)
ContentEditorBinding::class.java
.getDeclaredField("bottomSheet")
.apply { isAccessible = true }
.set(content, mockk<EditorBottomSheet>(relaxed = true))
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
}
}
Original file line number Diff line number Diff line change
@@ -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<ContentEditorBinding>(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<TabLayout>(relaxed = true) { every { tabCount } returns 3 })
ContentEditorBinding::class.java
.getDeclaredField("editorContainer")
.apply { isAccessible = true }
.set(content, mockk<ViewFlipper>(relaxed = true))
val binding = mockk<ActivityEditorBinding>(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<Int, String>
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<TabLayout.Tab> { every { position } returns 2 })

assertThat(activity.editorViewModel.displayedFileIndex).isEqualTo(-1)
assertThat(activity.editorViewModel.displayedFile()).isNull()
}
}
Loading
Loading