Skip to content

Commit d45ec86

Browse files
ADFA-5472: Revert two fixes from the last round that made things worse
Eleven of twelve findings. Two of them are mine from the previous round, and both were wrong in the same way: I took a reviewer's suggestion at face value without checking the surrounding facts. destroy() must not clear the caches. I added that clearing last round on the grounds that it "costs nothing and removes the whole class of staleness". It costs plenty: EditorActivityLifecyclerObserver.onPause calls EditorActivityActions.clearActions(), which calls destroy() on every action in this location, and onResume registers fresh ones. So destroy() runs on every backgrounding, not at teardown. The clearing therefore threw the verdict cache away on each background/foreground cycle -- so the item went missing from the first menu open after every resume -- and clearing the in-flight set alongside it let a still-running job's completion release a claim the next cycle's job had already taken, which is exactly the duplicate work the claim exists to prevent. Reverted, with the pause/resume fact recorded so the suggestion is not retried. isDeepLinkTargetOfOpenProject keeps its per-side fallback. I collapsed it to `deepLinkTargetOfOpenProjectOrNull(...) ?: false` last round and asserted in the commit message that this "is not a behaviour change ... the answer was false either way". It is a behaviour change: the old form compares per side, so when exactly one side's canonicalPath fails it still compares that side's absolutePath against the other's canonical path, and those can match. At this function's two callers a false means a same-project deep link is treated as a project switch -- the project is closed and reopened instead of the file being shown. The two functions now differ deliberately: lenient for callers that must answer now, strict for the one caller that remembers the answer. That also makes the KDoc true again, including its [canonicalOrAbsolute] link. The rest: The popup is bounded to the room below its anchor. WRAP_CONTENT reports height -2 to showAsDropDown, whose fit check is then trivially satisfied, so the content was measured against the whole display and the ScrollView believed it fit. capHeightToSpaceBelow measures and caps against getMaxAvailableHeight, at both call sites. It leaves the popup alone when the content already fits, so a bad measurement degrades to the previous behaviour rather than a zero-height window. The manifest guard now pins host and scheme, not just the path. An intent-filter matches on all three, so changing CANONICAL_HOST or SCHEME breaks delivery exactly as changing the prefix does -- and the path-only assertion stayed green through both. The one-based cursor conversion is named and tested. It is called an invariant twice in ARCHITECTURE.md and had no test at any level; dropping a `+ 1` fails silently, because buildUrl then refuses the link and the item merely disappears. oneBasedCursorPosition is now covered directly, plus a test showing the raw zero-based values produce no link at all -- which is why the conversion is load-bearing rather than cosmetic. That test needed a real android.net.Uri, so CreateLinkActionTest gains the Robolectric runner its siblings already use. projectsRoot() failing is reported as false, not null. null means "ask again shortly" and there is nothing to wait for, so the item was hidden forever while the code promised a retry; the catch is also narrow now, because runCatching there swallowed Error while a comment twenty lines below explicitly rejected runCatching for that reason. Corrected comments rather than leaving them: onNewIntent's claim that the same-project check is "disk-free" (it falls through to two canonicalPath calls on the main thread), prepare()'s hide-silently rationale (which did not cover the length ceiling, a property of the FILE -- so the item comes and goes as the user switches between a deep and a shallow tab), and a note that the shared rule's name half is trivially satisfied at this call site because the name is derived from the path being compared. Deferred: the shared "close options" tooltip is now ADFA-5477, with the two blockers recorded there. Also worth recording: every `:app:spotlessApply` in this branch's history silently did nothing -- there is no such task, only a root-level `spotlessApply`, and the "task not found" failure looked like the daemon noise I had been seeing. That is why the hook kept finding work. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Gw89A3KWsPtvgPYtXYLBwr
1 parent 29b0032 commit d45ec86

6 files changed

Lines changed: 150 additions & 33 deletions

File tree

