pull/840/head
gedoor 4 years ago
parent 0fac54d28a
commit e360ef66f5
  1. 35
      app/src/main/java/io/legado/app/App.kt
  2. 3
      app/src/main/java/io/legado/app/api/controller/BookshelfController.kt
  3. 4
      app/src/main/java/io/legado/app/constant/AppConst.kt
  4. 4
      app/src/main/java/io/legado/app/data/entities/BookSource.kt
  5. 4
      app/src/main/java/io/legado/app/help/AppConfig.kt
  6. 3
      app/src/main/java/io/legado/app/help/BookHelp.kt
  7. 5
      app/src/main/java/io/legado/app/help/CacheManager.kt
  8. 5
      app/src/main/java/io/legado/app/help/ContentProcessor.kt
  9. 11
      app/src/main/java/io/legado/app/help/DefaultData.kt
  10. 4
      app/src/main/java/io/legado/app/help/JsExtensions.kt
  11. 22
      app/src/main/java/io/legado/app/help/LauncherIconHelp.kt
  12. 4
      app/src/main/java/io/legado/app/help/LocalConfig.kt
  13. 4
      app/src/main/java/io/legado/app/help/ReadBookConfig.kt
  14. 4
      app/src/main/java/io/legado/app/help/ReadTipConfig.kt
  15. 7
      app/src/main/java/io/legado/app/help/SourceHelp.kt
  16. 25
      app/src/main/java/io/legado/app/help/ThemeConfig.kt
  17. 4
      app/src/main/java/io/legado/app/help/http/AjaxWebView.kt
  18. 7
      app/src/main/java/io/legado/app/help/storage/Backup.kt
  19. 16
      app/src/main/java/io/legado/app/help/storage/BookWebDav.kt
  20. 35
      app/src/main/java/io/legado/app/help/storage/Restore.kt
  21. 4
      app/src/main/java/io/legado/app/lib/theme/ATH.kt
  22. 10
      app/src/main/java/io/legado/app/lib/theme/ThemeStore.kt
  23. 3
      app/src/main/java/io/legado/app/model/localBook/AnalyzeTxtFile.kt
  24. 6
      app/src/main/java/io/legado/app/model/localBook/EPUBFile.kt
  25. 15
      app/src/main/java/io/legado/app/model/localBook/LocalBook.kt
  26. 4
      app/src/main/java/io/legado/app/model/rss/RssParserByRule.kt
  27. 4
      app/src/main/java/io/legado/app/model/webBook/BookChapterList.kt
  28. 3
      app/src/main/java/io/legado/app/model/webBook/BookContent.kt
  29. 4
      app/src/main/java/io/legado/app/model/webBook/BookInfo.kt
  30. 4
      app/src/main/java/io/legado/app/model/webBook/BookList.kt
  31. 3
      app/src/main/java/io/legado/app/model/webBook/SearchBookModel.kt
  32. 3
      app/src/main/java/io/legado/app/service/AudioPlayService.kt
  33. 4
      app/src/main/java/io/legado/app/service/BaseReadAloudService.kt
  34. 3
      app/src/main/java/io/legado/app/service/CacheBookService.kt
  35. 4
      app/src/main/java/io/legado/app/service/help/CacheBook.kt
  36. 5
      app/src/main/java/io/legado/app/service/help/ReadAloud.kt
  37. 5
      app/src/main/java/io/legado/app/service/help/ReadBook.kt
  38. 5
      app/src/main/java/io/legado/app/ui/book/cache/CacheViewModel.kt
  39. 3
      app/src/main/java/io/legado/app/ui/book/changesource/ChangeSourceViewModel.kt
  40. 4
      app/src/main/java/io/legado/app/ui/book/read/ReadMenu.kt
  41. 3
      app/src/main/java/io/legado/app/ui/book/read/config/ReadAloudConfigDialog.kt
  42. 3
      app/src/main/java/io/legado/app/ui/book/read/config/SpeakEngineDialog.kt
  43. 4
      app/src/main/java/io/legado/app/ui/book/read/page/entities/TextPage.kt
  44. 6
      app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt
  45. 22
      app/src/main/java/io/legado/app/ui/config/BackupRestoreUi.kt
  46. 12
      app/src/main/java/io/legado/app/ui/config/OtherConfigFragment.kt
  47. 3
      app/src/main/java/io/legado/app/ui/config/ThemeConfigFragment.kt
  48. 4
      app/src/main/java/io/legado/app/ui/main/my/MyFragment.kt
  49. 6
      app/src/main/java/io/legado/app/ui/widget/font/FontSelectDialog.kt
  50. 6
      app/src/main/java/io/legado/app/ui/widget/image/CoverImageView.kt
  51. 4
      app/src/main/java/io/legado/app/utils/ACache.kt
  52. 4
      app/src/main/java/io/legado/app/utils/BitmapUtils.kt
  53. 6
      app/src/main/java/io/legado/app/utils/FileUtils.kt
  54. 9
      app/src/main/java/io/legado/app/utils/LogUtils.kt
  55. 4
      app/src/main/java/io/legado/app/utils/ViewExtensions.kt
  56. 3
      app/src/main/java/io/legado/app/web/SourceDebugWebSocket.kt
  57. 4
      app/src/main/java/io/legado/app/web/utils/AssetsWeb.kt

