fix: 优化代码

This commit is contained in:
Yaoliang
2024-07-10 09:28:10 +08:00
parent ddca205446
commit 14e0c37ccf
25 changed files with 66 additions and 62 deletions
@@ -16,12 +16,10 @@ import io.legado.app.help.book.BookHelp
import io.legado.app.help.book.ContentProcessor import io.legado.app.help.book.ContentProcessor
import io.legado.app.help.book.isEpub import io.legado.app.help.book.isEpub
import io.legado.app.help.book.isImage import io.legado.app.help.book.isImage
import io.legado.app.help.book.isLocal
import io.legado.app.help.book.isPdf import io.legado.app.help.book.isPdf
import io.legado.app.help.config.AppConfig import io.legado.app.help.config.AppConfig
import io.legado.app.help.config.ReadBookConfig import io.legado.app.help.config.ReadBookConfig
import io.legado.app.model.ReadBook import io.legado.app.model.ReadBook
import io.legado.app.model.localBook.LocalBook
import io.legado.app.utils.GSON import io.legado.app.utils.GSON
import io.legado.app.utils.MD5Utils import io.legado.app.utils.MD5Utils
import io.legado.app.utils.fromJsonObject import io.legado.app.utils.fromJsonObject
@@ -30,7 +28,6 @@ import kotlinx.parcelize.Parcelize
import java.nio.charset.Charset import java.nio.charset.Charset
import java.time.LocalDate import java.time.LocalDate
import java.time.Period.between import java.time.Period.between
import java.time.chrono.Chronology
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@@ -170,14 +167,14 @@ data class Book(
val daysPassed = between(this.config.startDate, currentDate).days + 1 val daysPassed = between(this.config.startDate, currentDate).days + 1
// 计算当前应该解锁到哪一章 // 计算当前应该解锁到哪一章
val chaptersToUnlock = (config.startChapter?:0) + (daysPassed * config.dailyChapters) val chaptersToUnlock = (config.startChapter ?: 0) + (daysPassed * config.dailyChapters)
return min(this.totalChapterNum, chaptersToUnlock); return chaptersToUnlock
} else return this.totalChapterNum; } else return this.totalChapterNum
} }
fun getRealAuthor() = author.replace(AppPattern.authorRegex, "") fun getRealAuthor() = author.replace(AppPattern.authorRegex, "")
fun getUnreadChapterNum() = max(simulatedTotalChapterNum() - durChapterIndex - 1, 0) fun getUnreadChapterNum() = max(totalChapterNum - durChapterIndex - 1, 0)
fun getDisplayCover() = if (customCoverUrl.isNullOrEmpty()) coverUrl else customCoverUrl fun getDisplayCover() = if (customCoverUrl.isNullOrEmpty()) coverUrl else customCoverUrl
@@ -299,7 +296,7 @@ data class Book(
} }
fun getStartChapter(): Int { fun getStartChapter(): Int {
if(config.readSimulating) return config.startChapter?:0 if (config.readSimulating) return config.startChapter ?: 0
return this.durChapterIndex return this.durChapterIndex
} }
@@ -165,7 +165,7 @@ object AudioPlay {
fun next(context: Context) { fun next(context: Context) {
book?.let { book -> book?.let { book ->
if (book.durChapterIndex + 1 < book.simulatedTotalChapterNum()) { if (book.durChapterIndex + 1 < book.totalChapterNum) {
book.durChapterIndex += 1 book.durChapterIndex += 1
book.durChapterPos = 0 book.durChapterPos = 0
durChapterIndex = book.durChapterIndex durChapterIndex = book.durChapterIndex
@@ -151,7 +151,7 @@ object ReadBook : CoroutineScope by MainScope() {
fun setProgress(progress: BookProgress) { fun setProgress(progress: BookProgress) {
if (progress.durChapterIndex < chapterSize && if (progress.durChapterIndex < chapterSize &&
(durChapterIndex != progress.durChapterIndex (durChapterIndex != progress.durChapterIndex
|| durChapterPos != progress.durChapterPos) || durChapterPos != progress.durChapterPos)
) { ) {
durChapterIndex = progress.durChapterIndex durChapterIndex = progress.durChapterIndex
durChapterPos = progress.durChapterPos durChapterPos = progress.durChapterPos
@@ -229,7 +229,7 @@ object ReadBook : CoroutineScope by MainScope() {
} }
fun moveToNextChapter(upContent: Boolean, upContentInPlace: Boolean = true): Boolean { fun moveToNextChapter(upContent: Boolean, upContentInPlace: Boolean = true): Boolean {
if (durChapterIndex < (book?.simulatedTotalChapterNum()?: chapterSize) - 1) { if (durChapterIndex < chapterSize - 1) {
durChapterPos = 0 durChapterPos = 0
durChapterIndex++ durChapterIndex++
prevTextChapter?.cancelLayout() prevTextChapter?.cancelLayout()
@@ -576,7 +576,7 @@ object ReadBook : CoroutineScope by MainScope() {
prevTextChapter?.cancelLayout() prevTextChapter?.cancelLayout()
prevTextChapter = textChapter prevTextChapter = textChapter
textChapter.layoutChannel.receiveAsFlow().collect() textChapter.layoutChannel.receiveAsFlow().collect()
if (upContent) callBack?.upContent(offset, resetPageOffset) else TODO() if (upContent) callBack?.upContent(offset, resetPageOffset)
} }
1 -> { 1 -> {
@@ -589,9 +589,10 @@ object ReadBook : CoroutineScope by MainScope() {
if (upContent) callBack?.upContent(offset, resetPageOffset) if (upContent) callBack?.upContent(offset, resetPageOffset)
} }
} }
else -> {TODO()}
} }
// put a log to avoid Kotlin K2 compiler take "when" as a return statement
AppLog.putDebug("contentLoadFinish done")
}.onError { }.onError {
AppLog.put("ChapterProvider ERROR", it) AppLog.put("ChapterProvider ERROR", it)
appCtx.toastOnUi("ChapterProvider ERROR:\n${it.stackTraceStr}") appCtx.toastOnUi("ChapterProvider ERROR:\n${it.stackTraceStr}")
@@ -113,16 +113,18 @@ object BookChapterList {
if (chapterList.isEmpty()) { if (chapterList.isEmpty()) {
throw TocEmptyException(appCtx.getString(R.string.chapter_list_empty)) throw TocEmptyException(appCtx.getString(R.string.chapter_list_empty))
} }
//去重
if (!reverse) { if (!reverse) {
chapterList.reverse() chapterList.reverse()
} }
coroutineContext.ensureActive() coroutineContext.ensureActive()
//去重
val lh = LinkedHashSet(chapterList) val lh = LinkedHashSet(chapterList)
val list = ArrayList(lh) val fullList = ArrayList(lh)
if (!book.getReverseToc()) { if (!book.getReverseToc()) {
list.reverse() fullList.reverse()
} }
val list =
if (book.getReadSimulating()) fullList.take(book.simulatedTotalChapterNum()) else fullList
Debug.log(book.origin, "◇目录总数:${list.size}") Debug.log(book.origin, "◇目录总数:${list.size}")
coroutineContext.ensureActive() coroutineContext.ensureActive()
val formatJs = tocRule.formatJs val formatJs = tocRule.formatJs
@@ -145,8 +147,7 @@ object BookChapterList {
} }
val replaceRules = ContentProcessor.get(book.name, book.origin).getTitleReplaceRules() val replaceRules = ContentProcessor.get(book.name, book.origin).getTitleReplaceRules()
book.latestChapterTitle = book.latestChapterTitle =
list.getOrElse(book.simulatedTotalChapterNum() - 1) { list.last().getDisplayTitle(replaceRules, book.getUseReplaceRule())
list.last() }.getDisplayTitle(replaceRules, book.getUseReplaceRule())
book.durChapterTitle = list.getOrElse(book.durChapterIndex) { list.last() } book.durChapterTitle = list.getOrElse(book.durChapterIndex) { list.last() }
.getDisplayTitle(replaceRules, book.getUseReplaceRule()) .getDisplayTitle(replaceRules, book.getUseReplaceRule())
if (book.totalChapterNum < list.size) { if (book.totalChapterNum < list.size) {
@@ -36,13 +36,21 @@ import io.legado.app.ui.book.source.edit.BookSourceEditActivity
import io.legado.app.ui.book.toc.TocActivityResult import io.legado.app.ui.book.toc.TocActivityResult
import io.legado.app.ui.login.SourceLoginActivity import io.legado.app.ui.login.SourceLoginActivity
import io.legado.app.ui.widget.seekbar.SeekBarChangeListener import io.legado.app.ui.widget.seekbar.SeekBarChangeListener
import io.legado.app.utils.* import io.legado.app.utils.StartActivityContract
import io.legado.app.utils.dpToPx
import io.legado.app.utils.invisible
import io.legado.app.utils.observeEvent
import io.legado.app.utils.observeEventSticky
import io.legado.app.utils.sendToClip
import io.legado.app.utils.showDialogFragment
import io.legado.app.utils.startActivity
import io.legado.app.utils.viewbindingdelegate.viewBinding import io.legado.app.utils.viewbindingdelegate.viewBinding
import io.legado.app.utils.visible
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import splitties.views.onLongClick import splitties.views.onLongClick
import java.util.* import java.util.Locale
/** /**
* 音频播放 * 音频播放
@@ -258,7 +266,7 @@ class AudioPlayActivity :
binding.tvSubTitle.text = it binding.tvSubTitle.text = it
AudioPlay.book?.let { book -> AudioPlay.book?.let { book ->
binding.ivSkipPrevious.isEnabled = book.durChapterIndex > 0 binding.ivSkipPrevious.isEnabled = book.durChapterIndex > 0
binding.ivSkipNext.isEnabled = book.durChapterIndex < book.simulatedTotalChapterNum() - 1 binding.ivSkipNext.isEnabled = book.durChapterIndex < book.totalChapterNum - 1
} }
} }
observeEventSticky<Int>(EventBus.AUDIO_SIZE) { observeEventSticky<Int>(EventBus.AUDIO_SIZE) {
@@ -251,7 +251,7 @@ class BookInfoViewModel(application: Application) : BaseViewModel(application) {
appDb.bookChapterDao.insert(*it.toTypedArray()) appDb.bookChapterDao.insert(*it.toTypedArray())
if (book.isSameNameAuthor(ReadBook.book)) { if (book.isSameNameAuthor(ReadBook.book)) {
ReadBook.book = book ReadBook.book = book
ReadBook.chapterSize = book.simulatedTotalChapterNum() ReadBook.chapterSize = book.totalChapterNum
} }
} }
bookData.postValue(book) bookData.postValue(book)
@@ -61,6 +61,8 @@ abstract class BaseReadBookActivity :
override val binding by viewBinding(ActivityBookReadBinding::inflate) override val binding by viewBinding(ActivityBookReadBinding::inflate)
override val viewModel by viewModels<ReadBookViewModel>() override val viewModel by viewModels<ReadBookViewModel>()
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
var bottomDialog = 0 var bottomDialog = 0
set(value) { set(value) {
if (field != value) { if (field != value) {
@@ -309,7 +311,6 @@ abstract class BaseReadBookActivity :
} }
fun showSimulatedReading() { fun showSimulatedReading() {
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
ReadBook.book?.let { book -> ReadBook.book?.let { book ->
alert(titleResource = R.string.simulated_reading) { alert(titleResource = R.string.simulated_reading) {
val alertBinding = DialogSimulatedReadingBinding.inflate(layoutInflater).apply { val alertBinding = DialogSimulatedReadingBinding.inflate(layoutInflater).apply {
@@ -318,8 +319,8 @@ abstract class BaseReadBookActivity :
editStart.setText(book.getStartChapter().toString()) editStart.setText(book.getStartChapter().toString())
editNum.setText(book.getDailyChapters().toString()) editNum.setText(book.getDailyChapters().toString())
startDate.setText(book.getStartDate()?.format(dateFormatter)) startDate.setText(book.getStartDate()?.format(dateFormatter))
startDate.isFocusable = false; // 设置为false,不允许获得焦点 startDate.isFocusable = false // 设置为false,不允许获得焦点
startDate.isCursorVisible = false; // 不显示光标 startDate.isCursorVisible = false // 不显示光标
startDate.setOnClickListener { startDate.setOnClickListener {
// 获取当前日期 // 获取当前日期
val localStartDate = LocalDate.parse(startDate.text) val localStartDate = LocalDate.parse(startDate.text)
@@ -229,7 +229,6 @@ class ReadBookViewModel(application: Application) : BaseViewModel(application) {
AppLog.put("拉取阅读进度失败《${book.name}\n${it.localizedMessage}", it) AppLog.put("拉取阅读进度失败《${book.name}\n${it.localizedMessage}", it)
}.onSuccess { progress -> }.onSuccess { progress ->
if (progress.durChapterIndex < book.durChapterIndex || if (progress.durChapterIndex < book.durChapterIndex ||
progress.durChapterIndex >= book.simulatedTotalChapterNum() ||
(progress.durChapterIndex == book.durChapterIndex (progress.durChapterIndex == book.durChapterIndex
&& progress.durChapterPos < book.durChapterPos) && progress.durChapterPos < book.durChapterPos)
) { ) {
@@ -708,8 +708,7 @@ class ReadView(context: Context, attrs: AttributeSet) :
} }
override fun hasNextChapter(): Boolean { override fun hasNextChapter(): Boolean {
return ReadBook.durChapterIndex < ((ReadBook.book?.simulatedTotalChapterNum() return ReadBook.durChapterIndex < ReadBook.chapterSize - 1
?: ReadBook.chapterSize) - 1)
} }
override fun hasPrevChapter(): Boolean { override fun hasPrevChapter(): Boolean {
@@ -118,8 +118,7 @@ class ChapterListFragment : VMBaseFragment<TocViewModel>(R.layout.fragment_chapt
lifecycleScope.launch { lifecycleScope.launch {
withContext(IO) { withContext(IO) {
when { when {
searchKey.isNullOrBlank() -> appDb.bookChapterDao.getChapterList( searchKey.isNullOrBlank() -> appDb.bookChapterDao.getChapterList(viewModel.bookUrl)
viewModel.bookUrl).take(book?.simulatedTotalChapterNum()?: Int.MAX_VALUE)
else -> appDb.bookChapterDao.search(viewModel.bookUrl, searchKey) else -> appDb.bookChapterDao.search(viewModel.bookUrl, searchKey)
} }
}.let { }.let {
@@ -192,7 +192,7 @@ class TocActivity : VMBaseActivity<ActivityChapterListBinding, TocViewModel>(),
ReadBook.book?.let { readBook -> ReadBook.book?.let { readBook ->
if (readBook == book) { if (readBook == book) {
ReadBook.book = book ReadBook.book = book
ReadBook.chapterSize = book.simulatedTotalChapterNum() ReadBook.chapterSize = book.totalChapterNum
ReadBook.upMsg(null) ReadBook.upMsg(null)
ReadBook.loadContent(resetPageOffset = true) ReadBook.loadContent(resetPageOffset = true)
} }
@@ -163,7 +163,7 @@ class MainViewModel(application: Application) : BaseViewModel(application) {
appDb.bookChapterDao.insert(*toc.toTypedArray()) appDb.bookChapterDao.insert(*toc.toTypedArray())
if (book.isSameNameAuthor(ReadBook.book)) { if (book.isSameNameAuthor(ReadBook.book)) {
ReadBook.book = book ReadBook.book = book
ReadBook.chapterSize = book.simulatedTotalChapterNum() ReadBook.chapterSize = book.totalChapterNum
} }
addDownload(source, book) addDownload(source, book)
}.onFailure { }.onFailure {
@@ -28,7 +28,6 @@ abstract class BaseBooksAdapter<VB : ViewBinding>(context: Context) :
oldItem.lastCheckCount != newItem.lastCheckCount -> false oldItem.lastCheckCount != newItem.lastCheckCount -> false
oldItem.getDisplayCover() != newItem.getDisplayCover() -> false oldItem.getDisplayCover() != newItem.getDisplayCover() -> false
oldItem.getUnreadChapterNum() != newItem.getUnreadChapterNum() -> false oldItem.getUnreadChapterNum() != newItem.getUnreadChapterNum() -> false
oldItem.getReadSimulating() -> false
else -> true else -> true
} }
} }
@@ -4,7 +4,6 @@
android:id="@+id/ll_content" android:id="@+id/ll_content"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:background="@color/background"
android:gravity="center" android:gravity="center"
android:padding="20dp" android:padding="20dp"
android:orientation="vertical"> android:orientation="vertical">
@@ -12,7 +11,6 @@
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="60dp" android:layout_height="60dp"
android:background="@color/background"
android:gravity="center" android:gravity="center"
android:orientation="horizontal" android:orientation="horizontal"
android:padding="16dp"> android:padding="16dp">
@@ -59,7 +57,6 @@
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="65dp" android:layout_height="65dp"
android:background="@color/background"
android:orientation="horizontal" android:orientation="horizontal"
android:padding="16dp" android:padding="16dp"
android:gravity="start|center_vertical"> android:gravity="start|center_vertical">
@@ -116,20 +113,11 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
android:layout_marginRight="2dp" android:layout_marginRight="2dp"
android:text="@string/start" android:text="@string/start_chapter"
android:textColor="@color/primaryText" android:textColor="@color/primaryText"
android:textSize="16sp" android:textSize="16sp"
tools:ignore="RtlHardcoded" /> tools:ignore="RtlHardcoded" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="5dp"
android:text="@string/chapter"
android:textColor="@color/primaryText"
android:textSize="16sp"
tools:ignore="RtlHardcoded" />
</LinearLayout> </LinearLayout>
<EditText <EditText
+5 -5
View File
@@ -49,11 +49,6 @@
android:title="@string/bookmark_add" android:title="@string/bookmark_add"
app:showAsAction="never" /> app:showAsAction="never" />
<item
android:id="@+id/menu_simulated_reading"
android:title="@string/simulated_reading"
app:showAsAction="never" />
<item <item
android:id="@+id/menu_edit_content" android:id="@+id/menu_edit_content"
android:title="@string/edit_content" android:title="@string/edit_content"
@@ -75,6 +70,11 @@
android:title="@string/reverse_content" android:title="@string/reverse_content"
app:showAsAction="never" /> app:showAsAction="never" />
<item
android:id="@+id/menu_simulated_reading"
android:title="@string/simulated_reading"
app:showAsAction="never" />
<item <item
android:id="@+id/menu_enable_replace" android:id="@+id/menu_enable_replace"
android:checkable="true" android:checkable="true"
@@ -1152,4 +1152,5 @@
<string name="switch_on">Enc/Apag</string> <string name="switch_on">Enc/Apag</string>
<string name="start_from">Comenzar</string> <string name="start_from">Comenzar</string>
<string name="daily_chapters">Cap. al día</string> <string name="daily_chapters">Cap. al día</string>
<string name="start_chapter">Cap. inicio</string>
</resources> </resources>
@@ -1155,4 +1155,5 @@
<string name="switch_on">スイッチ</string> <string name="switch_on">スイッチ</string>
<string name="start_from">開始日</string> <string name="start_from">開始日</string>
<string name="daily_chapters">日更の章数</string> <string name="daily_chapters">日更の章数</string>
<string name="start_chapter">開始の章</string>
</resources> </resources>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="start_chapter">Start Chapter</string>
</resources>
@@ -1155,4 +1155,5 @@
<string name="switch_on">Lig/Desl</string> <string name="switch_on">Lig/Desl</string>
<string name="start_from">Começar</string> <string name="start_from">Começar</string>
<string name="daily_chapters">Cap. por dia</string> <string name="daily_chapters">Cap. por dia</string>
<string name="start_chapter">Início</string>
</resources> </resources>
+1
View File
@@ -1151,4 +1151,5 @@ Còn </string>
<string name="switch_on">Bật</string> <string name="switch_on">Bật</string>
<string name="start_from">Bắt đầu</string> <string name="start_from">Bắt đầu</string>
<string name="daily_chapters">Chương/ngày</string> <string name="daily_chapters">Chương/ngày</string>
<string name="start_chapter">Chương đầu</string>
</resources> </resources>
@@ -1152,4 +1152,5 @@
<string name="switch_on">開關</string> <string name="switch_on">開關</string>
<string name="start_from">起始日期</string> <string name="start_from">起始日期</string>
<string name="daily_chapters">日更章數</string> <string name="daily_chapters">日更章數</string>
<string name="start_chapter">開始篇章</string>
</resources> </resources>
@@ -1154,4 +1154,5 @@
<string name="switch_on">開關</string> <string name="switch_on">開關</string>
<string name="start_from">起始日期</string> <string name="start_from">起始日期</string>
<string name="daily_chapters">日更章數</string> <string name="daily_chapters">日更章數</string>
<string name="start_chapter">開始篇章</string>
</resources> </resources>
+1
View File
@@ -1154,4 +1154,5 @@
<string name="switch_on">开关</string> <string name="switch_on">开关</string>
<string name="start_from">开始日期</string> <string name="start_from">开始日期</string>
<string name="daily_chapters">日更章数</string> <string name="daily_chapters">日更章数</string>
<string name="start_chapter">起始章节</string>
</resources> </resources>
+1
View File
@@ -1155,4 +1155,5 @@
<string name="switch_on">Switch</string> <string name="switch_on">Switch</string>
<string name="start_from">Start from</string> <string name="start_from">Start from</string>
<string name="daily_chapters">Daily Chapters</string> <string name="daily_chapters">Daily Chapters</string>
<string name="start_chapter">Start Chapter</string>
</resources> </resources>