‎app/src/main/java/com/itsaky/androidide/actions/file/CreateLinkAction.kt‎

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,19 @@ class CreateLinkAction(
6161
/**
6262
* Verdicts for "can a link name this project", keyed by project path. Keyed rather than a
6363
* single slot so a slow answer for a project the user has left cannot be mistaken for the
64-
* current one -- there is nothing to invalidate and no stale-write window to guard. Holds only
65-
* strings and booleans, so it is safe in a companion.
64+
* current one. Holds only strings and booleans, so it is safe in a companion.
65+
*
66+
* Deliberately NOT cleared in `destroy()`, which was tried and is wrong:
67+
* `EditorActivityLifecyclerObserver.onPause` calls `EditorActivityActions.clearActions()`,
68+
* which destroys every action in this location, and `onResume` registers fresh ones. So
69+
* `destroy()` runs on every backgrounding, not at teardown -- clearing here threw the cache
70+
* away on each background/foreground cycle, and clearing the in-flight set alongside it let a
71+
* still-running job's completion release a claim the next cycle's job had already taken.
72+
*
73+
* The cost of keeping them is a verdict that outlives the fact it describes: rename the
74+
* project directory mid-process and a cached answer is stale. That surfaces as one link that
75+
* fails to open, or one item hidden that need not be -- both recoverable, and both cheaper
76+
* than losing the answer every time the user switches apps.
6677
*/
6778
private val linkableProjects = ConcurrentHashMap<String, Boolean>()
6879

@@ -87,7 +98,19 @@ class CreateLinkAction(
8798
private fun linkableProject(projectPath: String): Boolean? {
8899
linkableProjects[projectPath]?.let { return it }
89100

90-
val root = runCatching { projectsRoot() }.getOrNull() ?: return null
101+
// false, not null: null means "ask again shortly", and there is nothing to wait for if the
102+
// projects root cannot be derived at all. Narrow, because runCatching here would swallow Error
103+
// too -- the same reason the IO block below does not use it.
104+
val root =
105+
try {
106+
projectsRoot()
107+
} catch (e: Exception) {
108+
log.warn("Cannot locate the projects directory, so nothing can be linked", e)
109+
return false
110+
}
111+
112+
// The name half of the shared rule is trivially satisfied here -- the name is derived from the
113+
// very path being compared -- so this call is really asking the parent question alone.
91114
val projectName = File(projectPath).name
92115

93116
deepLinkTargetOfOpenProjectWithoutIo(projectPath, projectName, root)?.let {
@@ -152,16 +175,6 @@ class CreateLinkAction(
152175
icon = ContextCompat.getDrawable(context, R.drawable.ic_copy)
153176
}
154177

155-
override fun destroy() {
156-
super.destroy()
157-
// A verdict describes the filesystem as it was. Renaming the project directory, or swapping
158-
// <projectsRoot> for a symlink, while the process lives would leave a cached answer to the old
159-
// question -- so the answers do not outlive the activity that asked. REVIEW.md section 2 flags
160-
// companion-held state for exactly this.
161-
linkableProjects.clear()
162-
canonicalisationsInFlight.clear()
163-
}
164-
165178
override fun prepare(data: ActionData) {
166179
super.prepare(data)
167180

@@ -173,8 +186,13 @@ class CreateLinkAction(
173186
// there is no activity, and the !visible check just above returns in exactly that case.
174187
val activity = data.getActivity() ?: return
175188

176-
// Hidden rather than shown-and-failing: the states that produce no link are properties of how
177-
// the project was opened, not transient ones the user could correct by tapping again.
189+
// Hidden rather than shown-and-failing. Most states that produce no link are properties of how
190+
// the project was opened, which a second tap could not correct. One is a property of the FILE:
191+
// a path long enough to push the decoded URL past parse()'s 512-character ceiling. That one
192+
// makes the item come and go as the user switches between a deep and a shallow tab, with no
193+
// explanation offered, because the tap that would explain is never available. Surfacing a
194+
// reason means buildUrl reporting WHY it refused rather than just null -- worth doing, and
195+
// deliberately not bundled into this change.
178196
//
179197
// Only the cheap predicates run here. prepare() is called synchronously, from the touch
180198
// handler, for every action in this menu on every open, and building the URL just to compare
@@ -290,15 +308,15 @@ class CreateLinkAction(
290308
return null
291309
}
292310

293-
// The editor is zero-based at both ends; the URL scheme is one-based. Both coordinates are
294-
// always written, never omitted at 1:1 -- see buildUrl, which refuses the coordinate-free and
295-
// column-only shapes precisely because the reader mis-handles them.
311+
// Both coordinates are always written, never omitted at 1:1 -- see buildUrl, which refuses the
312+
// coordinate-free and column-only shapes precisely because the reader mis-handles them.
296313
val cursor = editor.cursor
314+
val (line, column) = oneBasedCursorPosition(cursor.leftLine, cursor.leftColumn)
297315
return LinkTarget(
298316
projectName = projectDir.name,
299317
relativePath = relativePath,
300-
line = cursor.leftLine + 1,
301-
column = cursor.leftColumn + 1,
318+
line = line,
319+
column = column,
302320
)
303321
}
304322
}
@@ -323,3 +341,17 @@ internal fun projectRelativePathOrNull(
323341
}
324342
return relative
325343
}
344+
345+
/**
346+
* The one-based line and column a link carries, from the editor's zero-based cursor.
347+
*
348+
* Two characters of arithmetic, named and tested because dropping either `+ 1` fails silently:
349+
* buildUrl refuses a line or column below 1, so a cursor at the very start of a file simply makes
350+
* the menu item vanish -- indistinguishable from the ordinary hidden-when-unlinkable state -- and a
351+
* cursor anywhere else yields a link that quietly points one line too high.
352+
*/
353+
@VisibleForTesting
354+
internal fun oneBasedCursorPosition(
355+
zeroBasedLine: Int,
356+
zeroBasedColumn: Int,
357+
): Pair<Int, Int> = (zeroBasedLine + 1) to (zeroBasedColumn + 1)

‎app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ import com.itsaky.androidide.tasks.executeAsync
111111
import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult
112112
import com.itsaky.androidide.ui.ARCHIVE_EXTENSIONS
113113
import com.itsaky.androidide.ui.CodeEditorView
114+
import com.itsaky.androidide.utils.ActionMenuUtils
114115
import com.itsaky.androidide.utils.DeepLinkProjectLookup
115116
import com.itsaky.androidide.utils.DialogUtils.newMaterialDialogBuilder
116117
import com.itsaky.androidide.utils.DialogUtils.showConfirmationDialog
@@ -2240,6 +2241,8 @@ open class EditorHandlerActivity :
22402241
}
22412242
binding.actionItems.addView(undockItem)
22422243

2244+
// Same cap as the file-tab popup: this popup shares that layout, so it shares the problem.
2245+
with(ActionMenuUtils) { popupWindow.capHeightToSpaceBelow(anchorView, binding.root) }
22432246
popupWindow.showAsDropDown(anchorView, 0, 0)
22442247
}
22452248

@@ -2670,8 +2673,13 @@ open class EditorHandlerActivity :
26702673
// branch reads the carried-forward extra itself -- they only apply whatever fileRequest THIS
26712674
// intent carries, which is often none. Comparing the deep link's project name against the
26722675
// currently-loading project's directory name (mirroring BaseEditorActivity.onCreate's own
2673-
// deepLinkTargetsAnotherProject check) is a synchronous, disk-free way to tell same from
2674-
// different without waiting on the deep-link path's own async resolve.
2676+
// deepLinkTargetsAnotherProject check) is a synchronous way to tell same from
2677+
// different without waiting on the deep-link path's own async resolve. It is not free, though:
2678+
// this comment used to claim "disk-free", and isDeepLinkTargetOfOpenProject falls through to
2679+
// two File.canonicalPath calls whenever the paths differ as text. Deep-link arrival is a rare,
2680+
// user-initiated event so the stall is bounded, but it is a main-thread read on this path and
2681+
// on BaseEditorActivity.onCreate's -- see deepLinkTargetOfOpenProjectWithoutIo for the half
2682+
// that needs no disk, which CreateLinkAction uses because it is called on every menu open.
26752683
// EditorIntentExtras.EXTRA_PREVIOUS_PROJECT_PATH, when present, is what IProjectManager.projectDirPath held before
26762684
// MainActivity.openProject's bookkeeping call overwrote it to the NEW path -- by the time this
26772685
// intent arrives here, the global itself already reads as the new path regardless of whether

‎app/src/main/java/com/itsaky/androidide/utils/ActionMenuUtils.kt‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,33 @@ import com.itsaky.androidide.idetooltips.TooltipTag
3535
import com.itsaky.androidide.plugins.extensions.FileTabMenuItem
3636

3737
object ActionMenuUtils {
38+
/**
39+
* Caps [this] at the room actually available below [anchorView], measuring [content] first.
40+
*
41+
* A PopupWindow built WRAP_CONTENT reports height -2 to `showAsDropDown`, and its fit check
42+
* (`height <= spaceBelow`) is therefore trivially satisfied -- so no resize is ever negotiated and
43+
* the content gets measured against the whole display instead of the space under the tab strip.
44+
* The ScrollView then believes it fits and does not scroll, and the window is left to run off the
45+
* bottom or be shoved up over the tabs and toolbar. At 2x font scale with the undock item and
46+
* plugin contributions, this menu can reach that size.
47+
*
48+
* Left alone when the content already fits, so the failure mode of a bad measurement is the
49+
* previous behaviour rather than a zero-height popup.
50+
*/
51+
internal fun PopupWindow.capHeightToSpaceBelow(
52+
anchorView: View,
53+
content: View,
54+
) {
55+
val available = getMaxAvailableHeight(anchorView)
56+
if (available <= 0) return
57+
58+
val unspecified = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
59+
content.measure(unspecified, unspecified)
60+
if (content.measuredHeight > available) {
61+
height = available
62+
}
63+
}
64+
3865
fun showPopupWindow(
3966
context: Context,
4067
anchorView: View,
@@ -161,6 +188,7 @@ object ActionMenuUtils {
161188
}
162189
}
163190

191+
popupWindow.capHeightToSpaceBelow(anchorView, binding.root)
164192
popupWindow.showAsDropDown(anchorView, 0, 0)
165193
}
166194
}

