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 40f2dc6425..888d58a211 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 @@ -25,7 +25,6 @@ import android.content.res.Configuration import android.os.Bundle import android.text.TextUtils import android.util.Log -import android.util.TypedValue import android.view.KeyEvent import android.view.View import android.view.ViewGroup.LayoutParams @@ -135,7 +134,6 @@ import com.itsaky.androidide.utils.UniqueNameBuilder import com.itsaky.androidide.utils.capHeightToSpaceBelow import com.itsaky.androidide.utils.flashError import com.itsaky.androidide.utils.flashSuccess -import com.itsaky.androidide.utils.forEachViewRecursively import com.itsaky.androidide.utils.hasVisibleDialog import com.itsaky.androidide.utils.isDeepLinkTargetOfOpenProject import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping @@ -154,7 +152,6 @@ import org.greenrobot.eventbus.ThreadMode import org.koin.android.ext.android.inject import org.koin.core.qualifier.named import java.io.File -import java.util.WeakHashMap import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicBoolean @@ -183,8 +180,7 @@ open class EditorHandlerActivity : private val pluginTabIndices = mutableMapOf() private val tabIndexToPluginId = mutableMapOf() - private var lastAppliedPluginFontScale = EditorPreferences.editorFontScale - private val pluginTextBaseSizes = WeakHashMap() + private val pluginTextScaler = PluginTextScaler(EditorPreferences.editorFontScale) private val pluginFontScalingListener = object : FragmentManager.FragmentLifecycleCallbacks() { @@ -194,9 +190,8 @@ open class EditorHandlerActivity : view: View, savedInstanceState: Bundle?, ) { - val scale = EditorPreferences.editorFontScale - if (scale != 1f && isPluginFragment(mFragment)) { - applyPluginFontScale(view, scale) + if (isPluginFragment(mFragment)) { + pluginTextScaler.track(view) } } } @@ -2026,47 +2021,13 @@ open class EditorHandlerActivity : } } + // Also run from onStart: the event is missed while another activity, such as Preferences, is in front. private fun syncPluginUiFontSize() { - val scale = EditorPreferences.editorFontScale - if (scale == lastAppliedPluginFontScale) { - return - } - lastAppliedPluginFontScale = scale - - val pluginFragments = mutableListOf() - collectPluginFragments(supportFragmentManager, pluginFragments) - pluginFragments.forEach { fragment -> - fragment.view?.let { applyPluginFontScale(it, scale) } - } + pluginTextScaler.onEditorFontScaleChanged(EditorPreferences.editorFontScale) } private fun isPluginFragment(fragment: Fragment): Boolean = fragment.javaClass.classLoader !== javaClass.classLoader - private fun applyPluginFontScale( - root: View, - scale: Float, - ) { - root.forEachViewRecursively { view -> - if (view is TextView) { - val baseSize = pluginTextBaseSizes.getOrPut(view) { view.textSize } - view.setTextSize(TypedValue.COMPLEX_UNIT_PX, baseSize * scale) - } - } - } - - private fun collectPluginFragments( - manager: FragmentManager, - into: MutableList, - ) { - manager.fragments.forEach { fragment -> - if (isPluginFragment(fragment)) { - into.add(fragment) - } else { - collectPluginFragments(fragment.childFragmentManager, into) - } - } - } - /** * Shows [dialog] above any floating windows, tracking it when it was actually raised. * diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/PluginTextScaler.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/PluginTextScaler.kt new file mode 100644 index 0000000000..04270253b2 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/PluginTextScaler.kt @@ -0,0 +1,180 @@ +package com.itsaky.androidide.activities.editor + +import android.util.TypedValue +import android.view.View +import android.view.ViewTreeObserver +import android.widget.TextView +import com.itsaky.androidide.utils.forEachViewRecursively +import java.util.Collections +import java.util.WeakHashMap +import kotlin.math.max + +/** + * Scales the text in plugin views by the editor's font-size preference (ADFA-4212). + * + * The scale never goes below 1 (ADFA-7142). The editor's size goes down to 6sp, often by pinching + * the code, and plugin tabs followed it to under half their size. Views a plugin adds after its + * view was built (list rows, chips) are scaled too; without that, one panel mixed two sizes. + * + * Sizes are px, scaled from the size each [TextView] was given by its plugin, so applying the same + * scale twice changes nothing. A size the plugin sets again later becomes that view's new base. + * Auto-sized text is left alone: [TextView.setTextSize] does nothing to it. + */ +internal class PluginTextScaler( + editorFontScale: Float, +) { + private class Sizing( + val base: Float, + var applied: Float, + ) + + private val sizings = WeakHashMap() + private val trackedRoots: MutableSet = Collections.newSetFromMap(WeakHashMap()) + + // Keyed by the window's observer; an entry lasts while some tracked root is in that window. + private val windowWatchers = HashMap() + + private var scale = max(1f, editorFontScale) + + /** + * Scales the text under [root] now, and in the views added under it later. A root tracked + * again, as a fragment that reuses its view causes, is still watched once. + */ + fun track(root: View) { + scaleNewText(root) + if (trackedRoots.add(root)) { + root.addOnAttachStateChangeListener(attachListener) + if (root.isAttachedToWindow) startWatching(root) + } + } + + /** + * Follows a change to the editor's font scale. Unless the plugin text scale stays the same (any + * size below the editor's default leaves it at 1), the text under every tracked root is rescaled, + * and so is every text view seen before that is now off the window, such as a pooled list row. + * After that no text is left at an old scale, so at scale 1 no frame needs a walk. + */ + fun onEditorFontScaleChanged(editorFontScale: Float) { + val newScale = max(1f, editorFontScale) + if (newScale == scale) return + scale = newScale + for (root in trackedRoots.toList()) { + root.forEachViewRecursively { view -> + if (view is TextView && !view.isAutoSized()) apply(view, sizingFor(view), scale) + } + } + for (view in sizings.keys.toList()) { + if (view.isAutoSized()) continue + val sizing = sizingFor(view) + if (sizing.applied != scale) apply(view, sizing, scale) + } + } + + /** + * Brings every text view under [root] to the current scale: new ones, and ones the plugin + * resized. At scale 1 there is nothing to do: plugin text is drawn at its own size, and a scale + * change leaves no view at an old one. Returns whether any changed. + */ + private fun scaleNewText(root: View): Boolean { + if (scale == 1f) return false + var changed = false + root.forEachViewRecursively { view -> + if (view !is TextView || view.isAutoSized()) return@forEachViewRecursively + val sizing = sizingFor(view) + if (sizing.applied != scale) { + apply(view, sizing, scale) + changed = true + } + } + return changed + } + + // Re-recorded when the size is no longer the one this class set: the plugin has set its own. + private fun sizingFor(view: TextView): Sizing { + val known = sizings[view] + if (known != null && view.textSize == known.base * known.applied) return known + return Sizing(view.textSize, 1f).also { sizings[view] = it } + } + + private fun apply( + view: TextView, + sizing: Sizing, + scale: Float, + ) { + view.setTextSize(TypedValue.COMPLEX_UNIT_PX, sizing.base * scale) + sizing.applied = scale + } + + private fun TextView.isAutoSized() = autoSizeTextType != TextView.AUTO_SIZE_TEXT_TYPE_NONE + + private val attachListener = + object : View.OnAttachStateChangeListener { + override fun onViewAttachedToWindow(v: View) = startWatching(v) + + override fun onViewDetachedFromWindow(v: View) = stopWatching(v) + } + + private fun startWatching(root: View) { + val observer = root.viewTreeObserver + val watcher = + windowWatchers.getOrPut(observer) { + WindowWatcher().also { observer.addOnPreDrawListener(it) } + } + watcher.roots.add(root) + } + + // Found by its roots: once a view has left its window, root.viewTreeObserver is a different + // observer, which could not remove the listener. + private fun stopWatching(root: View) { + val entry = windowWatchers.entries.firstOrNull { root in it.value.roots } ?: return + val (observer, watcher) = entry + watcher.roots.remove(root) + if (watcher.roots.isEmpty()) { + if (observer.isAlive) observer.removeOnPreDrawListener(watcher) + windowWatchers.remove(observer) + } + } + + /** + * Catches views added under the tracked roots in one window before the frame that would draw + * them. A pre-draw listener, not a layout one: a scrolling RecyclerView or ListView adds rows + * without any layout pass. A frame in which something was resized is skipped, so its text is + * never drawn at the old size; the next one is laid out for the new size. Never two in a row, + * though: a plugin that sets its own size on every layout would otherwise have every frame + * skipped, and the window would stop drawing. + * + * One per window, not one per root: the window skips a frame if any of its listeners asks it + * to, so two roots each skipping every other frame, a frame apart, would skip them all. Plugin + * dialogs and bottom sheets are windows of their own, so each window decides for itself. + */ + private inner class WindowWatcher : ViewTreeObserver.OnPreDrawListener { + val roots = LinkedHashSet() + private var skippedLast = false + + // Hidden text is caught on the frame that first shows it. At scale 1 nothing is looked at: + // a scale change leaves no text at an old scale (see onEditorFontScaleChanged). + override fun onPreDraw(): Boolean { + if (scale == 1f) { + skippedLast = false + return true + } + var changed = false + for (root in roots) { + if (root.isShown && !isInsideAnotherRoot(root) && scaleNewText(root)) changed = true + } + val skip = changed && !skippedLast + skippedLast = skip + return !skip + } + + // A plugin fragment nested in another's view is tracked too; the outer walk covers it. + private fun isInsideAnotherRoot(root: View): Boolean { + var parent = root.parent + while (parent is View) { + if (parent in roots) return true + parent = parent.parent + } + return false + } + } +} diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/EditorPluginTextScalingTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/EditorPluginTextScalingTest.kt new file mode 100644 index 0000000000..089e9c334a --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/EditorPluginTextScalingTest.kt @@ -0,0 +1,108 @@ +package com.itsaky.androidide.activities.editor + +import android.util.TypedValue +import android.widget.TextView +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.eventbus.events.preferences.PreferenceChangeEvent +import com.itsaky.androidide.preferences.internal.EditorPreferences +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * How [EditorHandlerActivity] feeds [PluginTextScaler] (ADFA-7142): which fragments it tracks and + * which preference changes rescale them. The activity is built but not created, as in the other + * activity tests here, so its own handlers run without the editor's views. Two calls need a + * created activity and are not reached: the callbacks' registration in `onCreate`, and the + * re-read in `onStart` (a direct `onStart` fails in FragmentManager without one). + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = EditorPluginTextScalingTest.TestApp::class) +class EditorPluginTextScalingTest { + open class TestApp : BaseApplication() + + /** Stands in for a plugin's fragment once [pluginFragment] loads it through its own class loader. */ + class StandInFragment : Fragment() + + @Test + fun onlyAPluginFragmentsViewIsScaled() { + EditorPreferences.fontSize = 28f + val activity = activity() + val pluginText = textView(activity) + val ideText = textView(activity) + + fragmentCallbacks(activity).run { + onFragmentViewCreated(activity.supportFragmentManager, pluginFragment(), pluginText, null) + onFragmentViewCreated(activity.supportFragmentManager, StandInFragment(), ideText, null) + } + + assertThat(pluginText.textSize).isEqualTo(40f) + assertThat(ideText.textSize).isEqualTo(20f) + } + + @Test + fun aFontSizeChangeRescalesPluginTextAndOtherPreferencesDoNot() { + val activity = activity() + val text = textView(activity) + fragmentCallbacks(activity).onFragmentViewCreated(activity.supportFragmentManager, pluginFragment(), text, null) + assertThat(text.textSize).isEqualTo(20f) + + EditorPreferences.fontSize = 28f + activity.onPreferenceChanged(PreferenceChangeEvent(EditorPreferences.TAB_SIZE, 8)) + assertThat(text.textSize).isEqualTo(20f) + + activity.onPreferenceChanged(PreferenceChangeEvent(EditorPreferences.FONT_SIZE, 28f)) + assertThat(text.textSize).isEqualTo(40f) + } + + // Pinch-zoom saves through PreferenceManager, which posts the event; this is what receives it. + @Test + fun theFontSizeHandlerIsSubscribedOnTheMainThread() { + val subscribe = + EditorHandlerActivity::class.java + .getMethod("onPreferenceChanged", PreferenceChangeEvent::class.java) + .getAnnotation(Subscribe::class.java) + + assertThat(subscribe).isNotNull() + assertThat(subscribe!!.threadMode).isEqualTo(ThreadMode.MAIN) + } + + private fun activity(): EditorHandlerActivity = Robolectric.buildActivity(EditorHandlerActivity::class.java).get() + + private fun textView(activity: EditorHandlerActivity) = TextView(activity).apply { setTextSize(TypedValue.COMPLEX_UNIT_PX, 20f) } + + private fun fragmentCallbacks(activity: EditorHandlerActivity) = + EditorHandlerActivity::class.java + .getDeclaredField("pluginFontScalingListener") + .apply { isAccessible = true } + .get(activity) as FragmentManager.FragmentLifecycleCallbacks + + // The activity tells a plugin's fragment by its class loader, so define the stand-in again in + // a loader of its own, the way the plugin manager loads a .cgp. + private fun pluginFragment(): Fragment { + val name = StandInFragment::class.java.name + val parent = StandInFragment::class.java.classLoader!! + val loader = + object : ClassLoader(parent) { + override fun loadClass( + className: String, + resolve: Boolean, + ): Class<*> { + if (className != name) return super.loadClass(className, resolve) + synchronized(this) { + findLoadedClass(className)?.let { return it } + val bytes = parent.getResourceAsStream(className.replace('.', '/') + ".class")!!.use { it.readBytes() } + return defineClass(className, bytes, 0, bytes.size) + } + } + } + return loader.loadClass(name).getDeclaredConstructor().newInstance() as Fragment + } +} diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTextScalerTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTextScalerTest.kt new file mode 100644 index 0000000000..9285513cad --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/PluginTextScalerTest.kt @@ -0,0 +1,484 @@ +package com.itsaky.androidide.activities.editor + +import android.app.Activity +import android.app.Application +import android.app.Dialog +import android.content.Context +import android.os.Looper +import android.util.TypedValue +import android.view.View +import android.view.ViewGroup +import android.view.ViewTreeObserver +import android.widget.LinearLayout +import android.widget.TextView +import com.google.common.truth.Truth.assertThat +import org.junit.Before +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 + +/** + * Plugin text follows the editor's font size up, never down (ADFA-7142), and text a plugin adds + * after its view was built gets the same scale as the rest. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [33]) +class PluginTextScalerTest { + private val scaler = PluginTextScaler(1f) + private lateinit var activity: Activity + private lateinit var root: LinearLayout + + @Before + fun setUp() { + activity = Robolectric.buildActivity(Activity::class.java).setup().get() + root = LinearLayout(activity) + } + + private fun text(px: Float) = TextView(activity).apply { setTextSize(TypedValue.COMPLEX_UNIT_PX, px) } + + // Counts how often its size is read: each walk over it reads the size once. + private class CountingTextView( + context: Context, + ) : TextView(context) { + var sizeReads = 0 + + override fun getTextSize(): Float { + sizeReads++ + return super.getTextSize() + } + } + + private fun countingText(px: Float) = CountingTextView(activity).apply { setTextSize(TypedValue.COMPLEX_UNIT_PX, px) } + + // Counts how often a frame asks whether it is shown, the first thing a frame checks per root. + private class CountingRoot( + context: Context, + ) : LinearLayout(context) { + var shownChecks = 0 + + override fun isShown(): Boolean { + shownChecks++ + return super.isShown() + } + } + + private fun attach() = activity.setContentView(root) + + // The window's step before it draws a frame. Returns whether that frame was skipped. + private fun drawFrame(window: View = activity.window.decorView) = window.viewTreeObserver.dispatchOnPreDraw() + + // How many pre-draw listeners the window has, read where ViewTreeObserver keeps them. + private fun preDrawListeners(): Int { + val field = ViewTreeObserver::class.java.getDeclaredField("mOnPreDrawListeners").apply { isAccessible = true } + val listeners = field.get(activity.window.decorView.viewTreeObserver) ?: return 0 + return listeners.javaClass + .getDeclaredMethod("size") + .apply { isAccessible = true } + .invoke(listeners) as Int + } + + @Test + fun textIsScaledWhenTheViewIsTracked() { + scaler.onEditorFontScaleChanged(1.5f) + val label = text(20f).also(root::addView) + + scaler.track(root) + + assertThat(label.textSize).isEqualTo(30f) + } + + @Test + fun textAddedAfterTheViewWasBuiltIsScaledToo() { + scaler.onEditorFontScaleChanged(1.5f) + // As a fragment's view: tracked when created, attached to the window after. + scaler.track(root) + attach() + + val row = text(20f).also(root::addView) + drawFrame() + + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun aViewAlreadyAttachedWhenTrackedStillCatchesLaterText() { + scaler.onEditorFontScaleChanged(1.5f) + attach() + scaler.track(root) + + val row = text(20f).also(root::addView) + drawFrame() + + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun laterFramesDoNotScaleTextAgain() { + scaler.onEditorFontScaleChanged(1.5f) + scaler.track(root) + attach() + val row = text(20f).also(root::addView) + + assertThat(drawFrame()).isTrue() + assertThat(drawFrame()).isFalse() + + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun theEditorsSmallestSizeLeavesPluginTextAtItsOwnSize() { + // The phone ADFA-7142 was found on: the code pinched down to 6.38sp, against a default of 14. + scaler.onEditorFontScaleChanged(6.3809667f / 14f) + val label = text(28f).also(root::addView) + scaler.track(root) + attach() + val row = text(28f).also(root::addView) + + drawFrame() + + assertThat(label.textSize).isEqualTo(28f) + assertThat(row.textSize).isEqualTo(28f) + } + + @Test + fun aPreferenceChangeScalesFromEachViewsOwnSize() { + scaler.onEditorFontScaleChanged(2f) + val label = text(20f).also(root::addView) + scaler.track(root) + + scaler.onEditorFontScaleChanged(1.5f) + assertThat(label.textSize).isEqualTo(30f) + + scaler.onEditorFontScaleChanged(0.5f) + assertThat(label.textSize).isEqualTo(20f) + } + + @Test + fun textAddedAtTheDefaultSizeIsScaledWhenThePreferenceGrows() { + scaler.track(root) + attach() + val row = text(20f).also(root::addView) + drawFrame() + assertThat(row.textSize).isEqualTo(20f) + + scaler.onEditorFontScaleChanged(2f) + + assertThat(row.textSize).isEqualTo(40f) + } + + @Test + fun aDetachedViewStopsWatchingTheWindow() { + scaler.onEditorFontScaleChanged(1.5f) + attach() + val before = preDrawListeners() + scaler.track(root) + (root.parent as ViewGroup).removeView(root) + + val row = text(20f).also(root::addView) + drawFrame() + + assertThat(row.textSize).isEqualTo(20f) + assertThat(preDrawListeners()).isEqualTo(before) + } + + @Test + fun aRootLeavingTheWindowLeavesTheOtherRootsWatched() { + // Two plugin tabs: one is closed, the other stays. + scaler.onEditorFontScaleChanged(1.5f) + val closed = LinearLayout(activity).also(root::addView) + val open = LinearLayout(activity).also(root::addView) + scaler.track(closed) + scaler.track(open) + attach() + + root.removeView(closed) + val row = text(20f).also(open::addView) + drawFrame() + + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun aViewReinsertedAfterThePreferenceChangedMatchesAFreshOne() { + scaler.onEditorFontScaleChanged(1.5f) + attach() + scaler.track(root) + val pooled = text(20f).also(root::addView) + drawFrame() + assertThat(pooled.textSize).isEqualTo(30f) + root.removeView(pooled) + + scaler.onEditorFontScaleChanged(2f) + root.addView(pooled) + val fresh = text(20f).also(root::addView) + drawFrame() + + assertThat(pooled.textSize).isEqualTo(40f) + assertThat(fresh.textSize).isEqualTo(40f) + } + + @Test + fun aViewReinsertedAfterThePreferenceFellToTheDefaultGoesBackToItsOwnSize() { + scaler.onEditorFontScaleChanged(1.5f) + attach() + scaler.track(root) + val pooled = text(20f).also(root::addView) + drawFrame() + root.removeView(pooled) + + scaler.onEditorFontScaleChanged(1f) + root.addView(pooled) + drawFrame() + + assertThat(pooled.textSize).isEqualTo(20f) + } + + @Test + fun textAddedWithNoLayoutPassIsScaledBeforeItIsDrawn() { + // A scrolling RecyclerView or ListView adds rows and draws them with no layout pass in + // between, so only the step before drawing sees them. + scaler.onEditorFontScaleChanged(1.5f) + scaler.track(root) + attach() + val row = text(20f).also(root::addView) + + val skipped = drawFrame() + + assertThat(row.textSize).isEqualTo(30f) + // The frame that found it is skipped, so the row is never drawn at its old size. + assertThat(skipped).isTrue() + } + + @Test + fun hiddenTextIsScaledOnTheFrameThatShowsIt() { + scaler.onEditorFontScaleChanged(1.5f) + scaler.track(root) + attach() + root.visibility = View.GONE + val row = text(20f).also(root::addView) + + assertThat(drawFrame()).isFalse() + assertThat(row.textSize).isEqualTo(20f) + + root.visibility = View.VISIBLE + drawFrame() + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun aSizeThePluginSetsLaterIsScaledFromThere() { + // Say a recycled row whose binding sets its text size again. + scaler.onEditorFontScaleChanged(2f) + scaler.track(root) + attach() + val row = text(20f).also(root::addView) + drawFrame() + assertThat(row.textSize).isEqualTo(40f) + + row.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30f) + drawFrame() + + assertThat(row.textSize).isEqualTo(60f) + } + + @Test + fun aPreferenceChangeKeepsASizeThePluginSetLater() { + scaler.onEditorFontScaleChanged(2f) + val row = text(20f).also(root::addView) + scaler.track(root) + row.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30f) + + scaler.onEditorFontScaleChanged(1.5f) + + assertThat(row.textSize).isEqualTo(45f) + } + + @Test + fun autoSizedTextIsLeftAloneAndNeverHoldsUpAFrame() { + // setTextSize does nothing to auto-sized text, so it would look resized on every frame. + scaler.onEditorFontScaleChanged(2f) + val fitted = text(20f).apply { setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM) } + root.addView(fitted) + scaler.track(root) + attach() + val size = fitted.textSize + + assertThat(listOf(drawFrame(), drawFrame())).containsExactly(false, false) + assertThat(fitted.textSize).isEqualTo(size) + } + + @Test + fun aRootTrackedAgainKeepsOneWatcher() { + // A fragment that hands back the same view each time its view is recreated. + attach() + val before = preDrawListeners() + + scaler.track(root) + scaler.track(root) + + assertThat(preDrawListeners()).isEqualTo(before + 1) + } + + @Test + fun aPluginThatResizesItsTextEveryFrameNeverStopsTheWindowDrawing() { + // Say a fit-to-width routine that sets the size again on every layout. + scaler.onEditorFontScaleChanged(2f) + scaler.track(root) + attach() + val fitted = text(25f).also(root::addView) + + val skipped = + (1..6).map { + fitted.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f) + drawFrame() + } + + assertThat(skipped.zipWithNext().none { (first, second) -> first && second }).isTrue() + assertThat(skipped).contains(true) + } + + @Test + fun aRootAttachedAgainCatchesTextAddedAfterward() { + // A tab whose view is taken off the window and put back, as a pager does. + scaler.onEditorFontScaleChanged(1.5f) + scaler.track(root) + attach() + (root.parent as ViewGroup).removeView(root) + attach() + + val row = text(20f).also(root::addView) + drawFrame() + + assertThat(row.textSize).isEqualTo(30f) + } + + @Test + fun twoPluginsResizingTheirTextEveryFrameStillLetEveryOtherFrameDraw() { + // The window skips a frame if any listener asks. Two plugin tabs, each rescaled on every + // frame and starting a frame apart, must not take turns skipping every one of them. + scaler.onEditorFontScaleChanged(2f) + val first = LinearLayout(activity).also(root::addView) + val second = LinearLayout(activity).also(root::addView) + val fittedFirst = text(25f).also(first::addView) + val fittedSecond = text(25f).also(second::addView) + scaler.track(first) + scaler.track(second) + attach() + + val skipped = + (1..6).map { frame -> + fittedFirst.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f) + if (frame > 1) fittedSecond.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f) + drawFrame() + } + + assertThat(skipped.zipWithNext().none { (first, second) -> first && second }).isTrue() + assertThat(skipped).contains(true) + } + + @Test + fun aPluginDialogSkipsFramesApartFromTheEditorWindow() { + // A plugin's dialog or bottom sheet is a window of its own, drawn in turn with the editor's. + // What one window skipped must not decide whether the other may skip. + scaler.onEditorFontScaleChanged(2f) + val sheet = LinearLayout(activity) + val dialog = Dialog(activity).apply { setContentView(sheet) } + dialog.show() + attach() + shadowOf(Looper.getMainLooper()).idle() + assertThat(sheet.isAttachedToWindow).isTrue() + assertThat(sheet.viewTreeObserver).isNotSameInstanceAs(root.viewTreeObserver) + val inEditor = text(25f).also(root::addView) + val inSheet = text(25f).also(sheet::addView) + scaler.track(root) + scaler.track(sheet) + + val editorSkipped = + (1..6).map { + inEditor.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f) + inSheet.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f) + drawFrame().also { drawFrame(dialog.window!!.decorView) } + } + + assertThat(editorSkipped.zipWithNext().none { (first, second) -> first && second }).isTrue() + assertThat(editorSkipped).contains(true) + } + + @Test + fun aPluginViewNestedInAnotherIsWalkedOncePerFrame() { + // A plugin fragment inside another plugin fragment's view: both views are tracked, the inner + // one first, as its view is created first. + scaler.onEditorFontScaleChanged(2f) + val inner = LinearLayout(activity).also(root::addView) + val label = countingText(20f).also(inner::addView) + scaler.track(inner) + scaler.track(root) + attach() + drawFrame() + label.sizeReads = 0 + + drawFrame() + + assertThat(label.sizeReads).isEqualTo(1) + } + + @Test + fun onceTheScaleIsBackTo1FramesNoLongerWalkThePluginViews() { + scaler.onEditorFontScaleChanged(2f) + val label = countingText(20f).also(root::addView) + scaler.track(root) + attach() + drawFrame() + + scaler.onEditorFontScaleChanged(1f) + label.sizeReads = 0 + drawFrame() + + assertThat(label.sizeReads).isEqualTo(0) + assertThat(label.textSize).isEqualTo(20f) + } + + @Test + fun atScale1AFrameLooksAtNoPluginRoot() { + val counted = CountingRoot(activity).also { it.addView(text(20f)) } + scaler.track(counted) + activity.setContentView(counted) + counted.shownChecks = 0 + + drawFrame() + + assertThat(counted.shownChecks).isEqualTo(0) + } + + @Test + fun aPooledViewThePluginResizedOffTheWindowIsScaledFromItsNewSize() { + scaler.onEditorFontScaleChanged(2f) + attach() + scaler.track(root) + val pooled = text(20f).also(root::addView) + drawFrame() + root.removeView(pooled) + // Bound again while pooled, at a size of the plugin's own. + pooled.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30f) + + scaler.onEditorFontScaleChanged(3f) + + assertThat(pooled.textSize).isEqualTo(90f) + } + + @Test + fun aScaleChangeThatStaysAt1LeavesThePluginTextAlone() { + // Pinching the code from 10 to 8: both below the editor's default. + scaler.onEditorFontScaleChanged(10f / 14f) + val label = countingText(20f).also(root::addView) + scaler.track(root) + label.sizeReads = 0 + + scaler.onEditorFontScaleChanged(8f / 14f) + + assertThat(label.sizeReads).isEqualTo(0) + } +}