@ -6,29 +6,26 @@ import android.content.Context
import android.content.res.Configuration import android.content.res.Configuration
import android.os.Build import android.os.Build
import android.provider.Settings import android.provider.Settings
import androidx.appcompat.app.AppCompatDelegate
import androidx.multidex.MultiDexApplication import androidx.multidex.MultiDexApplication
import com.jeremyliao.liveeventbus.LiveEventBus import com.jeremyliao.liveeventbus.LiveEventBus
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
import io.legado.app.constant.AppConst.channelIdDownload import io.legado.app.constant.AppConst.channelIdDownload
import io.legado.app.constant.AppConst.channelIdReadAloud import io.legado.app.constant.AppConst.channelIdReadAloud
import io.legado.app.constant.AppConst.channelIdWeb import io.legado.app.constant.AppConst.channelIdWeb
import io.legado.app.constant.EventBus
import io.legado.app.data.AppDatabase import io.legado.app.data.AppDatabase
import io.legado.app.help.* import io.legado.app.help.ActivityHelp
import io.legado.app.help.AppConfig
import io.legado.app.help.CrashHandler
import io.legado.app.help.ThemeConfig.applyDayNight
import io.legado.app.help.http.HttpHelper import io.legado.app.help.http.HttpHelper
import io.legado.app.utils.LanguageUtils import io.legado.app.utils.LanguageUtils
import io.legado.app.utils.defaultSharedPreferences import io.legado.app.utils.defaultSharedPreferences
import io.legado.app.utils.postEvent
import rxhttp.wrapper.param.RxHttp import rxhttp.wrapper.param.RxHttp
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
class App : MultiDexApplication() { class App : MultiDexApplication() {
companion object { companion object {
@JvmStatic
lateinit var INSTANCE: App
private set
@JvmStatic @JvmStatic
lateinit var db: AppDatabase lateinit var db: AppDatabase
@ -42,11 +39,10 @@ class App : MultiDexApplication() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
INSTANCE = this
androidId = Settings.System.getString(contentResolver, Settings.Secure.ANDROID_ID) androidId = Settings.System.getString(contentResolver, Settings.Secure.ANDROID_ID)
CrashHandler(this) CrashHandler(this)
LanguageUtils.setConfiguration(this) LanguageUtils.setConfiguration(this)
db = AppDatabase.createDatabase(INSTANCE) db = AppDatabase.createDatabase(this)
RxHttp.init(HttpHelper.client, BuildConfig.DEBUG) RxHttp.init(HttpHelper.client, BuildConfig.DEBUG)
RxHttp.setOnParamAssembly { RxHttp.setOnParamAssembly {
it.addHeader(AppConst.UA_NAME, AppConfig.userAgent) it.addHeader(AppConst.UA_NAME, AppConfig.userAgent)
@ -56,7 +52,7 @@ class App : MultiDexApplication() {
versionName = it.versionName versionName = it.versionName
} }
createNotificationChannels() createNotificationChannels()
applyDayNight() applyDayNight(this)
LiveEventBus.config() LiveEventBus.config()
.supportBroadcast(this) .supportBroadcast(this)
.lifecycleObserverAlwaysActive(true) .lifecycleObserverAlwaysActive(true)
@ -69,27 +65,10 @@ class App : MultiDexApplication() {
super.onConfigurationChanged(newConfig) super.onConfigurationChanged(newConfig)
when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) { when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES, Configuration.UI_MODE_NIGHT_YES,
Configuration.UI_MODE_NIGHT_NO -> applyDayNight() Configuration.UI_MODE_NIGHT_NO -> applyDayNight(this)
} }
} }
fun applyDayNight() {
ReadBookConfig.upBg()
ThemeConfig.applyTheme(this)
initNightMode()
postEvent(EventBus.RECREATE, "")
}
private fun initNightMode() {
val targetMode =
if (AppConfig.isNightTheme) {
AppCompatDelegate.MODE_NIGHT_YES
} else {
AppCompatDelegate.MODE_NIGHT_NO
}
AppCompatDelegate.setDefaultNightMode(targetMode)
}
/** /**
* 创建通知ID * 创建通知ID
*/ */

@ -12,6 +12,7 @@ import io.legado.app.utils.cnCompare
import io.legado.app.utils.fromJsonObject import io.legado.app.utils.fromJsonObject
import io.legado.app.utils.getPrefInt import io.legado.app.utils.getPrefInt
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import splitties.init.appCtx
object BookshelfController { object BookshelfController {
@ -22,7 +23,7 @@ object BookshelfController {
return if (books.isEmpty()) { return if (books.isEmpty()) {
returnData.setErrorMsg("还没有添加小说") returnData.setErrorMsg("还没有添加小说")
} else { } else {
val data = when (App.INSTANCE.getPrefInt(PreferKey.bookshelfSort)) { val data = when (appCtx.getPrefInt(PreferKey.bookshelfSort)) {
1 -> books.sortedByDescending { it.latestChapterTime } 1 -> books.sortedByDescending { it.latestChapterTime }
2 -> books.sortedWith { o1, o2 -> 2 -> books.sortedWith { o1, o2 ->
o1.name.cnCompare(o2.name) o1.name.cnCompare(o2.name)

@ -1,8 +1,8 @@
package io.legado.app.constant package io.legado.app.constant
import android.annotation.SuppressLint import android.annotation.SuppressLint
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import splitties.init.appCtx
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import javax.script.ScriptEngine import javax.script.ScriptEngine
import javax.script.ScriptEngineManager import javax.script.ScriptEngineManager
@ -68,5 +68,5 @@ object AppConst {
"androidx.appcompat.view.menu.ListMenuItemView" "androidx.appcompat.view.menu.ListMenuItemView"
) )
val sysElevation = App.INSTANCE.resources.getDimension(R.dimen.design_appbar_elevation).toInt() val sysElevation = appCtx.resources.getDimension(R.dimen.design_appbar_elevation).toInt()
} }

@ -3,7 +3,6 @@ package io.legado.app.data.entities
import android.os.Parcelable import android.os.Parcelable
import android.text.TextUtils import android.text.TextUtils
import androidx.room.* import androidx.room.*
import io.legado.app.App
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
import io.legado.app.constant.BookType import io.legado.app.constant.BookType
import io.legado.app.data.entities.rule.* import io.legado.app.data.entities.rule.*
@ -16,6 +15,7 @@ import io.legado.app.utils.GSON
import io.legado.app.utils.fromJsonObject import io.legado.app.utils.fromJsonObject
import io.legado.app.utils.splitNotBlank import io.legado.app.utils.splitNotBlank
import kotlinx.parcelize.Parcelize import kotlinx.parcelize.Parcelize
import splitties.init.appCtx
import javax.script.SimpleBindings import javax.script.SimpleBindings
@Parcelize @Parcelize
@ -106,7 +106,7 @@ data class BookSource(
if (a.isNotBlank()) { if (a.isNotBlank()) {
kotlin.runCatching { kotlin.runCatching {
if (urlRule.startsWith("<js>", false)) { if (urlRule.startsWith("<js>", false)) {
val aCache = ACache.get(App.INSTANCE, "explore") val aCache = ACache.get(appCtx, "explore")
a = aCache.getAsString(bookSourceUrl) ?: "" a = aCache.getAsString(bookSourceUrl) ?: ""
if (a.isBlank()) { if (a.isBlank()) {
val bindings = SimpleBindings() val bindings = SimpleBindings()

@ -2,15 +2,15 @@ package io.legado.app.help
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
@Suppress("MemberVisibilityCanBePrivate") @Suppress("MemberVisibilityCanBePrivate")
object AppConfig : SharedPreferences.OnSharedPreferenceChangeListener { object AppConfig : SharedPreferences.OnSharedPreferenceChangeListener {
private val context get() = App.INSTANCE private val context get() = appCtx
val isGooglePlay = context.channel == "google" val isGooglePlay = context.channel == "google"
var userAgent: String = getPrefUserAgent() var userAgent: String = getPrefUserAgent()
var replaceEnableDefault = context.getPrefBoolean(PreferKey.replaceEnableDefault, true) var replaceEnableDefault = context.getPrefBoolean(PreferKey.replaceEnableDefault, true)

@ -11,6 +11,7 @@ import io.legado.app.model.localBook.LocalBook
import io.legado.app.utils.* import io.legado.app.utils.*
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import org.apache.commons.text.similarity.JaccardSimilarity import org.apache.commons.text.similarity.JaccardSimilarity
import splitties.init.appCtx
import java.io.File import java.io.File
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
import java.util.regex.Matcher import java.util.regex.Matcher
@ -22,7 +23,7 @@ import kotlin.math.min
object BookHelp { object BookHelp {
private const val cacheFolderName = "book_cache" private const val cacheFolderName = "book_cache"
private const val cacheImageFolderName = "images" private const val cacheImageFolderName = "images"
private val downloadDir: File = App.INSTANCE.externalFilesDir private val downloadDir: File = appCtx.externalFilesDir
private val downloadImages = CopyOnWriteArraySet<String>() private val downloadImages = CopyOnWriteArraySet<String>()
fun clearCache() { fun clearCache() {

@ -4,6 +4,7 @@ import io.legado.app.App
import io.legado.app.data.entities.Cache import io.legado.app.data.entities.Cache
import io.legado.app.model.analyzeRule.QueryTTF import io.legado.app.model.analyzeRule.QueryTTF
import io.legado.app.utils.ACache import io.legado.app.utils.ACache
import splitties.init.appCtx
@Suppress("unused") @Suppress("unused")
object CacheManager { object CacheManager {
@ -19,7 +20,7 @@ object CacheManager {
if (saveTime == 0) 0 else System.currentTimeMillis() + saveTime * 1000 if (saveTime == 0) 0 else System.currentTimeMillis() + saveTime * 1000
when (value) { when (value) {
is QueryTTF -> queryTTFMap[key] = Pair(deadline, value) is QueryTTF -> queryTTFMap[key] = Pair(deadline, value)
is ByteArray -> ACache.get(App.INSTANCE).put(key, value, saveTime) is ByteArray -> ACache.get(appCtx).put(key, value, saveTime)
else -> { else -> {
val cache = Cache(key, value.toString(), deadline) val cache = Cache(key, value.toString(), deadline)
App.db.cacheDao.insert(cache) App.db.cacheDao.insert(cache)
@ -48,7 +49,7 @@ object CacheManager {
} }
fun getByteArray(key: String): ByteArray? { fun getByteArray(key: String): ByteArray? {
return ACache.get(App.INSTANCE).getAsBinary(key) return ACache.get(appCtx).getAsBinary(key)
} }
fun getQueryTTF(key: String): QueryTTF? { fun getQueryTTF(key: String): QueryTTF? {

@ -7,6 +7,7 @@ import io.legado.app.data.entities.ReplaceRule
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
class ContentProcessor(private val bookName: String, private val bookOrigin: String) { class ContentProcessor(private val bookName: String, private val bookOrigin: String) {
@ -40,7 +41,7 @@ class ContentProcessor(private val bookName: String, private val bookOrigin: Str
} }
} catch (e: Exception) { } catch (e: Exception) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
App.INSTANCE.toastOnUi("${item.name}替换出错") appCtx.toastOnUi("${item.name}替换出错")
} }
} }
} }
@ -57,7 +58,7 @@ class ContentProcessor(private val bookName: String, private val bookOrigin: Str
} }
} catch (e: Exception) { } catch (e: Exception) {
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
App.INSTANCE.toastOnUi("简繁转换出错") appCtx.toastOnUi("简繁转换出错")
} }
} }
} }

@ -6,6 +6,7 @@ import io.legado.app.data.entities.RssSource
import io.legado.app.data.entities.TxtTocRule import io.legado.app.data.entities.TxtTocRule
import io.legado.app.utils.GSON import io.legado.app.utils.GSON
import io.legado.app.utils.fromJsonArray import io.legado.app.utils.fromJsonArray
import splitties.init.appCtx
import java.io.File import java.io.File
object DefaultData { object DefaultData {
@ -16,7 +17,7 @@ object DefaultData {
val httpTTS by lazy { val httpTTS by lazy {
val json = val json =
String( String(
App.INSTANCE.assets.open("defaultData${File.separator}$httpTtsFileName") appCtx.assets.open("defaultData${File.separator}$httpTtsFileName")
.readBytes() .readBytes()
) )
GSON.fromJsonArray<HttpTTS>(json)!! GSON.fromJsonArray<HttpTTS>(json)!!
@ -24,7 +25,7 @@ object DefaultData {
val readConfigs by lazy { val readConfigs by lazy {
val json = String( val json = String(
App.INSTANCE.assets.open("defaultData${File.separator}${ReadBookConfig.configFileName}") appCtx.assets.open("defaultData${File.separator}${ReadBookConfig.configFileName}")
.readBytes() .readBytes()
) )
GSON.fromJsonArray<ReadBookConfig.Config>(json)!! GSON.fromJsonArray<ReadBookConfig.Config>(json)!!
@ -32,7 +33,7 @@ object DefaultData {
val txtTocRules by lazy { val txtTocRules by lazy {
val json = String( val json = String(
App.INSTANCE.assets.open("defaultData${File.separator}$txtTocRuleFileName") appCtx.assets.open("defaultData${File.separator}$txtTocRuleFileName")
.readBytes() .readBytes()
) )
GSON.fromJsonArray<TxtTocRule>(json)!! GSON.fromJsonArray<TxtTocRule>(json)!!
@ -40,7 +41,7 @@ object DefaultData {
val themeConfigs by lazy { val themeConfigs by lazy {
val json = String( val json = String(
App.INSTANCE.assets.open("defaultData${File.separator}${ThemeConfig.configFileName}") appCtx.assets.open("defaultData${File.separator}${ThemeConfig.configFileName}")
.readBytes() .readBytes()
) )
GSON.fromJsonArray<ThemeConfig.Config>(json)!! GSON.fromJsonArray<ThemeConfig.Config>(json)!!
@ -48,7 +49,7 @@ object DefaultData {
val rssSources by lazy { val rssSources by lazy {
val json = String( val json = String(
App.INSTANCE.assets.open("defaultData${File.separator}rssSources.json") appCtx.assets.open("defaultData${File.separator}rssSources.json")
.readBytes() .readBytes()
) )
GSON.fromJsonArray<RssSource>(json)!! GSON.fromJsonArray<RssSource>(json)!!

@ -3,7 +3,6 @@ package io.legado.app.help
import android.net.Uri import android.net.Uri
import android.util.Base64 import android.util.Base64
import androidx.annotation.Keep import androidx.annotation.Keep
import io.legado.app.App
import io.legado.app.constant.AppConst.dateFormat import io.legado.app.constant.AppConst.dateFormat
import io.legado.app.help.http.CookieStore import io.legado.app.help.http.CookieStore
import io.legado.app.help.http.SSLHelper import io.legado.app.help.http.SSLHelper
@ -16,6 +15,7 @@ import org.jsoup.Connection
import org.jsoup.Jsoup import org.jsoup.Jsoup
import rxhttp.wrapper.param.RxHttp import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toByteArray import rxhttp.wrapper.param.toByteArray
import splitties.init.appCtx
import java.io.File import java.io.File
import java.net.URLEncoder import java.net.URLEncoder
import java.util.* import java.util.*
@ -273,7 +273,7 @@ interface JsExtensions {
} }
return@runBlocking x return@runBlocking x
} }
str.isContentScheme() -> Uri.parse(str).readBytes(App.INSTANCE) str.isContentScheme() -> Uri.parse(str).readBytes(appCtx)
str.startsWith("/storage") -> File(str).readBytes() str.startsWith("/storage") -> File(str).readBytes()
else -> base64DecodeToByteArray(str) else -> base64DecodeToByteArray(str)
} }

@ -3,30 +3,30 @@ package io.legado.app.help
import android.content.ComponentName import android.content.ComponentName
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.ui.welcome.* import io.legado.app.ui.welcome.*
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import splitties.init.appCtx
/** /**
* Created by GKF on 2018/2/27. * Created by GKF on 2018/2/27.
* 更换图标 * 更换图标
*/ */
object LauncherIconHelp { object LauncherIconHelp {
private val packageManager: PackageManager = App.INSTANCE.packageManager private val packageManager: PackageManager = appCtx.packageManager
private val componentNames = arrayListOf( private val componentNames = arrayListOf(
ComponentName(App.INSTANCE, Launcher1::class.java.name), ComponentName(appCtx, Launcher1::class.java.name),
ComponentName(App.INSTANCE, Launcher2::class.java.name), ComponentName(appCtx, Launcher2::class.java.name),
ComponentName(App.INSTANCE, Launcher3::class.java.name), ComponentName(appCtx, Launcher3::class.java.name),
ComponentName(App.INSTANCE, Launcher4::class.java.name), ComponentName(appCtx, Launcher4::class.java.name),
ComponentName(App.INSTANCE, Launcher5::class.java.name), ComponentName(appCtx, Launcher5::class.java.name),
ComponentName(App.INSTANCE, Launcher6::class.java.name) ComponentName(appCtx, Launcher6::class.java.name)
) )
fun changeIcon(icon: String?) { fun changeIcon(icon: String?) {
if (icon.isNullOrEmpty()) return if (icon.isNullOrEmpty()) return
if (Build.VERSION.SDK_INT < 26) { if (Build.VERSION.SDK_INT < 26) {
App.INSTANCE.toastOnUi(R.string.change_icon_error) appCtx.toastOnUi(R.string.change_icon_error)
return return
} }
var hasEnabled = false var hasEnabled = false
@ -50,13 +50,13 @@ object LauncherIconHelp {
} }
if (hasEnabled) { if (hasEnabled) {
packageManager.setComponentEnabledSetting( packageManager.setComponentEnabledSetting(
ComponentName(App.INSTANCE, WelcomeActivity::class.java.name), ComponentName(appCtx, WelcomeActivity::class.java.name),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP PackageManager.DONT_KILL_APP
) )
} else { } else {
packageManager.setComponentEnabledSetting( packageManager.setComponentEnabledSetting(
ComponentName(App.INSTANCE, WelcomeActivity::class.java.name), ComponentName(appCtx, WelcomeActivity::class.java.name),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP PackageManager.DONT_KILL_APP
) )

@ -2,13 +2,13 @@ package io.legado.app.help
import android.content.Context import android.content.Context
import androidx.core.content.edit import androidx.core.content.edit
import io.legado.app.App import splitties.init.appCtx
object LocalConfig { object LocalConfig {
private const val versionCodeKey = "versionCode" private const val versionCodeKey = "versionCode"
private val localConfig = private val localConfig =
App.INSTANCE.getSharedPreferences("local", Context.MODE_PRIVATE) appCtx.getSharedPreferences("local", Context.MODE_PRIVATE)
var versionCode var versionCode
get() = localConfig.getInt(versionCodeKey, 0) get() = localConfig.getInt(versionCodeKey, 0)

@ -5,12 +5,12 @@ import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import androidx.annotation.Keep import androidx.annotation.Keep
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.help.coroutine.Coroutine import io.legado.app.help.coroutine.Coroutine
import io.legado.app.ui.book.read.page.provider.ChapterProvider import io.legado.app.ui.book.read.page.provider.ChapterProvider
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
/** /**
@ -20,7 +20,7 @@ import java.io.File
object ReadBookConfig { object ReadBookConfig {
const val configFileName = "readConfig.json" const val configFileName = "readConfig.json"
const val shareConfigFileName = "shareReadConfig.json" const val shareConfigFileName = "shareReadConfig.json"
val context get() = App.INSTANCE val context get() = appCtx
val configFilePath = FileUtils.getPath(context.filesDir, configFileName) val configFilePath = FileUtils.getPath(context.filesDir, configFileName)
val shareConfigFilePath = FileUtils.getPath(context.filesDir, shareConfigFileName) val shareConfigFilePath = FileUtils.getPath(context.filesDir, shareConfigFileName)
val configList: ArrayList<Config> = arrayListOf() val configList: ArrayList<Config> = arrayListOf()

@ -1,11 +1,11 @@
package io.legado.app.help package io.legado.app.help
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import splitties.init.appCtx
object ReadTipConfig { object ReadTipConfig {
val tips by lazy { val tips by lazy {
App.INSTANCE.resources.getStringArray(R.array.read_tip).toList() appCtx.resources.getStringArray(R.array.read_tip).toList()
} }
val headerModes by lazy { val headerModes by lazy {
linkedMapOf(0 to "状态栏显示时隐藏", 1 to "显示", 2 to "隐藏") linkedMapOf(0 to "状态栏显示时隐藏", 1 to "显示", 2 to "隐藏")

@ -9,13 +9,14 @@ import io.legado.app.utils.EncoderUtils
import io.legado.app.utils.NetworkUtils import io.legado.app.utils.NetworkUtils
import io.legado.app.utils.splitNotBlank import io.legado.app.utils.splitNotBlank
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import splitties.init.appCtx
object SourceHelp { object SourceHelp {
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
private val list18Plus by lazy { private val list18Plus by lazy {
try { try {
return@lazy String(App.INSTANCE.assets.open("18PlusList.txt").readBytes()) return@lazy String(appCtx.assets.open("18PlusList.txt").readBytes())
.splitNotBlank("\n") .splitNotBlank("\n")
} catch (e: Exception) { } catch (e: Exception) {
return@lazy arrayOf<String>() return@lazy arrayOf<String>()
@ -26,7 +27,7 @@ object SourceHelp {
rssSources.forEach { rssSource -> rssSources.forEach { rssSource ->
if (is18Plus(rssSource.sourceUrl)) { if (is18Plus(rssSource.sourceUrl)) {
handler.post { handler.post {
App.INSTANCE.toastOnUi("${rssSource.sourceName}是18+网址,禁止导入.") appCtx.toastOnUi("${rssSource.sourceName}是18+网址,禁止导入.")
} }
} else { } else {
App.db.rssSourceDao.insert(rssSource) App.db.rssSourceDao.insert(rssSource)
@ -38,7 +39,7 @@ object SourceHelp {
bookSources.forEach { bookSource -> bookSources.forEach { bookSource ->
if (is18Plus(bookSource.bookSourceUrl)) { if (is18Plus(bookSource.bookSourceUrl)) {
handler.post { handler.post {
App.INSTANCE.toastOnUi("${bookSource.bookSourceName}是18+网址,禁止导入.") appCtx.toastOnUi("${bookSource.bookSourceName}是18+网址,禁止导入.")
} }
} else { } else {
App.db.bookSourceDao.insert(bookSource) App.db.bookSourceDao.insert(bookSource)

@ -5,24 +5,42 @@ import android.graphics.Color
import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import androidx.annotation.Keep import androidx.annotation.Keep
import io.legado.app.App import androidx.appcompat.app.AppCompatDelegate
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.EventBus import io.legado.app.constant.EventBus
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.constant.Theme import io.legado.app.constant.Theme
import io.legado.app.lib.theme.ThemeStore import io.legado.app.lib.theme.ThemeStore
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
object ThemeConfig { object ThemeConfig {
const val configFileName = "themeConfig.json" const val configFileName = "themeConfig.json"
val configFilePath = FileUtils.getPath(App.INSTANCE.filesDir, configFileName) val configFilePath = FileUtils.getPath(appCtx.filesDir, configFileName)
val configList: ArrayList<Config> by lazy { val configList: ArrayList<Config> by lazy {
val cList = getConfigs() ?: DefaultData.themeConfigs val cList = getConfigs() ?: DefaultData.themeConfigs
ArrayList(cList) ArrayList(cList)
} }
fun applyDayNight(context: Context) {
ReadBookConfig.upBg()
applyTheme(context)
initNightMode()
postEvent(EventBus.RECREATE, "")
}
private fun initNightMode() {
val targetMode =
if (AppConfig.isNightTheme) {
AppCompatDelegate.MODE_NIGHT_YES
} else {
AppCompatDelegate.MODE_NIGHT_NO
}
AppCompatDelegate.setDefaultNightMode(targetMode)
}
fun getBgImage(context: Context): Drawable? { fun getBgImage(context: Context): Drawable? {
val bgPath = when (Theme.getTheme()) { val bgPath = when (Theme.getTheme()) {
Theme.Light -> context.getPrefString(PreferKey.bgImage) Theme.Light -> context.getPrefString(PreferKey.bgImage)
@ -101,8 +119,7 @@ object ThemeConfig {
context.putPrefInt(PreferKey.cBBackground, bBackground) context.putPrefInt(PreferKey.cBBackground, bBackground)
} }
AppConfig.isNightTheme = config.isNightTheme AppConfig.isNightTheme = config.isNightTheme
App.INSTANCE.applyDayNight() applyDayNight(context)
postEvent(EventBus.RECREATE, "")
} }
fun saveDayTheme(context: Context, name: String) { fun saveDayTheme(context: Context, name: String) {

@ -9,9 +9,9 @@ import android.webkit.CookieManager
import android.webkit.WebSettings import android.webkit.WebSettings
import android.webkit.WebView import android.webkit.WebView
import android.webkit.WebViewClient import android.webkit.WebViewClient
import io.legado.app.App
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
import org.apache.commons.text.StringEscapeUtils import org.apache.commons.text.StringEscapeUtils
import splitties.init.appCtx
import java.lang.ref.WeakReference import java.lang.ref.WeakReference
@ -51,7 +51,7 @@ class AjaxWebView {
@SuppressLint("SetJavaScriptEnabled", "JavascriptInterface") @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
fun createAjaxWebView(params: AjaxParams, handler: Handler): WebView { fun createAjaxWebView(params: AjaxParams, handler: Handler): WebView {
val webView = WebView(App.INSTANCE) val webView = WebView(appCtx)
val settings = webView.settings val settings = webView.settings
settings.javaScriptEnabled = true settings.javaScriptEnabled = true
settings.domStorageEnabled = true settings.domStorageEnabled = true

@ -12,6 +12,7 @@ import io.legado.app.help.coroutine.Coroutine
import io.legado.app.utils.* import io.legado.app.utils.*
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
import java.io.File import java.io.File
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
@ -19,7 +20,7 @@ import java.util.concurrent.TimeUnit
object Backup { object Backup {
val backupPath: String by lazy { val backupPath: String by lazy {
FileUtils.getFile(App.INSTANCE.filesDir, "backup").absolutePath FileUtils.getFile(appCtx.filesDir, "backup").absolutePath
} }
val backupFileNames by lazy { val backupFileNames by lazy {
@ -80,9 +81,9 @@ object Backup {
FileUtils.createFileIfNotExist(backupPath + File.separator + ThemeConfig.configFileName) FileUtils.createFileIfNotExist(backupPath + File.separator + ThemeConfig.configFileName)
.writeText(it) .writeText(it)
} }
Preferences.getSharedPreferences(App.INSTANCE, backupPath, "config")?.let { sp -> Preferences.getSharedPreferences(appCtx, backupPath, "config")?.let { sp ->
val edit = sp.edit() val edit = sp.edit()
App.INSTANCE.defaultSharedPreferences.all.map { appCtx.defaultSharedPreferences.all.map {
when (val value = it.value) { when (val value = it.value) {
is Int -> edit.putInt(it.key, value) is Int -> edit.putInt(it.key, value)
is Boolean -> edit.putBoolean(it.key, value) is Boolean -> edit.putBoolean(it.key, value)

@ -3,7 +3,6 @@ package io.legado.app.help.storage
import android.content.Context import android.content.Context
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
@ -16,6 +15,7 @@ import io.legado.app.utils.*
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
import java.io.File import java.io.File
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
@ -27,20 +27,20 @@ object BookWebDav {
private val rootWebDavUrl: String private val rootWebDavUrl: String
get() { get() {
var url = App.INSTANCE.getPrefString(PreferKey.webDavUrl) var url = appCtx.getPrefString(PreferKey.webDavUrl)
if (url.isNullOrEmpty()) { if (url.isNullOrEmpty()) {
url = defaultWebDavUrl url = defaultWebDavUrl
} }
if (!url.endsWith("/")) url = "${url}/" if (!url.endsWith("/")) url = "${url}/"
if (App.INSTANCE.getPrefBoolean(PreferKey.webDavCreateDir, true)) { if (appCtx.getPrefBoolean(PreferKey.webDavCreateDir, true)) {
url = "${url}legado/" url = "${url}legado/"
} }
return url return url
} }
suspend fun initWebDav(): Boolean { suspend fun initWebDav(): Boolean {
val account = App.INSTANCE.getPrefString(PreferKey.webDavAccount) val account = appCtx.getPrefString(PreferKey.webDavAccount)
val password = App.INSTANCE.getPrefString(PreferKey.webDavPassword) val password = appCtx.getPrefString(PreferKey.webDavPassword)
if (!account.isNullOrBlank() && !password.isNullOrBlank()) { if (!account.isNullOrBlank() && !password.isNullOrBlank()) {
HttpAuth.auth = HttpAuth.Auth(account, password) HttpAuth.auth = HttpAuth.Auth(account, password)
WebDav(rootWebDavUrl).makeAsDir() WebDav(rootWebDavUrl).makeAsDir()
@ -79,7 +79,7 @@ object BookWebDav {
Coroutine.async { Coroutine.async {
restoreWebDav(names[index]) restoreWebDav(names[index])
}.onError { }.onError {
App.INSTANCE.toastOnUi("WebDavError:${it.localizedMessage}") appCtx.toastOnUi("WebDavError:${it.localizedMessage}")
} }
} }
} }
@ -117,7 +117,7 @@ object BookWebDav {
} }
} catch (e: Exception) { } catch (e: Exception) {
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
App.INSTANCE.toastOnUi("WebDav\n${e.localizedMessage}") appCtx.toastOnUi("WebDav\n${e.localizedMessage}")
} }
} }
} }
@ -138,7 +138,7 @@ object BookWebDav {
} }
} catch (e: Exception) { } catch (e: Exception) {
Handler(Looper.getMainLooper()).post { Handler(Looper.getMainLooper()).post {
App.INSTANCE.toastOnUi("WebDav导出\n${e.localizedMessage}") appCtx.toastOnUi("WebDav导出\n${e.localizedMessage}")
} }
} }
} }

@ -23,10 +23,11 @@ import io.legado.app.utils.*
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
import java.io.File import java.io.File
object Restore { object Restore {
private val ignoreConfigPath = FileUtils.getPath(App.INSTANCE.filesDir, "restoreIgnore.json") private val ignoreConfigPath = FileUtils.getPath(appCtx.filesDir, "restoreIgnore.json")
val ignoreConfig: HashMap<String, Boolean> by lazy { val ignoreConfig: HashMap<String, Boolean> by lazy {
val file = FileUtils.createFileIfNotExist(ignoreConfigPath) val file = FileUtils.createFileIfNotExist(ignoreConfigPath)
val json = file.readText() val json = file.readText()
@ -44,11 +45,11 @@ object Restore {
//忽略标题 //忽略标题
val ignoreTitle = arrayOf( val ignoreTitle = arrayOf(
App.INSTANCE.getString(R.string.read_config), appCtx.getString(R.string.read_config),
App.INSTANCE.getString(R.string.theme_mode), appCtx.getString(R.string.theme_mode),
App.INSTANCE.getString(R.string.bookshelf_layout), appCtx.getString(R.string.bookshelf_layout),
App.INSTANCE.getString(R.string.show_rss), appCtx.getString(R.string.show_rss),
App.INSTANCE.getString(R.string.thread_count) appCtx.getString(R.string.thread_count)
) )
//默认忽略keys //默认忽略keys
@ -195,8 +196,8 @@ object Restore {
e.printStackTrace() e.printStackTrace()
} }
} }
Preferences.getSharedPreferences(App.INSTANCE, path, "config")?.all?.let { map -> Preferences.getSharedPreferences(appCtx, path, "config")?.all?.let { map ->
val edit = App.INSTANCE.defaultSharedPreferences.edit() val edit = appCtx.defaultSharedPreferences.edit()
map.forEach { map.forEach {
if (keyIsNotIgnore(it.key)) { if (keyIsNotIgnore(it.key)) {
when (val value = it.value) { when (val value = it.value) {
@ -212,22 +213,22 @@ object Restore {
edit.apply() edit.apply()
} }
ReadBookConfig.apply { ReadBookConfig.apply {
styleSelect = App.INSTANCE.getPrefInt(PreferKey.readStyleSelect) styleSelect = appCtx.getPrefInt(PreferKey.readStyleSelect)
shareLayout = App.INSTANCE.getPrefBoolean(PreferKey.shareLayout) shareLayout = appCtx.getPrefBoolean(PreferKey.shareLayout)
hideStatusBar = App.INSTANCE.getPrefBoolean(PreferKey.hideStatusBar) hideStatusBar = appCtx.getPrefBoolean(PreferKey.hideStatusBar)
hideNavigationBar = App.INSTANCE.getPrefBoolean(PreferKey.hideNavigationBar) hideNavigationBar = appCtx.getPrefBoolean(PreferKey.hideNavigationBar)
autoReadSpeed = App.INSTANCE.getPrefInt(PreferKey.autoReadSpeed, 46) autoReadSpeed = appCtx.getPrefInt(PreferKey.autoReadSpeed, 46)
} }
ChapterProvider.upStyle() ChapterProvider.upStyle()
ReadBook.loadContent(resetPageOffset = false) ReadBook.loadContent(resetPageOffset = false)
} }
withContext(Main) { withContext(Main) {
App.INSTANCE.toastOnUi(R.string.restore_success) appCtx.toastOnUi(R.string.restore_success)
if (!BuildConfig.DEBUG) { if (!BuildConfig.DEBUG) {
LauncherIconHelp.changeIcon(App.INSTANCE.getPrefString(PreferKey.launcherIcon)) LauncherIconHelp.changeIcon(appCtx.getPrefString(PreferKey.launcherIcon))
} }
LanguageUtils.setConfiguration(App.INSTANCE) LanguageUtils.setConfiguration(appCtx)
App.INSTANCE.applyDayNight() ThemeConfig.applyDayNight(appCtx)
postEvent(EventBus.SHOW_RSS, "") postEvent(EventBus.SHOW_RSS, "")
} }
} }

@ -18,12 +18,12 @@ import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomnavigation.BottomNavigationView
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.help.AppConfig import io.legado.app.help.AppConfig
import io.legado.app.utils.ColorUtils import io.legado.app.utils.ColorUtils
import io.legado.app.utils.dp import io.legado.app.utils.dp
import io.legado.app.utils.getCompatColor import io.legado.app.utils.getCompatColor
import splitties.init.appCtx
/** /**
* @author Karim Abou Zeid (kabouzeid) * @author Karim Abou Zeid (kabouzeid)
@ -288,7 +288,7 @@ object ATH {
fun getDialogBackground(): GradientDrawable { fun getDialogBackground(): GradientDrawable {
val background = GradientDrawable() val background = GradientDrawable()
background.cornerRadius = 3F.dp background.cornerRadius = 3F.dp
background.setColor(App.INSTANCE.backgroundColor) background.setColor(appCtx.backgroundColor)
return background return background
} }

@ -9,9 +9,9 @@ import androidx.annotation.CheckResult
import androidx.annotation.ColorInt import androidx.annotation.ColorInt
import androidx.annotation.ColorRes import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.utils.ColorUtils import io.legado.app.utils.ColorUtils
import splitties.init.appCtx
/** /**
* @author Aidan Follestad (afollestad), Karim Abou Zeid (kabouzeid) * @author Aidan Follestad (afollestad), Karim Abou Zeid (kabouzeid)
@ -200,7 +200,7 @@ private constructor(private val mContext: Context) : ThemeStoreInterface {
@CheckResult @CheckResult
@ColorInt @ColorInt
fun primaryColor(context: Context = App.INSTANCE): Int { fun primaryColor(context: Context = appCtx): Int {
return prefs(context).getInt( return prefs(context).getInt(
ThemeStorePrefKeys.KEY_PRIMARY_COLOR, ThemeStorePrefKeys.KEY_PRIMARY_COLOR,
ATHUtils.resolveColor(context, R.attr.colorPrimary, Color.parseColor("#455A64")) ATHUtils.resolveColor(context, R.attr.colorPrimary, Color.parseColor("#455A64"))
@ -218,7 +218,7 @@ private constructor(private val mContext: Context) : ThemeStoreInterface {
@CheckResult @CheckResult
@ColorInt @ColorInt
fun accentColor(context: Context = App.INSTANCE): Int { fun accentColor(context: Context = appCtx): Int {
return prefs(context).getInt( return prefs(context).getInt(
ThemeStorePrefKeys.KEY_ACCENT_COLOR, ThemeStorePrefKeys.KEY_ACCENT_COLOR,
ATHUtils.resolveColor(context, R.attr.colorAccent, Color.parseColor("#263238")) ATHUtils.resolveColor(context, R.attr.colorAccent, Color.parseColor("#263238"))
@ -292,7 +292,7 @@ private constructor(private val mContext: Context) : ThemeStoreInterface {
@CheckResult @CheckResult
@ColorInt @ColorInt
fun backgroundColor(context: Context = App.INSTANCE): Int { fun backgroundColor(context: Context = appCtx): Int {
return prefs(context).getInt( return prefs(context).getInt(
ThemeStorePrefKeys.KEY_BACKGROUND_COLOR, ThemeStorePrefKeys.KEY_BACKGROUND_COLOR,
ATHUtils.resolveColor(context, android.R.attr.colorBackground) ATHUtils.resolveColor(context, android.R.attr.colorBackground)
@ -314,7 +314,7 @@ private constructor(private val mContext: Context) : ThemeStoreInterface {
@CheckResult @CheckResult
@ColorInt @ColorInt
fun bottomBackground(context: Context = App.INSTANCE): Int { fun bottomBackground(context: Context = appCtx): Int {
return prefs(context).getInt( return prefs(context).getInt(
ThemeStorePrefKeys.KEY_BOTTOM_BACKGROUND, ThemeStorePrefKeys.KEY_BOTTOM_BACKGROUND,
ATHUtils.resolveColor(context, android.R.attr.colorBackground) ATHUtils.resolveColor(context, android.R.attr.colorBackground)

@ -7,6 +7,7 @@ import io.legado.app.data.entities.BookChapter
import io.legado.app.data.entities.TxtTocRule import io.legado.app.data.entities.TxtTocRule
import io.legado.app.help.DefaultData import io.legado.app.help.DefaultData
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
import java.io.RandomAccessFile import java.io.RandomAccessFile
import java.nio.charset.Charset import java.nio.charset.Charset
@ -266,7 +267,7 @@ class AnalyzeTxtFile {
val bookFile = FileUtils.getFile(LocalBook.cacheFolder, book.originName) val bookFile = FileUtils.getFile(LocalBook.cacheFolder, book.originName)
if (!bookFile.exists()) { if (!bookFile.exists()) {
bookFile.createNewFile() bookFile.createNewFile()
DocumentUtils.readBytes(App.INSTANCE, uri)?.let { DocumentUtils.readBytes(appCtx, uri)?.let {
bookFile.writeBytes(it) bookFile.writeBytes(it)
} }
} }

@ -4,13 +4,13 @@ import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.net.Uri import android.net.Uri
import android.text.TextUtils import android.text.TextUtils
import io.legado.app.App
import io.legado.app.data.entities.BookChapter import io.legado.app.data.entities.BookChapter
import io.legado.app.utils.* import io.legado.app.utils.*
import nl.siegmann.epublib.domain.Book import nl.siegmann.epublib.domain.Book
import nl.siegmann.epublib.domain.TOCReference import nl.siegmann.epublib.domain.TOCReference
import nl.siegmann.epublib.epub.EpubReader import nl.siegmann.epublib.epub.EpubReader
import org.jsoup.Jsoup import org.jsoup.Jsoup
import splitties.init.appCtx
import java.io.File import java.io.File
import java.io.FileOutputStream import java.io.FileOutputStream
import java.io.IOException import java.io.IOException
@ -59,14 +59,14 @@ class EPUBFile(val book: io.legado.app.data.entities.Book) {
val epubReader = EpubReader() val epubReader = EpubReader()
val inputStream = if (book.bookUrl.isContentScheme()) { val inputStream = if (book.bookUrl.isContentScheme()) {
val uri = Uri.parse(book.bookUrl) val uri = Uri.parse(book.bookUrl)
App.INSTANCE.contentResolver.openInputStream(uri) appCtx.contentResolver.openInputStream(uri)
} else { } else {
File(book.bookUrl).inputStream() File(book.bookUrl).inputStream()
} }
epubBook = epubReader.readEpub(inputStream) epubBook = epubReader.readEpub(inputStream)
if (book.coverUrl.isNullOrEmpty()) { if (book.coverUrl.isNullOrEmpty()) {
book.coverUrl = FileUtils.getPath( book.coverUrl = FileUtils.getPath(
App.INSTANCE.externalFilesDir, appCtx.externalFilesDir,
"covers", "covers",
"${MD5Utils.md5Encode16(book.bookUrl)}.jpg" "${MD5Utils.md5Encode16(book.bookUrl)}.jpg"
) )

@ -7,15 +7,16 @@ import io.legado.app.data.entities.Book
import io.legado.app.data.entities.BookChapter import io.legado.app.data.entities.BookChapter
import io.legado.app.help.BookHelp import io.legado.app.help.BookHelp
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
object LocalBook { object LocalBook {
private const val folderName = "bookTxt" private const val folderName = "bookTxt"
val cacheFolder: File by lazy { val cacheFolder: File by lazy {
val rootFile = App.INSTANCE.getExternalFilesDir(null) val rootFile = appCtx.getExternalFilesDir(null)
?: App.INSTANCE.externalCacheDir ?: appCtx.externalCacheDir
?: App.INSTANCE.cacheDir ?: appCtx.cacheDir
FileUtils.createFolderIfNotExist(rootFile, folderName) FileUtils.createFolderIfNotExist(rootFile, folderName)
} }
@ -39,12 +40,12 @@ object LocalBook {
val path: String val path: String
val fileName = if (uri.isContentScheme()) { val fileName = if (uri.isContentScheme()) {
path = uri.toString() path = uri.toString()
val doc = DocumentFile.fromSingleUri(App.INSTANCE, uri) val doc = DocumentFile.fromSingleUri(appCtx, uri)
doc?.let { doc?.let {
val bookFile = FileUtils.getFile(cacheFolder, it.name!!) val bookFile = FileUtils.getFile(cacheFolder, it.name!!)
if (!bookFile.exists()) { if (!bookFile.exists()) {
bookFile.createNewFile() bookFile.createNewFile()
doc.readBytes(App.INSTANCE)?.let { bytes -> doc.readBytes(appCtx)?.let { bytes ->
bookFile.writeBytes(bytes) bookFile.writeBytes(bytes)
} }
} }
@ -77,7 +78,7 @@ object LocalBook {
author = author, author = author,
originName = fileName, originName = fileName,
coverUrl = FileUtils.getPath( coverUrl = FileUtils.getPath(
App.INSTANCE.externalFilesDir, appCtx.externalFilesDir,
"covers", "covers",
"${MD5Utils.md5Encode16(path)}.jpg" "${MD5Utils.md5Encode16(path)}.jpg"
) )
@ -96,7 +97,7 @@ object LocalBook {
if (deleteOriginal) { if (deleteOriginal) {
if (book.bookUrl.isContentScheme()) { if (book.bookUrl.isContentScheme()) {
val uri = Uri.parse(book.bookUrl) val uri = Uri.parse(book.bookUrl)
DocumentFile.fromSingleUri(App.INSTANCE, uri)?.delete() DocumentFile.fromSingleUri(appCtx, uri)?.delete()
} else { } else {
FileUtils.deleteFile(book.bookUrl) FileUtils.deleteFile(book.bookUrl)
} }

@ -1,7 +1,6 @@
package io.legado.app.model.rss package io.legado.app.model.rss
import androidx.annotation.Keep import androidx.annotation.Keep
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.data.entities.RssArticle import io.legado.app.data.entities.RssArticle
import io.legado.app.data.entities.RssSource import io.legado.app.data.entities.RssSource
@ -10,6 +9,7 @@ import io.legado.app.model.analyzeRule.AnalyzeRule
import io.legado.app.model.analyzeRule.RuleDataInterface import io.legado.app.model.analyzeRule.RuleDataInterface
import io.legado.app.utils.GSON import io.legado.app.utils.GSON
import io.legado.app.utils.NetworkUtils import io.legado.app.utils.NetworkUtils
import splitties.init.appCtx
import java.util.* import java.util.*
@Keep @Keep
@ -27,7 +27,7 @@ object RssParserByRule {
var nextUrl: String? = null var nextUrl: String? = null
if (body.isNullOrBlank()) { if (body.isNullOrBlank()) {
throw Exception( throw Exception(
App.INSTANCE.getString(R.string.error_get_web_content, rssSource.sourceUrl) appCtx.getString(R.string.error_get_web_content, rssSource.sourceUrl)
) )
} }
Debug.log(sourceUrl, "≡获取成功:$sourceUrl") Debug.log(sourceUrl, "≡获取成功:$sourceUrl")

@ -1,7 +1,6 @@
package io.legado.app.model.webBook package io.legado.app.model.webBook
import android.text.TextUtils import android.text.TextUtils
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
import io.legado.app.data.entities.BookChapter import io.legado.app.data.entities.BookChapter
@ -14,6 +13,7 @@ import io.legado.app.model.analyzeRule.AnalyzeUrl
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ensureActive import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.suspendCancellableCoroutine
import splitties.init.appCtx
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException import kotlin.coroutines.resumeWithException
@ -29,7 +29,7 @@ object BookChapterList {
kotlin.runCatching { kotlin.runCatching {
val chapterList = ArrayList<BookChapter>() val chapterList = ArrayList<BookChapter>()
body ?: throw Exception( body ?: throw Exception(
App.INSTANCE.getString(R.string.error_get_web_content, baseUrl) appCtx.getString(R.string.error_get_web_content, baseUrl)
) )
Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}") Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}")

@ -14,6 +14,7 @@ import io.legado.app.utils.NetworkUtils
import io.legado.app.utils.htmlFormat import io.legado.app.utils.htmlFormat
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
object BookContent { object BookContent {
@ -28,7 +29,7 @@ object BookContent {
nextChapterUrlF: String? = null nextChapterUrlF: String? = null
): String { ): String {
body ?: throw Exception( body ?: throw Exception(
App.INSTANCE.getString(R.string.error_get_web_content, baseUrl) appCtx.getString(R.string.error_get_web_content, baseUrl)
) )
Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}") Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}")
val content = StringBuilder() val content = StringBuilder()

@ -1,6 +1,5 @@
package io.legado.app.model.webBook package io.legado.app.model.webBook
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
import io.legado.app.data.entities.BookSource import io.legado.app.data.entities.BookSource
@ -12,6 +11,7 @@ import io.legado.app.utils.StringUtils.wordCountFormat
import io.legado.app.utils.htmlFormat import io.legado.app.utils.htmlFormat
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ensureActive import kotlinx.coroutines.ensureActive
import splitties.init.appCtx
object BookInfo { object BookInfo {
@ -25,7 +25,7 @@ object BookInfo {
canReName: Boolean, canReName: Boolean,
) { ) {
body ?: throw Exception( body ?: throw Exception(
App.INSTANCE.getString(R.string.error_get_web_content, baseUrl) appCtx.getString(R.string.error_get_web_content, baseUrl)
) )
Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}") Debug.log(bookSource.bookSourceUrl, "≡获取成功:${baseUrl}")
val infoRule = bookSource.getBookInfoRule() val infoRule = bookSource.getBookInfoRule()

@ -1,6 +1,5 @@
package io.legado.app.model.webBook package io.legado.app.model.webBook
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.data.entities.BookSource import io.legado.app.data.entities.BookSource
import io.legado.app.data.entities.SearchBook import io.legado.app.data.entities.SearchBook
@ -14,6 +13,7 @@ import io.legado.app.utils.StringUtils.wordCountFormat
import io.legado.app.utils.htmlFormat import io.legado.app.utils.htmlFormat
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ensureActive import kotlinx.coroutines.ensureActive
import splitties.init.appCtx
object BookList { object BookList {
@ -29,7 +29,7 @@ object BookList {
): ArrayList<SearchBook> { ): ArrayList<SearchBook> {
val bookList = ArrayList<SearchBook>() val bookList = ArrayList<SearchBook>()
body ?: throw Exception( body ?: throw Exception(
App.INSTANCE.getString( appCtx.getString(
R.string.error_get_web_content, R.string.error_get_web_content,
analyzeUrl.ruleUrl analyzeUrl.ruleUrl
) )

@ -10,6 +10,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.ExecutorCoroutineDispatcher import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher
import splitties.init.appCtx
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlin.math.min import kotlin.math.min
@ -44,7 +45,7 @@ class SearchBookModel(private val scope: CoroutineScope, private val callBack: C
initSearchPool() initSearchPool()
mSearchId = searchId mSearchId = searchId
searchPage = 1 searchPage = 1
val searchGroup = App.INSTANCE.getPrefString("searchGroup") ?: "" val searchGroup = appCtx.getPrefString("searchGroup") ?: ""
bookSourceList.clear() bookSourceList.clear()
if (searchGroup.isBlank()) { if (searchGroup.isBlank()) {
bookSourceList.addAll(App.db.bookSourceDao.allEnabled) bookSourceList.addAll(App.db.bookSourceDao.allEnabled)

@ -35,6 +35,7 @@ import io.legado.app.utils.toastOnUi
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.init.appCtx
class AudioPlayService : BaseService(), class AudioPlayService : BaseService(),
@ -370,7 +371,7 @@ class AudioPlayService : BaseService(),
Intent( Intent(
Intent.ACTION_MEDIA_BUTTON, Intent.ACTION_MEDIA_BUTTON,
null, null,
App.INSTANCE, appCtx,
MediaButtonReceiver::class.java MediaButtonReceiver::class.java
), ),
PendingIntent.FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT

@ -14,7 +14,6 @@ import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat import android.support.v4.media.session.PlaybackStateCompat
import androidx.annotation.CallSuper import androidx.annotation.CallSuper
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseService import io.legado.app.base.BaseService
import io.legado.app.constant.* import io.legado.app.constant.*
@ -27,6 +26,7 @@ import io.legado.app.ui.book.read.ReadBookActivity
import io.legado.app.ui.book.read.page.entities.TextChapter import io.legado.app.ui.book.read.page.entities.TextChapter
import io.legado.app.utils.getPrefBoolean import io.legado.app.utils.getPrefBoolean
import io.legado.app.utils.postEvent import io.legado.app.utils.postEvent
import splitties.init.appCtx
abstract class BaseReadAloudService : BaseService(), abstract class BaseReadAloudService : BaseService(),
AudioManager.OnAudioFocusChangeListener { AudioManager.OnAudioFocusChangeListener {
@ -233,7 +233,7 @@ abstract class BaseReadAloudService : BaseService(),
Intent( Intent(
Intent.ACTION_MEDIA_BUTTON, Intent.ACTION_MEDIA_BUTTON,
null, null,
App.INSTANCE, appCtx,
MediaButtonReceiver::class.java MediaButtonReceiver::class.java
), ),
PendingIntent.FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT

@ -23,6 +23,7 @@ import io.legado.app.utils.postEvent
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import splitties.init.appCtx
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.Executors import java.util.concurrent.Executors
@ -43,7 +44,7 @@ class CacheBookService : BaseService() {
@Volatile @Volatile
private var downloadingCount = 0 private var downloadingCount = 0
private var notificationContent = App.INSTANCE.getString(R.string.starting_download) private var notificationContent = appCtx.getString(R.string.starting_download)
private val notificationBuilder by lazy { private val notificationBuilder by lazy {
val builder = NotificationCompat.Builder(this, AppConst.channelIdDownload) val builder = NotificationCompat.Builder(this, AppConst.channelIdDownload)

@ -2,7 +2,6 @@ package io.legado.app.service.help
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.IntentAction import io.legado.app.constant.IntentAction
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
@ -11,6 +10,7 @@ import io.legado.app.model.webBook.WebBook
import io.legado.app.service.CacheBookService import io.legado.app.service.CacheBookService
import io.legado.app.utils.msg import io.legado.app.utils.msg
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import splitties.init.appCtx
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
@ -81,7 +81,7 @@ object CacheBook {
ReadBook.contentLoadFinish( ReadBook.contentLoadFinish(
book, book,
chapter, chapter,
content.ifBlank { App.INSTANCE.getString(R.string.content_empty) }, content.ifBlank { appCtx.getString(R.string.content_empty) },
resetPageOffset = resetPageOffset resetPageOffset = resetPageOffset
) )
} }

@ -10,13 +10,14 @@ import io.legado.app.service.BaseReadAloudService
import io.legado.app.service.HttpReadAloudService import io.legado.app.service.HttpReadAloudService
import io.legado.app.service.TTSReadAloudService import io.legado.app.service.TTSReadAloudService
import io.legado.app.utils.getPrefLong import io.legado.app.utils.getPrefLong
import splitties.init.appCtx
object ReadAloud { object ReadAloud {
private var aloudClass: Class<*> = getReadAloudClass() private var aloudClass: Class<*> = getReadAloudClass()
var httpTTS: HttpTTS? = null var httpTTS: HttpTTS? = null
private fun getReadAloudClass(): Class<*> { private fun getReadAloudClass(): Class<*> {
val spId = App.INSTANCE.getPrefLong(PreferKey.speakEngine) val spId = appCtx.getPrefLong(PreferKey.speakEngine)
httpTTS = App.db.httpTTSDao.get(spId) httpTTS = App.db.httpTTSDao.get(spId)
return if (httpTTS != null) { return if (httpTTS != null) {
HttpReadAloudService::class.java HttpReadAloudService::class.java
@ -26,7 +27,7 @@ object ReadAloud {
} }
fun upReadAloudClass() { fun upReadAloudClass() {
stop(App.INSTANCE) stop(appCtx)
aloudClass = getReadAloudClass() aloudClass = getReadAloudClass()
} }

@ -20,6 +20,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import splitties.init.appCtx
@Suppress("MemberVisibilityCanBePrivate") @Suppress("MemberVisibilityCanBePrivate")
@ -215,7 +216,7 @@ object ReadBook {
if (book != null && textChapter != null) { if (book != null && textChapter != null) {
val key = IntentDataHelp.putData(textChapter) val key = IntentDataHelp.putData(textChapter)
ReadAloud.play( ReadAloud.play(
App.INSTANCE, book.name, textChapter.title, durPageIndex(), key, play appCtx, book.name, textChapter.title, durPageIndex(), key, play
) )
} }
} }
@ -437,7 +438,7 @@ object ReadBook {
} }
}.onError { }.onError {
it.printStackTrace() it.printStackTrace()
App.INSTANCE.toastOnUi("ChapterProvider ERROR:\n${it.msg}") appCtx.toastOnUi("ChapterProvider ERROR:\n${it.msg}")
}.onSuccess { }.onSuccess {
success?.invoke() success?.invoke()
} }

@ -13,6 +13,7 @@ import io.legado.app.help.BookHelp
import io.legado.app.help.ContentProcessor import io.legado.app.help.ContentProcessor
import io.legado.app.help.storage.BookWebDav import io.legado.app.help.storage.BookWebDav
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
@ -41,7 +42,7 @@ class CacheViewModel(application: Application) : BaseViewModel(application) {
val content = getAllContents(book) val content = getAllContents(book)
DocumentUtils.createFileIfNotExist(doc, filename) DocumentUtils.createFileIfNotExist(doc, filename)
?.writeText(context, content) ?.writeText(context, content)
if (App.INSTANCE.getPrefBoolean(PreferKey.webDavCacheBackup, false)) { if (appCtx.getPrefBoolean(PreferKey.webDavCacheBackup, false)) {
FileUtils.createFileIfNotExist( FileUtils.createFileIfNotExist(
File(FileUtils.getCachePath()), File(FileUtils.getCachePath()),
filename filename
@ -67,7 +68,7 @@ class CacheViewModel(application: Application) : BaseViewModel(application) {
val filename = "${book.name} by ${book.author}.txt" val filename = "${book.name} by ${book.author}.txt"
FileUtils.createFileIfNotExist(file, filename) FileUtils.createFileIfNotExist(file, filename)
.writeText(getAllContents(book)) .writeText(getAllContents(book))
if (App.INSTANCE.getPrefBoolean(PreferKey.webDavCacheBackup, false)) { if (appCtx.getPrefBoolean(PreferKey.webDavCacheBackup, false)) {
BookWebDav.exportWebDav(file.absolutePath, filename) // 导出到webdav BookWebDav.exportWebDav(file.absolutePath, filename) // 导出到webdav
} }
getSrcList(book).forEach { getSrcList(book).forEach {

@ -20,6 +20,7 @@ import io.legado.app.utils.getPrefString
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.ExecutorCoroutineDispatcher import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher
import splitties.init.appCtx
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.Executors import java.util.concurrent.Executors
@ -37,7 +38,7 @@ class ChangeSourceViewModel(application: Application) : BaseViewModel(applicatio
private val searchBooks = CopyOnWriteArraySet<SearchBook>() private val searchBooks = CopyOnWriteArraySet<SearchBook>()
private var postTime = 0L private var postTime = 0L
private val sendRunnable = Runnable { upAdapter() } private val sendRunnable = Runnable { upAdapter() }
private val searchGroup get() = App.INSTANCE.getPrefString("searchGroup") ?: "" private val searchGroup get() = appCtx.getPrefString("searchGroup") ?: ""
@Volatile @Volatile
private var searchIndex = -1 private var searchIndex = -1

@ -11,12 +11,12 @@ import android.widget.FrameLayout
import android.widget.SeekBar import android.widget.SeekBar
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.core.view.isVisible import androidx.core.view.isVisible
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.databinding.ViewReadMenuBinding import io.legado.app.databinding.ViewReadMenuBinding
import io.legado.app.help.AppConfig import io.legado.app.help.AppConfig
import io.legado.app.help.LocalConfig import io.legado.app.help.LocalConfig
import io.legado.app.help.ThemeConfig
import io.legado.app.lib.theme.* import io.legado.app.lib.theme.*
import io.legado.app.service.help.ReadBook import io.legado.app.service.help.ReadBook
import io.legado.app.ui.widget.seekbar.SeekBarChangeListener import io.legado.app.ui.widget.seekbar.SeekBarChangeListener
@ -189,7 +189,7 @@ class ReadMenu @JvmOverloads constructor(
//夜间模式 //夜间模式
fabNightTheme.setOnClickListener { fabNightTheme.setOnClickListener {
AppConfig.isNightTheme = !AppConfig.isNightTheme AppConfig.isNightTheme = !AppConfig.isNightTheme
App.INSTANCE.applyDayNight() ThemeConfig.applyDayNight(context)
} }
//上一章 //上一章

@ -21,6 +21,7 @@ import io.legado.app.service.help.ReadAloud
import io.legado.app.utils.getPrefLong import io.legado.app.utils.getPrefLong
import io.legado.app.utils.getSize import io.legado.app.utils.getSize
import io.legado.app.utils.postEvent import io.legado.app.utils.postEvent
import splitties.init.appCtx
class ReadAloudConfigDialog : DialogFragment() { class ReadAloudConfigDialog : DialogFragment() {
private val readAloudPreferTag = "readAloudPreferTag" private val readAloudPreferTag = "readAloudPreferTag"
@ -60,7 +61,7 @@ class ReadAloudConfigDialog : DialogFragment() {
private val speakEngineSummary: String private val speakEngineSummary: String
get() { get() {
val eid = App.INSTANCE.getPrefLong(PreferKey.speakEngine) val eid = appCtx.getPrefLong(PreferKey.speakEngine)
val ht = App.db.httpTTSDao.get(eid) val ht = App.db.httpTTSDao.get(eid)
return ht?.name ?: getString(R.string.local_tts) return ht?.name ?: getString(R.string.local_tts)
} }

@ -28,6 +28,7 @@ import io.legado.app.service.help.ReadAloud
import io.legado.app.ui.widget.dialog.TextDialog import io.legado.app.ui.widget.dialog.TextDialog
import io.legado.app.utils.* import io.legado.app.utils.*
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import splitties.init.appCtx
class SpeakEngineDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener { class SpeakEngineDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener {
@ -35,7 +36,7 @@ class SpeakEngineDialog : BaseDialogFragment(), Toolbar.OnMenuItemClickListener
lateinit var adapter: Adapter lateinit var adapter: Adapter
private val viewModel: SpeakEngineViewModel by viewModels() private val viewModel: SpeakEngineViewModel by viewModels()
private var httpTTSData: LiveData<List<HttpTTS>>? = null private var httpTTSData: LiveData<List<HttpTTS>>? = null
var engineId = App.INSTANCE.getPrefLong(PreferKey.speakEngine) var engineId = appCtx.getPrefLong(PreferKey.speakEngine)
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()

@ -2,18 +2,18 @@ package io.legado.app.ui.book.read.page.entities
import android.text.Layout import android.text.Layout
import android.text.StaticLayout import android.text.StaticLayout
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.help.ReadBookConfig import io.legado.app.help.ReadBookConfig
import io.legado.app.service.help.ReadBook import io.legado.app.service.help.ReadBook
import io.legado.app.ui.book.read.page.provider.ChapterProvider import io.legado.app.ui.book.read.page.provider.ChapterProvider
import splitties.init.appCtx
import java.text.DecimalFormat import java.text.DecimalFormat
import kotlin.math.min import kotlin.math.min
@Suppress("unused") @Suppress("unused")
data class TextPage( data class TextPage(
var index: Int = 0, var index: Int = 0,
var text: String = App.INSTANCE.getString(R.string.data_loading), var text: String = appCtx.getString(R.string.data_loading),
var title: String = "", var title: String = "",
val textLines: ArrayList<TextLine> = arrayListOf(), val textLines: ArrayList<TextLine> = arrayListOf(),
var pageSize: Int = 0, var pageSize: Int = 0,

@ -6,7 +6,6 @@ import android.os.Build
import android.text.Layout import android.text.Layout
import android.text.StaticLayout import android.text.StaticLayout
import android.text.TextPaint import android.text.TextPaint
import io.legado.app.App
import io.legado.app.constant.AppPattern import io.legado.app.constant.AppPattern
import io.legado.app.constant.EventBus import io.legado.app.constant.EventBus
import io.legado.app.data.entities.Book import io.legado.app.data.entities.Book
@ -19,6 +18,7 @@ import io.legado.app.ui.book.read.page.entities.TextChar
import io.legado.app.ui.book.read.page.entities.TextLine import io.legado.app.ui.book.read.page.entities.TextLine
import io.legado.app.ui.book.read.page.entities.TextPage import io.legado.app.ui.book.read.page.entities.TextPage
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.util.* import java.util.*
@ -355,13 +355,13 @@ object ChapterProvider {
return kotlin.runCatching { return kotlin.runCatching {
when { when {
fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> { fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
val fd = App.INSTANCE.contentResolver val fd = appCtx.contentResolver
.openFileDescriptor(Uri.parse(fontPath), "r")!! .openFileDescriptor(Uri.parse(fontPath), "r")!!
.fileDescriptor .fileDescriptor
Typeface.Builder(fd).build() Typeface.Builder(fd).build()
} }
fontPath.isContentScheme() -> { fontPath.isContentScheme() -> {
Typeface.createFromFile(RealPathUtil.getPath(App.INSTANCE, Uri.parse(fontPath))) Typeface.createFromFile(RealPathUtil.getPath(appCtx, Uri.parse(fontPath)))
} }
fontPath.isNotEmpty() -> Typeface.createFromFile(fontPath) fontPath.isNotEmpty() -> Typeface.createFromFile(fontPath)
else -> when (AppConfig.systemTypefaces) { else -> when (AppConfig.systemTypefaces) {

@ -5,7 +5,6 @@ import android.content.Intent
import android.net.Uri import android.net.Uri
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.help.AppConfig import io.legado.app.help.AppConfig
@ -22,6 +21,7 @@ import io.legado.app.utils.isContentScheme
import io.legado.app.utils.longToast import io.legado.app.utils.longToast
import io.legado.app.utils.toastOnUi import io.legado.app.utils.toastOnUi
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import splitties.init.appCtx
object BackupRestoreUi { object BackupRestoreUi {
private const val selectFolderRequestCode = 21 private const val selectFolderRequestCode = 21
@ -125,24 +125,24 @@ object BackupRestoreUi {
backupSelectRequestCode -> if (resultCode == RESULT_OK) { backupSelectRequestCode -> if (resultCode == RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
if (uri.isContentScheme()) { if (uri.isContentScheme()) {
App.INSTANCE.contentResolver.takePersistableUriPermission( appCtx.contentResolver.takePersistableUriPermission(
uri, uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
) )
AppConfig.backupPath = uri.toString() AppConfig.backupPath = uri.toString()
Coroutine.async { Coroutine.async {
Backup.backup(App.INSTANCE, uri.toString()) Backup.backup(appCtx, uri.toString())
}.onSuccess { }.onSuccess {
App.INSTANCE.toastOnUi(R.string.backup_success) appCtx.toastOnUi(R.string.backup_success)
} }
} else { } else {
uri.path?.let { path -> uri.path?.let { path ->
AppConfig.backupPath = path AppConfig.backupPath = path
Coroutine.async { Coroutine.async {
Backup.backup(App.INSTANCE, path) Backup.backup(appCtx, path)
}.onSuccess { }.onSuccess {
App.INSTANCE.toastOnUi(R.string.backup_success) appCtx.toastOnUi(R.string.backup_success)
} }
} }
} }
@ -151,20 +151,20 @@ object BackupRestoreUi {
restoreSelectRequestCode -> if (resultCode == RESULT_OK) { restoreSelectRequestCode -> if (resultCode == RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
if (uri.isContentScheme()) { if (uri.isContentScheme()) {
App.INSTANCE.contentResolver.takePersistableUriPermission( appCtx.contentResolver.takePersistableUriPermission(
uri, uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
) )
AppConfig.backupPath = uri.toString() AppConfig.backupPath = uri.toString()
Coroutine.async { Coroutine.async {
Restore.restore(App.INSTANCE, uri.toString()) Restore.restore(appCtx, uri.toString())
} }
} else { } else {
uri.path?.let { path -> uri.path?.let { path ->
AppConfig.backupPath = path AppConfig.backupPath = path
Coroutine.async { Coroutine.async {
Restore.restore(App.INSTANCE, path) Restore.restore(appCtx, path)
} }
} }
} }
@ -173,7 +173,7 @@ object BackupRestoreUi {
selectFolderRequestCode -> if (resultCode == RESULT_OK) { selectFolderRequestCode -> if (resultCode == RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
if (uri.isContentScheme()) { if (uri.isContentScheme()) {
App.INSTANCE.contentResolver.takePersistableUriPermission( appCtx.contentResolver.takePersistableUriPermission(
uri, uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
@ -186,7 +186,7 @@ object BackupRestoreUi {
} }
oldDataRequestCode -> if (resultCode == RESULT_OK) { oldDataRequestCode -> if (resultCode == RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
ImportOldData.importUri(App.INSTANCE, uri) ImportOldData.importUri(appCtx, uri)
} }
} }
} }

@ -13,7 +13,6 @@ import android.view.View
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.preference.ListPreference import androidx.preference.ListPreference
import androidx.preference.Preference import androidx.preference.Preference
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BasePreferenceFragment import io.legado.app.base.BasePreferenceFragment
import io.legado.app.constant.EventBus import io.legado.app.constant.EventBus
@ -32,6 +31,7 @@ import io.legado.app.ui.main.MainActivity
import io.legado.app.ui.widget.image.CoverImageView import io.legado.app.ui.widget.image.CoverImageView
import io.legado.app.ui.widget.number.NumberPickerDialog import io.legado.app.ui.widget.number.NumberPickerDialog
import io.legado.app.utils.* import io.legado.app.utils.*
import splitties.init.appCtx
import java.io.File import java.io.File
@ -40,9 +40,9 @@ class OtherConfigFragment : BasePreferenceFragment(),
private val requestCodeCover = 231 private val requestCodeCover = 231
private val packageManager = App.INSTANCE.packageManager private val packageManager = appCtx.packageManager
private val componentName = ComponentName( private val componentName = ComponentName(
App.INSTANCE, appCtx,
SharedReceiverActivity::class.java.name SharedReceiverActivity::class.java.name
) )
private val webPort get() = getPrefInt(PreferKey.webPort, 1122) private val webPort get() = getPrefInt(PreferKey.webPort, 1122)
@ -124,10 +124,10 @@ class OtherConfigFragment : BasePreferenceFragment(),
key, getPrefString(PreferKey.defaultCover) key, getPrefString(PreferKey.defaultCover)
) )
PreferKey.language -> listView.postDelayed({ PreferKey.language -> listView.postDelayed({
LanguageUtils.setConfiguration(App.INSTANCE) LanguageUtils.setConfiguration(appCtx)
val intent = Intent(App.INSTANCE, MainActivity::class.java) val intent = Intent(appCtx, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
App.INSTANCE.startActivity(intent) appCtx.startActivity(intent)
Process.killProcess(Process.myPid()) Process.killProcess(Process.myPid())
}, 1000) }, 1000)
PreferKey.userAgent -> listView.post { PreferKey.userAgent -> listView.post {

@ -13,7 +13,6 @@ import android.view.MenuItem
import android.view.View import android.view.View
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.preference.Preference import androidx.preference.Preference
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BasePreferenceFragment import io.legado.app.base.BasePreferenceFragment
import io.legado.app.constant.AppConst import io.legado.app.constant.AppConst
@ -140,7 +139,7 @@ class ThemeConfigFragment : BasePreferenceFragment(),
when (item.itemId) { when (item.itemId) {
R.id.menu_theme_mode -> { R.id.menu_theme_mode -> {
AppConfig.isNightTheme = !AppConfig.isNightTheme AppConfig.isNightTheme = !AppConfig.isNightTheme
App.INSTANCE.applyDayNight() ThemeConfig.applyDayNight(requireContext())
} }
} }
return super.onOptionsItemSelected(item) return super.onOptionsItemSelected(item)

@ -7,7 +7,6 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.view.View import android.view.View
import androidx.preference.Preference import androidx.preference.Preference
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseFragment import io.legado.app.base.BaseFragment
import io.legado.app.base.BasePreferenceFragment import io.legado.app.base.BasePreferenceFragment
@ -15,6 +14,7 @@ import io.legado.app.constant.EventBus
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.databinding.FragmentMyConfigBinding import io.legado.app.databinding.FragmentMyConfigBinding
import io.legado.app.help.AppConfig import io.legado.app.help.AppConfig
import io.legado.app.help.ThemeConfig
import io.legado.app.lib.theme.ATH import io.legado.app.lib.theme.ATH
import io.legado.app.service.WebService import io.legado.app.service.WebService
import io.legado.app.ui.about.AboutActivity import io.legado.app.ui.about.AboutActivity
@ -90,7 +90,7 @@ class MyFragment : BaseFragment(R.layout.fragment_my_config), FilePickerDialog.C
} }
findPreference<NameListPreference>(PreferKey.themeMode)?.let { findPreference<NameListPreference>(PreferKey.themeMode)?.let {
it.setOnPreferenceChangeListener { _, _ -> it.setOnPreferenceChangeListener { _, _ ->
view?.post { App.INSTANCE.applyDayNight() } view?.post { ThemeConfig.applyDayNight(requireContext()) }
true true
} }
} }

@ -11,7 +11,6 @@ import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.documentfile.provider.DocumentFile import androidx.documentfile.provider.DocumentFile
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.base.BaseDialogFragment import io.legado.app.base.BaseDialogFragment
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
@ -27,6 +26,7 @@ import io.legado.app.utils.*
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import splitties.init.appCtx
import java.io.File import java.io.File
import java.util.* import java.util.*
import kotlin.collections.ArrayList import kotlin.collections.ArrayList
@ -38,7 +38,7 @@ class FontSelectDialog : BaseDialogFragment(),
private val fontFolderRequestCode = 35485 private val fontFolderRequestCode = 35485
private val fontRegex = Regex(".*\\.[ot]tf") private val fontRegex = Regex(".*\\.[ot]tf")
private val fontFolder by lazy { private val fontFolder by lazy {
FileUtils.createFolderIfNotExist(App.INSTANCE.filesDir, "Fonts") FileUtils.createFolderIfNotExist(appCtx.filesDir, "Fonts")
} }
private var adapter: FontAdapter? = null private var adapter: FontAdapter? = null
private val binding by viewBinding(DialogFontSelectBinding::bind) private val binding by viewBinding(DialogFontSelectBinding::bind)
@ -147,7 +147,7 @@ class FontSelectDialog : BaseDialogFragment(),
private fun loadFontFiles(doc: DocumentFile) { private fun loadFontFiles(doc: DocumentFile) {
execute { execute {
val fontItems = arrayListOf<DocItem>() val fontItems = arrayListOf<DocItem>()
val docItems = DocumentUtils.listFiles(App.INSTANCE, doc.uri) val docItems = DocumentUtils.listFiles(appCtx, doc.uri)
docItems.forEach { item -> docItems.forEach { item ->
if (item.name.toLowerCase(Locale.getDefault()).matches(fontRegex)) { if (item.name.toLowerCase(Locale.getDefault()).matches(fontRegex)) {
fontItems.add(item) fontItems.add(item)

@ -10,11 +10,11 @@ import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.target.Target
import io.legado.app.App
import io.legado.app.R import io.legado.app.R
import io.legado.app.constant.PreferKey import io.legado.app.constant.PreferKey
import io.legado.app.help.ImageLoader import io.legado.app.help.ImageLoader
import io.legado.app.utils.getPrefString import io.legado.app.utils.getPrefString
import splitties.init.appCtx
/** /**
* 封面 * 封面
@ -172,11 +172,11 @@ class CoverImageView @JvmOverloads constructor(
@SuppressLint("UseCompatLoadingForDrawables") @SuppressLint("UseCompatLoadingForDrawables")
fun upDefaultCover() { fun upDefaultCover() {
val path = App.INSTANCE.getPrefString(PreferKey.defaultCover) val path = appCtx.getPrefString(PreferKey.defaultCover)
var dw = Drawable.createFromPath(path) var dw = Drawable.createFromPath(path)
if (dw == null) { if (dw == null) {
showBookName = true showBookName = true
dw = App.INSTANCE.resources.getDrawable(R.drawable.image_cover_default, null) dw = appCtx.resources.getDrawable(R.drawable.image_cover_default, null)
} else { } else {
showBookName = false showBookName = false
} }

@ -9,9 +9,9 @@ import android.graphics.PixelFormat
import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import android.util.Log import android.util.Log
import io.legado.app.App
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import splitties.init.appCtx
import java.io.* import java.io.*
import java.util.* import java.util.*
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
@ -619,7 +619,7 @@ class ACache private constructor(cacheDir: File, max_size: Long, max_count: Int)
fun bitmap2Drawable(bm: Bitmap?): Drawable? { fun bitmap2Drawable(bm: Bitmap?): Drawable? {
return if (bm == null) { return if (bm == null) {
null null
} else BitmapDrawable(App.INSTANCE.resources, bm) } else BitmapDrawable(appCtx.resources, bm)
} }
} }

@ -8,7 +8,7 @@ import android.renderscript.Element
import android.renderscript.RenderScript import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur import android.renderscript.ScriptIntrinsicBlur
import android.view.View import android.view.View
import io.legado.app.App import splitties.init.appCtx
import java.io.IOException import java.io.IOException
import kotlin.math.* import kotlin.math.*
@ -247,7 +247,7 @@ object BitmapUtils {
*/ */
fun stackBlur(srcBitmap: Bitmap?): Bitmap? { fun stackBlur(srcBitmap: Bitmap?): Bitmap? {
if (srcBitmap == null) return null if (srcBitmap == null) return null
val rs = RenderScript.create(App.INSTANCE) val rs = RenderScript.create(appCtx)
val blurredBitmap = srcBitmap.copy(Config.ARGB_8888, true) val blurredBitmap = srcBitmap.copy(Config.ARGB_8888, true)
//分配用于渲染脚本的内存 //分配用于渲染脚本的内存

@ -3,8 +3,8 @@ package io.legado.app.utils
import android.os.Environment import android.os.Environment
import android.webkit.MimeTypeMap import android.webkit.MimeTypeMap
import androidx.annotation.IntDef import androidx.annotation.IntDef
import io.legado.app.App
import io.legado.app.ui.filepicker.utils.ConvertUtils import io.legado.app.ui.filepicker.utils.ConvertUtils
import splitties.init.appCtx
import java.io.* import java.io.*
import java.nio.charset.Charset import java.nio.charset.Charset
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
@ -105,8 +105,8 @@ object FileUtils {
} }
fun getCachePath(): String { fun getCachePath(): String {
return App.INSTANCE.externalCacheDir?.absolutePath return appCtx.externalCacheDir?.absolutePath
?: App.INSTANCE.cacheDir.absolutePath ?: appCtx.cacheDir.absolutePath
} }
fun getSdCardPath(): String { fun getSdCardPath(): String {

@ -1,11 +1,10 @@
package io.legado.app.utils package io.legado.app.utils
import android.annotation.SuppressLint import android.annotation.SuppressLint
import io.legado.app.App import splitties.init.appCtx
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
import java.util.logging.* import java.util.logging.*
import java.util.logging.Formatter
@Suppress("unused") @Suppress("unused")
object LogUtils { object LogUtils {
@ -30,7 +29,7 @@ object LogUtils {
} }
private val fileHandler by lazy { private val fileHandler by lazy {
val root = App.INSTANCE.externalCacheDir ?: return@lazy null val root = appCtx.externalCacheDir ?: return@lazy null
val logFolder = FileUtils.createFolderIfNotExist(root, "logs") val logFolder = FileUtils.createFolderIfNotExist(root, "logs")
val logPath = FileUtils.getPath(root = logFolder, "appLog") val logPath = FileUtils.getPath(root = logFolder, "appLog")
FileHandler(logPath, 10240, 10).apply { FileHandler(logPath, 10240, 10).apply {
@ -40,7 +39,7 @@ object LogUtils {
return (getCurrentDateStr(TIME_PATTERN) + ": " + record.message + "\n") return (getCurrentDateStr(TIME_PATTERN) + ": " + record.message + "\n")
} }
} }
level = if (App.INSTANCE.getPrefBoolean("recordLog")) { level = if (appCtx.getPrefBoolean("recordLog")) {
Level.INFO Level.INFO
} else { } else {
Level.OFF Level.OFF
@ -49,7 +48,7 @@ object LogUtils {
} }
fun upLevel() { fun upLevel() {
fileHandler?.level = if (App.INSTANCE.getPrefBoolean("recordLog")) { fileHandler?.level = if (appCtx.getPrefBoolean("recordLog")) {
Level.INFO Level.INFO
} else { } else {
Level.OFF Level.OFF

@ -14,7 +14,7 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuPopupHelper import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.PopupMenu
import androidx.core.view.get import androidx.core.view.get
import io.legado.app.App import splitties.init.appCtx
import java.lang.reflect.Field import java.lang.reflect.Field
@ -31,7 +31,7 @@ val View.activity: AppCompatActivity?
get() = getCompatActivity(context) get() = getCompatActivity(context)
fun View.hideSoftInput() = run { fun View.hideSoftInput() = run {
val imm = App.INSTANCE.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager val imm = appCtx.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.let { imm?.let {
imm.hideSoftInputFromWindow(this.windowToken, 0) imm.hideSoftInputFromWindow(this.windowToken, 0)
} }

@ -13,6 +13,7 @@ import io.legado.app.utils.fromJsonObject
import io.legado.app.utils.isJson import io.legado.app.utils.isJson
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import splitties.init.appCtx
import java.io.IOException import java.io.IOException
@ -54,7 +55,7 @@ class SourceDebugWebSocket(handshakeRequest: NanoHTTPD.IHTTPSession) :
val tag = debugBean["tag"] val tag = debugBean["tag"]
val key = debugBean["key"] val key = debugBean["key"]
if (tag.isNullOrBlank() || key.isNullOrBlank()) { if (tag.isNullOrBlank() || key.isNullOrBlank()) {
send(App.INSTANCE.getString(R.string.cannot_empty)) send(appCtx.getString(R.string.cannot_empty))
close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false) close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
return@launch return@launch
} }

@ -3,13 +3,13 @@ package io.legado.app.web.utils
import android.content.res.AssetManager import android.content.res.AssetManager
import android.text.TextUtils import android.text.TextUtils
import fi.iki.elonen.NanoHTTPD import fi.iki.elonen.NanoHTTPD
import io.legado.app.App import splitties.init.appCtx
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
class AssetsWeb(rootPath: String) { class AssetsWeb(rootPath: String) {
private val assetManager: AssetManager = App.INSTANCE.assets private val assetManager: AssetManager = appCtx.assets
private var rootPath = "web" private var rootPath = "web"
init { init {

Loading…
Cancel
Save