‎app/src/main/java/com/itsaky/androidide/utils/ProjectValidations.kt‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -146,13 +146,24 @@ internal fun isDeepLinkTargetOfOpenProject(
146146
openProjectPath: String,
147147
projectName: String,
148148
projectsRoot: File,
149-
): Boolean =
150-
// "Could not tell" collapses to "no" for callers that only want a Boolean. That is not a
151-
// behaviour change from the older canonicalOrAbsolute fallback: that fallback compared the plain
152-
// absolutePath when canonicalisation failed, and equal absolute paths are already settled true by
153-
// the no-IO shortcut -- so reaching it at all meant they differed, and the answer was false
154-
// either way. Expressing it this way keeps the canonicalisation spelled once.
155-
deepLinkTargetOfOpenProjectOrNull(openProjectPath, projectName, projectsRoot) ?: false
149+
): Boolean {
150+
deepLinkTargetOfOpenProjectWithoutIo(openProjectPath, projectName, projectsRoot)?.let { return it }
151+
152+
// Deliberately NOT `deepLinkTargetOfOpenProjectOrNull(...) ?: false`, which was tried on the
153+
// grounds that it could not change behaviour. It can: this compares per side, so when exactly one
154+
// side's canonicalPath fails it still compares that side's absolutePath against the other's
155+
// canonical path -- and those can match, e.g. a projectsRoot given as /sdcard/CodeOnTheGoProjects
156+
// against an open project under /storage/emulated/0/CodeOnTheGoProjects whose parent has just
157+
// become unreadable. The nullable variant returns null on the first failure, which collapses to
158+
// false, and at this function's two callers a false means a same-project deep link is treated as
159+
// a project switch: the project is closed and reopened instead of the file simply being shown.
160+
//
161+
// So the two functions differ on purpose. This one stays lenient for callers that must answer
162+
// now; the nullable one is strict for a caller that will REMEMBER the answer, where a wrong false
163+
// outlives the condition that caused it.
164+
val parent = File(openProjectPath).parentFile ?: return false
165+
return canonicalOrAbsolute(parent) == canonicalOrAbsolute(projectsRoot)
166+
}
156167

