Update FontsModule.kt

This commit is contained in:
OTKUSteyler 2026-09-05 19:46:48 +02:00 • committed by GitHub
parent f96d53db9a
commit baacefef54
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,4 +1,6 @@
package GoonXposed.xposed.modules.appearance @file:Suppress("DEPRECATION")
package GoonXposed.xposed.tweaks.appearance
import android.content.res.AssetManager import android.content.res.AssetManager
import android.graphics.Typeface import android.graphics.Typeface
@ -6,26 +8,15 @@ import android.graphics.Typeface.CustomFallbackBuilder
import android.graphics.fonts.Font import android.graphics.fonts.Font
import android.graphics.fonts.FontFamily import android.graphics.fonts.FontFamily
import android.os.Build import android.os.Build
import de.robv.android.xposed.XC_MethodHook.MethodHookParam import GoonXposed.Logger
import de.robv.android.xposed.XC_MethodReplacement import GoonXposed.xposed.*
import de.robv.android.xposed.XposedHelpers import GoonXposed.xposed.tweaks.PayloadBuilder
import de.robv.android.xposed.callbacks.XC_LoadPackage
import GoonXposed.xposed.Constants
import GoonXposed.xposed.Module
import GoonXposed.xposed.Utils.Companion.JSON
import GoonXposed.xposed.Utils.Log
import GoonXposed.xposed.asDir
import GoonXposed.xposed.asFile
import io.ktor.client.*
import io.ktor.client.call.* import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.request.* import io.ktor.client.request.*
import io.ktor.client.statement.* import io.ktor.client.statement.*
import io.ktor.http.* import io.ktor.http.*
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.put import kotlinx.serialization.json.put
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
@ -38,166 +29,107 @@ data class FontDefinition(
val main: Map<String, String>, val main: Map<String, String>,
) )
object FontsModule : Module() { /**
private val EXTENSIONS = arrayOf("", "_bold", "_italic", "_bold_italic") * Custom font loading + ReactFontManager hijack.
private val FILE_EXTENSIONS = arrayOf(".ttf", ".otf") */
private const val FONTS_ASSET_PATH = "fonts/" val fonts by tweak {
val log: Logger = this.log
private lateinit var fontsDir: File PayloadBuilder.contribute { put("fontPatch", 2) }
private lateinit var fontsDownloadsDir: File
private var fontsAbsPath: String? = null
override fun buildPayload(builder: JsonObjectBuilder) { // ReactFontManager hijack runs regardless of fonts.json presence it falls back to the default Typeface chain if no custom font file is found.
builder.apply { listOf(
put("fontPatch", 2) "com.facebook.react.common.assets.ReactFontManager\$Companion",
"com.facebook.react.views.text.ReactFontManager\$Companion",
).forEach { clsName ->
classLoader.loadClassOrNull(clsName)?.let { cls ->
runCatching {
cls.method("createAssetTypeface", String::class.java, Int::class.java, AssetManager::class.java).hook {
before {
val fontFamilyName: String = args[0].toString()
val style: Int = args[1] as Int
val assetManager: AssetManager = args[2] as AssetManager
result = FontsState.createAssetTypeface(fontFamilyName, style, assetManager)
}
}
}
} }
} }
override fun onLoad(packageParam: XC_LoadPackage.LoadPackageParam) = with(packageParam) { withAppContext { ctx ->
XposedHelpers.findAndHookMethod( val dataDir = ctx.dataDir.absolutePath
"com.facebook.react.common.assets.ReactFontManager\$Companion", val fontDefFile = File(dataDir, "${Constants.FILES_DIR}/fonts.json").apply { ensureFile() }
classLoader, if (!fontDefFile.exists()) return@withAppContext
"createAssetTypeface",
String::class.java,
Int::class.java,
"android.content.res.AssetManager",
object : XC_MethodReplacement() {
override fun replaceHookedMethod(param: MethodHookParam): Typeface? {
val fontFamilyName: String = param.args[0].toString()
val style: Int = param.args[1] as Int
val assetManager: AssetManager = param.args[2] as AssetManager
return createAssetTypeface(fontFamilyName, style, assetManager)
}
})
val fontDefFile = File(appInfo.dataDir, "${Constants.FILES_DIR}/fonts.json").apply { asFile() }
if (!fontDefFile.exists()) return@with
val fontDef = try { val fontDef = try {
JSON.decodeFromString<FontDefinition>(fontDefFile.readText()) Json.decodeFromString<FontDefinition>(fontDefFile.readText())
} catch (_: Throwable) { } catch (e: Throwable) {
return@with log.w("fonts.json malformed: ${e.message}")
return@withAppContext
} }
val setName = fontDef.name ?: return@withAppContext
val fontName = fontDef.name ?: return@with val downloadsDir = File(dataDir, "${Constants.FILES_DIR}/downloads/fonts").apply { ensureDir() }
fontsDownloadsDir = File(appInfo.dataDir, "${Constants.FILES_DIR}/downloads/fonts").apply { asDir() } val setDir = File(downloadsDir, setName).apply { ensureDir() }
fontsDir = File(fontsDownloadsDir, fontName).apply { asDir() } FontsState.fontsDownloadsDir = downloadsDir
fontsAbsPath = fontsDir.absolutePath + "/" FontsState.fontsAbsPath = setDir.absolutePath + "/"
fontsDir.listFiles()?.forEach { file -> // Prune stale font files for this set.
setDir.listFiles()?.forEach { file ->
val fileName = file.name val fileName = file.name
if (!fileName.startsWith(".")) { if (!fileName.startsWith(".")) {
val fontName = fileName.split('.')[0] val fontName = fileName.split('.')[0]
if (fontDef.main.keys.none { it == fontName }) { if (fontDef.main.keys.none { it == fontName }) {
Log.i("Deleting font file: $fileName") log.i("Deleting stale font file: $fileName")
file.delete() file.delete()
} }
} }
} }
// These files should be downloaded by the JS side, but oh well
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
fontDef.main.keys.map { name -> fontDef.main.entries.map { (name, url) ->
async { async {
val url = fontDef.main.getValue(name)
try { try {
Log.i("Downloading $name from $url") log.i("Downloading $name from $url")
val file = val ext = FontsState.FILE_EXTENSIONS.firstOrNull { url.endsWith(it) } ?: ".ttf"
File(fontsDir, "$name${FILE_EXTENSIONS.first { url.endsWith(it) }}").apply { asFile() } val file = File(setDir, "$name$ext").apply { ensureFile() }
if (file.exists()) return@async if (file.exists()) return@async
val response: HttpResponse = httpClient.get(url)
val client = HttpClient(CIO) { if (response.status == HttpStatusCode.OK) {
install(UserAgent) { agent = Constants.USER_AGENT } file.writeBytes(response.body())
} }
val response: HttpResponse = client.get(url)
if (response.status == HttpStatusCode.OK) file.writeBytes(response.body())
return@async
} catch (e: Throwable) { } catch (e: Throwable) {
Log.e("Failed to download fonts ($name from $url)", e) log.e("Failed to download font ($name from $url)", e)
} }
} }
}.awaitAll() }.awaitAll()
} }
} }
}
private fun splitFontName(fontFamilyName: String): Pair<String, String> { /**
val parts = fontFamilyName.split(":") * Holds the per-process font-state used by the `createAssetTypeface` hijack. Mirrors the static
return if (parts.size >= 2) parts[0] to parts[1] else "" to fontFamilyName * fields of the old `FontsModule`.
} */
private object FontsState {
val EXTENSIONS = arrayOf("", "_bold", "_italic", "_bold_italic")
val FILE_EXTENSIONS = arrayOf(".ttf", ".otf")
const val FONTS_ASSET_PATH = "fonts/"
private fun fontFileFor(customName: String, refName: String, fileExtension: String): File = @Volatile
if (customName.isEmpty()) File(fontsDownloadsDir, "$refName.$fileExtension") var fontsDownloadsDir: File? = null
else File(fontsDownloadsDir, "$customName/$refName.$fileExtension")
private fun createAssetTypefaceWithFallbacks( @Volatile
fontFamilyNames: Array<String>, style: Int, assetManager: AssetManager var fontsAbsPath: String? = null
fun createAssetTypeface(
rawName: String,
style: Int,
assetManager: AssetManager,
): Typeface? { ): Typeface? {
val fontFamilies: MutableList<FontFamily> = ArrayList() val fontFamilyNames = rawName.split(",").map { it.trim() }.filter { it.isNotEmpty() }.toTypedArray()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Iterate over the list of fontFamilyNames, constructing new FontFamily objects
// for use in the CustomFallbackBuilder below.
for (fontFamilyName in fontFamilyNames) {
try {
for (fileExtension in FILE_EXTENSIONS) {
val (customName, refName) = splitFontName(fontFamilyName)
val file = fontFileFor(customName, refName, fileExtension).apply { asFile() }
val font = Font.Builder(file).build()
val family = FontFamily.Builder(font).build()
fontFamilies.add(family)
}
} catch (_: Throwable) {
}
for (fontRootPath in arrayOf(fontsAbsPath, FONTS_ASSET_PATH).filterNotNull()) { var fontFamilyName = rawName
for (fileExtension in FILE_EXTENSIONS) {
val fileName =
StringBuilder().append(fontRootPath).append(fontFamilyName).append(fileExtension).toString()
try {
val builder = if (fileName[0] == '/') Font.Builder(File(fileName)) else Font.Builder(
assetManager, fileName
)
val font = builder.build()
val family = FontFamily.Builder(font).build()
fontFamilies.add(family)
} catch (_: RuntimeException) {
// If the typeface asset does not exist, try another extension.
continue
} catch (_: IOException) {
// If the typeface asset does not exist, try another extension.
continue
}
}
}
}
// If there's some problem constructing fonts, fall back to the default behavior.
if (fontFamilies.isEmpty()) return createAssetTypeface(fontFamilyNames[0], style, assetManager)
val fallbackBuilder = CustomFallbackBuilder(fontFamilies[0])
for (i in 1 until fontFamilies.size) {
fallbackBuilder.addCustomFallback(fontFamilies[i])
}
return fallbackBuilder.build()
}
return null
}
private fun createAssetTypeface(
fontFamilyName: String, style: Int, assetManager: AssetManager
): Typeface? {
// This logic attempts to safely check if the frontend code is attempting to use
// fallback fonts, and if it is, to use the fallback typeface creation logic.
var fontFamilyName: String = fontFamilyName
val fontFamilyNames = fontFamilyName.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in fontFamilyNames.indices) {
fontFamilyNames[i] = fontFamilyNames[i].trim()
}
// If there are multiple font family names:
// For newer versions of Android, construct a Typeface with fallbacks
// For older versions of Android, ignore all the fallbacks and just use the first font family
if (fontFamilyNames.size > 1) { if (fontFamilyNames.size > 1) {
fontFamilyName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { fontFamilyName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return createAssetTypefaceWithFallbacks(fontFamilyNames, style, assetManager) return createAssetTypefaceWithFallbacks(fontFamilyNames, style, assetManager)
@ -206,36 +138,78 @@ object FontsModule : Module() {
} }
} }
val extension = EXTENSIONS[style] val extension = EXTENSIONS.getOrElse(style) { "" }
try { try {
for (fileExtension in FILE_EXTENSIONS) { for (fileExt in FILE_EXTENSIONS) {
val (customName, refName) = splitFontName(fontFamilyName) val split = fontFamilyName.split(":")
val file = fontFileFor(customName, refName, fileExtension).apply { asFile() } if (split.size != 2) break
if (!file.exists()) throw Exception() val (customName, refName) = split
val downloads = fontsDownloadsDir ?: break
val file = File(downloads, "$customName/$refName.$fileExt").apply { ensureFile() }
if (!file.exists()) continue
return Typeface.createFromFile(file.absolutePath) return Typeface.createFromFile(file.absolutePath)
} }
} catch (_: Throwable) { } catch (_: Throwable) {
} }
// Lastly, after all those checks above, this is the original RN logic for
// getting the typeface.
for (fontRootPath in arrayOf(fontsAbsPath, FONTS_ASSET_PATH).filterNotNull()) { for (fontRootPath in arrayOf(fontsAbsPath, FONTS_ASSET_PATH).filterNotNull()) {
for (fileExtension in FILE_EXTENSIONS) { for (fileExt in FILE_EXTENSIONS) {
val fileName = val fileName = "$fontRootPath$fontFamilyName$extension$fileExt"
StringBuilder().append(fontRootPath).append(fontFamilyName).append(extension).append(fileExtension)
.toString()
return try { return try {
if (fileName[0] == '/') Typeface.createFromFile(fileName) if (fileName[0] == '/') Typeface.createFromFile(fileName)
else Typeface.createFromAsset(assetManager, fileName) else Typeface.createFromAsset(assetManager, fileName)
} catch (_: RuntimeException) { } catch (_: RuntimeException) {
// If the typeface asset does not exist, try another extension.
continue continue
} }
} }
} }
return Typeface.create(fontFamilyName, style) return Typeface.create(fontFamilyName, style)
} }
private fun createAssetTypefaceWithFallbacks(
fontFamilyNames: Array<String>,
style: Int,
assetManager: AssetManager,
): Typeface? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null
val fontFamilies: MutableList<FontFamily> = ArrayList()
for (fontFamilyName in fontFamilyNames) {
try {
for (fileExt in FILE_EXTENSIONS) {
val split = fontFamilyName.split(":")
if (split.size != 2) break
val (customName, refName) = split
val downloads = fontsDownloadsDir ?: break
val file = File(downloads, "$customName/$refName.$fileExt").apply { ensureFile() }
if (!file.exists()) continue
val font = Font.Builder(file).build()
fontFamilies.add(FontFamily.Builder(font).build())
}
} catch (_: Throwable) {
}
for (fontRootPath in arrayOf(fontsAbsPath, FONTS_ASSET_PATH).filterNotNull()) {
for (fileExt in FILE_EXTENSIONS) {
val fileName = "$fontRootPath$fontFamilyName$fileExt"
try {
val builder = if (fileName[0] == '/') Font.Builder(File(fileName))
else Font.Builder(assetManager, fileName)
val font = builder.build()
fontFamilies.add(FontFamily.Builder(font).build())
} catch (_: RuntimeException) {
continue
} catch (_: IOException) {
continue
}
}
}
}
if (fontFamilies.isEmpty()) return createAssetTypeface(fontFamilyNames[0], style, assetManager)
val fallbackBuilder = CustomFallbackBuilder(fontFamilies[0])
for (i in 1 until fontFamilies.size) fallbackBuilder.addCustomFallback(fontFamilies[i])
return fallbackBuilder.build()
}
} }