Skip to content
Closed
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 @@ -21,6 +21,7 @@ import com.itsaky.androidide.plugins.manager.core.PluginManager
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.lang.ref.WeakReference

class PluginResourceContext(
baseContext: Context,
Expand Down Expand Up @@ -84,13 +85,19 @@ class PluginResourceContext(
oldAssetManager?.close()
}

// The activity's Resources only: each copy gets the loader once, when it is built.
private var patchedResources: Resources? = null
private var cachedLoader: ResourcesLoader? = null
private var cachedProvider: ResourcesProvider? = null

@Suppress("NewApi")
private fun ensurePluginResourcesAdded(targetResources: Resources) {
if (patchedResources === targetResources) return
addPluginResources(targetResources)
patchedResources = targetResources
}

@Suppress("NewApi")
private fun addPluginResources(targetResources: Resources) {
val sourceDir = pluginSourceDir ?: return

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Expand All @@ -102,20 +109,16 @@ class PluginResourceContext(
}
}
targetResources.addLoaders(cachedLoader!!)
patchedResources = targetResources
Log.d(TAG, "Added plugin resources via ResourcesLoader for ${pluginPackageInfo?.packageName}")
} catch (e: FileNotFoundException) {
Log.e(TAG, "ResourcesLoader failed, falling back to addAssetPath", e)
addAssetPathFallback(targetResources.assets, sourceDir)
patchedResources = targetResources
} catch (e: IOException) {
Log.e(TAG, "ResourcesLoader failed, falling back to addAssetPath", e)
addAssetPathFallback(targetResources.assets, sourceDir)
patchedResources = targetResources
}
} else {
addAssetPathFallback(targetResources.assets, sourceDir)
patchedResources = targetResources
}
}

Expand All @@ -130,6 +133,42 @@ class PluginResourceContext(
}
}

private var hostResourcesOwner: WeakReference<Context>? = null
private var hostResourcesConfig: Configuration? = null
private var hostResources: Resources? = null

/**
* The Resources this plugin's views are built on. On Android 11+ that is a copy of [actCtx]'s,
* pinned to its current configuration and never changed once handed out: built on the activity's
* own, which addLoaders had just rebuilt, a tab's first views drew sp text at about half size
* (ADFA-7142). The activity's Resources still get the loader, and first, because plugins also
* resolve their ids through the activity, as AI Core's ChatFragment does with Fragment.getString
* and ContextThemeWrapper(requireContext(), R.style.PluginTheme). Before R there are no loaders,
* and the activity's assets are patched in place.
*/
private fun pluginResourcesFor(actCtx: Context): Resources {
ensurePluginResourcesAdded(actCtx.resources)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return actCtx.resources
val config = actCtx.resources.configuration
val cached = hostResources
if (cached != null && hostResourcesOwner?.get() === actCtx && hostResourcesConfig == config) return cached

val pinned = Configuration(config)
val res = actCtx.createConfigurationContext(pinned).resources
addPluginResources(res)
hostResourcesOwner = WeakReference(actCtx)
hostResourcesConfig = pinned
hostResources = res
val metrics = res.displayMetrics
@Suppress("DEPRECATION")
Log.d(
TAG,
"Resources for $pluginId: fontScale=${res.configuration.fontScale} " +
"density=${metrics.density} scaledDensity=${metrics.scaledDensity}",
)
return res
}