157168
/**
158169
* [isDeepLinkTargetOfOpenProject] with "could not tell" kept apart from "no", for a caller that
@@ -209,6 +220,8 @@ internal fun deepLinkTargetOfOpenProjectWithoutIo(
209220
return null
210221
}
211222

223+
private fun canonicalOrAbsolute(file: File): String = runCatching { file.canonicalPath }.getOrElse { file.absolutePath }
224+
212225
/** Determines if the directory contains a valid Android project structure. */
213226
fun isValidProjectDirectory(selectedDir: File): Boolean {
214227
if (isPluginProject(selectedDir)) {

‎app/src/test/java/com/itsaky/androidide/actions/file/CreateLinkActionTest.kt‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,17 @@
1818
package com.itsaky.androidide.actions.file
1919

2020
import com.google.common.truth.Truth.assertThat
21+
import com.itsaky.androidide.models.DeepLinkRequest
2122
import org.junit.Test
23+
import org.junit.runner.RunWith
24+
import org.robolectric.RobolectricTestRunner
2225
import java.io.File
2326

2427
/**
2528
* The non-UI half of [CreateLinkAction]: deciding what path a link may name. A link gets handed to
2629
* another person, so "outside the project" has to be a hard no rather than a best effort.
2730
*/
31+
@RunWith(RobolectricTestRunner::class)
2832
class CreateLinkActionTest {
2933
private val project = File("/storage/emulated/0/CodeOnTheGoProjects/MyApp")
3034

@@ -70,4 +74,21 @@ class CreateLinkActionTest {
7074
// which is the branch worth covering anyway.
7175
assertThat(projectRelativePathOrNull(project, File("/data/local/tmp/Main.kt"))).isNull()
7276
}
77+
78+
@Test
79+
fun `the cursor is converted from zero-based to one-based`() {
80+
assertThat(oneBasedCursorPosition(0, 0)).isEqualTo(1 to 1)
81+
assertThat(oneBasedCursorPosition(9, 4)).isEqualTo(10 to 5)
82+
}
83+
84+
@Test
85+
fun `a cursor at the very start of a file still yields a link`() {
86+
// Why the conversion is load-bearing rather than cosmetic: buildUrl refuses a line or column
87+
// below 1, so passing the raw zero-based cursor produces no link at all -- and the action
88+
// hides the menu item, which looks exactly like the ordinary hidden-when-unlinkable state.
89+
val (line, column) = oneBasedCursorPosition(0, 0)
90+
assertThat(DeepLinkRequest.buildUrl("MyApp", "Main.kt", line, column))
91+
.endsWith("/file/Main.kt/line/1/column/1")
92+
assertThat(DeepLinkRequest.buildUrl("MyApp", "Main.kt", 0, 0)).isNull()
93+
}
7394
}

‎app/src/test/java/com/itsaky/androidide/models/DeepLinkManifestPrefixTest.kt‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ class DeepLinkManifestPrefixTest {
4949
// Scoped to <data> elements that name a deep-link host, NOT every pathPrefix in the file. An
5050
// unrelated App Link added elsewhere in the manifest is not drift in this scheme, and failing
5151
// on it would point the reader at DeepLinkRequest for someone else's change.
52-
val declared =
52+
val elements =
5353
Regex("""<data\b[^>]*>""", RegexOption.DOT_MATCHES_ALL)
5454
.findAll(manifest!!.readText())
5555
.map { it.value }
5656
.filter { it.contains("appdevforall.org") }
57-
.mapNotNull { Regex("""android:pathPrefix\s*=\s*"([^"]*)"""").find(it)?.groupValues?.get(1) }
5857
.toList()
58+
val declared = elements.mapNotNull { attribute(it, "android:pathPrefix") }
5959

6060
// If the intent-filter stops declaring a prefix, this test must fail rather than vacuously
6161
// pass over an empty list -- there are two <data> elements today, one per verified host.
@@ -64,10 +64,25 @@ class DeepLinkManifestPrefixTest {
6464
// Taken from a URL the builder actually produces, so this asserts against the emitted shape
6565
// rather than against a second copy of the constant.
6666
val built = DeepLinkRequest.buildUrl("MyApp", "Main.kt", line = 1, column = 1)
67-
val path = Uri.parse(built!!).path!!
67+
val emitted = Uri.parse(built!!)
6868

6969
for (prefix in declared) {
70-
assertThat(path).startsWith(prefix)
70+
assertThat(emitted.path).startsWith(prefix)
7171
}
72+
73+
// Host and scheme too, not only the path. An intent-filter matches on all three, so changing
74+
// CANONICAL_HOST or SCHEME without the manifest breaks delivery exactly as changing the prefix
75+
// does -- and a path-only assertion stays green through both.
76+
val hosts = elements.mapNotNull { attribute(it, "android:host") }.toSet()
77+
val schemes = elements.mapNotNull { attribute(it, "android:scheme") }.toSet()
78+
assertThat(hosts).isNotEmpty()
79+
assertThat(schemes).isNotEmpty()
80+
assertThat(hosts).contains(emitted.host)
81+
assertThat(schemes).contains(emitted.scheme)
7282
}
83+
84+
private fun attribute(
85+
element: String,
86+
name: String,
87+
): String? = Regex("""$name\s*=\s*"([^"]*)"""").find(element)?.groupValues?.get(1)
7388
}

0 commit comments

Comments
 (0)