diff --git a/app/src/main/java/eu/kanade/tachiyomi/App.kt b/app/src/main/java/eu/kanade/tachiyomi/App.kt index 7f35adea30..d85f9ead74 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/App.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/App.kt @@ -26,11 +26,11 @@ import uy.kohesive.injekt.registry.default.DefaultRegistrar import java.security.Security @ReportsCrashes( - formUri = "https://collector.tracepot.com/e90773ff", - reportType = org.acra.sender.HttpSender.Type.JSON, - httpMethod = org.acra.sender.HttpSender.Method.PUT, - buildConfigClass = BuildConfig::class, - excludeMatchingSharedPreferencesKeys = [".*username.*", ".*password.*", ".*token.*"] + formUri = "https://collector.tracepot.com/e90773ff", + reportType = org.acra.sender.HttpSender.Type.JSON, + httpMethod = org.acra.sender.HttpSender.Method.PUT, + buildConfigClass = BuildConfig::class, + excludeMatchingSharedPreferencesKeys = [".*username.*", ".*password.*", ".*token.*"] ) open class App : Application(), LifecycleObserver { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreateService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreateService.kt index 9e3120774d..997f559fed 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreateService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreateService.kt @@ -75,7 +75,8 @@ class BackupCreateService : Service() { startForeground(Notifications.ID_BACKUP_PROGRESS, notifier.showBackupProgress().build()) wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, "${javaClass.name}:WakeLock" + PowerManager.PARTIAL_WAKE_LOCK, + "${javaClass.name}:WakeLock" ) wakeLock.acquire() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt index 64f66d42e5..73d6509adf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt @@ -14,7 +14,7 @@ import uy.kohesive.injekt.api.get import java.util.concurrent.TimeUnit class BackupCreatorJob(private val context: Context, workerParams: WorkerParameters) : - Worker(context, workerParams) { + Worker(context, workerParams) { override fun doWork(): Result { val preferences = Injekt.get() @@ -37,10 +37,13 @@ class BackupCreatorJob(private val context: Context, workerParams: WorkerParamet val interval = prefInterval ?: preferences.backupInterval().getOrDefault() if (interval > 0) { val request = PeriodicWorkRequestBuilder( - interval.toLong(), TimeUnit.HOURS, - 10, TimeUnit.MINUTES) - .addTag(TAG) - .build() + interval.toLong(), + TimeUnit.HOURS, + 10, + TimeUnit.MINUTES + ) + .addTag(TAG) + .build() WorkManager.getInstance().enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request) } else { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupManager.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupManager.kt index 461abbb5d7..882c67e9e9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupManager.kt @@ -103,7 +103,8 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { private fun initParser(): Gson = when (version) { 1 -> GsonBuilder().create() - 2 -> GsonBuilder() + 2 -> + GsonBuilder() .registerTypeAdapter(MangaTypeAdapter.build()) .registerTypeHierarchyAdapter(ChapterTypeAdapter.build()) .registerTypeAdapter(CategoryTypeAdapter.build()) @@ -176,14 +177,14 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { val numberOfBackups = numberOfBackups() val backupRegex = Regex("""tachiyomi_\d+-\d+-\d+_\d+-\d+.json""") dir.listFiles { _, filename -> backupRegex.matches(filename) } - .orEmpty() - .sortedByDescending { it.name } - .drop(numberOfBackups - 1) - .forEach { it.delete() } + .orEmpty() + .sortedByDescending { it.name } + .drop(numberOfBackups - 1) + .forEach { it.delete() } // Create new file to place backup val newFile = dir.createFile(Backup.getDefaultFilename()) - ?: throw Exception("Couldn't create backup file") + ?: throw Exception("Couldn't create backup file") newFile.openOutputStream().bufferedWriter().use { parser.toJson(root, it) @@ -192,7 +193,7 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { return newFile.uri.toString() } else { val file = UniFile.fromUri(context, uri) - ?: throw Exception("Couldn't create backup file") + ?: throw Exception("Couldn't create backup file") file.openOutputStream().bufferedWriter().use { parser.toJson(root, it) } @@ -514,7 +515,7 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { * @return [Manga], null if not found */ internal fun getMangaFromDatabase(manga: Manga): Manga? = - databaseHelper.getManga(manga.url, manga.source).executeAsBlocking() + databaseHelper.getManga(manga.url, manga.source).executeAsBlocking() /** * Returns list containing manga from library @@ -522,7 +523,7 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { * @return [Manga] from library */ internal fun getFavoriteManga(): List = - databaseHelper.getFavoriteMangas().executeAsBlocking() + databaseHelper.getFavoriteMangas().executeAsBlocking() /** * Inserts manga and returns id @@ -530,7 +531,7 @@ class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { * @return id of [Manga], null if not found */ internal fun insertManga(manga: Manga): Long? = - databaseHelper.insertManga(manga).executeAsBlocking().insertedId() + databaseHelper.insertManga(manga).executeAsBlocking().insertedId() /** * Inserts list of chapters diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt index 38bed9af4e..9e03185418 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt @@ -121,7 +121,9 @@ class BackupRestoreService : Service() { super.onCreate() startForeground(Notifications.ID_RESTORE_PROGRESS, progressNotification.build()) wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, "BackupRestoreService:WakeLock") + PowerManager.PARTIAL_WAKE_LOCK, + "BackupRestoreService:WakeLock" + ) wakeLock.acquire(TimeUnit.HOURS.toMillis(3)) } @@ -358,13 +360,13 @@ class BackupRestoreService : Service() { */ private val progressNotification by lazy { NotificationCompat.Builder(this, Notifications.CHANNEL_BACKUP_RESTORE) - .setContentTitle(getString(R.string.app_name)) - .setSmallIcon(R.drawable.ic_tachi) - .setOngoing(true) - .setOnlyAlertOnce(true) - .setAutoCancel(false) - .setColor(ContextCompat.getColor(this, R.color.colorAccent)) - .addAction(R.drawable.ic_close_24dp, getString(android.R.string.cancel), cancelIntent) + .setContentTitle(getString(R.string.app_name)) + .setSmallIcon(R.drawable.ic_tachi) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setAutoCancel(false) + .setColor(ContextCompat.getColor(this, R.color.colorAccent)) + .addAction(R.drawable.ic_close_24dp, getString(android.R.string.cancel), cancelIntent) } /** @@ -382,12 +384,20 @@ class BackupRestoreService : Service() { * @param total the total progress. */ private fun showProgressNotification(current: Int, total: Int, title: String) { - notificationManager.notify(Notifications.ID_RESTORE_PROGRESS, progressNotification + notificationManager.notify( + Notifications.ID_RESTORE_PROGRESS, + progressNotification .setContentTitle(title.chop(30)) - .setContentText(getString(R.string.restoring_progress, restoreProgress, - totalAmount)) + .setContentText( + getString( + R.string.restoring_progress, + restoreProgress, + totalAmount + ) + ) .setProgress(total, current, false) - .build()) + .build() + ) } /** @@ -395,8 +405,14 @@ class BackupRestoreService : Service() { */ private fun showResultNotification(path: String?, file: String?) { - val content = mutableListOf(getString(R.string.restore_completed_content, restoreProgress - .toString(), errors.size.toString())) + val content = mutableListOf( + getString( + R.string.restore_completed_content, + restoreProgress + .toString(), + errors.size.toString() + ) + ) val sourceMissingCount = sourcesMissing.distinct().size if (sourceMissingCount > 0) { val sources = sourcesMissing.distinct().filter { it.toLongOrNull() == null } @@ -408,20 +424,29 @@ class BackupRestoreService : Service() { if (sources.isEmpty()) { content.add( resources.getQuantityString( - R.plurals.sources_missing, sourceMissingCount, sourceMissingCount + R.plurals.sources_missing, + sourceMissingCount, + sourceMissingCount ) ) } else { content.add( resources.getQuantityString( - R.plurals.sources_missing, sourceMissingCount, sourceMissingCount + R.plurals.sources_missing, + sourceMissingCount, + sourceMissingCount ) + ": " + missingSourcesString ) } } if (lincensedManga > 0) - content.add(resources.getQuantityString(R.plurals.licensed_manga, lincensedManga, - lincensedManga)) + content.add( + resources.getQuantityString( + R.plurals.licensed_manga, + lincensedManga, + lincensedManga + ) + ) val trackingErrors = trackingErrors.distinct() if (trackingErrors.isNotEmpty()) { val trackingErrorsString = trackingErrors.distinct().joinToString("\n") @@ -433,15 +458,21 @@ class BackupRestoreService : Service() { val restoreString = content.joinToString("\n") val resultNotification = NotificationCompat.Builder(this, Notifications.CHANNEL_BACKUP_RESTORE) - .setContentTitle(getString(R.string.restore_completed)) - .setContentText(restoreString) - .setStyle(NotificationCompat.BigTextStyle().bigText(restoreString)) - .setSmallIcon(R.drawable.ic_tachi) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setColor(ContextCompat.getColor(this, R.color.colorAccent)) + .setContentTitle(getString(R.string.restore_completed)) + .setContentText(restoreString) + .setStyle(NotificationCompat.BigTextStyle().bigText(restoreString)) + .setSmallIcon(R.drawable.ic_tachi) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setColor(ContextCompat.getColor(this, R.color.colorAccent)) if (errors.size > 0 && !path.isNullOrEmpty() && !file.isNullOrEmpty()) { - resultNotification.addAction(R.drawable.ic_close_24dp, getString(R.string - .view_all_errors), getErrorLogIntent(path, file)) + resultNotification.addAction( + R.drawable.ic_close_24dp, + getString( + R.string + .view_all_errors + ), + getErrorLogIntent(path, file) + ) } notificationManager.notify(Notifications.ID_RESTORE_COMPLETE, resultNotification.build()) } @@ -451,11 +482,11 @@ class BackupRestoreService : Service() { */ private fun showErrorNotification(errorMessage: String) { val resultNotification = NotificationCompat.Builder(this, Notifications.CHANNEL_BACKUP_RESTORE) - .setContentTitle(getString(R.string.restore_error)) - .setContentText(errorMessage) - .setSmallIcon(R.drawable.ic_error_24dp) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setColor(ContextCompat.getColor(this, R.color.md_red_500)) + .setContentTitle(getString(R.string.restore_error)) + .setContentText(errorMessage) + .setSmallIcon(R.drawable.ic_error_24dp) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setColor(ContextCompat.getColor(this, R.color.md_red_500)) notificationManager.notify(Notifications.ID_RESTORE_ERROR, resultNotification.build()) } @@ -477,7 +508,7 @@ class BackupRestoreService : Service() { * @return true if the service is running, false otherwise. */ fun isRunning(context: Context): Boolean = - context.isServiceRunning(BackupRestoreService::class.java) + context.isServiceRunning(BackupRestoreService::class.java) /** * Starts a service to restore a backup from Json diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.kt b/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.kt index b20b284655..709f6d9d42 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.kt @@ -46,10 +46,12 @@ class ChapterCache(private val context: Context) { private val gson: Gson by injectLazy() /** Cache class used for cache management. */ - private val diskCache = DiskLruCache.open(File(context.cacheDir, PARAMETER_CACHE_DIRECTORY), - PARAMETER_APP_VERSION, - PARAMETER_VALUE_COUNT, - PARAMETER_CACHE_SIZE) + private val diskCache = DiskLruCache.open( + File(context.cacheDir, PARAMETER_CACHE_DIRECTORY), + PARAMETER_APP_VERSION, + PARAMETER_VALUE_COUNT, + PARAMETER_CACHE_SIZE + ) /** * Returns directory of cache. diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.kt b/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.kt index 8e11469190..ce01535bb1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.kt @@ -83,7 +83,8 @@ class CoverCache(val context: Context) { withContext(Dispatchers.Main) { context.toast( context.getString( - R.string.deleted_, Formatter.formatFileSize(context, deletedSize) + R.string.deleted_, + Formatter.formatFileSize(context, deletedSize) ) ) } @@ -111,7 +112,8 @@ class CoverCache(val context: Context) { withContext(Dispatchers.Main) { context.toast( context.getString( - R.string.deleted_, Formatter.formatFileSize(context, deletedSize) + R.string.deleted_, + Formatter.formatFileSize(context, deletedSize) ) ) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/DatabaseHelper.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/DatabaseHelper.kt index 4509319c9c..c3d69c1b0c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/DatabaseHelper.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/DatabaseHelper.kt @@ -30,8 +30,13 @@ import io.requery.android.database.sqlite.RequerySQLiteOpenHelperFactory * This class provides operations to manage the database through its interfaces. */ open class DatabaseHelper(context: Context) : -MangaQueries, ChapterQueries, TrackQueries, CategoryQueries, MangaCategoryQueries, - HistoryQueries, SearchMetadataQueries { + MangaQueries, + ChapterQueries, + TrackQueries, + CategoryQueries, + MangaCategoryQueries, + HistoryQueries, + SearchMetadataQueries { private val configuration = SupportSQLiteOpenHelper.Configuration.builder(context) .name(DbOpenCallback.DATABASE_NAME) @@ -39,15 +44,15 @@ MangaQueries, ChapterQueries, TrackQueries, CategoryQueries, MangaCategoryQuerie .build() override val db = DefaultStorIOSQLite.builder() - .sqliteOpenHelper(RequerySQLiteOpenHelperFactory().create(configuration)) - .addTypeMapping(Manga::class.java, MangaTypeMapping()) - .addTypeMapping(Chapter::class.java, ChapterTypeMapping()) - .addTypeMapping(Track::class.java, TrackTypeMapping()) - .addTypeMapping(Category::class.java, CategoryTypeMapping()) - .addTypeMapping(MangaCategory::class.java, MangaCategoryTypeMapping()) - .addTypeMapping(SearchMetadata::class.java, SearchMetadataTypeMapping()) - .addTypeMapping(History::class.java, HistoryTypeMapping()) - .build() + .sqliteOpenHelper(RequerySQLiteOpenHelperFactory().create(configuration)) + .addTypeMapping(Manga::class.java, MangaTypeMapping()) + .addTypeMapping(Chapter::class.java, ChapterTypeMapping()) + .addTypeMapping(Track::class.java, TrackTypeMapping()) + .addTypeMapping(Category::class.java, CategoryTypeMapping()) + .addTypeMapping(MangaCategory::class.java, MangaCategoryTypeMapping()) + .addTypeMapping(SearchMetadata::class.java, SearchMetadataTypeMapping()) + .addTypeMapping(History::class.java, HistoryTypeMapping()) + .build() inline fun inTransaction(block: () -> Unit) = db.inTransaction(block) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt index 7fbd7089a2..e5f90313c1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt @@ -44,8 +44,10 @@ class DbOpenCallback : SupportSQLiteOpenHelper.Callback(DATABASE_VERSION) { db.execSQL(ChapterTable.sourceOrderUpdateQuery) // Fix kissmanga covers after supporting cloudflare - db.execSQL("""UPDATE mangas SET thumbnail_url = - REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""") + db.execSQL( + """UPDATE mangas SET thumbnail_url = + REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""" + ) } if (oldVersion < 3) { // Initialize history tables diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/CategoryTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/CategoryTypeMapping.kt index beefde472b..c05f95c220 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/CategoryTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/CategoryTypeMapping.kt @@ -19,22 +19,22 @@ import eu.kanade.tachiyomi.data.database.tables.CategoryTable.COL_ORDER import eu.kanade.tachiyomi.data.database.tables.CategoryTable.TABLE class CategoryTypeMapping : SQLiteTypeMapping( - CategoryPutResolver(), - CategoryGetResolver(), - CategoryDeleteResolver() + CategoryPutResolver(), + CategoryGetResolver(), + CategoryDeleteResolver() ) class CategoryPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: Category) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: Category) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: Category) = ContentValues(4).apply { put(COL_ID, obj.id) @@ -76,8 +76,8 @@ class CategoryGetResolver : DefaultGetResolver() { class CategoryDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: Category) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/ChapterTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/ChapterTypeMapping.kt index c9d9b13d3e..769bca5ee2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/ChapterTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/ChapterTypeMapping.kt @@ -27,22 +27,22 @@ import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_URL import eu.kanade.tachiyomi.data.database.tables.ChapterTable.TABLE class ChapterTypeMapping : SQLiteTypeMapping( - ChapterPutResolver(), - ChapterGetResolver(), - ChapterDeleteResolver() + ChapterPutResolver(), + ChapterGetResolver(), + ChapterDeleteResolver() ) class ChapterPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: Chapter) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: Chapter) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: Chapter) = ContentValues(11).apply { put(COL_ID, obj.id) @@ -83,8 +83,8 @@ class ChapterGetResolver : DefaultGetResolver() { class ChapterDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: Chapter) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/HistoryTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/HistoryTypeMapping.kt index fdd96f69ad..e3da101695 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/HistoryTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/HistoryTypeMapping.kt @@ -18,22 +18,22 @@ import eu.kanade.tachiyomi.data.database.tables.HistoryTable.COL_TIME_READ import eu.kanade.tachiyomi.data.database.tables.HistoryTable.TABLE class HistoryTypeMapping : SQLiteTypeMapping( - HistoryPutResolver(), - HistoryGetResolver(), - HistoryDeleteResolver() + HistoryPutResolver(), + HistoryGetResolver(), + HistoryDeleteResolver() ) open class HistoryPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: History) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: History) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: History) = ContentValues(4).apply { put(COL_ID, obj.id) @@ -56,8 +56,8 @@ class HistoryGetResolver : DefaultGetResolver() { class HistoryDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: History) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaCategoryTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaCategoryTypeMapping.kt index 99cfdd47cc..24fff124cd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaCategoryTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaCategoryTypeMapping.kt @@ -16,22 +16,22 @@ import eu.kanade.tachiyomi.data.database.tables.MangaCategoryTable.COL_MANGA_ID import eu.kanade.tachiyomi.data.database.tables.MangaCategoryTable.TABLE class MangaCategoryTypeMapping : SQLiteTypeMapping( - MangaCategoryPutResolver(), - MangaCategoryGetResolver(), - MangaCategoryDeleteResolver() + MangaCategoryPutResolver(), + MangaCategoryGetResolver(), + MangaCategoryDeleteResolver() ) class MangaCategoryPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: MangaCategory) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: MangaCategory) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: MangaCategory) = ContentValues(3).apply { put(COL_ID, obj.id) @@ -52,8 +52,8 @@ class MangaCategoryGetResolver : DefaultGetResolver() { class MangaCategoryDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: MangaCategory) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaTypeMapping.kt index 8cc35cbd8c..90b78c9014 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaTypeMapping.kt @@ -31,22 +31,22 @@ import eu.kanade.tachiyomi.data.database.tables.MangaTable.COL_VIEWER import eu.kanade.tachiyomi.data.database.tables.MangaTable.TABLE class MangaTypeMapping : SQLiteTypeMapping( - MangaPutResolver(), - MangaGetResolver(), - MangaDeleteResolver() + MangaPutResolver(), + MangaGetResolver(), + MangaDeleteResolver() ) class MangaPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: Manga) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: Manga) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: Manga) = ContentValues(15).apply { put(COL_ID, obj.id) @@ -101,8 +101,8 @@ open class MangaGetResolver : DefaultGetResolver(), BaseMangaGetResolver class MangaDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: Manga) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/TrackTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/TrackTypeMapping.kt index 797c6a2524..875059530e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/TrackTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/TrackTypeMapping.kt @@ -25,22 +25,22 @@ import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_TRACKING_URL import eu.kanade.tachiyomi.data.database.tables.TrackTable.TABLE class TrackTypeMapping : SQLiteTypeMapping( - TrackPutResolver(), - TrackGetResolver(), - TrackDeleteResolver() + TrackPutResolver(), + TrackGetResolver(), + TrackDeleteResolver() ) class TrackPutResolver : DefaultPutResolver() { override fun mapToInsertQuery(obj: Track) = InsertQuery.builder() - .table(TABLE) - .build() + .table(TABLE) + .build() override fun mapToUpdateQuery(obj: Track) = UpdateQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() override fun mapToContentValues(obj: Track) = ContentValues(10).apply { put(COL_ID, obj.id) @@ -77,8 +77,8 @@ class TrackGetResolver : DefaultGetResolver() { class TrackDeleteResolver : DefaultDeleteResolver() { override fun mapToDeleteQuery(obj: Track) = DeleteQuery.builder() - .table(TABLE) - .where("$COL_ID = ?") - .whereArgs(obj.id) - .build() + .table(TABLE) + .where("$COL_ID = ?") + .whereArgs(obj.id) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/LibraryManga.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/LibraryManga.kt index d6cdd4a2cc..f71a1ae3d9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/LibraryManga.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/LibraryManga.kt @@ -22,8 +22,8 @@ class LibraryManga : MangaImpl() { fun createHide(categoryId: Int, title: String): LibraryManga = createBlank(categoryId).apply { - this.title = title - status = -1 - } + this.title = title + status = -1 + } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt index e5351e4536..403c0fe3e0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Manga.kt @@ -73,13 +73,14 @@ interface Manga : SManga { genre?.split(",")?.map { it.trim().toLowerCase(Locale.US) } ?: emptyList() return if (currentTags.any { tag -> tag.startsWith("japanese") || isMangaTag(tag) }) { TYPE_MANGA - } else if (currentTags.any { tag -> tag.startsWith("english") || isComicTag(tag) } || isComicSource( - sourceName - )) { + } else if (currentTags.any { tag -> tag.startsWith("english") || isComicTag(tag) } || + isComicSource(sourceName) + ) { TYPE_COMIC } else if (currentTags.any { tag -> - tag.startsWith("chinese") || isManhuaTag(tag) - } || sourceName.contains("manhua", true)) { + tag.startsWith("chinese") || isManhuaTag(tag) + } || sourceName.contains("manhua", true) + ) { TYPE_MANHUA } else if (currentTags.any { tag -> isManhwaTag(tag) } || isWebtoonSource(sourceName)) { TYPE_MANHWA diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaImpl.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaImpl.kt index 22f8527d8b..4372faa32e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaImpl.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaImpl.kt @@ -74,7 +74,8 @@ open class MangaImpl : Manga { override fun copyFrom(other: SManga) { if (other is MangaImpl && other::ogTitle.isInitialized && - !other.title.isBlank() && other.ogTitle != ogTitle) { + !other.title.isBlank() && other.ogTitle != ogTitle + ) { val oldTitle = ogTitle title = other.ogTitle val db: DownloadManager by injectLazy() diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/CategoryQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/CategoryQueries.kt index d677d880d3..bf769b1545 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/CategoryQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/CategoryQueries.kt @@ -10,20 +10,24 @@ import eu.kanade.tachiyomi.data.database.tables.CategoryTable interface CategoryQueries : DbProvider { fun getCategories() = db.get() - .listOfObjects(Category::class.java) - .withQuery(Query.builder() - .table(CategoryTable.TABLE) - .orderBy(CategoryTable.COL_ORDER) - .build()) - .prepare() + .listOfObjects(Category::class.java) + .withQuery( + Query.builder() + .table(CategoryTable.TABLE) + .orderBy(CategoryTable.COL_ORDER) + .build() + ) + .prepare() fun getCategoriesForManga(manga: Manga) = db.get() - .listOfObjects(Category::class.java) - .withQuery(RawQuery.builder() - .query(getCategoriesForMangaQuery()) - .args(manga.id) - .build()) - .prepare() + .listOfObjects(Category::class.java) + .withQuery( + RawQuery.builder() + .query(getCategoriesForMangaQuery()) + .args(manga.id) + .build() + ) + .prepare() fun insertCategory(category: Category) = db.put().`object`(category).prepare() diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/ChapterQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/ChapterQueries.kt index 84ecb3ffa5..10aacb08f1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/ChapterQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/ChapterQueries.kt @@ -19,68 +19,82 @@ import java.util.Date interface ChapterQueries : DbProvider { fun getChapters(manga: Manga) = db.get() - .listOfObjects(Chapter::class.java) - .withQuery(Query.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_MANGA_ID} = ?") - .whereArgs(manga.id) - .build()) - .prepare() + .listOfObjects(Chapter::class.java) + .withQuery( + Query.builder() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_MANGA_ID} = ?") + .whereArgs(manga.id) + .build() + ) + .prepare() fun getRecentChapters(date: Date) = db.get() - .listOfObjects(MangaChapter::class.java) - .withQuery(RawQuery.builder() - .query(getRecentsQuery()) - .args(date.time) - .observesTables(ChapterTable.TABLE) - .build()) - .withGetResolver(MangaChapterGetResolver.INSTANCE) - .prepare() + .listOfObjects(MangaChapter::class.java) + .withQuery( + RawQuery.builder() + .query(getRecentsQuery()) + .args(date.time) + .observesTables(ChapterTable.TABLE) + .build() + ) + .withGetResolver(MangaChapterGetResolver.INSTANCE) + .prepare() fun getUpdatedManga(date: Date, search: String = "", endless: Boolean) = db.get() .listOfObjects(MangaChapterHistory::class.java) - .withQuery(RawQuery.builder() - .query(getRecentsQueryDistinct(search.sqLite, endless)) - .args(date.time) - .observesTables(ChapterTable.TABLE) - .build()) + .withQuery( + RawQuery.builder() + .query(getRecentsQueryDistinct(search.sqLite, endless)) + .args(date.time) + .observesTables(ChapterTable.TABLE) + .build() + ) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() fun getChapter(id: Long) = db.get() - .`object`(Chapter::class.java) - .withQuery(Query.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_ID} = ?") - .whereArgs(id) - .build()) - .prepare() + .`object`(Chapter::class.java) + .withQuery( + Query.builder() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_ID} = ?") + .whereArgs(id) + .build() + ) + .prepare() fun getChapter(url: String) = db.get() - .`object`(Chapter::class.java) - .withQuery(Query.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_URL} = ?") - .whereArgs(url) - .build()) - .prepare() + .`object`(Chapter::class.java) + .withQuery( + Query.builder() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_URL} = ?") + .whereArgs(url) + .build() + ) + .prepare() fun getChapters(url: String) = db.get() .listOfObjects(Chapter::class.java) - .withQuery(Query.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_URL} = ?") - .whereArgs(url) - .build()) + .withQuery( + Query.builder() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_URL} = ?") + .whereArgs(url) + .build() + ) .prepare() fun getChapter(url: String, mangaId: Long) = db.get() .`object`(Chapter::class.java) - .withQuery(Query.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_URL} = ? AND ${ChapterTable.COL_MANGA_ID} = ?") - .whereArgs(url, mangaId) - .build()) + .withQuery( + Query.builder() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_URL} = ? AND ${ChapterTable.COL_MANGA_ID} = ?") + .whereArgs(url, mangaId) + .build() + ) .prepare() fun insertChapter(chapter: Chapter) = db.put().`object`(chapter).prepare() @@ -92,22 +106,22 @@ interface ChapterQueries : DbProvider { fun deleteChapters(chapters: List) = db.delete().objects(chapters).prepare() fun updateChaptersBackup(chapters: List) = db.put() - .objects(chapters) - .withPutResolver(ChapterBackupPutResolver()) - .prepare() + .objects(chapters) + .withPutResolver(ChapterBackupPutResolver()) + .prepare() fun updateChapterProgress(chapter: Chapter) = db.put() - .`object`(chapter) - .withPutResolver(ChapterProgressPutResolver()) - .prepare() + .`object`(chapter) + .withPutResolver(ChapterProgressPutResolver()) + .prepare() fun updateChaptersProgress(chapters: List) = db.put() - .objects(chapters) - .withPutResolver(ChapterProgressPutResolver()) - .prepare() + .objects(chapters) + .withPutResolver(ChapterProgressPutResolver()) + .prepare() fun fixChaptersSourceOrder(chapters: List) = db.put() - .objects(chapters) - .withPutResolver(ChapterSourceOrderPutResolver()) - .prepare() + .objects(chapters) + .withPutResolver(ChapterSourceOrderPutResolver()) + .prepare() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt index e17c5046da..58d6f28659 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/HistoryQueries.kt @@ -26,14 +26,16 @@ interface HistoryQueries : DbProvider { * @offset offset the db by */ fun getRecentManga(date: Date, offset: Int = 0, search: String = "") = db.get() - .listOfObjects(MangaChapterHistory::class.java) - .withQuery(RawQuery.builder() - .query(getRecentMangasQuery(offset, search.sqLite)) - .args(date.time) - .observesTables(HistoryTable.TABLE) - .build()) - .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) - .prepare() + .listOfObjects(MangaChapterHistory::class.java) + .withQuery( + RawQuery.builder() + .query(getRecentMangasQuery(offset, search.sqLite)) + .args(date.time) + .observesTables(HistoryTable.TABLE) + .build() + ) + .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) + .prepare() /** * Returns history of recent manga containing last read chapter in 25s @@ -42,11 +44,13 @@ interface HistoryQueries : DbProvider { */ fun getRecentlyAdded(date: Date, search: String = "", endless: Boolean) = db.get() .listOfObjects(MangaChapterHistory::class.java) - .withQuery(RawQuery.builder() - .query(getRecentAdditionsQuery(search.sqLite, endless)) - .args(date.time) - .observesTables(MangaTable.TABLE) - .build()) + .withQuery( + RawQuery.builder() + .query(getRecentAdditionsQuery(search.sqLite, endless)) + .args(date.time) + .observesTables(MangaTable.TABLE) + .build() + ) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() @@ -57,11 +61,13 @@ interface HistoryQueries : DbProvider { */ fun getRecentMangaLimit(date: Date, limit: Int = 0, search: String = "") = db.get() .listOfObjects(MangaChapterHistory::class.java) - .withQuery(RawQuery.builder() - .query(getRecentMangasLimitQuery(limit, search.sqLite)) - .args(date.time) - .observesTables(HistoryTable.TABLE) - .build()) + .withQuery( + RawQuery.builder() + .query(getRecentMangasLimitQuery(limit, search.sqLite)) + .args(date.time) + .observesTables(HistoryTable.TABLE) + .build() + ) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() @@ -72,31 +78,37 @@ interface HistoryQueries : DbProvider { */ fun getRecentsWithUnread(date: Date, search: String = "", endless: Boolean) = db.get() .listOfObjects(MangaChapterHistory::class.java) - .withQuery(RawQuery.builder() - .query(getRecentReadWithUnreadChapters(search.sqLite, endless)) - .args(date.time) - .observesTables(HistoryTable.TABLE) - .build()) + .withQuery( + RawQuery.builder() + .query(getRecentReadWithUnreadChapters(search.sqLite, endless)) + .args(date.time) + .observesTables(HistoryTable.TABLE) + .build() + ) .withGetResolver(MangaChapterHistoryGetResolver.INSTANCE) .prepare() fun getHistoryByMangaId(mangaId: Long) = db.get() - .listOfObjects(History::class.java) - .withQuery(RawQuery.builder() - .query(getHistoryByMangaId()) - .args(mangaId) - .observesTables(HistoryTable.TABLE) - .build()) - .prepare() + .listOfObjects(History::class.java) + .withQuery( + RawQuery.builder() + .query(getHistoryByMangaId()) + .args(mangaId) + .observesTables(HistoryTable.TABLE) + .build() + ) + .prepare() fun getHistoryByChapterUrl(chapterUrl: String) = db.get() - .`object`(History::class.java) - .withQuery(RawQuery.builder() - .query(getHistoryByChapterUrl()) - .args(chapterUrl) - .observesTables(HistoryTable.TABLE) - .build()) - .prepare() + .`object`(History::class.java) + .withQuery( + RawQuery.builder() + .query(getHistoryByChapterUrl()) + .args(chapterUrl) + .observesTables(HistoryTable.TABLE) + .build() + ) + .prepare() /** * Updates the history last read. @@ -104,9 +116,9 @@ interface HistoryQueries : DbProvider { * @param history history object */ fun updateHistoryLastRead(history: History) = db.put() - .`object`(history) - .withPutResolver(HistoryLastReadPutResolver()) - .prepare() + .`object`(history) + .withPutResolver(HistoryLastReadPutResolver()) + .prepare() /** * Updates the history last read. @@ -114,21 +126,25 @@ interface HistoryQueries : DbProvider { * @param historyList history object list */ fun updateHistoryLastRead(historyList: List) = db.put() - .objects(historyList) - .withPutResolver(HistoryLastReadPutResolver()) - .prepare() + .objects(historyList) + .withPutResolver(HistoryLastReadPutResolver()) + .prepare() fun deleteHistory() = db.delete() - .byQuery(DeleteQuery.builder() - .table(HistoryTable.TABLE) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(HistoryTable.TABLE) + .build() + ) + .prepare() fun deleteHistoryNoLastRead() = db.delete() - .byQuery(DeleteQuery.builder() - .table(HistoryTable.TABLE) - .where("${HistoryTable.COL_LAST_READ} = ?") - .whereArgs(0) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(HistoryTable.TABLE) + .where("${HistoryTable.COL_LAST_READ} = ?") + .whereArgs(0) + .build() + ) + .prepare() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaCategoryQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaCategoryQueries.kt index 926339d0c8..9330f4923a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaCategoryQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaCategoryQueries.kt @@ -15,12 +15,14 @@ interface MangaCategoryQueries : DbProvider { fun insertMangasCategories(mangasCategories: List) = db.put().objects(mangasCategories).prepare() fun deleteOldMangasCategories(mangas: List) = db.delete() - .byQuery(DeleteQuery.builder() - .table(MangaCategoryTable.TABLE) - .where("${MangaCategoryTable.COL_MANGA_ID} IN (${Queries.placeholders(mangas.size)})") - .whereArgs(*mangas.map { it.id }.toTypedArray()) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(MangaCategoryTable.TABLE) + .where("${MangaCategoryTable.COL_MANGA_ID} IN (${Queries.placeholders(mangas.size)})") + .whereArgs(*mangas.map { it.id }.toTypedArray()) + .build() + ) + .prepare() fun setMangaCategories(mangasCategories: List, mangas: List) { db.inTransaction { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaQueries.kt index d503aedecb..ed7aa4d8e8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaQueries.kt @@ -22,67 +22,77 @@ import eu.kanade.tachiyomi.data.database.tables.MangaTable interface MangaQueries : DbProvider { fun getMangas() = db.get() - .listOfObjects(Manga::class.java) - .withQuery(Query.builder() - .table(MangaTable.TABLE) - .build()) - .prepare() + .listOfObjects(Manga::class.java) + .withQuery( + Query.builder() + .table(MangaTable.TABLE) + .build() + ) + .prepare() fun getLibraryMangas() = db.get() - .listOfObjects(LibraryManga::class.java) - .withQuery(RawQuery.builder() - .query(libraryQuery) - .observesTables(MangaTable.TABLE, ChapterTable.TABLE, MangaCategoryTable.TABLE, CategoryTable.TABLE) - .build()) - .withGetResolver(LibraryMangaGetResolver.INSTANCE) - .prepare() + .listOfObjects(LibraryManga::class.java) + .withQuery( + RawQuery.builder() + .query(libraryQuery) + .observesTables(MangaTable.TABLE, ChapterTable.TABLE, MangaCategoryTable.TABLE, CategoryTable.TABLE) + .build() + ) + .withGetResolver(LibraryMangaGetResolver.INSTANCE) + .prepare() fun getFavoriteMangas() = db.get() - .listOfObjects(Manga::class.java) - .withQuery(Query.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_FAVORITE} = ?") - .whereArgs(1) - .orderBy(MangaTable.COL_TITLE) - .build()) - .prepare() + .listOfObjects(Manga::class.java) + .withQuery( + Query.builder() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_FAVORITE} = ?") + .whereArgs(1) + .orderBy(MangaTable.COL_TITLE) + .build() + ) + .prepare() fun getManga(url: String, sourceId: Long) = db.get() - .`object`(Manga::class.java) - .withQuery(Query.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_URL} = ? AND ${MangaTable.COL_SOURCE} = ?") - .whereArgs(url, sourceId) - .build()) - .prepare() + .`object`(Manga::class.java) + .withQuery( + Query.builder() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_URL} = ? AND ${MangaTable.COL_SOURCE} = ?") + .whereArgs(url, sourceId) + .build() + ) + .prepare() fun getManga(id: Long) = db.get() - .`object`(Manga::class.java) - .withQuery(Query.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(id) - .build()) - .prepare() + .`object`(Manga::class.java) + .withQuery( + Query.builder() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(id) + .build() + ) + .prepare() fun insertManga(manga: Manga) = db.put().`object`(manga).prepare() fun insertMangas(mangas: List) = db.put().objects(mangas).prepare() fun updateFlags(manga: Manga) = db.put() - .`object`(manga) - .withPutResolver(MangaFlagsPutResolver()) - .prepare() + .`object`(manga) + .withPutResolver(MangaFlagsPutResolver()) + .prepare() fun updateLastUpdated(manga: Manga) = db.put() - .`object`(manga) - .withPutResolver(MangaLastUpdatedPutResolver()) - .prepare() + .`object`(manga) + .withPutResolver(MangaLastUpdatedPutResolver()) + .prepare() fun updateMangaFavorite(manga: Manga) = db.put() - .`object`(manga) - .withPutResolver(MangaFavoritePutResolver()) - .prepare() + .`object`(manga) + .withPutResolver(MangaFavoritePutResolver()) + .prepare() fun updateMangaAdded(manga: Manga) = db.put() .`object`(manga) @@ -90,14 +100,14 @@ interface MangaQueries : DbProvider { .prepare() fun updateMangaViewer(manga: Manga) = db.put() - .`object`(manga) - .withPutResolver(MangaViewerPutResolver()) - .prepare() + .`object`(manga) + .withPutResolver(MangaViewerPutResolver()) + .prepare() fun updateMangaTitle(manga: Manga) = db.put() - .`object`(manga) - .withPutResolver(MangaTitlePutResolver()) - .prepare() + .`object`(manga) + .withPutResolver(MangaTitlePutResolver()) + .prepare() fun updateMangaInfo(manga: Manga) = db.put() .`object`(manga) @@ -114,27 +124,33 @@ interface MangaQueries : DbProvider { fun deleteMangas(mangas: List) = db.delete().objects(mangas).prepare() fun deleteMangasNotInLibrary() = db.delete() - .byQuery(DeleteQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_FAVORITE} = ?") - .whereArgs(0) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_FAVORITE} = ?") + .whereArgs(0) + .build() + ) + .prepare() fun deleteMangas() = db.delete() - .byQuery(DeleteQuery.builder() - .table(MangaTable.TABLE) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(MangaTable.TABLE) + .build() + ) + .prepare() fun getLastReadManga() = db.get() - .listOfObjects(Manga::class.java) - .withQuery(RawQuery.builder() - .query(getLastReadMangaQuery()) - .observesTables(MangaTable.TABLE) - .build()) - .prepare() + .listOfObjects(Manga::class.java) + .withQuery( + RawQuery.builder() + .query(getLastReadMangaQuery()) + .observesTables(MangaTable.TABLE) + .build() + ) + .prepare() fun getTotalChapterManga() = db.get().listOfObjects(Manga::class.java) - .withQuery(RawQuery.builder().query(getTotalChapterMangaQuery()).observesTables(MangaTable.TABLE).build()).prepare() + .withQuery(RawQuery.builder().query(getTotalChapterMangaQuery()).observesTables(MangaTable.TABLE).build()).prepare() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/RawQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/RawQueries.kt index 2bfb7d65b7..eb96a2b0e7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/RawQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/RawQueries.kt @@ -9,7 +9,8 @@ import eu.kanade.tachiyomi.data.database.tables.MangaTable as Manga /** * Query to get the manga from the library, with their categories and unread count. */ -val libraryQuery = """ +val libraryQuery = + """ SELECT M.*, COALESCE(MC.${MangaCategory.COL_CATEGORY_ID}, 0) AS ${Manga.COL_CATEGORY} FROM ( SELECT ${Manga.TABLE}.*, COALESCE(C.unread, 0) AS ${Manga.COL_UNREAD}, COALESCE(R.hasread, 0) AS ${Manga.COL_HAS_READ} @@ -40,7 +41,8 @@ val libraryQuery = """ /** * Query to get the recent chapters of manga from the library up to a date. */ -fun getRecentsQuery() = """ +fun getRecentsQuery() = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, * FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} ON ${Manga.TABLE}.${Manga.COL_ID} = ${Chapter.TABLE}.${Chapter.COL_MANGA_ID} WHERE ${Manga.COL_FAVORITE} = 1 @@ -52,7 +54,8 @@ fun getRecentsQuery() = """ /** * Query to get the recently added manga */ -fun getRecentAdditionsQuery(search: String, endless: Boolean) = """ +fun getRecentAdditionsQuery(search: String, endless: Boolean) = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, * FROM ${Manga.TABLE} WHERE ${Manga.COL_FAVORITE} = 1 AND ${Manga.COL_DATE_ADDED} > ? @@ -64,7 +67,8 @@ fun getRecentAdditionsQuery(search: String, endless: Boolean) = """ /** * Query to get the manga with recently uploaded chapters */ -fun getRecentsQueryDistinct(search: String, endless: Boolean) = """ +fun getRecentsQueryDistinct(search: String, endless: Boolean) = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, ${Manga.TABLE}.*, ${Chapter.TABLE}.* FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -92,7 +96,8 @@ fun getRecentsQueryDistinct(search: String, endless: Boolean) = """ * and are read after the given time period * @return return limit is 25 */ -fun getRecentMangasQuery(offset: Int = 0, search: String = "") = """ +fun getRecentMangasQuery(offset: Int = 0, search: String = "") = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, ${Manga.TABLE}.*, ${Chapter.TABLE}.*, ${History.TABLE}.* FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -118,7 +123,8 @@ fun getRecentMangasQuery(offset: Int = 0, search: String = "") = """ * The select statement returns all information of chapters that have the same id as the chapter in max_last_read * and are read after the given time period */ -fun getRecentMangasLimitQuery(limit: Int = 25, search: String = "") = """ +fun getRecentMangasLimitQuery(limit: Int = 25, search: String = "") = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, ${Manga.TABLE}.*, ${Chapter.TABLE}.*, ${History.TABLE}.* FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -145,7 +151,8 @@ fun getRecentMangasLimitQuery(limit: Int = 25, search: String = "") = """ * The select statement returns all information of chapters that have the same id as the chapter in max_last_read * and are read after the given time period */ -fun getRecentReadWithUnreadChapters(search: String = "", endless: Boolean) = """ +fun getRecentReadWithUnreadChapters(search: String = "", endless: Boolean) = + """ SELECT ${Manga.TABLE}.${Manga.COL_URL} as mangaUrl, ${Manga.TABLE}.*, ${Chapter.TABLE}.*, ${History.TABLE}.* FROM ( SELECT ${Manga.TABLE}.* @@ -178,7 +185,8 @@ fun getRecentReadWithUnreadChapters(search: String = "", endless: Boolean) = """ ${if (endless) "" else "LIMIT 8"} """ -fun getHistoryByMangaId() = """ +fun getHistoryByMangaId() = + """ SELECT ${History.TABLE}.* FROM ${History.TABLE} JOIN ${Chapter.TABLE} @@ -186,7 +194,8 @@ fun getHistoryByMangaId() = """ WHERE ${Chapter.TABLE}.${Chapter.COL_MANGA_ID} = ? AND ${History.TABLE}.${History.COL_CHAPTER_ID} = ${Chapter.TABLE}.${Chapter.COL_ID} """ -fun getHistoryByChapterUrl() = """ +fun getHistoryByChapterUrl() = + """ SELECT ${History.TABLE}.* FROM ${History.TABLE} JOIN ${Chapter.TABLE} @@ -194,7 +203,8 @@ fun getHistoryByChapterUrl() = """ WHERE ${Chapter.TABLE}.${Chapter.COL_URL} = ? AND ${History.TABLE}.${History.COL_CHAPTER_ID} = ${Chapter.TABLE}.${Chapter.COL_ID} """ -fun getLastReadMangaQuery() = """ +fun getLastReadMangaQuery() = + """ SELECT ${Manga.TABLE}.*, MAX(${History.TABLE}.${History.COL_LAST_READ}) AS max FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -206,7 +216,8 @@ fun getLastReadMangaQuery() = """ ORDER BY max DESC """ -fun getTotalChapterMangaQuery() = """ +fun getTotalChapterMangaQuery() = + """ SELECT ${Manga.TABLE}.* FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -218,7 +229,8 @@ fun getTotalChapterMangaQuery() = """ /** * Query to get the categories for a manga. */ -fun getCategoriesForMangaQuery() = """ +fun getCategoriesForMangaQuery() = + """ SELECT ${Category.TABLE}.* FROM ${Category.TABLE} JOIN ${MangaCategory.TABLE} ON ${Category.TABLE}.${Category.COL_ID} = ${MangaCategory.TABLE}.${MangaCategory.COL_CATEGORY_ID} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/SearchMetadataQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/SearchMetadataQueries.kt index c23c25466d..dda8d11672 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/SearchMetadataQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/SearchMetadataQueries.kt @@ -10,35 +10,43 @@ interface SearchMetadataQueries : DbProvider { fun getSearchMetadataForManga(mangaId: Long) = db.get() .`object`(SearchMetadata::class.java) - .withQuery(Query.builder() - .table(SearchMetadataTable.TABLE) - .where("${SearchMetadataTable.COL_MANGA_ID} = ?") - .whereArgs(mangaId) - .build()) + .withQuery( + Query.builder() + .table(SearchMetadataTable.TABLE) + .where("${SearchMetadataTable.COL_MANGA_ID} = ?") + .whereArgs(mangaId) + .build() + ) .prepare() fun getSearchMetadata() = db.get() .listOfObjects(SearchMetadata::class.java) - .withQuery(Query.builder() - .table(SearchMetadataTable.TABLE) - .build()) + .withQuery( + Query.builder() + .table(SearchMetadataTable.TABLE) + .build() + ) .prepare() fun getSearchMetadataByIndexedExtra(extra: String) = db.get() .listOfObjects(SearchMetadata::class.java) - .withQuery(Query.builder() - .table(SearchMetadataTable.TABLE) - .where("${SearchMetadataTable.COL_INDEXED_EXTRA} = ?") - .whereArgs(extra) - .build()) + .withQuery( + Query.builder() + .table(SearchMetadataTable.TABLE) + .where("${SearchMetadataTable.COL_INDEXED_EXTRA} = ?") + .whereArgs(extra) + .build() + ) .prepare() fun insertSearchMetadata(metadata: SearchMetadata) = db.put().`object`(metadata).prepare() fun deleteSearchMetadata(metadata: SearchMetadata) = db.delete().`object`(metadata).prepare() - fun deleteAllSearchMetadata() = db.delete().byQuery(DeleteQuery.builder() - .table(SearchMetadataTable.TABLE) - .build()) + fun deleteAllSearchMetadata() = db.delete().byQuery( + DeleteQuery.builder() + .table(SearchMetadataTable.TABLE) + .build() + ) .prepare() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/TrackQueries.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/TrackQueries.kt index fee55dbd54..7311fe40de 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/TrackQueries.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/queries/TrackQueries.kt @@ -11,23 +11,27 @@ import eu.kanade.tachiyomi.data.track.TrackService interface TrackQueries : DbProvider { fun getTracks(manga: Manga) = db.get() - .listOfObjects(Track::class.java) - .withQuery(Query.builder() - .table(TrackTable.TABLE) - .where("${TrackTable.COL_MANGA_ID} = ?") - .whereArgs(manga.id) - .build()) - .prepare() + .listOfObjects(Track::class.java) + .withQuery( + Query.builder() + .table(TrackTable.TABLE) + .where("${TrackTable.COL_MANGA_ID} = ?") + .whereArgs(manga.id) + .build() + ) + .prepare() fun insertTrack(track: Track) = db.put().`object`(track).prepare() fun insertTracks(tracks: List) = db.put().objects(tracks).prepare() fun deleteTrackForManga(manga: Manga, sync: TrackService) = db.delete() - .byQuery(DeleteQuery.builder() - .table(TrackTable.TABLE) - .where("${TrackTable.COL_MANGA_ID} = ? AND ${TrackTable.COL_SYNC_ID} = ?") - .whereArgs(manga.id, sync.id) - .build()) - .prepare() + .byQuery( + DeleteQuery.builder() + .table(TrackTable.TABLE) + .where("${TrackTable.COL_MANGA_ID} = ? AND ${TrackTable.COL_SYNC_ID} = ?") + .whereArgs(manga.id, sync.id) + .build() + ) + .prepare() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterBackupPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterBackupPutResolver.kt index d42758beae..20008e0748 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterBackupPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterBackupPutResolver.kt @@ -20,10 +20,10 @@ class ChapterBackupPutResolver : PutResolver() { } fun mapToUpdateQuery(chapter: Chapter) = UpdateQuery.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_URL} = ?") - .whereArgs(chapter.url) - .build() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_URL} = ?") + .whereArgs(chapter.url) + .build() fun mapToContentValues(chapter: Chapter) = ContentValues(3).apply { put(ChapterTable.COL_READ, chapter.read) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterProgressPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterProgressPutResolver.kt index e2304eaaf1..38b4d59d49 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterProgressPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterProgressPutResolver.kt @@ -20,10 +20,10 @@ class ChapterProgressPutResolver : PutResolver() { } fun mapToUpdateQuery(chapter: Chapter) = UpdateQuery.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_ID} = ?") - .whereArgs(chapter.id) - .build() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_ID} = ?") + .whereArgs(chapter.id) + .build() fun mapToContentValues(chapter: Chapter) = ContentValues(3).apply { put(ChapterTable.COL_READ, chapter.read) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterSourceOrderPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterSourceOrderPutResolver.kt index 40c7a7df79..fa0f3514c8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterSourceOrderPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterSourceOrderPutResolver.kt @@ -20,10 +20,10 @@ class ChapterSourceOrderPutResolver : PutResolver() { } fun mapToUpdateQuery(chapter: Chapter) = UpdateQuery.builder() - .table(ChapterTable.TABLE) - .where("${ChapterTable.COL_URL} = ? AND ${ChapterTable.COL_MANGA_ID} = ?") - .whereArgs(chapter.url, chapter.manga_id) - .build() + .table(ChapterTable.TABLE) + .where("${ChapterTable.COL_URL} = ? AND ${ChapterTable.COL_MANGA_ID} = ?") + .whereArgs(chapter.url, chapter.manga_id) + .build() fun mapToContentValues(chapter: Chapter) = ContentValues(1).apply { put(ChapterTable.COL_SOURCE_ORDER, chapter.source_order) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt index 98ec17cb4f..d33dbc3359 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt @@ -19,11 +19,13 @@ class HistoryLastReadPutResolver : HistoryPutResolver() { override fun performPut(@NonNull db: StorIOSQLite, @NonNull history: History): PutResult = db.inTransactionReturn { val updateQuery = mapToUpdateQuery(history) - val cursor = db.lowLevel().query(Query.builder() + val cursor = db.lowLevel().query( + Query.builder() .table(updateQuery.table()) .where(updateQuery.where()) .whereArgs(updateQuery.whereArgs()) - .build()) + .build() + ) val putResult: PutResult @@ -48,10 +50,10 @@ class HistoryLastReadPutResolver : HistoryPutResolver() { * @param obj history object */ override fun mapToUpdateQuery(obj: History) = UpdateQuery.builder() - .table(HistoryTable.TABLE) - .where("${HistoryTable.COL_CHAPTER_ID} = ?") - .whereArgs(obj.chapter_id) - .build() + .table(HistoryTable.TABLE) + .where("${HistoryTable.COL_CHAPTER_ID} = ?") + .whereArgs(obj.chapter_id) + .build() /** * Create content query diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterHistoryGetResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterHistoryGetResolver.kt index 91aedffbbe..63d33d1332 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterHistoryGetResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterHistoryGetResolver.kt @@ -42,8 +42,8 @@ class MangaChapterHistoryGetResolver : DefaultGetResolver() val chapter = if (!cursor.isNull(cursor.getColumnIndex(ChapterTable.COL_MANGA_ID))) chapterResolver .mapFromCursor( - cursor - ) else ChapterImpl() + cursor + ) else ChapterImpl() // Get history object val history = diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFavoritePutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFavoritePutResolver.kt index a2d23f5051..5c948a2c8e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFavoritePutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFavoritePutResolver.kt @@ -20,10 +20,10 @@ class MangaFavoritePutResolver : PutResolver() { } fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(manga.id) - .build() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(manga.id) + .build() fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_FAVORITE, manga.favorite) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFlagsPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFlagsPutResolver.kt index 4ed0a07288..0a30da7dab 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFlagsPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaFlagsPutResolver.kt @@ -20,10 +20,10 @@ class MangaFlagsPutResolver : PutResolver() { } fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(manga.id) - .build() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(manga.id) + .build() fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_CHAPTER_FLAGS, manga.chapter_flags) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaLastUpdatedPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaLastUpdatedPutResolver.kt index b1e5e78165..6b33ed2554 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaLastUpdatedPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaLastUpdatedPutResolver.kt @@ -20,10 +20,10 @@ class MangaLastUpdatedPutResolver : PutResolver() { } fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(manga.id) - .build() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(manga.id) + .build() fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_LAST_UPDATE, manga.last_update) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaTitlePutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaTitlePutResolver.kt index 0ffb18ffd1..cb29c26d95 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaTitlePutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaTitlePutResolver.kt @@ -20,10 +20,10 @@ class MangaTitlePutResolver : PutResolver() { } fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(manga.id) - .build() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(manga.id) + .build() fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_TITLE, manga.title) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaViewerPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaViewerPutResolver.kt index a6b7c9b195..13005d24c2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaViewerPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaViewerPutResolver.kt @@ -20,10 +20,10 @@ class MangaViewerPutResolver : PutResolver() { } fun mapToUpdateQuery(manga: Manga) = UpdateQuery.builder() - .table(MangaTable.TABLE) - .where("${MangaTable.COL_ID} = ?") - .whereArgs(manga.id) - .build() + .table(MangaTable.TABLE) + .where("${MangaTable.COL_ID} = ?") + .whereArgs(manga.id) + .build() fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_VIEWER, manga.viewer) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt index 28a565d219..d3b9477b8a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt @@ -15,7 +15,8 @@ object CategoryTable { const val COL_MANGA_ORDER = "manga_order" val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_NAME TEXT NOT NULL, $COL_ORDER INTEGER NOT NULL, diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/ChapterTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/ChapterTable.kt index 803714a845..5448ff7ef7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/ChapterTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/ChapterTable.kt @@ -31,7 +31,8 @@ object ChapterTable { const val COL_SOURCE_ORDER = "source_order" val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_MANGA_ID INTEGER NOT NULL, $COL_URL TEXT NOT NULL, @@ -54,7 +55,7 @@ object ChapterTable { val createUnreadChaptersIndexQuery: String get() = "CREATE INDEX ${TABLE}_unread_by_manga_index ON $TABLE($COL_MANGA_ID, $COL_READ) " + - "WHERE $COL_READ = 0" + "WHERE $COL_READ = 0" val sourceOrderUpdateQuery: String get() = "ALTER TABLE $TABLE ADD COLUMN $COL_SOURCE_ORDER INTEGER DEFAULT 0" diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/HistoryTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/HistoryTable.kt index d552b8fbd2..9d19544a49 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/HistoryTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/HistoryTable.kt @@ -31,7 +31,8 @@ object HistoryTable { * query to create history table */ val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_CHAPTER_ID INTEGER NOT NULL UNIQUE, $COL_LAST_READ LONG, diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaCategoryTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaCategoryTable.kt index d0d34bbb78..578a85bbc9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaCategoryTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaCategoryTable.kt @@ -11,7 +11,8 @@ object MangaCategoryTable { const val COL_CATEGORY_ID = "category_id" val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_MANGA_ID INTEGER NOT NULL, $COL_CATEGORY_ID INTEGER NOT NULL, diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaTable.kt index 30d98e780f..1778dd8cb3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/MangaTable.kt @@ -45,7 +45,8 @@ object MangaTable { const val COL_DATE_ADDED = "date_added" val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_SOURCE INTEGER NOT NULL, $COL_URL TEXT NOT NULL, @@ -71,7 +72,7 @@ object MangaTable { val createLibraryIndexQuery: String get() = "CREATE INDEX library_${COL_FAVORITE}_index ON $TABLE($COL_FAVORITE) " + - "WHERE $COL_FAVORITE = 1" + "WHERE $COL_FAVORITE = 1" val addHideTitle: String get() = "ALTER TABLE $TABLE ADD COLUMN $COL_HIDE_TITLE INTEGER DEFAULT 0" diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/SearchMetadataTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/SearchMetadataTable.kt index b7ac1744aa..89f318c6dc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/SearchMetadataTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/SearchMetadataTable.kt @@ -15,7 +15,8 @@ object SearchMetadataTable { // Insane foreign, primary key to avoid touch manga table val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_MANGA_ID INTEGER NOT NULL PRIMARY KEY, $COL_UPLOADER TEXT, $COL_EXTRA TEXT NOT NULL, diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/TrackTable.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/TrackTable.kt index 82c863fb90..0a3ccf3442 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/TrackTable.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/tables/TrackTable.kt @@ -27,7 +27,8 @@ object TrackTable { const val COL_TRACKING_URL = "remote_url" val createTableQuery: String - get() = """CREATE TABLE $TABLE( + get() = + """CREATE TABLE $TABLE( $COL_ID INTEGER NOT NULL PRIMARY KEY, $COL_MANGA_ID INTEGER NOT NULL, $COL_SYNC_ID INTEGER NOT NULL, diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt index c794dd55b4..4b4a8c6c20 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt @@ -251,7 +251,9 @@ class DownloadManager(val context: Context) { queue.remove(chapters) val chapterDirs = provider.findChapterDirs(chapters, manga, source) + provider.findTempChapterDirs( - chapters, manga, source + chapters, + manga, + source ) chapterDirs.forEach { it.delete() } cache.removeChapters(chapters, manga) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadNotifier.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadNotifier.kt index 13d5e8208d..13fda6607f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadNotifier.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadNotifier.kt @@ -24,7 +24,7 @@ internal class DownloadNotifier(private val context: Context) { */ private val notification by lazy { NotificationCompat.Builder(context, Notifications.CHANNEL_DOWNLOADER) - .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) + .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) } /** @@ -78,16 +78,21 @@ internal class DownloadNotifier(private val context: Context) { setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) isDownloading = true // Pause action - addAction(R.drawable.ic_pause_24dp, + addAction( + R.drawable.ic_pause_24dp, context.getString(R.string.pause), - NotificationReceiver.pauseDownloadsPendingBroadcast(context)) + NotificationReceiver.pauseDownloadsPendingBroadcast(context) + ) } if (download != null) { val title = download.manga.title.chop(15) val quotedTitle = Pattern.quote(title) - val chapter = download.chapter.name.replaceFirst("$quotedTitle[\\s]*[-]*[\\s]*" - .toRegex(RegexOption.IGNORE_CASE), "") + val chapter = download.chapter.name.replaceFirst( + "$quotedTitle[\\s]*[-]*[\\s]*" + .toRegex(RegexOption.IGNORE_CASE), + "" + ) setContentTitle("$title - $chapter".chop(30)) setContentText( context.getString(R.string.downloading) @@ -124,17 +129,21 @@ internal class DownloadNotifier(private val context: Context) { setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) isDownloading = true // Pause action - addAction(R.drawable.ic_pause_24dp, - context.getString(R.string.pause), - NotificationReceiver.pauseDownloadsPendingBroadcast(context)) + addAction( + R.drawable.ic_pause_24dp, + context.getString(R.string.pause), + NotificationReceiver.pauseDownloadsPendingBroadcast(context) + ) } val title = download.manga.title.chop(15) val quotedTitle = Pattern.quote(title) val chapter = download.chapter.name.replaceFirst("$quotedTitle[\\s]*[-]*[\\s]*".toRegex(RegexOption.IGNORE_CASE), "") setContentTitle("$title - $chapter".chop(30)) - setContentText(context.getString(R.string.downloading_progress) - .format(download.downloadedImages, download.pages!!.size)) + setContentText( + context.getString(R.string.downloading_progress) + .format(download.downloadedImages, download.pages!!.size) + ) setStyle(null) setProgress(download.pages!!.size, download.downloadedImages, false) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadService.kt index 41e5520d42..f109a808a5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadService.kt @@ -161,13 +161,17 @@ class DownloadService : Service() { */ private fun listenNetworkChanges() { subscriptions += ReactiveNetwork.observeNetworkConnectivity(applicationContext) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ state -> onNetworkStateChanged(state) - }, { + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe( + { state -> + onNetworkStateChanged(state) + }, + { toast(R.string.could_not_download_chapter_can_try_again) stopSelf() - }) + } + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt index cfa82a2753..9ae4229c42 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt @@ -80,9 +80,9 @@ class DownloadStore( */ fun restore(): List { val objs = preferences.all - .mapNotNull { it.value as? String } - .mapNotNull { deserialize(it) } - .sortedBy { it.order } + .mapNotNull { it.value as? String } + .mapNotNull { deserialize(it) } + .sortedBy { it.order } val downloads = mutableListOf() if (objs.isNotEmpty()) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt index 474c6ed0a9..8f9feedd81 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt @@ -288,23 +288,23 @@ class Downloader( val pageListObservable = if (download.pages == null) { // Pull page list from network and add them to download object download.source.fetchPageList(download.chapter).doOnNext { pages -> - if (pages.isEmpty()) { - throw Exception("Page list is empty") - } - download.pages = pages + if (pages.isEmpty()) { + throw Exception("Page list is empty") } + download.pages = pages + } } else { // Or if the page list already exists, start from the file Observable.just(download.pages!!) } pageListObservable.doOnNext { _ -> - // Delete all temporary (unfinished) files - tmpDir.listFiles()?.filter { it.name!!.endsWith(".tmp") }?.forEach { it.delete() } + // Delete all temporary (unfinished) files + tmpDir.listFiles()?.filter { it.name!!.endsWith(".tmp") }?.forEach { it.delete() } - download.downloadedImages = 0 - download.status = Download.DOWNLOADING - } + download.downloadedImages = 0 + download.status = Download.DOWNLOADING + } // Get all the URLs to the source images, fetch pages if necessary .flatMap { download.source.fetchAllImageUrlsFromPageList(it) } // Start downloading images, consider we can have downloaded images already @@ -447,7 +447,7 @@ class Downloader( private fun getImageExtension(response: Response, file: UniFile): String { // Read content type if available. val mime = response.body?.contentType()?.let { ct -> "${ct.type}/${ct.subtype}" } - // Else guess from the uri. + // Else guess from the uri. ?: context.contentResolver.getType(file.uri) // Else read magic numbers. ?: ImageUtil.findImageType { file.openInputStream() }?.mime diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt index 5325af0bbb..585206c711 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt @@ -13,7 +13,7 @@ class DownloadQueue( private val store: DownloadStore, private val queue: MutableList = CopyOnWriteArrayList() ) : -List by queue { + List by queue { private val statusSubject = PublishSubject.create() @@ -80,8 +80,8 @@ List by queue { fun getStatusObservable(): Observable = statusSubject.onBackpressureBuffer() fun getUpdatedObservable(): Observable> = updatedRelay.onBackpressureBuffer() - .startWith(Unit) - .map { this } + .startWith(Unit) + .map { this } private fun setPagesFor(download: Download) { if (download.status == Download.DOWNLOADING) { @@ -105,23 +105,23 @@ List by queue { fun getProgressObservable(): Observable { return statusSubject.onBackpressureBuffer() - .startWith(getActiveDownloads()) - .flatMap { download -> - if (download.status == Download.DOWNLOADING) { - val pageStatusSubject = PublishSubject.create() - setPagesSubject(download.pages, pageStatusSubject) - downloadListeners.forEach { it.updateDownload(download) } - return@flatMap pageStatusSubject - .onBackpressureBuffer() - .filter { it == Page.READY } - .map { download } - } else if (download.status == Download.DOWNLOADED || download.status == Download.ERROR) { - setPagesSubject(download.pages, null) - downloadListeners.forEach { it.updateDownload(download) } - } - Observable.just(download) + .startWith(getActiveDownloads()) + .flatMap { download -> + if (download.status == Download.DOWNLOADING) { + val pageStatusSubject = PublishSubject.create() + setPagesSubject(download.pages, pageStatusSubject) + downloadListeners.forEach { it.updateDownload(download) } + return@flatMap pageStatusSubject + .onBackpressureBuffer() + .filter { it == Page.READY } + .map { download } + } else if (download.status == Download.DOWNLOADED || download.status == Download.ERROR) { + setPagesSubject(download.pages, null) + downloadListeners.forEach { it.updateDownload(download) } } - .filter { it.status == Download.DOWNLOADING } + Observable.just(download) + } + .filter { it.status == Download.DOWNLOADING } } private fun setPagesSubject(pages: List?, subject: PublishSubject?) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/CoverViewTarget.kt b/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/CoverViewTarget.kt index 1e3841d4fd..db0ccc2c49 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/CoverViewTarget.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/CoverViewTarget.kt @@ -20,7 +20,9 @@ class CoverViewTarget( progress?.gone() view.scaleType = ImageView.ScaleType.CENTER val vector = VectorDrawableCompat.create( - view.context.resources, R.drawable.ic_broken_image_24dp, null + view.context.resources, + R.drawable.ic_broken_image_24dp, + null ) vector?.setTint(view.context.getResourceColor(android.R.attr.textColorSecondary)) view.setImageDrawable(vector) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/MangaFetcher.kt b/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/MangaFetcher.kt index 0d284251c8..76a606949f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/MangaFetcher.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/image/coil/MangaFetcher.kt @@ -70,7 +70,8 @@ class MangaFetcher : Fetcher { return fileLoader(coverFile) } val (_, body) = awaitGetCall( - manga, if (manga.favorite) { + manga, + if (manga.favorite) { !options.networkCachePolicy.readEnabled } else { false diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/library/CustomMangaManager.kt b/app/src/main/java/eu/kanade/tachiyomi/data/library/CustomMangaManager.kt index 6ce0ce311f..743bada22c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/library/CustomMangaManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/library/CustomMangaManager.kt @@ -29,7 +29,8 @@ class CustomMangaManager(val context: Context) { val json = try { Gson().fromJson( - Scanner(editJson).useDelimiter("\\Z").next(), JsonObject::class.java + Scanner(editJson).useDelimiter("\\Z").next(), + JsonObject::class.java ) } catch (e: Exception) { null @@ -83,7 +84,12 @@ class CustomMangaManager(val context: Context) { fun Manga.toJson(): MangaJson { return MangaJson( - id!!, title, author, artist, description, genre?.split(", ")?.toTypedArray() + id!!, + title, + author, + artist, + description, + genre?.split(", ")?.toTypedArray() ) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt index 3401262ecf..aaf6e8abb1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt @@ -15,7 +15,7 @@ import uy.kohesive.injekt.api.get import java.util.concurrent.TimeUnit class LibraryUpdateJob(private val context: Context, workerParams: WorkerParameters) : - Worker(context, workerParams) { + Worker(context, workerParams) { override fun doWork(): Result { LibraryUpdateService.start(context) @@ -37,16 +37,19 @@ class LibraryUpdateJob(private val context: Context, workerParams: WorkerParamet NetworkType.CONNECTED val constraints = Constraints.Builder() - .setRequiredNetworkType(wifiRestriction) - .setRequiresCharging(acRestriction) - .build() + .setRequiredNetworkType(wifiRestriction) + .setRequiresCharging(acRestriction) + .build() val request = PeriodicWorkRequestBuilder( - interval.toLong(), TimeUnit.HOURS, - 10, TimeUnit.MINUTES) - .addTag(TAG) - .setConstraints(constraints) - .build() + interval.toLong(), + TimeUnit.HOURS, + 10, + TimeUnit.MINUTES + ) + .addTag(TAG) + .setConstraints(constraints) + .build() WorkManager.getInstance().enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request) } else { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateNotifier.kt b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateNotifier.kt index 766ddf2f14..8258efe5f9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateNotifier.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateNotifier.kt @@ -131,60 +131,73 @@ class LibraryUpdateNotifier(private val context: Context) { val manga = it.key val chapters = it.value val chapterNames = chapters.map { chapter -> chapter.name } - notifications.add(Pair(context.notification(Notifications.CHANNEL_NEW_CHAPTERS) { - setSmallIcon(R.drawable.ic_tachi) - try { - val request = GetRequest.Builder(context).data(manga) - .networkCachePolicy(CachePolicy.DISABLED) - .transformations(CircleCropTransformation()) - .size(width = ICON_SIZE, height = ICON_SIZE).build() + notifications.add( + Pair( + context.notification(Notifications.CHANNEL_NEW_CHAPTERS) { + setSmallIcon(R.drawable.ic_tachi) + try { + val request = GetRequest.Builder(context).data(manga) + .networkCachePolicy(CachePolicy.DISABLED) + .transformations(CircleCropTransformation()) + .size(width = ICON_SIZE, height = ICON_SIZE).build() - Coil.imageLoader(context).execute(request).drawable?.let { drawable -> - setLargeIcon((drawable as BitmapDrawable).bitmap) + Coil.imageLoader(context).execute(request).drawable?.let { drawable -> + setLargeIcon((drawable as BitmapDrawable).bitmap) + } + } catch (e: Exception) { } - } catch (e: Exception) { - } - setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) - setContentTitle(manga.title) - color = ContextCompat.getColor(context, R.color.colorAccent) - val chaptersNames = if (chapterNames.size > MAX_CHAPTERS) { - "${chapterNames.take(MAX_CHAPTERS - 1) - .joinToString(", ")}, " + context.resources.getQuantityString( - R.plurals.notification_and_n_more, - (chapterNames.size - (MAX_CHAPTERS - 1)), - (chapterNames.size - (MAX_CHAPTERS - 1)) - ) - } else chapterNames.joinToString(", ") - setContentText(chaptersNames) - setStyle(NotificationCompat.BigTextStyle().bigText(chaptersNames)) - priority = NotificationCompat.PRIORITY_HIGH - setGroup(Notifications.GROUP_NEW_CHAPTERS) - setContentIntent( - NotificationReceiver.openChapterPendingActivity( - context, manga, chapters.first() - ) + setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) + setContentTitle(manga.title) + color = ContextCompat.getColor(context, R.color.colorAccent) + val chaptersNames = if (chapterNames.size > MAX_CHAPTERS) { + "${chapterNames.take(MAX_CHAPTERS - 1).joinToString(", ")}, " + + context.resources.getQuantityString( + R.plurals.notification_and_n_more, + (chapterNames.size - (MAX_CHAPTERS - 1)), + (chapterNames.size - (MAX_CHAPTERS - 1)) + ) + } else chapterNames.joinToString(", ") + setContentText(chaptersNames) + setStyle(NotificationCompat.BigTextStyle().bigText(chaptersNames)) + priority = NotificationCompat.PRIORITY_HIGH + setGroup(Notifications.GROUP_NEW_CHAPTERS) + setContentIntent( + NotificationReceiver.openChapterPendingActivity( + context, + manga, + chapters.first() + ) + ) + addAction( + R.drawable.ic_eye_24dp, + context.getString(R.string.mark_as_read), + NotificationReceiver.markAsReadPendingBroadcast( + context, + manga, + chapters, + Notifications.ID_NEW_CHAPTERS + ) + ) + addAction( + R.drawable.ic_book_24dp, + context.getString(R.string.view_chapters), + NotificationReceiver.openChapterPendingActivity( + context, + manga, + Notifications.ID_NEW_CHAPTERS + ) + ) + setAutoCancel(true) + }, + manga.id.hashCode() ) - addAction( - R.drawable.ic_eye_24dp, - context.getString(R.string.mark_as_read), - NotificationReceiver.markAsReadPendingBroadcast( - context, manga, chapters, Notifications.ID_NEW_CHAPTERS - ) - ) - addAction( - R.drawable.ic_book_24dp, - context.getString(R.string.view_chapters), - NotificationReceiver.openChapterPendingActivity( - context, manga, Notifications.ID_NEW_CHAPTERS - ) - ) - setAutoCancel(true) - }, manga.id.hashCode())) + ) } NotificationManagerCompat.from(context).apply { - notify(Notifications.ID_NEW_CHAPTERS, + notify( + Notifications.ID_NEW_CHAPTERS, context.notification(Notifications.CHANNEL_NEW_CHAPTERS) { setSmallIcon(R.drawable.ic_tachi) setLargeIcon(notificationBitmap) @@ -193,14 +206,18 @@ class LibraryUpdateNotifier(private val context: Context) { if (updates.size > 1) { setContentText( context.resources.getQuantityString( - R.plurals.for_n_titles, updates.size, updates.size + R.plurals.for_n_titles, + updates.size, + updates.size ) ) setStyle( NotificationCompat.BigTextStyle() - .bigText(updates.keys.joinToString("\n") { - it.title.chop(45) - }) + .bigText( + updates.keys.joinToString("\n") { + it.title.chop(45) + } + ) ) } else { setContentText(updates.keys.first().title.chop(45)) @@ -211,7 +228,8 @@ class LibraryUpdateNotifier(private val context: Context) { setGroupSummary(true) setContentIntent(getNotificationIntent()) setAutoCancel(true) - }) + } + ) notifications.forEach { notify(it.second, it.first) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt index c7f9699d9b..651a391ee4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt @@ -8,8 +8,9 @@ import eu.kanade.tachiyomi.data.database.models.Manga object LibraryUpdateRanker { val rankingScheme = listOf( - (this::lexicographicRanking)(), - (this::latestFirstRanking)()) + (this::lexicographicRanking)(), + (this::latestFirstRanking)() + ) /** * Provides a total ordering over all the Mangas. @@ -22,7 +23,7 @@ object LibraryUpdateRanker { */ fun latestFirstRanking(): Comparator { return Comparator { mangaFirst: Manga, - mangaSecond: Manga -> + mangaSecond: Manga -> compareValues(mangaSecond.last_update, mangaFirst.last_update) } } @@ -35,7 +36,7 @@ object LibraryUpdateRanker { */ fun lexicographicRanking(): Comparator { return Comparator { mangaFirst: Manga, - mangaSecond: Manga -> + mangaSecond: Manga -> compareValues(mangaFirst.title, mangaSecond.title) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateService.kt index b6c4214080..bc5ee54847 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateService.kt @@ -134,16 +134,18 @@ class LibraryUpdateService( val selectedScheme = preferences.libraryUpdatePrioritization().getOrDefault() val savedMangasList = intent.getLongArrayExtra(KEY_MANGAS)?.asList() - val mangaList = (if (savedMangasList != null) { - val mangas = db.getLibraryMangas().executeAsBlocking().filter { - it.id in savedMangasList - }.distinctBy { it.id } - val categoryId = intent.getIntExtra(KEY_CATEGORY, -1) - if (categoryId > -1) categoryIds.add(categoryId) - mangas - } else { - getMangaToUpdate(intent, target) - }).sortedWith(rankingScheme[selectedScheme]) + val mangaList = ( + if (savedMangasList != null) { + val mangas = db.getLibraryMangas().executeAsBlocking().filter { + it.id in savedMangasList + }.distinctBy { it.id } + val categoryId = intent.getIntExtra(KEY_CATEGORY, -1) + if (categoryId > -1) categoryIds.add(categoryId) + mangas + } else { + getMangaToUpdate(intent, target) + } + ).sortedWith(rankingScheme[selectedScheme]) // Update favorite manga. Destroy service when completed or in case of an error. launchTarget(target, mangaList, startId) return START_REDELIVER_INTENT @@ -157,7 +159,8 @@ class LibraryUpdateService( super.onCreate() notifier = LibraryUpdateNotifier(this) wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, "LibraryUpdateService:WakeLock" + PowerManager.PARTIAL_WAKE_LOCK, + "LibraryUpdateService:WakeLock" ) wakeLock.acquire(TimeUnit.MINUTES.toMillis(30)) startForeground(Notifications.ID_LIBRARY_PROGRESS, notifier.progressNotificationBuilder.build()) @@ -247,7 +250,9 @@ class LibraryUpdateService( val hasDLs = try { requestSemaphore.withPermit { updateMangaInSource( - it.key, downloadNew, categoriesToDownload + it.key, + downloadNew, + categoriesToDownload ) } } catch (e: Exception) { @@ -351,13 +356,15 @@ class LibraryUpdateService( var hasDownloads = false while (count < mangaToUpdateMap[source]!!.size) { val shouldDownload = - (downloadNew && (categoriesToDownload.isEmpty() || mangaToUpdateMap[source]!![count].category in categoriesToDownload || db.getCategoriesForManga( - mangaToUpdateMap[source]!![count] - ).executeOnIO().any { (it.id ?: -1) in categoriesToDownload })) - if (updateMangaChapters( - mangaToUpdateMap[source]!![count], this.count.andIncrement, shouldDownload - ) - ) { + ( + downloadNew && ( + categoriesToDownload.isEmpty() || + mangaToUpdateMap[source]!![count].category in categoriesToDownload || + db.getCategoriesForManga(mangaToUpdateMap[source]!![count]) + .executeOnIO().any { (it.id ?: -1) in categoriesToDownload } + ) + ) + if (updateMangaChapters(mangaToUpdateMap[source]!![count], this.count.andIncrement, shouldDownload)) { hasDownloads = true } count++ @@ -372,47 +379,47 @@ class LibraryUpdateService( shouldDownload: Boolean ): Boolean { - try { - var hasDownloads = false - if (job?.isCancelled == true) { + try { + var hasDownloads = false + if (job?.isCancelled == true) { + return false + } + notifier.showProgressNotification(manga, progress, mangaToUpdate.size) + val source = sourceManager.get(manga.source) as? HttpSource ?: return false + val fetchedChapters = withContext(Dispatchers.IO) { + source.fetchChapterList(manga).toBlocking().single() + } ?: emptyList() + if (fetchedChapters.isNotEmpty()) { + val newChapters = syncChaptersWithSource(db, fetchedChapters, manga, source) + if (newChapters.first.isNotEmpty()) { + if (shouldDownload) { + downloadChapters(manga, newChapters.first.sortedBy { it.chapter_number }) + hasDownloads = true + } + newUpdates[manga] = + newChapters.first.sortedBy { it.chapter_number }.toTypedArray() + } + if (deleteRemoved && newChapters.second.isNotEmpty()) { + val removedChapters = newChapters.second.filter { + downloadManager.isChapterDownloaded(it, manga) + } + if (removedChapters.isNotEmpty()) { + downloadManager.deleteChapters(removedChapters, manga, source) + } + } + if (newChapters.first.size + newChapters.second.size > 0) listener?.onUpdateManga( + manga + ) + } + return hasDownloads + } catch (e: Exception) { + if (e !is CancellationException) { + failedUpdates[manga] = e.message + Timber.e("Failed updating: ${manga.title}: $e") + } return false } - notifier.showProgressNotification(manga, progress, mangaToUpdate.size) - val source = sourceManager.get(manga.source) as? HttpSource ?: return false - val fetchedChapters = withContext(Dispatchers.IO) { - source.fetchChapterList(manga).toBlocking().single() - } ?: emptyList() - if (fetchedChapters.isNotEmpty()) { - val newChapters = syncChaptersWithSource(db, fetchedChapters, manga, source) - if (newChapters.first.isNotEmpty()) { - if (shouldDownload) { - downloadChapters(manga, newChapters.first.sortedBy { it.chapter_number }) - hasDownloads = true - } - newUpdates[manga] = - newChapters.first.sortedBy { it.chapter_number }.toTypedArray() - } - if (deleteRemoved && newChapters.second.isNotEmpty()) { - val removedChapters = newChapters.second.filter { - downloadManager.isChapterDownloaded(it, manga) - } - if (removedChapters.isNotEmpty()) { - downloadManager.deleteChapters(removedChapters, manga, source) - } - } - if (newChapters.first.size + newChapters.second.size > 0) listener?.onUpdateManga( - manga - ) - } - return hasDownloads - } catch (e: Exception) { - if (e !is CancellationException) { - failedUpdates[manga] = e.message - Timber.e("Failed updating: ${manga.title}: $e") - } - return false } - } private fun downloadChapters(manga: Manga, chapters: List) { // We don't want to start downloading while the library is updating, because websites diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt index 74869196b6..1878aeba2b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt @@ -58,29 +58,41 @@ class NotificationReceiver : BroadcastReceiver() { // Clear the download queue ACTION_CLEAR_DOWNLOADS -> downloadManager.clearQueue(true) // Launch share activity and dismiss notification - ACTION_SHARE_IMAGE -> shareImage(context, intent.getStringExtra(EXTRA_FILE_LOCATION), - intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)) + ACTION_SHARE_IMAGE -> shareImage( + context, + intent.getStringExtra(EXTRA_FILE_LOCATION), + intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1) + ) // Delete image from path and dismiss notification - ACTION_DELETE_IMAGE -> deleteImage(context, intent.getStringExtra(EXTRA_FILE_LOCATION), - intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)) + ACTION_DELETE_IMAGE -> deleteImage( + context, + intent.getStringExtra(EXTRA_FILE_LOCATION), + intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1) + ) // Cancel library update and dismiss notification ACTION_CANCEL_LIBRARY_UPDATE -> cancelLibraryUpdate(context) ACTION_CANCEL_RESTORE -> cancelRestoreUpdate(context) // Share backup file ACTION_SHARE_BACKUP -> shareBackup( - context, intent.getParcelableExtra(EXTRA_URI), + context, + intent.getParcelableExtra(EXTRA_URI), intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1) ) // Open reader activity ACTION_OPEN_CHAPTER -> { - openChapter(context, intent.getLongExtra(EXTRA_MANGA_ID, -1), - intent.getLongExtra(EXTRA_CHAPTER_ID, -1)) + openChapter( + context, + intent.getLongExtra(EXTRA_MANGA_ID, -1), + intent.getLongExtra(EXTRA_CHAPTER_ID, -1) + ) } ACTION_MARK_AS_READ -> { val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1) if (notificationId > -1) dismissNotification( - context, notificationId, intent.getIntExtra(EXTRA_GROUP_ID, 0) + context, + notificationId, + intent.getIntExtra(EXTRA_GROUP_ID, 0) ) val urls = intent.getStringArrayExtra(EXTRA_CHAPTER_URL) ?: return val mangaId = intent.getLongExtra(EXTRA_MANGA_ID, -1) @@ -342,7 +354,7 @@ class NotificationReceiver : BroadcastReceiver() { context: Context, notificationId: Int, groupId: Int? = - null + null ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val groupKey = context.notificationManager.activeNotifications.find { @@ -377,8 +389,13 @@ class NotificationReceiver : BroadcastReceiver() { clipData = ClipData.newRawUri(null, uri) type = "image/*" } - return PendingIntent.getActivity(context, 0, shareIntent, PendingIntent - .FLAG_CANCEL_CURRENT) + return PendingIntent.getActivity( + context, + 0, + shareIntent, + PendingIntent + .FLAG_CANCEL_CURRENT + ) } /** @@ -409,11 +426,16 @@ class NotificationReceiver : BroadcastReceiver() { context: Context, manga: Manga, chapter: - Chapter + Chapter ): PendingIntent { val newIntent = ReaderActivity.newIntent(context, manga, chapter) - return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent - .FLAG_UPDATE_CURRENT) + return PendingIntent.getActivity( + context, + manga.id.hashCode(), + newIntent, + PendingIntent + .FLAG_UPDATE_CURRENT + ) } /** @@ -424,16 +446,19 @@ class NotificationReceiver : BroadcastReceiver() { */ internal fun openChapterPendingActivity(context: Context, manga: Manga, groupId: Int): PendingIntent { - val newIntent = - Intent(context, MainActivity::class.java).setAction(MainActivity.SHORTCUT_MANGA) - .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) - .putExtra(MangaDetailsController.MANGA_EXTRA, manga.id) - .putExtra("notificationId", manga.id.hashCode()) - .putExtra("groupId", groupId) - return PendingIntent.getActivity( - context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT - ) - } + val newIntent = + Intent(context, MainActivity::class.java).setAction(MainActivity.SHORTCUT_MANGA) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .putExtra(MangaDetailsController.MANGA_EXTRA, manga.id) + .putExtra("notificationId", manga.id.hashCode()) + .putExtra("groupId", groupId) + return PendingIntent.getActivity( + context, + manga.id.hashCode(), + newIntent, + PendingIntent.FLAG_UPDATE_CURRENT + ) + } /** * Returns [PendingIntent] that opens the error log file in an external viewer @@ -462,7 +487,10 @@ class NotificationReceiver : BroadcastReceiver() { Intent(context, MainActivity::class.java).setAction(MainActivity.SHORTCUT_EXTENSIONS) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) return PendingIntent.getActivity( - context, 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT + context, + 0, + newIntent, + PendingIntent.FLAG_UPDATE_CURRENT ) } @@ -473,7 +501,7 @@ class NotificationReceiver : BroadcastReceiver() { val toLaunch = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "text/plain") flags = Intent.FLAG_ACTIVITY_NEW_TASK or - Intent.FLAG_GRANT_READ_URI_PERMISSION + Intent.FLAG_GRANT_READ_URI_PERMISSION } return PendingIntent.getActivity(context, 0, toLaunch, 0) } @@ -488,19 +516,19 @@ class NotificationReceiver : BroadcastReceiver() { context: Context, manga: Manga, chapters: - Array, + Array, groupId: Int ): PendingIntent { - val newIntent = Intent(context, NotificationReceiver::class.java).apply { - action = ACTION_MARK_AS_READ - putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray()) - putExtra(EXTRA_MANGA_ID, manga.id) - putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode()) - putExtra(EXTRA_GROUP_ID, groupId) + val newIntent = Intent(context, NotificationReceiver::class.java).apply { + action = ACTION_MARK_AS_READ + putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray()) + putExtra(EXTRA_MANGA_ID, manga.id) + putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode()) + putExtra(EXTRA_GROUP_ID, groupId) + } + return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT) } - return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT) - } /** * Returns [PendingIntent] that starts a service which stops the library update diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt b/app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt index 07b36d116f..7da05fa80b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt @@ -61,37 +61,44 @@ object Notifications { fun createChannels(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return - val channels = listOf(NotificationChannel( - CHANNEL_COMMON, - context.getString(R.string.common), - NotificationManager.IMPORTANCE_LOW - ), NotificationChannel( - CHANNEL_LIBRARY, - context.getString(R.string.updating_library), - NotificationManager.IMPORTANCE_LOW - ).apply { - setShowBadge(false) - }, NotificationChannel( - CHANNEL_DOWNLOADER, - context.getString(R.string.downloads), - NotificationManager.IMPORTANCE_LOW - ).apply { - setShowBadge(false) - }, NotificationChannel( - CHANNEL_UPDATES_TO_EXTS, - context.getString(R.string.extension_updates), - NotificationManager.IMPORTANCE_DEFAULT - ), NotificationChannel( - CHANNEL_NEW_CHAPTERS, - context.getString(R.string.new_chapters), - NotificationManager.IMPORTANCE_DEFAULT - ), NotificationChannel( - CHANNEL_BACKUP_RESTORE, - context.getString(R.string.restoring_backup), - NotificationManager.IMPORTANCE_LOW - ).apply { - setShowBadge(false) - }) + val channels = listOf( + NotificationChannel( + CHANNEL_COMMON, + context.getString(R.string.common), + NotificationManager.IMPORTANCE_LOW + ), + NotificationChannel( + CHANNEL_LIBRARY, + context.getString(R.string.updating_library), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + }, + NotificationChannel( + CHANNEL_DOWNLOADER, + context.getString(R.string.downloads), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + }, + NotificationChannel( + CHANNEL_UPDATES_TO_EXTS, + context.getString(R.string.extension_updates), + NotificationManager.IMPORTANCE_DEFAULT + ), + NotificationChannel( + CHANNEL_NEW_CHAPTERS, + context.getString(R.string.new_chapters), + NotificationManager.IMPORTANCE_DEFAULT + ), + NotificationChannel( + CHANNEL_BACKUP_RESTORE, + context.getString(R.string.restoring_backup), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + } + ) context.notificationManager.createNotificationChannels(channels) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferencesHelper.kt b/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferencesHelper.kt index f4a333160e..342db58f3f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferencesHelper.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferencesHelper.kt @@ -43,12 +43,20 @@ class PreferencesHelper(val context: Context) { private val flowPrefs = FlowSharedPreferences(prefs) private val defaultDownloadsDir = Uri.fromFile( - File(Environment.getExternalStorageDirectory().absolutePath + File.separator + - context.getString(R.string.app_name), "downloads")) + File( + Environment.getExternalStorageDirectory().absolutePath + File.separator + + context.getString(R.string.app_name), + "downloads" + ) + ) private val defaultBackupDir = Uri.fromFile( - File(Environment.getExternalStorageDirectory().absolutePath + File.separator + - context.getString(R.string.app_name), "backup")) + File( + Environment.getExternalStorageDirectory().absolutePath + File.separator + + context.getString(R.string.app_name), + "backup" + ) + ) fun getInt(key: String, default: Int?) = rxPrefs.getInteger(key, default) fun getStringPref(key: String, default: String?) = rxPrefs.getString(key, default) @@ -130,9 +138,9 @@ class PreferencesHelper(val context: Context) { fun setTrackCredentials(sync: TrackService, username: String, password: String) { prefs.edit() - .putString(Keys.trackUsername(sync.id), username) - .putString(Keys.trackPassword(sync.id), password) - .apply() + .putString(Keys.trackUsername(sync.id), username) + .putString(Keys.trackPassword(sync.id), password) + .apply() } fun trackToken(sync: TrackService) = rxPrefs.getString(Keys.trackToken(sync.id), "") diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackService.kt index 99ca915512..4b1df5a4a6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackService.kt @@ -60,7 +60,7 @@ abstract class TrackService(val id: Int) { open val isLogged: Boolean get() = getUsername().isNotEmpty() && - getPassword().isNotEmpty() + getPassword().isNotEmpty() fun getUsername() = preferences.trackUsername(this)!! diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistApi.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistApi.kt index dbdd603764..71b9c76ca6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistApi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistApi.kt @@ -237,7 +237,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { .appendQueryParameter("response_type", "token") .build()!! - fun addToLibraryQuery() = """ + fun addToLibraryQuery() = + """ |mutation AddManga(${'$'}mangaId: Int, ${'$'}progress: Int, ${'$'}status: MediaListStatus) { |SaveMediaListEntry (mediaId: ${'$'}mangaId, progress: ${'$'}progress, status: ${'$'}status) { | id @@ -246,7 +247,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { |} |""".trimMargin() - fun deleteFromLibraryQuery() = """ + fun deleteFromLibraryQuery() = + """ |mutation DeleteManga(${'$'}listId: Int) { |DeleteMediaListEntry (id: ${'$'}listId) { |deleted @@ -254,7 +256,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { |} |}""".trimMargin() - fun updateInLibraryQuery() = """ + fun updateInLibraryQuery() = + """ |mutation UpdateManga(${'$'}listId: Int, ${'$'}progress: Int, ${'$'}status: MediaListStatus, ${'$'}score: Int) { |SaveMediaListEntry (id: ${'$'}listId, progress: ${'$'}progress, status: ${'$'}status, scoreRaw: ${'$'}score) { |id @@ -264,7 +267,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { |} |""".trimMargin() - fun searchQuery() = """ + fun searchQuery() = + """ |query Search(${'$'}query: String) { |Page (perPage: 50) { |media(search: ${'$'}query, type: MANGA, format_not_in: [NOVEL]) { @@ -289,7 +293,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { |} |""".trimMargin() - fun findLibraryMangaQuery() = """ + fun findLibraryMangaQuery() = + """ |query (${'$'}id: Int!, ${'$'}manga_id: Int!) { |Page { |mediaList(userId: ${'$'}id, type: MANGA, mediaId: ${'$'}manga_id) { @@ -320,7 +325,8 @@ class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { |} |""".trimMargin() - fun currentUserQuery() = """ + fun currentUserQuery() = + """ |query User { |Viewer { |id diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistInterceptor.kt index 8c9e33bf89..c9f80a15f9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistInterceptor.kt @@ -38,8 +38,8 @@ class AnilistInterceptor(private val anilist: Anilist, private var token: String // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() - .addHeader("Authorization", "Bearer ${oauth!!.access_token}") - .build() + .addHeader("Authorization", "Bearer ${oauth!!.access_token}") + .build() return chain.proceed(authRequest) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiInterceptor.kt index 261f997524..4f7e19424d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiInterceptor.kt @@ -36,25 +36,28 @@ class BangumiInterceptor(val bangumi: Bangumi, val gson: Gson) : Interceptor { } val authRequest = if (originalRequest.method == "GET") originalRequest.newBuilder() - .header("User-Agent", "Tachiyomi") - .url(originalRequest.url.newBuilder() - .addQueryParameter("access_token", currAuth.access_token).build()) - .build() else originalRequest.newBuilder() - .post(addTocken(currAuth.access_token, originalRequest.body as FormBody)) - .header("User-Agent", "Tachiyomi") - .build() + .header("User-Agent", "Tachiyomi") + .url( + originalRequest.url.newBuilder() + .addQueryParameter("access_token", currAuth.access_token).build() + ) + .build() else originalRequest.newBuilder() + .post(addTocken(currAuth.access_token, originalRequest.body as FormBody)) + .header("User-Agent", "Tachiyomi") + .build() return chain.proceed(authRequest) } fun newAuth(oauth: OAuth) { this.oauth = OAuth( - oauth.access_token, - oauth.token_type, - System.currentTimeMillis() / 1000, - oauth.expires_in, - oauth.refresh_token, - this.oauth?.user_id) + oauth.access_token, + oauth.token_type, + System.currentTimeMillis() / 1000, + oauth.expires_in, + oauth.refresh_token, + this.oauth?.user_id + ) bangumi.saveToken(oauth) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt index 5045677e9c..7601630f35 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt @@ -20,8 +20,8 @@ data class OAuth( val refresh_token: String?, val user_id: Long? ) { - // Access token refresh before expired - fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) + // Access token refresh before expired + fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) } data class Status( diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt index 1f1d4e8f2a..0e4dc070cb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt @@ -30,10 +30,10 @@ class KitsuInterceptor(val kitsu: Kitsu, val gson: Gson) : Interceptor { // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() - .addHeader("Authorization", "Bearer ${oauth!!.access_token}") - .header("Accept", "application/vnd.api+json") - .header("Content-Type", "application/vnd.api+json") - .build() + .addHeader("Authorization", "Bearer ${oauth!!.access_token}") + .header("Accept", "application/vnd.api+json") + .header("Content-Type", "application/vnd.api+json") + .build() return chain.proceed(authRequest) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriApi.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriApi.kt index 7968a1059a..0b5030ea54 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriApi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriApi.kt @@ -103,7 +103,7 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter val request = Request.Builder().url(url.toString()).get().build() val urlMangas = "$apiUrl/mangas".toUri().buildUpon().appendPath(track.media_id.toString()) - .build() + .build() val requestMangas = Request.Builder().url(urlMangas.toString()).get().build() val requestMangasResponse = authClient.newCall(requestMangas).execute() diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt index 6e10b4de3d..0a2688d70f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt @@ -29,9 +29,9 @@ class ShikimoriInterceptor(val shikimori: Shikimori, val gson: Gson) : Intercept } // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() - .addHeader("Authorization", "Bearer ${oauth!!.access_token}") - .header("User-Agent", "Tachiyomi") - .build() + .addHeader("Authorization", "Bearer ${oauth!!.access_token}") + .header("User-Agent", "Tachiyomi") + .build() return chain.proceed(authRequest) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterJob.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterJob.kt index a0c89b83bb..f6a16fbe5f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterJob.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterJob.kt @@ -44,7 +44,10 @@ class UpdaterJob(private val context: Context, workerParams: WorkerParameters) : android.R.drawable.stat_sys_download_done, context.getString(R.string.download), PendingIntent.getService( - context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT + context, + 0, + intent, + PendingIntent.FLAG_UPDATE_CURRENT ) ) } @@ -62,15 +65,18 @@ class UpdaterJob(private val context: Context, workerParams: WorkerParameters) : fun setupTask() { val constraints = Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) - .build() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() val request = PeriodicWorkRequestBuilder( - 1, TimeUnit.DAYS, - 1, TimeUnit.HOURS) - .addTag(TAG) - .setConstraints(constraints) - .build() + 1, + TimeUnit.DAYS, + 1, + TimeUnit.HOURS + ) + .addTag(TAG) + .setConstraints(constraints) + .build() WorkManager.getInstance().enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterNotifier.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterNotifier.kt index 64c4b97356..f13b5aab70 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterNotifier.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterNotifier.kt @@ -75,13 +75,17 @@ internal class UpdaterNotifier(private val context: Context) { setProgress(0, 0, false) // Install action setContentIntent(NotificationHandler.installApkPendingActivity(context, uri)) - addAction(R.drawable.ic_system_update_24dp, - context.getString(R.string.install), - NotificationHandler.installApkPendingActivity(context, uri)) + addAction( + R.drawable.ic_system_update_24dp, + context.getString(R.string.install), + NotificationHandler.installApkPendingActivity(context, uri) + ) // Cancel action - addAction(R.drawable.ic_close_24dp, - context.getString(R.string.cancel), - NotificationReceiver.dismissNotificationPendingBroadcast(context, Notifications.ID_UPDATER)) + addAction( + R.drawable.ic_close_24dp, + context.getString(R.string.cancel), + NotificationReceiver.dismissNotificationPendingBroadcast(context, Notifications.ID_UPDATER) + ) } notification.show() } @@ -99,13 +103,17 @@ internal class UpdaterNotifier(private val context: Context) { setProgress(0, 0, false) color = ContextCompat.getColor(context, R.color.colorAccent) // Retry action - addAction(R.drawable.ic_refresh_24dp, - context.getString(R.string.retry), - UpdaterService.downloadApkPendingService(context, url)) + addAction( + R.drawable.ic_refresh_24dp, + context.getString(R.string.retry), + UpdaterService.downloadApkPendingService(context, url) + ) // Cancel action - addAction(R.drawable.ic_close_24dp, - context.getString(R.string.cancel), - NotificationReceiver.dismissNotificationPendingBroadcast(context, Notifications.ID_UPDATER)) + addAction( + R.drawable.ic_close_24dp, + context.getString(R.string.cancel), + NotificationReceiver.dismissNotificationPendingBroadcast(context, Notifications.ID_UPDATER) + ) } notification.show(Notifications.ID_UPDATER) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterService.kt index 5ce2c45558..eb5a3be1bf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdaterService.kt @@ -43,7 +43,8 @@ class UpdaterService : Service() { startForeground(Notifications.ID_UPDATER, notifier.onDownloadStarted(getString(R.string.app_name)).build()) wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, "${javaClass.name}:WakeLock" + PowerManager.PARTIAL_WAKE_LOCK, + "${javaClass.name}:WakeLock" ) wakeLock.acquire() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubService.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubService.kt index 8f9a4857bd..de3032b5af 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubService.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubService.kt @@ -15,10 +15,10 @@ interface GithubService { companion object { fun create(): GithubService { val restAdapter = Retrofit.Builder() - .baseUrl("https://api.github.com") - .addConverterFactory(GsonConverterFactory.create()) - .client(Injekt.get().client) - .build() + .baseUrl("https://api.github.com") + .addConverterFactory(GsonConverterFactory.create()) + .client(Injekt.get().client) + .build() return restAdapter.create(GithubService::class.java) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateChecker.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateChecker.kt index f90d8c8179..5da5fac945 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateChecker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateChecker.kt @@ -4,7 +4,7 @@ import eu.kanade.tachiyomi.BuildConfig import eu.kanade.tachiyomi.data.updater.UpdateChecker import eu.kanade.tachiyomi.data.updater.UpdateResult - class GithubUpdateChecker : UpdateChecker() { +class GithubUpdateChecker : UpdateChecker() { private val service: GithubService = GithubService.create() diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt index 7a50c38730..6c07f88411 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt @@ -80,8 +80,7 @@ class ExtensionManager( context.packageManager.getApplicationIcon(pkgName) } catch (e: Exception) { null - } - else null + } else null } /** @@ -136,16 +135,16 @@ class ExtensionManager( val extensions = ExtensionLoader.loadExtensions(context) installedExtensions = extensions - .filterIsInstance() - .map { it.extension } + .filterIsInstance() + .map { it.extension } installedExtensions - .flatMap { it.sources } - // overwrite is needed until the bundled sources are removed - .forEach { sourceManager.registerSource(it, true) } + .flatMap { it.sources } + // overwrite is needed until the bundled sources are removed + .forEach { sourceManager.registerSource(it, true) } untrustedExtensions = extensions - .filterIsInstance() - .map { it.extension } + .filterIsInstance() + .map { it.extension } } /** @@ -251,7 +250,7 @@ class ExtensionManager( */ fun updateExtension(extension: Extension.Installed): Observable { val availableExt = availableExtensions.find { it.pkgName == extension.pkgName } - ?: return Observable.empty() + ?: return Observable.empty() return installExtension(availableExt) } @@ -296,10 +295,10 @@ class ExtensionManager( nowTrustedExtensions.map { extension -> async { ExtensionLoader.loadExtensionFromPkgName(ctx, extension.pkgName) } }.map { it.await() }.forEach { result -> - if (result is LoadResult.Success) { - registerNewExtension(result.extension) - } + if (result is LoadResult.Success) { + registerNewExtension(result.extension) } + } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt index b8f7f5a94a..795ac690d4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt @@ -45,12 +45,15 @@ class ExtensionUpdateJob(private val context: Context, workerParams: WorkerParam val preferences: PreferencesHelper by injectLazy() preferences.extensionUpdatesCount().set(names.size) NotificationManagerCompat.from(context).apply { - notify(Notifications.ID_UPDATES_TO_EXTS, + notify( + Notifications.ID_UPDATES_TO_EXTS, context.notification(Notifications.CHANNEL_UPDATES_TO_EXTS) { setContentTitle( context.resources.getQuantityString( - R.plurals.extension_updates_available, names - .size, names.size + R.plurals.extension_updates_available, + names + .size, + names.size ) ) val extNames = names.joinToString(", ") @@ -64,7 +67,8 @@ class ExtensionUpdateJob(private val context: Context, workerParams: WorkerParam ) ) setAutoCancel(true) - }) + } + ) } } @@ -80,8 +84,11 @@ class ExtensionUpdateJob(private val context: Context, workerParams: WorkerParam .build() val request = PeriodicWorkRequestBuilder( - 12, TimeUnit.HOURS, - 1, TimeUnit.HOURS) + 12, + TimeUnit.HOURS, + 1, + TimeUnit.HOURS + ) .addTag(TAG) .setConstraints(constraints) .build() diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallActivity.kt index db2f726ea2..1623a5d7d6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallActivity.kt @@ -18,9 +18,9 @@ class ExtensionInstallActivity : Activity() { super.onCreate(savedInstanceState) val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) - .setDataAndType(intent.data, intent.type) - .putExtra(Intent.EXTRA_RETURN_RESULT, true) - .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + .setDataAndType(intent.data, intent.type) + .putExtra(Intent.EXTRA_RETURN_RESULT, true) + .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) try { startActivityForResult(installIntent, INSTALL_REQUEST_CODE) diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt index ed84370de7..43ff15310c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallReceiver.kt @@ -19,7 +19,7 @@ import kotlinx.coroutines.async * @param listener The listener that should be notified of extension installation events. */ internal class ExtensionInstallReceiver(private val listener: Listener) : - BroadcastReceiver() { + BroadcastReceiver() { /** * Registers this broadcast receiver @@ -94,7 +94,7 @@ internal class ExtensionInstallReceiver(private val listener: Listener) : */ private suspend fun getExtensionFromIntent(context: Context, intent: Intent?): LoadResult { val pkgName = getPackageNameFromIntent(intent) - ?: return LoadResult.Error("Package name not found") + ?: return LoadResult.Error("Package name not found") return GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) { ExtensionLoader.loadExtensionFromPkgName(context, pkgName) }.await() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstaller.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstaller.kt index 64d717a973..a58543d220 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstaller.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstaller.kt @@ -144,7 +144,7 @@ internal class ExtensionInstaller(private val context: Context) { fun uninstallApk(pkgName: String) { val packageUri = "package:$pkgName".toUri() val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionLoader.kt index 29525d8159..8ba9847fba 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionLoader.kt @@ -36,9 +36,9 @@ internal object ExtensionLoader { * List of the trusted signatures. */ var trustedSignatures = mutableSetOf() + - Injekt.get().trustedSignatures().getOrDefault() + - // inorichi's key - "7ce04da7773d41b489f4693a366c36bcd0a11fc39b547168553c285bd7348e23" + Injekt.get().trustedSignatures().getOrDefault() + + // inorichi's key + "7ce04da7773d41b489f4693a366c36bcd0a11fc39b547168553c285bd7348e23" /** * Return a list of all the installed extensions initialized concurrently. @@ -103,8 +103,10 @@ internal object ExtensionLoader { // Validate lib version val majorLibVersion = versionName.substringBefore('.').toInt() if (majorLibVersion < LIB_VERSION_MIN || majorLibVersion > LIB_VERSION_MAX) { - val exception = Exception("Lib version is $majorLibVersion, while only versions " + - "$LIB_VERSION_MIN to $LIB_VERSION_MAX are allowed") + val exception = Exception( + "Lib version is $majorLibVersion, while only versions " + + "$LIB_VERSION_MIN to $LIB_VERSION_MAX are allowed" + ) Timber.w(exception) return LoadResult.Error(exception) } @@ -122,30 +124,30 @@ internal object ExtensionLoader { val classLoader = PathClassLoader(appInfo.sourceDir, null, context.classLoader) val sources = appInfo.metaData.getString(METADATA_SOURCE_CLASS)!! - .split(";") - .map { - val sourceClass = it.trim() - if (sourceClass.startsWith(".")) - pkgInfo.packageName + sourceClass - else - sourceClass - } - .flatMap { - try { - val obj = Class.forName(it, false, classLoader).newInstance() - when (obj) { - is Source -> listOf(obj) - is SourceFactory -> obj.createSources() - else -> throw Exception("Unknown source class type! ${obj.javaClass}") - } - } catch (e: Throwable) { - Timber.e(e, "Extension load error: $extName.") - return LoadResult.Error(e) + .split(";") + .map { + val sourceClass = it.trim() + if (sourceClass.startsWith(".")) + pkgInfo.packageName + sourceClass + else + sourceClass + } + .flatMap { + try { + val obj = Class.forName(it, false, classLoader).newInstance() + when (obj) { + is Source -> listOf(obj) + is SourceFactory -> obj.createSources() + else -> throw Exception("Unknown source class type! ${obj.javaClass}") } + } catch (e: Throwable) { + Timber.e(e, "Extension load error: $extName.") + return LoadResult.Error(e) } + } val langs = sources.filterIsInstance() - .map { it.lang } - .toSet() + .map { it.lang } + .toSet() val lang = when (langs.size) { 0 -> "" diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt index a652e2ba1e..975ae6250b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt @@ -58,17 +58,19 @@ fun Call.asObservable(): Observable { // Based on https://github.com/gildor/kotlin-coroutines-okhttp suspend fun Call.await(): Response { return suspendCancellableCoroutine { continuation -> - enqueue(object : Callback { - override fun onResponse(call: Call, response: Response) { - continuation.resume(response) - } + enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + continuation.resume(response) + } - override fun onFailure(call: Call, e: IOException) { - // Don't bother with resuming the continuation if it is already cancelled. - if (continuation.isCancelled) return - continuation.resumeWithException(e) + override fun onFailure(call: Call, e: IOException) { + // Don't bother with resuming the continuation if it is already cancelled. + if (continuation.isCancelled) return + continuation.resumeWithException(e) + } } - }) + ) continuation.invokeOnCancellation { try { @@ -91,14 +93,14 @@ fun Call.asObservableSuccess(): Observable { fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListener): Call { val progressClient = newBuilder() - .cache(null) - .addNetworkInterceptor { chain -> - val originalResponse = chain.proceed(chain.request()) - originalResponse.newBuilder() - .body(ProgressResponseBody(originalResponse.body!!, listener)) - .build() - } - .build() + .cache(null) + .addNetworkInterceptor { chain -> + val originalResponse = chain.proceed(chain.request()) + originalResponse.newBuilder() + .body(ProgressResponseBody(originalResponse.body!!, listener)) + .build() + } + .build() return progressClient.newCall(request) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt b/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt index 5ed56dcb2e..f9ac33edbd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt @@ -18,10 +18,10 @@ fun GET( ): Request { return Request.Builder() - .url(url) - .headers(headers) - .cacheControl(cache) - .build() + .url(url) + .headers(headers) + .cacheControl(cache) + .build() } fun POST( @@ -32,9 +32,9 @@ fun POST( ): Request { return Request.Builder() - .url(url) - .post(body) - .headers(headers) - .cacheControl(cache) - .build() + .url(url) + .post(body) + .headers(headers) + .cacheControl(cache) + .build() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/UserAgentInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/network/UserAgentInterceptor.kt index 52d37a77aa..a5aa3e4f51 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/UserAgentInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/UserAgentInterceptor.kt @@ -10,10 +10,10 @@ class UserAgentInterceptor : Interceptor { return if (originalRequest.header("User-Agent").isNullOrEmpty()) { val newRequest = originalRequest - .newBuilder() - .removeHeader("User-Agent") - .addHeader("User-Agent", HttpSource.DEFAULT_USERAGENT) - .build() + .newBuilder() + .removeHeader("User-Agent") + .addHeader("User-Agent", HttpSource.DEFAULT_USERAGENT) + .build() chain.proceed(newRequest) } else { chain.proceed(originalRequest) diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt b/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt index 692fc11514..5b68d14d4d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt @@ -143,7 +143,7 @@ class LocalSource(private val context: Context) : CatalogueSource { override fun fetchMangaDetails(manga: SManga): Observable { val baseDirs = getBaseDirectories(context) - baseDirs + baseDirs .mapNotNull { File(it, manga.url).listFiles()?.toList() } .flatten() .filter { it.extension == "json" }.firstOrNull()?.apply { @@ -241,10 +241,12 @@ class LocalSource(private val context: Context) : CatalogueSource { date_upload = chapterFile.lastModified() ChapterRecognition.parseChapterNumber(this, manga) } - }.sortedWith(Comparator { c1, c2 -> - val c = c2.chapter_number.compareTo(c1.chapter_number) - if (c == 0) c2.name.compareToCaseInsensitiveNaturalOrder(c1.name) else c - }) + }.sortedWith( + Comparator { c1, c2 -> + val c = c2.chapter_number.compareTo(c1.chapter_number) + if (c == 0) c2.name.compareToCaseInsensitiveNaturalOrder(c1.name) else c + } + ) return Observable.just(chapters) } @@ -289,18 +291,22 @@ class LocalSource(private val context: Context) : CatalogueSource { return when (format) { is Format.Directory -> { val entry = format.file.listFiles() - ?.sortedWith(Comparator { f1, f2 -> - f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) - }) + ?.sortedWith( + Comparator { f1, f2 -> + f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) + } + ) ?.find { !it.isDirectory && ImageUtil.isImage(it.name) { FileInputStream(it) } } entry?.let { updateCover(context, manga, it.inputStream()) } } is Format.Zip -> { ZipFile(format.file).use { zip -> - val entry = zip.entries().toList().sortedWith(Comparator { f1, f2 -> - f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) - }).find { + val entry = zip.entries().toList().sortedWith( + Comparator { f1, f2 -> + f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) + } + ).find { !it.isDirectory && ImageUtil.isImage(it.name) { zip.getInputStream(it) } @@ -311,9 +317,11 @@ class LocalSource(private val context: Context) : CatalogueSource { } is Format.Rar -> { Archive(format.file).use { archive -> - val entry = archive.fileHeaders.sortedWith(Comparator { f1, f2 -> - f1.fileNameString.compareToCaseInsensitiveNaturalOrder(f2.fileNameString) - }).find { + val entry = archive.fileHeaders.sortedWith( + Comparator { f1, f2 -> + f1.fileNameString.compareToCaseInsensitiveNaturalOrder(f2.fileNameString) + } + ).find { !it.isDirectory && ImageUtil.isImage(it.fileNameString) { archive.getInputStream(it) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/SourceManager.kt b/app/src/main/java/eu/kanade/tachiyomi/source/SourceManager.kt index 8ba52becb6..fc0caa99f0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/SourceManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/SourceManager.kt @@ -21,13 +21,24 @@ open class SourceManager(private val context: Context) { private val delegatedSources = listOf( DelegatedSource( - "reader.kireicake.com", 5509224355268673176, KireiCake() - ), DelegatedSource( - "jaiminisbox.com", 9064882169246918586, FoolSlide("jaiminis", "/reader") - ), DelegatedSource( - "mangadex.org", 2499283573021220255, MangaDex() - ), DelegatedSource( - "mangaplus.shueisha.co.jp", 1998944621602463790, MangaPlus() + "reader.kireicake.com", + 5509224355268673176, + KireiCake() + ), + DelegatedSource( + "jaiminisbox.com", + 9064882169246918586, + FoolSlide("jaiminis", "/reader") + ), + DelegatedSource( + "mangadex.org", + 2499283573021220255, + MangaDex() + ), + DelegatedSource( + "mangaplus.shueisha.co.jp", + 1998944621602463790, + MangaPlus() ) ).associateBy { it.sourceId } @@ -92,8 +103,10 @@ open class SourceManager(private val context: Context) { private fun getSourceNotInstalledException(): Exception { return SourceNotFoundException( context.getString( - R.string.source_not_installed_, id.toString() - ), id + R.string.source_not_installed_, + id.toString() + ), + id ) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt index 259ea92f0b..9d0784056b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt @@ -90,10 +90,10 @@ abstract class HttpSource : CatalogueSource { */ override fun fetchPopularManga(page: Int): Observable { return client.newCall(popularMangaRequest(page)) - .asObservableSuccess() - .map { response -> - popularMangaParse(response) - } + .asObservableSuccess() + .map { response -> + popularMangaParse(response) + } } /** @@ -120,10 +120,10 @@ abstract class HttpSource : CatalogueSource { */ override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable { return client.newCall(searchMangaRequest(page, query, filters)) - .asObservableSuccess() - .map { response -> - searchMangaParse(response) - } + .asObservableSuccess() + .map { response -> + searchMangaParse(response) + } } /** @@ -149,10 +149,10 @@ abstract class HttpSource : CatalogueSource { */ override fun fetchLatestUpdates(page: Int): Observable { return client.newCall(latestUpdatesRequest(page)) - .asObservableSuccess() - .map { response -> - latestUpdatesParse(response) - } + .asObservableSuccess() + .map { response -> + latestUpdatesParse(response) + } } /** @@ -177,10 +177,10 @@ abstract class HttpSource : CatalogueSource { */ override fun fetchMangaDetails(manga: SManga): Observable { return client.newCall(mangaDetailsRequest(manga)) - .asObservableSuccess() - .map { response -> - mangaDetailsParse(response).apply { initialized = true } - } + .asObservableSuccess() + .map { response -> + mangaDetailsParse(response).apply { initialized = true } + } } /** @@ -209,10 +209,10 @@ abstract class HttpSource : CatalogueSource { override fun fetchChapterList(manga: SManga): Observable> { return if (manga.status != SManga.LICENSED) { client.newCall(chapterListRequest(manga)) - .asObservableSuccess() - .map { response -> - chapterListParse(response) - } + .asObservableSuccess() + .map { response -> + chapterListParse(response) + } } else { Observable.error(Exception("Licensed - No chapters to show")) } @@ -242,10 +242,10 @@ abstract class HttpSource : CatalogueSource { */ override fun fetchPageList(chapter: SChapter): Observable> { return client.newCall(pageListRequest(chapter)) - .asObservableSuccess() - .map { response -> - pageListParse(response) - } + .asObservableSuccess() + .map { response -> + pageListParse(response) + } } /** @@ -273,8 +273,8 @@ abstract class HttpSource : CatalogueSource { */ open fun fetchImageUrl(page: Page): Observable { return client.newCall(imageUrlRequest(page)) - .asObservableSuccess() - .map { imageUrlParse(it) } + .asObservableSuccess() + .map { imageUrlParse(it) } } /** @@ -301,7 +301,7 @@ abstract class HttpSource : CatalogueSource { */ fun fetchImage(page: Page): Observable { return client.newCallWithProgress(imageRequest(page), page) - .asObservableSuccess() + .asObservableSuccess() } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt index 2c8f2d0b85..7b3ea4bdec 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt @@ -14,12 +14,12 @@ fun HttpSource.getImageUrl(page: Page): Observable { fun HttpSource.fetchAllImageUrlsFromPageList(pages: List): Observable { return Observable.from(pages) - .filter { !it.imageUrl.isNullOrEmpty() } - .mergeWith(fetchRemainingImageUrlsFromPageList(pages)) + .filter { !it.imageUrl.isNullOrEmpty() } + .mergeWith(fetchRemainingImageUrlsFromPageList(pages)) } fun HttpSource.fetchRemainingImageUrlsFromPageList(pages: List): Observable { return Observable.from(pages) - .filter { it.imageUrl.isNullOrEmpty() } - .concatMap { getImageUrl(it) } + .filter { it.imageUrl.isNullOrEmpty() } + .concatMap { getImageUrl(it) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/FoolSlide.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/FoolSlide.kt index 9edbaac03f..6101772e07 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/FoolSlide.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/FoolSlide.kt @@ -21,7 +21,7 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get open class FoolSlide(override val domainName: String, private val urlModifier: String = "") : -DelegatedHttpSource + DelegatedHttpSource () { override fun canOpenUrl(uri: Uri): Boolean = true @@ -34,7 +34,11 @@ DelegatedHttpSource val chapterNumber = uri.pathSegments.getOrNull(4 + offset) ?: return null val subChapterNumber = uri.pathSegments.getOrNull(5 + offset)?.toIntOrNull()?.toString() return "$urlModifier/read/" + listOfNotNull( - mangaName, lang, volume, chapterNumber, subChapterNumber + mangaName, + lang, + volume, + chapterNumber, + subChapterNumber ).joinToString("/") + "/" } @@ -95,8 +99,11 @@ DelegatedHttpSource private fun allowAdult(request: Request) = allowAdult(request.url.toString()) private fun allowAdult(url: String): Request { - return POST(url, body = FormBody.Builder() - .add("adult", "true") - .build()) + return POST( + url, + body = FormBody.Builder() + .add("adult", "true") + .build() + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/KireiCake.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/KireiCake.kt index 31d6f1a3fe..05048c30e2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/KireiCake.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/KireiCake.kt @@ -17,9 +17,8 @@ class KireiCake : FoolSlide("kireicake") { this.url = url source = delegate?.id ?: -1 title = document.select("$mangaDetailsInfoSelector li:has(b:contains(title))").first() - ?.ownText()?.substringAfter(":")?.trim() ?: url.split("/").last().replace( - "_", " " + "" - ).capitalizeWords() + ?.ownText()?.substringAfter(":")?.trim() + ?: url.split("/").last().replace("_", " " + "").capitalizeWords() description = document.select("$mangaDetailsInfoSelector li:has(b:contains(description))").first() ?.ownText()?.substringAfter(":") diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/MangaPlus.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/MangaPlus.kt index 24877d08be..e1e71fdfcd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/english/MangaPlus.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/english/MangaPlus.kt @@ -61,9 +61,13 @@ class MangaPlus : DelegatedHttpSource() { context.getString(R.string.chapter_not_found) ) if (manga != null) { - Triple(trueChapter, manga.apply { - this.title = trimmedTitle - }, chapters.orEmpty()) + Triple( + trueChapter, + manga.apply { + this.title = trimmedTitle + }, + chapters.orEmpty() + ) } else null } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/CenteredToolbar.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/CenteredToolbar.kt index db606905f9..fb6fd22176 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/CenteredToolbar.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/CenteredToolbar.kt @@ -33,12 +33,16 @@ class CenteredToolbar@JvmOverloads constructor(context: Context, attrs: Attribut } fun showDropdown(down: Boolean = true) { - toolbar_title.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_blank_24dp, 0, - if (down) { - R.drawable.ic_arrow_drop_down_24dp - } else { - R.drawable.ic_arrow_drop_up_24dp - }, 0) + toolbar_title.setCompoundDrawablesRelativeWithIntrinsicBounds( + R.drawable.ic_blank_24dp, + 0, + if (down) { + R.drawable.ic_arrow_drop_down_24dp + } else { + R.drawable.ic_arrow_drop_up_24dp + }, + 0 + ) } fun hideDropdown() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialFastScroll.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialFastScroll.kt index 69581b342e..746623609e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialFastScroll.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialFastScroll.kt @@ -21,7 +21,9 @@ class MaterialFastScroll @JvmOverloads constructor(context: Context, attrs: Attr var scrollOffset = 0 init { setViewsToUse( - R.layout.material_fastscroll, R.id.fast_scroller_bubble, R.id.fast_scroller_handle + R.layout.material_fastscroll, + R.id.fast_scroller_bubble, + R.id.fast_scroller_handle ) autoHideEnabled = true ignoreTouchesOutsideHandle = false @@ -85,7 +87,8 @@ class MaterialFastScroll @JvmOverloads constructor(context: Context, attrs: Attr val targetPos = getTargetPos(y) if (layoutManager is StaggeredGridLayoutManager) { (layoutManager as StaggeredGridLayoutManager).scrollToPositionWithOffset( - targetPos, scrollOffset + targetPos, + scrollOffset ) } else { (layoutManager as LinearLayoutManager).scrollToPositionWithOffset(targetPos, scrollOffset) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialMenuSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialMenuSheet.kt index a614b57c22..9e189cb72b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialMenuSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/MaterialMenuSheet.kt @@ -119,7 +119,10 @@ class MaterialMenuSheet( isElevated = elevate elevationAnimator?.cancel() elevationAnimator = ObjectAnimator.ofFloat( - title_layout, "elevation", title_layout.elevation, if (elevate) 10f else 0f + title_layout, + "elevation", + title_layout.elevation, + if (elevate) 10f else 0f ) elevationAnimator?.start() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt index 1fcec6214d..1641b637f1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/BaseController.kt @@ -14,31 +14,34 @@ import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.* import timber.log.Timber -abstract class BaseController(bundle: Bundle? = null) : RestoreViewOnCreateController(bundle), - LayoutContainer { +abstract class BaseController(bundle: Bundle? = null) : + RestoreViewOnCreateController(bundle), + LayoutContainer { init { - addLifecycleListener(object : LifecycleListener() { - override fun postCreateView(controller: Controller, view: View) { - onViewCreated(view) - } + addLifecycleListener( + object : LifecycleListener() { + override fun postCreateView(controller: Controller, view: View) { + onViewCreated(view) + } - override fun preCreateView(controller: Controller) { - Timber.d("Create view for ${controller.instance()}") - } + override fun preCreateView(controller: Controller) { + Timber.d("Create view for ${controller.instance()}") + } - override fun preAttach(controller: Controller, view: View) { - Timber.d("Attach view for ${controller.instance()}") - } + override fun preAttach(controller: Controller, view: View) { + Timber.d("Attach view for ${controller.instance()}") + } - override fun preDetach(controller: Controller, view: View) { - Timber.d("Detach view for ${controller.instance()}") - } + override fun preDetach(controller: Controller, view: View) { + Timber.d("Detach view for ${controller.instance()}") + } - override fun preDestroyView(controller: Controller, view: View) { - Timber.d("Destroy view for ${controller.instance()}") + override fun preDestroyView(controller: Controller, view: View) { + Timber.d("Destroy view for ${controller.instance()}") + } } - }) + ) } override val containerView: View? @@ -96,17 +99,19 @@ abstract class BaseController(bundle: Bundle? = null) : RestoreViewOnCreateContr */ var expandActionViewFromInteraction = false fun MenuItem.fixExpand(onExpand: ((MenuItem) -> Boolean)? = null, onCollapse: ((MenuItem) -> Boolean)? = null) { - setOnActionExpandListener(object : MenuItem.OnActionExpandListener { - override fun onMenuItemActionExpand(item: MenuItem): Boolean { - return onExpand?.invoke(item) ?: true - } + setOnActionExpandListener( + object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem): Boolean { + return onExpand?.invoke(item) ?: true + } - override fun onMenuItemActionCollapse(item: MenuItem): Boolean { - activity?.invalidateOptionsMenu() + override fun onMenuItemActionCollapse(item: MenuItem): Boolean { + activity?.invalidateOptionsMenu() - return onCollapse?.invoke(item) ?: true + return onCollapse?.invoke(item) ?: true + } } - }) + ) if (expandActionViewFromInteraction) { expandActionViewFromInteraction = false diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt index 4388fa8d1d..9fecbecda4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt @@ -87,10 +87,12 @@ abstract class DialogController : RestoreViewOnCreateController { */ fun showDialog(router: Router, tag: String?) { dismissed = false - router.pushController(RouterTransaction.with(this) + router.pushController( + RouterTransaction.with(this) .pushChangeHandler(SimpleSwapChangeHandler(false)) .popChangeHandler(SimpleSwapChangeHandler(false)) - .tag(tag)) + .tag(tag) + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/NucleusController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/NucleusController.kt index 5a9250d87c..b3c592dfa5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/NucleusController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/NucleusController.kt @@ -7,8 +7,9 @@ import nucleus.factory.PresenterFactory import nucleus.presenter.Presenter @Suppress("LeakingThis") -abstract class NucleusController

>(val bundle: Bundle? = null) : RxController(bundle), - PresenterFactory

{ +abstract class NucleusController

>(val bundle: Bundle? = null) : + RxController(bundle), + PresenterFactory

{ private val delegate = NucleusConductorDelegate(this) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseFlexibleViewHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseFlexibleViewHolder.kt index c4953b85d6..79f3455fe6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseFlexibleViewHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseFlexibleViewHolder.kt @@ -10,7 +10,7 @@ abstract class BaseFlexibleViewHolder( adapter: FlexibleAdapter<*>, stickyHeader: Boolean = false ) : - FlexibleViewHolder(view, adapter, stickyHeader), LayoutContainer { + FlexibleViewHolder(view, adapter, stickyHeader), LayoutContainer { override val containerView: View? get() = itemView diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/BasePresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/BasePresenter.kt index 74375832a9..29d2ae9eb5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/BasePresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/BasePresenter.kt @@ -24,7 +24,7 @@ open class BasePresenter : RxPresenter() { * @param onError function to execute when the observable throws an error. */ fun Observable.subscribeFirst(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = - compose(deliverFirst()).subscribe(split(onNext, onError)).apply { add(this) } + compose(deliverFirst()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [deliverLatestCache] and adds it to the presenter's lifecycle @@ -34,7 +34,7 @@ open class BasePresenter : RxPresenter() { * @param onError function to execute when the observable throws an error. */ fun Observable.subscribeLatestCache(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = - compose(deliverLatestCache()).subscribe(split(onNext, onError)).apply { add(this) } + compose(deliverLatestCache()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [deliverReplay] and adds it to the presenter's lifecycle @@ -44,7 +44,7 @@ open class BasePresenter : RxPresenter() { * @param onError function to execute when the observable throws an error. */ fun Observable.subscribeReplay(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = - compose(deliverReplay()).subscribe(split(onNext, onError)).apply { add(this) } + compose(deliverReplay()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [DeliverWithView] and adds it to the presenter's lifecycle @@ -54,7 +54,7 @@ open class BasePresenter : RxPresenter() { * @param onError function to execute when the observable throws an error. */ fun Observable.subscribeWithView(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = - compose(DeliverWithView(view())).subscribe(split(onNext, onError)).apply { add(this) } + compose(DeliverWithView(view())).subscribe(split(onNext, onError)).apply { add(this) } /** * A deliverable that only emits to the view if attached, otherwise the event is ignored. @@ -63,11 +63,11 @@ open class BasePresenter : RxPresenter() { override fun call(observable: Observable): Observable> { return observable - .materialize() - .filter { notification -> !notification.isOnCompleted } - .flatMap { notification -> - view.take(1).filter { it != null }.map { Delivery(it, notification) } - } + .materialize() + .filter { notification -> !notification.isOnCompleted } + .flatMap { notification -> + view.take(1).filter { it != null }.map { Delivery(it, notification) } + } } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryAdapter.kt index c1ef5d5af6..b1783af770 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryAdapter.kt @@ -8,7 +8,7 @@ import eu.davidea.flexibleadapter.FlexibleAdapter * @param controller The containing controller. */ class CategoryAdapter(controller: CategoryController) : - FlexibleAdapter(null, controller, true) { + FlexibleAdapter(null, controller, true) { /** * Listener called when an item of the list is released. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt index 0c9b6b2474..06ea862f31 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt @@ -22,10 +22,11 @@ import kotlinx.android.synthetic.main.categories_controller.* /** * Controller to manage the categories for the users' library. */ -class CategoryController(bundle: Bundle? = null) : BaseController(bundle), - FlexibleAdapter.OnItemClickListener, - FlexibleAdapter.OnItemMoveListener, - CategoryAdapter.CategoryItemListener { +class CategoryController(bundle: Bundle? = null) : + BaseController(bundle), + FlexibleAdapter.OnItemClickListener, + FlexibleAdapter.OnItemMoveListener, + CategoryAdapter.CategoryItemListener { /** * Adapter containing category items. @@ -147,12 +148,14 @@ class CategoryController(bundle: Bundle? = null) : BaseController(bundle), adapter?.restoreDeletedItems() undoing = true } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!undoing) confirmDelete() + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!undoing) confirmDelete() + } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryHolder.kt index 8d0849a819..ca525c0b59 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryHolder.kt @@ -51,16 +51,22 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie createCategory = category.order == CREATE_CATEGORY_ORDER if (createCategory) { title.setTextColor(ContextCompat.getColor(itemView.context, R.color.text_color_hint)) - regularDrawable = ContextCompat.getDrawable(itemView.context, R.drawable - .ic_add_24dp) + regularDrawable = ContextCompat.getDrawable( + itemView.context, + R.drawable + .ic_add_24dp + ) image.gone() edit_button.setImageDrawable(null) edit_text.setText("") edit_text.hint = title.text } else { title.setTextColor(ContextCompat.getColor(itemView.context, R.color.textColorPrimary)) - regularDrawable = ContextCompat.getDrawable(itemView.context, R.drawable - .ic_drag_handle_24dp) + regularDrawable = ContextCompat.getDrawable( + itemView.context, + R.drawable + .ic_drag_handle_24dp + ) image.visible() edit_text.setText(title.text) } @@ -80,7 +86,8 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie if (!createCategory) { reorder.setImageDrawable( ContextCompat.getDrawable( - itemView.context, R.drawable.ic_delete_24dp + itemView.context, + R.drawable.ic_delete_24dp ) ) reorder.setOnClickListener { @@ -96,8 +103,13 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie reorder.setOnTouchListener { _, _ -> true } } edit_text.clearFocus() - edit_button.drawable?.mutate()?.setTint(ContextCompat.getColor(itemView.context, R - .color.gray_button)) + edit_button.drawable?.mutate()?.setTint( + ContextCompat.getColor( + itemView.context, + R + .color.gray_button + ) + ) reorder.setImageDrawable(regularDrawable) } } @@ -105,7 +117,8 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie private fun submitChanges() { if (edit_text.visibility == View.VISIBLE) { if (adapter.categoryItemListener - .onCategoryRename(adapterPosition, edit_text.text.toString())) { + .onCategoryRename(adapterPosition, edit_text.text.toString()) + ) { isEditing(false) edit_text.inputType = InputType.TYPE_NULL if (!createCategory) @@ -119,8 +132,11 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie private fun showKeyboard() { val inputMethodManager: InputMethodManager = itemView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - inputMethodManager.showSoftInput(edit_text, WindowManager.LayoutParams - .SOFT_INPUT_ADJUST_PAN) + inputMethodManager.showSoftInput( + edit_text, + WindowManager.LayoutParams + .SOFT_INPUT_ADJUST_PAN + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/ManageCategoryDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/ManageCategoryDialog.kt index 4d48d2862f..9d187ed3e2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/ManageCategoryDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/ManageCategoryDialog.kt @@ -70,7 +70,8 @@ class ManageCategoryDialog(bundle: Bundle? = null) : preferences.downloadNew().set(true) } if (preferences.libraryUpdateInterval().getOrDefault() > 0 && - !updatePref(preferences.libraryUpdateCategories(), view.include_global)) { + !updatePref(preferences.libraryUpdateCategories(), view.include_global) + ) { preferences.libraryUpdateInterval().set(0) LibraryUpdateJob.setupTask(0) } @@ -99,9 +100,11 @@ class ManageCategoryDialog(bundle: Bundle? = null) : view.title.hint = category.name view.title.append(category.name) val downloadNew = preferences.downloadNew().getOrDefault() - setCheckbox(view.download_new, + setCheckbox( + view.download_new, preferences.downloadNewCategories(), - true) + true + ) if (downloadNew && preferences.downloadNewCategories().getOrDefault().isEmpty()) view.download_new.gone() else if (!downloadNew) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadAdapter.kt index 4e81ecb29b..e6d375d85c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadAdapter.kt @@ -8,8 +8,11 @@ import eu.davidea.flexibleadapter.FlexibleAdapter * * @param context the context of the fragment containing this adapter. */ -class DownloadAdapter(controller: DownloadItemListener) : FlexibleAdapter(null, controller, - true) { +class DownloadAdapter(controller: DownloadItemListener) : FlexibleAdapter( + null, + controller, + true +) { /** * Listener called when an item of the list is released. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadBottomSheet.kt index 40d2f4cb87..94e7f8e732 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadBottomSheet.kt @@ -94,7 +94,8 @@ class DownloadBottomSheet @JvmOverloads constructor( private fun updateDLTitle() { val extCount = presenter.downloadQueue.firstOrNull() title_text.text = if (extCount != null) resources.getString( - R.string.downloading_, extCount.chapter.name + R.string.downloading_, + extCount.chapter.name ) else "" } @@ -164,7 +165,8 @@ class DownloadBottomSheet @JvmOverloads constructor( if (presenter.downloadQueue.isEmpty()) { empty_view?.show( R.drawable.ic_download_off_24dp, - R.string.nothing_is_downloading) + R.string.nothing_is_downloading + ) } else { empty_view?.hide() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadButton.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadButton.kt index beecc88a4a..b79e9876d4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadButton.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadButton.kt @@ -17,22 +17,38 @@ class DownloadButton @JvmOverloads constructor(context: Context, attrs: Attribut FrameLayout(context, attrs) { private val activeColor = context.getResourceColor(R.attr.colorAccent) - private val progressBGColor = ContextCompat.getColor(context, - R.color.divider) - private val disabledColor = ContextCompat.getColor(context, - R.color.material_on_surface_disabled) - private val downloadedColor = ContextCompat.getColor(context, - R.color.download) - private val errorColor = ContextCompat.getColor(context, - R.color.material_red_500) - private val filledCircle = ContextCompat.getDrawable(context, - R.drawable.filled_circle)?.mutate() - private val borderCircle = ContextCompat.getDrawable(context, - R.drawable.border_circle)?.mutate() - private val downloadDrawable = ContextCompat.getDrawable(context, - R.drawable.ic_arrow_downward_24dp)?.mutate() - private val checkDrawable = ContextCompat.getDrawable(context, - R.drawable.ic_check_24dp)?.mutate() + private val progressBGColor = ContextCompat.getColor( + context, + R.color.divider + ) + private val disabledColor = ContextCompat.getColor( + context, + R.color.material_on_surface_disabled + ) + private val downloadedColor = ContextCompat.getColor( + context, + R.color.download + ) + private val errorColor = ContextCompat.getColor( + context, + R.color.material_red_500 + ) + private val filledCircle = ContextCompat.getDrawable( + context, + R.drawable.filled_circle + )?.mutate() + private val borderCircle = ContextCompat.getDrawable( + context, + R.drawable.border_circle + )?.mutate() + private val downloadDrawable = ContextCompat.getDrawable( + context, + R.drawable.ic_arrow_downward_24dp + )?.mutate() + private val checkDrawable = ContextCompat.getDrawable( + context, + R.drawable.ic_check_24dp + )?.mutate() private var isAnimating = false private var iconAnimation: ObjectAnimator? = null @@ -42,8 +58,10 @@ class DownloadButton @JvmOverloads constructor(context: Context, attrs: Attribut download_icon.alpha = 1f isAnimating = false } - download_icon.setImageDrawable(if (state == Download.CHECKED) - checkDrawable else downloadDrawable) + download_icon.setImageDrawable( + if (state == Download.CHECKED) + checkDrawable else downloadDrawable + ) when (state) { Download.CHECKED -> { download_progress.gone() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHolder.kt index 729d632e46..6373c9c9d0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHolder.kt @@ -54,8 +54,10 @@ class DownloadHolder(private val view: View, val adapter: DownloadAdapter) : migration_menu.visibleIf(adapterPosition != 0 || adapterPosition != adapter.itemCount - 1) migration_menu.setVectorCompat( - R.drawable.ic_more_vert_24dp, view.context - .getResourceColor(android.R.attr.textColorPrimary)) + R.drawable.ic_more_vert_24dp, + view.context + .getResourceColor(android.R.attr.textColorPrimary) + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadItem.kt index b8fef48d1c..9c10f61e51 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadItem.kt @@ -31,7 +31,7 @@ class DownloadItem(val download: Download) : AbstractFlexibleItem> + .ViewHolder>> ): DownloadHolder { return DownloadHolder(view, adapter as DownloadAdapter) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionAdapter.kt index 58c72e8c7e..0354744ae8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionAdapter.kt @@ -10,7 +10,7 @@ import eu.kanade.tachiyomi.ui.extension.ExtensionAdapter.OnButtonClickListener * @param listener instance of [OnButtonClickListener]. */ class ExtensionAdapter(val listener: OnButtonClickListener) : - FlexibleAdapter>(null, listener, true) { + FlexibleAdapter>(null, listener, true) { init { setDisplayHeadersAtStartUp(true) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomPresenter.kt index 0918673a7b..521caf95c2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomPresenter.kt @@ -83,9 +83,11 @@ class ExtensionBottomPresenter( val untrustedSorted = untrusted.sortedBy { it.pkgName } val availableSorted = available // Filter out already installed extensions and disabled languages - .filter { avail -> installed.none { it.pkgName == avail.pkgName } && - untrusted.none { it.pkgName == avail.pkgName } && - (avail.lang in activeLangs || avail.lang == "all") } + .filter { avail -> + installed.none { it.pkgName == avail.pkgName } && + untrusted.none { it.pkgName == avail.pkgName } && + (avail.lang in activeLangs || avail.lang == "all") + } .sortedBy { it.pkgName } if (installedSorted.isNotEmpty() || untrustedSorted.isNotEmpty()) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomSheet.kt index 9be1903d09..f096002f32 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionBottomSheet.kt @@ -21,8 +21,8 @@ import eu.kanade.tachiyomi.util.view.withFadeTransaction import kotlinx.android.synthetic.main.extensions_bottom_sheet.view.* class ExtensionBottomSheet @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : -LinearLayout(context, attrs), -ExtensionAdapter.OnButtonClickListener, + LinearLayout(context, attrs), + ExtensionAdapter.OnButtonClickListener, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, ExtensionTrustDialog.Listener { @@ -88,11 +88,17 @@ ExtensionAdapter.OnButtonClickListener, fun updateExtTitle() { val extCount = presenter.getExtensionUpdateCount() title_text.text = if (extCount == 0) context.getString(R.string.extensions) - else resources.getQuantityString(R.plurals.extension_updates_available, extCount, - extCount) + else resources.getQuantityString( + R.plurals.extension_updates_available, + extCount, + extCount + ) - title_text.setTextColor(context.getResourceColor( - if (extCount == 0) R.attr.actionBarTintColor else R.attr.colorAccent)) + title_text.setTextColor( + context.getResourceColor( + if (extCount == 0) R.attr.actionBarTintColor else R.attr.colorAccent + ) + ) } override fun onButtonClick(position: Int) { @@ -153,7 +159,8 @@ ExtensionAdapter.OnButtonClickListener, adapter?.updateDataSet( extensions.filter { it.extension.name.contains(controller.extQuery, ignoreCase = true) - }) + } + ) } else { adapter?.updateDataSet(extensions) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsController.kt index 1995f2f63e..44dc8c4ef3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsController.kt @@ -36,17 +36,19 @@ import kotlinx.android.synthetic.main.extension_detail_controller.* @SuppressLint("RestrictedApi") class ExtensionDetailsController(bundle: Bundle? = null) : - NucleusController(bundle), - PreferenceManager.OnDisplayPreferenceDialogListener, - DialogPreference.TargetFragment { + NucleusController(bundle), + PreferenceManager.OnDisplayPreferenceDialogListener, + DialogPreference.TargetFragment { private var lastOpenPreferencePosition: Int? = null private var preferenceScreen: PreferenceScreen? = null - constructor(pkgName: String) : this(Bundle().apply { - putString(PKGNAME_KEY, pkgName) - }) + constructor(pkgName: String) : this( + Bundle().apply { + putString(PKGNAME_KEY, pkgName) + } + ) override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { val themedInflater = inflater.cloneInContext(getPreferenceThemeContext()) @@ -107,8 +109,10 @@ class ExtensionDetailsController(bundle: Bundle? = null) : extension_prefs_recycler.setOnApplyWindowInsetsListener(RecyclerWindowInsetsListener) if (screen.preferenceCount == 0) { - extension_prefs_empty_view.show(R.drawable.ic_no_settings_24dp, - R.string.empty_preferences_for_extension) + extension_prefs_empty_view.show( + R.drawable.ic_no_settings_24dp, + R.string.empty_preferences_for_extension + ) } } @@ -138,8 +142,9 @@ class ExtensionDetailsController(bundle: Bundle? = null) : val dataStore = SharedPreferencesDataStore(/*if (source is HttpSource) { source.preferences } else {*/ - context.getSharedPreferences("source_${source.id}", Context.MODE_PRIVATE) - /*}*/) + context.getSharedPreferences("source_${source.id}", Context.MODE_PRIVATE) + /*}*/ + ) if (source is ConfigurableSource) { if (multiSource) { @@ -193,14 +198,19 @@ class ExtensionDetailsController(bundle: Bundle? = null) : } val f = when (preference) { - is EditTextPreference -> EditTextPreferenceDialogController + is EditTextPreference -> + EditTextPreferenceDialogController .newInstance(preference.getKey()) - is ListPreference -> ListPreferenceDialogController + is ListPreference -> + ListPreferenceDialogController .newInstance(preference.getKey()) - is MultiSelectListPreference -> MultiSelectListPreferenceDialogController + is MultiSelectListPreference -> + MultiSelectListPreferenceDialogController .newInstance(preference.getKey()) - else -> throw IllegalArgumentException("Tried to display dialog for unknown " + - "preference type. Did you forget to override onDisplayPreferenceDialog()?") + else -> throw IllegalArgumentException( + "Tried to display dialog for unknown " + + "preference type. Did you forget to override onDisplayPreferenceDialog()?" + ) } f.targetController = this f.showDialog(router) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsPresenter.kt index 93b79d4670..51e58c34b7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDetailsPresenter.kt @@ -22,14 +22,14 @@ class ExtensionDetailsPresenter( private fun bindToUninstalledExtension() { extensionManager.getInstalledExtensionsObservable() - .skip(1) - .filter { extensions -> extensions.none { it.pkgName == pkgName } } - .map { Unit } - .take(1) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeFirst({ view, _ -> - view.onExtensionUninstalled() - }) + .skip(1) + .filter { extensions -> extensions.none { it.pkgName == pkgName } } + .map { Unit } + .take(1) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeFirst({ view, _ -> + view.onExtensionUninstalled() + }) } fun uninstallExtension() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDividerItemDecoration.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDividerItemDecoration.kt index f2175918f8..15b3fdc142 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDividerItemDecoration.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionDividerItemDecoration.kt @@ -24,7 +24,8 @@ class ExtensionDividerItemDecoration(context: Context) : androidx.recyclerview.w val child = parent.getChildAt(i) val holder = parent.getChildViewHolder(child) if (holder is ExtensionHolder && - parent.getChildViewHolder(parent.getChildAt(i + 1)) is ExtensionHolder) { + parent.getChildViewHolder(parent.getChildAt(i + 1)) is ExtensionHolder + ) { val params = child.layoutParams as androidx.recyclerview.widget.RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + divider.intrinsicHeight diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupHolder.kt index 49234aae4b..849c766227 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupHolder.kt @@ -9,7 +9,7 @@ import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import kotlinx.android.synthetic.main.extension_card_header.* class ExtensionGroupHolder(view: View, adapter: FlexibleAdapter>) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { @SuppressLint("SetTextI18n") fun bind(item: ExtensionGroupItem) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionHolder.kt index 4b8a5c2e57..03dd190113 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionHolder.kt @@ -18,7 +18,7 @@ import kotlinx.android.synthetic.main.extension_card_item.* import kotlinx.android.synthetic.main.source_global_search_controller_card_item.* class ExtensionHolder(view: View, val adapter: ExtensionAdapter) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { init { ext_button.setOnClickListener { @@ -63,13 +63,15 @@ class ExtensionHolder(view: View, val adapter: ExtensionAdapter) : val extension = item.extension val installStep = item.installStep if (installStep != null) { - setText(when (installStep) { - InstallStep.Pending -> R.string.pending - InstallStep.Downloading -> R.string.downloading - InstallStep.Installing -> R.string.installing - InstallStep.Installed -> R.string.installed - InstallStep.Error -> R.string.retry - }) + setText( + when (installStep) { + InstallStep.Pending -> R.string.pending + InstallStep.Downloading -> R.string.downloading + InstallStep.Installing -> R.string.installing + InstallStep.Installed -> R.string.installed + InstallStep.Error -> R.string.retry + } + ) if (installStep != InstallStep.Error) { isEnabled = false isClickable = false @@ -79,7 +81,8 @@ class ExtensionHolder(view: View, val adapter: ExtensionAdapter) : extension.hasUpdate -> { isActivated = true backgroundTintList = ColorStateList.valueOf( - context.getResourceColor(R.attr.colorAccent)) + context.getResourceColor(R.attr.colorAccent) + ) strokeColor = ColorStateList.valueOf(Color.TRANSPARENT) setText(R.string.update) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionItem.kt index 2fb20c0b19..be4abf80ef 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionItem.kt @@ -21,7 +21,7 @@ data class ExtensionItem( val header: ExtensionGroupItem? = null, val installStep: InstallStep? = null ) : - AbstractSectionableItem(header) { + AbstractSectionableItem(header) { /** * Returns the layout resource of this item. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionTrustDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionTrustDialog.kt index fcae6b480d..747469b3f4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionTrustDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionTrustDialog.kt @@ -10,23 +10,25 @@ class ExtensionTrustDialog(bundle: Bundle? = null) : DialogController(bundle) where T : ExtensionTrustDialog.Listener { lateinit var listener: Listener - constructor(target: T, signatureHash: String, pkgName: String) : this(Bundle().apply { - putString(SIGNATURE_KEY, signatureHash) - putString(PKGNAME_KEY, pkgName) - }) { + constructor(target: T, signatureHash: String, pkgName: String) : this( + Bundle().apply { + putString(SIGNATURE_KEY, signatureHash) + putString(PKGNAME_KEY, pkgName) + } + ) { listener = target } override fun onCreateDialog(savedViewState: Bundle?): Dialog { return MaterialDialog(activity!!) - .title(R.string.untrusted_extension) - .message(R.string.untrusted_extension_message) - .positiveButton(R.string.trust) { - listener.trustSignature(args.getString(SIGNATURE_KEY)!!) - } - .negativeButton(R.string.uninstall) { - listener.uninstallExtension(args.getString(PKGNAME_KEY)!!) - } + .title(R.string.untrusted_extension) + .message(R.string.untrusted_extension_message) + .positiveButton(R.string.trust) { + listener.trustSignature(args.getString(SIGNATURE_KEY)!!) + } + .negativeButton(R.string.uninstall) { + listener.uninstallExtension(args.getString(PKGNAME_KEY)!!) + } } private companion object { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/ChangeMangaCategoriesDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/ChangeMangaCategoriesDialog.kt index ed46df504d..f3ac85fc4b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/ChangeMangaCategoriesDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/ChangeMangaCategoriesDialog.kt @@ -11,7 +11,7 @@ import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.controller.DialogController class ChangeMangaCategoriesDialog(bundle: Bundle? = null) : - DialogController(bundle) where T : Controller, T : ChangeMangaCategoriesDialog.Listener { + DialogController(bundle) where T : Controller, T : ChangeMangaCategoriesDialog.Listener { private var mangas = emptyList() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/DisplayBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/DisplayBottomSheet.kt index 463333c127..0fdf79077f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/DisplayBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/DisplayBottomSheet.kt @@ -24,7 +24,7 @@ import kotlinx.android.synthetic.main.display_bottom_sheet.* import uy.kohesive.injekt.injectLazy class DisplayBottomSheet(private val controller: LibraryController) : BottomSheetDialog - (controller.activity!!, R.style.BottomSheetDialogTheme) { +(controller.activity!!, R.style.BottomSheetDialogTheme) { val activity = controller.activity!! @@ -45,15 +45,17 @@ class DisplayBottomSheet(private val controller: LibraryController) : BottomShee val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom sheetBehavior.peekHeight = 220.dpToPx + height - sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { } + sheetBehavior.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { } - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_EXPANDED) { + sheetBehavior.skipCollapsed = true + } } } - }) + ) } override fun onStart() { @@ -132,7 +134,7 @@ class DisplayBottomSheet(private val controller: LibraryController) : BottomShee */ private fun CompoundButton.bindToPreference( pref: com.tfcporciuncula.flow -.Preference, + .Preference, block: ((Boolean) -> Unit)? = null ) { isChecked = pref.get() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt index 6c47e30cdd..7809995b5d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt @@ -22,7 +22,7 @@ import java.util.Locale * @param view the fragment containing this adapter. */ class LibraryCategoryAdapter(val controller: LibraryController) : - FlexibleAdapter>(null, controller, true) { + FlexibleAdapter>(null, controller, true) { val sourceManager by injectLazy() @@ -59,7 +59,8 @@ class LibraryCategoryAdapter(val controller: LibraryController) : fun indexOf(categoryOrder: Int): Int { return currentItems.indexOfFirst { if (it is LibraryHeaderItem) it.category.order == categoryOrder - else false } + else false + } } /** @@ -70,13 +71,15 @@ class LibraryCategoryAdapter(val controller: LibraryController) : fun indexOf(manga: Manga): Int { return currentItems.indexOfFirst { if (it is LibraryItem) it.manga.id == manga.id - else false } + else false + } } fun getHeaderPositions(): List { return currentItems.mapIndexedNotNull { index, it -> if (it is LibraryHeaderItem) index - else null } + else null + } } /** @@ -87,7 +90,8 @@ class LibraryCategoryAdapter(val controller: LibraryController) : fun allIndexOf(manga: Manga): List { return currentItems.mapIndexedNotNull { index, it -> if (it is LibraryItem && it.manga.id == manga.id) index - else null } + else null + } } fun performFilter() { @@ -140,7 +144,8 @@ class LibraryCategoryAdapter(val controller: LibraryController) : val last = history.maxBy { it.last_read } if (last != null && last.last_read > 100) { recyclerView.context.getString( - R.string.read_, last.last_read.timeSpanFromNow + R.string.read_, + last.last_read.timeSpanFromNow ) } else { "N/A" @@ -154,7 +159,9 @@ class LibraryCategoryAdapter(val controller: LibraryController) : LibrarySort.TOTAL -> { val total = item.manga.totalChapters if (total > 0) recyclerView.resources.getQuantityString( - R.plurals.chapters, total, total + R.plurals.chapters, + total, + total ) else { "N/A" @@ -164,7 +171,8 @@ class LibraryCategoryAdapter(val controller: LibraryController) : val lastUpdate = item.manga.last_update if (lastUpdate > 0) { recyclerView.context.getString( - R.string.updated_, lastUpdate.timeSpanFromNow + R.string.updated_, + lastUpdate.timeSpanFromNow ) } else { "N/A" diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt index cf82db52a3..63aeda7baa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt @@ -108,10 +108,13 @@ class LibraryController( ) : BaseController(bundle), ActionMode.Callback, ChangeMangaCategoriesDialog.Listener, - FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, - FlexibleAdapter.OnItemMoveListener, LibraryCategoryAdapter.LibraryListener, + FlexibleAdapter.OnItemClickListener, + FlexibleAdapter.OnItemLongClickListener, + FlexibleAdapter.OnItemMoveListener, + LibraryCategoryAdapter.LibraryListener, BottomSheetController, - RootSearchInterface, LibraryServiceListener { + RootSearchInterface, + LibraryServiceListener { init { setHasOptionsMenu(true) @@ -325,17 +328,19 @@ class LibraryController( adapter = LibraryCategoryAdapter(this) setRecyclerLayout() - recycler.manager.spanSizeLookup = (object : GridLayoutManager.SpanSizeLookup() { - override fun getSpanSize(position: Int): Int { - if (libraryLayout == 0) return 1 - val item = this@LibraryController.adapter.getItem(position) - return if (item is LibraryHeaderItem || item is SearchGlobalItem || (item is LibraryItem && item.manga.isBlank())) { - recycler?.manager?.spanCount ?: 1 - } else { - 1 + recycler.manager.spanSizeLookup = ( + object : GridLayoutManager.SpanSizeLookup() { + override fun getSpanSize(position: Int): Int { + if (libraryLayout == 0) return 1 + val item = this@LibraryController.adapter.getItem(position) + return if (item is LibraryHeaderItem || item is SearchGlobalItem || (item is LibraryItem && item.manga.isBlank())) { + recycler?.manager?.spanCount ?: 1 + } else { + 1 + } } } - }) + ) recycler.setHasFixedSize(true) recycler.adapter = adapter @@ -360,17 +365,22 @@ class LibraryController( setUpHopper() elevateAppBar = - scrollViewWith(recycler, swipeRefreshLayout = swipe_refresh, afterInsets = { insets -> - category_recycler?.updateLayoutParams { - topMargin = recycler?.paddingTop ?: 0 + scrollViewWith( + recycler, + swipeRefreshLayout = swipe_refresh, + afterInsets = { insets -> + category_recycler?.updateLayoutParams { + topMargin = recycler?.paddingTop ?: 0 + } + fast_scroller?.updateLayoutParams { + topMargin = recycler?.paddingTop ?: 0 + } + header_title?.updatePaddingRelative(top = insets.systemWindowInsetTop + 2.dpToPx) + }, + onLeavingController = { + header_title?.gone() } - fast_scroller?.updateLayoutParams { - topMargin = recycler?.paddingTop ?: 0 - } - header_title?.updatePaddingRelative(top = insets.systemWindowInsetTop + 2.dpToPx) - }, onLeavingController = { - header_title?.gone() - }) + ) swipe_refresh.setOnRefreshListener { swipe_refresh.isRefreshing = false @@ -387,19 +397,24 @@ class LibraryController( preferences.updateOnRefresh().getOrDefault() == -1 -> { MaterialDialog(activity!!).title(R.string.what_should_update) .negativeButton(android.R.string.cancel) - .listItemsSingleChoice(items = listOf( - view.context.getString( - R.string.top_category, presenter.allCategories.first().name - ), view.context.getString( - R.string.categories_in_global_update - ) - ), selection = { _, index, _ -> - preferences.updateOnRefresh().set(index) - when (index) { - 0 -> updateLibrary(presenter.allCategories.first()) - else -> updateLibrary() + .listItemsSingleChoice( + items = listOf( + view.context.getString( + R.string.top_category, + presenter.allCategories.first().name + ), + view.context.getString( + R.string.categories_in_global_update + ) + ), + selection = { _, index, _ -> + preferences.updateOnRefresh().set(index) + when (index) { + 0 -> updateLibrary(presenter.allCategories.first()) + else -> updateLibrary() + } } - }).positiveButton(R.string.update).show() + ).positiveButton(R.string.update).show() } else -> { when (preferences.updateOnRefresh().getOrDefault()) { @@ -557,8 +572,8 @@ class LibraryController( presenter.categories.indexOfFirst { presenter.currentCategory == it.id } + (if (next) 1 else -1) if (if (!next) { - newOffset > -1 - } else { + newOffset > -1 + } else { newOffset < presenter.categories.size } ) { @@ -632,7 +647,8 @@ class LibraryController( if (libraryLayout == 0) { recycler.spanCount = 1 recycler.updatePaddingRelative( - start = 0, end = 0 + start = 0, + end = 0 ) } else { recycler.columnWidth = when (preferences.gridSize().getOrDefault()) { @@ -712,9 +728,9 @@ class LibraryController( } adapter.setItems(mangaMap) if (recycler.itemAnimator == null) - recycler.post { - recycler.itemAnimator = DefaultItemAnimator() - } + recycler.post { + recycler.itemAnimator = DefaultItemAnimator() + } singleCategory = presenter.categories.size <= 1 showDropdown() progress.gone() @@ -733,7 +749,8 @@ class LibraryController( category_hopper_frame.visibleIf(!singleCategory && !preferences.hideHopper().get()) filter_bottom_sheet.updateButtons( - showExpand = !singleCategory && presenter.showAllCategories, groupType = presenter.groupType + showExpand = !singleCategory && presenter.showAllCategories, + groupType = presenter.groupType ) adapter.isLongPressDragEnabled = canDrag() category_recycler.setCategories(presenter.categories) @@ -783,9 +800,11 @@ class LibraryController( ) animatorSet.playSequentially(animations) animatorSet.startDelay = 1250 - animatorSet.addListener(EndAnimatorListener { - isAnimatingHopper = false - }) + animatorSet.addListener( + EndAnimatorListener { + isAnimatingHopper = false + } + ) animatorSet.start() } @@ -836,16 +855,21 @@ class LibraryController( if (headerPosition > -1) { val appbar = activity?.appbar recycler.suppressLayout(true) - val appbarOffset = if (appbar?.y ?: 0f > -20) 0 else (appbar?.y?.plus( - view?.rootWindowInsets?.systemWindowInsetTop ?: 0 - ) ?: 0f).roundToInt() + 30.dpToPx + val appbarOffset = if (appbar?.y ?: 0f > -20) 0 else ( + appbar?.y?.plus( + view?.rootWindowInsets?.systemWindowInsetTop ?: 0 + ) ?: 0f + ).roundToInt() + 30.dpToPx val previousHeader = adapter.getItem(adapter.indexOf(pos - 1)) as? LibraryHeaderItem (recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset( - headerPosition, (when { - headerPosition == 0 -> 0 - previousHeader?.category?.isHidden == true -> (-3).dpToPx - else -> (-30).dpToPx - }) + appbarOffset + headerPosition, + ( + when { + headerPosition == 0 -> 0 + previousHeader?.category?.isHidden == true -> (-3).dpToPx + else -> (-30).dpToPx + } + ) + appbarOffset ) (adapter.getItem(headerPosition) as? LibraryHeaderItem)?.category?.let { saveActiveCategory(it) @@ -1033,9 +1057,9 @@ class LibraryController( val position = viewHolder?.adapterPosition ?: return swipe_refresh.isEnabled = actionState != ItemTouchHelper.ACTION_STATE_DRAG if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) { - if (lastItemPosition != null && position != lastItemPosition && lastItem == adapter.getItem( - position - ) + if (lastItemPosition != null && + position != lastItemPosition && + lastItem == adapter.getItem(position) ) { // because for whatever reason you can repeatedly tap on a currently dragging manga adapter.removeSelection(position) @@ -1063,10 +1087,11 @@ class LibraryController( override fun onItemMove(fromPosition: Int, toPosition: Int) { // Because padding a recycler causes it to scroll up we have to scroll it back down... wild - if ((adapter.getItem(fromPosition) is LibraryItem && adapter.getItem(fromPosition) is - LibraryItem) || adapter.getItem( - fromPosition - ) == null + if (( + adapter.getItem(fromPosition) is LibraryItem && + adapter.getItem(fromPosition) is LibraryItem + ) || + adapter.getItem(fromPosition) == null ) { recycler.scrollBy(0, recycler.paddingTop) } @@ -1079,9 +1104,12 @@ class LibraryController( val item = adapter.getItem(fromPosition) as? LibraryItem ?: return false val newHeader = adapter.getSectionHeader(toPosition) as? LibraryHeaderItem if (toPosition < 1) return false - return (adapter.getItem(toPosition) !is LibraryHeaderItem) && (newHeader?.category?.id == item.manga.category || !presenter.mangaIsInCategory( - item.manga, newHeader?.category?.id - )) + return (adapter.getItem(toPosition) !is LibraryHeaderItem) && ( + newHeader?.category?.id == item.manga.category || !presenter.mangaIsInCategory( + item.manga, + newHeader?.category?.id + ) + ) } override fun onItemReleased(position: Int) { @@ -1110,7 +1138,9 @@ class LibraryController( return } if (newHeader?.category != null) moveMangaToCategory( - item.manga, newHeader.category, mangaIds + item.manga, + newHeader.category, + mangaIds ) } lastItemPosition = null @@ -1147,8 +1177,10 @@ class LibraryController( inQueue -> R.string._already_in_queue LibraryUpdateService.isRunning() -> R.string.adding_category_to_queue else -> R.string.updating_ - }, category.name - ), Snackbar.LENGTH_LONG + }, + category.name + ), + Snackbar.LENGTH_LONG ) { anchorView = anchorView() view.elevation = 15f.dpToPx @@ -1163,7 +1195,9 @@ class LibraryController( } } if (!inQueue) LibraryUpdateService.start( - view!!.context, category, mangaToUse = if (category.isDynamic) { + view!!.context, + category, + mangaToUse = if (category.isDynamic) { presenter.getMangaInCategories(category.id) } else null ) @@ -1327,9 +1361,11 @@ class LibraryController( } R.id.action_migrate -> { val skipPre = preferences.skipPreMigration().getOrDefault() - PreMigrationController.navigateToMigration(skipPre, + PreMigrationController.navigateToMigration( + skipPre, router, - selectedMangas.filter { it.id != LocalSource.ID }.mapNotNull { it.id }) + selectedMangas.filter { it.id != LocalSource.ID }.mapNotNull { it.id } + ) destroyActionModeIfNeeded() } else -> return false @@ -1356,7 +1392,8 @@ class LibraryController( destroyActionModeIfNeeded() snack?.dismiss() snack = view?.snack( - activity?.getString(R.string.removed_from_library) ?: "", Snackbar.LENGTH_INDEFINITE + activity?.getString(R.string.removed_from_library) ?: "", + Snackbar.LENGTH_INDEFINITE ) { anchorView = anchorView() view.elevation = 15f.dpToPx @@ -1365,12 +1402,14 @@ class LibraryController( presenter.reAddMangas(mangas) undoing = true } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!undoing) presenter.confirmDeletion(mangas) + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!undoing) presenter.confirmDeletion(mangas) + } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGestureDetector.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGestureDetector.kt index fc6636747c..9fcb2443fa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGestureDetector.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGestureDetector.kt @@ -26,38 +26,45 @@ class LibraryGestureDetector(private val controller: LibraryController) : Gestur var result = false val diffY = e2.y - e1.y val diffX = e2.x - e1.x - if (abs(diffX) <= abs(diffY) && abs(diffY) > MainActivity.SWIPE_THRESHOLD && abs(velocityY) > MainActivity.SWIPE_VELOCITY_THRESHOLD) { + if (abs(diffX) <= abs(diffY) && + abs(diffY) > MainActivity.SWIPE_THRESHOLD && + abs(velocityY) > MainActivity.SWIPE_VELOCITY_THRESHOLD + ) { if (diffY <= 0) { controller.showSheet() } else { controller.filter_bottom_sheet.sheetBehavior?.hide() } result = true - } else if (abs(diffX) >= abs(diffY) && abs(diffX) > MainActivity.SWIPE_THRESHOLD * 3 && abs( - velocityX - ) > MainActivity.SWIPE_VELOCITY_THRESHOLD + } else if (abs(diffX) >= abs(diffY) && + abs(diffX) > MainActivity.SWIPE_THRESHOLD * 3 && + abs(velocityX) > MainActivity.SWIPE_VELOCITY_THRESHOLD ) { if (diffX <= 0) { controller.category_hopper_frame.updateLayoutParams { anchorGravity = - Gravity.TOP or (if (anchorGravity == Gravity.TOP or Gravity.RIGHT) { + Gravity.TOP or ( + if (anchorGravity == Gravity.TOP or Gravity.RIGHT) { controller.preferences.hopperGravity().set(1) Gravity.CENTER } else { controller.preferences.hopperGravity().set(0) Gravity.LEFT - }) + } + ) } } else { controller.category_hopper_frame.updateLayoutParams { anchorGravity = - Gravity.TOP or Gravity.TOP or (if (anchorGravity == Gravity.TOP or Gravity.LEFT) { + Gravity.TOP or Gravity.TOP or ( + if (anchorGravity == Gravity.TOP or Gravity.LEFT) { controller.preferences.hopperGravity().set(1) Gravity.CENTER } else { controller.preferences.hopperGravity().set(2) Gravity.RIGHT - }) + } + ) } } if (!controller.hasMovedHopper) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderHolder.kt index ea659555dd..972ad8314a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderHolder.kt @@ -79,11 +79,13 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd } val shorterMargin = adapter.headerItems.firstOrNull() == item sectionText.updateLayoutParams { - topMargin = (when { - shorterMargin -> 2 - previousIsCollapsed -> 5 - else -> 32 - }).dpToPx + topMargin = ( + when { + shorterMargin -> 2 + previousIsCollapsed -> 5 + else -> 32 + } + ).dpToPx } val category = item.category @@ -117,7 +119,8 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd sortText.setText(category.sortRes()) expandImage.setImageResource( if (category.isHidden) R.drawable.ic_expand_more_24dp - else R.drawable.ic_expand_less_24dp) + else R.drawable.ic_expand_less_24dp + ) when { adapter.mode == SelectableAdapter.Mode.MULTI -> { checkboxImage.visibleIf(!category.isHidden) @@ -160,22 +163,31 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd adapter.controller.activity?.let { activity -> val items = mutableListOf( MaterialMenuSheet.MenuSheetItem( - LibrarySort.ALPHA, R.drawable.ic_sort_by_alpha_24dp, R.string.title - ), MaterialMenuSheet.MenuSheetItem( + LibrarySort.ALPHA, + R.drawable.ic_sort_by_alpha_24dp, + R.string.title + ), + MaterialMenuSheet.MenuSheetItem( LibrarySort.LAST_READ, R.drawable.ic_recent_read_outline_24dp, R.string.last_read - ), MaterialMenuSheet.MenuSheetItem( + ), + MaterialMenuSheet.MenuSheetItem( LibrarySort.LATEST_CHAPTER, R.drawable.ic_new_releases_24dp, R.string.latest_chapter - ), MaterialMenuSheet.MenuSheetItem( - LibrarySort.UNREAD, R.drawable.ic_eye_24dp, R.string.unread - ), MaterialMenuSheet.MenuSheetItem( + ), + MaterialMenuSheet.MenuSheetItem( + LibrarySort.UNREAD, + R.drawable.ic_eye_24dp, + R.string.unread + ), + MaterialMenuSheet.MenuSheetItem( LibrarySort.TOTAL, R.drawable.ic_sort_by_numeric_24dp, R.string.total_chapters - ), MaterialMenuSheet.MenuSheetItem( + ), + MaterialMenuSheet.MenuSheetItem( LibrarySort.DATE_ADDED, R.drawable.ic_heart_outline_24dp, R.string.date_added @@ -192,7 +204,10 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd } val sortingMode = category.sortingMode() val sheet = MaterialMenuSheet( - activity, items, activity.getString(R.string.sort_by), sortingMode + activity, + items, + activity.getString(R.string.sort_by), + sortingMode ) { sheet, item -> onCatSortClicked(category, item) val nCategory = (adapter.getItem(adapterPosition) as? LibraryHeaderItem)?.category @@ -212,7 +227,8 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd sortingMode == LibrarySort.DRAG_AND_DROP -> R.drawable.ic_check_24dp if (sortingMode == LibrarySort.DATE_ADDED || sortingMode == LibrarySort.LATEST_CHAPTER || - sortingMode == LibrarySort.LAST_READ) !isAscending else isAscending -> + sortingMode == LibrarySort.LAST_READ + ) !isAscending else isAscending -> R.drawable.ic_arrow_downward_24dp else -> R.drawable.ic_arrow_upward_24dp } @@ -257,7 +273,8 @@ class LibraryHeaderHolder(val view: View, private val adapter: LibraryCategoryAd val tintedDrawable = drawable?.mutate() tintedDrawable?.setTint( ContextCompat.getColor( - contentView.context, if (allSelected) R.color.colorAccent + contentView.context, + if (allSelected) R.color.colorAccent else R.color.gray_button ) ) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt index c5f3b41c6c..8cac903330 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt @@ -39,7 +39,8 @@ abstract class LibraryHolder( item.manga.source == LocalSource.ID -> -2 else -> item.downloadCount }, - showTotal) + showTotal + ) } fun setReadingButton(item: LibraryItem) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt index 3cf00fb545..13cdb045eb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryItem.kt @@ -66,18 +66,21 @@ class LibraryItem( gradient.layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, (coverHeight * 0.66f).toInt(), - Gravity.BOTTOM) + Gravity.BOTTOM + ) card.updateLayoutParams { bottomMargin = 6.dpToPx } } else if (libraryLayout == 2) { constraint_layout.background = ContextCompat.getDrawable( - context, R.drawable.library_item_selector + context, + R.drawable.library_item_selector ) } if (isFixedSize) { constraint_layout.layoutParams = FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT ) cover_thumbnail.maxHeight = Int.MAX_VALUE cover_thumbnail.minimumHeight = 0 @@ -162,7 +165,8 @@ class LibraryItem( } == null else genres?.find { - it.trim().toLowerCase() == tag.toLowerCase() } != null + it.trim().toLowerCase() == tag.toLowerCase() + } != null } override fun equals(other: Any?): Boolean { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt index e768555e19..eadc5c0fac 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt @@ -129,7 +129,8 @@ class LibraryPresenter( private fun blankItem(id: Int = currentCategory): List { return listOf( LibraryItem( - LibraryManga.createBlank(id), LibraryHeaderItem({ getCategory(id) }, id) + LibraryManga.createBlank(id), + LibraryHeaderItem({ getCategory(id) }, id) ) ) } @@ -146,7 +147,8 @@ class LibraryPresenter( view.onNextLibraryUpdate( if (!show) sectionedLibraryItems[currentCategory] ?: sectionedLibraryItems[categories.first().id] ?: blankItem() - else libraryItems, true + else libraryItems, + true ) } @@ -168,8 +170,9 @@ class LibraryPresenter( withContext(Dispatchers.Main) { view.onNextLibraryUpdate( if (!showAll) sectionedLibraryItems[currentCategory] - ?: sectionedLibraryItems[categories.first().id] ?: blankItem() - else libraryItems, freshStart + ?: sectionedLibraryItems[categories.first().id] ?: blankItem() + else libraryItems, + freshStart ) } } @@ -247,8 +250,8 @@ class LibraryPresenter( if (filterMangaType > 0) { if (if (filterMangaType == Manga.TYPE_MANHWA) { - (filterMangaType != item.manga.mangaType() && filterMangaType != Manga.TYPE_WEBTOON) - } else { + (filterMangaType != item.manga.mangaType() && filterMangaType != Manga.TYPE_WEBTOON) + } else { filterMangaType != item.manga.mangaType() } ) return false @@ -454,15 +457,19 @@ class LibraryPresenter( ) val catItemAll = LibraryHeaderItem({ categoryAll }, -1) val categorySet = mutableSetOf() - val headerItems = (categories.mapNotNull { category -> - val id = category.id - if (id == null) null - else id to LibraryHeaderItem({ getCategory(id) }, id) - } + (-1 to catItemAll) + (0 to LibraryHeaderItem({ getCategory(0) }, 0))).toMap() + val headerItems = ( + categories.mapNotNull { category -> + val id = category.id + if (id == null) null + else id to LibraryHeaderItem({ getCategory(id) }, id) + } + (-1 to catItemAll) + (0 to LibraryHeaderItem({ getCategory(0) }, 0)) + ).toMap() val items = libraryManga.mapNotNull { - val headerItem = (if (!libraryIsGrouped) catItemAll - else headerItems[it.category]) ?: return@mapNotNull null + val headerItem = ( + if (!libraryIsGrouped) catItemAll + else headerItems[it.category] + ) ?: return@mapNotNull null categorySet.add(it.category) LibraryItem(it, headerItem) }.toMutableList() @@ -475,8 +482,11 @@ class LibraryPresenter( if (libraryIsGrouped) { categories.forEach { category -> val catId = category.id ?: return@forEach - if (catId > 0 && !categorySet.contains(catId) && (catId !in categoriesHidden || - !showAll)) { + if (catId > 0 && !categorySet.contains(catId) && ( + catId !in categoriesHidden || + !showAll + ) + ) { val headerItem = headerItems[catId] if (headerItem != null) items.add( LibraryItem(LibraryManga.createBlank(catId), headerItem) @@ -592,18 +602,21 @@ class LibraryPresenter( mapTrackingOrder(it.name) } else { it.name - } } + } + } headers.forEachIndexed { index, category -> category.order = index } return items to headers } private fun mapStatus(status: Int): String { - return context.getString(when (status) { - SManga.LICENSED -> R.string.licensed - SManga.ONGOING -> R.string.ongoing - SManga.COMPLETED -> R.string.completed - else -> R.string.unknown - }) + return context.getString( + when (status) { + SManga.LICENSED -> R.string.licensed + SManga.ONGOING -> R.string.ongoing + SManga.COMPLETED -> R.string.completed + else -> R.string.unknown + } + ) } private fun mapTrackingOrder(status: String): String { @@ -681,8 +694,8 @@ class LibraryPresenter( fun getCommonCategories(mangas: List): Collection { if (mangas.isEmpty()) return emptyList() return mangas.toSet() - .map { db.getCategoriesForManga(it).executeAsBlocking() } - .reduce { set1: Iterable, set2 -> set1.intersect(set2).toMutableList() } + .map { db.getCategoriesForManga(it).executeAsBlocking() } + .reduce { set1: Iterable, set2 -> set1.intersect(set2).toMutableList() } } fun getMangaUrls(mangas: List): List { @@ -813,8 +826,8 @@ class LibraryPresenter( val categories = if (catId == 0) emptyList() else - db.getCategoriesForManga(manga).executeOnIO() - .filter { it.id != oldCatId } + listOf(category) + db.getCategoriesForManga(manga).executeOnIO() + .filter { it.id != oldCatId } + listOf(category) for (cat in categories) { mc.add(MangaCategory.create(manga, cat)) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/category/CategoryRecyclerView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/category/CategoryRecyclerView.kt index d396dd584e..46b5f8fd01 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/category/CategoryRecyclerView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/category/CategoryRecyclerView.kt @@ -33,17 +33,19 @@ class CategoryRecyclerView @JvmOverloads constructor( fun setCategories(items: List) { itemAdapter.set(items.map(::CategoryItem)) fastAdapter.onBindViewHolderListener = - (object : OnBindViewHolderListenerImpl() { - override fun onBindViewHolder( - viewHolder: ViewHolder, - position: Int, - payloads: List - ) { - super.onBindViewHolder(viewHolder, position, payloads) - (viewHolder as? CategoryItem.ViewHolder)?.categoryTitle?.isSelected = - selectedCategory == position + ( + object : OnBindViewHolderListenerImpl() { + override fun onBindViewHolder( + viewHolder: ViewHolder, + position: Int, + payloads: List + ) { + super.onBindViewHolder(viewHolder, position, payloads) + (viewHolder as? CategoryItem.ViewHolder)?.categoryTitle?.isSelected = + selectedCategory == position + } } - }) + ) fastAdapter.onClickListener = { _, _, item, _ -> if (item.category.id != -1) onCategoryClicked(item.category.order) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterBottomSheet.kt index 838a8f68bc..d472a59e83 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterBottomSheet.kt @@ -104,18 +104,20 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri pager = controller.recycler val shadow2: View = controller.shadow2 val shadow: View = controller.shadow - sheetBehavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - pill.alpha = (1 - max(0f, progress)) * 0.25f - shadow2.alpha = (1 - max(0f, progress)) * 0.25f - shadow.alpha = 1 + min(0f, progress) - updateRootPadding(progress) - } + sheetBehavior?.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + pill.alpha = (1 - max(0f, progress)) * 0.25f + shadow2.alpha = (1 - max(0f, progress)) * 0.25f + shadow.alpha = 1 + min(0f, progress) + updateRootPadding(progress) + } - override fun onStateChanged(p0: View, state: Int) { - stateChanged(state) + override fun onStateChanged(p0: View, state: Int) { + stateChanged(state) + } } - }) + ) if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { second_layout.removeView(view_options) @@ -284,13 +286,15 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri unreadProgress.state = unreadP - 3 } tracked?.setState(preferences.filterTracked()) - mangaType?.setState(when (preferences.filterMangaType().getOrDefault()) { - Manga.TYPE_MANGA -> context.getString(R.string.manga) - Manga.TYPE_MANHUA -> context.getString(R.string.manhua) - Manga.TYPE_MANHWA -> context.getString(R.string.manhwa) - Manga.TYPE_COMIC -> context.getString(R.string.comic) - else -> "" - }) + mangaType?.setState( + when (preferences.filterMangaType().getOrDefault()) { + Manga.TYPE_MANGA -> context.getString(R.string.manga) + Manga.TYPE_MANHUA -> context.getString(R.string.manhua) + Manga.TYPE_MANHWA -> context.getString(R.string.manhwa) + Manga.TYPE_COMIC -> context.getString(R.string.comic) + else -> "" + } + ) reorderFilters() reSortViews() } @@ -329,10 +333,10 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri } listOfNotNull(unreadProgress, unread, downloaded, completed, mangaType, tracked) .forEach { - if (!filterItems.contains(it)) { - filterItems.add(it) + if (!filterItems.contains(it)) { + filterItems.add(it) + } } - } } private fun indexOf(filterTagGroup: FilterTagGroup): Int { charOfFilter(filterTagGroup)?.let { @@ -361,8 +365,11 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri val recycler = RecyclerView(context) if (filterOrder.count() != 6) filterOrder = "urdcmt" - val adapter = FlexibleAdapter(filterOrder.toCharArray().map(::ManageFilterItem), - this, true) + val adapter = FlexibleAdapter( + filterOrder.toCharArray().map(::ManageFilterItem), + this, + true + ) recycler.layoutManager = LinearLayoutManager(context) recycler.adapter = adapter adapter.isHandleDragEnabled = true diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterTagGroup.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterTagGroup.kt index 7e7682fce6..31507c3972 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterTagGroup.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/filter/FilterTagGroup.kt @@ -16,7 +16,7 @@ import eu.kanade.tachiyomi.util.view.visibleIf import kotlinx.android.synthetic.main.filter_buttons.view.* class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout - (context, attrs) { +(context, attrs) { private var listener: FilterTagGroupListener? = null @@ -83,19 +83,23 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute private fun toggleButton(index: Int, callBack: Boolean = true) { if (index < 0 || itemCount == 0 || - (isActivated && index != buttons.indexOfFirst { it.isActivated })) + (isActivated && index != buttons.indexOfFirst { it.isActivated }) + ) return if (callBack) { val transition = androidx.transition.AutoTransition() transition.duration = 150 androidx.transition.TransitionManager.beginDelayedTransition( - parent.parent as ViewGroup, transition + parent.parent as ViewGroup, + transition ) } if (itemCount == 1) { firstButton.isActivated = !firstButton.isActivated - firstButton.setTextColor(if (firstButton.isActivated) Color.WHITE else context - .getResourceColor(android.R.attr.textColorPrimary)) + firstButton.setTextColor( + if (firstButton.isActivated) Color.WHITE else context + .getResourceColor(android.R.attr.textColorPrimary) + ) listener?.onFilterClicked(this, if (firstButton.isActivated) index else -1, callBack) return } @@ -118,8 +122,10 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute buttons.forEach { if (it != mainButton) it.gone() } separators.forEach { it.gone() } } - mainButton.setTextColor(if (mainButton.isActivated) Color.WHITE else context - .getResourceColor(android.R.attr.textColorPrimary)) + mainButton.setTextColor( + if (mainButton.isActivated) Color.WHITE else context + .getResourceColor(android.R.attr.textColorPrimary) + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/main/ChangelogDialogController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/main/ChangelogDialogController.kt index 0af5118f4d..07adaab74a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/main/ChangelogDialogController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/main/ChangelogDialogController.kt @@ -17,9 +17,9 @@ class ChangelogDialogController : DialogController() { val activity = activity!! val view = WhatsNewRecyclerView(activity) return MaterialDialog(activity) - .title(text = if (BuildConfig.DEBUG) "Notices" else "Changelog") - .customView(view = view, scrollable = false) - .positiveButton(android.R.string.yes) + .title(text = if (BuildConfig.DEBUG) "Notices" else "Changelog") + .customView(view = view, scrollable = false) + .positiveButton(android.R.string.yes) } class WhatsNewRecyclerView(context: Context) : ChangeLogRecyclerView(context) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt index eebdf09794..be4b883ebb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt @@ -144,10 +144,12 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { drawerArrow = DrawerArrowDrawable(this) drawerArrow?.color = getResourceColor(R.attr.actionBarTintColor) searchDrawable = ContextCompat.getDrawable( - this, R.drawable.ic_search_24dp + this, + R.drawable.ic_search_24dp ) dismissDrawable = ContextCompat.getDrawable( - this, R.drawable.ic_close_24dp + this, + R.drawable.ic_close_24dp ) var continueSwitchingTabs = false @@ -180,20 +182,24 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { val currentController = router.backstack.lastOrNull()?.controller() if (!continueSwitchingTabs && currentController is BottomNavBarInterface) { if (!currentController.canChangeTabs { - continueSwitchingTabs = true - this@MainActivity.bottom_nav.selectedItemId = id - }) return@setOnNavigationItemSelectedListener false + continueSwitchingTabs = true + this@MainActivity.bottom_nav.selectedItemId = id + } + ) return@setOnNavigationItemSelectedListener false } continueSwitchingTabs = false if (item.itemId != R.id.nav_browse) preferences.lastTab().set(item.itemId) val currentRoot = router.backstack.firstOrNull() if (currentRoot?.tag()?.toIntOrNull() != id) { - setRoot(when (id) { - R.id.nav_library -> LibraryController() - R.id.nav_recents -> RecentsController() - else -> SourceController() - }, id) + setRoot( + when (id) { + R.id.nav_library -> LibraryController() + R.id.nav_recents -> RecentsController() + else -> SourceController() + }, + id + ) } else if (currentRoot.tag()?.toIntOrNull() == id) { if (router.backstackSize == 1) { val controller = @@ -225,7 +231,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { // Consume any horizontal insets and pad all content in. There's not much we can do // with horizontal insets v.updatePadding( - left = insets.systemWindowInsetLeft, right = insets.systemWindowInsetRight + left = insets.systemWindowInsetLeft, + right = insets.systemWindowInsetRight ) appbar.updatePadding( top = insets.systemWindowInsetTop @@ -251,31 +258,33 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { bottom_nav.visibleIf(!hideBottomNav) bottom_nav.alpha = if (hideBottomNav) 0f else 1f - router.addChangeListener(object : ControllerChangeHandler.ControllerChangeListener { - override fun onChangeStarted( - to: Controller?, - from: Controller?, - isPush: Boolean, - container: ViewGroup, - handler: ControllerChangeHandler - ) { + router.addChangeListener( + object : ControllerChangeHandler.ControllerChangeListener { + override fun onChangeStarted( + to: Controller?, + from: Controller?, + isPush: Boolean, + container: ViewGroup, + handler: ControllerChangeHandler + ) { - syncActivityViewWithController(to, from, isPush) - appbar.y = 0f - snackBar?.dismiss() - } + syncActivityViewWithController(to, from, isPush) + appbar.y = 0f + snackBar?.dismiss() + } - override fun onChangeCompleted( - to: Controller?, - from: Controller?, - isPush: Boolean, - container: ViewGroup, - handler: ControllerChangeHandler - ) { - appbar.y = 0f - showDLQueueTutorial() + override fun onChangeCompleted( + to: Controller?, + from: Controller?, + isPush: Boolean, + container: ViewGroup, + handler: ControllerChangeHandler + ) { + appbar.y = 0f + showDLQueueTutorial() + } } - }) + ) syncActivityViewWithController(router.backstack.lastOrNull()?.controller()) @@ -322,7 +331,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { // if in portrait with 2/3 button mode, translucent nav bar else { ColorUtils.setAlphaComponent( - getResourceColor(R.attr.colorPrimaryVariant), 179 + getResourceColor(R.attr.colorPrimaryVariant), + 179 ) } } @@ -335,7 +345,9 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { override fun onSupportActionModeFinished(mode: androidx.appcompat.view.ActionMode) { launchUI { val scale = Settings.Global.getFloat( - contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1.0f + contentResolver, + Settings.Global.ANIMATOR_DURATION_SCALE, + 1.0f ) val duration = resources.getInteger(android.R.integer.config_mediumAnimTime) * scale delay(duration.toLong()) @@ -372,7 +384,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { ) { val recentsItem = bottom_nav.getItemView(R.id.nav_recents) ?: return preferences.shownDownloadQueueTutorial().set(true) - TapTargetView.showFor(this, + TapTargetView.showFor( + this, TapTarget.forView( recentsItem, getString(R.string.manage_whats_downloading), @@ -387,7 +400,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { super.onTargetClick(view) bottom_nav.selectedItemId = R.id.nav_recents } - }) + } + ) } } @@ -398,7 +412,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { private fun getAppUpdates() { if (isUpdaterEnabled && - Date().time >= preferences.lastAppCheck().get() + TimeUnit.DAYS.toMillis(1)) { + Date().time >= preferences.lastAppCheck().get() + TimeUnit.DAYS.toMillis(1) + ) { lifecycleScope.launch(Dispatchers.IO) { try { val result = updateChecker.checkForUpdate() @@ -441,7 +456,9 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { protected open fun handleIntentAction(intent: Intent): Boolean { val notificationId = intent.getIntExtra("notificationId", -1) if (notificationId > -1) NotificationReceiver.dismissNotification( - applicationContext, notificationId, intent.getIntExtra("groupId", 0) + applicationContext, + notificationId, + intent.getIntExtra("groupId", 0) ) when (intent.action) { SHORTCUT_LIBRARY -> bottom_nav.selectedItemId = R.id.nav_library @@ -508,8 +525,8 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { R.id.action_settings -> { router.pushController( (RouterTransaction.with(SettingsMainController())).popChangeHandler( - FadeChangeHandler() - ).pushChangeHandler(FadeChangeHandler()) + FadeChangeHandler() + ).pushChangeHandler(FadeChangeHandler()) ) } else -> return super.onOptionsItemSelected(item) @@ -528,10 +545,9 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { extraViewForUndo?.getGlobalVisibleRect(extRect) // This way the snackbar will only be dismissed if // the user clicks outside it. - if (canDismissSnackBar && !sRect.contains( - ev.x.toInt(), - ev.y.toInt() - ) && (extRect == null || !extRect.contains(ev.x.toInt(), ev.y.toInt())) + if (canDismissSnackBar && + !sRect.contains(ev.x.toInt(), ev.y.toInt()) && + (extRect == null || !extRect.contains(ev.x.toInt(), ev.y.toInt())) ) { snackBar?.dismiss() snackBar = null @@ -567,14 +583,17 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { animationSet?.cancel() animationSet = AnimatorSet() val alphaAnimation = ValueAnimator.ofFloat( - bottom_nav.alpha, if (hideBottomNav) 0f else 1f + bottom_nav.alpha, + if (hideBottomNav) 0f else 1f ) alphaAnimation.addUpdateListener { valueAnimator -> bottom_nav.alpha = valueAnimator.animatedValue as Float } - alphaAnimation.addListener(EndAnimatorListener { - bottom_nav.visibility = if (hideBottomNav) View.GONE else View.VISIBLE - }) + alphaAnimation.addListener( + EndAnimatorListener { + bottom_nav.visibility = if (hideBottomNav) View.GONE else View.VISIBLE + } + ) alphaAnimation.duration = 200 alphaAnimation.startDelay = 50 animationSet?.playTogether(alphaAnimation) @@ -610,9 +629,10 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { if (abs(diffX) <= abs(diffY)) { val sheetRect = Rect() bottom_nav.getGlobalVisibleRect(sheetRect) - if (sheetRect.contains( - e1.x.toInt(), e1.y.toInt() - ) && abs(diffY) > Companion.SWIPE_THRESHOLD && abs(velocityY) > Companion.SWIPE_VELOCITY_THRESHOLD && diffY <= 0 + if (sheetRect.contains(e1.x.toInt(), e1.y.toInt()) && + abs(diffY) > Companion.SWIPE_THRESHOLD && + abs(velocityY) > Companion.SWIPE_VELOCITY_THRESHOLD && + diffY <= 0 ) { val bottomSheetController = router.backstack.lastOrNull()?.controller() as? BottomSheetController diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/main/SearchActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/main/SearchActivity.kt index c8a7f68f5d..4f6b650186 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/main/SearchActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/main/SearchActivity.kt @@ -64,7 +64,9 @@ class SearchActivity : MainActivity() { override fun handleIntentAction(intent: Intent): Boolean { val notificationId = intent.getIntExtra("notificationId", -1) if (notificationId > -1) NotificationReceiver.dismissNotification( - applicationContext, notificationId, intent.getIntExtra("groupId", 0) + applicationContext, + notificationId, + intent.getIntExtra("groupId", 0) ) when (intent.action) { Intent.ACTION_SEARCH, "com.google.android.gms.actions.SEARCH_ACTION" -> { @@ -91,8 +93,9 @@ class SearchActivity : MainActivity() { val extras = intent.extras ?: return false router.replaceTopController( RouterTransaction.with(MangaDetailsController(extras)) - .pushChangeHandler(SimpleSwapChangeHandler()) - .popChangeHandler(FadeChangeHandler())) + .pushChangeHandler(SimpleSwapChangeHandler()) + .popChangeHandler(FadeChangeHandler()) + ) } else -> return false } @@ -100,8 +103,11 @@ class SearchActivity : MainActivity() { } companion object { - fun openMangaIntent(context: Context, id: Long) = Intent(context, SearchActivity::class - .java) + fun openMangaIntent(context: Context, id: Long) = Intent( + context, + SearchActivity::class + .java + ) .apply { action = SHORTCUT_MANGA putExtra(MangaDetailsController.MANGA_EXTRA, id) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/EditMangaDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/EditMangaDialog.kt index f3b116139d..99750859e4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/EditMangaDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/EditMangaDialog.kt @@ -33,10 +33,12 @@ class EditMangaDialog : DialogController { private val infoController get() = targetController as MangaDetailsController - constructor(target: MangaDetailsController, manga: Manga) : super(Bundle() - .apply { - putLong(KEY_MANGA, manga.id!!) - }) { + constructor(target: MangaDetailsController, manga: Manga) : super( + Bundle() + .apply { + putLong(KEY_MANGA, manga.id!!) + } + ) { targetController = target this.manga = manga } @@ -44,7 +46,7 @@ class EditMangaDialog : DialogController { @Suppress("unused") constructor(bundle: Bundle) : super(bundle) { manga = Injekt.get().getManga(bundle.getLong(KEY_MANGA)) - .executeAsBlocking()!! + .executeAsBlocking()!! } override fun onCreateDialog(savedViewState: Bundle?): Dialog { @@ -99,7 +101,8 @@ class EditMangaDialog : DialogController { if (manga.originalDescription != null) { view.manga_description.hint = "${resources?.getString(R.string.description)}: ${manga.originalDescription?.replace( - "\n", " " + "\n", + " " )?.chop(20)}" } } @@ -110,9 +113,12 @@ class EditMangaDialog : DialogController { view.reset_tags.setOnClickListener { resetTags() } view.reset_cover.visibleIf(!isLocal) view.reset_cover.setOnClickListener { - view.manga_cover.loadAny(manga, builder = { - parameters(Parameters.Builder().set(MangaFetcher.realCover, true).build()) - }) + view.manga_cover.loadAny( + manga, + builder = { + parameters(Parameters.Builder().set(MangaFetcher.realCover, true).build()) + } + ) willResetCover = true } } @@ -136,10 +142,15 @@ class EditMangaDialog : DialogController { } private fun onPositiveButtonClick() { - infoController.presenter.updateManga(dialogView?.title?.text.toString(), - dialogView?.manga_author?.text.toString(), dialogView?.manga_artist?.text.toString(), - customCoverUri, dialogView?.manga_description?.text.toString(), - dialogView?.manga_genres_tags?.tags, willResetCover) + infoController.presenter.updateManga( + dialogView?.title?.text.toString(), + dialogView?.manga_author?.text.toString(), + dialogView?.manga_artist?.text.toString(), + customCoverUri, + dialogView?.manga_description?.text.toString(), + dialogView?.manga_genres_tags?.tags, + willResetCover + ) } private companion object { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsAdapter.kt index 90964874ba..1e7cab04ec 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsAdapter.kt @@ -26,8 +26,11 @@ class MangaDetailsAdapter( val delegate: MangaDetailsInterface = controller val presenter = controller.presenter - val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols() - .apply { decimalSeparator = '.' }) + val decimalFormat = DecimalFormat( + "#.###", + DecimalFormatSymbols() + .apply { decimalSeparator = '.' } + ) fun setChapters(items: List?) { this.items = items ?: emptyList() @@ -47,10 +50,12 @@ class MangaDetailsAdapter( if (s.isNullOrBlank()) { updateDataSet(items) } else { - updateDataSet(items.filter { - it.name.contains(s, true) || - it.scanlator?.contains(s, true) == true - }) + updateDataSet( + items.filter { + it.name.contains(s, true) || + it.scanlator?.contains(s, true) == true + } + ) } } @@ -71,14 +76,16 @@ class MangaDetailsAdapter( if (volume != null) { recyclerView.context.getString( if (scrollType == MangaDetailsPresenter.MULTIPLE_SEASONS) R.string.season_ - else R.string.volume_, volume + else R.string.volume_, + volume ) } else { getChapterName(chapter) } } MangaDetailsPresenter.TENS_OF_CHAPTERS -> recyclerView.context.getString( - R.string.chapters_, get10sRange( + R.string.chapters_, + get10sRange( chapter.chapter_number ) ) @@ -89,7 +96,8 @@ class MangaDetailsAdapter( private fun getChapterName(item: ChapterItem): String { return if (item.chapter_number > 0) { recyclerView.context.getString( - R.string.chapter_, decimalFormat.format(item.chapter_number) + R.string.chapter_, + decimalFormat.format(item.chapter_number) ) } else { item.name diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsController.kt index 1df61ecea8..9a32e39c4d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsController.kt @@ -110,7 +110,8 @@ import java.io.IOException import java.util.Locale import kotlin.math.max -class MangaDetailsController : BaseController, +class MangaDetailsController : + BaseController, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, ActionMode.Callback, @@ -124,12 +125,14 @@ class MangaDetailsController : BaseController, fromCatalogue: Boolean = false, smartSearchConfig: SourceController.SmartSearchConfig? = null, update: Boolean = false - ) : super(Bundle().apply { - putLong(MANGA_EXTRA, manga?.id ?: 0) - putBoolean(FROM_CATALOGUE_EXTRA, fromCatalogue) - putParcelable(SMART_SEARCH_CONFIG_EXTRA, smartSearchConfig) - putBoolean(UPDATE_EXTRA, update) - }) { + ) : super( + Bundle().apply { + putLong(MANGA_EXTRA, manga?.id ?: 0) + putBoolean(FROM_CATALOGUE_EXTRA, fromCatalogue) + putParcelable(SMART_SEARCH_CONFIG_EXTRA, smartSearchConfig) + putBoolean(UPDATE_EXTRA, update) + } + ) { this.manga = manga if (manga != null) { source = Injekt.get().getOrStub(manga.source) @@ -145,7 +148,9 @@ class MangaDetailsController : BaseController, val notificationId = bundle.getInt("notificationId", -1) val context = applicationContext ?: return if (notificationId > -1) NotificationReceiver.dismissNotification( - context, notificationId, bundle.getInt("groupId", 0) + context, + notificationId, + bundle.getInt("groupId", 0) ) } @@ -227,26 +232,34 @@ class MangaDetailsController : BaseController, swipe_refresh.setDistanceToTriggerSync(70.dpToPx) activity!!.appbar.elevation = 0f - scrollViewWith(recycler, padBottom = true, customPadding = true, afterInsets = { insets -> - setInsets(insets, appbarHeight, offset) - }, liftOnScroll = { - colorToolbar(it) - }) - - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - super.onScrolled(recyclerView, dx, dy) - val atTop = !recyclerView.canScrollVertically(-1) - val tY = getHeader()?.backdrop?.translationY ?: 0f - getHeader()?.backdrop?.translationY = max(0f, tY + dy * 0.25f) - if (atTop) getHeader()?.backdrop?.translationY = 0f + scrollViewWith( + recycler, + padBottom = true, + customPadding = true, + afterInsets = { insets -> + setInsets(insets, appbarHeight, offset) + }, + liftOnScroll = { + colorToolbar(it) } + ) - override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { - val atTop = !recyclerView.canScrollVertically(-1) - if (atTop) getHeader()?.backdrop?.translationY = 0f + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + super.onScrolled(recyclerView, dx, dy) + val atTop = !recyclerView.canScrollVertically(-1) + val tY = getHeader()?.backdrop?.translationY ?: 0f + getHeader()?.backdrop?.translationY = max(0f, tY + dy * 0.25f) + if (atTop) getHeader()?.backdrop?.translationY = 0f + } + + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + val atTop = !recyclerView.canScrollVertically(-1) + if (atTop) getHeader()?.backdrop?.translationY = 0f + } } - }) + ) } private fun setInsets(insets: WindowInsets, appbarHeight: Int, offset: Int) { @@ -280,15 +293,19 @@ class MangaDetailsController : BaseController, if (colorAnimator?.isRunning == true) activity?.window?.statusBarColor ?: color else ColorUtils.setAlphaComponent( - color, if (toolbarIsColored) 0 else 175 + color, + if (toolbarIsColored) 0 else 175 ) val colorTo = ColorUtils.setAlphaComponent( - color, if (toolbarIsColored) 175 else 0 + color, + if (toolbarIsColored) 175 else 0 ) colorAnimator?.cancel() if (animate) { colorAnimator = ValueAnimator.ofObject( - android.animation.ArgbEvaluator(), colorFrom, colorTo + android.animation.ArgbEvaluator(), + colorFrom, + colorTo ) colorAnimator?.duration = 250 // milliseconds colorAnimator?.addUpdateListener { animator -> @@ -307,35 +324,38 @@ class MangaDetailsController : BaseController, val view = view ?: return val request = LoadRequest.Builder(view.context).data(presenter.manga).allowHardware(false) - .target(onSuccess = { drawable -> - val bitmap = (drawable as BitmapDrawable).bitmap - // Generate the Palette on a background thread. - Palette.from(bitmap).generate { - if (recycler == null || it == null) return@generate - val colorBack = view.context.getResourceColor( - android.R.attr.colorBackground - ) - // this makes the color more consistent regardless of theme - val backDropColor = - ColorUtils.blendARGB(it.getVibrantColor(colorBack), colorBack, .35f) + .target( + onSuccess = { drawable -> + val bitmap = (drawable as BitmapDrawable).bitmap + // Generate the Palette on a background thread. + Palette.from(bitmap).generate { + if (recycler == null || it == null) return@generate + val colorBack = view.context.getResourceColor( + android.R.attr.colorBackground + ) + // this makes the color more consistent regardless of theme + val backDropColor = + ColorUtils.blendARGB(it.getVibrantColor(colorBack), colorBack, .35f) - coverColor = backDropColor - getHeader()?.setBackDrop(backDropColor) - if (toolbarIsColored) { - val translucentColor = ColorUtils.setAlphaComponent(backDropColor, 175) - (activity as MainActivity).toolbar.setBackgroundColor(translucentColor) - activity?.window?.statusBarColor = translucentColor + coverColor = backDropColor + getHeader()?.setBackDrop(backDropColor) + if (toolbarIsColored) { + val translucentColor = ColorUtils.setAlphaComponent(backDropColor, 175) + (activity as MainActivity).toolbar.setBackgroundColor(translucentColor) + activity?.window?.statusBarColor = translucentColor + } + } + manga_cover_full.setImageDrawable(drawable) + getHeader()?.updateCover(manga!!) + }, + onError = { + val file = presenter.coverCache.getCoverFile(manga!!) + if (file.exists()) { + file.delete() + setPaletteColor() } } - manga_cover_full.setImageDrawable(drawable) - getHeader()?.updateCover(manga!!) - }, onError = { - val file = presenter.coverCache.getCoverFile(manga!!) - if (file.exists()) { - file.delete() - setPaletteColor() - } - }).build() + ).build() Coil.imageLoader(view.context).execute(request) } @@ -343,10 +363,7 @@ class MangaDetailsController : BaseController, private fun setActionBar(forThis: Boolean) { val activity = activity ?: return // if the theme is using inverted toolbar color - if (!activity.isInNightMode() && ThemeUtil.isBlueTheme( - presenter.preferences.theme() - ) - ) { + if (!activity.isInNightMode() && ThemeUtil.isBlueTheme(presenter.preferences.theme())) { if (forThis) (activity as MainActivity).appbar.context.setTheme( R.style.ThemeOverlay_AppCompat_DayNight_ActionBar ) @@ -481,10 +498,12 @@ class MangaDetailsController : BaseController, 1 -> return else -> { MaterialDialog(context).title(R.string.chapters_removed).message( - text = context.resources.getQuantityString(R.plurals.deleted_chapters, + text = context.resources.getQuantityString( + R.plurals.deleted_chapters, deletedChapters.size, deletedChapters.size, - deletedChapters.joinToString("\n") { "${it.name}" }) + deletedChapters.joinToString("\n") { "${it.name}" } + ) ).positiveButton(R.string.delete) { presenter.deleteChapters(deletedChapters, false) if (it.isCheckPromptChecked()) deleteRemovedPref.set(2) @@ -502,7 +521,8 @@ class MangaDetailsController : BaseController, //region Recycler methods fun updateChapterDownload(download: Download) { getHolder(download.chapter)?.notifyStatus( - download.status, presenter.isLockedFromSearch, + download.status, + presenter.isLockedFromSearch, download.progress ) } @@ -638,7 +658,8 @@ class MangaDetailsController : BaseController, snack?.dismiss() snack = view?.snack( if (bookmarked) R.string.removed_bookmark - else R.string.bookmarked, Snackbar.LENGTH_INDEFINITE + else R.string.bookmarked, + Snackbar.LENGTH_INDEFINITE ) { setAction(R.string.undo) { bookmarkChapters(listOf(item), bookmarked) @@ -657,21 +678,24 @@ class MangaDetailsController : BaseController, snack?.dismiss() snack = view?.snack( if (read) R.string.marked_as_unread - else R.string.marked_as_read, Snackbar.LENGTH_INDEFINITE + else R.string.marked_as_read, + Snackbar.LENGTH_INDEFINITE ) { var undoing = false setAction(R.string.undo) { presenter.markChaptersRead(listOf(item), read, true, lastRead, pagesLeft) undoing = true } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!undoing && !read && presenter.preferences.removeAfterMarkedAsRead()) { - presenter.deleteChapters(listOf(item)) + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!undoing && !read && presenter.preferences.removeAfterMarkedAsRead()) { + presenter.deleteChapters(listOf(item)) + } } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } @@ -707,7 +731,7 @@ class MangaDetailsController : BaseController, presenter.anyRead() && !presenter.isLockedFromSearch menu.findItem(R.id.action_remove_downloads).isVisible = presenter.hasDownloads() && !presenter.isLockedFromSearch && - manga?.source != LocalSource.ID + manga?.source != LocalSource.ID menu.findItem(R.id.remove_non_bookmarked).isVisible = presenter.hasBookmark() && !presenter.isLockedFromSearch menu.findItem(R.id.action_migrate).isVisible = !presenter.isLockedFromSearch && @@ -748,7 +772,8 @@ class MangaDetailsController : BaseController, when (item.itemId) { R.id.action_edit -> { editMangaDialog = EditMangaDialog( - this, presenter.manga + this, + presenter.manga ) editMangaDialog?.showDialog(router) } @@ -781,11 +806,14 @@ class MangaDetailsController : BaseController, override fun prepareToShareManga() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - val request = LoadRequest.Builder(activity!!).data(manga).target(onError = { - shareManga() - }, onSuccess = { - presenter.shareManga((it as BitmapDrawable).bitmap) - }).build() + val request = LoadRequest.Builder(activity!!).data(manga).target( + onError = { + shareManga() + }, + onSuccess = { + presenter.shareManga((it as BitmapDrawable).bitmap) + } + ).build() Coil.imageLoader(activity!!).execute(request) } else { shareManga() @@ -825,7 +853,10 @@ class MangaDetailsController : BaseController, val activity = activity ?: return val intent = WebViewActivity.newIntent( - activity.applicationContext, source.id, url, presenter.manga + activity.applicationContext, + source.id, + url, + presenter.manga .title ) startActivity(intent) @@ -847,7 +878,9 @@ class MangaDetailsController : BaseController, val context = view?.context ?: return MaterialDialog(context).message( text = context.resources.getQuantityString( - R.plurals.remove_n_chapters, chapters.size, chapters.size + R.plurals.remove_n_chapters, + chapters.size, + chapters.size ) ).positiveButton(R.string.remove) { presenter.deleteChapters(chapters) @@ -901,22 +934,27 @@ class MangaDetailsController : BaseController, val view = view ?: return presenter.downloadChapters(chapters) val text = view.context.getString( - R.string.add_x_to_library, presenter.manga.mangaType - (view.context).toLowerCase(Locale.ROOT) + R.string.add_x_to_library, + presenter.manga.mangaType + (view.context).toLowerCase(Locale.ROOT) ) - if (!presenter.manga.favorite && (snack == null || - snack?.getText() != text) + if (!presenter.manga.favorite && ( + snack == null || + snack?.getText() != text + ) ) { snack = view.snack(text, Snackbar.LENGTH_INDEFINITE) { setAction(R.string.add) { presenter.setFavorite(true) } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (snack == transientBottomBar) snack = null + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (snack == transientBottomBar) snack = null + } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } @@ -935,17 +973,18 @@ class MangaDetailsController : BaseController, val item = presenter.getNextUnreadChapter() if (item != null) { openChapter(item.chapter) - } else if (snack == null || snack?.getText() != view?.context?.getString( - R.string.next_chapter_not_found - ) + } else if (snack == null || + snack?.getText() != view?.context?.getString(R.string.next_chapter_not_found) ) { snack = view?.snack(R.string.next_chapter_not_found, Snackbar.LENGTH_LONG) { - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (snack == transientBottomBar) snack = null + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (snack == transientBottomBar) snack = null + } } - }) + ) } } } @@ -1023,7 +1062,10 @@ class MangaDetailsController : BaseController, categories.indexOfFirst { it.id == id }.takeIf { it != -1 } }.toTypedArray() ChangeMangaCategoriesDialog( - this, listOf(manga), categories, preselected + this, + listOf(manga), + categories, + preselected ).showDialog( router ) @@ -1080,12 +1122,14 @@ class MangaDetailsController : BaseController, setAction(R.string.undo) { presenter.setFavorite(true) } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!presenter.manga.favorite) presenter.confirmDeletion() + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!presenter.manga.favorite) presenter.confirmDeletion() + } } - }) + ) } val favButton = getHeader()?.favorite_button (activity as? MainActivity)?.setUndoSnackBar(snack, favButton) @@ -1204,7 +1248,9 @@ class MangaDetailsController : BaseController, if (startingDLChapterPos != null) { val item = adapter?.getItem(startingDLChapterPos!!) as? ChapterItem (recycler.findViewHolderForAdapterPosition(startingDLChapterPos!!) as? ChapterHolder)?.notifyStatus( - item?.status ?: Download.NOT_DOWNLOADED, false, 0 + item?.status ?: Download.NOT_DOWNLOADED, + false, + 0 ) } startingDLChapterPos = null @@ -1308,18 +1354,20 @@ class MangaDetailsController : BaseController, ) duration = shortAnimationDuration.toLong() interpolator = DecelerateInterpolator() - addListener(object : AnimatorListenerAdapter() { + addListener( + object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator) { - TransitionManager.endTransitions(frame_layout) - currentAnimator = null - } + override fun onAnimationEnd(animation: Animator) { + TransitionManager.endTransitions(frame_layout) + currentAnimator = null + } - override fun onAnimationCancel(animation: Animator) { - TransitionManager.endTransitions(frame_layout) - currentAnimator = null + override fun onAnimationCancel(animation: Animator) { + TransitionManager.endTransitions(frame_layout) + currentAnimator = null + } } - }) + ) start() } @@ -1351,24 +1399,26 @@ class MangaDetailsController : BaseController, play(ObjectAnimator.ofFloat(fullBackdrop, View.ALPHA, 0f)) duration = shortAnimationDuration.toLong() interpolator = DecelerateInterpolator() - addListener(object : AnimatorListenerAdapter() { + addListener( + object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator) { - thumbView.alpha = 1f - expandedImageView.visibility = View.GONE - fullBackdrop.visibility = View.GONE - swipe_refresh.isEnabled = true - currentAnimator = null - } + override fun onAnimationEnd(animation: Animator) { + thumbView.alpha = 1f + expandedImageView.visibility = View.GONE + fullBackdrop.visibility = View.GONE + swipe_refresh.isEnabled = true + currentAnimator = null + } - override fun onAnimationCancel(animation: Animator) { - thumbView.alpha = 1f - expandedImageView.visibility = View.GONE - fullBackdrop.visibility = View.GONE - swipe_refresh.isEnabled = true - currentAnimator = null + override fun onAnimationCancel(animation: Animator) { + thumbView.alpha = 1f + expandedImageView.visibility = View.GONE + fullBackdrop.visibility = View.GONE + swipe_refresh.isEnabled = true + currentAnimator = null + } } - }) + ) start() } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsPresenter.kt index ee1ab8f2b7..4da74f6c84 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaDetailsPresenter.kt @@ -353,8 +353,10 @@ class MangaDetailsPresenter( val categoriesToDownload = preferences.downloadNewCategories().getOrDefault().map(String::toInt) val shouldDownload = categoriesToDownload.isEmpty() || getMangaCategoryIds().any { it in categoriesToDownload } if (shouldDownload) { - downloadChapters(newChapters.first.sortedBy { it.chapter_number } - .map { it.toModel() }) + downloadChapters( + newChapters.first.sortedBy { it.chapter_number } + .map { it.toModel() } + ) } } } @@ -419,9 +421,11 @@ class MangaDetailsPresenter( } private fun trimException(e: java.lang.Exception): String { - return (if (e.message?.contains(": ") == true) e.message?.split(": ")?.drop(1) - ?.joinToString(": ") - else e.message) ?: preferences.context.getString(R.string.unknown_error) + return ( + if (e.message?.contains(": ") == true) e.message?.split(": ")?.drop(1) + ?.joinToString(": ") + else e.message + ) ?: preferences.context.getString(R.string.unknown_error) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderHolder.kt index ddf42f9966..43562d4677 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderHolder.kt @@ -160,11 +160,13 @@ class MangaHeaderHolder( else expand() } manga_summary_label.text = itemView.context.getString( - R.string.about_this_, manga.mangaType(itemView.context) + R.string.about_this_, + manga.mangaType(itemView.context) ) with(favorite_button) { icon = ContextCompat.getDrawable( - itemView.context, when { + itemView.context, + when { item.isLocked -> R.drawable.ic_lock_24dp manga.favorite -> R.drawable.ic_heart_24dp else -> R.drawable.ic_heart_outline_24dp @@ -210,7 +212,8 @@ class MangaHeaderHolder( val number = adapter.decimalFormat.format(nextChapter.chapter_number.toDouble()) if (nextChapter.chapter_number > 0) resources.getString( if (nextChapter.last_page_read > 0) R.string.continue_reading_chapter_ - else R.string.start_reading_chapter_, number + else R.string.start_reading_chapter_, + number ) else { resources.getString( @@ -231,14 +234,16 @@ class MangaHeaderHolder( } manga_status.visibleIf(manga.status != 0) - manga_status.text = (itemView.context.getString( - when (manga.status) { - SManga.ONGOING -> R.string.ongoing - SManga.COMPLETED -> R.string.completed - SManga.LICENSED -> R.string.licensed - else -> R.string.unknown_status - } - )) + manga_status.text = ( + itemView.context.getString( + when (manga.status) { + SManga.ONGOING -> R.string.ongoing + SManga.COMPLETED -> R.string.completed + SManga.LICENSED -> R.string.licensed + else -> R.string.unknown_status + } + ) + ) manga_source.text = presenter.source.toString() filters_text.text = presenter.currentFilters() @@ -256,7 +261,8 @@ class MangaHeaderHolder( if (checked) { backgroundTintList = ColorStateList.valueOf( ColorUtils.setAlphaComponent( - context.getResourceColor(R.attr.colorAccent), 75 + context.getResourceColor(R.attr.colorAccent), + 75 ) ) strokeColor = ColorStateList.valueOf(Color.TRANSPARENT) @@ -287,7 +293,8 @@ class MangaHeaderHolder( ) icon = ContextCompat.getDrawable( - itemView.context, if (tracked) R.drawable + itemView.context, + if (tracked) R.drawable .ic_check_24dp else R.drawable.ic_sync_24dp ) checked(tracked) @@ -308,16 +315,22 @@ class MangaHeaderHolder( fun updateCover(manga: Manga) { if (!manga.initialized) return val drawable = adapter.controller.manga_cover_full?.drawable - manga_cover.loadAny(manga, builder = { - placeholder(drawable) - error(drawable) - if (manga.favorite) networkCachePolicy(CachePolicy.DISABLED) - }) - backdrop.loadAny(manga, builder = { - placeholder(drawable) - error(drawable) - if (manga.favorite) networkCachePolicy(CachePolicy.DISABLED) - }) + manga_cover.loadAny( + manga, + builder = { + placeholder(drawable) + error(drawable) + if (manga.favorite) networkCachePolicy(CachePolicy.DISABLED) + } + ) + backdrop.loadAny( + manga, + builder = { + placeholder(drawable) + error(drawable) + if (manga.favorite) networkCachePolicy(CachePolicy.DISABLED) + } + ) } fun expand() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/BaseChapterItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/BaseChapterItem.kt index dece86fe00..05c0bb68ff 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/BaseChapterItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/BaseChapterItem.kt @@ -8,7 +8,7 @@ import eu.kanade.tachiyomi.source.model.Page abstract class BaseChapterItem>( val chapter: -Chapter, + Chapter, header: H? = null ) : AbstractSectionableItem(header), diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterFilterLayout.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterFilterLayout.kt index 9c647e1462..219ec75cec 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterFilterLayout.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterFilterLayout.kt @@ -44,7 +44,9 @@ class ChapterFilterLayout @JvmOverloads constructor(context: Context, attrs: Att show_download.isChecked = manga.downloadedFilter == Manga.SHOW_DOWNLOADED show_bookmark.isChecked = manga.bookmarkedFilter == Manga.SHOW_BOOKMARKED - show_all.isChecked = !(show_read.isChecked || show_unread.isChecked || - show_download.isChecked || show_bookmark.isChecked) + show_all.isChecked = !( + show_read.isChecked || show_unread.isChecked || + show_download.isChecked || show_bookmark.isChecked + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterHolder.kt index c576cb4371..0ff4e0dbdc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterHolder.kt @@ -58,13 +58,16 @@ class ChapterHolder( if (showPagesLeft && chapter.pages_left > 0) { statuses.add( itemView.resources.getQuantityString( - R.plurals.pages_left, chapter.pages_left, chapter.pages_left + R.plurals.pages_left, + chapter.pages_left, + chapter.pages_left ) ) } else if (showPagesLeft) { statuses.add( itemView.context.getString( - R.string.page_, chapter.last_page_read + 1 + R.string.page_, + chapter.last_page_read + 1 ) ) } @@ -81,7 +84,10 @@ class ChapterHolder( } // this will color the scanlator the same bookmarks ChapterUtil.setTextViewForChapter( - chapter_scanlator, item, showBookmark = false, hideStatus = isLocked + chapter_scanlator, + item, + showBookmark = false, + hideStatus = isLocked ) chapter_scanlator.text = statuses.joinToString(" • ") @@ -115,9 +121,11 @@ class ChapterHolder( val anim3 = slideAnimation(-slide, 0f) anim3.startDelay = 750 animatorSet.playSequentially(anim1, anim2, anim3) - animatorSet.addListener(EndAnimatorListener { - adapter.hasShownSwipeTut.set(true) - }) + animatorSet.addListener( + EndAnimatorListener { + adapter.hasShownSwipeTut.set(true) + } + ) animatorSet.start() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersSortBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersSortBottomSheet.kt index 772aed0363..480e1ae1b1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersSortBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersSortBottomSheet.kt @@ -19,7 +19,7 @@ import kotlinx.android.synthetic.main.chapter_sort_bottom_sheet.* import kotlin.math.max class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetDialog - (controller.activity!!, R.style.BottomSheetDialogTheme) { +(controller.activity!!, R.style.BottomSheetDialogTheme) { val activity = controller.activity!! @@ -37,20 +37,22 @@ class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetD val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom sheetBehavior.peekHeight = 415.dpToPx + height - sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - if (progress.isNaN()) - pill.alpha = 0f - else - pill.alpha = (1 - max(0f, progress)) * 0.25f - } + sheetBehavior.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + if (progress.isNaN()) + pill.alpha = 0f + else + pill.alpha = (1 - max(0f, progress)) * 0.25f + } - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_EXPANDED) { + sheetBehavior.skipCollapsed = true + } } } - }) + ) } override fun onStart() { @@ -89,19 +91,27 @@ class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetD chapter_filter_layout.setCheckboxes(presenter.manga) var defPref = presenter.globalSort() - sort_group.check(if (presenter.manga.sortDescending(defPref)) R.id.sort_newest else - R.id.sort_oldest) + sort_group.check( + if (presenter.manga.sortDescending(defPref)) R.id.sort_newest else + R.id.sort_oldest + ) hide_titles.isChecked = presenter.manga.displayMode != Manga.DISPLAY_NAME - sort_method_group.check(if (presenter.manga.sorting == Manga.SORTING_SOURCE) R.id.sort_by_source else - R.id.sort_by_number) + sort_method_group.check( + if (presenter.manga.sorting == Manga.SORTING_SOURCE) R.id.sort_by_source else + R.id.sort_by_number + ) - set_as_default_sort.visInvisIf(defPref != presenter.manga.sortDescending() && - presenter.manga.usesLocalSort()) + set_as_default_sort.visInvisIf( + defPref != presenter.manga.sortDescending() && + presenter.manga.usesLocalSort() + ) sort_group.setOnCheckedChangeListener { _, checkedId -> presenter.setSortOrder(checkedId == R.id.sort_newest) - set_as_default_sort.visInvisIf(defPref != presenter.manga.sortDescending() && - presenter.manga.usesLocalSort()) + set_as_default_sort.visInvisIf( + defPref != presenter.manga.sortDescending() && + presenter.manga.usesLocalSort() + ) } set_as_default_sort.setOnClickListener { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackChaptersDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackChaptersDialog.kt index a6099dae9d..ce21d2ebce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackChaptersDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackChaptersDialog.kt @@ -19,9 +19,11 @@ class SetTrackChaptersDialog : DialogController private val item: TrackItem private lateinit var listener: Listener - constructor(target: T, item: TrackItem) : super(Bundle().apply { - putSerializable(KEY_ITEM_TRACK, item.track) - }) { + constructor(target: T, item: TrackItem) : super( + Bundle().apply { + putSerializable(KEY_ITEM_TRACK, item.track) + } + ) { listener = target this.item = item } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackScoreDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackScoreDialog.kt index 4efb4ebe4c..0f9a13b514 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackScoreDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackScoreDialog.kt @@ -18,9 +18,11 @@ class SetTrackScoreDialog : DialogController where T : SetTrackScoreDialog.Li private val item: TrackItem private lateinit var listener: Listener - constructor(target: T, item: TrackItem) : super(Bundle().apply { - putSerializable(KEY_ITEM_TRACK, item.track) - }) { + constructor(target: T, item: TrackItem) : super( + Bundle().apply { + putSerializable(KEY_ITEM_TRACK, item.track) + } + ) { listener = target this.item = item } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt index dc621058b6..ee9fbc7a90 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt @@ -17,9 +17,11 @@ class SetTrackStatusDialog : DialogController private val item: TrackItem private lateinit var listener: Listener - constructor(target: T, item: TrackItem) : super(Bundle().apply { - putSerializable(KEY_ITEM_TRACK, item.track) - }) { + constructor(target: T, item: TrackItem) : super( + Bundle().apply { + putSerializable(KEY_ITEM_TRACK, item.track) + } + ) { listener = target this.item = item } @@ -40,8 +42,11 @@ class SetTrackStatusDialog : DialogController return MaterialDialog(activity!!) .title(R.string.status) .negativeButton(android.R.string.cancel) - .listItemsSingleChoice(items = statusString, initialSelection = selectedIndex, - waitForPositiveButton = false) { dialog, position, _ -> + .listItemsSingleChoice( + items = statusString, + initialSelection = selectedIndex, + waitForPositiveButton = false + ) { dialog, position, _ -> listener.setStatus(item, position) dialog.dismiss() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt index 4fad573d15..95d933b3ce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt @@ -42,10 +42,13 @@ class TrackHolder(view: View, adapter: TrackAdapter) : BaseViewHolder(view) { R.string.all_chapters_read ) track.total_chapters > 0 -> context.getString( - R.string.chapter_x_of_y, track.last_chapter_read, track.total_chapters + R.string.chapter_x_of_y, + track.last_chapter_read, + track.total_chapters ) track.last_chapter_read > 0 -> context.getString( - R.string.chapter_, track.last_chapter_read.toString() + R.string.chapter_, + track.last_chapter_read.toString() ) else -> context.getString(R.string.not_started) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackRemoveDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackRemoveDialog.kt index 8ba87836d7..8858ba077a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackRemoveDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackRemoveDialog.kt @@ -19,9 +19,11 @@ class TrackRemoveDialog : DialogController private val item: TrackItem private lateinit var listener: Listener - constructor(target: T, item: TrackItem) : super(Bundle().apply { - putSerializable(KEY_ITEM_TRACK, item.track) - }) { + constructor(target: T, item: TrackItem) : super( + Bundle().apply { + putSerializable(KEY_ITEM_TRACK, item.track) + } + ) { listener = target this.item = item } @@ -42,11 +44,15 @@ class TrackRemoveDialog : DialogController if (item.service.canRemoveFromService()) { dialog.checkBoxPrompt( text = activity!!.getString( - R.string.remove_tracking_from_, item.service.name - ), isCheckedDefault = true, onToggle = null + R.string.remove_tracking_from_, + item.service.name + ), + isCheckedDefault = true, + onToggle = null ).positiveButton(R.string.remove) { listener.removeTracker( - item, it.isCheckPromptChecked() + item, + it.isCheckPromptChecked() ) } dialog.getCheckBoxPrompt().textSize = 16f diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSearchDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSearchDialog.kt index cd57e1fbad..31de90a90d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSearchDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSearchDialog.kt @@ -43,10 +43,12 @@ class TrackSearchDialog : DialogController { private lateinit var presenter: MangaDetailsPresenter - constructor(target: TrackingBottomSheet, service: TrackService, wasTracked: Boolean) : super(Bundle() - .apply { - putInt(KEY_SERVICE, service.id) - }) { + constructor(target: TrackingBottomSheet, service: TrackService, wasTracked: Boolean) : super( + Bundle() + .apply { + putInt(KEY_SERVICE, service.id) + } + ) { wasPreviouslyTracked = wasTracked bottomSheet = target presenter = target.presenter @@ -112,11 +114,11 @@ class TrackSearchDialog : DialogController { override fun onAttach(view: View) { super.onAttach(view) searchTextSubscription = dialogView!!.track_search.textChanges() - .skip(1) - .debounce(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) - .map { it.toString() } - .filter(String::isNotBlank) - .subscribe { search(it) } + .skip(1) + .debounce(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) + .map { it.toString() } + .filter(String::isNotBlank) + .subscribe { search(it) } } override fun onDetach(view: View) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackingBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackingBottomSheet.kt index 3628229ee7..ca1ca640bf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackingBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackingBottomSheet.kt @@ -19,7 +19,8 @@ import eu.kanade.tachiyomi.util.view.setEdgeToEdge import kotlinx.android.synthetic.main.tracking_bottom_sheet.* import timber.log.Timber -class TrackingBottomSheet(private val controller: MangaDetailsController) : BottomSheetDialog +class TrackingBottomSheet(private val controller: MangaDetailsController) : + BottomSheetDialog (controller.activity!!, R.style.BottomSheetDialogTheme), TrackAdapter.OnClickListener, SetTrackStatusDialog.Listener, @@ -45,15 +46,17 @@ class TrackingBottomSheet(private val controller: MangaDetailsController) : Bott val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom sheetBehavior.peekHeight = 380.dpToPx + height - sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { } + sheetBehavior.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { } - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_EXPANDED) { + sheetBehavior.skipCollapsed = true + } } } - }) + ) } override fun onStart() { @@ -107,7 +110,7 @@ class TrackingBottomSheet(private val controller: MangaDetailsController) : Bott activity.toast(error.message) } - override fun onLogoClick(position: Int) { + override fun onLogoClick(position: Int) { val track = adapter?.getItem(position)?.track ?: return if (controller.isNotOnline()) { dismiss() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaAdapter.kt index a2860c2e58..5cf41f0cd6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaAdapter.kt @@ -4,7 +4,7 @@ import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible class MangaAdapter(controller: MigrationController) : - FlexibleAdapter>(null, controller) { + FlexibleAdapter>(null, controller) { private var items: List>? = null diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationController.kt index d49a515abf..8e34950563 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationController.kt @@ -22,10 +22,11 @@ import rx.schedulers.Schedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -class MigrationController : NucleusController(), - FlexibleAdapter.OnItemClickListener, - SourceAdapter.OnAllClickListener, - MigrationInterface { +class MigrationController : + NucleusController(), + FlexibleAdapter.OnItemClickListener, + SourceAdapter.OnAllClickListener, + MigrationInterface { private var adapter: FlexibleAdapter>? = null @@ -105,9 +106,11 @@ class MigrationController : NucleusController(), val item = adapter?.getItem(position) ?: return false if (item is MangaItem) { - PreMigrationController.navigateToMigration(Injekt.get().skipPreMigration().getOrDefault(), + PreMigrationController.navigateToMigration( + Injekt.get().skipPreMigration().getOrDefault(), router, - listOf(item.manga.id!!)) + listOf(item.manga.id!!) + ) } else if (item is SourceItem) { presenter.setSelectedSource(item.source) } @@ -124,9 +127,11 @@ class MigrationController : NucleusController(), val sourceMangas = manga.asSequence().filter { it.source == item.source.id }.map { it.id!! }.toList() withContext(Dispatchers.Main) { - PreMigrationController.navigateToMigration(Injekt.get().skipPreMigration().getOrDefault(), + PreMigrationController.navigateToMigration( + Injekt.get().skipPreMigration().getOrDefault(), router, - sourceMangas) + sourceMangas + ) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationMangaDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationMangaDialog.kt index d965fc031b..cddcb917fe 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationMangaDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationMangaDialog.kt @@ -23,10 +23,15 @@ class MigrationMangaDialog(bundle: Bundle? = null) : DialogController(bundle) override fun onCreateDialog(savedViewState: Bundle?): Dialog { val confirmRes = if (copy) R.plurals.copy_manga else R.plurals.migrate_manga - val confirmString = activity?.resources?.getQuantityString(confirmRes, mangaSet, - mangaSet, ( - if (mangaSkipped > 0) " " + view?.context?.getString(R.string.skipping_, mangaSkipped) - else "")) ?: "" + val confirmString = activity?.resources?.getQuantityString( + confirmRes, + mangaSet, + mangaSet, + ( + if (mangaSkipped > 0) " " + view?.context?.getString(R.string.skipping_, mangaSkipped) + else "" + ) + ) ?: "" return MaterialDialog(activity!!).show { message(text = confirmString) positiveButton(if (copy) R.string.copy_value else R.string.migrate) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationPresenter.kt index c3eaef94e1..ca2825934b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationPresenter.kt @@ -39,8 +39,10 @@ class MigrationPresenter( db.getFavoriteMangas().asRxObservable().observeOn(AndroidSchedulers.mainThread()) .doOnNext { state = state.copy(sourcesWithManga = findSourcesWithManga(it)) } - .combineLatest(stateRelay.map { it.selectedSource } - .distinctUntilChanged()) { library, source -> library to source } + .combineLatest( + stateRelay.map { it.selectedSource } + .distinctUntilChanged() + ) { library, source -> library to source } .filter { (_, source) -> source != null }.observeOn(Schedulers.io()) .map { (library, source) -> libraryToMigrationItem(library, source!!.id) } .observeOn(AndroidSchedulers.mainThread()) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt index f069ff98de..6522af0536 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt @@ -140,19 +140,21 @@ class SearchController( val preselected = MigrationFlags.getEnabledFlagsPositions(prefValue) return MaterialDialog(activity!!) - .message(R.string.data_to_include_in_migration) - .listItemsMultiChoice(items = MigrationFlags.titles.map + .message(R.string.data_to_include_in_migration) + .listItemsMultiChoice( + items = MigrationFlags.titles.map { resources?.getString(it) as CharSequence }, - initialSelection = preselected.toIntArray()) { _, positions, _ -> - val newValue = MigrationFlags.getFlagsFromPositions(positions.toTypedArray()) - preferences.migrateFlags().set(newValue) - } - .positiveButton(R.string.migrate) { - (targetController as? SearchController)?.migrateManga() - } - .negativeButton(R.string.copy_value) { - (targetController as? SearchController)?.copyManga() - } + initialSelection = preselected.toIntArray() + ) { _, positions, _ -> + val newValue = MigrationFlags.getFlagsFromPositions(positions.toTypedArray()) + preferences.migrateFlags().set(newValue) + } + .positiveButton(R.string.migrate) { + (targetController as? SearchController)?.migrateManga() + } + .negativeButton(R.string.copy_value) { + (targetController as? SearchController)?.copyManga() + } } } @@ -170,17 +172,19 @@ class SearchController( val searchItem = menu.findItem(R.id.action_search) val searchView = searchItem.actionView as SearchView - searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { - override fun onMenuItemActionExpand(item: MenuItem?): Boolean { - searchView.onActionViewExpanded() // Required to show the query in the view - searchView.setQuery(presenter.query, false) - return true - } + searchItem.setOnActionExpandListener( + object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem?): Boolean { + searchView.onActionViewExpanded() // Required to show the query in the view + searchView.setQuery(presenter.query, false) + return true + } - override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { - return true + override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { + return true + } } - }) + ) searchView.queryTextChangeEvents() .filter { it.isSubmitted } @@ -193,7 +197,7 @@ class SearchController( override fun canChangeTabs(block: () -> Unit): Boolean { val migrationListController = router.getControllerWithTag(MigrationListController.TAG) - as? BottomNavBarInterface + as? BottomNavBarInterface if (migrationListController != null) return migrationListController.canChangeTabs(block) return true } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchPresenter.kt index 4dea5351b4..30e8830158 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchPresenter.kt @@ -15,7 +15,7 @@ class SearchPresenter( override fun getEnabledSources(): List { // Put the source of the selected manga at the top return super.getEnabledSources() - .sortedByDescending { it.id == manga.source } + .sortedByDescending { it.id == manga.source } } override fun createCatalogueSearchItem(source: CatalogueSource, results: List?): GlobalSearchItem { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceAdapter.kt index 27d8f512be..a0b4185174 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceAdapter.kt @@ -9,7 +9,7 @@ import eu.davidea.flexibleadapter.items.IFlexible * @param controller instance of [MigrationController]. */ class SourceAdapter(val controller: MigrationController) : - FlexibleAdapter>(null, controller, true) { + FlexibleAdapter>(null, controller, true) { private var items: List>? = null diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceHolder.kt index 65bfadab94..35ecaa1903 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceHolder.kt @@ -8,7 +8,7 @@ import kotlinx.android.synthetic.main.source_item.edit_button import kotlinx.android.synthetic.main.source_item.title class SourceHolder(view: View, val adapter: SourceAdapter) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { init { migration_all.setOnClickListener { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceItem.kt index 267c625841..3c7c92bd3f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SourceItem.kt @@ -15,7 +15,7 @@ import eu.kanade.tachiyomi.source.Source * @param header The header for this item. */ data class SourceItem(val source: Source, val header: SelectionHeader? = null) : - AbstractSectionableItem(header) { + AbstractSectionableItem(header) { /** * Returns the layout resource of this item. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationBottomSheetDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationBottomSheetDialog.kt index 03fe0998cf..589afef64f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationBottomSheetDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationBottomSheetDialog.kt @@ -64,7 +64,8 @@ class MigrationBottomSheetDialog( setEdgeToEdge(activity, view) setBottomEdge( if (activity.resources.configuration?.orientation == Configuration.ORIENTATION_LANDSCAPE) extra_search_param_text - else skip_step, activity + else skip_step, + activity ) } @@ -114,7 +115,8 @@ class MigrationBottomSheetDialog( skip_step.isChecked = preferences.skipPreMigration().getOrDefault() skip_step.setOnCheckedChangeListener { _, isChecked -> if (isChecked) (listener as? Controller)?.activity?.toast( - R.string.to_show_again_setting_sources, Toast.LENGTH_LONG + R.string.to_show_again_setting_sources, + Toast.LENGTH_LONG ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceAdapter.kt index 7056d18da2..39821522f4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceAdapter.kt @@ -9,16 +9,21 @@ class MigrationSourceAdapter( var items: List, val controllerPre: PreMigrationController ) : FlexibleAdapter( - items, - controllerPre, - true + items, + controllerPre, + true ) { override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) - outState.putParcelableArrayList(SELECTED_SOURCES_KEY, ArrayList(currentItems.map { - it.asParcelable() - })) + outState.putParcelableArrayList( + SELECTED_SOURCES_KEY, + ArrayList( + currentItems.map { + it.asParcelable() + } + ) + ) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceHolder.kt index 3dff9740db..4f650de380 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceHolder.kt @@ -11,7 +11,7 @@ import kotlinx.android.synthetic.main.migration_source_item.* import uy.kohesive.injekt.injectLazy class MigrationSourceHolder(view: View, val adapter: MigrationSourceAdapter) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { init { setDragHandleView(reorder) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceItem.kt index de66151e41..a9c95ac55e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/MigrationSourceItem.kt @@ -66,8 +66,8 @@ class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean) : val source = sourceManager.get(si.sourceId) as? HttpSource ?: return null return MigrationSourceItem( - source, - si.sourceEnabled + source, + si.sourceEnabled ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/PreMigrationController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/PreMigrationController.kt index 23d97cab6a..46c642ed08 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/PreMigrationController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/design/PreMigrationController.kt @@ -31,8 +31,11 @@ import eu.kanade.tachiyomi.util.view.withFadeTransaction import kotlinx.android.synthetic.main.pre_migration_controller.* import uy.kohesive.injekt.injectLazy -class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), FlexibleAdapter -.OnItemClickListener, StartMigrationListener { +class PreMigrationController(bundle: Bundle? = null) : + BaseController(bundle), + FlexibleAdapter + .OnItemClickListener, + StartMigrationListener { private val sourceManager: SourceManager by injectLazy() private val prefs: PreferencesHelper by injectLazy() @@ -55,8 +58,8 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F liftAppbarWith(recycler) val ourAdapter = adapter ?: MigrationSourceAdapter( - getEnabledSources().map { MigrationSourceItem(it, isEnabled(it.id.toString())) }, - this + getEnabledSources().map { MigrationSourceItem(it, isEnabled(it.id.toString())) }, + this ) adapter = ourAdapter recycler.layoutManager = LinearLayoutManager(view.context) @@ -74,8 +77,10 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F v.post { // offset the recycler by the fab's inset + some inset on top v.updatePaddingRelative( - bottom = insets.systemWindowInsetBottom + (fab?.marginBottom - ?: 0) + (fab?.height ?: 0) + bottom = insets.systemWindowInsetBottom + ( + fab?.marginBottom + ?: 0 + ) + (fab?.height ?: 0) ) } } @@ -108,7 +113,8 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F config.toList(), extraSearchParams = extraParam ) - ).withFadeTransaction().tag(MigrationListController.TAG)) + ).withFadeTransaction().tag(MigrationListController.TAG) + ) } override fun onSaveInstanceState(outState: Bundle) { @@ -143,10 +149,13 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F .filter { it.lang in languages } .sortedBy { "(${it.lang}) ${it.name}" } sources = - sources.filter { isEnabled(it.id.toString()) }.sortedBy { sourcesSaved.indexOf(it.id - .toString()) - } + - sources.filterNot { isEnabled(it.id.toString()) } + sources.filter { isEnabled(it.id.toString()) }.sortedBy { + sourcesSaved.indexOf( + it.id + .toString() + ) + } + + sources.filterNot { isEnabled(it.id.toString()) } return sources } @@ -208,9 +217,11 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F } fun create(mangaIds: List): PreMigrationController { - return PreMigrationController(Bundle().apply { - putLongArray(MANGA_IDS_EXTRA, mangaIds.toLongArray()) - }) + return PreMigrationController( + Bundle().apply { + putLongArray(MANGA_IDS_EXTRA, mangaIds.toLongArray()) + } + ) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationListController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationListController.kt index 18979e6a94..56c79d073a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationListController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationListController.kt @@ -57,8 +57,11 @@ import uy.kohesive.injekt.injectLazy import java.util.concurrent.atomic.AtomicInteger import kotlin.coroutines.CoroutineContext -class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), - MigrationProcessAdapter.MigrationProcessInterface, BottomNavBarInterface, CoroutineScope { +class MigrationListController(bundle: Bundle? = null) : + BaseController(bundle), + MigrationProcessAdapter.MigrationProcessInterface, + BottomNavBarInterface, + CoroutineScope { init { setHasOptionsMenu(true) @@ -165,13 +168,16 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), sourceSemaphore.withPermit { try { val searchResult = smartSearchEngine.normalSearch( - source, - mangaObj.title - ) + source, + mangaObj.title + ) if (searchResult != null && - !(searchResult.url == mangaObj.url && - source.id == mangaObj.source)) { + !( + searchResult.url == mangaObj.url && + source.id == mangaObj.source + ) + ) { val localManga = smartSearchEngine.networkToLocalManga( searchResult, @@ -210,9 +216,9 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), validSources.forEachIndexed { index, source -> val searchResult = try { val searchResult = smartSearchEngine.normalSearch( - source, - mangaObj.title - ) + source, + mangaObj.title + ) if (searchResult != null) { val localManga = smartSearchEngine.networkToLocalManga( @@ -309,7 +315,9 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), if (res != null) { activity?.toast( res.getQuantityString( - R.plurals.manga_migrated, manaulMigrations, manaulMigrations + R.plurals.manga_migrated, + manaulMigrations, + manaulMigrations ) ) } @@ -419,8 +427,8 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), if (manga != null) { val newStack = router.backstack.filter { it.controller() !is MangaDetailsController && - it.controller() !is MigrationListController && - it.controller() !is PreMigrationController + it.controller() !is MigrationListController && + it.controller() !is PreMigrationController } + MangaDetailsController(manga).withFadeTransaction() router.setBackstack(newStack, FadeChangeHandler()) return@launchUI @@ -463,7 +471,9 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), if (adapter?.itemCount == 1) { menuMigrate.icon = VectorDrawableCompat.create( - resources!!, R.drawable.ic_done_24dp, null + resources!!, + R.drawable.ic_done_24dp, + null ) } @@ -520,9 +530,11 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), const val TAG = "migration_list" fun create(config: MigrationProcedureConfig): MigrationListController { - return MigrationListController(Bundle().apply { - putParcelable(CONFIG_EXTRA, config) - }) + return MigrationListController( + Bundle().apply { + putParcelable(CONFIG_EXTRA, config) + } + ) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessAdapter.kt index 1cdb3b3fb0..787e259c2a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessAdapter.kt @@ -44,8 +44,12 @@ class MigrationProcessAdapter( if (allMangasDone()) menuItemListener.enableButtons() } - fun allMangasDone() = (items.all { it.manga.migrationStatus != MigrationStatus - .RUNNUNG } && items.any { it.manga.migrationStatus == MigrationStatus.MANGA_FOUND }) + fun allMangasDone() = ( + items.all { + it.manga.migrationStatus != MigrationStatus + .RUNNUNG + } && items.any { it.manga.migrationStatus == MigrationStatus.MANGA_FOUND } + ) fun mangasSkipped() = (items.count { it.manga.migrationStatus == MigrationStatus.MANGA_NOT_FOUND }) @@ -61,7 +65,8 @@ class MigrationProcessAdapter( migrateMangaInternal( manga.manga() ?: return@forEach, toMangaObj, - !copy) + !copy + ) } } } @@ -76,7 +81,9 @@ class MigrationProcessAdapter( db.getManga(manga.searchResult.get() ?: return@launchUI).executeAsBlocking() ?: return@launchUI migrateMangaInternal( - manga.manga() ?: return@launchUI, toMangaObj, !copy + manga.manga() ?: return@launchUI, + toMangaObj, + !copy ) } removeManga(position) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessHolder.kt index 8599955f03..ebc90471aa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessHolder.kt @@ -52,10 +52,12 @@ class MigrationProcessHolder( val source = item.manga.mangaSource() migration_menu.setVectorCompat( - R.drawable.ic_more_vert_24dp, view.context.getResourceColor(android.R.attr.textColorPrimary) + R.drawable.ic_more_vert_24dp, + view.context.getResourceColor(android.R.attr.textColorPrimary) ) skip_manga.setVectorCompat( - R.drawable.ic_close_24dp, view.context.getResourceColor( + R.drawable.ic_close_24dp, + view.context.getResourceColor( android.R.attr.textColorPrimary ) ) @@ -68,7 +70,8 @@ class MigrationProcessHolder( migration_manga_card_from.setOnClickListener { adapter.controller.router.pushController( MangaDetailsController( - manga, true + manga, + true ).withFadeTransaction() ) } @@ -100,7 +103,8 @@ class MigrationProcessHolder( migration_manga_card_to.setOnClickListener { adapter.controller.router.pushController( MangaDetailsController( - searchResult, true + searchResult, + true ).withFadeTransaction() ) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ChapterLoadStrategy.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ChapterLoadStrategy.kt index e25abc0140..b07c803f23 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ChapterLoadStrategy.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ChapterLoadStrategy.kt @@ -26,7 +26,8 @@ class ChapterLoadByNumber { // If there is only one chapter for this number, use it chaptersForNumber.size == 1 -> chaptersForNumber.first() // Prefer a chapter of the same scanlator as the selected - else -> chaptersForNumber.find { it.scanlator == selectedChapter.scanlator } + else -> + chaptersForNumber.find { it.scanlator == selectedChapter.scanlator } ?: chaptersForNumber.first() } chapters.add(preferredChapter) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderActivity.kt index 4d7e66ff15..117b43d445 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderActivity.kt @@ -97,7 +97,8 @@ import kotlin.math.abs * viewers, to which calls from the presenter or UI events are delegated. */ @RequiresPresenter(ReaderPresenter::class) -class ReaderActivity : BaseRxActivity(), +class ReaderActivity : + BaseRxActivity(), SystemUiHelper.OnVisibilityChangeListener { /** @@ -346,7 +347,8 @@ class ReaderActivity : BaseRxActivity(), // Set toolbar setSupportActionBar(toolbar) val primaryColor = ColorUtils.setAlphaComponent( - getResourceColor(R.attr.colorSecondary), 200 + getResourceColor(R.attr.colorSecondary), + 200 ) appbar.setBackgroundColor(primaryColor) window.statusBarColor = Color.TRANSPARENT @@ -363,13 +365,15 @@ class ReaderActivity : BaseRxActivity(), } // Init listeners on bottom menu - page_seekbar.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (viewer != null && fromUser) { - moveToPageIndex(value) + page_seekbar.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (viewer != null && fromUser) { + moveToPageIndex(value) + } } } - }) + ) // Set initial visibility setMenuVisibility(menuVisible) @@ -432,11 +436,13 @@ class ReaderActivity : BaseRxActivity(), if (animate) { if (!menuStickyVisible) { val toolbarAnimation = AnimationUtils.loadAnimation(this, R.anim.enter_from_top) - toolbarAnimation.setAnimationListener(object : SimpleAnimationListener() { - override fun onAnimationStart(animation: Animation) { - window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + toolbarAnimation.setAnimationListener( + object : SimpleAnimationListener() { + override fun onAnimationStart(animation: Animation) { + window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + } } - }) + ) appbar.startAnimation(toolbarAnimation) } chapters_bottom_sheet.sheetBehavior?.collapse() @@ -446,11 +452,13 @@ class ReaderActivity : BaseRxActivity(), if (animate) { val toolbarAnimation = AnimationUtils.loadAnimation(this, R.anim.exit_to_top) - toolbarAnimation.setAnimationListener(object : SimpleAnimationListener() { - override fun onAnimationEnd(animation: Animation) { - reader_menu.gone() + toolbarAnimation.setAnimationListener( + object : SimpleAnimationListener() { + override fun onAnimationEnd(animation: Animation) { + reader_menu.gone() + } } - }) + ) appbar.startAnimation(toolbarAnimation) BottomSheetBehavior.from(chapters_bottom_sheet).isHideable = true chapters_bottom_sheet.sheetBehavior?.hide() @@ -480,7 +488,8 @@ class ReaderActivity : BaseRxActivity(), if (noDefault && presenter.manga?.viewer!! > 0) { snackbar = reader_layout.snack( getString( - R.string.reading_, getString( + R.string.reading_, + getString( when (mangaViewer) { RIGHT_TO_LEFT -> R.string.right_to_left_viewer VERTICAL -> R.string.vertical_viewer @@ -488,7 +497,8 @@ class ReaderActivity : BaseRxActivity(), else -> R.string.left_to_right_viewer } ).toLowerCase(Locale.getDefault()) - ), 4000 + ), + 4000 ) { if (mangaViewer != WEBTOON) setAction(R.string.use_default) { presenter.setMangaViewer(0) @@ -612,11 +622,19 @@ class ReaderActivity : BaseRxActivity(), fun onPageLongTap(page: ReaderPage) { val items = listOf( MaterialMenuSheet.MenuSheetItem( - 0, R.drawable.ic_photo_24dp, R.string.set_as_cover - ), MaterialMenuSheet.MenuSheetItem( - 1, R.drawable.ic_share_24dp, R.string.share - ), MaterialMenuSheet.MenuSheetItem( - 2, R.drawable.ic_save_24dp, R.string.save + 0, + R.drawable.ic_photo_24dp, + R.string.set_as_cover + ), + MaterialMenuSheet.MenuSheetItem( + 1, + R.drawable.ic_share_24dp, + R.string.share + ), + MaterialMenuSheet.MenuSheetItem( + 2, + R.drawable.ic_save_24dp, + R.string.save ) ) MaterialMenuSheet(this, items) { _, item -> @@ -686,7 +704,8 @@ class ReaderActivity : BaseRxActivity(), DecimalFormat("#.###", DecimalFormatSymbols().apply { decimalSeparator = '.' }) val text = "${manga.title}: ${getString( - R.string.chapter_, decimalFormat.format(chapter.chapter_number) + R.string.chapter_, + decimalFormat.format(chapter.chapter_number) )}, ${getString(R.string.page_, page.number)}" val stream = file.getUriCompat(this) @@ -760,11 +779,13 @@ class ReaderActivity : BaseRxActivity(), getResourceColor(R.attr.colorSecondary) reader_menu.visible() val toolbarAnimation = AnimationUtils.loadAnimation(this, R.anim.enter_from_top) - toolbarAnimation.setAnimationListener(object : SimpleAnimationListener() { - override fun onAnimationStart(animation: Animation) { - window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + toolbarAnimation.setAnimationListener( + object : SimpleAnimationListener() { + override fun onAnimationStart(animation: Animation) { + window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + } } - }) + ) appbar.startAnimation(toolbarAnimation) } } else { @@ -821,7 +842,10 @@ class ReaderActivity : BaseRxActivity(), } val intent = WebViewActivity.newIntent( - applicationContext, source.id, url, presenter.manga!!.title + applicationContext, + source.id, + url, + presenter.manga!!.title ) startActivity(intent) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterSheet.kt index 32b924a4a7..c8b13807cf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterSheet.kt @@ -31,7 +31,7 @@ import kotlin.math.abs * Color filter sheet to toggle custom filter and brightness overlay. */ class ReaderColorFilterSheet(private val activity: ReaderActivity) : BottomSheetDialog - (activity, R.style.BottomSheetDialogTheme) { +(activity, R.style.BottomSheetDialogTheme) { private val preferences by injectLazy() @@ -45,7 +45,8 @@ class ReaderColorFilterSheet(private val activity: ReaderActivity) : BottomSheet window?.navigationBarColor = Color.TRANSPARENT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !context.isInNightMode() && - !activity.window.decorView.rootWindowInsets.hasSideNavBar()) + !activity.window.decorView.rootWindowInsets.hasSideNavBar() + ) window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR setBottomEdge(brightness_seekbar, activity) @@ -95,45 +96,55 @@ class ReaderColorFilterSheet(private val activity: ReaderActivity) : BottomSheet } color_filter_mode.setSelection(preferences.colorFilterMode().get(), false) - seekbar_color_filter_alpha.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (fromUser) { - setColorValue(value, ALPHA_MASK, 24) + seekbar_color_filter_alpha.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (fromUser) { + setColorValue(value, ALPHA_MASK, 24) + } } } - }) + ) - seekbar_color_filter_red.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (fromUser) { - setColorValue(value, RED_MASK, 16) + seekbar_color_filter_red.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (fromUser) { + setColorValue(value, RED_MASK, 16) + } } } - }) + ) - seekbar_color_filter_green.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (fromUser) { - setColorValue(value, GREEN_MASK, 8) + seekbar_color_filter_green.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (fromUser) { + setColorValue(value, GREEN_MASK, 8) + } } } - }) + ) - seekbar_color_filter_blue.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (fromUser) { - setColorValue(value, BLUE_MASK, 0) + seekbar_color_filter_blue.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (fromUser) { + setColorValue(value, BLUE_MASK, 0) + } } } - }) + ) - brightness_seekbar.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { - if (fromUser) { - preferences.customBrightnessValue().set(value) + brightness_seekbar.setOnSeekBarChangeListener( + object : SimpleSeekBarListener() { + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { + if (fromUser) { + preferences.customBrightnessValue().set(value) + } } } - }) + ) } override fun onStart() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterView.kt index eb04c10133..4468ed32d3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderColorFilterView.kt @@ -17,14 +17,16 @@ class ReaderColorFilterView( fun setFilterColor(color: Int, filterMode: Int) { colorFilterPaint.color = color - colorFilterPaint.xfermode = PorterDuffXfermode(when (filterMode) { - 1 -> PorterDuff.Mode.MULTIPLY - 2 -> PorterDuff.Mode.SCREEN - 3 -> PorterDuff.Mode.OVERLAY - 4 -> PorterDuff.Mode.LIGHTEN - 5 -> PorterDuff.Mode.DARKEN - else -> PorterDuff.Mode.SRC_OVER - }) + colorFilterPaint.xfermode = PorterDuffXfermode( + when (filterMode) { + 1 -> PorterDuff.Mode.MULTIPLY + 2 -> PorterDuff.Mode.SCREEN + 3 -> PorterDuff.Mode.OVERLAY + 4 -> PorterDuff.Mode.LIGHTEN + 5 -> PorterDuff.Mode.DARKEN + else -> PorterDuff.Mode.SRC_OVER + } + ) invalidate() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt index 9c9880e199..084f658dc0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt @@ -179,9 +179,12 @@ class ReaderPresenter( .first() .observeOn(AndroidSchedulers.mainThread()) .doOnNext { init(it, initialChapterId) } - .subscribeFirst({ _, _ -> - // Ignore onNext event - }, ReaderActivity::setInitialChapterError) + .subscribeFirst( + { _, _ -> + // Ignore onNext event + }, + ReaderActivity::setInitialChapterError + ) } suspend fun getChapters(): List { @@ -190,16 +193,18 @@ class ReaderPresenter( val dbChapters = db.getChapters(manga).executeAsBlocking() val list = chapterFilter.filterChaptersForReader(dbChapters, manga, getCurrentChapter()?.chapter) - .sortedBy { - when (manga.sorting) { - Manga.SORTING_NUMBER -> it.chapter_number - else -> it.source_order.toFloat() + .sortedBy { + when (manga.sorting) { + Manga.SORTING_NUMBER -> it.chapter_number + else -> it.source_order.toFloat() + } + }.map { + ReaderChapterItem( + it, + manga, + it.id == getCurrentChapter()?.chapter?.id ?: chapterId + ) } - }.map { - ReaderChapterItem( - it, manga, it.id == getCurrentChapter()?.chapter?.id ?: chapterId - ) - } if (!manga.sortDescending(preferences.chaptersDescAsDefault().getOrDefault())) { list.reversed() } else { @@ -236,7 +241,9 @@ class ReaderPresenter( if (chapterId == -1L) chapterId = initialChapterId NotificationReceiver.dismissNotification( - preferences.context, manga.id!!.hashCode(), Notifications.ID_NEW_CHAPTERS + preferences.context, + manga.id!!.hashCode(), + Notifications.ID_NEW_CHAPTERS ) val source = sourceManager.getOrStub(manga.source) @@ -253,9 +260,12 @@ class ReaderPresenter( .flatMap { getLoadObservable(loader!!, it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) - .subscribeFirst({ _, _ -> - // Ignore onNext event - }, ReaderActivity::setInitialChapterError) + .subscribeFirst( + { _, _ -> + // Ignore onNext event + }, + ReaderActivity::setInitialChapterError + ) } /** @@ -270,15 +280,17 @@ class ReaderPresenter( chapter: ReaderChapter ): Observable { return loader.loadChapter(chapter) - .andThen(Observable.fromCallable { - val chapterPos = chapterList.indexOf(chapter) + .andThen( + Observable.fromCallable { + val chapterPos = chapterList.indexOf(chapter) - ViewerChapters( - chapter, - chapterList.getOrNull(chapterPos - 1), - chapterList.getOrNull(chapterPos + 1) - ) - }) + ViewerChapters( + chapter, + chapterList.getOrNull(chapterPos - 1), + chapterList.getOrNull(chapterPos + 1) + ) + } + ) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { newChapters -> val oldChapters = viewerChaptersRelay.value @@ -344,7 +356,10 @@ class ReaderPresenter( val chapterId = db.insertChapter(chapter).executeOnIO().insertedId() ?: return if (chapters.isNotEmpty()) { syncChaptersWithSource( - db, chapters, manga, delegatedSource.delegate!! + db, + chapters, + manga, + delegatedSource.delegate!! ) } withContext(Dispatchers.Main) { @@ -381,13 +396,16 @@ class ReaderPresenter( activeChapterSubscription = getLoadObservable(loader, ReaderChapter(chapter)) .doOnSubscribe { isLoadingAdjacentChapterRelay.call(true) } .doOnUnsubscribe { isLoadingAdjacentChapterRelay.call(false) } - .subscribeFirst({ view, _ -> - val lastPage = if (chapter.pages_left <= 1) 0 else chapter.last_page_read - view.moveToPageIndex(lastPage) - view.refreshChapters() - }, { _, _ -> - // Ignore onError event, viewers handle that state - }) + .subscribeFirst( + { view, _ -> + val lastPage = if (chapter.pages_left <= 1) 0 else chapter.last_page_read + view.moveToPageIndex(lastPage) + view.refreshChapters() + }, + { _, _ -> + // Ignore onError event, viewers handle that state + } + ) } fun toggleBookmark(chapter: Chapter) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsSheet.kt index 8e09aa9ff0..ce19647924 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsSheet.kt @@ -49,7 +49,9 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : sheetBehavior = BottomSheetBehavior.from(view.parent as ViewGroup) setEdgeToEdge( - activity, view, if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) + activity, + view, + if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) 0 else -1 ) window?.navigationBarColor = Color.TRANSPARENT @@ -63,20 +65,22 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom sheetBehavior.peekHeight = 550.dpToPx + height - sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - if (progress.isNaN()) - pill.alpha = 0f - else - pill.alpha = (1 - max(0f, progress)) * 0.25f - } + sheetBehavior.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + if (progress.isNaN()) + pill.alpha = 0f + else + pill.alpha = (1 - max(0f, progress)) * 0.25f + } - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_EXPANDED) { + sheetBehavior.skipCollapsed = true + } } } - }) + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/SaveImageNotifier.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/SaveImageNotifier.kt index cdd92d32f2..88bba6e265 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/SaveImageNotifier.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/SaveImageNotifier.kt @@ -42,14 +42,16 @@ class SaveImageNotifier(private val context: Context) { val request = LoadRequest.Builder(context).memoryCachePolicy(CachePolicy.DISABLED).diskCachePolicy(CachePolicy.DISABLED) .data(file) .size(720, 1280) - .target(onSuccess = { - val bitmap = (it as BitmapDrawable).bitmap - if (bitmap != null) { - showCompleteNotification(file, bitmap) - } else { - onError(null) + .target( + onSuccess = { + val bitmap = (it as BitmapDrawable).bitmap + if (bitmap != null) { + showCompleteNotification(file, bitmap) + } else { + onError(null) + } } - }).build() + ).build() Coil.imageLoader(context).execute(request) } @@ -67,13 +69,17 @@ class SaveImageNotifier(private val context: Context) { setContentIntent(NotificationHandler.openImagePendingActivity(context, file)) // Share action - addAction(R.drawable.ic_share_24dp, - context.getString(R.string.share), - NotificationReceiver.shareImagePendingBroadcast(context, file.absolutePath, notificationId)) + addAction( + R.drawable.ic_share_24dp, + context.getString(R.string.share), + NotificationReceiver.shareImagePendingBroadcast(context, file.absolutePath, notificationId) + ) // Delete action - addAction(R.drawable.ic_delete_24dp, - context.getString(R.string.delete), - NotificationReceiver.deleteImagePendingBroadcast(context, file.absolutePath, notificationId)) + addAction( + R.drawable.ic_delete_24dp, + context.getString(R.string.delete), + NotificationReceiver.deleteImagePendingBroadcast(context, file.absolutePath, notificationId) + ) updateNotification() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/chapter/ReaderChapterSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/chapter/ReaderChapterSheet.kt index ce08f453f2..34026c1717 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/chapter/ReaderChapterSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/chapter/ReaderChapterSheet.kt @@ -63,46 +63,48 @@ class ReaderChapterSheet @JvmOverloads constructor(context: Context, attrs: Attr chapter_recycler.isFocusable = sheetBehavior.isExpanded() } - sheetBehavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - pill.alpha = (1 - max(0f, progress)) * 0.25f - val trueProgress = max(progress, 0f) - chapters_button.alpha = 1 - trueProgress - webview_button.alpha = trueProgress - webview_button.visibleIf(webview_button.alpha > 0) - chapters_button.visInvisIf(chapters_button.alpha > 0) - backgroundTintList = - ColorStateList.valueOf(lerpColor(primary, fullPrimary, trueProgress)) - chapter_recycler.alpha = trueProgress - if (activity.sheetManageNavColor && progress > 0f) { - activity.window.navigationBarColor = - lerpColor(ColorUtils.setAlphaComponent(primary, 0), primary, trueProgress) + sheetBehavior?.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + pill.alpha = (1 - max(0f, progress)) * 0.25f + val trueProgress = max(progress, 0f) + chapters_button.alpha = 1 - trueProgress + webview_button.alpha = trueProgress + webview_button.visibleIf(webview_button.alpha > 0) + chapters_button.visInvisIf(chapters_button.alpha > 0) + backgroundTintList = + ColorStateList.valueOf(lerpColor(primary, fullPrimary, trueProgress)) + chapter_recycler.alpha = trueProgress + if (activity.sheetManageNavColor && progress > 0f) { + activity.window.navigationBarColor = + lerpColor(ColorUtils.setAlphaComponent(primary, 0), primary, trueProgress) + } } - } - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_COLLAPSED) { - shouldCollapse = true - sheetBehavior?.isHideable = false - (chapter_recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset( - adapter?.getPosition(presenter.getCurrentChapter()?.chapter?.id ?: 0L) ?: 0, - chapter_recycler.height / 2 - 30.dpToPx - ) - chapters_button.alpha = 1f - webview_button.alpha = 0f + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_COLLAPSED) { + shouldCollapse = true + sheetBehavior?.isHideable = false + (chapter_recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset( + adapter?.getPosition(presenter.getCurrentChapter()?.chapter?.id ?: 0L) ?: 0, + chapter_recycler.height / 2 - 30.dpToPx + ) + chapters_button.alpha = 1f + webview_button.alpha = 0f + } + if (state == BottomSheetBehavior.STATE_EXPANDED) { + chapter_recycler.alpha = 1f + chapters_button.alpha = 0f + webview_button.alpha = 1f + if (activity.sheetManageNavColor) activity.window.navigationBarColor = primary + } + chapter_recycler.isClickable = state == BottomSheetBehavior.STATE_EXPANDED + chapter_recycler.isFocusable = state == BottomSheetBehavior.STATE_EXPANDED + webview_button.visibleIf(state != BottomSheetBehavior.STATE_COLLAPSED) + chapters_button.visInvisIf(state != BottomSheetBehavior.STATE_EXPANDED) } - if (state == BottomSheetBehavior.STATE_EXPANDED) { - chapter_recycler.alpha = 1f - chapters_button.alpha = 0f - webview_button.alpha = 1f - if (activity.sheetManageNavColor) activity.window.navigationBarColor = primary - } - chapter_recycler.isClickable = state == BottomSheetBehavior.STATE_EXPANDED - chapter_recycler.isFocusable = state == BottomSheetBehavior.STATE_EXPANDED - webview_button.visibleIf(state != BottomSheetBehavior.STATE_COLLAPSED) - chapters_button.visInvisIf(state != BottomSheetBehavior.STATE_EXPANDED) } - }) + ) adapter = FastAdapter.with(itemAdapter) chapter_recycler.adapter = adapter @@ -117,25 +119,27 @@ class ReaderChapterSheet @JvmOverloads constructor(context: Context, attrs: Attr true } } - adapter?.addEventHook(object : ClickEventHook() { - override fun onBind(viewHolder: RecyclerView.ViewHolder): View? { - return if (viewHolder is ReaderChapterItem.ViewHolder) { - viewHolder.bookmarkButton - } else { - null + adapter?.addEventHook( + object : ClickEventHook() { + override fun onBind(viewHolder: RecyclerView.ViewHolder): View? { + return if (viewHolder is ReaderChapterItem.ViewHolder) { + viewHolder.bookmarkButton + } else { + null + } + } + + override fun onClick( + v: View, + position: Int, + fastAdapter: FastAdapter, + item: ReaderChapterItem + ) { + presenter.toggleBookmark(item.chapter) + refreshList() } } - - override fun onClick( - v: View, - position: Int, - fastAdapter: FastAdapter, - item: ReaderChapterItem - ) { - presenter.toggleBookmark(item.chapter) - refreshList() - } - }) + ) backgroundTintList = ColorStateList.valueOf( if (!sheetBehavior.isExpanded()) primary @@ -172,8 +176,11 @@ class ReaderChapterSheet @JvmOverloads constructor(context: Context, attrs: Attr } fun lerpColorCalc(colorStart: Int, colorEnd: Int, percent: Int): Int { - return (min(colorStart, colorEnd) * (100 - percent) + max( - colorStart, colorEnd - ) * percent) / 100 + return ( + min(colorStart, colorEnd) * (100 - percent) + max( + colorStart, + colorEnd + ) * percent + ) / 100 } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt index 25eabe291a..463b728950 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DownloadPageLoader.kt @@ -33,9 +33,14 @@ class DownloadPageLoader( return downloadManager.buildPageList(source, manga, chapter.chapter) .map { pages -> pages.map { page -> - ReaderPage(page.index, page.url, page.imageUrl, { - context.contentResolver.openInputStream(page.uri ?: Uri.EMPTY)!! - }).apply { + ReaderPage( + page.index, + page.url, + page.imageUrl, + { + context.contentResolver.openInputStream(page.uri ?: Uri.EMPTY)!! + } + ).apply { status = Page.READY } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/EpubPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/EpubPageLoader.kt index 06ef670d6b..99764ac7b1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/EpubPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/EpubPageLoader.kt @@ -44,10 +44,12 @@ class EpubPageLoader(file: File) : PageLoader() { * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable { - return Observable.just(if (isRecycled) { - Page.ERROR - } else { - Page.READY - }) + return Observable.just( + if (isRecycled) { + Page.ERROR + } else { + Page.READY + } + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt index c5e7d32c68..b204647016 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt @@ -45,16 +45,19 @@ class HttpPageLoader( init { subscriptions += Observable.defer { Observable.just(queue.take().page) } - .filter { it.status == Page.QUEUE } - .concatMap { source.fetchImageFromCacheThenNet(it) } - .repeat() - .subscribeOn(Schedulers.io()) - .subscribe({ - }, { error -> + .filter { it.status == Page.QUEUE } + .concatMap { source.fetchImageFromCacheThenNet(it) } + .repeat() + .subscribeOn(Schedulers.io()) + .subscribe( + { + }, + { error -> if (error !is InterruptedException) { Timber.e(error) } - }) + } + ) } /** @@ -86,13 +89,13 @@ class HttpPageLoader( */ override fun getPages(): Observable> { return chapterCache - .getPageListFromCache(chapter.chapter) - .onErrorResumeNext { source.fetchPageList(chapter.chapter) } - .map { pages -> - pages.mapIndexed { index, page -> // Don't trust sources and use our own indexing - ReaderPage(index, page.url, page.imageUrl) - } + .getPageListFromCache(chapter.chapter) + .onErrorResumeNext { source.fetchPageList(chapter.chapter) } + .map { pages -> + pages.mapIndexed { index, page -> // Don't trust sources and use our own indexing + ReaderPage(index, page.url, page.imageUrl) } + } } /** @@ -123,16 +126,16 @@ class HttpPageLoader( queuedPages += preloadNextPages(page, preloadSize) statusSubject.startWith(page.status) - .doOnUnsubscribe { - queuedPages.forEach { - if (it.page.status == Page.QUEUE) { - queue.remove(it) - } + .doOnUnsubscribe { + queuedPages.forEach { + if (it.page.status == Page.QUEUE) { + queue.remove(it) } } + } } - .subscribeOn(Schedulers.io()) - .unsubscribeOn(Schedulers.io()) + .subscribeOn(Schedulers.io()) + .unsubscribeOn(Schedulers.io()) } /** @@ -145,12 +148,12 @@ class HttpPageLoader( if (pageIndex == pages.lastIndex) return emptyList() return pages - .subList(pageIndex + 1, min(pageIndex + 1 + amount, pages.size)) - .mapNotNull { - if (it.status == Page.QUEUE) { - PriorityPage(it, 0).apply { queue.offer(this) } - } else null - } + .subList(pageIndex + 1, min(pageIndex + 1 + amount, pages.size)) + .mapNotNull { + if (it.status == Page.QUEUE) { + PriorityPage(it, 0).apply { queue.offer(this) } + } else null + } } /** @@ -214,25 +217,27 @@ class HttpPageLoader( val imageUrl = page.imageUrl ?: return Observable.just(page) return Observable.just(page).flatMap { - if (!chapterCache.isImageInCache(imageUrl)) { - cacheImage(page) - } else { - Observable.just(page) - } - }.doOnNext { - val readerTheme = preferences.readerTheme().get() - if (readerTheme >= 2) { - val stream = chapterCache.getImageFile(imageUrl).inputStream() - val image = BitmapFactory.decodeStream(stream) - page.bg = ImageUtil.autoSetBackground( - image, readerTheme == 2, preferences.context - ) - page.bgType = PagerPageHolder.getBGType(readerTheme, preferences.context) - stream.close() - } - page.stream = { chapterCache.getImageFile(imageUrl).inputStream() } - page.status = Page.READY - }.doOnError { page.status = Page.ERROR }.onErrorReturn { page } + if (!chapterCache.isImageInCache(imageUrl)) { + cacheImage(page) + } else { + Observable.just(page) + } + }.doOnNext { + val readerTheme = preferences.readerTheme().get() + if (readerTheme >= 2) { + val stream = chapterCache.getImageFile(imageUrl).inputStream() + val image = BitmapFactory.decodeStream(stream) + page.bg = ImageUtil.autoSetBackground( + image, + readerTheme == 2, + preferences.context + ) + page.bgType = PagerPageHolder.getBGType(readerTheme, preferences.context) + stream.close() + } + page.stream = { chapterCache.getImageFile(imageUrl).inputStream() } + page.status = Page.READY + }.doOnError { page.status = Page.ERROR }.onErrorReturn { page } } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/RarPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/RarPageLoader.kt index 2a4d31204c..9a6a6b88c6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/RarPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/RarPageLoader.kt @@ -60,11 +60,13 @@ class RarPageLoader(file: File) : PageLoader() { * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable { - return Observable.just(if (isRecycled) { - Page.ERROR - } else { - Page.READY - }) + return Observable.just( + if (isRecycled) { + Page.ERROR + } else { + Page.READY + } + ) } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt index 81524ffcbb..46cf79c86a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt @@ -49,10 +49,12 @@ class ZipPageLoader(file: File) : PageLoader() { * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable { - return Observable.just(if (isRecycled) { - Page.ERROR - } else { - Page.READY - }) + return Observable.just( + if (isRecycled) { + Page.ERROR + } else { + Page.READY + } + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt index 06f08b6db6..fe3285e9b7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderChapter.kt @@ -8,11 +8,11 @@ import timber.log.Timber data class ReaderChapter(val chapter: Chapter) { var state: State = - State.Wait + State.Wait set(value) { - field = value - stateRelay.call(value) - } + field = value + stateRelay.call(value) + } private val stateRelay by lazy { BehaviorRelay.create(state) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ReaderProgressBar.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ReaderProgressBar.kt index ed215bf812..045c6434d3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ReaderProgressBar.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ReaderProgressBar.kt @@ -60,9 +60,13 @@ class ReaderProgressBar @JvmOverloads constructor( * The rotation animation to use while the progress bar is visible. */ private val rotationAnimation by lazy { - RotateAnimation(0f, 360f, - Animation.RELATIVE_TO_SELF, 0.5f, - Animation.RELATIVE_TO_SELF, 0.5f + RotateAnimation( + 0f, + 360f, + Animation.RELATIVE_TO_SELF, + 0.5f, + Animation.RELATIVE_TO_SELF, + 0.5f ).apply { interpolator = LinearInterpolator() repeatCount = Animation.INFINITE @@ -160,16 +164,18 @@ class ReaderProgressBar @JvmOverloads constructor( ObjectAnimator.ofFloat(this, "alpha", 1f, 0f).apply { interpolator = DecelerateInterpolator() duration = 1000 - addListener(object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator?) { - visibility = View.GONE - alpha = 1f - } + addListener( + object : AnimatorListenerAdapter() { + override fun onAnimationEnd(animation: Animator?) { + visibility = View.GONE + alpha = 1f + } - override fun onAnimationCancel(animation: Animator?) { - alpha = 1f + override fun onAnimationCancel(animation: Animator?) { + alpha = 1f + } } - }) + ) start() } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerPageHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerPageHolder.kt index 015c64d4b2..2fee4e37e9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerPageHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerPageHolder.kt @@ -107,10 +107,12 @@ class PagerPageHolder( init { addView(progressBar) observeStatus() - setBackgroundColor(when (val theme = viewer.config.readerTheme) { - 3 -> Color.TRANSPARENT - else -> ThemeUtil.readerBackgroundColor(theme) - }) + setBackgroundColor( + when (val theme = viewer.config.readerTheme) { + 3 -> Color.TRANSPARENT + else -> ThemeUtil.readerBackgroundColor(theme) + } + ) } /** @@ -254,10 +256,9 @@ class PagerPageHolder( if (!isAnimated) { if (viewer.config.readerTheme >= 2) { val imageView = initSubsamplingImageView() - if (page.bg != null && page.bgType == getBGType( - viewer.config.readerTheme, - context - )) { + if (page.bg != null && + page.bgType == getBGType(viewer.config.readerTheme, context) + ) { imageView.setImage(ImageSource.inputStream(openStream!!)) imageView.background = page.bg } @@ -297,9 +298,15 @@ class PagerPageHolder( private suspend fun setBG(bytesArray: ByteArray): Drawable { return withContext(Default) { val preferences by injectLazy() - ImageUtil.autoSetBackground(BitmapFactory.decodeByteArray( - bytesArray, 0, bytesArray.size - ), preferences.readerTheme().get() == 2, context) + ImageUtil.autoSetBackground( + BitmapFactory.decodeByteArray( + bytesArray, + 0, + bytesArray.size + ), + preferences.readerTheme().get() == 2, + context + ) } } @@ -358,20 +365,22 @@ class PagerPageHolder( setMinimumDpi(90) setMinimumTileDpi(180) setCropBorders(config.imageCropBorders) - setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() { - override fun onReady() { - when (config.imageZoomType) { - ZoomType.Left -> setScaleAndCenter(scale, PointF(0f, 0f)) - ZoomType.Right -> setScaleAndCenter(scale, PointF(sWidth.toFloat(), 0f)) - ZoomType.Center -> setScaleAndCenter(scale, center.also { it?.y = 0f }) + setOnImageEventListener( + object : SubsamplingScaleImageView.DefaultOnImageEventListener() { + override fun onReady() { + when (config.imageZoomType) { + ZoomType.Left -> setScaleAndCenter(scale, PointF(0f, 0f)) + ZoomType.Right -> setScaleAndCenter(scale, PointF(sWidth.toFloat(), 0f)) + ZoomType.Center -> setScaleAndCenter(scale, center.also { it?.y = 0f }) + } + onImageDecoded() } - onImageDecoded() - } - override fun onImageLoadError(e: Exception) { - onImageDecodeError() + override fun onImageLoadError(e: Exception) { + onImageDecodeError() + } } - }) + ) } addView(subsamplingImageView) return subsamplingImageView!! @@ -389,16 +398,18 @@ class PagerPageHolder( setZoomTransitionDuration(viewer.config.doubleTapAnimDuration) setScaleLevels(1f, 2f, 3f) // Force 2 scale levels on double tap - setOnDoubleTapListener(object : GestureDetector.SimpleOnGestureListener() { - override fun onDoubleTap(e: MotionEvent): Boolean { - if (scale > 1f) { - setScale(1f, e.x, e.y, true) - } else { - setScale(2f, e.x, e.y, true) + setOnDoubleTapListener( + object : GestureDetector.SimpleOnGestureListener() { + override fun onDoubleTap(e: MotionEvent): Boolean { + if (scale > 1f) { + setScale(1f, e.x, e.y, true) + } else { + setScale(2f, e.x, e.y, true) + } + return true } - return true } - }) + ) } addView(imageView) return imageView!! @@ -486,7 +497,7 @@ class PagerPageHolder( this.loadAny(stream.readBytes()) { memoryCachePolicy(CachePolicy.DISABLED) diskCachePolicy(CachePolicy.DISABLED) - target(GifViewTarget(this@setImage, progressBar, decodeErrorLayout)) + target(GifViewTarget(this@setImage, progressBar, decodeErrorLayout)) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewer.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewer.kt index 2121a5861c..545e7e04cc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewer.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewer.kt @@ -70,15 +70,17 @@ abstract class PagerViewer(val activity: ReaderActivity) : BaseViewer { pager.offscreenPageLimit = 1 pager.id = R.id.reader_pager pager.adapter = adapter - pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() { - override fun onPageSelected(position: Int) { - onPageChange(position) - } + pager.addOnPageChangeListener( + object : ViewPager.SimpleOnPageChangeListener() { + override fun onPageSelected(position: Int) { + onPageChange(position) + } - override fun onPageScrollStateChanged(state: Int) { - isIdle = state == ViewPager.SCROLL_STATE_IDLE + override fun onPageScrollStateChanged(state: Int) { + isIdle = state == ViewPager.SCROLL_STATE_IDLE + } } - }) + ) pager.tapListener = { event -> val positionX = event.x when { @@ -201,8 +203,10 @@ abstract class PagerViewer(val activity: ReaderActivity) : BaseViewer { */ private fun setChaptersInternal(chapters: ViewerChapters) { Timber.d("setChaptersInternal") - val forceTransition = config.alwaysShowChapterTransition || adapter.items.getOrNull(pager - .currentItem) is ChapterTransition + val forceTransition = config.alwaysShowChapterTransition || adapter.items.getOrNull( + pager + .currentItem + ) is ChapterTransition adapter.setChapters(chapters, forceTransition) // Layout the pager once a chapter is being set diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonPageHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonPageHolder.kt index 25610c6d1e..354105133c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonPageHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonPageHolder.kt @@ -360,15 +360,17 @@ class WebtoonPageHolder( setMinimumDpi(90) setMinimumTileDpi(180) setCropBorders(if (viewer.hasMargins) config.verticalCropBorders else config.webtoonCropBorders) - setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() { - override fun onReady() { - onImageDecoded() - } + setOnImageEventListener( + object : SubsamplingScaleImageView.DefaultOnImageEventListener() { + override fun onReady() { + onImageDecoded() + } - override fun onImageLoadError(e: Exception) { - onImageDecodeError() + override fun onImageLoadError(e: Exception) { + onImageDecodeError() + } } - }) + ) } frame.addView(subsamplingImageView, MATCH_PARENT, MATCH_PARENT) return subsamplingImageView!! diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonRecyclerView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonRecyclerView.kt index d69418b6b3..197142922c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonRecyclerView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonRecyclerView.kt @@ -121,21 +121,23 @@ open class WebtoonRecyclerView @JvmOverloads constructor( animatorSet.duration = ANIMATOR_DURATION_TIME.toLong() animatorSet.interpolator = DecelerateInterpolator() animatorSet.start() - animatorSet.addListener(object : Animator.AnimatorListener { - override fun onAnimationStart(animation: Animator) { - } + animatorSet.addListener( + object : Animator.AnimatorListener { + override fun onAnimationStart(animation: Animator) { + } - override fun onAnimationEnd(animation: Animator) { - isZooming = false - currentScale = toRate - } + override fun onAnimationEnd(animation: Animator) { + isZooming = false + currentScale = toRate + } - override fun onAnimationCancel(animation: Animator) { - } + override fun onAnimationCancel(animation: Animator) { + } - override fun onAnimationRepeat(animation: Animator) { + override fun onAnimationRepeat(animation: Animator) { + } } - }) + ) } fun zoomFling(velocityX: Int, velocityY: Int): Boolean { @@ -183,8 +185,9 @@ open class WebtoonRecyclerView @JvmOverloads constructor( fun onScale(scaleFactor: Float) { currentScale *= scaleFactor currentScale = currentScale.coerceIn( - minRate, - MAX_SCALE_RATE) + minRate, + MAX_SCALE_RATE + ) setScaleRate(currentScale) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonViewer.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonViewer.kt index df7f8854ea..5ad24913cb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonViewer.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonViewer.kt @@ -71,28 +71,30 @@ class WebtoonViewer(val activity: ReaderActivity, val hasMargins: Boolean = fals recycler.itemAnimator = null recycler.layoutManager = layoutManager recycler.adapter = adapter - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - val position = layoutManager.findLastEndVisibleItemPosition() - val item = adapter.items.getOrNull(position) - val allowPreload = checkAllowPreload(item as? ReaderPage) - if (item != null && currentPage != item) { - currentPage = item - when (item) { - is ReaderPage -> onPageSelected(item, allowPreload) - is ChapterTransition -> onTransitionSelected(item) + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + val position = layoutManager.findLastEndVisibleItemPosition() + val item = adapter.items.getOrNull(position) + val allowPreload = checkAllowPreload(item as? ReaderPage) + if (item != null && currentPage != item) { + currentPage = item + when (item) { + is ReaderPage -> onPageSelected(item, allowPreload) + is ChapterTransition -> onTransitionSelected(item) + } } - } - if (dy < 0) { - val firstIndex = layoutManager.findFirstVisibleItemPosition() - val firstItem = adapter.items.getOrNull(firstIndex) - if (firstItem is ChapterTransition.Prev && firstItem.to != null) { - activity.requestPreloadChapter(firstItem.to) + if (dy < 0) { + val firstIndex = layoutManager.findFirstVisibleItemPosition() + val firstItem = adapter.items.getOrNull(firstIndex) + if (firstItem is ChapterTransition.Prev && firstItem.to != null) { + activity.requestPreloadChapter(firstItem.to) + } } } } - }) + ) recycler.tapListener = { event -> val positionX = event.rawX val positionY = event.rawY diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt index 5abc6bb5ca..81e8a2e317 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt @@ -12,7 +12,7 @@ import eu.kanade.tachiyomi.R import java.util.Date class DateItem(val date: Date, val addedString: Boolean = false) : AbstractHeaderItem() { + .Holder>() { override fun getLayoutRes(): Int { return R.layout.recent_chapters_section_item diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterHolder.kt index 257fe77a50..41d9eaabfa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterHolder.kt @@ -64,7 +64,8 @@ class RecentChapterHolder(private val view: View, private val adapter: RecentCha if (front_view.translationX == 0f) { read.setImageDrawable( ContextCompat.getDrawable( - read.context, if (item.read) R.drawable.ic_eye_off_24dp + read.context, + if (item.read) R.drawable.ic_eye_off_24dp else R.drawable.ic_eye_24dp ) ) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersController.kt index d263058225..410fbc06b2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersController.kt @@ -37,10 +37,13 @@ import timber.log.Timber * Uses [R.layout.recent_chapters_controller]. * UI related actions should be called from here. */ -class RecentChaptersController(bundle: Bundle? = null) : BaseController(bundle), - FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnUpdateListener, +class RecentChaptersController(bundle: Bundle? = null) : + BaseController(bundle), + FlexibleAdapter.OnItemClickListener, + FlexibleAdapter.OnUpdateListener, FlexibleAdapter.OnItemMoveListener, - RecentChaptersAdapter.OnCoverClickListener, BaseChapterAdapter.DownloadInterface { + RecentChaptersAdapter.OnCoverClickListener, + BaseChapterAdapter.DownloadInterface { /** * Adapter containing the recent chapters. @@ -207,15 +210,17 @@ class RecentChaptersController(bundle: Bundle? = null) : BaseController(bundle), presenter.markChapterRead(item, read, lastRead, pagesLeft) undoing = true } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!undoing && presenter.preferences.removeAfterMarkedAsRead()) { - lastChapterId = chapter.id - presenter.deleteChapter(chapter, item.manga) + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!undoing && presenter.preferences.removeAfterMarkedAsRead()) { + lastChapterId = chapter.id + presenter.deleteChapter(chapter, item.manga) + } } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersPresenter.kt index c1d4c41ed5..3f15354895 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersPresenter.kt @@ -58,7 +58,8 @@ class RecentChaptersPresenter( val items = byDay.flatMap { val dateItem = DateItem(it.key) it.value.map { mc -> - RecentChapterItem(mc.chapter, mc.manga, dateItem) } + RecentChapterItem(mc.chapter, mc.manga, dateItem) + } } setDownloadedChapters(items) chapters = items diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadAdapter.kt index 671766923f..fa72676177 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadAdapter.kt @@ -19,7 +19,7 @@ import java.text.DecimalFormatSymbols * @constructor creates an instance of the adapter. */ class RecentlyReadAdapter(controller: RecentlyReadController) : - FlexibleAdapter>(null, controller, true) { + FlexibleAdapter>(null, controller, true) { val sourceManager by injectLazy() @@ -32,8 +32,11 @@ class RecentlyReadAdapter(controller: RecentlyReadController) : /** * DecimalFormat used to display correct chapter number */ - val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols() - .apply { decimalSeparator = '.' }) + val decimalFormat = DecimalFormat( + "#.###", + DecimalFormatSymbols() + .apply { decimalSeparator = '.' } + ) private val preferences: PreferencesHelper by injectLazy() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt index 0927b74593..81e61ee240 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt @@ -32,13 +32,14 @@ import kotlinx.android.synthetic.main.recently_read_controller.* * Uses R.layout.fragment_recently_read. * UI related actions should be called from here. */ -class RecentlyReadController(bundle: Bundle? = null) : BaseController(bundle), - FlexibleAdapter.OnUpdateListener, - FlexibleAdapter.EndlessScrollListener, - RecentlyReadAdapter.OnRemoveClickListener, - RecentlyReadAdapter.OnResumeClickListener, - RecentlyReadAdapter.OnCoverClickListener, - RemoveHistoryDialog.Listener { +class RecentlyReadController(bundle: Bundle? = null) : + BaseController(bundle), + FlexibleAdapter.OnUpdateListener, + FlexibleAdapter.EndlessScrollListener, + RecentlyReadAdapter.OnRemoveClickListener, + RecentlyReadAdapter.OnResumeClickListener, + RecentlyReadAdapter.OnCoverClickListener, + RemoveHistoryDialog.Listener { init { setHasOptionsMenu(true) @@ -128,8 +129,11 @@ class RecentlyReadController(bundle: Bundle? = null) : BaseController(bundle), if (size > 0) { empty_view?.hide() } else { - empty_view.show(R.drawable.ic_history_24dp, R.string - .no_recently_read_manga) + empty_view.show( + R.drawable.ic_history_24dp, + R.string + .no_recently_read_manga + ) } } @@ -211,16 +215,18 @@ class RecentlyReadController(bundle: Bundle? = null) : BaseController(bundle), } // Fixes problem with the overflow icon showing up in lieu of search - searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { - override fun onMenuItemActionExpand(item: MenuItem): Boolean { - return true - } + searchItem.setOnActionExpandListener( + object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem): Boolean { + return true + } - override fun onMenuItemActionCollapse(item: MenuItem): Boolean { - activity?.invalidateOptionsMenu() - return true + override fun onMenuItemActionCollapse(item: MenuItem): Boolean { + activity?.invalidateOptionsMenu() + return true + } } - }) + ) } /*override fun onOptionsItemSelected(item: MenuItem): Boolean { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt index 40cc050d93..b55697aea3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt @@ -53,7 +53,7 @@ class RecentlyReadHolder( // Set source + chapter title val formattedNumber = adapter.decimalFormat.format(chapter.chapter_number.toDouble()) manga_source.text = itemView.context.getString(R.string.source_dash_chapter_) - .format(adapter.sourceManager.getOrStub(manga.source).toString(), formattedNumber) + .format(adapter.sourceManager.getOrStub(manga.source).toString(), formattedNumber) // Set last read timestamp title last_read.text = Date(history.last_read).toTimestampString(adapter.dateFormat) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadPresenter.kt index 0e025d639f..d79b8442a6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadPresenter.kt @@ -110,7 +110,7 @@ class RecentlyReadPresenter(private val view: RecentlyReadController) { } val chapters = db.getChapters(manga).executeAsBlocking() - .sortedWith(Comparator { c1, c2 -> sortFunction(c1, c2) }) + .sortedWith(Comparator { c1, c2 -> sortFunction(c1, c2) }) val currChapterIndex = chapters.indexOfFirst { chapter.id == it.id } return when (manga.sorting) { @@ -119,10 +119,11 @@ class RecentlyReadPresenter(private val view: RecentlyReadController) { val chapterNumber = chapter.chapter_number ((currChapterIndex + 1) until chapters.size) - .map { chapters[it] } - .firstOrNull { it.chapter_number > chapterNumber && - it.chapter_number <= chapterNumber + 1 - } + .map { chapters[it] } + .firstOrNull { + it.chapter_number > chapterNumber && + it.chapter_number <= chapterNumber + 1 + } } else -> throw NotImplementedError("Unknown sorting method") } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RemoveHistoryDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RemoveHistoryDialog.kt index c6546dc45c..141e5f80af 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RemoveHistoryDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RemoveHistoryDialog.kt @@ -32,17 +32,19 @@ class RemoveHistoryDialog(bundle: Bundle? = null) : DialogController(bundle) val activity = activity!! return MaterialDialog(activity).title(R.string.reset_chapter_question).message( - text = if (chapter?.name != null) activity.getString( - R.string.this_will_remove_the_read_date_for_x_question, chapter?.name ?: "" - ) - else activity.getString(R.string.this_will_remove_the_read_date_question) - ).checkBoxPrompt( - text = activity.getString( - R.string.reset_all_chapters_for_this_, manga!!.mangaType(activity) - ) - ) {}.negativeButton(android.R.string.cancel).positiveButton(R.string.reset) { - onPositive(it.isCheckPromptChecked()) - } + text = if (chapter?.name != null) activity.getString( + R.string.this_will_remove_the_read_date_for_x_question, + chapter?.name ?: "" + ) + else activity.getString(R.string.this_will_remove_the_read_date_question) + ).checkBoxPrompt( + text = activity.getString( + R.string.reset_all_chapters_for_this_, + manga!!.mangaType(activity) + ) + ) {}.negativeButton(android.R.string.cancel).positiveButton(R.string.reset) { + onPositive(it.isCheckPromptChecked()) + } } private fun onPositive(checked: Boolean) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaAdapter.kt index b5a0e40723..b3d5094e49 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaAdapter.kt @@ -17,8 +17,11 @@ class RecentMangaAdapter(val delegate: RecentsInterface) : updateDataSet(items) } - val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols() - .apply { decimalSeparator = '.' }) + val decimalFormat = DecimalFormat( + "#.###", + DecimalFormatSymbols() + .apply { decimalSeparator = '.' } + ) interface RecentsInterface : RecentMangaInterface, DownloadInterface diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHeaderItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHeaderItem.kt index 785c3a6467..ffaf94bb8d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHeaderItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHeaderItem.kt @@ -54,8 +54,11 @@ class RecentMangaHeaderItem(val recentsType: Int) : return recentsType.hashCode() } - class Holder(val view: View, adapter: RecentMangaAdapter) : BaseFlexibleViewHolder(view, adapter, - true) { + class Holder(val view: View, adapter: RecentMangaAdapter) : BaseFlexibleViewHolder( + view, + adapter, + true + ) { init { action_history.setOnClickListener { adapter.delegate.showHistory() } @@ -63,12 +66,14 @@ class RecentMangaHeaderItem(val recentsType: Int) : } fun bind(recentsType: Int) { - title.setText(when (recentsType) { - CONTINUE_READING -> R.string.continue_reading - NEW_CHAPTERS -> R.string.new_chapters - NEWLY_ADDED -> R.string.newly_added - else -> R.string.continue_reading - }) + title.setText( + when (recentsType) { + CONTINUE_READING -> R.string.continue_reading + NEW_CHAPTERS -> R.string.new_chapters + NEWLY_ADDED -> R.string.newly_added + else -> R.string.continue_reading + } + ) action_history.visibleIf(recentsType == -1) action_update.visibleIf(recentsType == -1) title.visibleIf(recentsType != -1) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHolder.kt index a5a8b0a876..4055e38e15 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentMangaHolder.kt @@ -47,25 +47,33 @@ class RecentMangaHolder( val notValidNum = item.mch.chapter.chapter_number <= 0 body.text = when { item.mch.chapter.id == null -> body.context.getString( - R.string.added_, item.mch.manga.date_added.timeSpanFromNow + R.string.added_, + item.mch.manga.date_added.timeSpanFromNow ) item.mch.history.id == null -> body.context.getString( - R.string.updated_, item.chapter.date_upload.timeSpanFromNow + R.string.updated_, + item.chapter.date_upload.timeSpanFromNow ) item.chapter.id != item.mch.chapter.id -> body.context.getString( - R.string.read_, item.mch.history.last_read.timeSpanFromNow + R.string.read_, + item.mch.history.last_read.timeSpanFromNow ) + "\n" + body.context.getString( - if (notValidNum) R.string.last_read_ else R.string.last_read_chapter_, - if (notValidNum) item.mch.chapter.name else adapter.decimalFormat.format(item.mch.chapter.chapter_number) - ) - item.chapter.pages_left > 0 && !item.chapter.read -> body.context.getString( - R.string.read_, item.mch.history.last_read.timeSpanFromNow - ) + "\n" + itemView.resources.getQuantityString( - R.plurals.pages_left, item.chapter.pages_left, item.chapter.pages_left - ) + if (notValidNum) R.string.last_read_ else R.string.last_read_chapter_, + if (notValidNum) item.mch.chapter.name else adapter.decimalFormat.format(item.mch.chapter.chapter_number) + ) + item.chapter.pages_left > 0 && !item.chapter.read -> + body.context.getString( + R.string.read_, + item.mch.history.last_read.timeSpanFromNow + ) + "\n" + itemView.resources.getQuantityString( + R.plurals.pages_left, + item.chapter.pages_left, + item.chapter.pages_left + ) else -> body.context.getString( - R.string.read_, item.mch.history.last_read.timeSpanFromNow + R.string.read_, + item.mch.history.last_read.timeSpanFromNow ) } if ((itemView.context as? Activity)?.isDestroyed != true) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsController.kt index 959da8e705..22e0aa893c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsController.kt @@ -60,7 +60,8 @@ import kotlin.math.max * Uses R.layout.fragment_recently_read. * UI related actions should be called from here. */ -class RecentsController(bundle: Bundle? = null) : BaseController(bundle), +class RecentsController(bundle: Bundle? = null) : + BaseController(bundle), RecentMangaAdapter.RecentsInterface, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, @@ -121,9 +122,13 @@ class RecentsController(bundle: Bundle? = null) : BaseController(bundle), val appBarHeight = array.getDimensionPixelSize(0, 0) array.recycle() swipe_refresh.setStyle() - scrollViewWith(recycler, swipeRefreshLayout = swipe_refresh, afterInsets = { - headerHeight = it.systemWindowInsetTop + appBarHeight - }) + scrollViewWith( + recycler, + swipeRefreshLayout = swipe_refresh, + afterInsets = { + headerHeight = it.systemWindowInsetTop + appBarHeight + } + ) presenter.onCreate() if (presenter.recentItems.isNotEmpty()) { @@ -140,62 +145,65 @@ class RecentsController(bundle: Bundle? = null) : BaseController(bundle), shadow.alpha = if (dl_bottom_sheet.sheetBehavior?.state == BottomSheetBehavior.STATE_COLLAPSED) 0.5f else 0f - dl_bottom_sheet.sheetBehavior?.addBottomSheetCallback(object : - BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - val shadow2 = shadow2 ?: return - shadow2.alpha = (1 - abs(progress)) * 0.25f - shadow.alpha = (1 - abs(progress)) * 0.5f - if (progress >= 0) activity?.appbar?.elevation = max( - progress * 15f, if (recycler.canScrollVertically(-1)) 15f else 0f - ) - sheet_layout.alpha = 1 - progress - activity?.appbar?.y = max(activity!!.appbar.y, -headerHeight * (1 - progress)) - val oldShow = showingDownloads - showingDownloads = progress > 0.92f - if (oldShow != showingDownloads) { - setTitle() - activity?.invalidateOptionsMenu() - } - } - - override fun onStateChanged(p0: View, state: Int) { - if (this@RecentsController.view == null) return - if (state == BottomSheetBehavior.STATE_EXPANDED) activity?.appbar?.y = 0f - if (state == BottomSheetBehavior.STATE_EXPANDED || state == BottomSheetBehavior.STATE_COLLAPSED) { - sheet_layout.alpha = - if (state == BottomSheetBehavior.STATE_COLLAPSED) 1f else 0f - showingDownloads = state == BottomSheetBehavior.STATE_EXPANDED - setTitle() - activity?.invalidateOptionsMenu() - } - - if (state == BottomSheetBehavior.STATE_COLLAPSED) { - if (hasQueue()) { - dl_bottom_sheet.sheetBehavior?.isHideable = false - } else { - dl_bottom_sheet.sheetBehavior?.isHideable = true - dl_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN - } - } else if (state == BottomSheetBehavior.STATE_HIDDEN) { - if (!hasQueue()) { - dl_bottom_sheet.sheetBehavior?.skipCollapsed = true - } else { - dl_bottom_sheet.sheetBehavior?.skipCollapsed = false - dl_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED + dl_bottom_sheet.sheetBehavior?.addBottomSheetCallback( + object : + BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + val shadow2 = shadow2 ?: return + shadow2.alpha = (1 - abs(progress)) * 0.25f + shadow.alpha = (1 - abs(progress)) * 0.5f + if (progress >= 0) activity?.appbar?.elevation = max( + progress * 15f, + if (recycler.canScrollVertically(-1)) 15f else 0f + ) + sheet_layout.alpha = 1 - progress + activity?.appbar?.y = max(activity!!.appbar.y, -headerHeight * (1 - progress)) + val oldShow = showingDownloads + showingDownloads = progress > 0.92f + if (oldShow != showingDownloads) { + setTitle() + activity?.invalidateOptionsMenu() } } - if (state == BottomSheetBehavior.STATE_HIDDEN || state == BottomSheetBehavior.STATE_COLLAPSED) { - shadow2.alpha = if (state == BottomSheetBehavior.STATE_COLLAPSED) 0.25f else 0f - shadow.alpha = if (state == BottomSheetBehavior.STATE_COLLAPSED) 0.5f else 0f - } + override fun onStateChanged(p0: View, state: Int) { + if (this@RecentsController.view == null) return + if (state == BottomSheetBehavior.STATE_EXPANDED) activity?.appbar?.y = 0f + if (state == BottomSheetBehavior.STATE_EXPANDED || state == BottomSheetBehavior.STATE_COLLAPSED) { + sheet_layout.alpha = + if (state == BottomSheetBehavior.STATE_COLLAPSED) 1f else 0f + showingDownloads = state == BottomSheetBehavior.STATE_EXPANDED + setTitle() + activity?.invalidateOptionsMenu() + } - sheet_layout?.isClickable = state == BottomSheetBehavior.STATE_COLLAPSED - sheet_layout?.isFocusable = state == BottomSheetBehavior.STATE_COLLAPSED - setPadding(dl_bottom_sheet.sheetBehavior?.isHideable == true) + if (state == BottomSheetBehavior.STATE_COLLAPSED) { + if (hasQueue()) { + dl_bottom_sheet.sheetBehavior?.isHideable = false + } else { + dl_bottom_sheet.sheetBehavior?.isHideable = true + dl_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN + } + } else if (state == BottomSheetBehavior.STATE_HIDDEN) { + if (!hasQueue()) { + dl_bottom_sheet.sheetBehavior?.skipCollapsed = true + } else { + dl_bottom_sheet.sheetBehavior?.skipCollapsed = false + dl_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED + } + } + + if (state == BottomSheetBehavior.STATE_HIDDEN || state == BottomSheetBehavior.STATE_COLLAPSED) { + shadow2.alpha = if (state == BottomSheetBehavior.STATE_COLLAPSED) 0.25f else 0f + shadow.alpha = if (state == BottomSheetBehavior.STATE_COLLAPSED) 0.5f else 0f + } + + sheet_layout?.isClickable = state == BottomSheetBehavior.STATE_COLLAPSED + sheet_layout?.isFocusable = state == BottomSheetBehavior.STATE_COLLAPSED + setPadding(dl_bottom_sheet.sheetBehavior?.isHideable == true) + } } - }) + ) swipe_refresh.isRefreshing = LibraryUpdateService.isRunning() swipe_refresh.setOnRefreshListener { if (!LibraryUpdateService.isRunning()) { @@ -281,7 +289,8 @@ class RecentsController(bundle: Bundle? = null) : BaseController(bundle), private fun refreshItem(chapterId: Long) { val recentItemPos = adapter.currentItems.indexOfFirst { it is RecentMangaItem && - it.mch.chapter.id == chapterId } + it.mch.chapter.id == chapterId + } if (recentItemPos > -1) adapter.notifyItemChanged(recentItemPos) } @@ -365,15 +374,17 @@ class RecentsController(bundle: Bundle? = null) : BaseController(bundle), presenter.markChapterRead(chapter, false, lastRead, pagesLeft) undoing = true } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!undoing && presenter.preferences.removeAfterMarkedAsRead()) { - lastChapterId = chapter.id - presenter.deleteChapter(chapter, manga) + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!undoing && presenter.preferences.removeAfterMarkedAsRead()) { + lastChapterId = chapter.id + presenter.deleteChapter(chapter, manga) + } } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } @@ -457,12 +468,14 @@ class RecentsController(bundle: Bundle? = null) : BaseController(bundle), when (item.itemId) { R.id.action_group_all, R.id.action_ungroup_all, R.id.action_only_history, R.id.action_only_updates -> { - presenter.toggleGroupRecents(when (item.itemId) { - R.id.action_ungroup_all -> 1 - R.id.action_only_history -> 2 - R.id.action_only_updates -> 3 - else -> 0 - }) + presenter.toggleGroupRecents( + when (item.itemId) { + R.id.action_ungroup_all -> 1 + R.id.action_only_history -> 2 + R.id.action_only_updates -> 3 + else -> 0 + } + ) if (item.itemId == R.id.action_only_history) activity?.toast(R.string.press_and_hold_to_reset_history, Toast.LENGTH_LONG) activity?.invalidateOptionsMenu() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsPresenter.kt index 857fd7362b..768f06bab2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recents/RecentsPresenter.kt @@ -46,8 +46,10 @@ class RecentsPresenter( private val newAdditionsHeader = RecentMangaHeaderItem(RecentMangaHeaderItem.NEWLY_ADDED) private val newChaptersHeader = RecentMangaHeaderItem(RecentMangaHeaderItem.NEW_CHAPTERS) val generalHeader = RecentMangaHeaderItem(-1) - private val continueReadingHeader = RecentMangaHeaderItem(RecentMangaHeaderItem - .CONTINUE_READING) + private val continueReadingHeader = RecentMangaHeaderItem( + RecentMangaHeaderItem + .CONTINUE_READING + ) var viewType: Int = preferences.recentsViewType().getOrDefault() fun onCreate() { @@ -99,7 +101,8 @@ class RecentsPresenter( else db.getRecentMangaLimit( cal.time, if (viewType == 2) 200 else 8, - query).executeOnIO() else emptyList() + query + ).executeOnIO() else emptyList() val rUpdates = when { viewType == 3 -> db.getRecentChapters(calWeek.time).executeOnIO().map { MangaChapterHistory(it.manga, it.chapter, HistoryImpl()) @@ -129,20 +132,24 @@ class RecentsPresenter( else -> it.chapter } if (chapter == null) if ((query.isNotEmpty() || viewType > 1) && - it.chapter.id != null) Pair(it, it.chapter) + it.chapter.id != null + ) Pair(it, it.chapter) else null else Pair(it, chapter) } if (query.isEmpty() && !isUngrouped) { val nChaptersItems = pairs.filter { it.first.history.id == null && it.first.chapter.id != null } - .sortedWith(Comparator> { f1, f2 -> - if (abs(f1.second.date_fetch - f2.second.date_fetch) <= - TimeUnit.HOURS.toMillis(12)) - f2.second.date_upload.compareTo(f1.second.date_upload) - else - f2.second.date_fetch.compareTo(f1.second.date_fetch) - }) + .sortedWith( + Comparator> { f1, f2 -> + if (abs(f1.second.date_fetch - f2.second.date_fetch) <= + TimeUnit.HOURS.toMillis(12) + ) + f2.second.date_upload.compareTo(f1.second.date_upload) + else + f2.second.date_fetch.compareTo(f1.second.date_fetch) + } + ) .take(4).map { RecentMangaItem( it.first, @@ -153,36 +160,40 @@ class RecentsPresenter( RecentMangaItem(header = newChaptersHeader) val cReadingItems = pairs.filter { it.first.history.id != null }.take(9 - nChaptersItems.size).map { - RecentMangaItem( - it.first, - it.second, - continueReadingHeader - ) - } + RecentMangaItem(header = continueReadingHeader) + RecentMangaItem( + it.first, + it.second, + continueReadingHeader + ) + } + RecentMangaItem(header = continueReadingHeader) val nAdditionsItems = pairs.filter { it.first.chapter.id == null }.take(4) .map { RecentMangaItem(it.first, it.second, newAdditionsHeader) } recentItems = listOf(nChaptersItems, cReadingItems, nAdditionsItems).sortedByDescending { - it.firstOrNull()?.mch?.history?.last_read ?: 0L - }.flatten() + it.firstOrNull()?.mch?.history?.last_read ?: 0L + }.flatten() } else { recentItems = if (viewType == 3) { val map = TreeMap>> { - d1, d2 -> d2 - .compareTo(d1) } + d1, d2 -> + d2 + .compareTo(d1) + } val byDay = pairs.groupByTo(map, { getMapKey(it.first.history.last_read) }) byDay.flatMap { val dateItem = DateItem(it.key, true) it.value.map { item -> - RecentMangaItem(item.first, item.second, dateItem) } + RecentMangaItem(item.first, item.second, dateItem) + } } } else pairs.map { RecentMangaItem(it.first, it.second, null) } if (isUngrouped && recentItems.isEmpty()) { recentItems = listOf( RecentMangaItem(header = newChaptersHeader), - RecentMangaItem(header = continueReadingHeader)) + RecentMangaItem(header = continueReadingHeader) + ) } } setDownloadedChapters(recentItems) @@ -229,7 +240,7 @@ class RecentsPresenter( item.status = Download.DOWNLOADED } else if (downloadManager.hasQueue()) { item.status = downloadManager.queue.find { it.chapter.id == item.chapter.id } - ?.status ?: 0 + ?.status ?: 0 } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/security/BiometricActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/security/BiometricActivity.kt index f097e2ca42..72f221700f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/security/BiometricActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/security/BiometricActivity.kt @@ -14,22 +14,26 @@ class BiometricActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val fromSearch = intent.getBooleanExtra("fromSearch", false) - val biometricPrompt = BiometricPrompt(this, executor, object : BiometricPrompt - .AuthenticationCallback() { + val biometricPrompt = BiometricPrompt( + this, + executor, + object : BiometricPrompt + .AuthenticationCallback() { - override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { - super.onAuthenticationError(errorCode, errString) - if (fromSearch) finish() - else finishAffinity() - } + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { + super.onAuthenticationError(errorCode, errString) + if (fromSearch) finish() + else finishAffinity() + } - override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { - super.onAuthenticationSucceeded(result) - SecureActivityDelegate.locked = false - preferences.lastUnlock().set(Date().time) - finish() + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { + super.onAuthenticationSucceeded(result) + SecureActivityDelegate.locked = false + preferences.lastUnlock().set(Date().time) + finish() + } } - }) + ) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle(getString(R.string.unlock_library)) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/security/SecureActivityDelegate.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/security/SecureActivityDelegate.kt index d37ea8bd69..18f6ad3491 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/security/SecureActivityDelegate.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/security/SecureActivityDelegate.kt @@ -51,8 +51,10 @@ object SecureActivityDelegate { private fun isAppLocked(): Boolean { return locked && - (preferences.lockAfter().getOrDefault() <= 0 || - Date().time >= preferences.lastUnlock().getOrDefault() + 60 * 1000 * preferences - .lockAfter().getOrDefault()) + ( + preferences.lockAfter().getOrDefault() <= 0 || + Date().time >= preferences.lastUnlock().getOrDefault() + 60 * 1000 * preferences + .lockAfter().getOrDefault() + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/AboutController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/AboutController.kt index bb93f7e12b..992dfe91c3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/AboutController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/AboutController.kt @@ -87,11 +87,11 @@ class AboutController : SettingsController() { onClick { val intent = Intent( Intent.ACTION_VIEW, - if (BuildConfig.DEBUG) { - "https://github.com/Jays2Kings/tachiyomiJ2K/commits/master" - } else { - "https://github.com/Jays2Kings/tachiyomiJ2K/releases/tag/v${BuildConfig.VERSION_NAME}" - }.toUri() + if (BuildConfig.DEBUG) { + "https://github.com/Jays2Kings/tachiyomiJ2K/commits/master" + } else { + "https://github.com/Jays2Kings/tachiyomiJ2K/releases/tag/v${BuildConfig.VERSION_NAME}" + }.toUri() ) startActivity(intent) } @@ -166,24 +166,26 @@ class AboutController : SettingsController() { class NewUpdateDialogController(bundle: Bundle? = null) : DialogController(bundle) { - constructor(body: String, url: String) : this(Bundle().apply { - putString(BODY_KEY, body) - putString(URL_KEY, url) - }) + constructor(body: String, url: String) : this( + Bundle().apply { + putString(BODY_KEY, body) + putString(URL_KEY, url) + } + ) override fun onCreateDialog(savedViewState: Bundle?): Dialog { return MaterialDialog(activity!!) - .title(R.string.new_version_available) - .message(text = args.getString(BODY_KEY) ?: "") - .positiveButton(R.string.download) { - val appContext = applicationContext - if (appContext != null) { - // Start download - val url = args.getString(URL_KEY) ?: "" - UpdaterService.start(appContext, url) - } + .title(R.string.new_version_available) + .message(text = args.getString(BODY_KEY) ?: "") + .positiveButton(R.string.download) { + val appContext = applicationContext + if (appContext != null) { + // Start download + val url = args.getString(URL_KEY) ?: "" + UpdaterService.start(appContext, url) } - .negativeButton(R.string.ignore) + } + .negativeButton(R.string.ignore) } private companion object { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/PreferenceDSL.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/PreferenceDSL.kt index 2e38b73590..938b310cce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/PreferenceDSL.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/PreferenceDSL.kt @@ -43,8 +43,8 @@ inline fun PreferenceGroup.editTextPreference(block: (@DSL EditTextPreference).( inline fun PreferenceGroup.dropDownPreference(block: (@DSL DropDownPreference).() -> Unit): DropDownPreference { - return initThenAdd(DropDownPreference(context), block).also(::initDialog) -} + return initThenAdd(DropDownPreference(context), block).also(::initDialog) + } inline fun PreferenceGroup.listPreference( activity: Activity?, @@ -52,31 +52,38 @@ inline fun PreferenceGroup.listPreference( -> Unit ): ListMatPreference { - return initThenAdd(ListMatPreference(activity, context), block) -} + return initThenAdd(ListMatPreference(activity, context), block) + } inline fun PreferenceGroup.intListPreference( activity: Activity?, - block: (@DSL - IntListMatPreference).() -> Unit + block: ( + @DSL + IntListMatPreference + ).() -> Unit ): IntListMatPreference { - return initThenAdd(IntListMatPreference(activity, context), block) -} + return initThenAdd(IntListMatPreference(activity, context), block) + } inline fun PreferenceGroup.multiSelectListPreferenceMat( activity: Activity?, - block: (@DSL - MultiListMatPreference).() + block: ( + @DSL + MultiListMatPreference + ).() -> Unit ): MultiListMatPreference { return initThenAdd(MultiListMatPreference(activity, context), block) } inline fun PreferenceScreen.preferenceCategory(block: (@DSL PreferenceCategory).() -> Unit): PreferenceCategory { - return addThenInit(PreferenceCategory(context).apply { - isIconSpaceReserved = false - }, block) + return addThenInit( + PreferenceCategory(context).apply { + isIconSpaceReserved = false + }, + block + ) } inline fun PreferenceScreen.preferenceScreen(block: (@DSL PreferenceScreen).() -> Unit): PreferenceScreen { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAdvancedController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAdvancedController.kt index 41ff71bf26..85f44ecb8e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAdvancedController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAdvancedController.kt @@ -72,7 +72,8 @@ class SettingsAdvancedController : SettingsController() { preference { titleRes = R.string.clean_up_cached_covers summary = context.getString( - R.string.delete_old_covers_in_library_used_, coverCache.getChapterCacheSize() + R.string.delete_old_covers_in_library_used_, + coverCache.getChapterCacheSize() ) onClick { @@ -209,7 +210,7 @@ class SettingsAdvancedController : SettingsController() { for (mangaFolder in mangaFolders) { val manga = sourceManga.find { downloadProvider.getMangaDirName(it) == mangaFolder.name } if (manga == null) { - // download is orphaned and not even in the db delete it if remove non favorited is enabled + // download is orphaned and not even in the db delete it if remove non favorited is enabled if (removeNonFavorite) { foldersCleared += 1 + (mangaFolder.listFiles()?.size ?: 0) mangaFolder.delete() @@ -248,19 +249,24 @@ class SettingsAdvancedController : SettingsController() { } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - }, { - activity?.toast(R.string.cache_delete_error) - }, { - activity?.toast( - resources?.getQuantityString( - R.plurals.cache_cleared, - deletedFiles, deletedFiles + .subscribe( + { + }, + { + activity?.toast(R.string.cache_delete_error) + }, + { + activity?.toast( + resources?.getQuantityString( + R.plurals.cache_cleared, + deletedFiles, + deletedFiles + ) ) - ) - findPreference(CLEAR_CACHE_KEY)?.summary = - resources?.getString(R.string.used_, chapterCache.readableSize) - }) + findPreference(CLEAR_CACHE_KEY)?.summary = + resources?.getString(R.string.used_, chapterCache.readableSize) + } + ) } class ClearDatabaseDialogController : DialogController() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt index e085caac36..6a51c8e219 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt @@ -69,9 +69,14 @@ class SettingsBackupController : SettingsController() { intListPreference(activity) { key = Keys.backupInterval titleRes = R.string.backup_frequency - entriesRes = arrayOf(R.string.manual, R.string.every_6_hours, - R.string.every_12_hours, R.string.daily, - R.string.every_2_days, R.string.weekly) + entriesRes = arrayOf( + R.string.manual, + R.string.every_6_hours, + R.string.every_12_hours, + R.string.daily, + R.string.every_2_days, + R.string.weekly + ) entryValues = listOf(0, 6, 12, 24, 48, 168) defaultValue = 0 @@ -102,10 +107,10 @@ class SettingsBackupController : SettingsController() { } preferences.backupsDirectory().asObservable() - .subscribeUntilDestroy { path -> - val dir = UniFile.fromUri(context, path.toUri()) - summary = dir.filePath + "/automatic" - } + .subscribeUntilDestroy { path -> + val dir = UniFile.fromUri(context, path.toUri()) + summary = dir.filePath + "/automatic" + } } val backupNumber = intListPreference(activity) { key = Keys.numberOfBackups @@ -116,10 +121,10 @@ class SettingsBackupController : SettingsController() { } preferences.backupInterval().asObservable() - .subscribeUntilDestroy { - backupDir.isVisible = it > 0 - backupNumber.isVisible = it > 0 - } + .subscribeUntilDestroy { + backupDir.isVisible = it > 0 + backupNumber.isVisible = it > 0 + } } } @@ -132,7 +137,7 @@ class SettingsBackupController : SettingsController() { // Get UriPermission so it's possible to write files val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_GRANT_WRITE_URI_PERMISSION + Intent.FLAG_GRANT_WRITE_URI_PERMISSION if (uri != null) { activity.contentResolver.takePersistableUriPermission(uri, flags) @@ -146,7 +151,7 @@ class SettingsBackupController : SettingsController() { val uri = data.data val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_GRANT_WRITE_URI_PERMISSION + Intent.FLAG_GRANT_WRITE_URI_PERMISSION if (uri != null) { activity.contentResolver.takePersistableUriPermission(uri, flags) @@ -176,9 +181,9 @@ class SettingsBackupController : SettingsController() { try { // Use Android's built-in file creator val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) - .addCategory(Intent.CATEGORY_OPENABLE) - .setType("application/*") - .putExtra(Intent.EXTRA_TITLE, Backup.getDefaultFilename()) + .addCategory(Intent.CATEGORY_OPENABLE) + .setType("application/*") + .putExtra(Intent.EXTRA_TITLE, Backup.getDefaultFilename()) startActivityForResult(intent, CODE_BACKUP_CREATE) } catch (e: ActivityNotFoundException) { @@ -190,48 +195,58 @@ class SettingsBackupController : SettingsController() { class CreateBackupDialog : DialogController() { override fun onCreateDialog(savedViewState: Bundle?): Dialog { val activity = activity!! - val options = arrayOf(R.string.manga, R.string.categories, R.string.chapters, - R.string.tracking, R.string.history) - .map { activity.getString(it) } + val options = arrayOf( + R.string.manga, + R.string.categories, + R.string.chapters, + R.string.tracking, + R.string.history + ) + .map { activity.getString(it) } return MaterialDialog(activity) - .title(R.string.create_backup) - .message(R.string.what_should_backup) - .listItemsMultiChoice(items = options, disabledIndices = intArrayOf(0), - initialSelection = intArrayOf(0, 1, 2, 3, 4)) { _, positions, _ -> - var flags = 0 - for (i in 1 until positions.size) { - when (positions[i]) { - 1 -> flags = flags or BackupCreateService.BACKUP_CATEGORY - 2 -> flags = flags or BackupCreateService.BACKUP_CHAPTER - 3 -> flags = flags or BackupCreateService.BACKUP_TRACK - 4 -> flags = flags or BackupCreateService.BACKUP_HISTORY - } + .title(R.string.create_backup) + .message(R.string.what_should_backup) + .listItemsMultiChoice( + items = options, + disabledIndices = intArrayOf(0), + initialSelection = intArrayOf(0, 1, 2, 3, 4) + ) { _, positions, _ -> + var flags = 0 + for (i in 1 until positions.size) { + when (positions[i]) { + 1 -> flags = flags or BackupCreateService.BACKUP_CATEGORY + 2 -> flags = flags or BackupCreateService.BACKUP_CHAPTER + 3 -> flags = flags or BackupCreateService.BACKUP_TRACK + 4 -> flags = flags or BackupCreateService.BACKUP_HISTORY } - - (targetController as? SettingsBackupController)?.createBackup(flags) } - .positiveButton(R.string.create) - .negativeButton(android.R.string.cancel) + + (targetController as? SettingsBackupController)?.createBackup(flags) + } + .positiveButton(R.string.create) + .negativeButton(android.R.string.cancel) } } class RestoreBackupDialog(bundle: Bundle? = null) : DialogController(bundle) { - constructor(uri: Uri) : this(Bundle().apply { - putParcelable(KEY_URI, uri) - }) + constructor(uri: Uri) : this( + Bundle().apply { + putParcelable(KEY_URI, uri) + } + ) override fun onCreateDialog(savedViewState: Bundle?): Dialog { return MaterialDialog(activity!!) - .title(R.string.restore_backup) - .message(R.string.restore_message) - .positiveButton(R.string.restore) { - val context = applicationContext - if (context != null) { - activity?.toast(R.string.restoring_backup) - BackupRestoreService.start(context, args.getParcelable(KEY_URI)!!) - } + .title(R.string.restore_backup) + .message(R.string.restore_message) + .positiveButton(R.string.restore) { + val context = applicationContext + if (context != null) { + activity?.toast(R.string.restoring_backup) + BackupRestoreService.start(context, args.getParcelable(KEY_URI)!!) } + } } private companion object { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBrowseController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBrowseController.kt index 7727fed5d6..e1a1a392cd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBrowseController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBrowseController.kt @@ -52,7 +52,7 @@ class SettingsBrowseController : SettingsController() { onClick { router.pushController(MigrationController().withFadeTransaction()) } } if (preferences.skipPreMigration().getOrDefault() || preferences.migrationSources() - .isSet() + .isSet() ) { switchPreference { key = PreferenceKeys.skipPreMigration @@ -69,13 +69,15 @@ class SettingsBrowseController : SettingsController() { val pinnedSources = (preferences.pinnedCatalogues().get() ?: emptySet()).joinToString("/") preferences.migrationSources().set(pinnedSources) - (activity as? MainActivity)?.setUndoSnackBar(view?.snack( - R.string.migration_sources_changed - ) { - setAction(R.string.undo) { - preferences.migrationSources().set(ogSources) + (activity as? MainActivity)?.setUndoSnackBar( + view?.snack( + R.string.migration_sources_changed + ) { + setAction(R.string.undo) { + preferences.migrationSources().set(ogSources) + } } - }) + ) } } @@ -92,13 +94,15 @@ class SettingsBrowseController : SettingsController() { .sortedBy { "(${it.lang}) ${it.name}" } .joinToString("/") { it.id.toString() } preferences.migrationSources().set(enabledSources) - (activity as? MainActivity)?.setUndoSnackBar(view?.snack( - R.string.migration_sources_changed - ) { - setAction(R.string.undo) { - preferences.migrationSources().set(ogSources) + (activity as? MainActivity)?.setUndoSnackBar( + view?.snack( + R.string.migration_sources_changed + ) { + setAction(R.string.undo) { + preferences.migrationSources().set(ogSources) + } } - }) + ) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsDownloadController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsDownloadController.kt index 8af76d799d..1df0d0d613 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsDownloadController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsDownloadController.kt @@ -42,10 +42,10 @@ class SettingsDownloadController : SettingsController() { } preferences.downloadsDirectory().asObservable() - .subscribeUntilDestroy { path -> - val dir = UniFile.fromUri(context, path.toUri()) - summary = dir.filePath ?: path - } + .subscribeUntilDestroy { path -> + val dir = UniFile.fromUri(context, path.toUri()) + summary = dir.filePath ?: path + } } switchPreference { key = Keys.downloadOnlyOverWifi @@ -63,9 +63,14 @@ class SettingsDownloadController : SettingsController() { intListPreference(activity) { key = Keys.removeAfterReadSlots titleRes = R.string.remove_after_read - entriesRes = arrayOf(R.string.never, R.string.last_read_chapter, - R.string.second_to_last, R.string.third_to_last, R.string.fourth_to_last, - R.string.fifth_to_last) + entriesRes = arrayOf( + R.string.never, + R.string.last_read_chapter, + R.string.second_to_last, + R.string.third_to_last, + R.string.fourth_to_last, + R.string.fifth_to_last + ) entryRange = -1..4 defaultValue = -1 } @@ -89,19 +94,19 @@ class SettingsDownloadController : SettingsController() { allSelectionRes = R.string.all preferences.downloadNew().asObservable() - .subscribeUntilDestroy { isVisible = it } + .subscribeUntilDestroy { isVisible = it } preferences.downloadNewCategories().asObservable() - .subscribeUntilDestroy { - val selectedCategories = it - .mapNotNull { id -> dbCategories.find { it.id == id.toInt() } } - .sortedBy { it.order } + .subscribeUntilDestroy { + val selectedCategories = it + .mapNotNull { id -> dbCategories.find { it.id == id.toInt() } } + .sortedBy { it.order } - customSummary = if (selectedCategories.isEmpty()) - resources?.getString(R.string.all) - else - selectedCategories.joinToString { it.name } - } + customSummary = if (selectedCategories.isEmpty()) + resources?.getString(R.string.all) + else + selectedCategories.joinToString { it.name } + } } preferenceCategory { intListPreference(activity) { @@ -126,7 +131,7 @@ class SettingsDownloadController : SettingsController() { val context = applicationContext ?: return val uri = data.data val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_GRANT_WRITE_URI_PERMISSION + Intent.FLAG_GRANT_WRITE_URI_PERMISSION if (uri != null) { @Suppress("NewApi") @@ -176,11 +181,11 @@ class SettingsDownloadController : SettingsController() { private fun getExternalDirs(): List { val defaultDir = Environment.getExternalStorageDirectory().absolutePath + - File.separator + resources?.getString(R.string.app_name) + - File.separator + "downloads" + File.separator + resources?.getString(R.string.app_name) + + File.separator + "downloads" return mutableListOf(File(defaultDir)) + - ContextCompat.getExternalFilesDirs(activity!!, "").filterNotNull() + ContextCompat.getExternalFilesDirs(activity!!, "").filterNotNull() } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt index b99421b35a..c847801c9d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt @@ -21,13 +21,15 @@ class SettingsGeneralController : SettingsController() { listPreference(activity) { key = Keys.lang titleRes = R.string.language - entryValues = listOf("", "ar", "bg", "bn", "ca", "cs", "de", "el", "en-US", "en-GB", - "es", "fr", "hi", "hu", "in", "it", "ja", "ko", "lv", "ms", "nb-rNO", "nl", "pl", "pt", - "pt-BR", "ro", "ru", "sc", "sr", "sv", "th", "tl", "tr", "uk", "vi", "zh-rCN") + entryValues = listOf( + "", "ar", "bg", "bn", "ca", "cs", "de", "el", "en-US", "en-GB", + "es", "fr", "hi", "hu", "in", "it", "ja", "ko", "lv", "ms", "nb-rNO", "nl", "pl", "pt", + "pt-BR", "ro", "ru", "sc", "sr", "sv", "th", "tl", "tr", "uk", "vi", "zh-rCN" + ) entries = entryValues.map { value -> val locale = LocaleHelper.getLocaleFromString(value.toString()) locale?.getDisplayName(locale)?.capitalize() - ?: context.getString(R.string.system_default) + ?: context.getString(R.string.system_default) } defaultValue = "" summary = "%s" @@ -45,10 +47,17 @@ class SettingsGeneralController : SettingsController() { intListPreference(activity) { key = Keys.theme titleRes = R.string.app_theme - entriesRes = arrayOf(R.string.white_theme, R.string.light_blue, R.string.dark, - R.string.amoled_black, R.string.dark_blue, R.string.system_default, R.string + entriesRes = arrayOf( + R.string.white_theme, + R.string.light_blue, + R.string.dark, + R.string.amoled_black, + R.string.dark_blue, + R.string.system_default, + R.string .system_default_amoled, - R.string.system_default_all_blue) + R.string.system_default_all_blue + ) entryValues = listOf(1, 8, 2, 3, 4, 5, 6, 7) defaultValue = 5 @@ -120,7 +129,9 @@ class SettingsGeneralController : SettingsController() { 0 -> context.getString(R.string.always) -1 -> context.getString(R.string.never) else -> resources?.getQuantityString( - R.plurals.after_minutes, it.toInt(), it + R.plurals.after_minutes, + it.toInt(), + it ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsLibraryController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsLibraryController.kt index 20a1202e12..58e50dcd19 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsLibraryController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsLibraryController.kt @@ -118,7 +118,8 @@ class SettingsLibraryController : SettingsController() { // The following array lines up with the list rankingScheme in: // ../../data/library/LibraryUpdateRanker.kt entriesRes = arrayOf( - R.string.alphabetically, R.string.last_updated + R.string.alphabetically, + R.string.last_updated ) entryRange = 0..1 defaultValue = 0 @@ -147,7 +148,8 @@ class SettingsLibraryController : SettingsController() { titleRes = R.string.categories_on_manual entriesRes = arrayOf( - R.string.first_category, R.string.categories_in_global_update + R.string.first_category, + R.string.categories_in_global_update ) entryRange = 0..1 defaultValue = -1 diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt index 38d92b02f0..3ef9e65315 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt @@ -29,7 +29,10 @@ class SettingsReaderController : SettingsController() { key = Keys.rotation titleRes = R.string.rotation entriesRes = arrayOf( - R.string.free, R.string.lock, R.string.force_portrait, R.string.force_landscape + R.string.free, + R.string.lock, + R.string.force_portrait, + R.string.force_landscape ) entryRange = 1..4 defaultValue = 1 @@ -50,9 +53,11 @@ class SettingsReaderController : SettingsController() { key = Keys.doubleTapAnimationSpeed titleRes = R.string.double_tap_anim_speed entries = listOf( - context.getString(R.string.no_animation), context.getString( + context.getString(R.string.no_animation), + context.getString( R.string.fast - ), context.getString(R.string.normal) + ), + context.getString(R.string.normal) ) entryValues = listOf(1, 250, 500) // using a value of 0 breaks the image viewer, so // min is 1 @@ -125,7 +130,10 @@ class SettingsReaderController : SettingsController() { key = Keys.zoomStart titleRes = R.string.zoom_start_position entriesRes = arrayOf( - R.string.automatic, R.string.left, R.string.right, R.string.center + R.string.automatic, + R.string.left, + R.string.right, + R.string.center ) entryRange = 1..4 defaultValue = 1 diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt index 5fbf31e480..b179ffe0f0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt @@ -50,28 +50,33 @@ class SettingsSourcesController : SettingsController() { orderedLangs.forEach { lang -> // Create a preference group and set initial state and change listener - langPrefs.add(Pair(lang, SwitchPreferenceCategory(context).apply { - preferenceScreen.addPreference(this) - title = LocaleHelper.getDisplayName(lang, context) - isPersistent = false - if (lang in activeLangsCodes) { - setChecked(true) - addLanguageSources(this, sortedSources(sourcesByLang[lang])) - } + langPrefs.add( + Pair( + lang, + SwitchPreferenceCategory(context).apply { + preferenceScreen.addPreference(this) + title = LocaleHelper.getDisplayName(lang, context) + isPersistent = false + if (lang in activeLangsCodes) { + setChecked(true) + addLanguageSources(this, sortedSources(sourcesByLang[lang])) + } - onChange { newValue -> - val checked = newValue as Boolean - val current = preferences.enabledLanguages().getOrDefault() - if (!checked) { - preferences.enabledLanguages().set(current - lang) - removeAll() - } else { - preferences.enabledLanguages().set(current + lang) - addLanguageSources(this, sortedSources(sourcesByLang[lang])) + onChange { newValue -> + val checked = newValue as Boolean + val current = preferences.enabledLanguages().getOrDefault() + if (!checked) { + preferences.enabledLanguages().set(current - lang) + removeAll() + } else { + preferences.enabledLanguages().set(current + lang) + addLanguageSources(this, sortedSources(sourcesByLang[lang])) + } + true + } } - true - } - })) + ) + ) } } @@ -180,17 +185,19 @@ class SettingsSourcesController : SettingsController() { var expandActionViewFromInteraction = false private fun MenuItem.fixExpand(onExpand: ((MenuItem) -> Boolean)? = null, onCollapse: ((MenuItem) -> Boolean)? = null) { - setOnActionExpandListener(object : MenuItem.OnActionExpandListener { - override fun onMenuItemActionExpand(item: MenuItem): Boolean { - return onExpand?.invoke(item) ?: true - } + setOnActionExpandListener( + object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem): Boolean { + return onExpand?.invoke(item) ?: true + } - override fun onMenuItemActionCollapse(item: MenuItem): Boolean { - activity?.invalidateOptionsMenu() + override fun onMenuItemActionCollapse(item: MenuItem): Boolean { + activity?.invalidateOptionsMenu() - return onCollapse?.invoke(item) ?: true + return onCollapse?.invoke(item) ?: true + } } - }) + ) if (expandActionViewFromInteraction) { expandActionViewFromInteraction = false diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt index d44ecd5c4b..cc0ad52415 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt @@ -18,8 +18,10 @@ import eu.kanade.tachiyomi.widget.preference.TrackLogoutDialog import uy.kohesive.injekt.injectLazy import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys -class SettingsTrackingController : SettingsController(), - TrackLoginDialog.Listener, TrackLogoutDialog.Listener { +class SettingsTrackingController : + SettingsController(), + TrackLoginDialog.Listener, + TrackLogoutDialog.Listener { private val trackManager: TrackManager by injectLazy() @@ -66,10 +68,13 @@ class SettingsTrackingController : SettingsController(), service: TrackService, block: (@DSL LoginPreference).() -> Unit ): LoginPreference { - return initThenAdd(LoginPreference(context).apply { - key = Keys.trackUsername(service.id) - title = service.name - }, block) + return initThenAdd( + LoginPreference(context).apply { + key = Keys.trackUsername(service.id) + title = service.name + }, + block + ) } override fun onActivityResumed(activity: Activity) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/LangHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/LangHolder.kt index 485993fcc5..6a1d5eaa5d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/LangHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/LangHolder.kt @@ -9,7 +9,7 @@ import eu.kanade.tachiyomi.util.system.LocaleHelper import kotlinx.android.synthetic.main.source_header_item.* class LangHolder(view: View, adapter: FlexibleAdapter>) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { fun bind(item: LangItem) { title.text = LocaleHelper.getDisplayName(item.code, itemView.context) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceAdapter.kt index c3ced3d249..aaf0440b04 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceAdapter.kt @@ -9,7 +9,7 @@ import eu.davidea.flexibleadapter.items.IFlexible * @param controller instance of [SourceController]. */ class SourceAdapter(val controller: SourceController) : - FlexibleAdapter>(null, controller, true) { + FlexibleAdapter>(null, controller, true) { init { setDisplayHeadersAtStartUp(true) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceController.kt index 8d7e1dadef..a1ed0eb2d0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceController.kt @@ -56,11 +56,12 @@ import kotlin.math.max * [SourceAdapter.SourceListener] call function data on browse item click. * [SourceAdapter.OnLatestClickListener] call function data on latest item click */ -class SourceController : NucleusController(), - FlexibleAdapter.OnItemClickListener, - SourceAdapter.SourceListener, - RootSearchInterface, - BottomSheetController { +class SourceController : + NucleusController(), + FlexibleAdapter.OnItemClickListener, + SourceAdapter.SourceListener, + RootSearchInterface, + BottomSheetController { /** * Application preferences. @@ -124,54 +125,62 @@ class SourceController : NucleusController(), val array = view.context.obtainStyledAttributes(attrsArray) val appBarHeight = array.getDimensionPixelSize(0, 0) array.recycle() - scrollViewWith(recycler, afterInsets = { - headerHeight = it.systemWindowInsetTop + appBarHeight - }) + scrollViewWith( + recycler, + afterInsets = { + headerHeight = it.systemWindowInsetTop + appBarHeight + } + ) requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 301) ext_bottom_sheet.onCreate(this) - ext_bottom_sheet.sheetBehavior?.addBottomSheetCallback(object : BottomSheetBehavior - .BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { - val recycler = recycler ?: return - shadow2?.alpha = (1 - max(0f, progress)) * 0.25f - activity?.appbar?.elevation = max(progress * 15f, - if (recycler.canScrollVertically(-1)) 15f else 0f) + ext_bottom_sheet.sheetBehavior?.addBottomSheetCallback( + object : BottomSheetBehavior + .BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) { + val recycler = recycler ?: return + shadow2?.alpha = (1 - max(0f, progress)) * 0.25f + activity?.appbar?.elevation = max( + progress * 15f, + if (recycler.canScrollVertically(-1)) 15f else 0f + ) - sheet_layout?.alpha = 1 - progress - activity?.appbar?.y = max(activity!!.appbar.y, -headerHeight * (1 - progress)) - val oldShow = showingExtensions - showingExtensions = progress > 0.92f - if (oldShow != showingExtensions) { - setTitle() - activity?.invalidateOptionsMenu() + sheet_layout?.alpha = 1 - progress + activity?.appbar?.y = max(activity!!.appbar.y, -headerHeight * (1 - progress)) + val oldShow = showingExtensions + showingExtensions = progress > 0.92f + if (oldShow != showingExtensions) { + setTitle() + activity?.invalidateOptionsMenu() + } + } + + override fun onStateChanged(p0: View, state: Int) { + val extBottomSheet = ext_bottom_sheet ?: return + if (state == BottomSheetBehavior.STATE_EXPANDED) { + activity?.appbar?.y = 0f + } + if (state == BottomSheetBehavior.STATE_EXPANDED || + state == BottomSheetBehavior.STATE_COLLAPSED + ) { + sheet_layout?.alpha = + if (state == BottomSheetBehavior.STATE_COLLAPSED) 1f else 0f + showingExtensions = state == BottomSheetBehavior.STATE_EXPANDED + setTitle() + if (state == BottomSheetBehavior.STATE_EXPANDED) + extBottomSheet.fetchOnlineExtensionsIfNeeded() + else extBottomSheet.shouldCallApi = true + activity?.invalidateOptionsMenu() + } + + retainViewMode = if (state == BottomSheetBehavior.STATE_EXPANDED) + RetainViewMode.RETAIN_DETACH else RetainViewMode.RELEASE_DETACH + sheet_layout.isClickable = state == BottomSheetBehavior.STATE_COLLAPSED + sheet_layout.isFocusable = state == BottomSheetBehavior.STATE_COLLAPSED } } - - override fun onStateChanged(p0: View, state: Int) { - val extBottomSheet = ext_bottom_sheet ?: return - if (state == BottomSheetBehavior.STATE_EXPANDED) { - activity?.appbar?.y = 0f - } - if (state == BottomSheetBehavior.STATE_EXPANDED || - state == BottomSheetBehavior.STATE_COLLAPSED) { - sheet_layout?.alpha = - if (state == BottomSheetBehavior.STATE_COLLAPSED) 1f else 0f - showingExtensions = state == BottomSheetBehavior.STATE_EXPANDED - setTitle() - if (state == BottomSheetBehavior.STATE_EXPANDED) - extBottomSheet.fetchOnlineExtensionsIfNeeded() - else extBottomSheet.shouldCallApi = true - activity?.invalidateOptionsMenu() - } - - retainViewMode = if (state == BottomSheetBehavior.STATE_EXPANDED) - RetainViewMode.RETAIN_DETACH else RetainViewMode.RELEASE_DETACH - sheet_layout.isClickable = state == BottomSheetBehavior.STATE_COLLAPSED - sheet_layout.isFocusable = state == BottomSheetBehavior.STATE_COLLAPSED - } - }) + ) if (showingExtensions) { ext_bottom_sheet.sheetBehavior?.expand() @@ -262,7 +271,7 @@ class SourceController : NucleusController(), override fun onPinClick(position: Int) { val item = adapter?.getItem(position) as? SourceItem ?: return val isPinned = item.isPinned ?: item.header?.code?.equals(SourcePresenter.PINNED_KEY) - ?: false + ?: false pinCatalogue(item.source, isPinned) } @@ -353,7 +362,7 @@ class SourceController : NucleusController(), (RouterTransaction.with(controller)).popChangeHandler( SettingsSourcesFadeChangeHandler() ).pushChangeHandler(FadeChangeHandler()) - ) + ) } else -> return super.onOptionsItemSelected(item) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceDividerItemDecoration.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceDividerItemDecoration.kt index b54a64bc8c..6531a5e8a1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceDividerItemDecoration.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceDividerItemDecoration.kt @@ -22,7 +22,8 @@ class SourceDividerItemDecoration(context: Context) : androidx.recyclerview.widg val child = parent.getChildAt(i) val holder = parent.getChildViewHolder(child) if (holder is SourceHolder && - parent.getChildViewHolder(parent.getChildAt(i + 1)) is SourceHolder) { + parent.getChildViewHolder(parent.getChildAt(i + 1)) is SourceHolder + ) { val params = child.layoutParams as androidx.recyclerview.widget.RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + divider.intrinsicHeight diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceHolder.kt index 05e1358141..a321828b54 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceHolder.kt @@ -12,7 +12,7 @@ import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.source_item.* class SourceHolder(view: View, val adapter: SourceAdapter) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { init { source_pin.setOnClickListener { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceItem.kt index 9ec99cfbb1..3d344d41cd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceItem.kt @@ -16,7 +16,7 @@ import eu.kanade.tachiyomi.source.LocalSource * @param header The header for this item. */ class SourceItem(val source: CatalogueSource, header: LangItem? = null, val isPinned: Boolean? = null) : - AbstractSectionableItem(header) { + AbstractSectionableItem(header) { /** * Returns the layout resource of this item. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourcePresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourcePresenter.kt index 11efa3e0c2..a4dc86519d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourcePresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/SourcePresenter.kt @@ -78,7 +78,7 @@ class SourcePresenter( } sourceSubscription = Observable.just(sourceItems) - .subscribeLatestCache(SourceController::setSources) + .subscribeLatestCache(SourceController::setSources) } private fun loadLastUsedSource() { @@ -90,13 +90,13 @@ class SourcePresenter( sharedObs.take(1), sharedObs.skip(1).delay(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) ).distinctUntilChanged().map { - (sourceManager.get(it) as? CatalogueSource)?.let { source -> - val pinnedCatalogues = preferences.pinnedCatalogues().getOrDefault() - val isPinned = source.id.toString() in pinnedCatalogues - if (isPinned) null - else SourceItem(source, null, isPinned) - } - }.subscribeLatestCache(SourceController::setLastUsedSource) + (sourceManager.get(it) as? CatalogueSource)?.let { source -> + val pinnedCatalogues = preferences.pinnedCatalogues().getOrDefault() + val isPinned = source.id.toString() in pinnedCatalogues + if (isPinned) null + else SourceItem(source, null, isPinned) + } + }.subscribeLatestCache(SourceController::setLastUsedSource) } fun updateSources() { @@ -115,10 +115,10 @@ class SourcePresenter( val hiddenCatalogues = preferences.hiddenSources().getOrDefault() return sourceManager.getCatalogueSources() - .filter { it.lang in languages } - .filterNot { it.id.toString() in hiddenCatalogues } - .sortedBy { "(${it.lang}) ${it.name}" } + - sourceManager.get(LocalSource.ID) as LocalSource + .filter { it.lang in languages } + .filterNot { it.id.toString() in hiddenCatalogues } + .sortedBy { "(${it.lang}) ${it.name}" } + + sourceManager.get(LocalSource.ID) as LocalSource } companion object { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceController.kt index e5c0fbaf91..e7b0af4673 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceController.kt @@ -57,29 +57,33 @@ import java.util.concurrent.TimeUnit * Controller to manage the catalogues available in the app. */ open class BrowseSourceController(bundle: Bundle) : - NucleusController(bundle), - FlexibleAdapter.OnItemClickListener, - FlexibleAdapter.OnItemLongClickListener, - FlexibleAdapter.EndlessScrollListener, + NucleusController(bundle), + FlexibleAdapter.OnItemClickListener, + FlexibleAdapter.OnItemLongClickListener, + FlexibleAdapter.EndlessScrollListener, AddToLibraryCategoriesDialog.Listener { constructor( source: CatalogueSource, searchQuery: String? = null, smartSearchConfig: SourceController.SmartSearchConfig? = null - ) : this(Bundle().apply { - putLong(SOURCE_ID_KEY, source.id) + ) : this( + Bundle().apply { + putLong(SOURCE_ID_KEY, source.id) - if (searchQuery != null) - putString(SEARCH_QUERY_KEY, searchQuery) + if (searchQuery != null) + putString(SEARCH_QUERY_KEY, searchQuery) - if (smartSearchConfig != null) - putParcelable(SMART_SEARCH_CONFIG_KEY, smartSearchConfig) - }) + if (smartSearchConfig != null) + putParcelable(SMART_SEARCH_CONFIG_KEY, smartSearchConfig) + } + ) - constructor(source: CatalogueSource) : this(Bundle().apply { - putLong(SOURCE_ID_KEY, source.id) - }) + constructor(source: CatalogueSource) : this( + Bundle().apply { + putLong(SOURCE_ID_KEY, source.id) + } + ) /** * Preferences helper. @@ -189,20 +193,26 @@ open class BrowseSourceController(bundle: Bundle) : recycler.setHasFixedSize(true) recycler.adapter = adapter - scrollViewWith(recycler, true, afterInsets = { insets -> - fab?.updateLayoutParams { - bottomMargin = insets.systemWindowInsetBottom + 16.dpToPx + scrollViewWith( + recycler, + true, + afterInsets = { insets -> + fab?.updateLayoutParams { + bottomMargin = insets.systemWindowInsetBottom + 16.dpToPx + } } - }) + ) - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - if (dy <= 0) - fab.extend() - else - fab.shrink() + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + if (dy <= 0) + fab.extend() + else + fab.shrink() + } } - }) + ) catalogue_view.addView(recycler, 1) if (oldPosition != RecyclerView.NO_POSITION) { @@ -302,8 +312,11 @@ open class BrowseSourceController(bundle: Bundle) : if (filter is List<*>) { for (j in filter.indices) { if (filter[j] != - ((presenter.sourceFilters[i] as Filter.Group<*>).state[j] as - Filter<*>).state) { + ( + (presenter.sourceFilters[i] as Filter.Group<*>).state[j] as + Filter<*> + ).state + ) { matches = false break } @@ -333,8 +346,13 @@ open class BrowseSourceController(bundle: Bundle) : private fun openInWebView() { val source = presenter.source as? HttpSource ?: return val activity = activity ?: return - val intent = WebViewActivity.newIntent(activity, source.id, source.baseUrl, presenter - .source.name) + val intent = WebViewActivity.newIntent( + activity, + source.id, + source.baseUrl, + presenter + .source.name + ) startActivity(intent) } @@ -403,15 +421,19 @@ open class BrowseSourceController(bundle: Bundle) : val actions = emptyList().toMutableList() actions += if (presenter.source is LocalSource) { - EmptyView.Action(R.string.local_source_help_guide, - View.OnClickListener { openLocalSourceHelpGuide() }) + EmptyView.Action( + R.string.local_source_help_guide, + View.OnClickListener { openLocalSourceHelpGuide() } + ) } else { EmptyView.Action(R.string.retry, retryAction) } if (presenter.source is HttpSource) { - actions += EmptyView.Action(R.string.open_in_webview, - View.OnClickListener { openInWebView() }) + actions += EmptyView.Action( + R.string.open_in_webview, + View.OnClickListener { openInWebView() } + ) } empty_view.show( @@ -561,12 +583,14 @@ open class BrowseSourceController(bundle: Bundle) : setAction(R.string.undo) { if (!manga.favorite) addManga(manga, position) } - addCallback(object : BaseTransientBottomBar.BaseCallback() { - override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { - super.onDismissed(transientBottomBar, event) - if (!manga.favorite) presenter.confirmDeletion(manga) + addCallback( + object : BaseTransientBottomBar.BaseCallback() { + override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { + super.onDismissed(transientBottomBar, event) + if (!manga.favorite) presenter.confirmDeletion(manga) + } } - }) + ) } (activity as? MainActivity)?.setUndoSnackBar(snack) } else { @@ -596,7 +620,7 @@ open class BrowseSourceController(bundle: Bundle) : }.toTypedArray() AddToLibraryCategoriesDialog(this, manga, categories, preselected, position) - .showDialog(router) + .showDialog(router) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceHolder.kt index b3bf5301e4..3278ed2cca 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceHolder.kt @@ -14,7 +14,7 @@ import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder * @param adapter the adapter handling this holder. */ abstract class BrowseSourceHolder(view: View, adapter: FlexibleAdapter>) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { /** * Method called from [CatalogueAdapter.onBindViewHolder]. It updates the data for this diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceItem.kt index 7465e1a912..8eaa6936c7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceItem.kt @@ -25,7 +25,7 @@ class BrowseSourceItem( private val catalogueAsList: Preference, private val catalogueListType: Preference ) : - AbstractFlexibleItem() { + AbstractFlexibleItem() { override fun getLayoutRes(): Int { return if (catalogueAsList.getOrDefault()) @@ -44,17 +44,20 @@ class BrowseSourceItem( gradient.layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, (coverHeight * 0.66f).toInt(), - Gravity.BOTTOM) + Gravity.BOTTOM + ) card.updateLayoutParams { bottomMargin = 6.dpToPx } } else { constraint_layout.background = ContextCompat.getDrawable( - context, R.drawable.library_item_selector + context, + R.drawable.library_item_selector ) } constraint_layout.layoutParams = FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT ) cover_thumbnail.maxHeight = Int.MAX_VALUE cover_thumbnail.minimumHeight = 0 diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceListHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceListHolder.kt index 44ed67421c..ec2dbb13dd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceListHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceListHolder.kt @@ -22,7 +22,7 @@ import kotlinx.android.synthetic.main.manga_list_item.* * @constructor creates a new catalogue holder. */ class BrowseSourceListHolder(private val view: View, adapter: FlexibleAdapter>) : - BrowseSourceHolder(view, adapter) { + BrowseSourceHolder(view, adapter) { /** * Method called from [CatalogueAdapter.onBindViewHolder]. It updates the data for this diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePager.kt index 5efdf10642..a28f38b6c1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePager.kt @@ -18,14 +18,14 @@ open class BrowseSourcePager(val source: CatalogueSource, val query: String, val source.fetchSearchManga(page, query, filters) return observable - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnNext { - if (it.mangas.isNotEmpty()) { - onPageReceived(it) - } else { - throw NoResultsException() - } + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnNext { + if (it.mangas.isNotEmpty()) { + onPageReceived(it) + } else { + throw NoResultsException() } + } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePresenter.kt index 4a900ab885..799107abcc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourcePresenter.kt @@ -120,8 +120,10 @@ open class BrowseSourcePresenter( query = savedState.getString(::query.name, "") } - add(prefs.browseAsList().asObservable() - .subscribe { setDisplayMode(it) }) + add( + prefs.browseAsList().asObservable() + .subscribe { setDisplayMode(it) } + ) restartPager() } @@ -154,16 +156,19 @@ open class BrowseSourcePresenter( // Prepare the pager. pagerSubscription?.let { remove(it) } pagerSubscription = pager.results() - .observeOn(Schedulers.io()) - .map { it.first to it.second.map { networkToLocalManga(it, sourceId) } } - .doOnNext { initializeMangas(it.second) } - .map { it.first to it.second.map { BrowseSourceItem(it, browseAsList, sourceListType) } } - .observeOn(AndroidSchedulers.mainThread()) - .subscribeReplay({ view, (page, mangas) -> + .observeOn(Schedulers.io()) + .map { it.first to it.second.map { networkToLocalManga(it, sourceId) } } + .doOnNext { initializeMangas(it.second) } + .map { it.first to it.second.map { BrowseSourceItem(it, browseAsList, sourceListType) } } + .observeOn(AndroidSchedulers.mainThread()) + .subscribeReplay( + { view, (page, mangas) -> view.onAddPage(page, mangas) - }, { _, error -> + }, + { _, error -> Timber.e(error) - }) + } + ) // Request first page. requestNext() @@ -177,9 +182,12 @@ open class BrowseSourcePresenter( pageSubscription?.let { remove(it) } pageSubscription = Observable.defer { pager.requestNext() } - .subscribeFirst({ _, _ -> + .subscribeFirst( + { _, _ -> // Nothing to do when onNext is emitted. - }, BrowseSourceController::onAddPageError) + }, + BrowseSourceController::onAddPageError + ) } /** @@ -205,18 +213,21 @@ open class BrowseSourcePresenter( private fun subscribeToMangaInitializer() { initializerSubscription?.let { remove(it) } initializerSubscription = mangaDetailSubject.observeOn(Schedulers.io()) - .flatMap { Observable.from(it) } - .filter { it.thumbnail_url == null && !it.initialized } - .concatMap { getMangaDetailsObservable(it) } - .onBackpressureBuffer() - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ manga -> + .flatMap { Observable.from(it) } + .filter { it.thumbnail_url == null && !it.initialized } + .concatMap { getMangaDetailsObservable(it) } + .onBackpressureBuffer() + .observeOn(AndroidSchedulers.mainThread()) + .subscribe( + { manga -> @Suppress("DEPRECATION") view?.onMangaInitialized(manga) - }, { error -> + }, + { error -> Timber.e(error) - }) - .apply { add(this) } + } + ) + .apply { add(this) } } /** @@ -258,13 +269,13 @@ open class BrowseSourcePresenter( */ private fun getMangaDetailsObservable(manga: Manga): Observable { return source.fetchMangaDetails(manga) - .flatMap { networkManga -> - manga.copyFrom(networkManga) - manga.initialized = true - db.insertManga(manga).executeAsBlocking() - Observable.just(manga) - } - .onErrorResumeNext { Observable.just(manga) } + .flatMap { networkManga -> + manga.copyFrom(networkManga) + manga.initialized = true + db.insertManga(manga).executeAsBlocking() + Observable.just(manga) + } + .onErrorResumeNext { Observable.just(manga) } } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/SourceSearchSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/SourceSearchSheet.kt index 0a5f65852d..25d40d90df 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/SourceSearchSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/SourceSearchSheet.kt @@ -54,7 +54,9 @@ class SourceSearchSheet(activity: Activity) : sheetBehavior.skipCollapsed = true sheetBehavior.expand() setEdgeToEdge( - activity, view, 50.dpToPx + activity, + view, + 50.dpToPx ) recycler.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) @@ -72,35 +74,39 @@ class SourceSearchSheet(activity: Activity) : } } - sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) {} + sheetBehavior.addBottomSheetCallback( + object : BottomSheetBehavior.BottomSheetCallback() { + override fun onSlide(bottomSheet: View, progress: Float) {} - override fun onStateChanged(p0: View, state: Int) { - if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + override fun onStateChanged(p0: View, state: Int) { + if (state == BottomSheetBehavior.STATE_EXPANDED) { + sheetBehavior.skipCollapsed = true + } } } - }) + ) - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - super.onScrolled(recyclerView, dx, dy) - val atTop = !recycler.canScrollVertically(-1) - if (atTop != isNotElevated) { - elevationAnimator?.cancel() - isNotElevated = atTop - elevationAnimator?.cancel() - elevationAnimator = ObjectAnimator.ofFloat( - title_layout, - "elevation", - title_layout.elevation, - if (atTop) 0f else 10f.dpToPx - ) - elevationAnimator?.duration = 100 - elevationAnimator?.start() + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + super.onScrolled(recyclerView, dx, dy) + val atTop = !recycler.canScrollVertically(-1) + if (atTop != isNotElevated) { + elevationAnimator?.cancel() + isNotElevated = atTop + elevationAnimator?.cancel() + elevationAnimator = ObjectAnimator.ofFloat( + title_layout, + "elevation", + title_layout.elevation, + if (atTop) 0f else 10f.dpToPx + ) + elevationAnimator?.duration = 100 + elevationAnimator?.start() + } } } - }) + ) } override fun onWindowStartingActionMode( diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/GroupItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/GroupItem.kt index 5d81dc3ad7..50f4d6f983 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/GroupItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/GroupItem.kt @@ -34,10 +34,12 @@ class GroupItem(val filter: Filter.Group<*>) : AbstractExpandableHeaderItem>, holder: Holder, position: Int, payloads: MutableList?) { holder.title.text = filter.name - holder.icon.setVectorCompat(if (isExpanded) - R.drawable.ic_expand_more_24dp - else - R.drawable.ic_chevron_right_24dp) + holder.icon.setVectorCompat( + if (isExpanded) + R.drawable.ic_expand_more_24dp + else + R.drawable.ic_chevron_right_24dp + ) holder.itemView.setOnClickListener(holder) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SelectItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SelectItem.kt index 10825e75fa..fca213ad6d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SelectItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SelectItem.kt @@ -28,8 +28,11 @@ open class SelectItem(val filter: Filter.Select<*>) : AbstractFlexibleItem(holder.itemView.context, - android.R.layout.simple_spinner_item, filter.values).apply { + spinner.adapter = ArrayAdapter( + holder.itemView.context, + android.R.layout.simple_spinner_item, + filter.values + ).apply { setDropDownViewResource(R.layout.common_spinner_item) } spinner.onItemSelectedListener = IgnoreFirstSpinnerListener { pos -> diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortGroup.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortGroup.kt index 09daf01c7f..79b68d7703 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortGroup.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortGroup.kt @@ -31,10 +31,12 @@ class SortGroup(val filter: Filter.Sort) : AbstractExpandableHeaderItem>, holder: Holder, position: Int, payloads: MutableList?) { holder.title.text = filter.name - holder.icon.setVectorCompat(if (isExpanded) - R.drawable.ic_expand_more_24dp - else - R.drawable.ic_chevron_right_24dp) + holder.icon.setVectorCompat( + if (isExpanded) + R.drawable.ic_expand_more_24dp + else + R.drawable.ic_chevron_right_24dp + ) holder.itemView.setOnClickListener(holder) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortItem.kt index eda45fa6f2..fbbeb3b6ad 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/SortItem.kt @@ -35,9 +35,11 @@ class SortItem(val name: String, val group: SortGroup) : AbstractSectionableItem val i = filter.values.indexOf(name) fun getIcon() = when (filter.state) { - Filter.Sort.Selection(i, false) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_downward_32dp, null) + Filter.Sort.Selection(i, false) -> + VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_downward_32dp, null) ?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) } - Filter.Sort.Selection(i, true) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_upward_32dp, null) + Filter.Sort.Selection(i, true) -> + VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_upward_32dp, null) ?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) } else -> ContextCompat.getDrawable(view.context, R.drawable.empty_drawable_32dp) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TextItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TextItem.kt index 1dfba705cf..99071fa232 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TextItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TextItem.kt @@ -25,11 +25,13 @@ open class TextItem(val filter: Filter.Text) : AbstractFlexibleItem>, holder: Holder, position: Int, payloads: MutableList?) { holder.wrapper.hint = filter.name holder.edit.setText(filter.state) - holder.edit.addTextChangedListener(object : SimpleTextWatcher() { - override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { - filter.state = s.toString() + holder.edit.addTextChangedListener( + object : SimpleTextWatcher() { + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + filter.state = s.toString() + } } - }) + ) } override fun equals(other: Any?): Boolean { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TriStateItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TriStateItem.kt index 8a6bee16a2..b8382a2314 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TriStateItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/filter/TriStateItem.kt @@ -32,12 +32,16 @@ open class TriStateItem(val filter: Filter.TriState) : AbstractFlexibleItem TR.drawable.ic_check_box_outline_blank_24dp - Filter.TriState.STATE_INCLUDE -> TR.drawable.ic_check_box_24dp - Filter.TriState.STATE_EXCLUDE -> TR.drawable.ic_check_box_x_24dp - else -> throw Exception("Unknown state") - }, null)?.apply { + fun getIcon() = VectorDrawableCompat.create( + view.resources, + when (filter.state) { + Filter.TriState.STATE_IGNORE -> TR.drawable.ic_check_box_outline_blank_24dp + Filter.TriState.STATE_INCLUDE -> TR.drawable.ic_check_box_24dp + Filter.TriState.STATE_EXCLUDE -> TR.drawable.ic_check_box_x_24dp + else -> throw Exception("Unknown state") + }, + null + )?.apply { val color = if (filter.state == Filter.TriState.STATE_INCLUDE) R.attr.colorAccent else diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchAdapter.kt index 8aac1f809b..fbd1e4c487 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchAdapter.kt @@ -11,7 +11,7 @@ import eu.davidea.flexibleadapter.FlexibleAdapter * @param controller instance of [GlobalSearchController]. */ class GlobalSearchAdapter(val controller: GlobalSearchController) : - FlexibleAdapter(null, controller, true) { + FlexibleAdapter(null, controller, true) { /** * Bundle where the view state of the holders is saved. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchCardAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchCardAdapter.kt index ce4f981404..d06c0ee6a0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchCardAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchCardAdapter.kt @@ -9,7 +9,7 @@ import eu.kanade.tachiyomi.data.database.models.Manga * @param controller instance of [GlobalSearchController]. */ class GlobalSearchCardAdapter(controller: GlobalSearchController) : - FlexibleAdapter(null, controller, true) { + FlexibleAdapter(null, controller, true) { /** * Listen for browse item clicks. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchController.kt index ee72f4be6a..08837ee5b0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchController.kt @@ -29,7 +29,7 @@ open class GlobalSearchController( protected val initialQuery: String? = null, protected val extensionFilter: String? = null ) : NucleusController(), - GlobalSearchCardAdapter.OnMangaClickListener { + GlobalSearchCardAdapter.OnMangaClickListener { /** * Adapter containing search results grouped by lang. @@ -109,25 +109,27 @@ open class GlobalSearchController( val searchView = searchItem.actionView as SearchView searchItem.isVisible = customTitle == null - searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { - override fun onMenuItemActionExpand(item: MenuItem?): Boolean { - searchView.onActionViewExpanded() // Required to show the query in the view - searchView.setQuery(presenter.query, false) - return true - } + searchItem.setOnActionExpandListener( + object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem?): Boolean { + searchView.onActionViewExpanded() // Required to show the query in the view + searchView.setQuery(presenter.query, false) + return true + } - override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { - return true + override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { + return true + } } - }) + ) searchView.queryTextChangeEvents() - .filter { it.isSubmitted } - .subscribeUntilDestroy { - presenter.search(it.queryText().toString()) - searchItem.collapseActionView() - setTitle() // Update toolbar title - } + .filter { it.isSubmitted } + .subscribeUntilDestroy { + presenter.search(it.queryText().toString()) + searchItem.collapseActionView() + setTitle() // Update toolbar title + } } /** @@ -198,8 +200,9 @@ open class GlobalSearchController( val results = searchResult.firstOrNull()?.results if (results != null && results.size == 1) { val manga = results.first().manga - router.replaceTopController(MangaDetailsController(manga, true) - .withFadeTransaction() + router.replaceTopController( + MangaDetailsController(manga, true) + .withFadeTransaction() ) return } else if (results != null) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchHolder.kt index af06e8b14d..4ea3e0f760 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchHolder.kt @@ -14,7 +14,7 @@ import kotlinx.android.synthetic.main.source_global_search_controller_card.* * @param adapter instance of [GlobalSearchAdapter] */ class GlobalSearchHolder(view: View, val adapter: GlobalSearchAdapter) : - BaseFlexibleViewHolder(view, adapter) { + BaseFlexibleViewHolder(view, adapter) { /** * Adapter containing manga from search results. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchPresenter.kt index 5e08aab526..7ac2f4fe66 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/global_search/GlobalSearchPresenter.kt @@ -166,7 +166,8 @@ open class GlobalSearchPresenter( var items = initialItems fetchSourcesSubscription?.unsubscribe() - fetchSourcesSubscription = Observable.from(sources).flatMap({ source -> + fetchSourcesSubscription = Observable.from(sources).flatMap( + { source -> Observable.defer { source.fetchSearchManga(1, query, FilterList()) } .subscribeOn(Schedulers.io()).onErrorReturn { MangasPage( @@ -187,9 +188,12 @@ open class GlobalSearchPresenter( .map { createCatalogueSearchItem( source, - it.map { GlobalSearchMangaItem(it) }) + it.map { GlobalSearchMangaItem(it) } + ) } - }, 5).observeOn(AndroidSchedulers.mainThread()) + }, + 5 + ).observeOn(AndroidSchedulers.mainThread()) // Update matching source with the obtained results .map { result -> items.map { item -> if (item.source == result.source) result else item } @@ -197,11 +201,14 @@ open class GlobalSearchPresenter( // Update current state .doOnNext { items = it } // Deliver initial state - .startWith(initialItems).subscribeLatestCache({ view, manga -> - view.setItems(manga) - }, { _, error -> - Timber.e(error) - }) + .startWith(initialItems).subscribeLatestCache( + { view, manga -> + view.setItems(manga) + }, + { _, error -> + Timber.e(error) + } + ) } /** @@ -219,17 +226,20 @@ open class GlobalSearchPresenter( private fun initializeFetchImageSubscription() { fetchImageSubscription?.unsubscribe() fetchImageSubscription = fetchImageSubject.observeOn(Schedulers.io()).flatMap { - val source = it.second - Observable.from(it.first).filter { it.thumbnail_url == null && !it.initialized } - .map { Pair(it, source) } - .concatMap { getMangaDetailsObservable(it.first, it.second) } - .map { Pair(source as CatalogueSource, it) } - }.onBackpressureBuffer().observeOn(AndroidSchedulers.mainThread()) - .subscribe({ (source, manga) -> - @Suppress("DEPRECATION") view?.onMangaInitialized(source, manga) - }, { error -> - Timber.e(error) - }) + val source = it.second + Observable.from(it.first).filter { it.thumbnail_url == null && !it.initialized } + .map { Pair(it, source) } + .concatMap { getMangaDetailsObservable(it.first, it.second) } + .map { Pair(source as CatalogueSource, it) } + }.onBackpressureBuffer().observeOn(AndroidSchedulers.mainThread()) + .subscribe( + { (source, manga) -> + @Suppress("DEPRECATION") view?.onMangaInitialized(source, manga) + }, + { error -> + Timber.e(error) + } + ) } /** @@ -240,11 +250,11 @@ open class GlobalSearchPresenter( */ private fun getMangaDetailsObservable(manga: Manga, source: Source): Observable { return source.fetchMangaDetails(manga).flatMap { networkManga -> - manga.copyFrom(networkManga) - manga.initialized = true - db.insertManga(manga).executeAsBlocking() - Observable.just(manga) - }.onErrorResumeNext { Observable.just(manga) } + manga.copyFrom(networkManga) + manga.initialized = true + db.insertManga(manga).executeAsBlocking() + Observable.just(manga) + }.onErrorResumeNext { Observable.just(manga) } } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesController.kt index 0bf7e46b34..9a28b7a394 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesController.kt @@ -15,9 +15,11 @@ import kotlinx.android.synthetic.main.browse_source_controller.* */ class LatestUpdatesController(bundle: Bundle) : BrowseSourceController(bundle) { - constructor(source: CatalogueSource) : this(Bundle().apply { - putLong(SOURCE_ID_KEY, source.id) - }) + constructor(source: CatalogueSource) : this( + Bundle().apply { + putLong(SOURCE_ID_KEY, source.id) + } + ) override fun onViewCreated(view: View) { super.onViewCreated(view) diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesPager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesPager.kt index ff908a40b8..ca55cdcf97 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesPager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/source/latest/LatestUpdatesPager.kt @@ -14,8 +14,8 @@ class LatestUpdatesPager(val source: CatalogueSource) : Pager() { override fun requestNext(): Observable { return source.fetchLatestUpdates(currentPage) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnNext { onPageReceived(it) } + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnNext { onPageReceived(it) } } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/webview/WebViewActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/webview/WebViewActivity.kt index 871b6b2b9f..b75abe0f64 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/webview/WebViewActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/webview/WebViewActivity.kt @@ -89,8 +89,10 @@ class WebViewActivity : BaseActivity() { right = insets.systemWindowInsetRight ) insets.replaceSystemWindowInsets( - 0, insets.systemWindowInsetTop, - 0, insets.systemWindowInsetBottom + 0, + insets.systemWindowInsetTop, + 0, + insets.systemWindowInsetBottom ) } swipe_refresh.setStyle() @@ -98,8 +100,13 @@ class WebViewActivity : BaseActivity() { refreshPage() } - window.statusBarColor = ColorUtils.setAlphaComponent(getResourceColor(R.attr - .colorSecondary), 255) + window.statusBarColor = ColorUtils.setAlphaComponent( + getResourceColor( + R.attr + .colorSecondary + ), + 255 + ) content.setOnApplyWindowInsetsListener { v, insets -> // if pure white theme on a device that does not support dark status bar @@ -113,13 +120,18 @@ class WebViewActivity : BaseActivity() { } // if the android q+ device has gesture nav, transparent nav bar else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && - (v.rootWindowInsets.systemWindowInsetBottom != v.rootWindowInsets.tappableElementInsets.bottom)) { + (v.rootWindowInsets.systemWindowInsetBottom != v.rootWindowInsets.tappableElementInsets.bottom) + ) { getColor(android.R.color.transparent) } else { getResourceColor(android.R.attr.colorBackground) } - v.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, - insets.systemWindowInsetRight, 0) + v.setPadding( + insets.systemWindowInsetLeft, + insets.systemWindowInsetTop, + insets.systemWindowInsetRight, + 0 + ) if (Build.VERSION.SDK_INT >= 26 && !isInNightMode()) { content.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } @@ -193,8 +205,13 @@ class WebViewActivity : BaseActivity() { override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val lightMode = !isInNightMode() - window.statusBarColor = ColorUtils.setAlphaComponent(getResourceColor(R.attr - .colorSecondary), 255) + window.statusBarColor = ColorUtils.setAlphaComponent( + getResourceColor( + R.attr + .colorSecondary + ), + 255 + ) toolbar.setBackgroundColor(getResourceColor(R.attr.colorSecondary)) toolbar.popupTheme = if (lightMode) R.style.ThemeOverlay_MaterialComponents else R .style.ThemeOverlay_MaterialComponents_Dark @@ -210,11 +227,13 @@ class WebViewActivity : BaseActivity() { window.navigationBarColor = getResourceColor(android.R.attr.colorBackground) web_linear_layout.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or - View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or - View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && lightMode) { - web_linear_layout.systemUiVisibility = web_linear_layout.systemUiVisibility.or(View - .SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) + web_linear_layout.systemUiVisibility = web_linear_layout.systemUiVisibility.or( + View + .SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + ) } val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.windowLightStatusBar, typedValue, true) diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt index 34e1e0557a..0148d0b1cd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt @@ -24,7 +24,7 @@ inline fun SharedPreferences.getKey(key: String, default: T, dispatc awaitClose { unregisterOnSharedPreferenceChangeListener(listener) } } return flow - .flowOn(dispatcher) + .flowOn(dispatcher) } inline fun SharedPreferences.getItem(key: String, default: T): T { diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterSourceSync.kt b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterSourceSync.kt index 79b13bb6dc..9f00d84db9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterSourceSync.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterSourceSync.kt @@ -163,6 +163,6 @@ fun syncChaptersWithSource( // checks if the chapter in db needs updated private fun shouldUpdateDbChapter(dbChapter: Chapter, sourceChapter: SChapter): Boolean { return dbChapter.scanlator != sourceChapter.scanlator || dbChapter.name != sourceChapter.name || - dbChapter.date_upload != sourceChapter.date_upload || - dbChapter.chapter_number != sourceChapter.chapter_number + dbChapter.date_upload != sourceChapter.date_upload || + dbChapter.chapter_number != sourceChapter.chapter_number } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterUtil.kt b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterUtil.kt index 2a1ceadbbf..e3a85446c1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterUtil.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterUtil.kt @@ -39,11 +39,16 @@ class ChapterUtil { if (chapter.bookmark) { val context = textView.context val drawable = VectorDrawableCompat.create( - textView.resources, R.drawable.ic_bookmark_24dp, context.theme + textView.resources, + R.drawable.ic_bookmark_24dp, + context.theme ) drawable?.setBounds(0, 0, textView.textSize.toInt(), textView.textSize.toInt()) textView.setCompoundDrawablesRelative( - drawable, null, null, null + drawable, + null, + null, + null ) textView.compoundDrawableTintList = ColorStateList.valueOf( bookmarkedColor(context) diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/lang/Hash.kt b/app/src/main/java/eu/kanade/tachiyomi/util/lang/Hash.kt index 4410274276..a890632080 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/lang/Hash.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/lang/Hash.kt @@ -4,8 +4,10 @@ import java.security.MessageDigest object Hash { - private val chars = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f') + private val chars = charArrayOf( + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f' + ) private val MD5 get() = MessageDigest.getInstance("MD5") diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/storage/DiskUtil.kt b/app/src/main/java/eu/kanade/tachiyomi/util/storage/DiskUtil.kt index 4ad9f57b4c..f4bab4b681 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/storage/DiskUtil.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/storage/DiskUtil.kt @@ -34,16 +34,16 @@ object DiskUtil { fun getExternalStorages(context: Context): Collection { val directories = mutableSetOf() directories += ContextCompat.getExternalFilesDirs(context, null) - .filterNotNull() - .mapNotNull { - val file = File(it.absolutePath.substringBefore("/Android/")) - val state = EnvironmentCompat.getStorageState(file) - if (state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY) { - file - } else { - null - } + .filterNotNull() + .mapNotNull { + val file = File(it.absolutePath.substringBefore("/Android/")) + val state = EnvironmentCompat.getStorageState(file) + if (state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY) { + file + } else { + null } + } return directories } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt index 5b983ffe96..43a63c8eec 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt @@ -71,10 +71,10 @@ inline fun Context.notification(channelId: String, func: NotificationCompat.Buil */ fun Context.getFilePicker(currentDir: String): Intent { return Intent(this, CustomLayoutPickerActivity::class.java) - .putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false) - .putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true) - .putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR) - .putExtra(FilePickerActivity.EXTRA_START_PATH, currentDir) + .putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false) + .putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true) + .putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR) + .putExtra(FilePickerActivity.EXTRA_START_PATH, currentDir) } /** @@ -84,7 +84,7 @@ fun Context.getFilePicker(currentDir: String): Intent { * @return true if it has permissions. */ fun Context.hasPermission(permission: String) = - ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED + ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED /** * Returns the color for the given attribute. @@ -133,8 +133,10 @@ val Float.dpToPx: Float /** Converts to px and takes into account LTR/RTL layout */ val Float.dpToPxEnd: Float - get() = (this * Resources.getSystem().displayMetrics.density * - if (Resources.getSystem().isLTR) 1 else -1) + get() = ( + this * Resources.getSystem().displayMetrics.density * + if (Resources.getSystem().isLTR) 1 else -1 + ) val Resources.isLTR get() = configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR @@ -217,7 +219,7 @@ fun Context.isServiceRunning(serviceClass: Class<*>): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager @Suppress("DEPRECATION") return manager.getRunningServices(Integer.MAX_VALUE) - .any { className == it.service.className } + .any { className == it.service.className } } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/ImageUtil.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/ImageUtil.kt index d29f508fb4..caf0fd02dc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/ImageUtil.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/ImageUtil.kt @@ -80,20 +80,22 @@ object ImageUtil { val botRightIsDark = isDark(image.getPixel(right, bot)) var darkBG = (topLeftIsDark && (botLeftIsDark || botRightIsDark || topRightIsDark || midLeftIsDark || topMidIsDark)) || - (topRightIsDark && (botRightIsDark || botLeftIsDark || midRightIsDark || topMidIsDark)) + (topRightIsDark && (botRightIsDark || botLeftIsDark || midRightIsDark || topMidIsDark)) if (!isWhite(image.getPixel(left, top)) && pixelIsClose(image.getPixel(left, top), image.getPixel(midX, top)) && - !isWhite(image.getPixel(midX, top)) && pixelIsClose(image.getPixel(midX, top), image.getPixel(right, top)) && - !isWhite(image.getPixel(right, top)) && pixelIsClose(image.getPixel(right, top), image.getPixel(right, bot)) && - !isWhite(image.getPixel(right, bot)) && pixelIsClose(image.getPixel(right, bot), image.getPixel(midX, bot)) && - !isWhite(image.getPixel(midX, bot)) && pixelIsClose(image.getPixel(midX, bot), image.getPixel(left, bot)) && - !isWhite(image.getPixel(left, bot)) && pixelIsClose(image.getPixel(left, bot), image.getPixel(left, top))) + !isWhite(image.getPixel(midX, top)) && pixelIsClose(image.getPixel(midX, top), image.getPixel(right, top)) && + !isWhite(image.getPixel(right, top)) && pixelIsClose(image.getPixel(right, top), image.getPixel(right, bot)) && + !isWhite(image.getPixel(right, bot)) && pixelIsClose(image.getPixel(right, bot), image.getPixel(midX, bot)) && + !isWhite(image.getPixel(midX, bot)) && pixelIsClose(image.getPixel(midX, bot), image.getPixel(left, bot)) && + !isWhite(image.getPixel(left, bot)) && pixelIsClose(image.getPixel(left, bot), image.getPixel(left, top)) + ) return ColorDrawable(image.getPixel(left, top)) if (isWhite(image.getPixel(left, top)).toInt() + - isWhite(image.getPixel(right, top)).toInt() + - isWhite(image.getPixel(left, bot)).toInt() + - isWhite(image.getPixel(right, bot)).toInt() > 2) + isWhite(image.getPixel(right, top)).toInt() + + isWhite(image.getPixel(left, bot)).toInt() + + isWhite(image.getPixel(right, bot)).toInt() > 2 + ) darkBG = false var blackPixel = when { @@ -186,22 +188,36 @@ object ImageUtil { if (topIsBlackStreak && bottomIsBlackStreak) darkBG = true if (darkBG) { - return if (isWhite(image.getPixel(left, bot)) && isWhite(image.getPixel(right, bot))) GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, - intArrayOf(blackPixel, blackPixel, backgroundColor, backgroundColor)) - else if (isWhite(image.getPixel(left, top)) && isWhite(image.getPixel(right, top))) GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, - intArrayOf(backgroundColor, backgroundColor, blackPixel, blackPixel)) + return if (isWhite(image.getPixel(left, bot)) && isWhite(image.getPixel(right, bot))) GradientDrawable( + GradientDrawable.Orientation.TOP_BOTTOM, + intArrayOf(blackPixel, blackPixel, backgroundColor, backgroundColor) + ) + else if (isWhite(image.getPixel(left, top)) && isWhite(image.getPixel(right, top))) GradientDrawable( + GradientDrawable.Orientation.TOP_BOTTOM, + intArrayOf(backgroundColor, backgroundColor, blackPixel, blackPixel) + ) else ColorDrawable(blackPixel) } - if (topIsBlackStreak || (topLeftIsDark && topRightIsDark && - isDark(image.getPixel(left - offsetX, top)) && isDark(image.getPixel(right + offsetX, top)) && - (topMidIsDark || overallBlackPixels > 9))) - return GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, - intArrayOf(blackPixel, blackPixel, backgroundColor, backgroundColor)) - else if (bottomIsBlackStreak || (botLeftIsDark && botRightIsDark && - isDark(image.getPixel(left - offsetX, bot)) && isDark(image.getPixel(right + offsetX, bot)) && - (isDark(image.getPixel(midX, bot)) || overallBlackPixels > 9))) - return GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, - intArrayOf(backgroundColor, backgroundColor, blackPixel, blackPixel)) + if (topIsBlackStreak || ( + topLeftIsDark && topRightIsDark && + isDark(image.getPixel(left - offsetX, top)) && isDark(image.getPixel(right + offsetX, top)) && + (topMidIsDark || overallBlackPixels > 9) + ) + ) + return GradientDrawable( + GradientDrawable.Orientation.TOP_BOTTOM, + intArrayOf(blackPixel, blackPixel, backgroundColor, backgroundColor) + ) + else if (bottomIsBlackStreak || ( + botLeftIsDark && botRightIsDark && + isDark(image.getPixel(left - offsetX, bot)) && isDark(image.getPixel(right + offsetX, bot)) && + (isDark(image.getPixel(midX, bot)) || overallBlackPixels > 9) + ) + ) + return GradientDrawable( + GradientDrawable.Orientation.TOP_BOTTOM, + intArrayOf(backgroundColor, backgroundColor, blackPixel, blackPixel) + ) return ColorDrawable(backgroundColor) } @@ -213,8 +229,8 @@ object ImageUtil { private fun pixelIsClose(color1: Int, color2: Int): Boolean { return abs(Color.red(color1) - Color.red(color2)) < 30 && - abs(Color.green(color1) - Color.green(color2)) < 30 && - abs(Color.blue(color1) - Color.blue(color2)) < 30 + abs(Color.green(color1) - Color.green(color2)) < 30 && + abs(Color.blue(color1) - Color.blue(color2)) < 30 } private fun isWhite(color: Int): Boolean { diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/RxUtil.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/RxUtil.kt index 25d761d07b..80d9c0a649 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/RxUtil.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/RxUtil.kt @@ -10,14 +10,17 @@ suspend fun Single.await(subscribeOn: Scheduler? = null): T { return suspendCancellableCoroutine { continuation -> val self = if (subscribeOn != null) subscribeOn(subscribeOn) else this lateinit var sub: Subscription - sub = self.subscribe({ - continuation.resume(it) { - sub.unsubscribe() + sub = self.subscribe( + { + continuation.resume(it) { + sub.unsubscribe() + } + }, + { + if (!continuation.isCancelled) + continuation.resumeWithException(it) } - }, { - if (!continuation.isCancelled) - continuation.resumeWithException(it) - }) + ) continuation.invokeOnCancellation { sub.unsubscribe() diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/WebViewClientCompat.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/WebViewClientCompat.kt index 0699214c88..8d2eea7cf0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/WebViewClientCompat.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/WebViewClientCompat.kt @@ -60,8 +60,13 @@ abstract class WebViewClientCompat : WebViewClient() { request: WebResourceRequest, error: WebResourceError ) { - onReceivedErrorCompat(view, error.errorCode, error.description?.toString(), - request.url.toString(), request.isForMainFrame) + onReceivedErrorCompat( + view, + error.errorCode, + error.description?.toString(), + request.url.toString(), + request.isForMainFrame + ) } final override fun onReceivedError( @@ -79,7 +84,13 @@ abstract class WebViewClientCompat : WebViewClient() { request: WebResourceRequest, error: WebResourceResponse ) { - onReceivedErrorCompat(view, error.statusCode, error.reasonPhrase, request.url - .toString(), request.isForMainFrame) + onReceivedErrorCompat( + view, + error.statusCode, + error.reasonPhrase, + request.url + .toString(), + request.isForMainFrame + ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/WindowInsetsExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/WindowInsetsExtensions.kt index 52d582837e..9c24f920bb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/WindowInsetsExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/WindowInsetsExtensions.kt @@ -9,8 +9,10 @@ fun WindowInsets.getBottomGestureInsets(): Int { } /** returns if device using gesture nav and supports true edge to edge */ -fun WindowInsets.isBottomTappable() = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && - systemWindowInsetBottom != tappableElementInsets.bottom) +fun WindowInsets.isBottomTappable() = ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && + systemWindowInsetBottom != tappableElementInsets.bottom + ) fun WindowInsets.hasSideInsets() = systemWindowInsetLeft > 0 || systemWindowInsetRight > 0 diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/view/ControllerExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/view/ControllerExtensions.kt index 5794f95089..1af397acaf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/view/ControllerExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/view/ControllerExtensions.kt @@ -32,27 +32,29 @@ fun Controller.setOnQueryTextChangeListener( onlyOnSubmit: Boolean = false, f: (text: String?) -> Boolean ) { - searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { - override fun onQueryTextChange(newText: String?): Boolean { - if (!onlyOnSubmit && router.backstack.lastOrNull() + searchView.setOnQueryTextListener( + object : SearchView.OnQueryTextListener { + override fun onQueryTextChange(newText: String?): Boolean { + if (!onlyOnSubmit && router.backstack.lastOrNull() ?.controller() == this@setOnQueryTextChangeListener - ) { - return f(newText) + ) { + return f(newText) + } + return false } - return false - } - override fun onQueryTextSubmit(query: String?): Boolean { - if (router.backstack.lastOrNull()?.controller() == this@setOnQueryTextChangeListener) { - val imm = - activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager - ?: return f(query) - imm.hideSoftInputFromWindow(searchView.windowToken, 0) - return f(query) + override fun onQueryTextSubmit(query: String?): Boolean { + if (router.backstack.lastOrNull()?.controller() == this@setOnQueryTextChangeListener) { + val imm = + activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + ?: return f(query) + imm.hideSoftInputFromWindow(searchView.windowToken, 0) + return f(query) + } + return true } - return true } - }) + ) } fun Controller.liftAppbarWith(recycler: RecyclerView) { @@ -65,7 +67,8 @@ fun Controller.liftAppbarWith(recycler: RecyclerView) { elevate = el elevationAnim?.cancel() elevationAnim = ValueAnimator.ofFloat( - activity?.appbar?.elevation ?: 0f, if (el) 15f else 0f + activity?.appbar?.elevation ?: 0f, + if (el) 15f else 0f ) elevationAnim?.addUpdateListener { valueAnimator -> activity?.appbar?.elevation = valueAnimator.animatedValue as Float @@ -73,17 +76,19 @@ fun Controller.liftAppbarWith(recycler: RecyclerView) { elevationAnim?.start() } elevateFunc(recycler.canScrollVertically(-1)) - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - super.onScrolled(recyclerView, dx, dy) - if (router?.backstack?.lastOrNull() + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + super.onScrolled(recyclerView, dx, dy) + if (router?.backstack?.lastOrNull() ?.controller() == this@liftAppbarWith && activity != null - ) { - val notAtTop = recycler.canScrollVertically(-1) - if (notAtTop != elevate) elevateFunc(notAtTop) + ) { + val notAtTop = recycler.canScrollVertically(-1) + if (notAtTop != elevate) elevateFunc(notAtTop) + } } } - }) + ) } fun Controller.scrollViewWith( @@ -119,7 +124,9 @@ fun Controller.scrollViewWith( bottom = if (padBottom) insets.systemWindowInsetBottom else view.paddingBottom ) swipeRefreshLayout?.setProgressViewOffset( - true, headerHeight + (-60).dpToPx, headerHeight + 10.dpToPx + true, + headerHeight + (-60).dpToPx, + headerHeight + 10.dpToPx ) statusBarHeight = insets.systemWindowInsetTop afterInsets?.invoke(insets) @@ -133,7 +140,8 @@ fun Controller.scrollViewWith( } else { elevationAnim?.cancel() elevationAnim = ValueAnimator.ofFloat( - activity?.appbar?.elevation ?: 0f, if (el) 15f else 0f + activity?.appbar?.elevation ?: 0f, + if (el) 15f else 0f ) elevationAnim?.addUpdateListener { valueAnimator -> activity?.appbar?.elevation = valueAnimator.animatedValue as Float @@ -141,101 +149,112 @@ fun Controller.scrollViewWith( elevationAnim?.start() } } - addLifecycleListener(object : Controller.LifecycleListener() { - override fun onChangeStart( - controller: Controller, - changeHandler: ControllerChangeHandler, - changeType: ControllerChangeType - ) { - super.onChangeStart(controller, changeHandler, changeType) - if (changeType.isEnter) { - elevateFunc(elevate) - if (fakeToolbarView?.parent != null) { - val parent = fakeToolbarView?.parent as? ViewGroup ?: return - parent.removeView(fakeToolbarView) - fakeToolbarView = null - } - lastY = 0f - activity!!.toolbar.tag = randomTag - activity!!.toolbar.setOnClickListener { - if ((this@scrollViewWith as? BottomSheetController)?.sheetIsExpanded() != true) { - recycler.scrollToPosition(0) - } else { - (this@scrollViewWith as? BottomSheetController)?.toggleSheet() - } - } - } else { - if (!customPadding && lastY == 0f && router.backstack.lastOrNull() - ?.controller() is MangaDetailsController - ) { - val parent = recycler.parent as? ViewGroup ?: return - val v = View(activity) - fakeToolbarView = v - parent.addView(v, parent.indexOfChild(recycler) + 1) - val params = fakeToolbarView?.layoutParams - params?.height = recycler.paddingTop - params?.width = MATCH_PARENT - v.setBackgroundColor(v.context.getResourceColor(R.attr.colorSecondary)) - v.layoutParams = params - onLeavingController?.invoke() - } - elevationAnim?.cancel() - if (activity!!.toolbar.tag == randomTag) activity!!.toolbar.setOnClickListener(null) - } - } - }) - elevateFunc(recycler.canScrollVertically(-1)) - recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { - override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - super.onScrolled(recyclerView, dx, dy) - if (router?.backstack?.lastOrNull() - ?.controller() == this@scrollViewWith && statusBarHeight > -1 && - activity != null && activity!!.appbar.height > 0 && - recycler.translationY == 0f + addLifecycleListener( + object : Controller.LifecycleListener() { + override fun onChangeStart( + controller: Controller, + changeHandler: ControllerChangeHandler, + changeType: ControllerChangeType ) { - if (!recycler.canScrollVertically(-1)) { - val shortAnimationDuration = resources?.getInteger( - android.R.integer.config_shortAnimTime - ) ?: 0 - activity!!.appbar.animate().y(0f).setDuration(shortAnimationDuration.toLong()) - .start() + super.onChangeStart(controller, changeHandler, changeType) + if (changeType.isEnter) { + elevateFunc(elevate) + if (fakeToolbarView?.parent != null) { + val parent = fakeToolbarView?.parent as? ViewGroup ?: return + parent.removeView(fakeToolbarView) + fakeToolbarView = null + } lastY = 0f - if (elevate) elevateFunc(false) + activity!!.toolbar.tag = randomTag + activity!!.toolbar.setOnClickListener { + if ((this@scrollViewWith as? BottomSheetController)?.sheetIsExpanded() != true) { + recycler.scrollToPosition(0) + } else { + (this@scrollViewWith as? BottomSheetController)?.toggleSheet() + } + } } else { - activity!!.appbar.y -= dy - activity!!.appbar.y = MathUtils.clamp( - activity!!.appbar.y, -activity!!.appbar.height.toFloat(), 0f - ) - if (((activity!!.appbar.y <= -activity!!.appbar.height.toFloat() || - dy == 0 && activity!!.appbar.y == 0f) || dy == 0) && !elevate) - elevateFunc(true) - lastY = activity!!.appbar.y + if (!customPadding && lastY == 0f && router.backstack.lastOrNull() + ?.controller() is MangaDetailsController + ) { + val parent = recycler.parent as? ViewGroup ?: return + val v = View(activity) + fakeToolbarView = v + parent.addView(v, parent.indexOfChild(recycler) + 1) + val params = fakeToolbarView?.layoutParams + params?.height = recycler.paddingTop + params?.width = MATCH_PARENT + v.setBackgroundColor(v.context.getResourceColor(R.attr.colorSecondary)) + v.layoutParams = params + onLeavingController?.invoke() + } + elevationAnim?.cancel() + if (activity!!.toolbar.tag == randomTag) activity!!.toolbar.setOnClickListener(null) } } } - - override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { - super.onScrollStateChanged(recyclerView, newState) - if (newState == RecyclerView.SCROLL_STATE_IDLE) { + ) + elevateFunc(recycler.canScrollVertically(-1)) + recycler.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + super.onScrolled(recyclerView, dx, dy) if (router?.backstack?.lastOrNull() - ?.controller() == this@scrollViewWith && statusBarHeight > -1 && + ?.controller() == this@scrollViewWith && statusBarHeight > -1 && activity != null && activity!!.appbar.height > 0 && recycler.translationY == 0f ) { - val halfWay = abs((-activity!!.appbar.height.toFloat()) / 2) - val shortAnimationDuration = resources?.getInteger( - android.R.integer.config_shortAnimTime - ) ?: 0 - val closerToTop = abs(activity!!.appbar.y) - halfWay > 0 - val atTop = !recycler.canScrollVertically(-1) - lastY = if (closerToTop && !atTop) (-activity!!.appbar.height.toFloat()) else 0f - activity!!.appbar.animate().y(lastY).setDuration(shortAnimationDuration.toLong()).start() - if (recycler.canScrollVertically(-1) && !elevate) elevateFunc(true) - else if (!recycler.canScrollVertically(-1) && elevate) elevateFunc(false) + if (!recycler.canScrollVertically(-1)) { + val shortAnimationDuration = resources?.getInteger( + android.R.integer.config_shortAnimTime + ) ?: 0 + activity!!.appbar.animate().y(0f).setDuration(shortAnimationDuration.toLong()) + .start() + lastY = 0f + if (elevate) elevateFunc(false) + } else { + activity!!.appbar.y -= dy + activity!!.appbar.y = MathUtils.clamp( + activity!!.appbar.y, + -activity!!.appbar.height.toFloat(), + 0f + ) + if (( + ( + activity!!.appbar.y <= -activity!!.appbar.height.toFloat() || + dy == 0 && activity!!.appbar.y == 0f + ) || dy == 0 + ) && !elevate + ) + elevateFunc(true) + lastY = activity!!.appbar.y + } + } + } + + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + super.onScrollStateChanged(recyclerView, newState) + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + if (router?.backstack?.lastOrNull() + ?.controller() == this@scrollViewWith && statusBarHeight > -1 && + activity != null && activity!!.appbar.height > 0 && + recycler.translationY == 0f + ) { + val halfWay = abs((-activity!!.appbar.height.toFloat()) / 2) + val shortAnimationDuration = resources?.getInteger( + android.R.integer.config_shortAnimTime + ) ?: 0 + val closerToTop = abs(activity!!.appbar.y) - halfWay > 0 + val atTop = !recycler.canScrollVertically(-1) + lastY = if (closerToTop && !atTop) (-activity!!.appbar.height.toFloat()) else 0f + activity!!.appbar.animate().y(lastY).setDuration(shortAnimationDuration.toLong()).start() + if (recycler.canScrollVertically(-1) && !elevate) elevateFunc(true) + else if (!recycler.canScrollVertically(-1) && elevate) elevateFunc(false) + } } } } - }) + ) return elevateFunc } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewExtensions.kt index 6bb814c03d..9b6481b0ed 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewExtensions.kt @@ -171,44 +171,50 @@ fun View.applyWindowInsetsForController() { } fun View.checkHeightThen(f: () -> Unit) { - viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { - override fun onGlobalLayout() { - if (height > 0) { - viewTreeObserver.removeOnGlobalLayoutListener(this) - f() + viewTreeObserver.addOnGlobalLayoutListener( + object : ViewTreeObserver.OnGlobalLayoutListener { + override fun onGlobalLayout() { + if (height > 0) { + viewTreeObserver.removeOnGlobalLayoutListener(this) + f() + } } } - }) + ) } fun View.applyWindowInsetsForRootController(bottomNav: View) { - viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { - override fun onGlobalLayout() { - if (bottomNav.height > 0) { - viewTreeObserver.removeOnGlobalLayoutListener(this) - setOnApplyWindowInsetsListener { view, insets -> - view.updateLayoutParams { - bottomMargin = bottomNav.height + viewTreeObserver.addOnGlobalLayoutListener( + object : ViewTreeObserver.OnGlobalLayoutListener { + override fun onGlobalLayout() { + if (bottomNav.height > 0) { + viewTreeObserver.removeOnGlobalLayoutListener(this) + setOnApplyWindowInsetsListener { view, insets -> + view.updateLayoutParams { + bottomMargin = bottomNav.height + } + insets } - insets + requestApplyInsetsWhenAttached() } - requestApplyInsetsWhenAttached() } } - }) + ) } fun View.requestApplyInsetsWhenAttached() { if (isAttachedToWindow) { requestApplyInsets() } else { - addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { - override fun onViewAttachedToWindow(v: View) { - v.requestApplyInsets() - } + addOnAttachStateChangeListener( + object : View.OnAttachStateChangeListener { + override fun onViewAttachedToWindow(v: View) { + v.requestApplyInsets() + } - override fun onViewDetachedFromWindow(v: View) = Unit - }) + override fun onViewDetachedFromWindow(v: View) = Unit + } + ) } } @@ -271,8 +277,10 @@ fun BottomSheetDialog.setEdgeToEdge( .SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION val insets = activity.window.decorView.rootWindowInsets - (contentView.parent as View).translationX = (insets.systemWindowInsetLeft - insets - .systemWindowInsetRight).toFloat() / 2f + (contentView.parent as View).translationX = ( + insets.systemWindowInsetLeft - insets + .systemWindowInsetRight + ).toFloat() / 2f if (setTopMargin > 0) (contentView.parent as View).updateLayoutParams { height = activity.window.decorView.height - insets.systemWindowInsetTop - setTopMargin } @@ -299,7 +307,8 @@ fun MaterialButton.resetStrokeColor() { ColorUtils.setAlphaComponent( context.getResourceColor( R.attr.colorOnSurface - ), 31 + ), + 31 ) ) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt index ad5921efc3..bc46cebf0b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt @@ -8,7 +8,7 @@ import kotlin.math.max import kotlin.math.roundToInt class AutofitRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - androidx.recyclerview.widget.RecyclerView(context, attrs) { + androidx.recyclerview.widget.RecyclerView(context, attrs) { val manager = GridLayoutManager(context, 1) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt index 2f71a21077..40f7b8ba8a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt @@ -13,11 +13,11 @@ import java.io.File class CustomLayoutPickerActivity : FilePickerActivity() { override fun getFragment(startPath: String?, mode: Int, allowMultiple: Boolean, allowCreateDir: Boolean): - AbstractFilePickerFragment { - val fragment = CustomLayoutFilePickerFragment() - fragment.setArgs(startPath, mode, allowMultiple, allowCreateDir) - return fragment - } + AbstractFilePickerFragment { + val fragment = CustomLayoutFilePickerFragment() + fragment.setArgs(startPath, mode, allowMultiple, allowCreateDir) + return fragment + } } class CustomLayoutFilePickerFragment : FilePickerFragment() { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt index adbe88ac75..dd99d9bc5b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt @@ -9,7 +9,7 @@ import eu.kanade.tachiyomi.util.view.inflate import kotlinx.android.synthetic.main.common_dialog_with_checkbox.view.* class DialogCheckboxView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - LinearLayout(context, attrs) { + LinearLayout(context, attrs) { init { addView(inflate(R.layout.common_dialog_with_checkbox)) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt index 7527eaf080..5bd0aa2003 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt @@ -14,7 +14,7 @@ import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.common_view_empty.view.* class EmptyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - RelativeLayout(context, attrs) { + RelativeLayout(context, attrs) { init { inflate(context, R.layout.common_view_empty, this) @@ -46,11 +46,13 @@ class EmptyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? actions_container.removeAllViews() if (!actions.isNullOrEmpty()) { actions.forEach { - val button = (inflate( - context, - R.layout.material_text_button, - null - ) as MaterialButton).apply { + val button = ( + inflate( + context, + R.layout.material_text_button, + null + ) as MaterialButton + ).apply { setText(it.resId) setOnClickListener(it.listener) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt index bdc7d79d14..a041db442b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt @@ -6,7 +6,7 @@ import android.widget.NumberPicker import eu.kanade.tachiyomi.R class MinMaxNumberPicker @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - NumberPicker(context, attrs) { + NumberPicker(context, attrs) { init { if (attrs != null) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt index 9ab0cc9c11..a0c8242b56 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt @@ -8,7 +8,7 @@ import eu.kanade.tachiyomi.R import kotlin.math.abs class NegativeSeekBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - SeekBar(context, attrs) { + SeekBar(context, attrs) { private var minValue: Int = 0 private var maxValue: Int = 0 @@ -16,8 +16,11 @@ class NegativeSeekBar @JvmOverloads constructor(context: Context, attrs: Attribu init { val styledAttributes = context.obtainStyledAttributes( - attrs, - R.styleable.NegativeSeekBar, 0, 0) + attrs, + R.styleable.NegativeSeekBar, + 0, + 0 + ) try { setMinSeek(styledAttributes.getInt(R.styleable.NegativeSeekBar_min_seek, 0)) @@ -26,19 +29,21 @@ class NegativeSeekBar @JvmOverloads constructor(context: Context, attrs: Attribu styledAttributes.recycle() } - super.setOnSeekBarChangeListener(object : OnSeekBarChangeListener { - override fun onProgressChanged(seekBar: SeekBar?, value: Int, fromUser: Boolean) { - listener?.onProgressChanged(seekBar, minValue + value, fromUser) - } + super.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, value: Int, fromUser: Boolean) { + listener?.onProgressChanged(seekBar, minValue + value, fromUser) + } - override fun onStartTrackingTouch(p0: SeekBar?) { - listener?.onStartTrackingTouch(p0) - } + override fun onStartTrackingTouch(p0: SeekBar?) { + listener?.onStartTrackingTouch(p0) + } - override fun onStopTrackingTouch(p0: SeekBar?) { - listener?.onStopTrackingTouch(p0) + override fun onStopTrackingTouch(p0: SeekBar?) { + listener?.onStopTrackingTouch(p0) + } } - }) + ) } override fun setProgress(progress: Int) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt index 9a79b0c68c..d9c3795776 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt @@ -8,7 +8,7 @@ import android.view.View import android.view.ViewAnimationUtils class RevealAnimationView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - View(context, attrs) { + View(context, attrs) { /** * Hides the animation view with a animation @@ -23,18 +23,25 @@ class RevealAnimationView @JvmOverloads constructor(context: Context, attrs: Att // Create the animation (the final radius is zero). val anim = ViewAnimationUtils.createCircularReveal( - this, centerX, centerY, initialRadius.toFloat(), 0f) + this, + centerX, + centerY, + initialRadius.toFloat(), + 0f + ) // Set duration of animation. anim.duration = 500 // make the view invisible when the animation is done - anim.addListener(object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator) { - super.onAnimationEnd(animation) - this@RevealAnimationView.visibility = View.INVISIBLE + anim.addListener( + object : AnimatorListenerAdapter() { + override fun onAnimationEnd(animation: Animator) { + super.onAnimationEnd(animation) + this@RevealAnimationView.visibility = View.INVISIBLE + } } - }) + ) anim.start() } @@ -55,7 +62,12 @@ class RevealAnimationView @JvmOverloads constructor(context: Context, attrs: Att // Create animation val anim = ViewAnimationUtils.createCircularReveal( - this, centerX, centerY, 0f, height.toFloat()) + this, + centerX, + centerY, + 0f, + height.toFloat() + ) // Set duration of animation anim.duration = 350 diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt index 91c2d487f1..64c07b5688 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt @@ -41,21 +41,34 @@ open class SimpleNavigationView @JvmOverloads constructor( init { // Custom attributes - val a = TintTypedArray.obtainStyledAttributes(context, attrs, - R.styleable.NavigationView, defStyleAttr, - R.style.Widget_Design_NavigationView) + val a = TintTypedArray.obtainStyledAttributes( + context, + attrs, + R.styleable.NavigationView, + defStyleAttr, + R.style.Widget_Design_NavigationView + ) ViewCompat.setBackground( - this, a.getDrawable(R.styleable.NavigationView_android_background)) + this, + a.getDrawable(R.styleable.NavigationView_android_background) + ) if (a.hasValue(R.styleable.NavigationView_elevation)) { - ViewCompat.setElevation(this, a.getDimensionPixelSize( - R.styleable.NavigationView_elevation, 0).toFloat()) + ViewCompat.setElevation( + this, + a.getDimensionPixelSize( + R.styleable.NavigationView_elevation, + 0 + ).toFloat() + ) } @Suppress("DEPRECATION") - ViewCompat.setFitsSystemWindows(this, - a.getBoolean(R.styleable.NavigationView_android_fitsSystemWindows, false)) + ViewCompat.setFitsSystemWindows( + this, + a.getBoolean(R.styleable.NavigationView_android_fitsSystemWindows, false) + ) maxWidth = a.getDimensionPixelSize(R.styleable.NavigationView_android_maxWidth, 0) @@ -72,7 +85,9 @@ open class SimpleNavigationView @JvmOverloads constructor( override fun onMeasure(widthSpec: Int, heightSpec: Int) { val width = when (MeasureSpec.getMode(widthSpec)) { MeasureSpec.AT_MOST -> MeasureSpec.makeMeasureSpec( - min(MeasureSpec.getSize(widthSpec), maxWidth), MeasureSpec.EXACTLY) + min(MeasureSpec.getSize(widthSpec), maxWidth), + MeasureSpec.EXACTLY + ) MeasureSpec.UNSPECIFIED -> MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY) else -> widthSpec } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListMatPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListMatPreference.kt index 0a92734dae..f33b372aa3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListMatPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListMatPreference.kt @@ -11,8 +11,8 @@ class IntListMatPreference @JvmOverloads constructor( activity: Activity?, context: Context, attrs: -AttributeSet? = - null + AttributeSet? = + null ) : MatPreference(activity, context, attrs) { var entryValues: List = emptyList() @@ -40,10 +40,12 @@ AttributeSet? = override fun dialog(): MaterialDialog { return super.dialog().apply { val default = entryValues.indexOf(prefs.getInt(key, defValue).getOrDefault()) - listItemsSingleChoice(items = entries, + listItemsSingleChoice( + items = entries, waitForPositiveButton = false, - initialSelection = default) { - _, pos, _ -> + initialSelection = default + ) { + _, pos, _ -> val value = entryValues[pos] if (key != null) prefs.getInt(key, defValue).set(value) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListPreference.kt index 37873398f9..63b52eb2a9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/IntListPreference.kt @@ -5,7 +5,7 @@ import android.util.AttributeSet import androidx.preference.ListPreference class IntListPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - ListPreference(context, attrs) { + ListPreference(context, attrs) { override fun persistString(value: String?): Boolean { return value != null && persistInt(value.toInt()) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ListMatPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ListMatPreference.kt index 352484eada..dbe7c70df9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ListMatPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ListMatPreference.kt @@ -13,7 +13,7 @@ open class ListMatPreference @JvmOverloads constructor( activity: Activity?, context: Context, attrs: AttributeSet? = - null + null ) : MatPreference(activity, context, attrs) { @@ -45,13 +45,17 @@ open class ListMatPreference @JvmOverloads constructor( @SuppressLint("CheckResult") open fun MaterialDialog.setItems() { - val default = entryValues.indexOf(if (sharedPref != null) { - val settings = context.getSharedPreferences(sharedPref, Context.MODE_PRIVATE) - settings.getString(key, "") - } else prefs.getStringPref(key, defValue).getOrDefault()) - listItemsSingleChoice(items = entries, + val default = entryValues.indexOf( + if (sharedPref != null) { + val settings = context.getSharedPreferences(sharedPref, Context.MODE_PRIVATE) + settings.getString(key, "") + } else prefs.getStringPref(key, defValue).getOrDefault() + ) + listItemsSingleChoice( + items = entries, waitForPositiveButton = false, - initialSelection = default) { _, pos, _ -> + initialSelection = default + ) { _, pos, _ -> val value = entryValues[pos] if (sharedPref != null) { val oldDef = if (default > -1) entries[default] else "" @@ -62,7 +66,8 @@ open class ListMatPreference @JvmOverloads constructor( otherPref?.callChangeListener(value) if (oldDef == otherPref?.summary || otherPref?.summary.isNullOrEmpty()) otherPref?.summary = entries[pos] - else otherPref?.summary = otherPref?.summary?.toString()?.replace(oldDef, + else otherPref?.summary = otherPref?.summary?.toString()?.replace( + oldDef, entries[pos] ) ?: entries[pos] } else { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginPreference.kt index fb2affc2e8..c6afc9ef1e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginPreference.kt @@ -10,7 +10,7 @@ import eu.kanade.tachiyomi.R import kotlinx.android.synthetic.main.pref_widget_imageview.view.* class LoginPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - Preference(context, attrs) { + Preference(context, attrs) { init { widgetLayoutResource = R.layout.pref_widget_imageview diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MatPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MatPreference.kt index e503ee6b6d..caecdd5e7e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MatPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MatPreference.kt @@ -14,8 +14,8 @@ open class MatPreference @JvmOverloads constructor( val activity: Activity?, context: Context, attrs: - AttributeSet? = - null + AttributeSet? = + null ) : Preference(context, attrs) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MultiListMatPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MultiListMatPreference.kt index 1d35f5bf0b..16958610eb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MultiListMatPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/MultiListMatPreference.kt @@ -15,7 +15,7 @@ class MultiListMatPreference @JvmOverloads constructor( activity: Activity?, context: Context, attrs: AttributeSet? = - null + null ) : ListMatPreference(activity, context, attrs) { @@ -39,7 +39,8 @@ class MultiListMatPreference @JvmOverloads constructor( val set = prefs.getStringSet(key, emptySet()).getOrDefault() var default = set.mapNotNull { if (entryValues.indexOf(it) == -1) null - else entryValues.indexOf(it) + if (allSelectionRes != null) 1 else 0 } + else entryValues.indexOf(it) + if (allSelectionRes != null) 1 else 0 + } .toIntArray() if (allSelectionRes != null && default.isEmpty()) default = intArrayOf(0) val items = if (allSelectionRes != null) @@ -49,17 +50,20 @@ class MultiListMatPreference @JvmOverloads constructor( for (i in items.indices) if (!(allSelectionRes != null && i == 0) && isItemChecked(i)) pos.add(i) var value = pos.map { - entryValues[it - if (allSelectionRes != null) 1 else 0] }?.toSet() ?: emptySet() + entryValues[it - if (allSelectionRes != null) 1 else 0] + }?.toSet() ?: emptySet() if (allSelectionRes != null && isItemChecked(0)) value = emptySet() prefs.getStringSet(key, emptySet()).set(value) callChangeListener(value) this@MultiListMatPreference.summary = this@MultiListMatPreference.summary } - listItemsMultiChoice(items = items, + listItemsMultiChoice( + items = items, allowEmptySelection = true, disabledIndices = if (allSelectionRes != null) intArrayOf(0) else null, waitForPositiveButton = false, - initialSelection = default) { _, pos, _ -> + initialSelection = default + ) { _, pos, _ -> if (allSelectionRes != null) { if (pos.isEmpty()) checkItem(0) else uncheckItem(0) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchPreferenceCategory.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchPreferenceCategory.kt index a4ed0194a5..9843d67216 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchPreferenceCategory.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchPreferenceCategory.kt @@ -19,11 +19,12 @@ class SwitchPreferenceCategory @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : -PreferenceCategory( + PreferenceCategory( context, attrs, - R.attr.switchPreferenceCompatStyle), -CompoundButton.OnCheckedChangeListener { + R.attr.switchPreferenceCompatStyle + ), + CompoundButton.OnCheckedChangeListener { private var mChecked = false @@ -117,9 +118,11 @@ CompoundButton.OnCheckedChangeListener { } override fun onSetInitialValue(restoreValue: Boolean, defaultValue: Any?) { - setChecked(if (restoreValue) - getPersistedBoolean(mChecked) - else - defaultValue as Boolean) + setChecked( + if (restoreValue) + getPersistedBoolean(mChecked) + else + defaultValue as Boolean + ) } } diff --git a/app/src/test/java/eu/kanade/tachiyomi/data/library/LibraryUpdateServiceTest.kt b/app/src/test/java/eu/kanade/tachiyomi/data/library/LibraryUpdateServiceTest.kt index 97c7f6ae67..2acdedcc9a 100644 --- a/app/src/test/java/eu/kanade/tachiyomi/data/library/LibraryUpdateServiceTest.kt +++ b/app/src/test/java/eu/kanade/tachiyomi/data/library/LibraryUpdateServiceTest.kt @@ -61,11 +61,11 @@ class LibraryUpdateServiceTest { fun testLifecycle() { // Smoke test Robolectric.buildService(LibraryUpdateService::class.java) - .attach() - .create() - .startCommand(0, 0) - .destroy() - .get() + .attach() + .create() + .startCommand(0, 0) + .destroy() + .get() } @Test diff --git a/buildSrc/src/main/kotlin/Dependencies.kt b/buildSrc/src/main/kotlin/Dependencies.kt index 370bc68544..51c98035dd 100644 --- a/buildSrc/src/main/kotlin/Dependencies.kt +++ b/buildSrc/src/main/kotlin/Dependencies.kt @@ -2,7 +2,7 @@ object Versions { const val ACRA = "4.9.2" const val CHUCKER = "3.2.0" const val COIL = "0.11.0" - const val COROUTINES = "1.3.5" + const val COROUTINES = "1.3.9" const val FASTADAPTER = "5.0.0" const val HYPERION = "0.9.27" const val NUCLEUS = "3.0.0" @@ -10,7 +10,7 @@ object Versions { const val OSS_LICENSE = "17.0.0" const val RETROFIT = "2.7.2" const val ROBO_ELECTRIC = "3.1.4" - const val RX_BINDING ="1.0.1" + const val RX_BINDING = "1.0.1" const val TIMBER = "4.7.1" const val WORKMANAGER = "2.3.3" } @@ -25,12 +25,12 @@ object AndroidVersions { } object BuildPluginsVersion { - const val AGP = "com.android.tools.build:gradle:4.0.0" - const val KOTLIN = "1.3.72" + const val AGP = "com.android.tools.build:gradle:4.0.1" + const val KOTLIN = "1.4.10" const val ANDROID_EXTENSIONS = "org.jetbrains.kotlin:kotlin-android-extensions:$KOTLIN" const val KOTLIN_GRADLE = "org.jetbrains.kotlin:kotlin-gradle-plugin:$KOTLIN" - const val KOTLINTER = "org.jmailen.gradle:kotlinter-gradle:2.3.2" + const val KOTLINTER = "org.jmailen.gradle:kotlinter-gradle:3.0.2" const val GOOGLE_SERVICES = "com.google.gms:google-services:4.3.3" const val OSS_LICENSE = "com.google.android.gms:oss-licenses-plugin:0.10.2" const val VERSIONS_PLUGIN = "0.28.0" -} \ No newline at end of file +}