private fun resolveActivityContextAndTheme(): Pair<Context, Theme>? {
val fragmentCtx = PluginFragmentHelper.getCurrentActivityContext(pluginId)
val fragmentTheme = PluginFragmentHelper.getCurrentActivityTheme(pluginId)
Expand All @@ -144,8 +183,7 @@ class PluginResourceContext(
if (!usesCustomPackageId) return pluginResources

val (actCtx, _) = resolveActivityContextAndTheme() ?: return pluginResources
ensurePluginResourcesAdded(actCtx.resources)
return actCtx.resources
return pluginResourcesFor(actCtx)
}

// Never the activity's: every plugin with its own package id adds its APK to those, and asset
Expand Down Expand Up @@ -184,14 +222,14 @@ class PluginResourceContext(
}

val (actCtx, actTheme) = resolveActivityContextAndTheme() ?: return pluginTheme ?: baseContext.theme
ensurePluginResourcesAdded(actCtx.resources)
if (pluginTheme == null || lastActivityTheme !== actTheme) {
val res = pluginResourcesFor(actCtx)
if (pluginTheme?.resources !== res || lastActivityTheme !== actTheme) {
lastActivityTheme = actTheme
inflater = null

if (!pluginThemeResIdResolved) {
pluginThemeResId =
actCtx.resources.getIdentifier(
res.getIdentifier(
PLUGIN_THEME_NAME,
"style",
pluginPackageInfo?.packageName,
Expand All @@ -200,7 +238,7 @@ class PluginResourceContext(
}

pluginTheme =
actCtx.resources.newTheme().apply {
res.newTheme().apply {
setTo(actTheme)

if (appThemeResId != 0) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package com.itsaky.androidide.plugins.manager.loaders

import android.app.Activity
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.res.Configuration
import android.content.res.Resources
import android.content.res.loader.ResourcesLoader
import android.util.TypedValue
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.widget.TextView
import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.plugins.base.PluginFragmentHelper
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

/**
* A plugin with its own resource package id inflates its views against a copy of the activity's
* Resources, which adding its loader never rebuilds mid-inflation (ADFA-7142). The activity's own
* Resources carry the loader too, because plugins also resolve their ids through the activity:
* AI Core's ChatFragment calls Fragment.getString and builds dialogs on
* ContextThemeWrapper(requireContext(), R.style.PluginTheme).
*
* Robolectric does not reproduce the half-size text and cannot load an APK into a ResourcesLoader,
* so these pin where the loader goes, not that a plugin id resolves. It also has no shadow for the
* native theme rebase that adding a loader to the activity triggers: any theme made on the
* activity's Resources before that, the activity's own included, can then neither build views nor
* be copied. So sp sizes are resolved through each side's DisplayMetrics, and the one inflation
* test snapshots a host theme made after the patch.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "xxhdpi")
class PluginResourceContextActivityResourcesTest {
private val activity = Robolectric.buildActivity(Activity::class.java).setup().get()

// Robolectric 4.11 cannot load an APK through ResourcesProvider on R+, so an empty loader
// stands in for the one built from the plugin's APK.
private val pluginLoader = ResourcesLoader()

private val pluginContext =
PluginResourceContext(
activity.applicationContext,
PLUGIN_ID,
activity.applicationContext.resources,
PackageInfo().apply {
packageName = PLUGIN_ID
applicationInfo = ApplicationInfo().apply { sourceDir = "plugin.apk" }
},
javaClass.classLoader,
).also {
PluginResourceContext::class.java
.getDeclaredField("cachedLoader")
.apply { isAccessible = true }
.set(it, pluginLoader)
}

private lateinit var pluginInflater: LayoutInflater

@Before
fun registerPlugin() {
assertThat(pluginContext.usesCustomPackageId()).isTrue()
PluginFragmentHelper.registerPluginContext(PLUGIN_ID, pluginContext)
pluginInflater = PluginFragmentHelper.getPluginInflater(PLUGIN_ID, LayoutInflater.from(activity))
}

@After
fun unregisterPlugin() {
PluginFragmentHelper.unregisterPluginContext(PLUGIN_ID)
}

@Test
fun onceThePluginContextIsUsedItsLoaderIsReachableThroughTheActivity() {
pluginInflater.context.resources

// AI Core: Fragment.getString resolves through requireContext(), and its dialogs through
// ContextThemeWrapper(requireContext(), R.style.PluginTheme).
assertThat(loadersOf(activity.resources)).contains(pluginLoader)
assertThat(loadersOf(ContextThemeWrapper(activity, android.R.style.Theme_Material).resources))
.contains(pluginLoader)
}

@Test
fun thePluginContextHandsOutACopyOfTheActivitysResourcesThatCarriesTheLoader() {
val resources = pluginInflater.context.resources

assertThat(resources).isNotSameInstanceAs(activity.resources)
assertThat(loadersOf(resources)).contains(pluginLoader)
}

@Test
fun pluginViewsAndThemeAreBuiltOnTheCopy() {
pluginInflater.context.resources
val host = ContextThemeWrapper(activity, android.R.style.Theme_Material)
val inflater = PluginFragmentHelper.getPluginInflater(PLUGIN_ID, LayoutInflater.from(host))

val view = inflater.inflate(android.R.layout.simple_list_item_1, null, false)

assertThat(view).isInstanceOf(TextView::class.java)
assertThat(view.resources).isNotSameInstanceAs(activity.resources)
assertThat(view.resources).isSameInstanceAs(inflater.context.resources)
assertThat(inflater.context.theme.resources).isSameInstanceAs(view.resources)
}

@Test
fun spThroughThePluginMatchesTheActivity() {
assertThat(sp15(pluginInflater.context.resources)).isEqualTo(sp15(activity.resources))
}

@Test
fun spThroughThePluginFollowsAFontScaleChangeTheActivityHandlesItself() {
val before = sp15(pluginInflater.context.resources)
assertThat(before).isEqualTo(sp15(activity.resources))

// EditorActivityKt declares fontScale in configChanges, so its Resources object is kept and
// updated in place rather than replaced.
@Suppress("DEPRECATION")
activity.resources.updateConfiguration(
Configuration(activity.resources.configuration).apply { fontScale = 2f },
activity.resources.displayMetrics,
)

assertThat(sp15(activity.resources)).isGreaterThan(before)
assertThat(sp15(pluginInflater.context.resources)).isEqualTo(sp15(activity.resources))
}

private fun sp15(resources: Resources): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15f, resources.displayMetrics)

/** Resources.getLoaders() is hidden; Robolectric's framework jar still has it. */
private fun loadersOf(resources: Resources): List<*> = Resources::class.java.getMethod("getLoaders").invoke(resources) as List<*>

private companion object {
const val PLUGIN_ID = "com.itsaky.androidide.plugins.manager.loaders.fakeplugin"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class PluginResourceContextActivitySnapshotTest {
PluginFragmentHelper.getPluginInflater(PLUGIN_ID, LayoutInflater.from(pluginContext))

assertThat(PluginFragmentHelper.getCurrentActivityContext(PLUGIN_ID)).isSameInstanceAs(app)
assertThat(pluginContext.resources).isSameInstanceAs(app.resources)
assertThat(pluginContext.resources.configuration).isEqualTo(app.resources.configuration)
}

@Test
Expand All @@ -58,7 +58,7 @@ class PluginResourceContextActivitySnapshotTest {
PluginFragmentHelper.getPluginInflater(PLUGIN_ID, wrapped)

assertThat(PluginFragmentHelper.getCurrentActivityContext(PLUGIN_ID)).isSameInstanceAs(app)
assertThat(pluginContext.resources).isSameInstanceAs(app.resources)
assertThat(pluginContext.resources.configuration).isEqualTo(app.resources.configuration)
}

private companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config

/**
* A plugin with its own resource package id resolves its resources through the activity's, which
* every such plugin adds its APK to. Asset paths carry no package id, so a path two plugins both
* ship must still open the reading plugin's own copy.
* A plugin with its own resource package id resolves its resources through the activity's, or a
* copy of them, which also hold the host APK. Asset paths carry no package id, so a path shipped
* twice must still open the reading plugin's own copy.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
Expand Down Expand Up @@ -61,7 +61,7 @@ class PluginResourceContextAssetsTest {

@Test
fun assetsComeFromThePluginsOwnApkWhileResourcesComeFromTheActivity() {
assertThat(pluginContext.resources).isSameInstanceAs(app.resources)
assertThat(pluginContext.resources.configuration).isEqualTo(app.resources.configuration)
assertThat(pluginContext.assets).isSameInstanceAs(ownResources.assets)
}

Expand Down
Loading