From da786bbc40f7bfe12d72548ee47d1bd1cfa9701f Mon Sep 17 00:00:00 2001 From: Jay Date: Sun, 15 Mar 2020 22:50:20 -0700 Subject: [PATCH] Turned on kt lint --- app/build.gradle.kts | 66 ++-- app/src/main/java/eu/kanade/tachiyomi/App.kt | 3 +- .../java/eu/kanade/tachiyomi/AppModule.kt | 8 +- .../java/eu/kanade/tachiyomi/Migrations.kt | 3 +- .../tachiyomi/data/backup/BackupConst.kt | 5 +- .../data/backup/BackupCreateService.kt | 4 +- .../tachiyomi/data/backup/BackupCreatorJob.kt | 2 +- .../tachiyomi/data/backup/BackupManager.kt | 33 +- .../data/backup/BackupRestoreService.kt | 25 +- .../tachiyomi/data/backup/models/Backup.kt | 5 +- .../tachiyomi/data/backup/models/DHistory.kt | 2 +- .../backup/serializer/CategoryTypeAdapter.kt | 2 +- .../backup/serializer/HistoryTypeAdapter.kt | 2 +- .../backup/serializer/MangaTypeAdapter.kt | 2 +- .../backup/serializer/TrackTypeAdapter.kt | 1 - .../tachiyomi/data/cache/ChapterCache.kt | 7 +- .../kanade/tachiyomi/data/cache/CoverCache.kt | 6 +- .../tachiyomi/data/database/DatabaseHelper.kt | 5 +- .../tachiyomi/data/database/DbExtensions.kt | 1 - .../tachiyomi/data/database/DbOpenCallback.kt | 11 +- .../tachiyomi/data/database/DbProvider.kt | 3 +- .../database/mappers/CategoryTypeMapping.kt | 1 - .../database/mappers/ChapterTypeMapping.kt | 1 - .../mappers/SearchMetadataTypeMapping.kt | 3 +- .../data/database/mappers/TrackTypeMapping.kt | 1 - .../data/database/models/Category.kt | 19 +- .../data/database/models/CategoryImpl.kt | 1 - .../data/database/models/ChapterImpl.kt | 3 +- .../tachiyomi/data/database/models/History.kt | 2 +- .../data/database/models/LibraryManga.kt | 3 +- .../tachiyomi/data/database/models/Manga.kt | 7 +- .../data/database/models/MangaCategory.kt | 1 - .../database/models/MangaChapterHistory.kt | 2 +- .../data/database/models/MangaImpl.kt | 10 +- .../data/database/models/SearchMetadata.kt | 2 +- .../tachiyomi/data/database/models/Track.kt | 1 - .../data/database/models/TrackImpl.kt | 1 - .../data/database/queries/CategoryQueries.kt | 3 +- .../data/database/queries/ChapterQueries.kt | 5 +- .../data/database/queries/HistoryQueries.kt | 2 +- .../database/queries/MangaCategoryQueries.kt | 3 +- .../data/database/queries/MangaQueries.kt | 2 +- .../data/database/queries/RawQueries.kt | 8 +- .../database/queries/SearchMetadataQueries.kt | 3 +- .../data/database/queries/TrackQueries.kt | 3 +- .../resolvers/ChapterBackupPutResolver.kt | 2 - .../resolvers/ChapterProgressPutResolver.kt | 2 - .../ChapterSourceOrderPutResolver.kt | 3 +- .../resolvers/HistoryLastReadPutResolver.kt | 1 - .../resolvers/LibraryMangaGetResolver.kt | 1 - .../resolvers/MangaChapterGetResolver.kt | 1 - .../resolvers/MangaFavoritePutResolver.kt | 2 - .../resolvers/MangaFlagsPutResolver.kt | 2 - .../resolvers/MangaHideTitlePutResolver.kt | 2 - .../resolvers/MangaInfoPutResolver.kt | 6 +- .../resolvers/MangaLastUpdatedPutResolver.kt | 2 - .../resolvers/MangaTitlePutResolver.kt | 1 - .../resolvers/MangaViewerPutResolver.kt | 1 - .../data/database/tables/CategoryTable.kt | 1 - .../data/database/tables/ChapterTable.kt | 1 - .../database/tables/MangaCategoryTable.kt | 1 - .../database/tables/SearchMetadataTable.kt | 1 - .../tachiyomi/data/download/DownloadCache.kt | 39 +- .../data/download/DownloadManager.kt | 11 +- .../data/download/DownloadNotifier.kt | 9 +- .../data/download/DownloadPendingDeleter.kt | 21 +- .../data/download/DownloadProvider.kt | 20 +- .../data/download/DownloadService.kt | 1 - .../tachiyomi/data/download/DownloadStore.kt | 5 +- .../tachiyomi/data/download/Downloader.kt | 29 +- .../tachiyomi/data/download/model/Download.kt | 2 +- .../data/download/model/DownloadQueue.kt | 16 +- .../tachiyomi/data/glide/FileFetcher.kt | 8 +- .../data/glide/LibraryMangaUrlFetcher.kt | 14 +- .../tachiyomi/data/glide/MangaModelLoader.kt | 21 +- .../tachiyomi/data/glide/MangaSignature.kt | 2 +- .../data/glide/PassthroughModelLoader.kt | 16 +- .../tachiyomi/data/glide/TachiGlideModule.kt | 6 +- .../data/library/LibraryUpdateJob.kt | 2 +- .../data/library/LibraryUpdateRanker.kt | 3 +- .../data/library/LibraryUpdateService.kt | 12 +- .../data/notification/NotificationReceiver.kt | 39 +- .../data/notification/Notifications.kt | 63 +-- .../data/preference/PreferenceKeys.kt | 2 - .../data/preference/PreferencesHelper.kt | 2 +- .../tachiyomi/data/track/TrackManager.kt | 3 +- .../tachiyomi/data/track/TrackService.kt | 2 +- .../tachiyomi/data/track/anilist/Anilist.kt | 27 +- .../data/track/anilist/AnilistApi.kt | 4 +- .../data/track/anilist/AnilistInterceptor.kt | 6 +- .../data/track/anilist/AnilistModels.kt | 22 +- .../tachiyomi/data/track/bangumi/Bangumi.kt | 6 +- .../data/track/bangumi/BangumiApi.kt | 98 ++--- .../data/track/bangumi/BangumiInterceptor.kt | 2 +- .../data/track/bangumi/Collection.kt | 58 ++- .../tachiyomi/data/track/kitsu/Kitsu.kt | 2 +- .../data/track/kitsu/KitsuInterceptor.kt | 1 - .../tachiyomi/data/track/kitsu/KitsuModels.kt | 12 +- .../tachiyomi/data/track/kitsu/OAuth.kt | 13 +- .../tachiyomi/data/track/model/TrackSearch.kt | 4 +- .../data/track/myanimelist/MyAnimeList.kt | 5 +- .../data/track/myanimelist/MyAnimeListApi.kt | 103 ++--- .../myanimelist/MyAnimeListInterceptor.kt | 1 - .../data/track/shikimori/Shikimori.kt | 1 - .../data/track/shikimori/ShikimoriApi.kt | 67 +--- .../data/track/shikimori/ShikimoriModels.kt | 4 +- .../kanade/tachiyomi/data/updater/Release.kt | 1 - .../tachiyomi/data/updater/UpdateChecker.kt | 3 +- .../tachiyomi/data/updater/UpdateResult.kt | 5 +- .../tachiyomi/data/updater/UpdaterJob.kt | 6 +- .../tachiyomi/data/updater/UpdaterService.kt | 4 +- .../data/updater/github/GithubRelease.kt | 9 +- .../data/updater/github/GithubService.kt | 2 - .../updater/github/GithubUpdateChecker.kt | 1 - .../data/updater/github/GithubUpdateResult.kt | 3 +- .../tachiyomi/extension/ExtensionManager.kt | 10 +- .../tachiyomi/extension/ExtensionUpdateJob.kt | 5 +- .../extension/api/ExtensionGithubApi.kt | 11 +- .../tachiyomi/extension/model/Extension.kt | 49 +-- .../util/ExtensionInstallReceiver.kt | 5 +- .../extension/util/ExtensionInstaller.kt | 5 +- .../extension/util/ExtensionLoader.kt | 1 - .../network/CloudflareInterceptor.kt | 2 +- .../kanade/tachiyomi/network/NetworkHelper.kt | 3 +- .../tachiyomi/network/OkHttpExtensions.kt | 18 +- .../tachiyomi/network/ProgressListener.kt | 2 +- .../tachiyomi/network/ProgressResponseBody.kt | 8 +- .../eu/kanade/tachiyomi/network/Requests.kt | 24 +- .../smartsearch/SmartSearchEngine.kt | 23 +- .../tachiyomi/source/CatalogueSource.kt | 2 +- .../eu/kanade/tachiyomi/source/LocalSource.kt | 144 +++---- .../java/eu/kanade/tachiyomi/source/Source.kt | 3 +- .../kanade/tachiyomi/source/model/Filter.kt | 9 +- .../tachiyomi/source/model/FilterList.kt | 3 +- .../tachiyomi/source/model/MangasPage.kt | 2 +- .../eu/kanade/tachiyomi/source/model/Page.kt | 9 +- .../kanade/tachiyomi/source/model/SChapter.kt | 3 +- .../tachiyomi/source/model/SChapterImpl.kt | 5 +- .../kanade/tachiyomi/source/model/SManga.kt | 13 +- .../tachiyomi/source/online/HttpSource.kt | 43 +- .../tachiyomi/source/online/LoginSource.kt | 3 +- .../source/online/ParsedHttpSource.kt | 28 +- .../tachiyomi/ui/base/CenteredToolbar.kt | 10 +- .../ui/base/activity/BaseRxActivity.kt | 1 - .../ui/base/controller/BaseController.kt | 1 - .../ui/base/controller/DialogController.kt | 2 +- .../NoToolbarElevationController.kt | 3 - .../ui/base/controller/RxController.kt | 32 +- .../controller/SecondaryDrawerController.kt | 2 +- .../ui/base/holder/BaseFlexibleViewHolder.kt | 12 +- .../ui/base/holder/BaseViewHolder.kt | 2 +- .../tachiyomi/ui/base/holder/SlicedHolder.kt | 10 +- .../ui/base/presenter/BasePresenter.kt | 17 +- .../presenter/NucleusConductorDelegate.kt | 1 - .../NucleusConductorLifecycleListener.kt | 1 - .../ui/catalogue/CatalogueAdapter.kt | 1 - .../ui/catalogue/CatalogueController.kt | 15 +- .../ui/catalogue/CataloguePresenter.kt | 10 +- .../tachiyomi/ui/catalogue/LangHolder.kt | 4 +- .../kanade/tachiyomi/ui/catalogue/LangItem.kt | 1 - .../catalogue/SourceDividerItemDecoration.kt | 11 +- .../tachiyomi/ui/catalogue/SourceItem.kt | 1 - .../browse/BrowseCatalogueController.kt | 11 +- .../browse/BrowseCataloguePresenter.kt | 30 +- .../catalogue/browse/CatalogueGridHolder.kt | 3 +- .../ui/catalogue/browse/CatalogueHolder.kt | 5 +- .../ui/catalogue/browse/CatalogueItem.kt | 11 +- .../catalogue/browse/CatalogueListHolder.kt | 9 +- .../browse/CatalogueNavigationView.kt | 7 +- .../ui/catalogue/browse/CataloguePager.kt | 3 +- .../ui/catalogue/browse/NoResultsException.kt | 2 +- .../tachiyomi/ui/catalogue/browse/Pager.kt | 1 - .../ui/catalogue/browse/ProgressItem.kt | 2 - .../ui/catalogue/filter/GroupItem.kt | 3 - .../ui/catalogue/filter/SeparatorItem.kt | 11 +- .../ui/catalogue/filter/SortGroup.kt | 1 - .../tachiyomi/ui/catalogue/filter/SortItem.kt | 5 +- .../ui/catalogue/filter/TriStateItem.kt | 3 +- .../global_search/CatalogueSearchAdapter.kt | 2 +- .../CatalogueSearchCardAdapter.kt | 3 +- .../CatalogueSearchCardHolder.kt | 7 +- .../global_search/CatalogueSearchCardItem.kt | 9 +- .../CatalogueSearchController.kt | 13 +- .../global_search/CatalogueSearchHolder.kt | 4 +- .../global_search/CatalogueSearchItem.kt | 13 +- .../global_search/CatalogueSearchPresenter.kt | 141 +++---- .../latest/LatestUpdatesController.kt | 4 +- .../ui/catalogue/latest/LatestUpdatesPager.kt | 3 +- .../latest/LatestUpdatesPresenter.kt | 3 +- .../tachiyomi/ui/category/CategoryAdapter.kt | 1 - .../ui/category/CategoryController.kt | 1 - .../ui/category/CategoryCreateDialog.kt | 1 - .../tachiyomi/ui/category/CategoryHolder.kt | 20 +- .../tachiyomi/ui/category/CategoryItem.kt | 1 - .../ui/category/CategoryPresenter.kt | 9 +- .../ui/category/CategoryRenameDialog.kt | 1 - .../tachiyomi/ui/download/DownloadButton.kt | 9 +- .../ui/download/DownloadController.kt | 5 +- .../tachiyomi/ui/download/DownloadHolder.kt | 4 - .../tachiyomi/ui/download/DownloadItem.kt | 18 +- .../ui/download/DownloadPresenter.kt | 1 - .../ui/extension/ExtensionBottomPresenter.kt | 20 +- .../ui/extension/ExtensionBottomSheet.kt | 24 +- .../extension/ExtensionDetailsController.kt | 1 - .../ui/extension/ExtensionDetailsPresenter.kt | 4 +- .../ExtensionDividerItemDecoration.kt | 11 +- .../ui/extension/ExtensionGroupHolder.kt | 4 +- .../ui/extension/ExtensionGroupItem.kt | 9 +- .../tachiyomi/ui/extension/ExtensionHolder.kt | 1 - .../tachiyomi/ui/extension/ExtensionItem.kt | 17 +- .../ui/extension/ExtensionTrustDialog.kt | 4 +- .../extension/SettingsExtensionsController.kt | 4 +- .../ui/library/ChangeMangaCategoriesDialog.kt | 11 +- .../ui/library/DisplayBottomSheet.kt | 3 - .../tachiyomi/ui/library/LibraryAdapter.kt | 1 - .../tachiyomi/ui/library/LibraryBadge.kt | 10 +- .../ui/library/LibraryCategoryAdapter.kt | 25 +- .../ui/library/LibraryCategoryView.kt | 3 +- .../tachiyomi/ui/library/LibraryController.kt | 213 +++++----- .../tachiyomi/ui/library/LibraryGridHolder.kt | 9 +- .../tachiyomi/ui/library/LibraryHeaderItem.kt | 11 +- .../tachiyomi/ui/library/LibraryHolder.kt | 5 +- .../tachiyomi/ui/library/LibraryItem.kt | 29 +- .../ui/library/LibraryListController.kt | 225 +++++------ .../tachiyomi/ui/library/LibraryListHolder.kt | 5 +- .../tachiyomi/ui/library/LibraryPresenter.kt | 93 ++--- .../ui/library/LibrarySelectionEvent.kt | 2 +- .../tachiyomi/ui/library/LibrarySort.kt | 2 +- .../kanade/tachiyomi/ui/library/ReSpinner.kt | 2 +- .../ui/library/filter/FilterBottomSheet.kt | 42 +- .../ui/library/filter/FilterTagGroup.kt | 40 +- .../kanade/tachiyomi/ui/main/MainActivity.kt | 369 +++++++++--------- .../tachiyomi/ui/main/SearchActivity.kt | 23 +- .../kanade/tachiyomi/ui/main/TabsAnimator.kt | 1 - .../ui/manga/ChaptersSortBottomSheet.kt | 9 +- .../tachiyomi/ui/manga/ChooseShapeDialog.kt | 7 +- .../ui/manga/MangaDetailsController.kt | 53 ++- .../ui/manga/MangaDetailsPresenter.kt | 130 +++--- .../tachiyomi/ui/manga/MangaHeaderHolder.kt | 22 +- .../tachiyomi/ui/manga/MangaHeaderItem.kt | 11 +- .../tachiyomi/ui/manga/TrackingBottomSheet.kt | 3 +- .../tachiyomi/ui/manga/chapter/ChapterItem.kt | 11 +- .../ui/manga/chapter/ChapterMatHolder.kt | 8 +- .../ui/manga/chapter/ChaptersAdapter.kt | 6 +- .../ui/manga/info/EditMangaDialog.kt | 9 +- .../ui/manga/track/SetTrackChaptersDialog.kt | 6 +- .../ui/manga/track/SetTrackScoreDialog.kt | 16 +- .../ui/manga/track/SetTrackStatusDialog.kt | 5 +- .../tachiyomi/ui/manga/track/TrackAdapter.kt | 3 +- .../ui/manga/track/TrackSearchAdapter.kt | 6 +- .../ui/manga/track/TrackSearchDialog.kt | 16 +- .../tachiyomi/ui/migration/MangaAdapter.kt | 2 +- .../tachiyomi/ui/migration/MangaHolder.kt | 9 +- .../tachiyomi/ui/migration/MangaItem.kt | 10 +- .../ui/migration/MigrationController.kt | 2 +- .../tachiyomi/ui/migration/MigrationFlags.kt | 8 +- .../ui/migration/MigrationMangaDialog.kt | 2 +- .../ui/migration/MigrationPresenter.kt | 66 ++-- .../ui/migration/SearchController.kt | 13 +- .../tachiyomi/ui/migration/SearchPresenter.kt | 7 +- .../tachiyomi/ui/migration/SelectionHeader.kt | 8 +- .../tachiyomi/ui/migration/SourceHolder.kt | 2 +- .../tachiyomi/ui/migration/SourceItem.kt | 9 +- .../tachiyomi/ui/migration/ViewState.kt | 10 +- .../design/MigrationBottomSheetDialog.kt | 42 +- .../manga/design/MigrationSourceAdapter.kt | 11 +- .../manga/design/MigrationSourceHolder.kt | 8 +- .../manga/design/MigrationSourceItem.kt | 16 +- .../manga/design/PreMigrationController.kt | 15 +- .../migration/manga/process/MigratingManga.kt | 18 +- .../manga/process/MigrationListController.kt | 141 ++++--- .../manga/process/MigrationProcedureConfig.kt | 6 +- .../manga/process/MigrationProcessAdapter.kt | 16 +- .../manga/process/MigrationProcessHolder.kt | 8 +- .../manga/process/MigrationProcessItem.kt | 9 +- .../ui/reader/PageIndicatorTextView.kt | 6 +- .../tachiyomi/ui/reader/ReaderActivity.kt | 19 +- .../ui/reader/ReaderColorFilterSheet.kt | 7 +- .../ui/reader/ReaderColorFilterView.kt | 9 +- .../tachiyomi/ui/reader/ReaderPageSheet.kt | 8 +- .../tachiyomi/ui/reader/ReaderPresenter.kt | 7 +- .../tachiyomi/ui/reader/ReaderSeekBar.kt | 6 +- .../ui/reader/ReaderSettingsSheet.kt | 40 +- .../tachiyomi/ui/reader/SaveImageNotifier.kt | 1 - .../ui/reader/loader/ChapterLoader.kt | 7 +- .../ui/reader/loader/DirectoryPageLoader.kt | 3 +- .../ui/reader/loader/DownloadPageLoader.kt | 9 +- .../ui/reader/loader/EpubPageLoader.kt | 3 +- .../ui/reader/loader/HttpPageLoader.kt | 21 +- .../tachiyomi/ui/reader/loader/PageLoader.kt | 1 - .../ui/reader/loader/RarPageLoader.kt | 7 +- .../ui/reader/loader/ZipPageLoader.kt | 2 +- .../ui/reader/model/ChapterTransition.kt | 7 +- .../tachiyomi/ui/reader/model/ReaderPage.kt | 13 +- .../ui/reader/model/ViewerChapters.kt | 7 +- .../tachiyomi/ui/reader/viewer/BaseViewer.kt | 1 - .../viewer/GestureDetectorWithLongTap.kt | 5 +- .../ui/reader/viewer/ReaderProgressBar.kt | 9 +- .../tachiyomi/ui/reader/viewer/pager/Pager.kt | 5 +- .../ui/reader/viewer/pager/PagerButton.kt | 3 +- .../ui/reader/viewer/pager/PagerConfig.kt | 5 +- .../ui/reader/viewer/pager/PagerPageHolder.kt | 32 +- .../viewer/pager/PagerTransitionHolder.kt | 9 +- .../ui/reader/viewer/pager/PagerViewer.kt | 5 +- .../reader/viewer/pager/PagerViewerAdapter.kt | 1 - .../reader/viewer/webtoon/WebtoonAdapter.kt | 9 +- .../viewer/webtoon/WebtoonBaseHolder.kt | 5 +- .../ui/reader/viewer/webtoon/WebtoonConfig.kt | 5 +- .../ui/reader/viewer/webtoon/WebtoonFrame.kt | 9 +- .../viewer/webtoon/WebtoonLayoutManager.kt | 1 - .../viewer/webtoon/WebtoonPageHolder.kt | 37 +- .../viewer/webtoon/WebtoonRecyclerView.kt | 24 +- .../webtoon/WebtoonSubsamplingImageView.kt | 5 +- .../viewer/webtoon/WebtoonTransitionHolder.kt | 5 +- .../ui/reader/viewer/webtoon/WebtoonViewer.kt | 7 +- .../ConfirmDeleteChaptersDialog.kt | 2 +- .../ui/recent_updates/RecentChapterItem.kt | 13 +- .../recent_updates/RecentChaptersAdapter.kt | 7 +- .../RecentChaptersController.kt | 4 +- .../recent_updates/RecentChaptersPresenter.kt | 15 +- .../ui/recently_read/RecentlyReadAdapter.kt | 6 +- .../recently_read/RecentlyReadController.kt | 3 +- .../ui/recently_read/RecentlyReadHolder.kt | 8 +- .../ui/recently_read/RecentlyReadItem.kt | 10 +- .../ui/recently_read/RecentlyReadPresenter.kt | 7 +- .../ui/recently_read/RemoveHistoryDialog.kt | 9 +- .../ui/security/BiometricActivity.kt | 3 +- .../ui/security/SecureActivityDelegate.kt | 11 +- .../tachiyomi/ui/setting/PreferenceDSL.kt | 26 +- .../ui/setting/SettingsAboutController.kt | 12 +- .../ui/setting/SettingsAdvancedController.kt | 1 - .../ui/setting/SettingsBackupController.kt | 17 +- .../ui/setting/SettingsDownloadController.kt | 7 +- .../ui/setting/SettingsGeneralController.kt | 8 +- .../ui/setting/SettingsLibraryController.kt | 5 +- .../ui/setting/SettingsReaderController.kt | 1 - .../ui/setting/SettingsSourcesController.kt | 4 +- .../ui/setting/SettingsTrackingController.kt | 9 +- .../ui/setting/track/BangumiLoginActivity.kt | 3 - .../tachiyomi/ui/webview/WebViewActivity.kt | 15 +- .../tachiyomi/util/PreferenceExtensions.kt | 2 +- .../util/chapter/ChapterRecognition.kt | 1 - .../util/chapter/ChapterSourceSync.kt | 20 +- .../tachiyomi/util/lang/RetryWithDelay.kt | 8 +- .../kanade/tachiyomi/util/storage/DiskUtil.kt | 1 - .../kanade/tachiyomi/util/storage/EpubFile.kt | 5 +- .../tachiyomi/util/storage/FileExtensions.kt | 1 - .../tachiyomi/util/storage/OkioExtensions.kt | 7 +- .../util/system/ContextExtensions.kt | 4 +- .../util/system/CoroutinesExtensions.kt | 3 +- .../kanade/tachiyomi/util/system/ImageUtil.kt | 28 +- .../tachiyomi/util/system/LocaleHelper.kt | 3 +- .../eu/kanade/tachiyomi/util/system/RxUtil.kt | 4 +- .../util/system/WebViewClientCompat.kt | 51 +-- .../tachiyomi/util/view/DeferredField.kt | 1 - .../util/view/ImageViewExtensions.kt | 2 +- .../tachiyomi/util/view/ViewExtensions.kt | 251 ++++++------ .../util/view/ViewGroupExtensions.kt | 2 +- .../tachiyomi/widget/AutofitRecyclerView.kt | 6 +- .../tachiyomi/widget/CustomLayoutPicker.kt | 2 +- .../tachiyomi/widget/DialogCheckboxView.kt | 6 +- .../widget/DialogCustomDownloadView.kt | 1 - .../widget/DrawerSwipeCloseListener.kt | 6 +- .../tachiyomi/widget/ElevationAppBarLayout.kt | 34 -- .../eu/kanade/tachiyomi/widget/EmptyView.kt | 2 +- .../widget/ExtendedNavigationView.kt | 35 +- .../tachiyomi/widget/FABMoveBehaviour.kt | 2 +- .../widget/IgnoreFirstSpinnerListener.kt | 5 +- .../tachiyomi/widget/MinMaxNumberPicker.kt | 1 - .../tachiyomi/widget/NegativeSeekBar.kt | 2 - .../eu/kanade/tachiyomi/widget/OutlineSpan.kt | 33 +- .../kanade/tachiyomi/widget/PTSansTextView.kt | 8 +- .../widget/PreCachingLayoutManager.kt | 1 - .../widget/RecyclerViewPagerAdapter.kt | 6 +- .../tachiyomi/widget/RevealAnimationView.kt | 1 - .../widget/SimpleAnimationListener.kt | 2 +- .../tachiyomi/widget/SimpleNavigationView.kt | 41 +- .../tachiyomi/widget/SimpleSeekBarListener.kt | 2 +- .../tachiyomi/widget/StateImageViewTarget.kt | 12 +- .../tachiyomi/widget/ViewPagerAdapter.kt | 3 +- .../widget/preference/ExtensionPreference.kt | 8 +- .../widget/preference/IntListMatPreference.kt | 19 +- .../widget/preference/IntListPreference.kt | 2 +- .../widget/preference/ListMatPreference.kt | 27 +- .../preference/LoginCheckBoxPreference.kt | 11 +- .../widget/preference/LoginPreference.kt | 5 +- .../widget/preference/MatPreference.kt | 11 +- .../preference/MultiListMatPreference.kt | 13 +- .../widget/preference/SourceLoginDialog.kt | 1 - .../preference/SwitchPreferenceCategory.kt | 14 +- app/src/main/res/layout/main_activity.xml | 4 +- .../CustomRobolectricGradleTestRunner.kt | 2 +- .../tachiyomi/data/backup/BackupTest.kt | 18 +- .../tachiyomi/data/database/CategoryTest.kt | 1 - .../data/database/ChapterRecognitionTest.kt | 1 - .../data/library/LibraryUpdateServiceTest.kt | 6 +- 396 files changed, 2539 insertions(+), 2843 deletions(-) delete mode 100644 app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/NoToolbarElevationController.kt delete mode 100644 app/src/main/java/eu/kanade/tachiyomi/widget/ElevationAppBarLayout.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 4c9ef098c0..a1f4663934 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -8,7 +8,7 @@ plugins { kotlin("android") kotlin("android.extensions") kotlin("kapt") - //id("org.jmailen.kotlinter") version "2.3.1" + id("org.jmailen.kotlinter") version "2.3.1" id("com.github.zellius.shortcut-helper") id("com.google.gms.google-services") apply false } @@ -114,9 +114,9 @@ dependencies { implementation("com.google.firebase:firebase-core:17.2.3") - val lifecycle_version = "2.1.0" - implementation("androidx.lifecycle:lifecycle-extensions:$lifecycle_version") - implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version") + val lifecycleVersion = "2.1.0" + implementation("androidx.lifecycle:lifecycle-extensions:$lifecycleVersion") + implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycleVersion") // ReactiveX implementation("io.reactivex:rxandroid:1.2.1") @@ -126,15 +126,15 @@ dependencies { implementation("com.github.pwittchen:reactivenetwork:0.13.0") // Network client - val okhttp_version = "4.3.1" - implementation("com.squareup.okhttp3:okhttp:$okhttp_version") - implementation("com.squareup.okhttp3:logging-interceptor:$okhttp_version") + val okhttpVersion = "4.3.1" + implementation("com.squareup.okhttp3:okhttp:$okhttpVersion") + implementation("com.squareup.okhttp3:logging-interceptor:$okhttpVersion") implementation("com.squareup.okio:okio:2.4.3") // REST - val retrofit_version = "2.7.1" - implementation("com.squareup.retrofit2:retrofit:$retrofit_version") - implementation("com.squareup.retrofit2:converter-gson:$retrofit_version") + val retrofitVersion = "2.7.1" + implementation("com.squareup.retrofit2:retrofit:$retrofitVersion") + implementation("com.squareup.retrofit2:converter-gson:$retrofitVersion") // JSON implementation("com.google.code.gson:gson:2.8.6") @@ -164,18 +164,18 @@ dependencies { implementation("io.requery:sqlite-android:3.31.0") // Model View Presenter - val nucleus_version = "3.0.0" - implementation("info.android15.nucleus:nucleus:$nucleus_version") - implementation("info.android15.nucleus:nucleus-support-v7:$nucleus_version") + val nucleusVersion = "3.0.0" + implementation("info.android15.nucleus:nucleus:$nucleusVersion") + implementation("info.android15.nucleus:nucleus-support-v7:$nucleusVersion") // Dependency injection implementation("com.github.inorichi.injekt:injekt-core:65b0440") // Image library - val glide_version = "4.11.0" - implementation("com.github.bumptech.glide:glide:$glide_version") - implementation("com.github.bumptech.glide:okhttp3-integration:$glide_version") - kapt("com.github.bumptech.glide:compiler:$glide_version") + val glideVersion = "4.11.0" + implementation("com.github.bumptech.glide:glide:$glideVersion") + implementation("com.github.bumptech.glide:okhttp3-integration:$glideVersion") + kapt("com.github.bumptech.glide:compiler:$glideVersion") // Transformations implementation("jp.wasabeef:glide-transformations:4.1.0") @@ -208,28 +208,28 @@ dependencies { implementation("com.github.inorichi:conductor-support-preference:a32c357") // RxBindings - val rxbindings_version = "1.0.1" - implementation("com.jakewharton.rxbinding:rxbinding-kotlin:$rxbindings_version") - implementation("com.jakewharton.rxbinding:rxbinding-appcompat-v7-kotlin:$rxbindings_version") - implementation("com.jakewharton.rxbinding:rxbinding-support-v4-kotlin:$rxbindings_version") - implementation("com.jakewharton.rxbinding:rxbinding-recyclerview-v7-kotlin:$rxbindings_version") + val rxbindingsVersion = "1.0.1" + implementation("com.jakewharton.rxbinding:rxbinding-kotlin:$rxbindingsVersion") + implementation("com.jakewharton.rxbinding:rxbinding-appcompat-v7-kotlin:$rxbindingsVersion") + implementation("com.jakewharton.rxbinding:rxbinding-support-v4-kotlin:$rxbindingsVersion") + implementation("com.jakewharton.rxbinding:rxbinding-recyclerview-v7-kotlin:$rxbindingsVersion") // Tests testImplementation("junit:junit:4.13") - testImplementation("org.assertj:assertj-core:1.7.1") + testImplementation("org.assertj:assertj-core:3.12.2") testImplementation("org.mockito:mockito-core:1.10.19") - val robolectric_version = "3.1.4" - testImplementation("org.robolectric:robolectric:$robolectric_version") - testImplementation("org.robolectric:shadows-multidex:$robolectric_version") - testImplementation("org.robolectric:shadows-play-services:$robolectric_version") + val robolectricVersion = "3.1.4" + testImplementation("org.robolectric:robolectric:$robolectricVersion") + testImplementation("org.robolectric:shadows-multidex:$robolectricVersion") + testImplementation("org.robolectric:shadows-play-services:$robolectricVersion") implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION)) - val coroutines_version = "1.3.3" - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version") + val coroutinesVersion = "1.3.3" + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion") //Crash reports val acraVersion = "4.9.2" @@ -239,13 +239,13 @@ dependencies { implementation("info.debatty:java-string-similarity:1.2.1") } -/*tasks.preBuild { +tasks.preBuild { dependsOn(tasks.lintKotlin) } tasks.lintKotlin { dependsOn(tasks.formatKotlin) -}*/ +} -if (getGradle().getStartParameter().getTaskRequests().toString().contains("Standard")) { +if (gradle.startParameter.taskRequests.toString().contains("Standard")) { apply(mapOf("plugin" to "com.google.gms.google-services")) } \ No newline at end of file diff --git a/app/src/main/java/eu/kanade/tachiyomi/App.kt b/app/src/main/java/eu/kanade/tachiyomi/App.kt index 90f4e5ba15..16ce8042cf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/App.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/App.kt @@ -52,7 +52,7 @@ open class App : Application(), LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onAppBackgrounded() { - //App in background + // App in background val preferences: PreferencesHelper by injectLazy() if (preferences.lockAfter().getOrDefault() >= 0) { SecureActivityDelegate.locked = true @@ -92,5 +92,4 @@ open class App : Application(), LifecycleObserver { protected open fun setupNotificationChannels() { Notifications.createChannels(this) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/AppModule.kt b/app/src/main/java/eu/kanade/tachiyomi/AppModule.kt index 4c0621a1a8..f9aa0a6dc3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/AppModule.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/AppModule.kt @@ -13,7 +13,11 @@ import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.source.SourceManager import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch -import uy.kohesive.injekt.api.* +import uy.kohesive.injekt.api.InjektModule +import uy.kohesive.injekt.api.InjektRegistrar +import uy.kohesive.injekt.api.addSingleton +import uy.kohesive.injekt.api.addSingletonFactory +import uy.kohesive.injekt.api.get class AppModule(val app: Application) : InjektModule { @@ -52,7 +56,5 @@ class AppModule(val app: Application) : InjektModule { GlobalScope.launch { get() } GlobalScope.launch { get() } - } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/Migrations.kt b/app/src/main/java/eu/kanade/tachiyomi/Migrations.kt index 0f0d7b1897..1e0897155e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/Migrations.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/Migrations.kt @@ -67,5 +67,4 @@ object Migrations { } return false } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupConst.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupConst.kt index 643c469a28..8a8cc45fba 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupConst.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupConst.kt @@ -1,7 +1,6 @@ package eu.kanade.tachiyomi.data.backup import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID - object BackupConst { const val INTENT_FILTER = "SettingsBackupFragment" @@ -18,5 +17,5 @@ object BackupConst { const val EXTRA_TIME = "$ID.$INTENT_FILTER.EXTRA_TIME" const val EXTRA_ERROR_FILE_PATH = "$ID.$INTENT_FILTER.EXTRA_ERROR_FILE_PATH" const val EXTRA_ERROR_FILE = "$ID.$INTENT_FILTER.EXTRA_ERROR_FILE" - const val EXTRA_MINI_ERROR= "$ID.$INTENT_FILTER.EXTRA_MINI_ERROR" -} \ No newline at end of file + const val EXTRA_MINI_ERROR = "$ID.$INTENT_FILTER.EXTRA_MINI_ERROR" +} 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 d7095642db..dd2359a366 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 @@ -5,8 +5,8 @@ import android.content.Context import android.content.Intent import android.net.Uri import com.google.gson.JsonArray -import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID +import eu.kanade.tachiyomi.data.database.models.Manga /** * [IntentService] used to backup [Manga] information to [JsonArray] @@ -45,7 +45,6 @@ class BackupCreateService : IntentService(NAME) { } context.startService(intent) } - } private val backupManager by lazy { BackupManager(this) } @@ -60,5 +59,4 @@ class BackupCreateService : IntentService(NAME) { if (uri != null) backupManager.createBackup(uri, flags, false) } - } 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 f18340ac52..f906568de0 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 @@ -6,9 +6,9 @@ import com.evernote.android.job.JobManager import com.evernote.android.job.JobRequest import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault +import java.util.concurrent.TimeUnit import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.concurrent.TimeUnit class BackupCreatorJob : Job() { 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 fb03033dc6..ac0bff496d 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 @@ -3,8 +3,15 @@ package eu.kanade.tachiyomi.data.backup import android.content.Context import android.content.Intent import android.net.Uri -import com.github.salomonbrys.kotson.* -import com.google.gson.* +import com.github.salomonbrys.kotson.fromJson +import com.github.salomonbrys.kotson.registerTypeAdapter +import com.github.salomonbrys.kotson.registerTypeHierarchyAdapter +import com.github.salomonbrys.kotson.set +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject import com.hippo.unifile.UniFile import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY_MASK @@ -22,22 +29,34 @@ import eu.kanade.tachiyomi.data.backup.models.Backup.HISTORY import eu.kanade.tachiyomi.data.backup.models.Backup.MANGA import eu.kanade.tachiyomi.data.backup.models.Backup.TRACK import eu.kanade.tachiyomi.data.backup.models.DHistory -import eu.kanade.tachiyomi.data.backup.serializer.* +import eu.kanade.tachiyomi.data.backup.serializer.CategoryTypeAdapter +import eu.kanade.tachiyomi.data.backup.serializer.ChapterTypeAdapter +import eu.kanade.tachiyomi.data.backup.serializer.HistoryTypeAdapter +import eu.kanade.tachiyomi.data.backup.serializer.MangaTypeAdapter +import eu.kanade.tachiyomi.data.backup.serializer.TrackTypeAdapter import eu.kanade.tachiyomi.data.database.DatabaseHelper -import eu.kanade.tachiyomi.data.database.models.* +import eu.kanade.tachiyomi.data.database.models.CategoryImpl +import eu.kanade.tachiyomi.data.database.models.Chapter +import eu.kanade.tachiyomi.data.database.models.ChapterImpl +import eu.kanade.tachiyomi.data.database.models.History +import eu.kanade.tachiyomi.data.database.models.Manga +import eu.kanade.tachiyomi.data.database.models.MangaCategory +import eu.kanade.tachiyomi.data.database.models.MangaImpl +import eu.kanade.tachiyomi.data.database.models.Track +import eu.kanade.tachiyomi.data.database.models.TrackImpl import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext import eu.kanade.tachiyomi.util.chapter.syncChaptersWithSource import eu.kanade.tachiyomi.util.system.sendLocalBroadcast +import kotlin.math.max +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import rx.Observable import timber.log.Timber import uy.kohesive.injekt.injectLazy -import kotlin.math.max class BackupManager(val context: Context, version: Int = CURRENT_VERSION) { 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 e08c24ce49..7d5991b8e3 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 @@ -38,23 +38,22 @@ import eu.kanade.tachiyomi.util.lang.chop import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.system.isServiceRunning import eu.kanade.tachiyomi.util.system.notificationManager +import java.io.File +import java.text.SimpleDateFormat +import java.util.Locale +import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.io.File -import java.text.SimpleDateFormat -import java.util.Locale -import java.util.concurrent.TimeUnit /** * Restores backup from json file */ class BackupRestoreService : Service() { - /** * Wake lock that will be held until the service is destroyed. */ @@ -87,7 +86,6 @@ class BackupRestoreService : Service() { */ private val trackingErrors = mutableListOf() - /** * List containing missing sources */ @@ -113,7 +111,6 @@ class BackupRestoreService : Service() { */ internal val trackManager: TrackManager by injectLazy() - /** * Method called when the service is created. It injects dependencies and acquire the wake lock. */ @@ -216,7 +213,6 @@ class BackupRestoreService : Service() { showResultNotification(logFile.parent, logFile.name) } - /**Restore categories if they were backed up * */ @@ -246,8 +242,7 @@ class BackupRestoreService : Service() { if (job?.isCancelled == false) { showProgressNotification(restoreProgress, totalAmount, manga.title) restoreProgress += 1 - } - else { + } else { throw java.lang.Exception("Job was cancelled") } val dbManga = backupManager.getMangaFromDatabase(manga) @@ -262,7 +257,7 @@ class BackupRestoreService : Service() { } if (!dbMangaExists || !backupManager.restoreChaptersForManga(manga, chapters)) { - //manga gets chapters added + // manga gets chapters added backupManager.restoreChapterFetch(source, manga, chapters) } // Restore categories @@ -280,8 +275,7 @@ class BackupRestoreService : Service() { val cause = e.cause if (cause is SourceNotFoundException) { sourcesMissing.add(cause.id) - } - else if (e.message?.contains("licensed", true) == true) { + } else if (e.message?.contains("licensed", true) == true) { lincensedManga++ } errors.add("${manga.title} - ${cause?.message ?: e.message}") @@ -303,7 +297,7 @@ class BackupRestoreService : Service() { try { service.refresh(track) db.insertTrack(track).executeAsBlocking() - }catch (e : Exception){ + } catch (e: Exception) { errors.add("${manga.title} - ${e.message}") } } else { @@ -357,7 +351,6 @@ class BackupRestoreService : Service() { NotificationReceiver.cancelRestorePendingBroadcast(this) } - /** * Shows the notification containing the currently updating manga and the progress. * @@ -473,4 +466,4 @@ class BackupRestoreService : Service() { context.stopService(Intent(context, BackupRestoreService::class.java)) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/Backup.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/Backup.kt index dd50553c0d..d0e46e1b3a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/Backup.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/Backup.kt @@ -1,7 +1,8 @@ package eu.kanade.tachiyomi.data.backup.models import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale /** * Json values @@ -20,4 +21,4 @@ object Backup { val date = SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.getDefault()).format(Date()) return "tachiyomi_$date.json" } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/DHistory.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/DHistory.kt index 3623dd0d37..a5e1c1a0f3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/DHistory.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/models/DHistory.kt @@ -1,3 +1,3 @@ package eu.kanade.tachiyomi.data.backup.models -data class DHistory(val url: String,val lastRead: Long) \ No newline at end of file +data class DHistory(val url: String, val lastRead: Long) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/CategoryTypeAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/CategoryTypeAdapter.kt index b31279268f..1beb5d9798 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/CategoryTypeAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/CategoryTypeAdapter.kt @@ -28,4 +28,4 @@ object CategoryTypeAdapter { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/HistoryTypeAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/HistoryTypeAdapter.kt index e313c3b90b..863a1a1f30 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/HistoryTypeAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/HistoryTypeAdapter.kt @@ -29,4 +29,4 @@ object HistoryTypeAdapter { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/MangaTypeAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/MangaTypeAdapter.kt index d63a040e14..d1ccf823e9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/MangaTypeAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/MangaTypeAdapter.kt @@ -35,4 +35,4 @@ object MangaTypeAdapter { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/TrackTypeAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/TrackTypeAdapter.kt index 0cc16d38e9..de78b8c115 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/TrackTypeAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/TrackTypeAdapter.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.data.backup.serializer -import android.telecom.DisconnectCause.REMOTE import com.github.salomonbrys.kotson.typeAdapter import com.google.gson.TypeAdapter import com.google.gson.stream.JsonToken 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 6f5f23958b..4b9117a3c9 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 @@ -9,14 +9,13 @@ import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.util.storage.DiskUtil import eu.kanade.tachiyomi.util.storage.saveTo +import java.io.File +import java.io.IOException import okhttp3.Response -import okio.Okio import okio.buffer import okio.sink import rx.Observable import uy.kohesive.injekt.injectLazy -import java.io.File -import java.io.IOException /** * Class used to create chapter cache @@ -136,7 +135,6 @@ class ChapterCache(private val context: Context) { diskCache.flush() editor.commit() editor.abortUnlessCommitted() - } catch (e: Exception) { // Ignore. } finally { @@ -202,4 +200,3 @@ class ChapterCache(private val context: Context) { return "${chapter.manga_id}${chapter.url}" } } - 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 479ad00c24..2fa227146a 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 @@ -20,8 +20,8 @@ class CoverCache(private val context: Context) { /** * Cache directory used for cache management. */ - private val cacheDir = context.getExternalFilesDir("covers") ?: - File(context.filesDir, "covers").also { it.mkdirs() } + private val cacheDir = context.getExternalFilesDir("covers") + ?: File(context.filesDir, "covers").also { it.mkdirs() } /** * Returns the cover from cache. @@ -37,7 +37,7 @@ class CoverCache(private val context: Context) { * Copy the given stream to this cache. * * @param thumbnailUrl url of the thumbnail. - * @param inputStream the stream to copy. + * @param inputStream the stream to copy. * @throws IOException if there's any error. */ @Throws(IOException::class) 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 815a6baee0..4509319c9c 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 @@ -29,8 +29,8 @@ 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, +open class DatabaseHelper(context: Context) : +MangaQueries, ChapterQueries, TrackQueries, CategoryQueries, MangaCategoryQueries, HistoryQueries, SearchMetadataQueries { private val configuration = SupportSQLiteOpenHelper.Configuration.builder(context) @@ -52,5 +52,4 @@ open class DatabaseHelper(context: Context) inline fun inTransaction(block: () -> Unit) = db.inTransaction(block) fun lowLevel() = db.lowLevel() - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbExtensions.kt index 252ac08290..caaba0e101 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbExtensions.kt @@ -22,4 +22,3 @@ inline fun StorIOSQLite.inTransactionReturn(block: () -> T): T { lowLevel().endTransaction() } } - 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 91b9a2aeaa..222fac6882 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 @@ -2,10 +2,12 @@ package eu.kanade.tachiyomi.data.database import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper -import android.content.Context -import android.database.sqlite.SQLiteDatabase -import android.database.sqlite.SQLiteOpenHelper -import eu.kanade.tachiyomi.data.database.tables.* +import eu.kanade.tachiyomi.data.database.tables.CategoryTable +import eu.kanade.tachiyomi.data.database.tables.ChapterTable +import eu.kanade.tachiyomi.data.database.tables.HistoryTable +import eu.kanade.tachiyomi.data.database.tables.MangaCategoryTable +import eu.kanade.tachiyomi.data.database.tables.MangaTable +import eu.kanade.tachiyomi.data.database.tables.TrackTable class DbOpenCallback : SupportSQLiteOpenHelper.Callback(DATABASE_VERSION) { @@ -81,5 +83,4 @@ class DbOpenCallback : SupportSQLiteOpenHelper.Callback(DATABASE_VERSION) { override fun onConfigure(db: SupportSQLiteDatabase) { db.setForeignKeyConstraintsEnabled(true) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbProvider.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbProvider.kt index 7af8dff0c1..4609852b96 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/DbProvider.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/DbProvider.kt @@ -5,5 +5,4 @@ import com.pushtorefresh.storio.sqlite.impl.DefaultStorIOSQLite interface DbProvider { val db: DefaultStorIOSQLite - -} \ No newline at end of file +} 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 d70d659877..beefde472b 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 @@ -47,7 +47,6 @@ class CategoryPutResolver : DefaultPutResolver() { val orderString = obj.mangaOrder.joinToString("/") put(COL_MANGA_ORDER, orderString) } - } } 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 56294337df..c9d9b13d3e 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 @@ -88,4 +88,3 @@ class ChapterDeleteResolver : DefaultDeleteResolver() { .whereArgs(obj.id) .build() } - diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/SearchMetadataTypeMapping.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/SearchMetadataTypeMapping.kt index 25df012756..1f9248a7c1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/SearchMetadataTypeMapping.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/SearchMetadataTypeMapping.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.data.database.mappers - import android.content.ContentValues import android.database.Cursor import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping @@ -63,4 +62,4 @@ class SearchMetadataDeleteResolver : DefaultDeleteResolver() { .where("$COL_MANGA_ID = ?") .whereArgs(obj.mangaId) .build() -} \ No newline at end of file +} 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 6759316de9..797c6a2524 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 @@ -54,7 +54,6 @@ class TrackPutResolver : DefaultPutResolver() { put(COL_STATUS, obj.status) put(COL_TRACKING_URL, obj.tracking_url) put(COL_SCORE, obj.score) - } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Category.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Category.kt index 6d08ea983e..8896493176 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Category.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Category.kt @@ -15,18 +15,18 @@ interface Category : Serializable { var flags: Int - var mangaOrder:List + var mangaOrder: List - var mangaSort:Char? + var mangaSort: Char? - var isFirst:Boolean? - var isLast:Boolean? + var isFirst: Boolean? + var isLast: Boolean? val nameLower: String get() = name.toLowerCase() fun isAscending(): Boolean { - return ((mangaSort?.minus('a') ?: 0) % 2) != 1 + return ((mangaSort?.minus('a') ?: 0) % 2) != 1 } fun sortingMode(): Int? = when (mangaSort) { @@ -42,9 +42,9 @@ interface Category : Serializable { fun sortRes(): Int = when (mangaSort) { ALPHA_ASC, ALPHA_DSC -> R.string.title UPDATED_ASC, UPDATED_DSC -> R.string.action_sort_latest_chapter - UNREAD_ASC, UNREAD_DSC -> R.string.action_filter_unread - LAST_READ_ASC, LAST_READ_DSC -> R.string.action_sort_last_read - TOTAL_ASC, TOTAL_DSC -> R.string.action_sort_total + UNREAD_ASC, UNREAD_DSC -> R.string.action_filter_unread + LAST_READ_ASC, LAST_READ_DSC -> R.string.action_sort_last_read + TOTAL_ASC, TOTAL_DSC -> R.string.action_sort_total else -> R.string.action_sort_drag_and_drop } @@ -111,5 +111,4 @@ interface Category : Serializable { isLast = true } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/CategoryImpl.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/CategoryImpl.kt index 2bea32c07c..1332434efe 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/CategoryImpl.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/CategoryImpl.kt @@ -30,5 +30,4 @@ class CategoryImpl : Category { override fun hashCode(): Int { return name.hashCode() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/ChapterImpl.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/ChapterImpl.kt index bdb7305c7c..0daae16f5d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/ChapterImpl.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/ChapterImpl.kt @@ -39,5 +39,4 @@ class ChapterImpl : Chapter { override fun hashCode(): Int { return url.hashCode() } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/History.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/History.kt index 30f50972c5..dff3bcb155 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/History.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/History.kt @@ -35,7 +35,7 @@ interface History : Serializable { * @param chapter chapter object * @return history object */ - fun create(chapter: Chapter): History = HistoryImpl().apply { + fun create(chapter: Chapter): History = HistoryImpl().apply { this.chapter_id = chapter.id!! } } 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 b9a7d94286..35cf30c67a 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 @@ -5,5 +5,4 @@ class LibraryManga : MangaImpl() { var unread: Int = 0 var category: Int = 0 - -} \ No newline at end of file +} 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 46bbd95246..0105e5f133 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 @@ -3,9 +3,9 @@ package eu.kanade.tachiyomi.data.database.models import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.ui.reader.ReaderActivity +import java.util.Locale import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.Locale interface Manga : SManga { @@ -82,7 +82,7 @@ interface Manga : SManga { tag.startsWith("chinese") || tag == "manhua" || tag.startsWith("english") || tag == "comic" } == true || isComicSource(sourceName) || - sourceName.contains("manhua", true) ) + sourceName.contains("manhua", true)) ReaderActivity.LEFT_TO_RIGHT else 0 } @@ -168,5 +168,4 @@ interface Manga : SManga { this.source = source } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt index 305d5ef9cf..2203370884 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt @@ -17,5 +17,4 @@ class MangaCategory { return mc } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapterHistory.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapterHistory.kt index e11fe8f832..5ed7ed455c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapterHistory.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapterHistory.kt @@ -5,6 +5,6 @@ package eu.kanade.tachiyomi.data.database.models * * @param manga object containing manga * @param chapter object containing chater - * @param history object containing history + * @param history object containing history */ data class MangaChapterHistory(val manga: Manga, val chapter: Chapter, val history: History) 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 032cd25f24..5540b3325c 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 @@ -3,8 +3,8 @@ package eu.kanade.tachiyomi.data.database.models import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.download.DownloadProvider import eu.kanade.tachiyomi.source.model.SManga -import uy.kohesive.injekt.injectLazy import kotlin.collections.set +import uy.kohesive.injekt.injectLazy open class MangaImpl : Manga { @@ -47,9 +47,9 @@ open class MangaImpl : Manga { title = if (currentTitle() != originalTitle()) { val customTitle = currentTitle() val trueTitle = other.title - "${customTitle}${SManga.splitter}${trueTitle}" + "${customTitle}${SManga.splitter}$trueTitle" } else other.title - val db:DownloadManager by injectLazy() + val db: DownloadManager by injectLazy() val provider = DownloadProvider(db.context) provider.renameMangaFolder(oldTitle, title, source) } @@ -63,7 +63,6 @@ open class MangaImpl : Manga { val manga = other as Manga return url == manga.url - } override fun hashCode(): Int { @@ -71,7 +70,7 @@ open class MangaImpl : Manga { } companion object { - private var lastCoverFetch:HashMap = hashMapOf() + private var lastCoverFetch: HashMap = hashMapOf() fun setLastCoverFetch(id: Long, time: Long) { lastCoverFetch[id] = time @@ -79,5 +78,4 @@ open class MangaImpl : Manga { fun getLastCoverFetch(id: Long) = lastCoverFetch[id] ?: 0 } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/SearchMetadata.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/SearchMetadata.kt index 64b1476378..d6bc94fe33 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/SearchMetadata.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/SearchMetadata.kt @@ -18,4 +18,4 @@ data class SearchMetadata( ) { // Transient information attached to this piece of metadata, useful for caching var transientCache: Map? = null -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Track.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Track.kt index 19133e0371..c64363efa0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Track.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/Track.kt @@ -37,5 +37,4 @@ interface Track : Serializable { sync_id = serviceId } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/TrackImpl.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/TrackImpl.kt index 65f6ec7ab1..03a878e146 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/models/TrackImpl.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/models/TrackImpl.kt @@ -41,5 +41,4 @@ class TrackImpl : Track { result = 31 * result + media_id return result } - } 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 edf839d8fa..d677d880d3 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 @@ -32,5 +32,4 @@ interface CategoryQueries : DbProvider { fun deleteCategory(category: Category) = db.delete().`object`(category).prepare() fun deleteCategories(categories: List) = db.delete().objects(categories).prepare() - -} \ No newline at end of file +} 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 c10d0b9367..9af8e810a2 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 @@ -11,7 +11,7 @@ import eu.kanade.tachiyomi.data.database.resolvers.ChapterProgressPutResolver import eu.kanade.tachiyomi.data.database.resolvers.ChapterSourceOrderPutResolver import eu.kanade.tachiyomi.data.database.resolvers.MangaChapterGetResolver import eu.kanade.tachiyomi.data.database.tables.ChapterTable -import java.util.* +import java.util.Date interface ChapterQueries : DbProvider { @@ -88,5 +88,4 @@ interface ChapterQueries : DbProvider { .objects(chapters) .withPutResolver(ChapterSourceOrderPutResolver()) .prepare() - -} \ No newline at end of file +} 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 bb361af48c..e9755efec7 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 @@ -8,7 +8,7 @@ import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory import eu.kanade.tachiyomi.data.database.resolvers.HistoryLastReadPutResolver import eu.kanade.tachiyomi.data.database.resolvers.MangaChapterHistoryGetResolver import eu.kanade.tachiyomi.data.database.tables.HistoryTable -import java.util.* +import java.util.Date interface HistoryQueries : DbProvider { 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 7ad7f937e2..926339d0c8 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 @@ -28,5 +28,4 @@ interface MangaCategoryQueries : DbProvider { insertMangasCategories(mangasCategories).executeAsBlocking() } } - -} \ No newline at end of file +} 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 58cda2fe1e..5f6323efee 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 @@ -145,5 +145,5 @@ interface MangaQueries : DbProvider { .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 ac63517686..319d0c854d 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 @@ -83,7 +83,7 @@ fun getRecentMangasQuery(offset: Int = 0, search: String = "") = """ ON ${Chapter.TABLE}.${Chapter.COL_MANGA_ID} = max_last_read.${Chapter.COL_MANGA_ID} WHERE ${History.TABLE}.${History.COL_LAST_READ} > ? AND max_last_read.${History.COL_CHAPTER_ID} = ${History.TABLE}.${History.COL_CHAPTER_ID} - AND lower(${Manga.TABLE}.${Manga.COL_TITLE}) LIKE '%${search}%' + AND lower(${Manga.TABLE}.${Manga.COL_TITLE}) LIKE '%$search%' ORDER BY max_last_read.${History.COL_LAST_READ} DESC LIMIT 25 OFFSET $offset """ @@ -109,7 +109,7 @@ fun getRecentMangasLimitQuery(limit: Int = 25, search: String = "") = """ ON ${Chapter.TABLE}.${Chapter.COL_MANGA_ID} = max_last_read.${Chapter.COL_MANGA_ID} WHERE ${History.TABLE}.${History.COL_LAST_READ} > ? AND max_last_read.${History.COL_CHAPTER_ID} = ${History.TABLE}.${History.COL_CHAPTER_ID} - AND lower(${Manga.TABLE}.${Manga.COL_TITLE}) LIKE '%${search}%' + AND lower(${Manga.TABLE}.${Manga.COL_TITLE}) LIKE '%$search%' ORDER BY max_last_read.${History.COL_LAST_READ} DESC LIMIT $limit """ @@ -142,7 +142,7 @@ fun getLastReadMangaQuery() = """ ORDER BY max DESC """ -fun getTotalChapterMangaQuery()= """ +fun getTotalChapterMangaQuery() = """ SELECT ${Manga.TABLE}.* FROM ${Manga.TABLE} JOIN ${Chapter.TABLE} @@ -159,4 +159,4 @@ fun getCategoriesForMangaQuery() = """ JOIN ${MangaCategory.TABLE} ON ${Category.TABLE}.${Category.COL_ID} = ${MangaCategory.TABLE}.${MangaCategory.COL_CATEGORY_ID} WHERE ${MangaCategory.COL_MANGA_ID} = ? -""" \ No newline at end of file +""" 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 e6b67ea057..c23c25466d 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 @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.data.database.queries - import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.Query import eu.kanade.tachiyomi.data.database.DbProvider @@ -42,4 +41,4 @@ interface SearchMetadataQueries : DbProvider { .table(SearchMetadataTable.TABLE) .build()) .prepare() -} \ No newline at end of file +} 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 a93877faf7..fee55dbd54 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 @@ -30,5 +30,4 @@ interface TrackQueries : DbProvider { .whereArgs(manga.id, sync.id) .build()) .prepare() - -} \ No newline at end of file +} 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 1c3e6fb74e..d42758beae 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 @@ -30,6 +30,4 @@ class ChapterBackupPutResolver : PutResolver() { put(ChapterTable.COL_BOOKMARK, chapter.bookmark) put(ChapterTable.COL_LAST_PAGE_READ, chapter.last_page_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 1fd82e1a30..e2304eaaf1 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 @@ -31,6 +31,4 @@ class ChapterProgressPutResolver : PutResolver() { put(ChapterTable.COL_LAST_PAGE_READ, chapter.last_page_read) put(ChapterTable.COL_PAGES_LEFT, chapter.pages_left) } - } - 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 77bc0afadc..40c7a7df79 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 @@ -28,5 +28,4 @@ class ChapterSourceOrderPutResolver : PutResolver() { fun mapToContentValues(chapter: Chapter) = ContentValues(1).apply { put(ChapterTable.COL_SOURCE_ORDER, chapter.source_order) } - -} \ No newline at end of file +} 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 f1d68c22a9..98ec17cb4f 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 @@ -60,5 +60,4 @@ class HistoryLastReadPutResolver : HistoryPutResolver() { fun mapToUpdateContentValues(history: History) = ContentValues(1).apply { put(HistoryTable.COL_LAST_READ, history.last_read) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt index 77369827a8..aac8ead3e8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt @@ -21,5 +21,4 @@ class LibraryMangaGetResolver : DefaultGetResolver(), BaseMangaGet return manga } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterGetResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterGetResolver.kt index 4f9ce536fe..edd6a8983d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterGetResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaChapterGetResolver.kt @@ -24,5 +24,4 @@ class MangaChapterGetResolver : DefaultGetResolver() { return MangaChapter(manga, chapter) } - } 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 c0057d2135..a2d23f5051 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 @@ -28,6 +28,4 @@ class MangaFavoritePutResolver : PutResolver() { 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 0c9b28c52d..4ed0a07288 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 @@ -28,6 +28,4 @@ class MangaFlagsPutResolver : PutResolver() { 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/MangaHideTitlePutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaHideTitlePutResolver.kt index 48ead1a5e6..69f76275a4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaHideTitlePutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaHideTitlePutResolver.kt @@ -6,7 +6,6 @@ import com.pushtorefresh.storio.sqlite.operations.put.PutResolver import com.pushtorefresh.storio.sqlite.operations.put.PutResult import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.inTransactionReturn -import eu.kanade.tachiyomi.data.database.models.LibraryManga import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.tables.MangaTable @@ -29,5 +28,4 @@ class MangaHideTitlePutResolver : PutResolver() { fun mapToContentValues(manga: Manga) = ContentValues(1).apply { put(MangaTable.COL_HIDE_TITLE, manga.hide_title) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaInfoPutResolver.kt b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaInfoPutResolver.kt index 84afbd8139..0c03aa8873 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaInfoPutResolver.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/MangaInfoPutResolver.kt @@ -9,7 +9,7 @@ import eu.kanade.tachiyomi.data.database.inTransactionReturn import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.tables.MangaTable -class MangaInfoPutResolver(val reset:Boolean = false): PutResolver() { +class MangaInfoPutResolver(val reset: Boolean = false) : PutResolver() { override fun performPut(db: StorIOSQLite, manga: Manga) = db.inTransactionReturn { val updateQuery = mapToUpdateQuery(manga) @@ -40,6 +40,4 @@ class MangaInfoPutResolver(val reset:Boolean = false): PutResolver() { put(MangaTable.COL_ARTIST, manga.originalArtist()) put(MangaTable.COL_DESCRIPTION, manga.originalDesc()) } - - -} \ No newline at end of file +} 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 8b2672ea98..b1e5e78165 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 @@ -28,6 +28,4 @@ class MangaLastUpdatedPutResolver : PutResolver() { 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 702173afbe..0ffb18ffd1 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 @@ -28,5 +28,4 @@ class MangaTitlePutResolver : PutResolver() { 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 e40f397a8d..a6b7c9b195 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 @@ -28,5 +28,4 @@ class MangaViewerPutResolver : PutResolver() { 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 675103c974..28a565d219 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 @@ -23,7 +23,6 @@ object CategoryTable { $COL_MANGA_ORDER TEXT NOT NULL )""" - val addMangaOrder: String get() = "ALTER TABLE $TABLE ADD COLUMN $COL_MANGA_ORDER TEXT" } 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 dc87afe810..803714a845 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 @@ -67,5 +67,4 @@ object ChapterTable { val pagesLeftQuery: String get() = "ALTER TABLE $TABLE ADD COLUMN $COL_PAGES_LEFT INTEGER DEFAULT 0" - } 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 a42e91e925..d0d34bbb78 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 @@ -20,5 +20,4 @@ object MangaCategoryTable { FOREIGN KEY($COL_MANGA_ID) REFERENCES ${MangaTable.TABLE} (${MangaTable.COL_ID}) ON DELETE CASCADE )""" - } 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 9bcd2895d0..b7ac1744aa 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 @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.data.database.tables - object SearchMetadataTable { const val TABLE = "search_metadata" diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadCache.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadCache.kt index c8b06d2dbb..986f71653e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadCache.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadCache.kt @@ -10,10 +10,10 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.util.storage.DiskUtil +import java.util.concurrent.TimeUnit import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy -import java.util.concurrent.TimeUnit /** * Cache where we dump the downloads directory from the filesystem. This class is needed because @@ -27,10 +27,10 @@ import java.util.concurrent.TimeUnit * @param preferences the preferences of the app. */ class DownloadCache( - private val context: Context, - private val provider: DownloadProvider, - private val sourceManager: SourceManager, - private val preferences: PreferencesHelper = Injekt.get() + private val context: Context, + private val provider: DownloadProvider, + private val sourceManager: SourceManager, + private val preferences: PreferencesHelper = Injekt.get() ) { /** @@ -119,7 +119,7 @@ class DownloadCache( onlineSources.find { provider.getSourceDirName(it) == entry.key }?.id } - val db:DatabaseHelper by injectLazy() + val db: DatabaseHelper by injectLazy() val mangas = db.getMangas().executeAsBlocking().groupBy { it.source } sourceDirs.forEach { sourceValue -> @@ -143,8 +143,8 @@ class DownloadCache( val trueMangaDirs = mangaDirs.mapNotNull { mangaDir -> val manga = sourceMangas.firstOrNull()?.find { DiskUtil.buildValidFilename( it.originalTitle()).toLowerCase() == mangaDir.key - .toLowerCase() && it.source == sourceValue.key } ?: - sourceMangas.lastOrNull()?.find { DiskUtil.buildValidFilename( + .toLowerCase() && it.source == sourceValue.key } + ?: sourceMangas.lastOrNull()?.find { DiskUtil.buildValidFilename( it.originalTitle()).toLowerCase() == mangaDir.key .toLowerCase() && it.source == sourceValue.key } val id = manga?.id ?: return@mapNotNull null @@ -169,8 +169,7 @@ class DownloadCache( val files = mangaFiles[id] if (files == null) { mangaFiles[id] = mutableSetOf(chapterDirName) - } - else { + } else { mangaFiles[id]?.add(chapterDirName) } } @@ -216,7 +215,6 @@ class DownloadCache( sourceDir.files = list }*/ - /** * Removes a manga that has been deleted from this cache. * @@ -230,20 +228,26 @@ class DownloadCache( /** * Class to store the files under the root downloads directory. */ - private class RootDirectory(val dir: UniFile, - var files: Map = hashMapOf()) + private class RootDirectory( + val dir: UniFile, + var files: Map = hashMapOf() + ) /** * Class to store the files under a source directory. */ - private class SourceDirectory(val dir: UniFile, - var files: Map> = hashMapOf()) + private class SourceDirectory( + val dir: UniFile, + var files: Map> = hashMapOf() + ) /** * Class to store the files under a manga directory. */ - private class MangaDirectory(val dir: UniFile, - var files: MutableSet = hashSetOf()) + private class MangaDirectory( + val dir: UniFile, + var files: MutableSet = hashSetOf() + ) /** * Returns a new map containing only the key entries of [transform] that are not null. @@ -267,5 +271,4 @@ class DownloadCache( } return destination } - } 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 e739430c06..ca266d3f44 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 @@ -114,7 +114,7 @@ class DownloadManager(val context: Context) { downloader.pause() downloader.queue.clear() downloader.queue.addAll(downloads) - if(!wasPaused){ + if (!wasPaused) { downloader.start() } } @@ -221,10 +221,9 @@ class DownloadManager(val context: Context) { } downloader.pause() downloader.queue.remove(chapters) - if(!wasPaused && downloader.queue.isNotEmpty()){ + if (!wasPaused && downloader.queue.isNotEmpty()) { downloader.start() - } - else if (downloader.queue.isEmpty() && DownloadService.isRunning(context)) { + } else if (downloader.queue.isEmpty() && DownloadService.isRunning(context)) { DownloadService.stop(context) } queue.remove(chapters) @@ -255,7 +254,7 @@ class DownloadManager(val context: Context) { cleaned += readChapterDirs.size cache.removeChapters(readChapters, manga) if (cache.getDownloadCount(manga) == 0) { - provider.findChapterDirs(allChapters, manga, source).firstOrNull()?.parentFile?.delete()// Delete manga directory if empty + provider.findChapterDirs(allChapters, manga, source).firstOrNull()?.parentFile?.delete() // Delete manga directory if empty } return cleaned } @@ -295,5 +294,5 @@ class DownloadManager(val context: Context) { } fun addListener(listener: DownloadQueue.DownloadListener) = queue.addListener(listener) - fun removeListener(listener: DownloadQueue.DownloadListener) = queue.removeListener(listener) + fun removeListener(listener: DownloadQueue.DownloadListener) = queue.removeListener(listener) } 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 8a2ea643cd..f8f7ea301c 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 @@ -6,7 +6,6 @@ import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.download.model.Download -import eu.kanade.tachiyomi.data.download.model.DownloadQueue import eu.kanade.tachiyomi.data.notification.NotificationHandler import eu.kanade.tachiyomi.data.notification.NotificationReceiver import eu.kanade.tachiyomi.data.notification.Notifications @@ -93,8 +92,7 @@ internal class DownloadNotifier(private val context: Context) { setContentText( context.getString(R.string.chapter_downloading) ) - } - else { + } else { setContentTitle( context.getString( R.string.chapter_downloading @@ -102,12 +100,11 @@ internal class DownloadNotifier(private val context: Context) { ) setContentText(null) } - setProgress(0,0, true) + setProgress(0, 0, true) setStyle(null) } // Displays the progress bar on notification notification.show() - } /** @@ -164,7 +161,7 @@ internal class DownloadNotifier(private val context: Context) { context.getString(R.string.action_resume), NotificationReceiver.resumeDownloadsPendingBroadcast(context) ) - //Clear action + // Clear action addAction( R.drawable.ic_clear_grey_24dp_img, context.getString(R.string.action_cancel_all), diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt index 1a0b29311a..d81ae629a1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt @@ -136,28 +136,28 @@ class DownloadPendingDeleter(context: Context) { * Class used to save an entry of chapters with their manga into preferences. */ private data class Entry( - val chapters: List, - val manga: MangaEntry + val chapters: List, + val manga: MangaEntry ) /** * Class used to save an entry for a chapter into preferences. */ private data class ChapterEntry( - val id: Long, - val url: String, - val name: String, - val scanlator: String? + val id: Long, + val url: String, + val name: String, + val scanlator: String? ) /** * Class used to save an entry for a manga into preferences. */ private data class MangaEntry( - val id: Long, - val url: String, - val title: String, - val source: Long + val id: Long, + val url: String, + val title: String, + val source: Long ) /** @@ -194,5 +194,4 @@ class DownloadPendingDeleter(context: Context) { it.name = name } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt index 03990d25ba..dc08390728 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt @@ -37,9 +37,8 @@ class DownloadProvider(private val context: Context) { } init { - preferences.downloadsDirectory().asObservable() - .skip(1) - .subscribe { downloadsDir = UniFile.fromUri(context, Uri.parse(it)) } + preferences.downloadsDirectory().asObservable().skip(1) + .subscribe { downloadsDir = UniFile.fromUri(context, Uri.parse(it)) } } /** @@ -50,9 +49,8 @@ class DownloadProvider(private val context: Context) { */ internal fun getMangaDir(manga: Manga, source: Source): UniFile { try { - return downloadsDir - .createDirectory(getSourceDirName(source)) - .createDirectory(getMangaDirName(manga)) + return downloadsDir.createDirectory(getSourceDirName(source)) + .createDirectory(getMangaDirName(manga)) } catch (e: NullPointerException) { throw Exception(context.getString(R.string.invalid_download_dir)) } @@ -136,8 +134,6 @@ class DownloadProvider(private val context: Context) { val sourceDir = findSourceDir(source) val mangaDir = sourceDir?.findFile(DiskUtil.buildValidFilename(from)) mangaDir?.renameTo(to) - // val downloadManager:DownloadManager by injectLazy() - // downloadManager.renameCache(from, to, sourceId) } /** @@ -147,7 +143,11 @@ class DownloadProvider(private val context: Context) { * @param manga the manga of the chapter. * @param source the source of the chapter. */ - fun findUnmatchedChapterDirs(chapters: List, manga: Manga, source: Source): List { + fun findUnmatchedChapterDirs( + chapters: List, + manga: Manga, + source: Source + ): List { val mangaDir = findMangaDir(manga, source) ?: return emptyList() return mangaDir.listFiles()!!.asList().filter { (chapters.find { chp -> @@ -170,7 +170,6 @@ class DownloadProvider(private val context: Context) { return chapters.mapNotNull { mangaDir.findFile("${getChapterDirName(it)}_tmp") } } - /** * Returns the download directory name for a source. * @@ -213,5 +212,4 @@ class DownloadProvider(private val context: Context) { DiskUtil.buildValidFilename(chapter.name) ) } - } 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 423455290d..0097366bc1 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 @@ -221,7 +221,6 @@ class DownloadService : Service() { .setContentTitle(getString(R.string.download_notifier_downloader_title)) .build() } - } interface DownloadServiceListener { 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 e9754053c0..cfa82a2753 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 @@ -15,8 +15,8 @@ import uy.kohesive.injekt.injectLazy * @param context the application context. */ class DownloadStore( - context: Context, - private val sourceManager: SourceManager + context: Context, + private val sourceManager: SourceManager ) { /** @@ -133,5 +133,4 @@ class DownloadStore( * @param order the order of the download in the queue. */ data class DownloadObject(val mangaId: Long, val chapterId: Long, val order: Int) - } 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 9c1e0c90cb..c7207c6c76 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 @@ -21,6 +21,7 @@ import eu.kanade.tachiyomi.util.storage.saveTo import eu.kanade.tachiyomi.util.system.ImageUtil import eu.kanade.tachiyomi.util.system.launchNow import eu.kanade.tachiyomi.util.system.launchUI +import java.io.File import kotlinx.coroutines.async import okhttp3.Response import rx.Observable @@ -28,7 +29,6 @@ import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import timber.log.Timber -import java.io.File /** * This class is the one in charge of downloading chapters. @@ -45,10 +45,10 @@ import java.io.File * @param sourceManager the source manager. */ class Downloader( - private val context: Context, - private val provider: DownloadProvider, - private val cache: DownloadCache, - private val sourceManager: SourceManager + private val context: Context, + private val provider: DownloadProvider, + private val cache: DownloadCache, + private val sourceManager: SourceManager ) { /** @@ -129,12 +129,11 @@ class Downloader( if (notifier.paused) { if (queue.isEmpty()) { notifier.dismiss() - } - else { + } else { notifier.paused = false notifier.onDownloadPaused() } - }else { + } else { notifier.dismiss() } } @@ -164,7 +163,7 @@ class Downloader( fun clearQueue(isNotification: Boolean = false) { destroySubscriptions() - //Needed to update the chapter view + // Needed to update the chapter view if (isNotification) { queue .filter { it.status == Download.QUEUE } @@ -180,7 +179,7 @@ class Downloader( * @param isNotification value that determines if status is set (needed for view updates) */ fun clearQueue(manga: Manga, isNotification: Boolean = false) { - //Needed to update the chapter view + // Needed to update the chapter view if (isNotification) { queue .filter { it.status == Download.QUEUE && it.manga.id == manga.id } @@ -318,7 +317,6 @@ class Downloader( notifier.onError(error.message, download.chapter.name) download } - } /** @@ -448,8 +446,12 @@ class Downloader( * @param tmpDir the directory where the download is currently stored. * @param dirname the real (non temporary) directory name of the download. */ - private fun ensureSuccessfulDownload(download: Download, mangaDir: UniFile, - tmpDir: UniFile, dirname: String) { + private fun ensureSuccessfulDownload( + download: Download, + mangaDir: UniFile, + tmpDir: UniFile, + dirname: String + ) { // Ensure that the chapter folder has all the images. val downloadedImages = tmpDir.listFiles().orEmpty().filterNot { it.name!!.endsWith(".tmp") } @@ -497,5 +499,4 @@ class Downloader( companion object { const val TMP_DIR_SUFFIX = "_tmp" } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/download/model/Download.kt b/app/src/main/java/eu/kanade/tachiyomi/data/download/model/Download.kt index 4ac514f732..8ef7af7ee5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/download/model/Download.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/download/model/Download.kt @@ -47,4 +47,4 @@ class Download(val source: HttpSource, val manga: Manga, val chapter: Chapter) { const val DOWNLOADED = 3 const val ERROR = 4 } -} \ No newline at end of file +} 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 fa9f857c88..bc2bd78036 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 @@ -5,14 +5,15 @@ import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.DownloadStore import eu.kanade.tachiyomi.source.model.Page +import java.util.concurrent.CopyOnWriteArrayList import rx.Observable import rx.subjects.PublishSubject -import java.util.concurrent.CopyOnWriteArrayList class DownloadQueue( - private val store: DownloadStore, - private val queue: MutableList = CopyOnWriteArrayList()) -: List by queue { + private val store: DownloadStore, + private val queue: MutableList = CopyOnWriteArrayList() +) : +List by queue { private val statusSubject = PublishSubject.create() @@ -89,8 +90,7 @@ class DownloadQueue( } else if (download.status == Download.DOWNLOADED || download.status == Download.ERROR) { setPagesSubject(download.pages, null) downloadListeners.forEach { it.updateDownload(download) } - } - else { + } else { downloadListeners.forEach { it.updateDownload(download) } } } @@ -111,7 +111,6 @@ class DownloadQueue( .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) } @@ -140,5 +139,4 @@ class DownloadQueue( interface DownloadListener { fun updateDownload(download: Download) } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/glide/FileFetcher.kt b/app/src/main/java/eu/kanade/tachiyomi/data/glide/FileFetcher.kt index a795e2e059..6f88ec722d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/glide/FileFetcher.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/glide/FileFetcher.kt @@ -5,7 +5,11 @@ import android.util.Log import com.bumptech.glide.Priority import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.data.DataFetcher -import java.io.* +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.IOException +import java.io.InputStream open class FileFetcher(private val file: File) : DataFetcher { @@ -48,4 +52,4 @@ open class FileFetcher(private val file: File) : DataFetcher { override fun getDataSource(): DataSource { return DataSource.LOCAL } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/glide/LibraryMangaUrlFetcher.kt b/app/src/main/java/eu/kanade/tachiyomi/data/glide/LibraryMangaUrlFetcher.kt index 5fec42af7a..f27f6e5363 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/glide/LibraryMangaUrlFetcher.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/glide/LibraryMangaUrlFetcher.kt @@ -16,10 +16,12 @@ import java.io.InputStream * @param manga the manga of the cover to load. * @param file the file where this cover should be. It may exists or not. */ -class LibraryMangaUrlFetcher(private val networkFetcher: DataFetcher, - private val manga: Manga, - private val file: File) -: FileFetcher(file) { +class LibraryMangaUrlFetcher( + private val networkFetcher: DataFetcher, + private val manga: Manga, + private val file: File +) : +FileFetcher(file) { override fun loadData(priority: Priority, callback: DataFetcher.DataCallback) { if (!file.exists()) { @@ -52,7 +54,6 @@ class LibraryMangaUrlFetcher(private val networkFetcher: DataFetcher { * @param width the width of the view where the resource will be loaded. * @param height the height of the view where the resource will be loaded. */ - override fun buildLoadData(manga: Manga, width: Int, height: Int, - options: Options): ModelLoader.LoadData? { + override fun buildLoadData( + manga: Manga, + width: Int, + height: Int, + options: Options + ): ModelLoader.LoadData? { // Check thumbnail is not null or empty val url = manga.thumbnail_url if (url == null || url.isEmpty()) { @@ -142,5 +150,4 @@ class MangaModelLoader : ModelLoader { value } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/glide/MangaSignature.kt b/app/src/main/java/eu/kanade/tachiyomi/data/glide/MangaSignature.kt index aa3ebf6f95..cdf880e426 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/glide/MangaSignature.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/glide/MangaSignature.kt @@ -24,4 +24,4 @@ class MangaSignature(manga: Manga, file: File) : Key { override fun updateDiskCacheKey(md: MessageDigest) { md.update(key.toByteArray(Key.CHARSET)) } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/glide/PassthroughModelLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/data/glide/PassthroughModelLoader.kt index bb117086e3..dd6d546f8c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/glide/PassthroughModelLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/glide/PassthroughModelLoader.kt @@ -14,10 +14,10 @@ import java.io.InputStream class PassthroughModelLoader : ModelLoader { override fun buildLoadData( - model: InputStream, - width: Int, - height: Int, - options: Options + model: InputStream, + width: Int, + height: Int, + options: Options ): ModelLoader.LoadData? { return ModelLoader.LoadData(ObjectKey(model), Fetcher(model)) } @@ -49,12 +49,11 @@ class PassthroughModelLoader : ModelLoader { } override fun loadData( - priority: Priority, - callback: DataFetcher.DataCallback + priority: Priority, + callback: DataFetcher.DataCallback ) { callback.onDataReady(stream) } - } /** @@ -63,12 +62,11 @@ class PassthroughModelLoader : ModelLoader { class Factory : ModelLoaderFactory { override fun build( - multiFactory: MultiModelLoaderFactory + multiFactory: MultiModelLoaderFactory ): ModelLoader { return PassthroughModelLoader() } override fun teardown() {} } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/glide/TachiGlideModule.kt b/app/src/main/java/eu/kanade/tachiyomi/data/glide/TachiGlideModule.kt index 99c56dd085..5270e3ebd5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/glide/TachiGlideModule.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/glide/TachiGlideModule.kt @@ -13,9 +13,9 @@ import com.bumptech.glide.module.AppGlideModule import com.bumptech.glide.request.RequestOptions import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.network.NetworkHelper +import java.io.InputStream import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.InputStream /** * Class used to update Glide module settings @@ -26,8 +26,8 @@ class TachiGlideModule : AppGlideModule() { override fun applyOptions(context: Context, builder: GlideBuilder) { builder.setDiskCache(InternalCacheDiskCacheFactory(context, 50 * 1024 * 1024)) builder.setDefaultRequestOptions(RequestOptions().format(DecodeFormat.PREFER_RGB_565)) - //val memoryCacheSizeBytes = 1024 * 1024 * 100 // 100mb - //builder.setMemoryCache(LruResourceCache(memoryCacheSizeBytes.toLong())) + // val memoryCacheSizeBytes = 1024 * 1024 * 100 // 100mb + // builder.setMemoryCache(LruResourceCache(memoryCacheSizeBytes.toLong())) /* builder.setDefaultTransitionOptions( Drawable::class.java, 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 01698a5ce0..4dee9f1997 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 @@ -5,9 +5,9 @@ import com.evernote.android.job.JobManager import com.evernote.android.job.JobRequest import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault +import java.util.concurrent.TimeUnit import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.concurrent.TimeUnit class LibraryUpdateJob : Job() { 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 d53cb5c90a..18f3fc2485 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 @@ -39,5 +39,4 @@ object LibraryUpdateRanker { compareValues(mangaFirst.currentTitle(), mangaSecond.currentTitle()) } } - -} \ No newline at end of file +} 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 847e942423..1092eb0e5d 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 @@ -38,6 +38,10 @@ import eu.kanade.tachiyomi.util.chapter.syncChaptersWithSource import eu.kanade.tachiyomi.util.lang.chop import eu.kanade.tachiyomi.util.system.notification import eu.kanade.tachiyomi.util.system.notificationManager +import java.util.ArrayList +import java.util.Date +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope @@ -50,10 +54,6 @@ import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.ArrayList -import java.util.Date -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicInteger /** * This class will take care of updating the chapters of the manga from the library. It can be @@ -127,8 +127,8 @@ class LibraryUpdateService( */ enum class Target { CHAPTERS, // Manga chapters - DETAILS, // Manga metadata - TRACKING // Tracking metadata + DETAILS, // Manga metadata + TRACKING // Tracking metadata } companion object { 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 2a02bb2a60..2a53d2ab58 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 @@ -10,6 +10,7 @@ import android.content.Intent import android.net.Uri import android.os.Build import android.os.Handler +import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.backup.BackupRestoreService import eu.kanade.tachiyomi.data.database.DatabaseHelper @@ -27,12 +28,10 @@ import eu.kanade.tachiyomi.util.storage.DiskUtil import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.system.notificationManager import eu.kanade.tachiyomi.util.system.toast +import java.io.File import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy -import java.io.File -import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID - /** * Global [BroadcastReceiver] that runs on UI thread @@ -113,7 +112,6 @@ class NotificationReceiver : BroadcastReceiver() { type = "image/*" } // Close Navigation Shade - } /** @@ -217,7 +215,6 @@ class NotificationReceiver : BroadcastReceiver() { // Called to cancel restore private const val ACTION_CANCEL_RESTORE = "$ID.$NAME.CANCEL_RESTORE" - // Called to open chapter private const val ACTION_OPEN_CHAPTER = "$ID.$NAME.ACTION_OPEN_CHAPTER" @@ -322,8 +319,12 @@ class NotificationReceiver : BroadcastReceiver() { * @param notificationId id of notification * @return [PendingIntent] */ - internal fun dismissNotification(context: Context, notificationId: Int, groupId: Int? = - null) { + internal fun dismissNotification( + context: Context, + notificationId: Int, + groupId: Int? = + null + ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val groupKey = context.notificationManager.activeNotifications.find { it.id == notificationId @@ -350,7 +351,7 @@ class NotificationReceiver : BroadcastReceiver() { * @return [PendingIntent] */ internal fun shareImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent { - //val shareIntent = ShareStartingActivity.newIntent(context, path) + // val shareIntent = ShareStartingActivity.newIntent(context, path) val shareIntent = Intent(Intent.ACTION_SEND).apply { val uri = File(path).getUriCompat(context) putExtra(Intent.EXTRA_STREAM, uri) @@ -358,7 +359,7 @@ class NotificationReceiver : BroadcastReceiver() { clipData = ClipData.newRawUri(null, uri) type = "image/*" } - //val shareIntent2 = Intent.createChooser(shareIntent, context.getString(R.string.action_share)) + // val shareIntent2 = Intent.createChooser(shareIntent, context.getString(R.string.action_share)) return PendingIntent.getActivity(context, 0, shareIntent, PendingIntent .FLAG_CANCEL_CURRENT) } @@ -387,8 +388,12 @@ class NotificationReceiver : BroadcastReceiver() { * @param manga manga of chapter * @param chapter chapter that needs to be opened */ - internal fun openChapterPendingActivity(context: Context, manga: Manga, chapter: - Chapter): PendingIntent { + internal fun openChapterPendingActivity( + context: Context, + manga: Manga, + chapter: + Chapter + ): PendingIntent { val newIntent = ReaderActivity.newIntent(context, manga, chapter) return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent .FLAG_UPDATE_CURRENT) @@ -440,15 +445,19 @@ class NotificationReceiver : BroadcastReceiver() { return PendingIntent.getActivity(context, 0, toLaunch, 0) } - /** * Returns [PendingIntent] that marks a chapter as read and deletes it if preferred * * @param context context of application * @param manga manga of chapter */ - internal fun markAsReadPendingBroadcast(context: Context, manga: Manga, chapters: - Array, groupId: Int): + internal fun markAsReadPendingBroadcast( + context: Context, + manga: Manga, + chapters: + Array, + groupId: Int + ): PendingIntent { val newIntent = Intent(context, NotificationReceiver::class.java).apply { action = ACTION_MARK_AS_READ @@ -486,4 +495,4 @@ class NotificationReceiver : BroadcastReceiver() { return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } } -} \ No newline at end of file +} 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 08ee6201e2..2e5371e280 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 @@ -38,6 +38,7 @@ object Notifications { const val CHANNEL_NEW_CHAPTERS = "new_chapters_channel" const val ID_NEW_CHAPTERS = -301 const val GROUP_NEW_CHAPTERS = "eu.kanade.tachiyomi.NEW_CHAPTERS" + /** * Notification channel and ids used by the library updater. */ @@ -49,7 +50,6 @@ object Notifications { const val ID_RESTORE_COMPLETE = -502 const val ID_RESTORE_ERROR = -503 - /** * Creates the notification channels introduced in Android Oreo. * @@ -58,36 +58,37 @@ 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.channel_common), - NotificationManager.IMPORTANCE_LOW - ), NotificationChannel( - CHANNEL_LIBRARY, - context.getString(R.string.channel_library_updates), - NotificationManager.IMPORTANCE_LOW - ).apply { - setShowBadge(false) - }, NotificationChannel( - CHANNEL_DOWNLOADER, - context.getString(R.string.channel_downloader), - NotificationManager.IMPORTANCE_LOW - ).apply { - setShowBadge(false) - }, NotificationChannel( - CHANNEL_UPDATES_TO_EXTS, - context.getString(R.string.channel_ext_updates), - NotificationManager.IMPORTANCE_DEFAULT - ), NotificationChannel( - CHANNEL_NEW_CHAPTERS, - context.getString(R.string.channel_new_chapters), - NotificationManager.IMPORTANCE_DEFAULT - ), NotificationChannel(CHANNEL_RESTORE, context.getString(R.string.channel_backup_restore), - NotificationManager.IMPORTANCE_LOW).apply { - setShowBadge(false) - } - ) + val channels = listOf(NotificationChannel( + CHANNEL_COMMON, + context.getString(R.string.channel_common), + NotificationManager.IMPORTANCE_LOW + ), NotificationChannel( + CHANNEL_LIBRARY, + context.getString(R.string.channel_library_updates), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + }, NotificationChannel( + CHANNEL_DOWNLOADER, + context.getString(R.string.channel_downloader), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + }, NotificationChannel( + CHANNEL_UPDATES_TO_EXTS, + context.getString(R.string.channel_ext_updates), + NotificationManager.IMPORTANCE_DEFAULT + ), NotificationChannel( + CHANNEL_NEW_CHAPTERS, + context.getString(R.string.channel_new_chapters), + NotificationManager.IMPORTANCE_DEFAULT + ), NotificationChannel( + CHANNEL_RESTORE, + context.getString(R.string.channel_backup_restore), + NotificationManager.IMPORTANCE_LOW + ).apply { + setShowBadge(false) + }) context.notificationManager.createNotificationChannels(channels) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt b/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt index 02c1011bbd..1fafd9d93d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt @@ -155,11 +155,9 @@ object PreferenceKeys { fun sourceSharedPref(sourceId: Long) = "source_$sourceId" - fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId" fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId" fun trackToken(syncId: Int) = "track_token_$syncId" - } 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 486851cdda..d973f11764 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 @@ -8,13 +8,13 @@ import androidx.preference.PreferenceManager import com.f2prateek.rx.preferences.Preference import com.f2prateek.rx.preferences.RxSharedPreferences import eu.kanade.tachiyomi.R +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.source.Source import java.io.File import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Locale -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys fun Preference.getOrDefault(): T = get() ?: defaultValue()!! diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt index 4cb4a2deb6..173a6ffd6f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/TrackManager.kt @@ -2,10 +2,10 @@ package eu.kanade.tachiyomi.data.track import android.content.Context import eu.kanade.tachiyomi.data.track.anilist.Anilist +import eu.kanade.tachiyomi.data.track.bangumi.Bangumi import eu.kanade.tachiyomi.data.track.kitsu.Kitsu import eu.kanade.tachiyomi.data.track.myanimelist.MyAnimeList import eu.kanade.tachiyomi.data.track.shikimori.Shikimori -import eu.kanade.tachiyomi.data.track.bangumi.Bangumi class TrackManager(context: Context) { @@ -32,5 +32,4 @@ class TrackManager(context: Context) { fun getService(id: Int) = services.find { it.id == id } fun hasLoggedServices() = services.any { it.isLogged } - } 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 8b2165952e..e8a2930ff7 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 @@ -3,8 +3,8 @@ package eu.kanade.tachiyomi.data.track import androidx.annotation.CallSuper import androidx.annotation.DrawableRes import eu.kanade.tachiyomi.data.database.models.Track -import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.data.preference.PreferencesHelper +import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.NetworkHelper import okhttp3.OkHttpClient import uy.kohesive.injekt.injectLazy diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt index 7ce286ddd5..b536909fa6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt @@ -7,7 +7,6 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.track.TrackService -import eu.kanade.tachiyomi.data.track.model.TrackSearch import timber.log.Timber import uy.kohesive.injekt.injectLazy @@ -144,25 +143,24 @@ class Anilist(private val context: Context, id: Int) : TrackService(id) { track.copyPersonalFrom(remoteTrack) track.total_chapters = remoteTrack.total_chapters return track - } override suspend fun login(username: String, password: String) = login(password) - suspend fun login(token: String): Boolean { + suspend fun login(token: String): Boolean { val oauth = api.createOAuth(token) interceptor.setAuth(oauth) - return try { - val currentUser = api.getCurrentUser() - scorePreference.set(currentUser.second) - saveCredentials(currentUser.first.toString(), oauth.access_token) - true - } catch (e: Exception) { - Timber.e(e) - logout() - false - } + return try { + val currentUser = api.getCurrentUser() + scorePreference.set(currentUser.second) + saveCredentials(currentUser.first.toString(), oauth.access_token) + true + } catch (e: Exception) { + Timber.e(e) + logout() + false + } } override fun logout() { @@ -184,7 +182,6 @@ class Anilist(private val context: Context, id: Int) : TrackService(id) { } } - companion object { const val READING = 1 const val COMPLETED = 2 @@ -202,6 +199,4 @@ class Anilist(private val context: Context, id: Int) : TrackService(id) { const val POINT_5 = "POINT_5" const val POINT_3 = "POINT_3" } - } - 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 8473a54c6e..2e08404134 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 @@ -12,6 +12,8 @@ import com.google.gson.JsonParser import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.jsonType +import java.util.Calendar +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.MediaType @@ -19,8 +21,6 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response -import java.util.Calendar -import java.util.concurrent.TimeUnit class AnilistApi(val client: OkHttpClient, interceptor: AnilistInterceptor) { 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 90ca64ffb9..8c9e33bf89 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 @@ -3,7 +3,6 @@ package eu.kanade.tachiyomi.data.track.anilist import okhttp3.Interceptor import okhttp3.Response - class AnilistInterceptor(private val anilist: Anilist, private var token: String?) : Interceptor { /** @@ -23,7 +22,7 @@ class AnilistInterceptor(private val anilist: Anilist, private var token: String if (token.isNullOrEmpty()) { throw Exception("Not authenticated with Anilist") } - if (oauth == null){ + if (oauth == null) { oauth = anilist.loadOAuth() } // Refresh access token if null or expired. @@ -54,5 +53,4 @@ class AnilistInterceptor(private val anilist: Anilist, private var token: String this.oauth = oauth anilist.saveOAuth(oauth) } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt index ea7f391762..e758167d59 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt @@ -5,28 +5,30 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch -import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Locale +import uy.kohesive.injekt.injectLazy data class OAuth( val access_token: String, val token_type: String, val expires: Long, - val expires_in: Long) { + val expires_in: Long +) { fun isExpired() = System.currentTimeMillis() > expires } data class ALManga( - val media_id: Int, - val title_romaji: String, - val image_url_lge: String, - val description: String?, - val type: String, - val publishing_status: String, - val start_date_fuzzy: Long, - val total_chapters: Int) { + val media_id: Int, + val title_romaji: String, + val image_url_lge: String, + val description: String?, + val type: String, + val publishing_status: String, + val start_date_fuzzy: Long, + val total_chapters: Int +) { fun toTrack() = TrackSearch.create(TrackManager.ANILIST).apply { media_id = this@ALManga.media_id diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Bangumi.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Bangumi.kt index 31fdc880ba..c75cac8e27 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Bangumi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Bangumi.kt @@ -60,12 +60,12 @@ class Bangumi(private val context: Context, id: Int) : TrackService(id) { override suspend fun refresh(track: Track): Track { val statusTrack = api.statusLibManga(track) track.copyPersonalFrom(statusTrack!!) - val remoteTrack = api.findLibManga(track) - if(remoteTrack != null){ + val remoteTrack = api.findLibManga(track) + if (remoteTrack != null) { track.total_chapters = remoteTrack.total_chapters track.status = remoteTrack.status } - return track + return track } override fun getLogo() = R.drawable.tracker_bangumi diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt index d24f50b042..6ad1bef277 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt @@ -11,6 +11,7 @@ import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.await +import java.net.URLEncoder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.CacheControl @@ -18,7 +19,6 @@ import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import uy.kohesive.injekt.injectLazy -import java.net.URLEncoder class BangumiApi(private val client: OkHttpClient, interceptor: BangumiInterceptor) { @@ -26,14 +26,10 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept private val authClient = client.newBuilder().addInterceptor(interceptor).build() suspend fun addLibManga(track: Track): Track { - val body = FormBody.Builder() - .add("rating", track.score.toInt().toString()) - .add("status", track.toBangumiStatus()) - .build() - val request = Request.Builder() - .url("$apiUrl/collection/${track.media_id}/update") - .post(body) - .build() + val body = FormBody.Builder().add("rating", track.score.toInt().toString()) + .add("status", track.toBangumiStatus()).build() + val request = + Request.Builder().url("$apiUrl/collection/${track.media_id}/update").post(body).build() val response = authClient.newCall(request).await() return track } @@ -41,22 +37,17 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept suspend fun updateLibManga(track: Track): Track { // chapter update return withContext(Dispatchers.IO) { - val body = FormBody.Builder() - .add("watched_eps", track.last_chapter_read.toString()) - .build() - val request = Request.Builder() - .url("$apiUrl/subject/${track.media_id}/update/watched_eps") - .post(body) - .build() + val body = + FormBody.Builder().add("watched_eps", track.last_chapter_read.toString()).build() + val request = + Request.Builder().url("$apiUrl/subject/${track.media_id}/update/watched_eps") + .post(body).build() // read status update - val sbody = FormBody.Builder() - .add("status", track.toBangumiStatus()) - .build() - val srequest = Request.Builder() - .url("$apiUrl/collection/${track.media_id}/update") - .post(sbody) - .build() + val sbody = FormBody.Builder().add("status", track.toBangumiStatus()).build() + val srequest = + Request.Builder().url("$apiUrl/collection/${track.media_id}/update").post(sbody) + .build() authClient.newCall(srequest).execute() authClient.newCall(request).execute() track @@ -67,13 +58,8 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept return withContext(Dispatchers.IO) { val url = Uri.parse( "$apiUrl/search/subject/${URLEncoder.encode(search, Charsets.UTF_8.name())}" - ).buildUpon() - .appendQueryParameter("max_results", "20") - .build() - val request = Request.Builder() - .url(url.toString()) - .get() - .build() + ).buildUpon().appendQueryParameter("max_results", "20").build() + val request = Request.Builder().url(url.toString()).get().build() val netResponse = authClient.newCall(request).await() var responseBody = netResponse.body?.string().orEmpty() @@ -106,9 +92,9 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept return Track.create(TrackManager.BANGUMI).apply { title = mangas["name"].asString media_id = mangas["id"].asInt - score = if (mangas["rating"] != null) - (if (mangas["rating"].isJsonObject) mangas["rating"].obj["score"].asFloat else 0f) - else 0f + score = + if (mangas["rating"] != null) (if (mangas["rating"].isJsonObject) mangas["rating"].obj["score"].asFloat else 0f) + else 0f status = Bangumi.DEFAULT_STATUS tracking_url = mangas["url"].asString } @@ -117,10 +103,7 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept suspend fun findLibManga(track: Track): Track? { return withContext(Dispatchers.IO) { val urlMangas = "$apiUrl/subject/${track.media_id}" - val requestMangas = Request.Builder() - .url(urlMangas) - .get() - .build() + val requestMangas = Request.Builder().url(urlMangas).get().build() val netResponse = authClient.newCall(requestMangas).execute() val responseBody = netResponse.body?.string().orEmpty() jsonToTrack(JsonParser.parseString(responseBody).obj) @@ -129,11 +112,9 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept suspend fun statusLibManga(track: Track): Track? { val urlUserRead = "$apiUrl/collection/${track.media_id}" - val requestUserRead = Request.Builder() - .url(urlUserRead) - .cacheControl(CacheControl.FORCE_NETWORK) - .get() - .build() + val requestUserRead = + Request.Builder().url(urlUserRead).cacheControl(CacheControl.FORCE_NETWORK).get() + .build() // todo get user readed chapter here val response = authClient.newCall(requestUserRead).await() @@ -145,10 +126,10 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept } suspend fun accessToken(code: String): OAuth { - return withContext(Dispatchers.IO){ - val netResponse = client.newCall(accessTokenRequest(code)).execute() + return withContext(Dispatchers.IO) { + val netResponse = client.newCall(accessTokenRequest(code)).execute() val responseBody = netResponse.body?.string().orEmpty() - if(responseBody.isEmpty()){ + if (responseBody.isEmpty()) { throw Exception("Null Response") } gson.fromJson(responseBody, OAuth::class.java) @@ -157,12 +138,8 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept private fun accessTokenRequest(code: String) = POST( oauthUrl, - body = FormBody.Builder() - .add("grant_type", "authorization_code") - .add("client_id", clientId) - .add("client_secret", clientSecret) - .add("code", code) - .add("redirect_uri", redirectUrl) + body = FormBody.Builder().add("grant_type", "authorization_code").add("client_id", clientId) + .add("client_secret", clientSecret).add("code", code).add("redirect_uri", redirectUrl) .build() ) @@ -182,22 +159,15 @@ class BangumiApi(private val client: OkHttpClient, interceptor: BangumiIntercept return "$baseMangaUrl/$remoteId" } - fun authUrl() = - Uri.parse(loginUrl).buildUpon() - .appendQueryParameter("client_id", clientId) - .appendQueryParameter("response_type", "code") - .appendQueryParameter("redirect_uri", redirectUrl) - .build() + fun authUrl() = Uri.parse(loginUrl).buildUpon().appendQueryParameter("client_id", clientId) + .appendQueryParameter("response_type", "code") + .appendQueryParameter("redirect_uri", redirectUrl).build() fun refreshTokenRequest(token: String) = POST( oauthUrl, - body = FormBody.Builder() - .add("grant_type", "refresh_token") - .add("client_id", clientId) - .add("client_secret", clientSecret) - .add("refresh_token", token) - .add("redirect_uri", redirectUrl) - .build() + body = FormBody.Builder().add("grant_type", "refresh_token").add("client_id", clientId) + .add("client_secret", clientSecret).add("refresh_token", token) + .add("redirect_uri", redirectUrl).build() ) } } 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 fc2617d335..261f997524 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 @@ -59,7 +59,7 @@ class BangumiInterceptor(val bangumi: Bangumi, val gson: Gson) : Interceptor { bangumi.saveToken(oauth) } - fun clearOauth(){ + fun clearOauth() { bangumi.saveToken(null) } } 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 db0d8396c0..5045677e9c 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 @@ -1,49 +1,47 @@ package eu.kanade.tachiyomi.data.track.bangumi data class Collection( - val `private`: Int? = 0, - val comment: String? = "", - val ep_status: Int? = 0, - val lasttouch: Int? = 0, - val rating: Int? = 0, - val status: Status? = Status(), - val tag: List? = listOf(), - val user: User? = User(), - val vol_status: Int? = 0 + val `private`: Int? = 0, + val comment: String? = "", + val ep_status: Int? = 0, + val lasttouch: Int? = 0, + val rating: Int? = 0, + val status: Status? = Status(), + val tag: List? = listOf(), + val user: User? = User(), + val vol_status: Int? = 0 ) data class OAuth( - val access_token: String, - val token_type: String, - val created_at: Long, - val expires_in: Long, - val refresh_token: String?, - val user_id: Long? + val access_token: String, + val token_type: String, + val created_at: Long, + val expires_in: Long, + val refresh_token: String?, + val user_id: Long? ) { // Access token refresh before expired fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) } data class Status( - val id: Int? = 0, - val name: String? = "", - val type: String? = "" + val id: Int? = 0, + val name: String? = "", + val type: String? = "" ) data class User( - val avatar: Avatar? = Avatar(), - val id: Int? = 0, - val nickname: String? = "", - val sign: String? = "", - val url: String? = "", - val usergroup: Int? = 0, - val username: String? = "" + val avatar: Avatar? = Avatar(), + val id: Int? = 0, + val nickname: String? = "", + val sign: String? = "", + val url: String? = "", + val usergroup: Int? = 0, + val username: String? = "" ) data class Avatar( - val large: String? = "", - val medium: String? = "", - val small: String? = "" + val large: String? = "", + val medium: String? = "", + val small: String? = "" ) - - diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/Kitsu.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/Kitsu.kt index f1993860e3..4e09b66661 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/Kitsu.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/Kitsu.kt @@ -7,9 +7,9 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.model.TrackSearch +import java.text.DecimalFormat import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.text.DecimalFormat class Kitsu(private val context: Context, id: Int) : TrackService(id) { 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 44b874bea7..1f1d4e8f2a 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 @@ -42,5 +42,4 @@ class KitsuInterceptor(val kitsu: Kitsu, val gson: Gson) : Interceptor { this.oauth = oauth kitsu.saveToken(oauth) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuModels.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuModels.kt index 5e709e810f..9664d87924 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuModels.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuModels.kt @@ -1,13 +1,19 @@ package eu.kanade.tachiyomi.data.track.kitsu import androidx.annotation.CallSuper -import com.github.salomonbrys.kotson.* +import com.github.salomonbrys.kotson.byInt +import com.github.salomonbrys.kotson.byString +import com.github.salomonbrys.kotson.nullInt +import com.github.salomonbrys.kotson.nullObj +import com.github.salomonbrys.kotson.nullString +import com.github.salomonbrys.kotson.obj import com.google.gson.JsonObject import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale class KitsuSearchManga(obj: JsonObject) { val id by obj.byInt @@ -40,7 +46,6 @@ class KitsuSearchManga(obj: JsonObject) { } } - class KitsuLibManga(obj: JsonObject, manga: JsonObject) { val id by manga.byInt private val canonicalTitle by manga["attributes"].byString @@ -77,7 +82,6 @@ class KitsuLibManga(obj: JsonObject, manga: JsonObject) { "planned" -> Kitsu.PLAN_TO_READ else -> throw Exception("Unknown status") } - } fun Track.toKitsuStatus() = when (status) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/OAuth.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/OAuth.kt index 678567ce99..a10981c51e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/OAuth.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/OAuth.kt @@ -1,11 +1,12 @@ package eu.kanade.tachiyomi.data.track.kitsu data class OAuth( - val access_token: String, - val token_type: String, - val created_at: Long, - val expires_in: Long, - val refresh_token: String?) { + val access_token: String, + val token_type: String, + val created_at: Long, + val expires_in: Long, + val refresh_token: String? +) { fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/model/TrackSearch.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/model/TrackSearch.kt index a7fb8b80d2..fe8bb99aef 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/model/TrackSearch.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/model/TrackSearch.kt @@ -58,7 +58,5 @@ class TrackSearch : Track { fun create(serviceId: Int): TrackSearch = TrackSearch().apply { sync_id = serviceId } - } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt index d159c1607b..e55ca8c7f9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt @@ -108,7 +108,7 @@ class MyAnimeList(private val context: Context, id: Int) : TrackService(id) { } // Attempt to login again if cookies have been cleared but credentials are still filled - suspend fun ensureLoggedIn() { + suspend fun ensureLoggedIn() { if (isAuthorized) return if (!isLogged) throw Exception("MAL Login Credentials not found") @@ -131,8 +131,7 @@ class MyAnimeList(private val context: Context, id: Int) : TrackService(id) { var ckCount = 0 val url = BASE_URL.toHttpUrlOrNull()!! for (ck in networkService.cookieManager.get(url)) { - if (ck.name == USER_SESSION_COOKIE || ck.name == LOGGED_IN_COOKIE) - ckCount++ + if (ck.name == USER_SESSION_COOKIE || ck.name == LOGGED_IN_COOKIE) ckCount++ } return ckCount == 2 diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListApi.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListApi.kt index 4ea961fcb4..af94d88eb6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListApi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListApi.kt @@ -36,12 +36,10 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI val realQuery = query.take(100) val response = client.newCall(GET(searchUrl(realQuery))).await() val matches = Jsoup.parse(response.consumeBody()) - .select("div.js-categories-seasonal.js-block-list.list") - .select("table").select("tbody") - .select("tr").drop(1) + .select("div.js-categories-seasonal.js-block-list.list").select("table") + .select("tbody").select("tr").drop(1) - matches.filter { row -> row.select(TD)[2].text() != "Novel" } - .map { row -> + matches.filter { row -> row.select(TD)[2].text() != "Novel" }.map { row -> TrackSearch.create(TrackManager.MYANIMELIST).apply { title = row.searchTitle() media_id = row.searchMediaId() @@ -53,8 +51,7 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI publishing_type = row.searchPublishingType() start_date = row.searchStartDate() } - } - .toList() + }.toList() } } } @@ -117,9 +114,7 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI private suspend fun getSessionInfo(): String { val response = client.newCall(GET(loginUrl())).execute() - return Jsoup.parse(response.consumeBody()) - .select("meta[name=csrf_token]") - .attr("content") + return Jsoup.parse(response.consumeBody()).select("meta[name=csrf_token]").attr("content") } private suspend fun login(username: String, password: String, csrf: String) { @@ -147,18 +142,15 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI total_chapters = it.selectInt("manga_chapters") tracking_url = mangaUrl(media_id) } - } - .toList() + }.toList() } private suspend fun getListUrl(): String { - return withContext(Dispatchers.IO) { + return withContext(Dispatchers.IO) { val response = authClient.newCall(POST(url = exportListUrl(), body = exportPostBody())).execute() - baseUrl + Jsoup.parse(response.consumeBody()) - .select("div.goodresult") - .select("a") + baseUrl + Jsoup.parse(response.consumeBody()).select("div.goodresult").select("a") .attr("href") } } @@ -179,66 +171,43 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI private fun mangaUrl(remoteId: Int) = baseMangaUrl + remoteId - private fun loginUrl() = Uri.parse(baseUrl).buildUpon() - .appendPath("login.php") - .toString() + private fun loginUrl() = Uri.parse(baseUrl).buildUpon().appendPath("login.php").toString() private fun searchUrl(query: String): String { val col = "c[]" - return Uri.parse(baseUrl).buildUpon() - .appendPath("manga.php") - .appendQueryParameter("q", query) - .appendQueryParameter(col, "a") - .appendQueryParameter(col, "b") - .appendQueryParameter(col, "c") - .appendQueryParameter(col, "d") - .appendQueryParameter(col, "e") - .appendQueryParameter(col, "g") - .toString() + return Uri.parse(baseUrl).buildUpon().appendPath("manga.php") + .appendQueryParameter("q", query).appendQueryParameter(col, "a") + .appendQueryParameter(col, "b").appendQueryParameter(col, "c") + .appendQueryParameter(col, "d").appendQueryParameter(col, "e") + .appendQueryParameter(col, "g").toString() } - private fun exportListUrl() = Uri.parse(baseUrl).buildUpon() - .appendPath("panel.php") - .appendQueryParameter("go", "export") - .toString() + private fun exportListUrl() = Uri.parse(baseUrl).buildUpon().appendPath("panel.php") + .appendQueryParameter("go", "export").toString() - private fun updateUrl() = Uri.parse(baseModifyListUrl).buildUpon() - .appendPath("edit.json") - .toString() + private fun updateUrl() = + Uri.parse(baseModifyListUrl).buildUpon().appendPath("edit.json").toString() - private fun addUrl() = Uri.parse(baseModifyListUrl).buildUpon() - .appendPath("add.json") - .toString() + private fun addUrl() = + Uri.parse(baseModifyListUrl).buildUpon().appendPath("add.json").toString() - private fun listEntryUrl(mediaId: Int) = Uri.parse(baseModifyListUrl).buildUpon() - .appendPath(mediaId.toString()) - .appendPath("edit") - .toString() + private fun listEntryUrl(mediaId: Int) = + Uri.parse(baseModifyListUrl).buildUpon().appendPath(mediaId.toString()) + .appendPath("edit").toString() private fun loginPostBody(username: String, password: String, csrf: String): RequestBody { - return FormBody.Builder() - .add("user_name", username) - .add("password", password) - .add("cookie", "1") - .add("sublogin", "Login") - .add("submit", "1") - .add(CSRF, csrf) + return FormBody.Builder().add("user_name", username).add("password", password) + .add("cookie", "1").add("sublogin", "Login").add("submit", "1").add(CSRF, csrf) .build() } private fun exportPostBody(): RequestBody { - return FormBody.Builder() - .add("type", "2") - .add("subexport", "Export My List") - .build() + return FormBody.Builder().add("type", "2").add("subexport", "Export My List").build() } private fun mangaPostPayload(track: Track): RequestBody { - val body = JSONObject() - .put("manga_id", track.media_id) - .put("status", track.status) - .put("score", track.score) - .put("num_read_chapters", track.last_chapter_read) + val body = JSONObject().put("manga_id", track.media_id).put("status", track.status) + .put("score", track.score).put("num_read_chapters", track.last_chapter_read) return body.toString() .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull()) @@ -249,19 +218,13 @@ class MyAnimeListApi(private val client: OkHttpClient, interceptor: MyAnimeListI private fun Element.searchTotalChapters() = if (select(TD)[4].text() == "-") 0 else select(TD)[4].text().toInt() - private fun Element.searchCoverUrl() = select("img") - .attr("data-src") - .split("\\?")[0] - .replace("/r/50x70/", "/") + private fun Element.searchCoverUrl() = + select("img").attr("data-src").split("\\?")[0].replace("/r/50x70/", "/") - private fun Element.searchMediaId() = select("div.picSurround") - .select("a").attr("id") - .replace("sarea", "") - .toInt() + private fun Element.searchMediaId() = + select("div.picSurround").select("a").attr("id").replace("sarea", "").toInt() - private fun Element.searchSummary() = select("div.pt4") - .first() - .ownText()!! + private fun Element.searchSummary() = select("div.pt4").first().ownText()!! private fun Element.searchPublishingStatus() = if (select(TD).last().text() == "-") "Publishing" else "Finished" diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListInterceptor.kt index 2c9bb356fb..bc017f8479 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeListInterceptor.kt @@ -22,7 +22,6 @@ class MyAnimeListInterceptor(private val myanimelist: MyAnimeList) : Interceptor } val request = chain.request() return chain.proceed(updateRequest(request)) - } private fun updateRequest(request: Request): Request { diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/Shikimori.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/Shikimori.kt index cbcb088e0b..5ebd356cae 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/Shikimori.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/Shikimori.kt @@ -6,7 +6,6 @@ import com.google.gson.Gson import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackService -import eu.kanade.tachiyomi.data.track.model.TrackSearch import timber.log.Timber import uy.kohesive.injekt.injectLazy 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 e5ff4ca81d..42d24b51c8 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 @@ -13,7 +13,6 @@ import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST -import eu.kanade.tachiyomi.network.asObservableSuccess import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.FormBody @@ -44,10 +43,7 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter ) ) val body = payload.toString().toRequestBody(jsonime) - val request = Request.Builder() - .url("$apiUrl/v2/user_rates") - .post(body) - .build() + val request = Request.Builder().url("$apiUrl/v2/user_rates").post(body).build() authClient.newCall(request).execute() track } @@ -55,15 +51,11 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter suspend fun search(search: String): List { return withContext(Dispatchers.IO) { - val url = Uri.parse("$apiUrl/mangas").buildUpon() - .appendQueryParameter("order", "popularity") - .appendQueryParameter("search", search) - .appendQueryParameter("limit", "20") - .build() - val request = Request.Builder() - .url(url.toString()) - .get() - .build() + val url = + Uri.parse("$apiUrl/mangas").buildUpon().appendQueryParameter("order", "popularity") + .appendQueryParameter("search", search).appendQueryParameter("limit", "20") + .build() + val request = Request.Builder().url(url.toString()).get().build() val netResponse = authClient.newCall(request).execute() val responseBody = netResponse.body?.string().orEmpty() @@ -73,7 +65,6 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter val response = JsonParser.parseString(responseBody).array response.map { jsonToSearch(it.obj) } - } } @@ -108,20 +99,13 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter val url = Uri.parse("$apiUrl/v2/user_rates").buildUpon() .appendQueryParameter("user_id", user_id) .appendQueryParameter("target_id", track.media_id.toString()) - .appendQueryParameter("target_type", "Manga") - .build() - val request = Request.Builder() - .url(url.toString()) - .get() - .build() + .appendQueryParameter("target_type", "Manga").build() + val request = Request.Builder().url(url.toString()).get().build() - val urlMangas = Uri.parse("$apiUrl/mangas").buildUpon() - .appendPath(track.media_id.toString()) - .build() - val requestMangas = Request.Builder() - .url(urlMangas.toString()) - .get() - .build() + val urlMangas = + Uri.parse("$apiUrl/mangas").buildUpon().appendPath(track.media_id.toString()) + .build() + val requestMangas = Request.Builder().url(urlMangas.toString()).get().build() val requestMangasResponse = authClient.newCall(requestMangas).execute() val requestMangasBody = requestMangasResponse.body?.string().orEmpty() @@ -151,7 +135,7 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter suspend fun accessToken(code: String): OAuth { return withContext(Dispatchers.IO) { - val netResponse= client.newCall(accessTokenRequest(code)).execute() + val netResponse = client.newCall(accessTokenRequest(code)).execute() val responseBody = netResponse.body?.string().orEmpty() if (responseBody.isEmpty()) { throw Exception("Null Response") @@ -162,12 +146,8 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter private fun accessTokenRequest(code: String) = POST( oauthUrl, - body = FormBody.Builder() - .add("grant_type", "authorization_code") - .add("client_id", clientId) - .add("client_secret", clientSecret) - .add("code", code) - .add("redirect_uri", redirectUrl) + body = FormBody.Builder().add("grant_type", "authorization_code").add("client_id", clientId) + .add("client_secret", clientSecret).add("code", code).add("redirect_uri", redirectUrl) .build() ) @@ -189,21 +169,14 @@ class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInter return "$baseMangaUrl/$remoteId" } - fun authUrl() = - Uri.parse(loginUrl).buildUpon() - .appendQueryParameter("client_id", clientId) - .appendQueryParameter("redirect_uri", redirectUrl) - .appendQueryParameter("response_type", "code") - .build() + fun authUrl() = Uri.parse(loginUrl).buildUpon().appendQueryParameter("client_id", clientId) + .appendQueryParameter("redirect_uri", redirectUrl) + .appendQueryParameter("response_type", "code").build() fun refreshTokenRequest(token: String) = POST( oauthUrl, - body = FormBody.Builder() - .add("grant_type", "refresh_token") - .add("client_id", clientId) - .add("client_secret", clientSecret) - .add("refresh_token", token) - .build() + body = FormBody.Builder().add("grant_type", "refresh_token").add("client_id", clientId) + .add("client_secret", clientSecret).add("refresh_token", token).build() ) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriModels.kt b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriModels.kt index 4ff0943c0e..4ad7218f36 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriModels.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriModels.kt @@ -28,9 +28,9 @@ data class OAuth( val token_type: String, val created_at: Long, val expires_in: Long, - val refresh_token: String?) { + val refresh_token: String? +) { // Access token lives 1 day fun isExpired() = (System.currentTimeMillis() / 1000) > (created_at + expires_in - 3600) } - diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/Release.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/Release.kt index 9ac138e980..61f2bd7870 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/Release.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/Release.kt @@ -9,5 +9,4 @@ interface Release { * @return download link of latest release. */ val downloadLink: String - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateChecker.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateChecker.kt index c4eb465651..d7a99ae2ad 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateChecker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateChecker.kt @@ -5,12 +5,11 @@ import eu.kanade.tachiyomi.data.updater.github.GithubUpdateChecker abstract class UpdateChecker { companion object { - fun getUpdateChecker(): UpdateChecker = GithubUpdateChecker() + fun getUpdateChecker(): UpdateChecker = GithubUpdateChecker() } /** * Returns suspended result containing release information */ abstract suspend fun checkForUpdate(): UpdateResult - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateResult.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateResult.kt index a59864f557..a147c01df1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateResult.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateResult.kt @@ -2,7 +2,6 @@ package eu.kanade.tachiyomi.data.updater abstract class UpdateResult { - open class NewUpdate(val release: T): UpdateResult() - open class NoNewUpdate: UpdateResult() - + open class NewUpdate(val release: T) : UpdateResult() + open class NoNewUpdate : UpdateResult() } 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 aef189fe52..56b975ac98 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 @@ -10,17 +10,16 @@ import com.evernote.android.job.JobRequest import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.util.system.notificationManager +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch -import java.util.concurrent.TimeUnit class UpdaterJob : Job() { override fun onRunJob(params: Params): Result { GlobalScope.launch(Dispatchers.IO) { - val result = try { UpdateChecker.getUpdateChecker().checkForUpdate() } - catch (e: Exception) { return@launch } + val result = try { UpdateChecker.getUpdateChecker().checkForUpdate() } catch (e: Exception) { return@launch } if (result is UpdateResult.NewUpdate<*>) { val url = result.release.downloadLink @@ -73,5 +72,4 @@ class UpdaterJob : Job() { JobManager.instance().cancelAllForTag(TAG) } } - } 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 ddce70db74..624d5cfdbd 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 @@ -12,9 +12,9 @@ import eu.kanade.tachiyomi.network.ProgressListener import eu.kanade.tachiyomi.network.newCallWithProgress import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.storage.saveTo +import java.io.File import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.io.File class UpdaterService : IntentService(UpdaterService::class.java.name) { @@ -119,5 +119,3 @@ class UpdaterService : IntentService(UpdaterService::class.java.name) { } } } - - diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubRelease.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubRelease.kt index 4e4d7feca2..09f1b37d01 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubRelease.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubRelease.kt @@ -11,9 +11,11 @@ import eu.kanade.tachiyomi.data.updater.Release * @param info log of latest release. * @param assets assets of latest release. */ -class GithubRelease(@SerializedName("tag_name") val version: String, - @SerializedName("body") override val info: String, - @SerializedName("assets") private val assets: List): Release { +class GithubRelease( + @SerializedName("tag_name") val version: String, + @SerializedName("body") override val info: String, + @SerializedName("assets") private val assets: List +) : Release { /** * Get download link of latest release from the assets. @@ -28,4 +30,3 @@ class GithubRelease(@SerializedName("tag_name") val version: String, */ inner class Assets(@SerializedName("browser_download_url") val downloadLink: String) } - 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 beaf42ea74..8f9a4857bd 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 @@ -4,7 +4,6 @@ import eu.kanade.tachiyomi.network.NetworkHelper import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET -import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get @@ -27,5 +26,4 @@ interface GithubService { @GET("/repos/Jays2Kings/tachiyomiJ2K/releases/latest") suspend fun getLatestVersion(): GithubRelease - } 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 b1be97df33..f90d8c8179 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 @@ -19,5 +19,4 @@ import eu.kanade.tachiyomi.data.updater.UpdateResult GithubUpdateResult.NoNewUpdate() } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateResult.kt b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateResult.kt index fcb304604b..8462f937ea 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateResult.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/data/updater/github/GithubUpdateResult.kt @@ -4,7 +4,6 @@ import eu.kanade.tachiyomi.data.updater.UpdateResult sealed class GithubUpdateResult : UpdateResult() { - class NewUpdate(release: GithubRelease): UpdateResult.NewUpdate(release) + class NewUpdate(release: GithubRelease) : UpdateResult.NewUpdate(release) class NoNewUpdate : UpdateResult.NoNewUpdate() - } 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 ea12b35d52..cfc3ae8339 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt @@ -29,8 +29,8 @@ import uy.kohesive.injekt.api.get * @param preferences The application preferences. */ class ExtensionManager( - private val context: Context, - private val preferences: PreferencesHelper = Injekt.get() + private val context: Context, + private val preferences: PreferencesHelper = Injekt.get() ) { /** @@ -159,8 +159,7 @@ class ExtensionManager( * @param availableExtensions The list of extensions given by the [api]. */ private fun updatedInstalledExtensionsStatuses(availableExtensions: List) { - if (availableExtensions.isEmpty()) - { + if (availableExtensions.isEmpty()) { preferences.extensionUpdatesCount().set(0) return } @@ -208,7 +207,7 @@ class ExtensionManager( * * @param extension The extension to be updated. */ - fun updateExtension(extension: Extension.Installed): Observable { + fun updateExtension(extension: Extension.Installed): Observable { val availableExt = availableExtensions.find { it.pkgName == extension.pkgName } ?: return Observable.empty() return installExtension(availableExt) @@ -343,5 +342,4 @@ class ExtensionManager( } return this } - } 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 72dd10d3f8..af82166f30 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionUpdateJob.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.extension - import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat @@ -13,11 +12,11 @@ import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi import eu.kanade.tachiyomi.util.system.notification +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import uy.kohesive.injekt.injectLazy -import java.util.concurrent.TimeUnit class ExtensionUpdateJob : Job() { @@ -77,4 +76,4 @@ class ExtensionUpdateJob : Job() { JobManager.instance().cancelAllForTag(TAG) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/api/ExtensionGithubApi.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/api/ExtensionGithubApi.kt index ad7ad63ce2..79fff8b97e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/api/ExtensionGithubApi.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/api/ExtensionGithubApi.kt @@ -28,7 +28,7 @@ internal class ExtensionGithubApi { val call = GET("$REPO_URL/index.json") return withContext(Dispatchers.IO) { - parseResponse(network.client.newCall(call).await()) + parseResponse(network.client.newCall(call).await()) } } @@ -41,9 +41,9 @@ internal class ExtensionGithubApi { val extensions = parseResponse(response) val extensionsWithUpdate = mutableListOf() - val installedExtensions = ExtensionLoader.loadExtensions(context) - .filterIsInstance() - .map { it.extension } + val installedExtensions = + ExtensionLoader.loadExtensions(context).filterIsInstance() + .map { it.extension } val mutInstalledExtensions = installedExtensions.toMutableList() for (installedExt in mutInstalledExtensions) { val pkgName = installedExt.pkgName @@ -84,6 +84,7 @@ internal class ExtensionGithubApi { } companion object { - private const val REPO_URL = "https://raw.githubusercontent.com/inorichi/tachiyomi-extensions/repo" + private const val REPO_URL = + "https://raw.githubusercontent.com/inorichi/tachiyomi-extensions/repo" } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt b/app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt index f0a53690f5..7fb384cc01 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/extension/model/Extension.kt @@ -10,28 +10,33 @@ sealed class Extension { abstract val versionCode: Int abstract val lang: String? - data class Installed(override val name: String, - override val pkgName: String, - override val versionName: String, - override val versionCode: Int, - val sources: List, - override val lang: String, - val hasUpdate: Boolean = false, - val isObsolete: Boolean = false) : Extension() + data class Installed( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Int, + val sources: List, + override val lang: String, + val hasUpdate: Boolean = false, + val isObsolete: Boolean = false + ) : Extension() - data class Available(override val name: String, - override val pkgName: String, - override val versionName: String, - override val versionCode: Int, - override val lang: String, - val apkName: String, - val iconUrl: String) : Extension() - - data class Untrusted(override val name: String, - override val pkgName: String, - override val versionName: String, - override val versionCode: Int, - val signatureHash: String, - override val lang: String? = null) : Extension() + data class Available( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Int, + override val lang: String, + val apkName: String, + val iconUrl: String + ) : Extension() + data class Untrusted( + override val name: String, + override val pkgName: String, + override val versionName: String, + override val versionCode: Int, + val signatureHash: String, + override val lang: String? = null + ) : Extension() } 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 bcabce0f42..ed84370de7 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 @@ -93,8 +93,8 @@ internal class ExtensionInstallReceiver(private val listener: Listener) : * @param intent The intent containing the package name of the extension. */ private suspend fun getExtensionFromIntent(context: Context, intent: Intent?): LoadResult { - val pkgName = getPackageNameFromIntent(intent) ?: - return LoadResult.Error("Package name not found") + val pkgName = getPackageNameFromIntent(intent) + ?: return LoadResult.Error("Package name not found") return GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) { ExtensionLoader.loadExtensionFromPkgName(context, pkgName) }.await() } @@ -114,5 +114,4 @@ internal class ExtensionInstallReceiver(private val listener: Listener) : fun onExtensionUntrusted(extension: Extension.Untrusted) fun onPackageUninstalled(pkgName: String) } - } 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 8c444a98ee..1cf21d9296 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 @@ -11,11 +11,11 @@ import com.jakewharton.rxrelay.PublishRelay import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.util.storage.getUriCompat +import java.io.File +import java.util.concurrent.TimeUnit import rx.Observable import rx.android.schedulers.AndroidSchedulers import timber.log.Timber -import java.io.File -import java.util.concurrent.TimeUnit /** * The installer which installs, updates and uninstalls the extensions. @@ -245,5 +245,4 @@ internal class ExtensionInstaller(private val context: Context) { const val APK_MIME = "application/vnd.android.package-archive" const val EXTRA_DOWNLOAD_ID = "ExtensionInstaller.extra.DOWNLOAD_ID" } - } 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 35a5948f22..29525d8159 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 @@ -179,5 +179,4 @@ internal object ExtensionLoader { null } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt b/app/src/main/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt index 77bffc2ec4..3411b4d06c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt @@ -173,4 +173,4 @@ class CloudflareInterceptor(private val context: Context) : Interceptor { private val COOKIE_NAMES = listOf("__cfduid", "cf_clearance") private const val DEFAULT_USERAGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64)" } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt b/app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt index 21445593e4..c19fbdd390 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.network import android.content.Context +import java.io.File import okhttp3.Cache import okhttp3.OkHttpClient -import java.io.File class NetworkHelper(context: Context) { @@ -21,5 +21,4 @@ class NetworkHelper(context: Context) { val cloudflareClient = client.newBuilder() .addInterceptor(CloudflareInterceptor(context)) .build() - } 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 8de9f9e25d..1a9e81622c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt @@ -1,11 +1,5 @@ package eu.kanade.tachiyomi.network -import kotlinx.coroutines.suspendCancellableCoroutine -import okhttp3.* -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import rx.Observable -import rx.Producer -import rx.Subscription import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader @@ -13,6 +7,16 @@ import java.util.concurrent.atomic.AtomicBoolean import java.util.zip.GZIPInputStream import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.suspendCancellableCoroutine +import okhttp3.Call +import okhttp3.Callback +import okhttp3.MediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import rx.Observable +import rx.Producer +import rx.Subscription fun Call.asObservable(): Observable { return Observable.unsafeCreate { subscriber -> @@ -99,7 +103,7 @@ fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListene return progressClient.newCall(request) } -fun MediaType.Companion.jsonType() : MediaType = "application/json; charset=utf-8".toMediaTypeOrNull()!! +fun MediaType.Companion.jsonType(): MediaType = "application/json; charset=utf-8".toMediaTypeOrNull()!! fun Response.consumeBody(): String? { use { diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/ProgressListener.kt b/app/src/main/java/eu/kanade/tachiyomi/network/ProgressListener.kt index 4bebcf87dd..2e219895fe 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/ProgressListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/ProgressListener.kt @@ -2,4 +2,4 @@ package eu.kanade.tachiyomi.network interface ProgressListener { fun update(bytesRead: Long, contentLength: Long, done: Boolean) -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt b/app/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt index 8308acc1c2..53799e9ca4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/ProgressResponseBody.kt @@ -1,9 +1,13 @@ package eu.kanade.tachiyomi.network +import java.io.IOException import okhttp3.MediaType import okhttp3.ResponseBody -import okio.* -import java.io.IOException +import okio.Buffer +import okio.BufferedSource +import okio.ForwardingSource +import okio.Source +import okio.buffer class ProgressResponseBody(private val responseBody: ResponseBody, private val progressListener: ProgressListener) : ResponseBody() { 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 9b2697a514..185bb2f75c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/network/Requests.kt @@ -1,15 +1,21 @@ package eu.kanade.tachiyomi.network -import okhttp3.* import java.util.concurrent.TimeUnit.MINUTES +import okhttp3.CacheControl +import okhttp3.FormBody +import okhttp3.Headers +import okhttp3.Request +import okhttp3.RequestBody private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, MINUTES).build() private val DEFAULT_HEADERS = Headers.Builder().build() private val DEFAULT_BODY: RequestBody = FormBody.Builder().build() -fun GET(url: String, - headers: Headers = DEFAULT_HEADERS, - cache: CacheControl = DEFAULT_CACHE_CONTROL): Request { +fun GET( + url: String, + headers: Headers = DEFAULT_HEADERS, + cache: CacheControl = DEFAULT_CACHE_CONTROL +): Request { return Request.Builder() .url(url) @@ -18,10 +24,12 @@ fun GET(url: String, .build() } -fun POST(url: String, - headers: Headers = DEFAULT_HEADERS, - body: RequestBody = DEFAULT_BODY, - cache: CacheControl = DEFAULT_CACHE_CONTROL): Request { +fun POST( + url: String, + headers: Headers = DEFAULT_HEADERS, + body: RequestBody = DEFAULT_BODY, + cache: CacheControl = DEFAULT_CACHE_CONTROL +): Request { return Request.Builder() .url(url) diff --git a/app/src/main/java/eu/kanade/tachiyomi/smartsearch/SmartSearchEngine.kt b/app/src/main/java/eu/kanade/tachiyomi/smartsearch/SmartSearchEngine.kt index b782193db1..c3e44e62fe 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/smartsearch/SmartSearchEngine.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/smartsearch/SmartSearchEngine.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.smartsearch - import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.source.CatalogueSource @@ -8,16 +7,18 @@ import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.util.system.await import info.debatty.java.stringsimilarity.NormalizedLevenshtein +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.supervisorScope import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy -import kotlin.coroutines.CoroutineContext -class SmartSearchEngine(parentContext: CoroutineContext, - val extraSearchParams: String? = null): CoroutineScope { +class SmartSearchEngine( + parentContext: CoroutineContext, + val extraSearchParams: String? = null +) : CoroutineScope { override val coroutineContext: CoroutineContext = parentContext + Job() + Dispatchers.Default private val db: DatabaseHelper by injectLazy() @@ -55,7 +56,7 @@ class SmartSearchEngine(parentContext: CoroutineContext, suspend fun normalSearch(source: CatalogueSource, title: String): SManga? { val eligibleManga = supervisorScope { - val searchQuery = if(extraSearchParams != null) { + val searchQuery = if (extraSearchParams != null) { "$title ${extraSearchParams.trim()}" } else title val searchResults = source.fetchSearchManga(1, searchQuery, FilterList()).toSingle().await(Schedulers.io()) @@ -88,7 +89,7 @@ class SmartSearchEngine(parentContext: CoroutineContext, }.toMap() // Reverse pairs if reading backwards - if(!readForward) { + if (!readForward) { val tmp = openingBracketPairs openingBracketPairs = closingBracketPairs closingBracketPairs = tmp @@ -97,16 +98,16 @@ class SmartSearchEngine(parentContext: CoroutineContext, val depthPairs = bracketPairs.map { 0 }.toMutableList() val result = StringBuilder() - for(c in if(readForward) text else text.reversed()) { + for (c in if (readForward) text else text.reversed()) { val openingBracketDepthIndex = openingBracketPairs[c] - if(openingBracketDepthIndex != null) { + if (openingBracketDepthIndex != null) { depthPairs[openingBracketDepthIndex]++ } else { val closingBracketDepthIndex = closingBracketPairs[c] - if(closingBracketDepthIndex != null) { + if (closingBracketDepthIndex != null) { depthPairs[closingBracketDepthIndex]-- } else { - if(depthPairs.all { it <= 0 }) { + if (depthPairs.all { it <= 0 }) { result.append(c) } else { // In brackets, do not append to result @@ -146,4 +147,4 @@ class SmartSearchEngine(parentContext: CoroutineContext, } } -data class SearchEntry(val manga: SManga, val dist: Double) \ No newline at end of file +data class SearchEntry(val manga: SManga, val dist: Double) diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/CatalogueSource.kt b/app/src/main/java/eu/kanade/tachiyomi/source/CatalogueSource.kt index f5f11a00bc..c78033ea60 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/CatalogueSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/CatalogueSource.kt @@ -43,4 +43,4 @@ interface CatalogueSource : Source { * Returns the list of filters for the source. */ fun getFilterList(): FilterList -} \ No newline at end of file +} 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 7dd9639d63..a92a8a3fd2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt @@ -16,10 +16,6 @@ import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder import eu.kanade.tachiyomi.util.storage.DiskUtil import eu.kanade.tachiyomi.util.storage.EpubFile import eu.kanade.tachiyomi.util.system.ImageUtil -import junrar.Archive -import junrar.rarfile.FileHeader -import rx.Observable -import timber.log.Timber import java.io.File import java.io.FileInputStream import java.io.InputStream @@ -28,12 +24,17 @@ import java.util.Scanner import java.util.concurrent.TimeUnit import java.util.zip.ZipEntry import java.util.zip.ZipFile +import junrar.Archive +import junrar.rarfile.FileHeader +import rx.Observable +import timber.log.Timber class LocalSource(private val context: Context) : CatalogueSource { companion object { private val COVER_NAME = "cover.jpg" private val POPULAR_FILTERS = FilterList(OrderBy()) - private val LATEST_FILTERS = FilterList(OrderBy().apply { state = Filter.Sort.Selection(1, false) }) + private val LATEST_FILTERS = + FilterList(OrderBy().apply { state = Filter.Sort.Selection(1, false) }) private val LATEST_THRESHOLD = TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS) val ID = 0L @@ -70,28 +71,33 @@ class LocalSource(private val context: Context) : CatalogueSource { override fun fetchPopularManga(page: Int) = fetchSearchManga(page, "", POPULAR_FILTERS) - override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable { + override fun fetchSearchManga( + page: Int, + query: String, + filters: FilterList + ): Observable { val baseDirs = getBaseDirectories(context) - val time = if (filters === LATEST_FILTERS) System.currentTimeMillis() - LATEST_THRESHOLD else 0L - var mangaDirs = baseDirs.mapNotNull { it.listFiles()?.toList() } - .flatten() - .filter { it.isDirectory && if (time == 0L) it.name.contains(query, ignoreCase = true) else it.lastModified() >= time } - .distinctBy { it.name } + val time = + if (filters === LATEST_FILTERS) System.currentTimeMillis() - LATEST_THRESHOLD else 0L + var mangaDirs = baseDirs.mapNotNull { it.listFiles()?.toList() }.flatten().filter { + it.isDirectory && if (time == 0L) it.name.contains( + query, + ignoreCase = true + ) else it.lastModified() >= time + }.distinctBy { it.name } val state = ((if (filters.isEmpty()) POPULAR_FILTERS else filters)[0] as OrderBy).state when (state?.index) { 0 -> { - if (state.ascending) - mangaDirs = mangaDirs.sortedBy { it.name.toLowerCase(Locale.ENGLISH) } - else - mangaDirs = mangaDirs.sortedByDescending { it.name.toLowerCase(Locale.ENGLISH) } + if (state.ascending) mangaDirs = + mangaDirs.sortedBy { it.name.toLowerCase(Locale.ENGLISH) } + else mangaDirs = + mangaDirs.sortedByDescending { it.name.toLowerCase(Locale.ENGLISH) } } 1 -> { - if (state.ascending) - mangaDirs = mangaDirs.sortedBy(File::lastModified) - else - mangaDirs = mangaDirs.sortedByDescending(File::lastModified) + if (state.ascending) mangaDirs = mangaDirs.sortedBy(File::lastModified) + else mangaDirs = mangaDirs.sortedByDescending(File::lastModified) } } @@ -129,44 +135,42 @@ class LocalSource(private val context: Context) : CatalogueSource { override fun fetchLatestUpdates(page: Int) = fetchSearchManga(page, "", LATEST_FILTERS) override fun fetchMangaDetails(manga: SManga): Observable { - getBaseDirectories(context) - .mapNotNull { File(it, manga.url).listFiles()?.toList() } - .flatten() - .filter { it.extension.equals("json") } - .firstOrNull() - ?.apply { - val json = Gson().fromJson(Scanner(this).useDelimiter("\\Z").next(), JsonObject::class.java) - manga.title = json["title"]?.asString ?: manga.title - manga.author = json["author"]?.asString ?: manga.author - manga.artist = json["artist"]?.asString ?: manga.artist - manga.description = json["description"]?.asString ?: manga.description - manga.genre = json["genre"]?.asJsonArray - ?.map { it.asString } - ?.joinToString(", ") + getBaseDirectories(context).mapNotNull { File(it, manga.url).listFiles()?.toList() } + .flatten().filter { it.extension.equals("json") }.firstOrNull()?.apply { + val json = Gson().fromJson( + Scanner(this).useDelimiter("\\Z").next(), + JsonObject::class.java + ) + manga.title = json["title"]?.asString ?: manga.title + manga.author = json["author"]?.asString ?: manga.author + manga.artist = json["artist"]?.asString ?: manga.artist + manga.description = json["description"]?.asString ?: manga.description + manga.genre = json["genre"]?.asJsonArray?.map { it.asString }?.joinToString(", ") ?: manga.genre - manga.status = json["status"]?.asInt ?: manga.status - } + manga.status = json["status"]?.asInt ?: manga.status + } return Observable.just(manga) } fun updateMangaInfo(manga: SManga) { - val directory = getBaseDirectories(context).mapNotNull { File(it, manga.url) }.find { it - .exists() } ?: return + val directory = getBaseDirectories(context).mapNotNull { File(it, manga.url) }.find { + it.exists() + } ?: return val gson = GsonBuilder().setPrettyPrinting().create() val file = File(directory, "info.json") file.writeText(gson.toJson(manga.toJson())) } - fun SManga.toJson():MangaJson { + fun SManga.toJson(): MangaJson { return MangaJson(title, author, artist, description, genre?.split(", ")?.toTypedArray()) } data class MangaJson( - val title:String, - val author:String?, - val artist:String?, - val description:String?, - val genre:Array? + val title: String, + val author: String?, + val artist: String?, + val description: String?, + val genre: Array? ) { override fun equals(other: Any?): Boolean { @@ -186,10 +190,9 @@ class LocalSource(private val context: Context) : CatalogueSource { } override fun fetchChapterList(manga: SManga): Observable> { - val chapters = getBaseDirectories(context) - .mapNotNull { File(it, manga.url).listFiles()?.toList() } - .flatten() - .filter { it.isDirectory || isSupportedFile(it.extension) } + val chapters = + getBaseDirectories(context).mapNotNull { File(it, manga.url).listFiles()?.toList() } + .flatten().filter { it.isDirectory || isSupportedFile(it.extension) } .map { chapterFile -> SChapter.create().apply { url = "${manga.url}/${chapterFile.name}" @@ -198,13 +201,13 @@ class LocalSource(private val context: Context) : CatalogueSource { } else { chapterFile.nameWithoutExtension } - val chapNameCut = chapName.replace(manga.originalTitle(), "", true).trim(' ', '-', '_') + val chapNameCut = + chapName.replace(manga.originalTitle(), "", true).trim(' ', '-', '_') name = if (chapNameCut.isEmpty()) chapName else chapNameCut date_upload = chapterFile.lastModified() ChapterRecognition.parseChapterNumber(this, manga) } - } - .sortedWith(Comparator { c1, c2 -> + }.sortedWith(Comparator { c1, c2 -> val c = c2.chapter_number.compareTo(c1.chapter_number) if (c == 0) c2.name.compareToCaseInsensitiveNaturalOrder(c1.name) else c }) @@ -251,35 +254,42 @@ class LocalSource(private val context: Context) : CatalogueSource { val format = getFormat(chapter) return when (format) { is Format.Directory -> { - val entry = format.file.listFiles() - .sortedWith(Comparator { f1, f2 -> f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) }) + val entry = format.file.listFiles().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())} + 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 { !it.isDirectory && ImageUtil.isImage(it.name) { zip.getInputStream(it) } } + val entry = zip.entries().toList().sortedWith(Comparator { f1, f2 -> + f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) + }).find { + !it.isDirectory && ImageUtil.isImage(it.name) { + zip.getInputStream(it) + } + } - entry?.let { updateCover(context, manga, zip.getInputStream(it) )} + entry?.let { updateCover(context, manga, zip.getInputStream(it)) } } } is Format.Rar -> { Archive(format.file).use { archive -> - val entry = archive.fileHeaders - .sortedWith(Comparator { f1, f2 -> f1.fileNameString.compareToCaseInsensitiveNaturalOrder(f2.fileNameString) }) - .find { !it.isDirectory && ImageUtil.isImage(it.fileNameString) { archive.getInputStream(it) } } + val entry = archive.fileHeaders.sortedWith(Comparator { f1, f2 -> + f1.fileNameString.compareToCaseInsensitiveNaturalOrder(f2.fileNameString) + }).find { + !it.isDirectory && ImageUtil.isImage(it.fileNameString) { + archive.getInputStream(it) + } + } - entry?.let { updateCover(context, manga, archive.getInputStream(it) )} + entry?.let { updateCover(context, manga, archive.getInputStream(it)) } } } is Format.Epub -> { EpubFile(format.file).use { epub -> - val entry = epub.getImagesFromPages() - .firstOrNull() - ?.let { epub.getEntry(it) } + val entry = epub.getImagesFromPages().firstOrNull()?.let { epub.getEntry(it) } entry?.let { updateCover(context, manga, epub.getInputStream(it)) } } @@ -287,15 +297,15 @@ class LocalSource(private val context: Context) : CatalogueSource { } } - private class OrderBy : Filter.Sort("Order by", arrayOf("Title", "Date"), Filter.Sort.Selection(0, true)) + private class OrderBy : + Filter.Sort("Order by", arrayOf("Title", "Date"), Filter.Sort.Selection(0, true)) override fun getFilterList() = FilterList(OrderBy()) sealed class Format { data class Directory(val file: File) : Format() data class Zip(val file: File) : Format() - data class Rar(val file: File): Format() + data class Rar(val file: File) : Format() data class Epub(val file: File) : Format() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/Source.kt b/app/src/main/java/eu/kanade/tachiyomi/source/Source.kt index 7a5f43a846..93a8a809ec 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/Source.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/Source.kt @@ -40,5 +40,4 @@ interface Source { * @param chapter the chapter. */ fun fetchPageList(chapter: SChapter): Observable> - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/Filter.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/Filter.kt index 8cd520d22d..f82ddfc21c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/Filter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/Filter.kt @@ -17,10 +17,10 @@ sealed class Filter(val name: String, var state: T) { const val STATE_EXCLUDE = 2 } } - abstract class Group(name: String, state: List): Filter>(name, state) + abstract class Group(name: String, state: List) : Filter>(name, state) - abstract class Sort(name: String, val values: Array, state: Selection? = null) - : Filter(name, state) { + abstract class Sort(name: String, val values: Array, state: Selection? = null) : + Filter(name, state) { data class Selection(val index: Int, val ascending: Boolean) } @@ -36,5 +36,4 @@ sealed class Filter(val name: String, var state: T) { result = 31 * result + (state?.hashCode() ?: 0) return result } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/FilterList.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/FilterList.kt index e24db65b65..42b6bc74ba 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/FilterList.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/FilterList.kt @@ -3,5 +3,4 @@ package eu.kanade.tachiyomi.source.model data class FilterList(val list: List>) : List> by list { constructor(vararg fs: Filter<*>) : this(if (fs.isNotEmpty()) fs.asList() else emptyList()) - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/MangasPage.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/MangasPage.kt index 12dd172a74..a377c36eaa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/MangasPage.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/MangasPage.kt @@ -1,3 +1,3 @@ package eu.kanade.tachiyomi.source.model -data class MangasPage(val mangas: List, val hasNextPage: Boolean) \ No newline at end of file +data class MangasPage(val mangas: List, val hasNextPage: Boolean) diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt index 1fc29ff5af..1ca0778b6f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt @@ -5,10 +5,10 @@ import eu.kanade.tachiyomi.network.ProgressListener import rx.subjects.Subject open class Page( - val index: Int, - val url: String = "", - var imageUrl: String? = null, - @Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions + val index: Int, + val url: String = "", + var imageUrl: String? = null, + @Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions ) : ProgressListener { val number: Int @@ -54,5 +54,4 @@ open class Page( const val READY = 3 const val ERROR = 4 } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapter.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapter.kt index 0017e51d63..f53bbe8f0a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapter.kt @@ -27,5 +27,4 @@ interface SChapter : Serializable { return SChapterImpl() } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapterImpl.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapterImpl.kt index 4fa55141f4..4d5e43f1e4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapterImpl.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/SChapterImpl.kt @@ -10,6 +10,5 @@ class SChapterImpl : SChapter { override var chapter_number: Float = -1f - override var scanlator: String? = null - -} \ No newline at end of file + override var scanlator: String? = null +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt b/app/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt index 7ed9f339ad..a3701637d1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt @@ -49,7 +49,7 @@ interface SManga : Serializable { fun originalArtist() = split(artist, false) - private fun split(string: String?, first: Boolean):String? { + private fun split(string: String?, first: Boolean): String? { val split = string?.split(splitter) ?: return null val s = if (first) split.first() else split.last() return if (s.isBlank()) null else s @@ -60,28 +60,28 @@ interface SManga : Serializable { author = if (currentAuthor() != originalAuthor()) { val current = currentAuthor() val og = other.author - "${current}$splitter${og}" + "${current}$splitter$og" } else other.author if (other.artist != null) artist = if (currentArtist() != originalArtist()) { val current = currentArtist() val og = other.artist - "${current}$splitter${og}" + "${current}$splitter$og" } else other.artist if (other.description != null) description = if (currentDesc() != originalDesc()) { val current = currentDesc() val og = other.description - "${current}$splitter${og}" + "${current}$splitter$og" } else other.description if (other.genre != null) genre = if (currentGenres() != originalGenres()) { val current = currentGenres() val og = other.genre - "${current}$splitter${og}" + "${current}$splitter$og" } else other.genre if (other.thumbnail_url != null) @@ -104,5 +104,4 @@ interface SManga : Serializable { return MangaImpl() } } - -} \ No newline at end of file +} 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 86b020be36..15a139fa1b 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 @@ -5,17 +5,20 @@ import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.network.newCallWithProgress import eu.kanade.tachiyomi.source.CatalogueSource -import eu.kanade.tachiyomi.source.model.* +import eu.kanade.tachiyomi.source.model.FilterList +import eu.kanade.tachiyomi.source.model.MangasPage +import eu.kanade.tachiyomi.source.model.Page +import eu.kanade.tachiyomi.source.model.SChapter +import eu.kanade.tachiyomi.source.model.SManga +import java.net.URI +import java.net.URISyntaxException +import java.security.MessageDigest import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.injectLazy -import java.lang.Exception -import java.net.URI -import java.net.URISyntaxException -import java.security.MessageDigest /** * A simple implementation for sources from a website. @@ -70,7 +73,7 @@ abstract class HttpSource : CatalogueSource { /** * Headers builder for requests. Implementations can override this method for custom headers. */ - open protected fun headersBuilder() = Headers.Builder().apply { + protected open fun headersBuilder() = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)") } @@ -98,14 +101,14 @@ abstract class HttpSource : CatalogueSource { * * @param page the page number to retrieve. */ - abstract protected fun popularMangaRequest(page: Int): Request + protected abstract fun popularMangaRequest(page: Int): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ - abstract protected fun popularMangaParse(response: Response): MangasPage + protected abstract fun popularMangaParse(response: Response): MangasPage /** * Returns an observable containing a page with a list of manga. Normally it's not needed to @@ -130,14 +133,14 @@ abstract class HttpSource : CatalogueSource { * @param query the search query. * @param filters the list of filters to apply. */ - abstract protected fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request + protected abstract fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ - abstract protected fun searchMangaParse(response: Response): MangasPage + protected abstract fun searchMangaParse(response: Response): MangasPage /** * Returns an observable containing a page with a list of latest manga updates. @@ -157,14 +160,14 @@ abstract class HttpSource : CatalogueSource { * * @param page the page number to retrieve. */ - abstract protected fun latestUpdatesRequest(page: Int): Request + protected abstract fun latestUpdatesRequest(page: Int): Request /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ - abstract protected fun latestUpdatesParse(response: Response): MangasPage + protected abstract fun latestUpdatesParse(response: Response): MangasPage /** * Returns an observable with the updated details for a manga. Normally it's not needed to @@ -195,7 +198,7 @@ abstract class HttpSource : CatalogueSource { * * @param response the response from the site. */ - abstract protected fun mangaDetailsParse(response: Response): SManga + protected abstract fun mangaDetailsParse(response: Response): SManga /** * Returns an observable with the updated chapter list for a manga. Normally it's not needed to @@ -221,7 +224,7 @@ abstract class HttpSource : CatalogueSource { * * @param manga the manga to look for chapters. */ - open protected fun chapterListRequest(manga: SManga): Request { + protected open fun chapterListRequest(manga: SManga): Request { return GET(baseUrl + manga.url, headers) } @@ -230,7 +233,7 @@ abstract class HttpSource : CatalogueSource { * * @param response the response from the site. */ - abstract protected fun chapterListParse(response: Response): List + protected abstract fun chapterListParse(response: Response): List /** * Returns an observable with the page list for a chapter. @@ -251,7 +254,7 @@ abstract class HttpSource : CatalogueSource { * * @param chapter the chapter whose page list has to be fetched. */ - open protected fun pageListRequest(chapter: SChapter): Request { + protected open fun pageListRequest(chapter: SChapter): Request { return GET(baseUrl + chapter.url, headers) } @@ -260,7 +263,7 @@ abstract class HttpSource : CatalogueSource { * * @param response the response from the site. */ - abstract protected fun pageListParse(response: Response): List + protected abstract fun pageListParse(response: Response): List /** * Returns an observable with the page containing the source url of the image. If there's any @@ -280,7 +283,7 @@ abstract class HttpSource : CatalogueSource { * * @param page the chapter whose page list has to be fetched */ - open protected fun imageUrlRequest(page: Page): Request { + protected open fun imageUrlRequest(page: Page): Request { return GET(page.url, headers) } @@ -289,7 +292,7 @@ abstract class HttpSource : CatalogueSource { * * @param response the response from the site. */ - abstract protected fun imageUrlParse(response: Response): String + protected abstract fun imageUrlParse(response: Response): String /** * Returns an observable with the response of the source image. @@ -307,7 +310,7 @@ abstract class HttpSource : CatalogueSource { * * @param page the chapter whose page list has to be fetched */ - open protected fun imageRequest(page: Page): Request { + protected open fun imageRequest(page: Page): Request { return GET(page.imageUrl!!, headers) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/LoginSource.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/LoginSource.kt index 8aae073e30..71ef190053 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/LoginSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/LoginSource.kt @@ -11,5 +11,4 @@ interface LoginSource : Source { fun login(username: String, password: String): Observable fun isAuthenticationSuccessful(response: Response): Boolean - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt b/app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt index 03d58d56a2..941a3167a8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt @@ -36,7 +36,7 @@ abstract class ParsedHttpSource : HttpSource() { /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga. */ - abstract protected fun popularMangaSelector(): String + protected abstract fun popularMangaSelector(): String /** * Returns a manga from the given [element]. Most sites only show the title and the url, it's @@ -44,13 +44,13 @@ abstract class ParsedHttpSource : HttpSource() { * * @param element an element obtained from [popularMangaSelector]. */ - abstract protected fun popularMangaFromElement(element: Element): SManga + protected abstract fun popularMangaFromElement(element: Element): SManga /** * Returns the Jsoup selector that returns the tag linking to the next page, or null if * there's no next page. */ - abstract protected fun popularMangaNextPageSelector(): String? + protected abstract fun popularMangaNextPageSelector(): String? /** * Parses the response from the site and returns a [MangasPage] object. @@ -74,7 +74,7 @@ abstract class ParsedHttpSource : HttpSource() { /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga. */ - abstract protected fun searchMangaSelector(): String + protected abstract fun searchMangaSelector(): String /** * Returns a manga from the given [element]. Most sites only show the title and the url, it's @@ -82,13 +82,13 @@ abstract class ParsedHttpSource : HttpSource() { * * @param element an element obtained from [searchMangaSelector]. */ - abstract protected fun searchMangaFromElement(element: Element): SManga + protected abstract fun searchMangaFromElement(element: Element): SManga /** * Returns the Jsoup selector that returns the tag linking to the next page, or null if * there's no next page. */ - abstract protected fun searchMangaNextPageSelector(): String? + protected abstract fun searchMangaNextPageSelector(): String? /** * Parses the response from the site and returns a [MangasPage] object. @@ -112,7 +112,7 @@ abstract class ParsedHttpSource : HttpSource() { /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each manga. */ - abstract protected fun latestUpdatesSelector(): String + protected abstract fun latestUpdatesSelector(): String /** * Returns a manga from the given [element]. Most sites only show the title and the url, it's @@ -120,13 +120,13 @@ abstract class ParsedHttpSource : HttpSource() { * * @param element an element obtained from [latestUpdatesSelector]. */ - abstract protected fun latestUpdatesFromElement(element: Element): SManga + protected abstract fun latestUpdatesFromElement(element: Element): SManga /** * Returns the Jsoup selector that returns the tag linking to the next page, or null if * there's no next page. */ - abstract protected fun latestUpdatesNextPageSelector(): String? + protected abstract fun latestUpdatesNextPageSelector(): String? /** * Parses the response from the site and returns the details of a manga. @@ -142,7 +142,7 @@ abstract class ParsedHttpSource : HttpSource() { * * @param document the parsed document. */ - abstract protected fun mangaDetailsParse(document: Document): SManga + protected abstract fun mangaDetailsParse(document: Document): SManga /** * Parses the response from the site and returns a list of chapters. @@ -157,14 +157,14 @@ abstract class ParsedHttpSource : HttpSource() { /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter. */ - abstract protected fun chapterListSelector(): String + protected abstract fun chapterListSelector(): String /** * Returns a chapter from the given element. * * @param element an element obtained from [chapterListSelector]. */ - abstract protected fun chapterFromElement(element: Element): SChapter + protected abstract fun chapterFromElement(element: Element): SChapter /** * Parses the response from the site and returns the page list. @@ -180,7 +180,7 @@ abstract class ParsedHttpSource : HttpSource() { * * @param document the parsed document. */ - abstract protected fun pageListParse(document: Document): List + protected abstract fun pageListParse(document: Document): List /** * Parse the response from the site and returns the absolute url to the source image. @@ -196,5 +196,5 @@ abstract class ParsedHttpSource : HttpSource() { * * @param document the parsed document. */ - abstract protected fun imageUrlParse(document: Document): String + protected abstract fun imageUrlParse(document: Document): String } 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 70536b3350..1e47b1bf2b 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 @@ -10,15 +10,14 @@ import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.main_activity.view.* -class CenteredToolbar@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null): Toolbar +class CenteredToolbar@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : Toolbar (context, attrs) { override fun setTitle(resId: Int) { if (navigationIcon is DrawerArrowDrawable) { super.setTitle(resId) toolbar_title.text = null - } - else { + } else { toolbar_title.text = context.getString(resId) post { if (navigationIcon !is DrawerArrowDrawable) { @@ -34,8 +33,7 @@ class CenteredToolbar@JvmOverloads constructor(context: Context, attrs: Attribut if (navigationIcon is DrawerArrowDrawable) { super.setTitle(title) toolbar_title.text = "" - } - else { + } else { toolbar_title.text = title post { if (navigationIcon !is DrawerArrowDrawable) { @@ -62,4 +60,4 @@ class CenteredToolbar@JvmOverloads constructor(context: Context, attrs: Attribut title_layout.setOnTouchListener(null) title_layout.setOnClickListener(null) } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseRxActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseRxActivity.kt index 4bfe865053..d38ecabcc9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseRxActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/BaseRxActivity.kt @@ -22,5 +22,4 @@ abstract class BaseRxActivity

> : NucleusAppCompatActivity

Observable.subscribeUntilDetach(): Subscription { return subscribe().also { untilDetachSubscriptions.add(it) } @@ -53,15 +52,19 @@ abstract class RxController(bundle: Bundle? = null) : BaseController(bundle) { return subscribe(onNext).also { untilDetachSubscriptions.add(it) } } - fun Observable.subscribeUntilDetach(onNext: (T) -> Unit, - onError: (Throwable) -> Unit): Subscription { + fun Observable.subscribeUntilDetach( + onNext: (T) -> Unit, + onError: (Throwable) -> Unit + ): Subscription { return subscribe(onNext, onError).also { untilDetachSubscriptions.add(it) } } - fun Observable.subscribeUntilDetach(onNext: (T) -> Unit, - onError: (Throwable) -> Unit, - onCompleted: () -> Unit): Subscription { + fun Observable.subscribeUntilDetach( + onNext: (T) -> Unit, + onError: (Throwable) -> Unit, + onCompleted: () -> Unit + ): Subscription { return subscribe(onNext, onError, onCompleted).also { untilDetachSubscriptions.add(it) } } @@ -76,17 +79,20 @@ abstract class RxController(bundle: Bundle? = null) : BaseController(bundle) { return subscribe(onNext).also { untilDestroySubscriptions.add(it) } } - fun Observable.subscribeUntilDestroy(onNext: (T) -> Unit, - onError: (Throwable) -> Unit): Subscription { + fun Observable.subscribeUntilDestroy( + onNext: (T) -> Unit, + onError: (Throwable) -> Unit + ): Subscription { return subscribe(onNext, onError).also { untilDestroySubscriptions.add(it) } } - fun Observable.subscribeUntilDestroy(onNext: (T) -> Unit, - onError: (Throwable) -> Unit, - onCompleted: () -> Unit): Subscription { + fun Observable.subscribeUntilDestroy( + onNext: (T) -> Unit, + onError: (Throwable) -> Unit, + onCompleted: () -> Unit + ): Subscription { return subscribe(onNext, onError, onCompleted).also { untilDestroySubscriptions.add(it) } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SecondaryDrawerController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SecondaryDrawerController.kt index 8a3229dd85..93db2ef342 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SecondaryDrawerController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SecondaryDrawerController.kt @@ -1,7 +1,7 @@ package eu.kanade.tachiyomi.ui.base.controller -import androidx.drawerlayout.widget.DrawerLayout import android.view.ViewGroup +import androidx.drawerlayout.widget.DrawerLayout interface SecondaryDrawerController { 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 2720eac37a..c4953b85d6 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 @@ -1,17 +1,17 @@ package eu.kanade.tachiyomi.ui.base.holder import android.view.View -import androidx.recyclerview.widget.RecyclerView -import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.viewholders.FlexibleViewHolder import kotlinx.android.extensions.LayoutContainer -abstract class BaseFlexibleViewHolder(view: View, - adapter: FlexibleAdapter<*>, - stickyHeader: Boolean = false) : +abstract class BaseFlexibleViewHolder( + view: View, + adapter: FlexibleAdapter<*>, + stickyHeader: Boolean = false +) : FlexibleViewHolder(view, adapter, stickyHeader), LayoutContainer { override val containerView: View? get() = itemView -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseViewHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseViewHolder.kt index 9c0112e6da..481262c923 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseViewHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseViewHolder.kt @@ -1,7 +1,7 @@ package eu.kanade.tachiyomi.ui.base.holder -import androidx.recyclerview.widget.RecyclerView import android.view.View +import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer abstract class BaseViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view), LayoutContainer { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/SlicedHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/SlicedHolder.kt index 499c4056c6..d31e6062d1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/SlicedHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/SlicedHolder.kt @@ -41,8 +41,13 @@ interface SlicedHolder { } } - private fun applySlice(radius: Float, topRect: Boolean, bottomRect: Boolean, - topShadow: Boolean, bottomShadow: Boolean) { + private fun applySlice( + radius: Float, + topRect: Boolean, + bottomRect: Boolean, + topShadow: Boolean, + bottomShadow: Boolean + ) { val margin = margin slice.setRadius(radius) @@ -62,5 +67,4 @@ interface SlicedHolder { val margin get() = 8.dpToPx - } 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 130362f51b..74375832a9 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 @@ -23,8 +23,8 @@ open class BasePresenter : RxPresenter() { * @param onNext function to execute when the observable emits an item. * @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) } + fun Observable.subscribeFirst(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = + compose(deliverFirst()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [deliverLatestCache] and adds it to the presenter's lifecycle @@ -33,8 +33,8 @@ open class BasePresenter : RxPresenter() { * @param onNext function to execute when the observable emits an item. * @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) } + fun Observable.subscribeLatestCache(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = + compose(deliverLatestCache()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [deliverReplay] and adds it to the presenter's lifecycle @@ -43,8 +43,8 @@ open class BasePresenter : RxPresenter() { * @param onNext function to execute when the observable emits an item. * @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) } + fun Observable.subscribeReplay(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = + compose(deliverReplay()).subscribe(split(onNext, onError)).apply { add(this) } /** * Subscribes an observable with [DeliverWithView] and adds it to the presenter's lifecycle @@ -53,8 +53,8 @@ open class BasePresenter : RxPresenter() { * @param onNext function to execute when the observable emits an item. * @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) } + fun Observable.subscribeWithView(onNext: (V, T) -> Unit, onError: ((V, Throwable) -> Unit)? = null) = + 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. @@ -70,5 +70,4 @@ open class BasePresenter : RxPresenter() { } } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorDelegate.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorDelegate.kt index bce36974bd..cd07ed478a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorDelegate.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorDelegate.kt @@ -43,5 +43,4 @@ class NucleusConductorDelegate

>(private val factory: PresenterF fun onDestroy() { presenter?.destroy() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorLifecycleListener.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorLifecycleListener.kt index 0e25020337..f59febccfa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorLifecycleListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/base/presenter/NucleusConductorLifecycleListener.kt @@ -29,5 +29,4 @@ class NucleusConductorLifecycleListener(private val delegate: NucleusConductorDe companion object { private const val PRESENTER_STATE_KEY = "presenter_state" } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueAdapter.kt index 6c92007313..ca78228789 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueAdapter.kt @@ -45,4 +45,3 @@ class CatalogueAdapter(val controller: CatalogueController) : fun onLatestClick(position: Int) } } - diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueController.kt index 8d11a52275..7725802e45 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CatalogueController.kt @@ -33,13 +33,13 @@ import eu.kanade.tachiyomi.util.view.applyWindowInsetsForRootController import eu.kanade.tachiyomi.util.view.scrollViewWith import eu.kanade.tachiyomi.util.view.setOnQueryTextChangeListener import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog +import kotlin.math.max import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.catalogue_main_controller.* import kotlinx.android.synthetic.main.extensions_bottom_sheet.* import kotlinx.android.synthetic.main.main_activity.* import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import kotlin.math.max /** * This controller shows and manages the different catalogues enabled by the user. @@ -131,7 +131,7 @@ class CatalogueController : NucleusController(), recycler.addItemDecoration(SourceDividerItemDecoration(view.context)) val attrsArray = intArrayOf(android.R.attr.actionBarSize) val array = view.context.obtainStyledAttributes(attrsArray) - val appBarHeight = array.getDimensionPixelSize(0, 0) + val appBarHeight = array.getDimensionPixelSize(0, 0) array.recycle() scrollViewWith(recycler) { headerHeight = it.systemWindowInsetTop + appBarHeight @@ -160,7 +160,7 @@ class CatalogueController : NucleusController(), state == BottomSheetBehavior.STATE_COLLAPSED) { sheet_layout.alpha = if (state == BottomSheetBehavior.STATE_COLLAPSED) 1f else 0f - showingExtenions = state == BottomSheetBehavior.STATE_EXPANDED + showingExtenions = state == BottomSheetBehavior.STATE_EXPANDED setTitle() activity?.invalidateOptionsMenu() } @@ -175,7 +175,6 @@ class CatalogueController : NucleusController(), if (showingExtenions) { ext_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED } - } fun showExtensions() { @@ -185,8 +184,7 @@ class CatalogueController : NucleusController(), fun toggleExtensions() { if (ext_bottom_sheet.sheetBehavior?.state != BottomSheetBehavior.STATE_COLLAPSED) { ext_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED - } - else { + } else { ext_bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED } } @@ -288,8 +286,7 @@ class CatalogueController : NucleusController(), ext_bottom_sheet.drawExtensions() true } - } - else { + } else { // Inflate menu inflater.inflate(R.menu.catalogue_main, menu) @@ -308,7 +305,7 @@ class CatalogueController : NucleusController(), } } - private fun performGlobalSearch(query: String){ + private fun performGlobalSearch(query: String) { router.pushController(CatalogueSearchController(query).withFadeTransaction()) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt index ae5611e70a..cd538a92a6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt @@ -7,13 +7,13 @@ import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter +import java.util.TreeMap +import java.util.concurrent.TimeUnit import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.TreeMap -import java.util.concurrent.TimeUnit /** * Presenter of [CatalogueController] @@ -23,8 +23,8 @@ import java.util.concurrent.TimeUnit * @param preferences application preferences. */ class CataloguePresenter( - val sourceManager: SourceManager = Injekt.get(), - private val preferences: PreferencesHelper = Injekt.get() + val sourceManager: SourceManager = Injekt.get(), + private val preferences: PreferencesHelper = Injekt.get() ) : BasePresenter() { /** @@ -101,4 +101,4 @@ class CataloguePresenter( .sortedBy { "(${it.lang}) ${it.name}" } + sourceManager.get(LocalSource.ID) as LocalSource } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangHolder.kt index 2d6dc40e53..c2cc7b36f8 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangHolder.kt @@ -1,10 +1,10 @@ package eu.kanade.tachiyomi.ui.catalogue import android.view.View -import eu.davidea.flexibleadapter.FlexibleAdapter -import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import androidx.recyclerview.widget.RecyclerView +import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible +import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.util.system.LocaleHelper import kotlinx.android.synthetic.main.catalogue_main_controller_card.title diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangItem.kt index c3f15a3f50..8e3167f358 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/LangItem.kt @@ -34,5 +34,4 @@ data class LangItem(val code: String) : AbstractHeaderItem() { override fun bindViewHolder(adapter: FlexibleAdapter>, holder: LangHolder, position: Int, payloads: MutableList) { holder.bind(this) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceDividerItemDecoration.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceDividerItemDecoration.kt index 0475b90276..b6cd968408 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceDividerItemDecoration.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceDividerItemDecoration.kt @@ -4,8 +4,8 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable -import androidx.recyclerview.widget.RecyclerView import android.view.View +import androidx.recyclerview.widget.RecyclerView class SourceDividerItemDecoration(context: Context) : androidx.recyclerview.widget.RecyclerView.ItemDecoration() { @@ -36,9 +36,12 @@ class SourceDividerItemDecoration(context: Context) : androidx.recyclerview.widg } } - override fun getItemOffsets(outRect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, - state: androidx.recyclerview.widget.RecyclerView.State) { + override fun getItemOffsets( + outRect: Rect, + view: View, + parent: androidx.recyclerview.widget.RecyclerView, + state: androidx.recyclerview.widget.RecyclerView.State + ) { outRect.set(0, 0, 0, divider.intrinsicHeight) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceItem.kt index 830f82b891..6bd24406e7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/SourceItem.kt @@ -37,5 +37,4 @@ data class SourceItem(val source: CatalogueSource, val header: LangItem? = null) override fun bindViewHolder(adapter: FlexibleAdapter>, holder: SourceHolder, position: Int, payloads: MutableList) { holder.bind(this) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCatalogueController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCatalogueController.kt index 2588d7cfa1..91be18e4c9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCatalogueController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCatalogueController.kt @@ -47,13 +47,13 @@ import eu.kanade.tachiyomi.util.view.updateLayoutParams import eu.kanade.tachiyomi.util.view.updatePaddingRelative import eu.kanade.tachiyomi.util.view.visible import eu.kanade.tachiyomi.widget.AutofitRecyclerView +import java.util.concurrent.TimeUnit import kotlinx.android.synthetic.main.catalogue_controller.* import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.util.concurrent.TimeUnit /** * Controller to manage the catalogues available in the app. @@ -66,12 +66,14 @@ open class BrowseCatalogueController(bundle: Bundle) : FlexibleAdapter.EndlessScrollListener, ChangeMangaCategoriesDialog.Listener { - constructor(source: CatalogueSource, + constructor( + source: CatalogueSource, searchQuery: String? = null, - smartSearchConfig: CatalogueController.SmartSearchConfig? = null) : this(Bundle().apply { + smartSearchConfig: CatalogueController.SmartSearchConfig? = null + ) : this(Bundle().apply { putLong(SOURCE_ID_KEY, source.id) - if(searchQuery != null) + if (searchQuery != null) putString(SEARCH_QUERY_KEY, searchQuery) if (smartSearchConfig != null) @@ -582,5 +584,4 @@ open class BrowseCatalogueController(bundle: Bundle) : const val SEARCH_QUERY_KEY = "searchQuery" const val SMART_SEARCH_CONFIG_KEY = "smartSearchConfig" } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCataloguePresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCataloguePresenter.kt index d93c36e924..aeabe520fc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCataloguePresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/BrowseCataloguePresenter.kt @@ -16,7 +16,19 @@ import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter -import eu.kanade.tachiyomi.ui.catalogue.filter.* +import eu.kanade.tachiyomi.ui.catalogue.filter.CheckboxItem +import eu.kanade.tachiyomi.ui.catalogue.filter.CheckboxSectionItem +import eu.kanade.tachiyomi.ui.catalogue.filter.GroupItem +import eu.kanade.tachiyomi.ui.catalogue.filter.HeaderItem +import eu.kanade.tachiyomi.ui.catalogue.filter.SelectItem +import eu.kanade.tachiyomi.ui.catalogue.filter.SelectSectionItem +import eu.kanade.tachiyomi.ui.catalogue.filter.SeparatorItem +import eu.kanade.tachiyomi.ui.catalogue.filter.SortGroup +import eu.kanade.tachiyomi.ui.catalogue.filter.SortItem +import eu.kanade.tachiyomi.ui.catalogue.filter.TextItem +import eu.kanade.tachiyomi.ui.catalogue.filter.TextSectionItem +import eu.kanade.tachiyomi.ui.catalogue.filter.TriStateItem +import eu.kanade.tachiyomi.ui.catalogue.filter.TriStateSectionItem import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers @@ -30,11 +42,11 @@ import uy.kohesive.injekt.api.get * Presenter of [BrowseCatalogueController]. */ open class BrowseCataloguePresenter( - sourceId: Long, - sourceManager: SourceManager = Injekt.get(), - private val db: DatabaseHelper = Injekt.get(), - private val prefs: PreferencesHelper = Injekt.get(), - private val coverCache: CoverCache = Injekt.get() + sourceId: Long, + sourceManager: SourceManager = Injekt.get(), + private val db: DatabaseHelper = Injekt.get(), + private val prefs: PreferencesHelper = Injekt.get(), + private val coverCache: CoverCache = Injekt.get() ) : BasePresenter() { /** @@ -217,8 +229,7 @@ open class BrowseCataloguePresenter( val result = db.insertManga(newManga).executeAsBlocking() newManga.id = result.insertedId() localManga = newManga - } - else if (localManga.title.isBlank()) { + } else if (localManga.title.isBlank()) { localManga.title = sManga.title db.insertManga(localManga).executeAsBlocking() } @@ -264,7 +275,7 @@ open class BrowseCataloguePresenter( fun confirmDeletion(manga: Manga) { coverCache.deleteFromCache(manga.thumbnail_url) val downloadManager: DownloadManager = Injekt.get() - downloadManager.deleteManga(manga,source) + downloadManager.deleteManga(manga, source) db.resetMangaInfo(manga).executeAsBlocking() } @@ -381,5 +392,4 @@ open class BrowseCataloguePresenter( changeMangaFavorite(manga) } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueGridHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueGridHolder.kt index cf3fac6e5d..db9088ffca 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueGridHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueGridHolder.kt @@ -25,7 +25,8 @@ import kotlinx.android.synthetic.main.unread_download_badge.* */ class CatalogueGridHolder( private val view: View, - private val adapter: FlexibleAdapter>) : + private val adapter: FlexibleAdapter> +) : CatalogueHolder(view, adapter) { /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueHolder.kt index 2356d1686f..722c731668 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueHolder.kt @@ -1,11 +1,11 @@ package eu.kanade.tachiyomi.ui.catalogue.browse import android.view.View +import androidx.recyclerview.widget.RecyclerView import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder -import androidx.recyclerview.widget.RecyclerView -import eu.davidea.flexibleadapter.items.IFlexible /** * Generic class used to hold the displayed data of a manga in the catalogue. @@ -24,7 +24,6 @@ abstract class CatalogueHolder(view: View, adapter: FlexibleAdapter>, - holder: CatalogueHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: CatalogueHolder, + position: Int, + payloads: MutableList? + ) { holder.onSetValues(manga) } @@ -68,5 +70,4 @@ class CatalogueItem(val manga: Manga, private val catalogueAsList: Preference> = FlexibleAdapter>(null) .setDisplayHeadersAtStartUp(true) @@ -42,5 +40,4 @@ class CatalogueNavigationView @JvmOverloads constructor(context: Context, attrs: fun setFilters(items: List>) { adapter.updateDataSet(items) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CataloguePager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CataloguePager.kt index a7b563074a..08dad01c28 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CataloguePager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CataloguePager.kt @@ -28,5 +28,4 @@ open class CataloguePager(val source: CatalogueSource, val query: String, val fi } } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/NoResultsException.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/NoResultsException.kt index 723782f5e5..ae6f39bcda 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/NoResultsException.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/NoResultsException.kt @@ -1,3 +1,3 @@ package eu.kanade.tachiyomi.ui.catalogue.browse -class NoResultsException : Exception() \ No newline at end of file +class NoResultsException : Exception() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/Pager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/Pager.kt index 104e5887df..62b88aa855 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/Pager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/Pager.kt @@ -27,5 +27,4 @@ abstract class Pager(var currentPage: Int = 1) { hasNextPage = mangasPage.hasNextPage && mangasPage.mangas.isNotEmpty() results.call(Pair(page, mangasPage.mangas)) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt index 3080240307..398df17b73 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt @@ -10,7 +10,6 @@ import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R - class ProgressItem : AbstractFlexibleItem() { private var loadMore = true @@ -47,5 +46,4 @@ class ProgressItem : AbstractFlexibleItem() { val progressBar: ProgressBar = view.findViewById(R.id.progress_bar) val progressMessage: TextView = view.findViewById(R.id.progress_message) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/GroupItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/GroupItem.kt index a54f6c0edd..d252cb3f03 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/GroupItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/GroupItem.kt @@ -40,7 +40,6 @@ class GroupItem(val filter: Filter.Group<*>) : AbstractExpandableHeaderItem) : AbstractExpandableHeaderItem>) : ExpandableViewHolder(view, adapter, true) { val title: TextView = itemView.findViewById(R.id.title) @@ -62,6 +60,5 @@ class GroupItem(val filter: Filter.Group<*>) : AbstractExpandableHeaderItem>, - holder: Holder, position: Int, payloads: MutableList?) { - + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: Holder, + position: Int, + payloads: MutableList? + ) { } override fun equals(other: Any?): Boolean { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortGroup.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortGroup.kt index 6c7f867dc9..1e65a3fd26 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortGroup.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortGroup.kt @@ -37,7 +37,6 @@ class SortGroup(val filter: Filter.Sort) : AbstractExpandableHeaderItem() { @@ -73,5 +73,4 @@ open class TriStateItem(val filter: Filter.TriState) : AbstractFlexibleItem>, holder: CatalogueSearchCardHolder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: CatalogueSearchCardHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(manga) } @@ -33,5 +37,4 @@ class CatalogueSearchCardItem(val manga: Manga) : AbstractFlexibleItem(), CatalogueSearchCardAdapter.OnMangaClickListener { @@ -35,7 +35,7 @@ open class CatalogueSearchController( */ protected var adapter: CatalogueSearchAdapter? = null - private var customTitle:String? = null + private var customTitle: String? = null /** * Called when controller is initialized. @@ -144,8 +144,7 @@ open class CatalogueSearchController( recycler.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(view.context) recycler.adapter = adapter recycler.setOnApplyWindowInsetsListener(RecyclerWindowInsetsListener) - if (extensionFilter != null) - { + if (extensionFilter != null) { customTitle = view.context?.getString(R.string.loading) setTitle() } @@ -199,8 +198,7 @@ open class CatalogueSearchController( .withFadeTransaction() ) return - } - else if (results != null) { + } else if (results != null) { customTitle = null setTitle() activity?.invalidateOptionsMenu() @@ -217,5 +215,4 @@ open class CatalogueSearchController( fun onMangaInitialized(source: CatalogueSource, manga: Manga) { getHolder(source)?.setImage(manga) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchHolder.kt index 678b9a8be1..32248dd775 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchHolder.kt @@ -1,8 +1,7 @@ package eu.kanade.tachiyomi.ui.catalogue.global_search -import androidx.recyclerview.widget.LinearLayoutManager import android.view.View -import eu.kanade.tachiyomi.R +import androidx.recyclerview.widget.LinearLayoutManager import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.util.view.gone @@ -105,5 +104,4 @@ class CatalogueSearchHolder(view: View, val adapter: CatalogueSearchAdapter) : title.gone() source_card.gone() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchItem.kt index 54796d3f98..c8408f2109 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchItem.kt @@ -15,8 +15,8 @@ import eu.kanade.tachiyomi.source.CatalogueSource * @param results the search results. * @param highlighted whether this search item should be highlighted/marked in the catalogue search view. */ -class CatalogueSearchItem(val source: CatalogueSource, val results: List?, val highlighted: Boolean = false) - : AbstractFlexibleItem() { +class CatalogueSearchItem(val source: CatalogueSource, val results: List?, val highlighted: Boolean = false) : + AbstractFlexibleItem() { /** * Set view. @@ -39,8 +39,12 @@ class CatalogueSearchItem(val source: CatalogueSource, val results: List>, holder: CatalogueSearchHolder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: CatalogueSearchHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this) } @@ -64,5 +68,4 @@ class CatalogueSearchItem(val source: CatalogueSource, val results: List() { /** @@ -74,11 +74,13 @@ open class CatalogueSearchPresenter( override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) - extensionFilter = savedState?.getString(CatalogueSearchPresenter::extensionFilter.name) ?: - initialExtensionFilter + extensionFilter = savedState?.getString(CatalogueSearchPresenter::extensionFilter.name) + ?: initialExtensionFilter // Perform a search with previous or initial state - search(savedState?.getString(BrowseCataloguePresenter::query.name) ?: initialQuery.orEmpty()) + search( + savedState?.getString(BrowseCataloguePresenter::query.name) ?: initialQuery.orEmpty() + ) } override fun onDestroy() { @@ -102,11 +104,10 @@ open class CatalogueSearchPresenter( val languages = preferencesHelper.enabledLanguages().getOrDefault() val hiddenCatalogues = preferencesHelper.hiddenCatalogues().getOrDefault() - return sourceManager.getCatalogueSources() - .filter { it.lang in languages } - .filterNot { it is LoginSource && !it.isLogged() } - .filterNot { it.id.toString() in hiddenCatalogues } - .sortedBy { "(${it.lang}) ${it.name}" } + return sourceManager.getCatalogueSources().filter { it.lang in languages } + .filterNot { it is LoginSource && !it.isLogged() } + .filterNot { it.id.toString() in hiddenCatalogues } + .sortedBy { "(${it.lang}) ${it.name}" } } private fun getSourcesToQuery(): List { @@ -116,10 +117,8 @@ open class CatalogueSearchPresenter( return enabledSources } - val filterSources = extensionManager.installedExtensions - .filter { it.pkgName == filter } - .flatMap { it.sources } - .filter { it in enabledSources } + val filterSources = extensionManager.installedExtensions.filter { it.pkgName == filter } + .flatMap { it.sources }.filter { it in enabledSources } .filterIsInstance() if (filterSources.isEmpty()) { @@ -132,7 +131,10 @@ open class CatalogueSearchPresenter( /** * Creates a catalogue search item */ - protected open fun createCatalogueSearchItem(source: CatalogueSource, results: List?): CatalogueSearchItem { + protected open fun createCatalogueSearchItem( + source: CatalogueSource, + results: List? + ): CatalogueSearchItem { return CatalogueSearchItem(source, results) } @@ -156,30 +158,42 @@ open class CatalogueSearchPresenter( var items = initialItems fetchSourcesSubscription?.unsubscribe() - fetchSourcesSubscription = Observable.from(sources) - .flatMap({ source -> - Observable.defer { source.fetchSearchManga(1, query, FilterList()) } - .subscribeOn(Schedulers.io()) - .onErrorReturn { MangasPage(emptyList(), false) } // Ignore timeouts or other exceptions - .map { it.mangas.take(10) } // Get at most 10 manga from search result. - .map { it.map { networkToLocalManga(it, source.id) } } // Convert to local manga. - .doOnNext { fetchImage(it, source) } // Load manga covers. - .map { createCatalogueSearchItem(source, it.map { CatalogueSearchCardItem(it) }) } - }, 5) - .observeOn(AndroidSchedulers.mainThread()) - // Update matching source with the obtained results - .map { result -> - items.map { item -> if (item.source == result.source) result else item } - } - // Update current state - .doOnNext { items = it } - // Deliver initial state - .startWith(initialItems) - .subscribeLatestCache({ view, manga -> - view.setItems(manga) - }, { _, error -> - Timber.e(error) - }) + fetchSourcesSubscription = Observable.from(sources).flatMap({ source -> + Observable.defer { source.fetchSearchManga(1, query, FilterList()) } + .subscribeOn(Schedulers.io()).onErrorReturn { + MangasPage( + emptyList(), + false + ) + } // Ignore timeouts or other exceptions + .map { it.mangas.take(10) } // Get at most 10 manga from search result. + .map { + it.map { + networkToLocalManga( + it, + source.id + ) + } + } // Convert to local manga. + .doOnNext { fetchImage(it, source) } // Load manga covers. + .map { + createCatalogueSearchItem( + source, + it.map { CatalogueSearchCardItem(it) }) + } + }, 5).observeOn(AndroidSchedulers.mainThread()) + // Update matching source with the obtained results + .map { result -> + items.map { item -> if (item.source == result.source) result else item } + } + // Update current state + .doOnNext { items = it } + // Deliver initial state + .startWith(initialItems).subscribeLatestCache({ view, manga -> + view.setItems(manga) + }, { _, error -> + Timber.e(error) + }) } /** @@ -196,23 +210,18 @@ open class CatalogueSearchPresenter( */ 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) - }) + 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) + }) } /** @@ -222,14 +231,12 @@ open class CatalogueSearchPresenter( * @return an observable of the manga to initialize */ 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) } + return source.fetchMangaDetails(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/catalogue/latest/LatestUpdatesController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesController.kt index 41c133a820..8eb53859f6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesController.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.ui.catalogue.latest import android.os.Bundle -import androidx.drawerlayout.widget.DrawerLayout import android.view.Menu import android.view.ViewGroup +import androidx.drawerlayout.widget.DrawerLayout import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.ui.catalogue.browse.BrowseCatalogueController @@ -33,7 +33,5 @@ class LatestUpdatesController(bundle: Bundle) : BrowseCatalogueController(bundle } override fun cleanupSecondaryDrawer(drawer: androidx.drawerlayout.widget.DrawerLayout) { - } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPager.kt index 2e646638b7..704b375c00 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPager.kt @@ -10,7 +10,7 @@ import rx.schedulers.Schedulers /** * LatestUpdatesPager inherited from the general Pager. */ -class LatestUpdatesPager(val source: CatalogueSource): Pager() { +class LatestUpdatesPager(val source: CatalogueSource) : Pager() { override fun requestNext(): Observable { return source.fetchLatestUpdates(currentPage) @@ -18,5 +18,4 @@ class LatestUpdatesPager(val source: CatalogueSource): Pager() { .observeOn(AndroidSchedulers.mainThread()) .doOnNext { onPageReceived(it) } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPresenter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPresenter.kt index a1be55797b..9b514528a3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPresenter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/latest/LatestUpdatesPresenter.kt @@ -12,5 +12,4 @@ class LatestUpdatesPresenter(sourceId: Long) : BrowseCataloguePresenter(sourceId override fun createPager(query: String, filters: FilterList): Pager { return LatestUpdatesPager(source) } - -} \ No newline at end of file +} 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 2525ec7fff..c1ef5d5af6 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 @@ -34,5 +34,4 @@ class CategoryAdapter(controller: CategoryController) : fun onCategoryRename(position: Int, newName: String): Boolean fun onItemDelete(position: Int) } - } 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 fdbe171132..8b3b7e69e5 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 @@ -218,5 +218,4 @@ class CategoryController(bundle: Bundle? = null) : BaseController(bundle), fun onCategoryExistsError() { activity?.toast(R.string.error_category_exists) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryCreateDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryCreateDialog.kt index c6d0cc37a7..988ed75d3e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryCreateDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryCreateDialog.kt @@ -37,5 +37,4 @@ class CategoryCreateDialog(bundle: Bundle? = null) : DialogController(bundle) interface Listener { fun createCategory(name: String) } - } 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 8f4cb3deee..5e269fbd74 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 @@ -57,15 +57,13 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie edit_button.setImageDrawable(null) edit_text.setText("") edit_text.hint = title.text - } - else { + } else { title.setTextColor(ContextCompat.getColor(itemView.context, R.color.textColorPrimary)) regularDrawable = ContextCompat.getDrawable(itemView.context, R.drawable .ic_reorder_grey_24dp) image.visible() edit_text.setText(title.text) } - } fun isEditing(editing: Boolean) { @@ -89,15 +87,13 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie adapter.categoryItemListener.onItemDelete(adapterPosition) } } - } - else { + } else { if (!createCategory) { setDragHandleView(reorder) edit_button.setImageDrawable(ContextCompat.getDrawable(itemView.context, R.drawable.ic_edit_white_24dp)) - } - else { + } else { edit_button.setImageDrawable(null) - reorder.setOnTouchListener { _, _ -> true} + reorder.setOnTouchListener { _, _ -> true } } edit_text.clearFocus() edit_button.drawable?.mutate()?.setTint(ContextCompat.getColor(itemView.context, R @@ -107,7 +103,7 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie } private fun submitChanges() { - if (edit_text.visibility == View.VISIBLE ) { + if (edit_text.visibility == View.VISIBLE) { if (adapter.categoryItemListener .onCategoryRename(adapterPosition, edit_text.text.toString())) { isEditing(false) @@ -115,8 +111,7 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie if (!createCategory) title.text = edit_text.text.toString() } - } - else { + } else { itemView.performClick() } } @@ -137,5 +132,4 @@ class CategoryHolder(view: View, val adapter: CategoryAdapter) : BaseFlexibleVie super.onItemReleased(position) adapter.categoryItemListener.onItemReleased(position) } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryItem.kt index f35bdb3627..f445e71f11 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryItem.kt @@ -67,5 +67,4 @@ class CategoryItem(val category: Category) : AbstractFlexibleItem(bundle: Bundle? = null) : DialogController(bundle) private companion object { const val CATEGORY_KEY = "CategoryRenameDialog.category" } - } 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 5f4a01851f..1ff691b163 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 @@ -13,8 +13,8 @@ import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.download_button.view.* -class DownloadButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) - : FrameLayout(context, attrs) { +class DownloadButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : + FrameLayout(context, attrs) { private val activeColor = context.getResourceColor(R.attr.colorAccent) private val progressBGColor = ContextCompat.getColor(context, @@ -30,8 +30,7 @@ class DownloadButton @JvmOverloads constructor(context: Context, attrs: Attribut private val borderCircle = ContextCompat.getDrawable(context, R.drawable.border_circle)?.mutate() private var isAnimating = false - private var iconAnimation:ObjectAnimator? = null - + private var iconAnimation: ObjectAnimator? = null fun setDownloadStatus(state: Int, progress: Int = 0) { if (state != Download.DOWNLOADING) { @@ -93,4 +92,4 @@ class DownloadButton @JvmOverloads constructor(context: Context, attrs: Attribut } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadController.kt index bf9f96ddca..2b9d86a69c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadController.kt @@ -14,12 +14,12 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.view.RecyclerWindowInsetsListener import eu.kanade.tachiyomi.util.view.applyWindowInsetsForController +import java.util.HashMap +import java.util.concurrent.TimeUnit import kotlinx.android.synthetic.main.download_controller.* import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers -import java.util.HashMap -import java.util.concurrent.TimeUnit /** * Controller that shows the currently active downloads. @@ -310,5 +310,4 @@ class DownloadController : NucleusController(), } } } - } 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 43eb60f39c..4fff93ac3c 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 @@ -57,7 +57,6 @@ class DownloadHolder(private val view: View, val adapter: DownloadAdapter) : .getResourceColor(R.attr.icon_color)) } - /** * Updates the progress bar of the download. */ @@ -82,7 +81,6 @@ class DownloadHolder(private val view: View, val adapter: DownloadAdapter) : adapter.downloadItemListener.onItemReleased(position) } - private fun showPopupMenu(view: View) { val item = adapter.getItem(adapterPosition) ?: return @@ -98,7 +96,6 @@ class DownloadHolder(private val view: View, val adapter: DownloadAdapter) : popup.menu.findItem(R.id.move_to_bottom).isVisible = adapterPosition != adapter .itemCount - 1 - // Set a listener so we are notified if a menu item is clicked popup.setOnMenuItemClickListener { menuItem -> adapter.downloadItemListener.onMenuItemClick(adapterPosition, menuItem) @@ -108,5 +105,4 @@ class DownloadHolder(private val view: View, val adapter: DownloadAdapter) : // Finally show the PopupMenu popup.show() } - } 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 5627ea127f..b8fef48d1c 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 @@ -28,8 +28,11 @@ class DownloadItem(val download: Download) : AbstractFlexibleItem>): DownloadHolder { + override fun createViewHolder( + view: View, + adapter: FlexibleAdapter> + ): DownloadHolder { return DownloadHolder(view, adapter as DownloadAdapter) } @@ -41,8 +44,12 @@ class DownloadItem(val download: Download) : AbstractFlexibleItem>, - holder: DownloadHolder, position: Int, payloads: MutableList) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: DownloadHolder, + position: Int, + payloads: MutableList + ) { holder.bind(download) } @@ -64,5 +71,4 @@ class DownloadItem(val download: Download) : AbstractFlexibleItem() { fun cancelDownload(download: Download) { downloadManager.deletePendingDownloads(download) } - } 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 43d9c22b7a..807c6baac9 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 @@ -8,6 +8,8 @@ import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.util.system.LocaleHelper +import java.util.concurrent.TimeUnit +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -16,11 +18,9 @@ import rx.Subscription import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.concurrent.TimeUnit -import kotlin.coroutines.CoroutineContext -typealias ExtensionTuple - = Triple, List, List> +typealias ExtensionTuple = + Triple, List, List> /** * Presenter of [ExtensionBottomSheet]. @@ -48,8 +48,7 @@ open class ExtensionBottomPresenter( val availableObservable = extensionManager.getAvailableExtensionsObservable() .startWith(emptyList()) - return Observable.combineLatest(installedObservable, untrustedObservable, availableObservable) - { installed, untrusted, available -> Triple(installed, untrusted, available) } + return Observable.combineLatest(installedObservable, untrustedObservable, availableObservable) { installed, untrusted, available -> Triple(installed, untrusted, available) } .debounce(100, TimeUnit.MILLISECONDS) .map(::toItems) .observeOn(AndroidSchedulers.mainThread()) @@ -71,9 +70,9 @@ open 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()) { @@ -103,7 +102,7 @@ open class ExtensionBottomPresenter( return items } - fun getExtensionUpdateCount():Int = preferences.extensionUpdatesCount().getOrDefault() + fun getExtensionUpdateCount(): Int = preferences.extensionUpdatesCount().getOrDefault() fun getAutoCheckPref() = preferences.automaticExtUpdates() @Synchronized @@ -152,5 +151,4 @@ open class ExtensionBottomPresenter( fun trustSignature(signatureHash: String) { extensionManager.trustSignature(signatureHash) } - } 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 7f2a106715..7802e9c166 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 @@ -23,15 +23,15 @@ import eu.kanade.tachiyomi.util.view.doOnApplyWindowInsets import eu.kanade.tachiyomi.util.view.updateLayoutParams import kotlinx.android.synthetic.main.extensions_bottom_sheet.view.* -class ExtensionBottomSheet @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) -: LinearLayout(context, attrs), +class ExtensionBottomSheet @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : +LinearLayout(context, attrs), ExtensionAdapter.OnButtonClickListener, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, ExtensionTrustDialog.Listener { var sheetBehavior: BottomSheetBehavior<*>? = null - lateinit var autoCheckItem:AutoCheckItem + lateinit var autoCheckItem: AutoCheckItem /** * Adapter containing the list of manga from the catalogue. @@ -60,7 +60,7 @@ ExtensionAdapter.OnButtonClickListener, val attrsArray = intArrayOf(android.R.attr.actionBarSize) val array = context.obtainStyledAttributes(attrsArray) - val headerHeight = array.getDimensionPixelSize(0, 0) + val headerHeight = array.getDimensionPixelSize(0, 0) array.recycle() ext_recycler.doOnApplyWindowInsets { _, windowInsets, _ -> ext_recycler.updateLayoutParams { @@ -136,7 +136,7 @@ ExtensionAdapter.OnButtonClickListener, } fun setExtensions(extensions: List) { - //ext_swipe_refresh?.isRefreshing = false + // ext_swipe_refresh?.isRefreshing = false this.extensions = extensions controller.presenter.updateSources() drawExtensions() @@ -183,7 +183,8 @@ class AutoCheckItem(private val autoCheck: Preference) : AbstractHeader } override fun createViewHolder( - view: View, adapter: FlexibleAdapter> + view: View, + adapter: FlexibleAdapter> ): AutoCheckHolder { return AutoCheckHolder(view, adapter, autoCheck) } @@ -194,7 +195,7 @@ class AutoCheckItem(private val autoCheck: Preference) : AbstractHeader position: Int, payloads: MutableList? ) { - //holder.bind(autoCheck.getOrDefault()) + // holder.bind(autoCheck.getOrDefault()) } override fun equals(other: Any?): Boolean { @@ -205,8 +206,11 @@ class AutoCheckItem(private val autoCheck: Preference) : AbstractHeader return -1 } - class AutoCheckHolder(val view: View, private val adapter: FlexibleAdapter>, - autoCheck: Preference) : + class AutoCheckHolder( + val view: View, + private val adapter: FlexibleAdapter>, + autoCheck: Preference + ) : FlexibleViewHolder(view, adapter, true) { private val autoCheckbox: CheckBox = view.findViewById(R.id.auto_checkbox) @@ -222,4 +226,4 @@ class AutoCheckItem(private val autoCheck: Preference) : AbstractHeader setOnCheckedChangeListener { _, isChecked -> pref.set(isChecked) } } } -} \ No newline at end of file +} 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 9371e11d7f..6eb7faf17a 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 @@ -223,5 +223,4 @@ class ExtensionDetailsController(bundle: Bundle? = null) : const val PKGNAME_KEY = "pkg_name" const val LASTOPENPREFERENCE_KEY = "last_open_preference" } - } 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 1b9b958f06..93b79d4670 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 @@ -8,8 +8,8 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class ExtensionDetailsPresenter( - val pkgName: String, - private val extensionManager: ExtensionManager = Injekt.get() + val pkgName: String, + private val extensionManager: ExtensionManager = Injekt.get() ) : BasePresenter() { val extension = extensionManager.installedExtensions.find { it.pkgName == pkgName } 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 cc99508e31..b4ed5f103f 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 @@ -4,8 +4,8 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable -import androidx.recyclerview.widget.RecyclerView import android.view.View +import androidx.recyclerview.widget.RecyclerView class ExtensionDividerItemDecoration(context: Context) : androidx.recyclerview.widget.RecyclerView.ItemDecoration() { @@ -36,9 +36,12 @@ class ExtensionDividerItemDecoration(context: Context) : androidx.recyclerview.w } } - override fun getItemOffsets(outRect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, - state: androidx.recyclerview.widget.RecyclerView.State) { + override fun getItemOffsets( + outRect: Rect, + view: View, + parent: androidx.recyclerview.widget.RecyclerView, + state: androidx.recyclerview.widget.RecyclerView.State + ) { outRect.set(0, 0, 0, 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 01a53c647d..5f8d852536 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 @@ -2,11 +2,11 @@ package eu.kanade.tachiyomi.ui.extension import android.annotation.SuppressLint import android.view.View +import androidx.recyclerview.widget.RecyclerView import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import kotlinx.android.synthetic.main.extension_card_header.title -import androidx.recyclerview.widget.RecyclerView -import eu.davidea.flexibleadapter.items.IFlexible class ExtensionGroupHolder(view: View, adapter: FlexibleAdapter>) : BaseFlexibleViewHolder(view, adapter) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupItem.kt index 36923297c6..186ef930ca 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/ExtensionGroupItem.kt @@ -32,8 +32,12 @@ data class ExtensionGroupItem(val name: String, val size: Int) : AbstractHeaderI /** * Binds this item to the given view holder. */ - override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ExtensionGroupHolder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: ExtensionGroupHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this) } @@ -49,5 +53,4 @@ data class ExtensionGroupItem(val name: String, val size: Int) : AbstractHeaderI override fun hashCode(): Int { return name.hashCode() } - } 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 e7a8127913..b7382d0d40 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 @@ -103,5 +103,4 @@ class ExtensionHolder(view: View, override val adapter: ExtensionAdapter) : setText(R.string.ext_install) } } - } 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 3ea8b2a933..2fb20c0b19 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 @@ -16,9 +16,11 @@ import eu.kanade.tachiyomi.source.CatalogueSource * @param source Instance of [CatalogueSource] containing source information. * @param header The header for this item. */ -data class ExtensionItem(val extension: Extension, - val header: ExtensionGroupItem? = null, - val installStep: InstallStep? = null) : +data class ExtensionItem( + val extension: Extension, + val header: ExtensionGroupItem? = null, + val installStep: InstallStep? = null +) : AbstractSectionableItem(header) { /** @@ -38,8 +40,12 @@ data class ExtensionItem(val extension: Extension, /** * Binds this item to the given view holder. */ - override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ExtensionHolder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: ExtensionHolder, + position: Int, + payloads: MutableList? + ) { if (payloads == null || payloads.isEmpty()) { holder.bind(this) @@ -57,5 +63,4 @@ data class ExtensionItem(val extension: Extension, override fun hashCode(): Int { return extension.pkgName.hashCode() } - } 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 3b16e4361b..f0416eb1d8 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 @@ -7,7 +7,7 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.ui.base.controller.DialogController class ExtensionTrustDialog(bundle: Bundle? = null) : DialogController(bundle) - where T: ExtensionTrustDialog.Listener { + where T : ExtensionTrustDialog.Listener { lateinit var listener: Listener constructor(target: T, signatureHash: String, pkgName: String) : this(Bundle().apply { @@ -24,7 +24,7 @@ class ExtensionTrustDialog(bundle: Bundle? = null) : DialogController(bundle) .positiveButton(R.string.ext_trust) { listener.trustSignature(args.getString(SIGNATURE_KEY)!!) } - .negativeButton(R.string.ext_uninstall) { + .negativeButton(R.string.ext_uninstall) { listener.uninstallExtension(args.getString(PKGNAME_KEY)!!) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/SettingsExtensionsController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/SettingsExtensionsController.kt index 61d0b71a9a..a9dfaeed02 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/extension/SettingsExtensionsController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/extension/SettingsExtensionsController.kt @@ -12,7 +12,7 @@ import eu.kanade.tachiyomi.util.system.LocaleHelper import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -class SettingsExtensionsController: SettingsController() { +class SettingsExtensionsController : SettingsController() { override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { titleRes = R.string.action_filter @@ -49,4 +49,4 @@ class SettingsExtensionsController: SettingsController() { } } } -} \ No newline at end of file +} 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 d2f56131fb..4b6bf66abb 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 @@ -19,8 +19,12 @@ class ChangeMangaCategoriesDialog(bundle: Bundle? = null) : private var preselected = emptyArray() - constructor(target: T, mangas: List, categories: List, - preselected: Array) : this() { + constructor( + target: T, + mangas: List, + categories: List, + preselected: Array + ) : this() { this.mangas = mangas this.categories = categories @@ -46,5 +50,4 @@ class ChangeMangaCategoriesDialog(bundle: Bundle? = null) : interface Listener { fun updateCategoriesForMangas(mangas: List, categories: List) } - -} \ No newline at end of file +} 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 abea5c9995..60ef7399c6 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 @@ -32,7 +32,6 @@ class DisplayBottomSheet(private val controller: LibraryController) : BottomShee private var sheetBehavior: BottomSheetBehavior<*> - init { // Use activity theme for this layout val view = activity.layoutInflater.inflate(R.layout.display_bottom_sheet, null) @@ -54,7 +53,6 @@ class DisplayBottomSheet(private val controller: LibraryController) : BottomShee } } }) - } override fun onStart() { @@ -82,7 +80,6 @@ class DisplayBottomSheet(private val controller: LibraryController) : BottomShee } } - private fun initGeneralPreferences() { display_group.bindToPreference(preferences.libraryLayout()) { controller.reattachAdapter() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt index 9eb0c9531b..27bb231829 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt @@ -99,5 +99,4 @@ class LibraryAdapter(private val controller: LibraryController) : RecyclerViewPa } } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryBadge.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryBadge.kt index 38c9df652e..1de46e3add 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryBadge.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryBadge.kt @@ -12,7 +12,7 @@ import eu.kanade.tachiyomi.util.system.getResourceColor import eu.kanade.tachiyomi.util.view.updatePaddingRelative import kotlinx.android.synthetic.main.unread_download_badge.view.* -class LibraryBadge @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null): +class LibraryBadge @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : MaterialCardView(context, attrs) { fun setUnreadDownload(unread: Int, downloads: Int, showTotalChapters: Boolean) { @@ -33,7 +33,7 @@ class LibraryBadge @JvmOverloads constructor(context: Context, attrs: AttributeS // Update the download count or local status and its visibility. with(download_text) { - visibility = if (downloads == -2 || downloads > 0) View.VISIBLE else View.GONE + visibility = if (downloads == -2 || downloads > 0) View.VISIBLE else View.GONE text = if (downloads == -2) resources.getString(R.string.local_source_badge) else downloads.toString() @@ -52,8 +52,7 @@ class LibraryBadge @JvmOverloads constructor(context: Context, attrs: AttributeS if (unread_angle.visibility == View.VISIBLE) { download_text.updatePaddingRelative(end = 8.dpToPx) unread_text.updatePaddingRelative(start = 2.dpToPx) - } - else { + } else { download_text.updatePaddingRelative(end = 5.dpToPx) unread_text.updatePaddingRelative(start = 5.dpToPx) } @@ -70,5 +69,4 @@ class LibraryBadge @JvmOverloads constructor(context: Context, attrs: AttributeS unread_text.visibility = if (inLibrary) View.VISIBLE else View.GONE unread_text.text = resources.getText(R.string.in_library) } - -} \ No newline at end of file +} 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 0e923b793b..cb39eca32d 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 @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.ui.library -import android.view.View import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.data.database.DatabaseHelper @@ -9,13 +8,13 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.util.lang.chop import eu.kanade.tachiyomi.util.lang.removeArticles -import uy.kohesive.injekt.Injekt -import uy.kohesive.injekt.api.get -import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale +import uy.kohesive.injekt.Injekt +import uy.kohesive.injekt.api.get +import uy.kohesive.injekt.injectLazy /** * Adapter storing a list of manga in a certain category. @@ -81,7 +80,7 @@ class LibraryCategoryAdapter(val libraryListener: LibraryListener) : */ fun allIndexOf(manga: Manga): List { return currentItems.mapIndexedNotNull { index, it -> - if (it is LibraryItem && it.manga.id == manga.id) index + if (it is LibraryItem && it.manga.id == manga.id) index else null } } @@ -89,14 +88,13 @@ class LibraryCategoryAdapter(val libraryListener: LibraryListener) : val s = getFilter(String::class.java) if (s.isNullOrBlank()) { updateDataSet(mangas) - } - else { + } else { updateDataSet(mangas.filter { it.filter(s) }) } isLongPressDragEnabled = libraryListener.canDrag() && s.isNullOrBlank() } - override fun onCreateBubbleText(position: Int):String { + override fun onCreateBubbleText(position: Int): String { return if (position < scrollableHeaders.size) { "Top" } else if (position >= itemCount - scrollableFooters.size) { @@ -106,7 +104,7 @@ class LibraryCategoryAdapter(val libraryListener: LibraryListener) : if (iFlexible is LibraryHeaderItem) { return iFlexible.category.name } - val preferences:PreferencesHelper by injectLazy() + val preferences: PreferencesHelper by injectLazy() when (preferences.librarySortingMode().getOrDefault()) { LibrarySort.DRAG_AND_DROP -> { if (!preferences.hideCategories().getOrDefault()) { @@ -114,16 +112,15 @@ class LibraryCategoryAdapter(val libraryListener: LibraryListener) : if (preferences.removeArticles().getOrDefault()) title.removeArticles().substring(0, 1).toUpperCase(Locale.US) else title.substring(0, 1).toUpperCase(Locale.US) - } - else { - val db:DatabaseHelper by injectLazy() + } else { + val db: DatabaseHelper by injectLazy() val category = db.getCategoriesForManga((iFlexible as LibraryItem).manga) .executeAsBlocking().firstOrNull()?.name category?.chop(10) ?: "Default" } } LibrarySort.LAST_READ -> { - val db:DatabaseHelper by injectLazy() + val db: DatabaseHelper by injectLazy() val id = (iFlexible as LibraryItem).manga.id ?: return "" val history = db.getHistoryByMangaId(id).executeAsBlocking() val last = history.maxBy { it.last_read } @@ -156,7 +153,7 @@ class LibraryCategoryAdapter(val libraryListener: LibraryListener) : } } - private fun getShortDate(date:Date):String { + private fun getShortDate(date: Date): String { val cal = Calendar.getInstance() cal.time = Date() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt index afd43acc0e..bb78f33178 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt @@ -364,7 +364,7 @@ class LibraryCategoryView @JvmOverloads constructor(context: Context, attrs: Att * * @param manga the manga to open. */ - private fun openManga(manga: Manga, startY:Float?) { + private fun openManga(manga: Manga, startY: Float?) { controller.openManga(manga, startY) } @@ -380,7 +380,6 @@ class LibraryCategoryView @JvmOverloads constructor(context: Context, attrs: Att controller.invalidateActionMode() } - /** * Tells the presenter to set the selection for the given position. * 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 c1aee94202..475b6cc8f2 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 @@ -63,15 +63,11 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get open class LibraryController( - bundle: Bundle? = null, - protected val preferences: PreferencesHelper = Injekt.get() -) : BaseController(bundle), TabbedController, - ActionMode.Callback, - ChangeMangaCategoriesDialog.Listener, - MigrationInterface, - DownloadServiceListener, - RootSearchInterface, - LibraryServiceListener { + bundle: Bundle? = null, + protected val preferences: PreferencesHelper = Injekt.get() +) : BaseController(bundle), TabbedController, ActionMode.Callback, + ChangeMangaCategoriesDialog.Listener, MigrationInterface, DownloadServiceListener, + RootSearchInterface, LibraryServiceListener { /** * Position of the active category. @@ -145,20 +141,20 @@ open class LibraryController( private var tabsVisibilitySubscription: Subscription? = null - private var observeLater:Boolean = false + private var observeLater: Boolean = false var snack: Snackbar? = null - lateinit var presenter:LibraryPresenter + lateinit var presenter: LibraryPresenter private set protected var justStarted = true - var libraryLayout:Int = preferences.libraryLayout().getOrDefault() + var libraryLayout: Int = preferences.libraryLayout().getOrDefault() private var usePager: Boolean = !preferences.libraryAsSingleList().getOrDefault() - open fun contentView():View = pager_layout + open fun contentView(): View = pager_layout init { setHasOptionsMenu(true) @@ -173,13 +169,11 @@ open class LibraryController( return inflater.inflate(R.layout.library_controller, container, false) } - override fun onViewCreated(view: View) { super.onViewCreated(view) view.applyWindowInsetsForRootController(activity!!.bottom_nav) mangaPerRow = getColumnsPreferenceForCurrentOrientation().getOrDefault() - if (!::presenter.isInitialized) - presenter = LibraryPresenter(this) + if (!::presenter.isInitialized) presenter = LibraryPresenter(this) layoutView(view) @@ -187,44 +181,34 @@ open class LibraryController( createActionModeIfNeeded() } - //bottom_sheet.onCreate(pager_layout) + // bottom_sheet.onCreate(pager_layout) bottom_sheet.onCreate(contentView()) bottom_sheet.onGroupClicked = { when (it) { FilterBottomSheet.ACTION_REFRESH -> onRefresh() FilterBottomSheet.ACTION_FILTER -> onFilterChanged() - FilterBottomSheet.ACTION_HIDE_FILTER_TIP -> activity?.toast(R.string - .hide_filters_tip, Toast.LENGTH_LONG) + FilterBottomSheet.ACTION_HIDE_FILTER_TIP -> activity?.toast( + R.string.hide_filters_tip, Toast.LENGTH_LONG + ) } } - /* fab.setOnClickListener { - router.pushController(DownloadController().withFadeTransaction()) - }*/ - - /* if (presenter.isDownloading()) { - fab.scaleY = 1f - fab.scaleX = 1f - fab.isClickable = true - fab.isFocusable = true - }*/ - val config = resources?.configuration - phoneLandscape = (config?.orientation == Configuration.ORIENTATION_LANDSCAPE && - (config.screenLayout.and(Configuration.SCREENLAYOUT_SIZE_MASK)) < - Configuration.SCREENLAYOUT_SIZE_LARGE) + phoneLandscape = + (config?.orientation == Configuration.ORIENTATION_LANDSCAPE && (config.screenLayout.and( + Configuration.SCREENLAYOUT_SIZE_MASK + )) < Configuration.SCREENLAYOUT_SIZE_LARGE) presenter.onRestore() val library = presenter.getAllManga() - if (library != null) presenter.updateViewBlocking() + if (library != null) presenter.updateViewBlocking() else { contentView().alpha = 0f presenter.getLibraryBlocking() } } - open fun layoutView(view: View) { pagerAdapter = LibraryAdapter(this) library_pager.adapter = pagerAdapter @@ -235,7 +219,9 @@ open class LibraryController( } override fun onPageScrolled( - position: Int, positionOffset: Float, positionOffsetPixels: Int + position: Int, + positionOffset: Float, + positionOffsetPixels: Int ) { } @@ -246,8 +232,8 @@ open class LibraryController( override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (type.isEnter) { - //if (library_pager != null) - //activity?.tabs?.setupWithViewPager(library_pager) + // if (library_pager != null) + // activity?.tabs?.setupWithViewPager(library_pager) presenter.getLibrary() DownloadService.addListener(this) DownloadService.callListeners() @@ -265,13 +251,11 @@ open class LibraryController( override fun onActivityPaused(activity: Activity) { super.onActivityPaused(activity) observeLater = true - if (::presenter.isInitialized) - presenter.onDestroy() + if (::presenter.isInitialized) presenter.onDestroy() } override fun onDestroy() { - if (::presenter.isInitialized) - presenter.onDestroy() + if (::presenter.isInitialized) presenter.onDestroy() super.onDestroy() } @@ -287,14 +271,14 @@ open class LibraryController( } override fun downloadStatusChanged(downloading: Boolean) { - /* launchUI { - val scale = if (downloading) 1f else 0f - val fab = fab ?: return@launchUI - fab.animate().scaleX(scale).scaleY(scale).setDuration(200).start() - fab.isClickable = downloading - fab.isFocusable = downloading - bottom_sheet?.adjustFiltersMargin(downloading) - }*/ + /* launchUI { + val scale = if (downloading) 1f else 0f + val fab = fab ?: return@launchUI + fab.animate().scaleX(scale).scaleY(scale).setDuration(200).start() + fab.isClickable = downloading + fab.isFocusable = downloading + bottom_sheet?.adjustFiltersMargin(downloading) + }*/ } override fun onUpdateManga(manga: LibraryManga) { @@ -310,19 +294,19 @@ open class LibraryController( } override fun configureTabs(tabs: TabLayout) { - /* with(tabs) { - tabGravity = TabLayout.GRAVITY_CENTER - tabMode = TabLayout.MODE_SCROLLABLE - } - tabsVisibilitySubscription?.unsubscribe() - tabsVisibilitySubscription = tabsVisibilityRelay.subscribe { visible -> - val tabAnimator = (activity as? MainActivity)?.tabAnimator ?: return@subscribe - if (visible) { - tabAnimator.expand() - } else if (!visible) { - tabAnimator.collapse() - } - }*/ + /* with(tabs) { + tabGravity = TabLayout.GRAVITY_CENTER + tabMode = TabLayout.MODE_SCROLLABLE + } + tabsVisibilitySubscription?.unsubscribe() + tabsVisibilitySubscription = tabsVisibilityRelay.subscribe { visible -> + val tabAnimator = (activity as? MainActivity)?.tabAnimator ?: return@subscribe + if (visible) { + tabAnimator.expand() + } else if (!visible) { + tabAnimator.collapse() + } + }*/ } override fun cleanupTabs(tabs: TabLayout) { @@ -330,10 +314,13 @@ open class LibraryController( tabsVisibilitySubscription = null } - open fun onNextLibraryUpdate(mangaMap: List, freshStart: Boolean = false) { } + open fun onNextLibraryUpdate(mangaMap: List, freshStart: Boolean = false) {} - fun onNextLibraryUpdate(categories: List, mangaMap: Map>, - freshStart: Boolean = false) { + fun onNextLibraryUpdate( + categories: List, + mangaMap: Map>, + freshStart: Boolean = false + ) { val view = view ?: return val adapter = pagerAdapter ?: return @@ -345,10 +332,8 @@ open class LibraryController( } // Get the current active category. - val activeCat = if (adapter.categories.isNotEmpty()) - library_pager.currentItem - else - activeCategory + val activeCat = if (adapter.categories.isNotEmpty()) library_pager.currentItem + else activeCategory categories.find { it.id == 0 }?.let { it.name = resources?.getString( @@ -362,20 +347,21 @@ open class LibraryController( // Restore active category. library_pager.setCurrentItem(activeCat, false) - //tabsVisibilityRelay.call(categories.size > 1) + // tabsVisibilityRelay.call(categories.size > 1) libraryMangaRelay.call(LibraryMangaEvent(mangaMap)) view.post { - //if (isAttached) { - // activity?.tabs?.setScrollPosition(library_pager.currentItem, 0f, true) - //} + // if (isAttached) { + // activity?.tabs?.setScrollPosition(library_pager.currentItem, 0f, true) + // } } if (!freshStart && justStarted) { if (!freshStart) { justStarted = false - if (pager_layout.alpha == 0f) pager_layout.animate().alpha(1f).setDuration(500).start() + if (pager_layout.alpha == 0f) pager_layout.animate().alpha(1f).setDuration(500) + .start() } } // Delay the scroll position to allow the view to be properly measured. @@ -389,10 +375,8 @@ open class LibraryController( * @return the preference. */ private fun getColumnsPreferenceForCurrentOrientation(): Preference { - return if (resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) - preferences.portraitColumns() - else - preferences.landscapeColumns() + return if (resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) preferences.portraitColumns() + else preferences.landscapeColumns() } /** @@ -419,9 +403,9 @@ open class LibraryController( } open fun onCatSortChanged(id: Int? = null) { - val catId = (id ?: pagerAdapter?.categories?.getOrNull(library_pager.currentItem)?.id) - ?: return - presenter.requestCatSortUpdate(catId) + val catId = + (id ?: pagerAdapter?.categories?.getOrNull(library_pager.currentItem)?.id) ?: return + presenter.requestCatSortUpdate(catId) } /** @@ -445,8 +429,9 @@ open class LibraryController( if (actionMode == null) { actionMode = (activity as AppCompatActivity).startSupportActionMode(this) val view = activity?.window?.currentFocus ?: return - val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? - InputMethodManager ?: return + val imm = + activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + ?: return imm.hideSoftInputFromWindow(view.windowToken, 0) } } @@ -493,8 +478,7 @@ open class LibraryController( override fun handleRootBack(): Boolean { val sheetBehavior = BottomSheetBehavior.from(bottom_sheet) - if (sheetBehavior.state != BottomSheetBehavior.STATE_COLLAPSED && - sheetBehavior.state != BottomSheetBehavior.STATE_HIDDEN) { + if (sheetBehavior.state != BottomSheetBehavior.STATE_COLLAPSED && sheetBehavior.state != BottomSheetBehavior.STATE_HIDDEN) { sheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED return true } @@ -528,16 +512,13 @@ open class LibraryController( } fun toggleFilters() { - if (bottom_sheet.sheetBehavior?.isHideable == true && - bottom_sheet.sheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) - bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN - else if (bottom_sheet.sheetBehavior?.state != BottomSheetBehavior.STATE_COLLAPSED - && bottom_sheet.sheetBehavior?.skipCollapsed == false) - bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED + if (bottom_sheet.sheetBehavior?.isHideable == true && bottom_sheet.sheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) bottom_sheet.sheetBehavior?.state = + BottomSheetBehavior.STATE_HIDDEN + else if (bottom_sheet.sheetBehavior?.state != BottomSheetBehavior.STATE_COLLAPSED && bottom_sheet.sheetBehavior?.skipCollapsed == false) bottom_sheet.sheetBehavior?.state = + BottomSheetBehavior.STATE_COLLAPSED else bottom_sheet.sheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED } - /** * Invalidates the action mode, forcing it to refresh its content. */ @@ -564,8 +545,7 @@ open class LibraryController( val sameCat = /*(adapter?.categories?.getOrNull(library_pager.currentItem)?.id == catId) &&*/ selectedMangas.all { (it as? LibraryManga)?.category == catId } menu.findItem(R.id.action_move_manga).isVisible = sameCat - } - else menu.findItem(R.id.action_move_manga).isVisible = false + } else menu.findItem(R.id.action_move_manga).isVisible = false } return false } @@ -574,13 +554,10 @@ open class LibraryController( when (item.itemId) { R.id.action_move_to_category -> showChangeMangaCategoriesDialog() R.id.action_delete -> { - MaterialDialog(activity!!) - .message(R.string.confirm_manga_deletion) + MaterialDialog(activity!!).message(R.string.confirm_manga_deletion) .positiveButton(R.string.action_remove) { deleteMangasFromLibrary() - } - .negativeButton(android.R.string.no) - .show() + }.negativeButton(android.R.string.no).show() } R.id.action_select_all -> { pagerAdapter?.categories?.getOrNull(library_pager.currentItem)?.id?.let { @@ -592,14 +569,12 @@ open class LibraryController( router.pushController( if (skipPre) { MigrationListController.create( - MigrationProcedureConfig( - selectedMangas.mapNotNull { it.id },null) + MigrationProcedureConfig(selectedMangas.mapNotNull { it.id }, null) ) - } - else { - PreMigrationController.create( selectedMangas.mapNotNull { it.id } ) - } - .withFadeTransaction().tag(if (skipPre) MigrationListController.TAG else null)) + } else { + PreMigrationController.create(selectedMangas.mapNotNull { it.id }) + }.withFadeTransaction().tag(if (skipPre) MigrationListController.TAG else null) + ) destroyActionModeIfNeeded() } /*R.id.action_to_top, R.id.action_to_bottom -> { @@ -631,7 +606,7 @@ open class LibraryController( fun openManga(manga: Manga, startY: Float?) { router.pushController(MangaDetailsController(manga).withFadeTransaction()) - // router.pushController(MangaController(manga, startY).withFadeTransaction()) + // router.pushController(MangaController(manga, startY).withFadeTransaction()) } /** @@ -663,12 +638,12 @@ open class LibraryController( val categories = presenter.allCategories.filter { it.id != 0 } // Get indexes of the common categories to preselect. - val commonCategoriesIndexes = presenter.getCommonCategories(mangas) - .map { categories.indexOf(it) } - .toTypedArray() + val commonCategoriesIndexes = + presenter.getCommonCategories(mangas).map { categories.indexOf(it) }.toTypedArray() - ChangeMangaCategoriesDialog(this, mangas, categories, commonCategoriesIndexes) - .showDialog(router) + ChangeMangaCategoriesDialog(this, mangas, categories, commonCategoriesIndexes).showDialog( + router + ) } private fun deleteMangasFromLibrary() { @@ -676,8 +651,9 @@ open class LibraryController( presenter.removeMangaFromLibrary(mangas) destroyActionModeIfNeeded() snack?.dismiss() - snack = snackbar_layout?.snack(activity?.getString(R.string.manga_removed_library) ?: "", Snackbar - .LENGTH_INDEFINITE) { + snack = snackbar_layout?.snack( + activity?.getString(R.string.manga_removed_library) ?: "", Snackbar.LENGTH_INDEFINITE + ) { var undoing = false setAction(R.string.action_undo) { presenter.addMangas(mangas) @@ -686,8 +662,7 @@ open class LibraryController( addCallback(object : BaseTransientBottomBar.BaseCallback() { override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { super.onDismissed(transientBottomBar, event) - if (!undoing) - presenter.confirmDeletion(mangas) + if (!undoing) presenter.confirmDeletion(mangas) } }) } @@ -699,7 +674,7 @@ open class LibraryController( destroyActionModeIfNeeded() } - /// Method for the category view + // / Method for the category view fun startReading(manga: Manga) { val activity = activity ?: return val chapter = presenter.getFirstUnread(manga) ?: return @@ -707,4 +682,4 @@ open class LibraryController( destroyActionModeIfNeeded() startActivity(intent) } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt index 093753eb1e..513e24dd08 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt @@ -24,7 +24,7 @@ import kotlinx.android.synthetic.main.unread_download_badge.* class LibraryGridHolder( private val view: View, adapter: LibraryCategoryAdapter, - var width:Int, + var width: Int, compact: Boolean, private var fixedSize: Boolean ) : LibraryHolder(view, adapter) { @@ -33,8 +33,7 @@ class LibraryGridHolder( play_layout.setOnClickListener { playButtonClicked() } if (compact) { text_layout.gone() - } - else { + } else { compact_title.gone() gradient.gone() val playLayout = play_layout.layoutParams as FrameLayout.LayoutParams @@ -73,8 +72,7 @@ class LibraryGridHolder( if (oldPos == adapterPosition) setCover(item.manga, id) } - } - else setCover(item.manga, id) + } else setCover(item.manga, id) } } @@ -106,5 +104,4 @@ class LibraryGridHolder( card.isDragged = false badge_view.isDragged = false } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderItem.kt index 217bef7d78..2802da15f5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHeaderItem.kt @@ -48,7 +48,7 @@ class LibraryHeaderItem(private val categoryF: (Int) -> Category, val catId: Int holder.bind(categoryF(catId)) } - val category:Category + val category: Category get() = categoryF(catId) override fun equals(other: Any?): Boolean { @@ -81,7 +81,7 @@ class LibraryHeaderItem(private val categoryF: (Int) -> Category, val catId: Int init { updateButton.setOnClickListener { addCategoryToUpdate() } - sortText.setOnClickListener { it.post { showCatSortOptions() } } + sortText.setOnClickListener { it.post { showCatSortOptions() } } checkboxImage.setOnClickListener { selectAll() } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { sortText.compoundDrawablesRelative[2]?.mutate()?.setTint( @@ -207,11 +207,10 @@ class LibraryHeaderItem(private val categoryF: (Int) -> Category, val catId: Int val t = (category.mangaSort?.minus('a') ?: 0) + 1 if (t % 2 != 0) t + 1 else t - 1 - } - else { + } else { val order = when (menuId) { R.id.action_drag_and_drop -> { - adapter.libraryListener.sortCategory(category.id!!, 'D' - 'a' + 1) + adapter.libraryListener.sortCategory(category.id!!, 'D' - 'a' + 1) return } R.id.action_total_chaps -> 4 @@ -251,4 +250,4 @@ class LibraryHeaderItem(private val categoryF: (Int) -> Category, val catId: Int return false } } -} \ No newline at end of file +} 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 5a7737e6fb..22011109a5 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 @@ -12,7 +12,7 @@ import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder */ abstract class LibraryHolder( - view: View, + view: View, val adapter: LibraryCategoryAdapter ) : BaseFlexibleViewHolder(view, adapter) { @@ -24,7 +24,6 @@ abstract class LibraryHolder( */ abstract fun onSetValues(item: LibraryItem) - fun setUnreadBadge(badge: LibraryBadge, item: LibraryItem) { badge.setUnreadDownload( when { @@ -36,7 +35,7 @@ abstract class LibraryHolder( when { item.downloadCount == -1 -> -1 item.manga.source == LocalSource.ID -> -2 - else -> item.downloadCount + else -> item.downloadCount }, item.chapterCount > -1) } 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 2e1209490b..0f8e12d276 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 @@ -24,10 +24,12 @@ import eu.kanade.tachiyomi.widget.AutofitRecyclerView import kotlinx.android.synthetic.main.catalogue_grid_item.view.* import uy.kohesive.injekt.injectLazy -class LibraryItem(val manga: LibraryManga, +class LibraryItem( + val manga: LibraryManga, private val libraryLayout: Preference, private val fixedSize: Preference, - header: LibraryHeaderItem?) : + header: LibraryHeaderItem? +) : AbstractSectionableItem(header), IFilterable { var downloadCount = -1 @@ -48,8 +50,7 @@ class LibraryItem(val manga: LibraryManga, val isFixedSize = fixedSize.getOrDefault() if (libraryLayout == 0) { LibraryListHolder(view, adapter as LibraryCategoryAdapter) - } - else { + } else { view.apply { val coverHeight = (parent.itemWidth / 3f * 4f).toInt() if (libraryLayout == 1) { @@ -60,8 +61,7 @@ class LibraryItem(val manga: LibraryManga, card.updateLayoutParams { bottomMargin = 6.dpToPx } - } - else if (libraryLayout == 2) { + } else if (libraryLayout == 2) { constraint_layout.background = ContextCompat.getDrawable( context, R.drawable.library_item_selector ) @@ -98,10 +98,12 @@ class LibraryItem(val manga: LibraryManga, } } - override fun bindViewHolder(adapter: FlexibleAdapter>, - holder: LibraryHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: LibraryHolder, + position: Int, + payloads: MutableList? + ) { holder.onSetValues(this) } @@ -130,8 +132,7 @@ class LibraryItem(val manga: LibraryManga, if (constraint.contains(",")) { val genres = manga.currentGenres()?.split(", ") constraint.split(",").all { containsGenre(it.trim(), genres) } - } - else containsGenre(constraint, manga.currentGenres()?.split(", ")) + } else containsGenre(constraint, manga.currentGenres()?.split(", ")) } @SuppressLint("DefaultLocale") @@ -140,7 +141,7 @@ class LibraryItem(val manga: LibraryManga, return if (tag.startsWith("-")) genres?.find { it.trim().toLowerCase() == tag.substringAfter("-").toLowerCase() - } == null + } == null else genres?.find { it.trim().toLowerCase() == tag.toLowerCase() } != null @@ -154,6 +155,6 @@ class LibraryItem(val manga: LibraryManga, } override fun hashCode(): Int { - return (manga.id!! + (manga.category shl 50).toLong()).hashCode() //!!.hashCode() + return (manga.id!! + (manga.category shl 50).toLong()).hashCode() // !!.hashCode() } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListController.kt index deee3a6e4c..12603eb000 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListController.kt @@ -40,11 +40,6 @@ import eu.kanade.tachiyomi.util.view.scrollViewWith import eu.kanade.tachiyomi.util.view.snack import eu.kanade.tachiyomi.util.view.updateLayoutParams import eu.kanade.tachiyomi.util.view.updatePaddingRelative -import kotlinx.android.synthetic.main.filter_bottom_sheet.* -import kotlinx.android.synthetic.main.library_grid_recycler.* -import kotlinx.android.synthetic.main.library_list_controller.* -import kotlinx.android.synthetic.main.main_activity.* -import kotlinx.coroutines.delay import java.util.Locale import kotlin.math.abs import kotlin.math.max @@ -52,15 +47,16 @@ import kotlin.math.min import kotlin.math.pow import kotlin.math.roundToInt import kotlin.math.sign +import kotlinx.android.synthetic.main.filter_bottom_sheet.* +import kotlinx.android.synthetic.main.library_grid_recycler.* +import kotlinx.android.synthetic.main.library_list_controller.* +import kotlinx.android.synthetic.main.main_activity.* +import kotlinx.coroutines.delay class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), - FlexibleAdapter.OnItemClickListener, - FlexibleAdapter.OnItemLongClickListener, - FlexibleAdapter.OnItemMoveListener, - LibraryCategoryAdapter.LibraryListener, - SpinnerTitleInterface, - OnTouchEventInterface, - SwipeGestureInterface { + FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, + FlexibleAdapter.OnItemMoveListener, LibraryCategoryAdapter.LibraryListener, + SpinnerTitleInterface, OnTouchEventInterface, SwipeGestureInterface { private lateinit var adapter: LibraryCategoryAdapter @@ -68,32 +64,33 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), private var updateScroll = true - private var lastItemPosition:Int? = null - private var lastItem:IFlexible<*>? = null + private var lastItemPosition: Int? = null + private var lastItem: IFlexible<*>? = null private var switchingCategories = false - private var startPosX:Float? = null - private var startPosY:Float? = null + private var startPosX: Float? = null + private var startPosY: Float? = null private var moved = false private var lockedRecycler = false private var lockedY = false - private var nextCategory:Int? = null - private var ogCategory:Int? = null - private var prevCategory:Int? = null + private var nextCategory: Int? = null + private var ogCategory: Int? = null + private var prevCategory: Int? = null private val swipeDistance = 300f private var flinging = false private var isDragging = false - override fun contentView():View = recycler_layout + override fun contentView(): View = recycler_layout override fun getTitle(): String? { return if (view != null && presenter.categories.size > 1) presenter.categories.find { - it.order == activeCategory }?.name ?: super.getTitle() + it.order == activeCategory + }?.name ?: super.getTitle() else super.getTitle() } - private var scrollListener = object : RecyclerView.OnScrollListener () { + private var scrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val order = getCategoryOrder() @@ -109,7 +106,8 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), super.onViewCreated(view) // pad the recycler if the filter bottom sheet is visible if (!phoneLandscape) { - val height = view.context.resources.getDimensionPixelSize(R.dimen.rounder_radius) + 4.dpToPx + val height = + view.context.resources.getDimensionPixelSize(R.dimen.rounder_radius) + 4.dpToPx recycler.updatePaddingRelative(bottom = height) } } @@ -133,7 +131,6 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), view?.getGlobalVisibleRect(recyclerRect) activity?.appbar?.getGlobalVisibleRect(appBarRect) - if (startPosX == null) { startPosX = event.rawX startPosY = event.rawY @@ -166,10 +163,14 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } return } - if (startPosX != null && startPosY != null && - (sheetRect.contains(startPosX!!.toInt(), startPosY!!.toInt()) || - !recyclerRect.contains(startPosX!!.toInt(), startPosY!!.toInt()) - || appBarRect.contains(startPosX!!.toInt(), startPosY!!.toInt()))) { + if (startPosX != null && startPosY != null && (sheetRect.contains( + startPosX!!.toInt(), + startPosY!!.toInt() + ) || !recyclerRect.contains( + startPosX!!.toInt(), + startPosY!!.toInt() + ) || appBarRect.contains(startPosX!!.toInt(), startPosY!!.toInt())) + ) { return } if (event.actionMasked != MotionEvent.ACTION_UP && startPosX != null) { @@ -178,25 +179,21 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), if (lockedY) return - if (distance > 60 && abs(event.rawY - startPosY!!) <= 30 && - !lockedRecycler) { + if (distance > 60 && abs(event.rawY - startPosY!!) <= 30 && !lockedRecycler) { lockedRecycler = true switchingCategories = true recycler.suppressLayout(true) - } - else if (!lockedRecycler && abs(event.rawY - startPosY!!) > 30) { + } else if (!lockedRecycler && abs(event.rawY - startPosY!!) > 30) { lockedY = true resetRecyclerY() return } - if (abs(event.rawY - startPosY!!) <= 30 || recycler.isLayoutSuppressed - || lockedRecycler) { + if (abs(event.rawY - startPosY!!) <= 30 || recycler.isLayoutSuppressed || lockedRecycler) { if ((prevCategory == null && sign > 0) || (nextCategory == null && sign < 0)) { recycler_layout.x = sign * distance.pow(0.6f) recycler_layout.alpha = 1f - } - else if (distance <= swipeDistance * 1.1f) { + } else if (distance <= swipeDistance * 1.1f) { recycler_layout.x = (max(0f, distance - 50f) * sign) / 3 recycler_layout.alpha = (1f - (distance - (swipeDistance * 0.1f)) / swipeDistance) @@ -258,14 +255,14 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), val set = AnimatorSet() val translationXAnimator = ValueAnimator.ofFloat(recycler_layout.x, 0f) translationXAnimator.duration = time - translationXAnimator.addUpdateListener { - animation -> recycler_layout.x = animation.animatedValue as Float + translationXAnimator.addUpdateListener { animation -> + recycler_layout.x = animation.animatedValue as Float } val translationAlphaAnimator = ValueAnimator.ofFloat(recycler_layout.alpha, 1f) translationAlphaAnimator.duration = time - translationAlphaAnimator.addUpdateListener { - animation -> recycler_layout.alpha = animation.animatedValue as Float + translationAlphaAnimator.addUpdateListener { animation -> + recycler_layout.alpha = animation.animatedValue as Float } set.playTogether(translationXAnimator, translationAlphaAnimator) set.start() @@ -274,8 +271,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), delay(time) if (!lockedRecycler) switchingCategories = false } - } - else { + } else { recycler_layout.x = 0f recycler_layout.alpha = 1f switchingCategories = false @@ -287,7 +283,6 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), return inflater.inflate(R.layout.library_list_controller, container, false) } - override fun layoutView(view: View) { adapter = LibraryCategoryAdapter(this) setRecyclerLayout() @@ -317,8 +312,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), if (libraryLayout == 0) { recycler.spanCount = 1 recycler.updatePaddingRelative(start = 0, end = 0) - } - else { + } else { recycler.columnWidth = (90 + (preferences.gridSize().getOrDefault() * 30)).dpToPx recycler.updatePaddingRelative(start = 5.dpToPx, end = 5.dpToPx) } @@ -356,34 +350,29 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } adapter.setItems(mangaMap) - val categoryNames = presenter.categories.map { it.name }.toTypedArray() + val categoryNames = presenter.categories.map { it.name }.toTypedArray() - val isCurrentController = router?.backstack?.lastOrNull()?.controller() == - this + val isCurrentController = router?.backstack?.lastOrNull()?.controller() == this setTitle() updateScroll = false if (!freshStart) { justStarted = false - if (contentView().alpha == 0f) - contentView().animate().alpha(1f).setDuration(500).start() - - + if (contentView().alpha == 0f) contentView().animate().alpha(1f).setDuration(500) + .start() } else if (justStarted) { if (freshStart) scrollToHeader(activeCategory) - } - else { + } else { updateScroll = true } adapter.isLongPressDragEnabled = canDrag() - val popupMenu = if (presenter.categories.size > 1 && isCurrentController) { + val popupMenu = if (presenter.categories.size > 1 && isCurrentController) { activity?.toolbar?.showSpinner() + } else { + activity?.toolbar?.removeSpinner() + null } - else { - activity?.toolbar?.removeSpinner() - null - } presenter.categories.forEach { category -> popupMenu?.menu?.add(0, category.order, max(0, category.order), category.name) @@ -401,18 +390,15 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), if (headerPosition > -1) { val appbar = activity?.appbar recycler.suppressLayout(true) - val appbarOffset = - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (appbar?.y ?: 0f > -20) 0 else - (appbar?.y?.plus(view?.rootWindowInsets?.systemWindowInsetTop ?: 0) - ?: 0f).roundToInt() + 30.dpToPx - } - else { - 0 - } + val appbarOffset = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (appbar?.y ?: 0f > -20) 0 else (appbar?.y?.plus( + view?.rootWindowInsets?.systemWindowInsetTop ?: 0 + ) ?: 0f).roundToInt() + 30.dpToPx + } else { + 0 + } (recycler.layoutManager as LinearLayoutManager).scrollToPositionWithOffset( - headerPosition, (if (headerPosition == 0) 0 else (-28).dpToPx) - + appbarOffset + headerPosition, (if (headerPosition == 0) 0 else (-28).dpToPx) + appbarOffset ) /*val headerItem = adapter.getItem(headerPosition) as? LibraryHeaderItem @@ -492,8 +478,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), headerPositions.forEach { if (changedMode) { adapter.notifyItemChanged(it) - } - else { + } else { (recycler.findViewHolderForAdapterPosition(it) as? LibraryHeaderItem.Holder)?.setSelection() } } @@ -517,8 +502,8 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } override fun canDrag(): Boolean { - val filterOff = !bottom_sheet.hasActiveFilters() && - !preferences.hideCategories().getOrDefault() + val filterOff = + !bottom_sheet.hasActiveFilters() && !preferences.hideCategories().getOrDefault() return filterOff && adapter.mode != SelectableAdapter.Mode.MULTI } @@ -552,10 +537,12 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), createActionModeIfNeeded() when { lastClickPosition == -1 -> setSelection(position) - lastClickPosition > position -> for (i in position until lastClickPosition) - setSelection(i) - lastClickPosition < position -> for (i in lastClickPosition + 1..position) - setSelection(i) + lastClickPosition > position -> for (i in position until lastClickPosition) setSelection( + i + ) + lastClickPosition < position -> for (i in lastClickPosition + 1..position) setSelection( + i + ) else -> setSelection(position) } lastClickPosition = position @@ -566,14 +553,15 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), if (actionState == 2) { isDragging = true activity?.appbar?.y = 0f - 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) (recycler.findViewHolderForAdapterPosition(position) as? LibraryHolder)?.toggleActivation() adapter.moveItem(position, lastItemPosition!!) - } - else { + } else { lastItem = adapter.getItem(position) lastItemPosition = position onItemLongClick(position) @@ -592,28 +580,27 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), setSelection(item.manga, selected) invalidateActionMode() } + 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) - recycler.scrollBy(0, recycler.paddingTop) + if ((adapter.getItem(fromPosition) is LibraryItem && adapter.getItem(fromPosition) is LibraryItem) || adapter.getItem( + fromPosition + ) == null + ) recycler.scrollBy(0, recycler.paddingTop) activity?.appbar?.y = 0f - if (lastItemPosition == toPosition) - lastItemPosition = null - else if (lastItemPosition == null) - lastItemPosition = fromPosition + if (lastItemPosition == toPosition) lastItemPosition = null + else if (lastItemPosition == null) lastItemPosition = fromPosition } override fun shouldMoveItem(fromPosition: Int, toPosition: Int): Boolean { - if (adapter.isSelected(fromPosition)) - toggleSelection(fromPosition) + if (adapter.isSelected(fromPosition)) toggleSelection(fromPosition) 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) { @@ -624,8 +611,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } destroyActionModeIfNeeded() // if nothing moved - if (lastItemPosition == null) - return + if (lastItemPosition == null) return val item = adapter.getItem(position) as? LibraryItem ?: return val newHeader = adapter.getSectionHeader(position) as? LibraryHeaderItem val libraryItems = adapter.getSectionItems(adapter.getSectionHeader(position)) @@ -652,9 +638,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), item, newHeader.category.id, mangaIds, true ) if (it.isCheckPromptChecked()) preferences.keepCatSort().set(2) - } - .checkBoxPrompt(R.string.remember_choice) {} - .negativeButton( + }.checkBoxPrompt(R.string.remember_choice) {}.negativeButton( text = resources?.getString( R.string.keep_current_sort, resources!!.getString(newHeader.category.sortRes()).toLowerCase( @@ -667,8 +651,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), ) if (it.isCheckPromptChecked()) preferences.keepCatSort().set(1) }.cancelOnTouchOutside(false).show() - } - else { + } else { presenter.moveMangaToCategory( item, newHeader.category.id, mangaIds, keepCatSort == 2 ) @@ -679,21 +662,21 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } override fun updateCategory(catId: Int): Boolean { - val category = (adapter.getItem(catId) as? LibraryHeaderItem)?.category ?: - return false + val category = (adapter.getItem(catId) as? LibraryHeaderItem)?.category ?: return false val inQueue = LibraryUpdateService.categoryInQueue(category.id) snack?.dismiss() - snack = view?.snack(resources!!.getString( - when { - inQueue -> R.string.category_already_in_queue - LibraryUpdateService.isRunning() -> - R.string.adding_category_to_queue - else -> R.string.updating_category_x - }, category.name)) { + snack = view?.snack( + resources!!.getString( + when { + inQueue -> R.string.category_already_in_queue + LibraryUpdateService.isRunning() -> R.string.adding_category_to_queue + else -> R.string.updating_category_x + }, category.name + ) + ) { anchorView = bottom_sheet } - if (!inQueue) - LibraryUpdateService.start(view!!.context, category) + if (!inQueue) LibraryUpdateService.start(view!!.context, category) return true } @@ -705,8 +688,7 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), val header = adapter.getSectionHeader(position) ?: return val items = adapter.getSectionItemPositions(header) val allSelected = allSelected(position) - for (i in items) - setSelection(i, !allSelected) + for (i in items) setSelection(i, !allSelected) } override fun allSelected(position: Int): Boolean { @@ -715,23 +697,22 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), return items.all { adapter.isSelected(it) } } - override fun onSwipeBottom(x: Float, y: Float) { } + override fun onSwipeBottom(x: Float, y: Float) {} override fun onSwipeTop(x: Float, y: Float) { val sheetRect = Rect() activity!!.bottom_nav.getGlobalVisibleRect(sheetRect) if (sheetRect.contains(x.toInt(), y.toInt())) { - if (bottom_sheet.sheetBehavior?.state != BottomSheetBehavior.STATE_EXPANDED) - toggleFilters() + if (bottom_sheet.sheetBehavior?.state != BottomSheetBehavior.STATE_EXPANDED) toggleFilters() } } + override fun onSwipeLeft(x: Float, y: Float) = goToNextCategory(x) override fun onSwipeRight(x: Float, y: Float) = goToNextCategory(x) private fun goToNextCategory(x: Float) { - if (lockedRecycler && abs(x) > 1000f) { + if (lockedRecycler && abs(x) > 1000f) { val sign = sign(x).roundToInt() - if ((sign < 0 && nextCategory == null) || (sign > 0) && prevCategory == null) - return + if ((sign < 0 && nextCategory == null) || (sign > 0) && prevCategory == null) return val distance = recycler_layout.alpha val speed = max(3000f / abs(x), 0.75f) if (sign(recycler_layout.x) == sign(x)) { @@ -770,4 +751,4 @@ class LibraryListController(bundle: Bundle? = null) : LibraryController(bundle), } override fun recyclerIsScrolling() = switchingCategories || lockedRecycler || lockedY -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListHolder.kt index 2f494d6bf9..7536b0bac2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryListHolder.kt @@ -22,8 +22,8 @@ import kotlinx.android.synthetic.main.unread_download_badge.* */ class LibraryListHolder( - private val view: View, - adapter: LibraryCategoryAdapter + private val view: View, + adapter: LibraryCategoryAdapter ) : LibraryHolder(view, adapter) { /** @@ -74,5 +74,4 @@ class LibraryListHolder( super.onItemReleased(position) view.card.isDragged = false } - } 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 212d248e18..150404dcfa 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 @@ -27,6 +27,9 @@ import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.TriStateGroup.Comp import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.TriStateGroup.Companion.STATE_IGNORE import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.TriStateGroup.Companion.STATE_INCLUDE import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.TriStateGroup.Companion.STATE_REALLY_EXCLUDE +import java.util.ArrayList +import java.util.Collections +import java.util.Comparator import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope @@ -37,9 +40,6 @@ import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.ArrayList -import java.util.Collections -import java.util.Comparator /** * Class containing library information. @@ -55,12 +55,12 @@ private typealias LibraryMap = Map> * Presenter of [LibraryController]. */ class LibraryPresenter( - private val view: LibraryController, - private val db: DatabaseHelper = Injekt.get(), - private val preferences: PreferencesHelper = Injekt.get(), - private val coverCache: CoverCache = Injekt.get(), - private val sourceManager: SourceManager = Injekt.get(), - private val downloadManager: DownloadManager = Injekt.get() + private val view: LibraryController, + private val db: DatabaseHelper = Injekt.get(), + private val preferences: PreferencesHelper = Injekt.get(), + private val coverCache: CoverCache = Injekt.get(), + private val sourceManager: SourceManager = Injekt.get(), + private val downloadManager: DownloadManager = Injekt.get() ) { private val context = preferences.context @@ -77,11 +77,11 @@ class LibraryPresenter( /** * List of all manga to update the */ - private var rawMangaMap:LibraryMap? = null + private var rawMangaMap: LibraryMap? = null - private var currentMangaMap:LibraryMap? = null + private var currentMangaMap: LibraryMap? = null - private var totalChapters:Map? = null + private var totalChapters: Map? = null fun isDownloading() = downloadManager.hasQueue() @@ -99,8 +99,8 @@ class LibraryPresenter( fun getLibrary() { launchUI { totalChapters = null - val freshStart = !preferences.libraryAsSingleList().getOrDefault() - && (currentMangaMap?.values?.firstOrNull()?.firstOrNull()?.header != null) + val freshStart = !preferences.libraryAsSingleList().getOrDefault() && + (currentMangaMap?.values?.firstOrNull()?.firstOrNull()?.header != null) val mangaMap = withContext(Dispatchers.IO) { val library = getLibraryFromDB() library.apply { setDownloadCount(library.mangaMap) } @@ -161,7 +161,7 @@ class LibraryPresenter( val filterTrackers = FilterBottomSheet.FILTER_TRACKER - val filterFn: (LibraryItem) -> Boolean = f@ { item -> + val filterFn: (LibraryItem) -> Boolean = f@{ item -> // Filter when there isn't unread chapters. if (filterUnread == STATE_INCLUDE && (item.manga.unread == 0 || db.getChapters(item.manga).executeAsBlocking() @@ -277,7 +277,7 @@ class LibraryPresenter( } val comparator = Comparator(sortFn) - return map.mapValues { entry -> entry.value.sortedWith(comparator) } + return map.mapValues { entry -> entry.value.sortedWith(comparator) } } /** @@ -332,8 +332,7 @@ class LibraryPresenter( if (compare == 0) { if (ascending) sortAlphabetical(i1, i2) else sortAlphabetical(i2, i1) - } - else compare + } else compare } val comparator = if (ascending) @@ -347,7 +346,7 @@ class LibraryPresenter( private fun setTotalChapters() { if (totalChapters != null) return val mangaMap = rawMangaMap ?: return - totalChapters = mangaMap.flatMap{ + totalChapters = mangaMap.flatMap { it.value }.associate { it.manga.id!! to db.getChapters(it.manga).executeAsBlocking().size @@ -364,8 +363,11 @@ class LibraryPresenter( return category } - private fun sortCategory(i1: LibraryItem, i2: LibraryItem, - lastReadManga: Map, initCat: Category? = null + private fun sortCategory( + i1: LibraryItem, + i2: LibraryItem, + lastReadManga: Map, + initCat: Category? = null ): Int { return if (initCat != null || i1.manga.category == i2.manga.category) { val category = initCat ?: allCategories.find { it.id == i1.manga.category } ?: return 0 @@ -426,7 +428,6 @@ class LibraryPresenter( } } - private fun sortAlphabetical(i1: LibraryItem, i2: LibraryItem): Int { return if (preferences.removeArticles().getOrDefault()) i1.manga.currentTitle().removeArticles().compareTo(i2.manga.currentTitle().removeArticles(), true) @@ -458,16 +459,15 @@ class LibraryPresenter( val libraryMap = if (!preferences.libraryAsSingleList().getOrDefault()) { libraryManga.map { manga -> - LibraryItem(manga, libraryLayout, preferences.uniformGrid(),null).apply { unreadType = + LibraryItem(manga, libraryLayout, preferences.uniformGrid(), null).apply { unreadType = unreadBadgeType } }.groupBy { if (showCategories) it.manga.category else -1 } - } - else { + } else { libraryManga.groupBy { manga -> if (showCategories) manga.category else -1 - //LibraryItem(manga, libraryLayout).apply { unreadType = unreadBadgeType } + // LibraryItem(manga, libraryLayout).apply { unreadType = unreadBadgeType } }.map { entry -> val categoryItem = if (!showCategories) catItemAll else @@ -480,7 +480,7 @@ class LibraryPresenter( }.map { val cat = if (showCategories) it.firstOrNull()?.manga?.category ?: 0 else -1 cat to it - //LibraryItem(manga, libraryLayout).apply { unreadType = unreadBadgeType } + // LibraryItem(manga, libraryLayout).apply { unreadType = unreadBadgeType } }.toMap() } if (libraryMap.containsKey(0)) @@ -518,12 +518,15 @@ class LibraryPresenter( } } - suspend fun updateView(categories: List, mangaMap: LibraryMap, freshStart:Boolean - = false) { + suspend fun updateView( + categories: List, + mangaMap: LibraryMap, + freshStart: Boolean = + false + ) { if (view !is LibraryListController) { view.onNextLibraryUpdate(categories, mangaMap, freshStart) - } - else { + } else { val mangaList = withContext(Dispatchers.IO) { val list = mutableListOf() for (element in mangaMap.toSortedMap(compareBy { entry -> @@ -553,8 +556,7 @@ class LibraryPresenter( if (mangaMap.values.firstOrNull()?.firstOrNull()?.header != null) return view.onNextLibraryUpdate(categories, mangaMap, true) - } - else { + } else { val list = mutableListOf() for (element in mangaMap.toSortedMap(compareBy { entry -> categories.find { it.id == entry }?.order ?: -1 @@ -563,7 +565,6 @@ class LibraryPresenter( } view.onNextLibraryUpdate(list, true) } - } /** @@ -585,7 +586,7 @@ class LibraryPresenter( * Requests the library to have unread badges changed. */ fun requestUnreadBadgesUpdate() { - //getLibrary() + // getLibrary() launchUI { val mangaMap = rawMangaMap ?: return@launchUI withContext(Dispatchers.IO) { setUnreadBadge(mangaMap) } @@ -715,7 +716,7 @@ class LibraryPresenter( fun migrateManga(prevManga: Manga, manga: Manga, replace: Boolean) { val source = sourceManager.get(manga.source) ?: return - //state = state.copy(isReplacingManga = true) + // state = state.copy(isReplacingManga = true) Observable.defer { source.fetchChapterList(manga) } .onErrorReturn { emptyList() } @@ -723,7 +724,7 @@ class LibraryPresenter( .onErrorReturn { emptyList() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) - //.doOnUnsubscribe { state = state.copy(isReplacingManga = false) } + // .doOnUnsubscribe { state = state.copy(isReplacingManga = false) } .subscribe() } @@ -736,8 +737,13 @@ class LibraryPresenter( } } - private fun migrateMangaInternal(source: Source, sourceChapters: List, - prevManga: Manga, manga: Manga, replace: Boolean) { + private fun migrateMangaInternal( + source: Source, + sourceChapters: List, + prevManga: Manga, + manga: Manga, + replace: Boolean + ) { val flags = preferences.migrateFlags().getOrDefault() val migrateChapters = MigrationFlags.hasChapters(flags) @@ -797,7 +803,6 @@ class LibraryPresenter( fun getFirstUnread(manga: Manga): Chapter? { val chapters = db.getChapters(manga).executeAsBlocking() return chapters.sortedByDescending { it.source_order }.find { !it.read } - } fun sortCategory(catId: Int, order: Int) { @@ -808,8 +813,7 @@ class LibraryPresenter( preferences.librarySortingMode().set(sort) preferences.librarySortingAscending().set(category.isAscending()) requestSortUpdate() - } - else { + } else { if (category.id == 0) preferences.defaultMangaOrder().set(category.mangaSort.toString()) else Injekt.get().insertCategory(category).executeAsBlocking() requestCatSortUpdate(category.id!!) @@ -845,10 +849,9 @@ class LibraryPresenter( item.manga.category = categoryId - val mc = ArrayList() val categories = - db.getCategoriesForManga(manga).executeAsBlocking().filter { it.id != oldCatId } + listOf(category) + db.getCategoriesForManga(manga).executeAsBlocking().filter { it.id != oldCatId } + listOf(category) for (cat in categories) { mc.add(MangaCategory.create(manga, cat)) @@ -874,6 +877,6 @@ class LibraryPresenter( } private companion object { - var currentLibrary:Library? = null + var currentLibrary: Library? = null } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySelectionEvent.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySelectionEvent.kt index e490e43649..2af28fca8f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySelectionEvent.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySelectionEvent.kt @@ -7,4 +7,4 @@ sealed class LibrarySelectionEvent { class Selected(val manga: Manga) : LibrarySelectionEvent() class Unselected(val manga: Manga) : LibrarySelectionEvent() class Cleared() : LibrarySelectionEvent() -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySort.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySort.kt index 8e0f0c5d13..8e31025ecf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySort.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/LibrarySort.kt @@ -8,4 +8,4 @@ object LibrarySort { const val UNREAD = 3 const val TOTAL = 4 const val DRAG_AND_DROP = 6 -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/library/ReSpinner.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/library/ReSpinner.kt index 5ecd695eb1..ba0823afb3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/library/ReSpinner.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/library/ReSpinner.kt @@ -35,4 +35,4 @@ class ReSpinner : Spinner { class SpinnerAdapter(context: Context, layoutId: Int, val array: Array) : ArrayAdapter - (context, layoutId, array) \ No newline at end of file + (context, layoutId, array) 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 5209777861..21a267d494 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 @@ -20,6 +20,9 @@ import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.inflate import eu.kanade.tachiyomi.util.view.updatePaddingRelative import eu.kanade.tachiyomi.util.view.visibleIf +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt import kotlinx.android.synthetic.main.filter_bottom_sheet.view.* import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers @@ -29,12 +32,9 @@ import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy -import kotlin.math.max -import kotlin.math.min -import kotlin.math.roundToInt -class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) - : LinearLayout(context, attrs), +class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : + LinearLayout(context, attrs), FilterTagGroupListener { /** @@ -54,11 +54,11 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri private var mangaType: FilterTagGroup? = null - var sheetBehavior:BottomSheetBehavior? = null + var sheetBehavior: BottomSheetBehavior? = null - private lateinit var clearButton:ImageView + private lateinit var clearButton: ImageView - private val filterItems:MutableList by lazy { + private val filterItems: MutableList by lazy { val list = mutableListOf() list.add(unread) list.add(downloaded) @@ -68,11 +68,11 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri list } - var onGroupClicked: (Int) -> Unit = { _ -> } - var pager:View? = null + var onGroupClicked: (Int) -> Unit = { _ -> } + var pager: View? = null var phoneLandscape = false - fun onCreate(pagerView:View) { + fun onCreate(pagerView: View) { clearButton = clear_button filter_layout.removeView(clearButton) sheetBehavior = BottomSheetBehavior.from(this) @@ -80,8 +80,8 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri sheetBehavior?.isHideable = true sheetBehavior?.skipCollapsed = phoneLandscape pager = pagerView - val shadow2:View = (pagerView.parent as ViewGroup).findViewById(R.id.shadow2) - val shadow:View = (pagerView.parent as ViewGroup).findViewById(R.id.shadow) + val shadow2: View = (pagerView.parent as ViewGroup).findViewById(R.id.shadow2) + val shadow: View = (pagerView.parent as ViewGroup).findViewById(R.id.shadow) if (phoneLandscape) { sheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN } @@ -156,8 +156,8 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri fun updateRootPadding(progress: Float? = null) { val minHeight = sheetBehavior?.peekHeight ?: 0 val maxHeight = height - val trueProgress = progress ?: - if (sheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) 1f else 0f + val trueProgress = progress + ?: if (sheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) 1f else 0f val percent = (trueProgress * 100).roundToInt() val value = (percent * (maxHeight - minHeight) / 100) + minHeight val height = context.resources.getDimensionPixelSize(R.dimen.rounder_radius) @@ -196,7 +196,7 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri private fun checkForManhwa() { GlobalScope.launch(Dispatchers.IO, CoroutineStart.DEFAULT) { - val db:DatabaseHelper by injectLazy() + val db: DatabaseHelper by injectLazy() val showCategoriesCheckBox = withContext(Dispatchers.IO) { db.getCategories().executeAsBlocking() .isNotEmpty() @@ -224,7 +224,7 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri filterItems.add(tracked) } } - withContext(Dispatchers.Main) { + withContext(Dispatchers.Main) { hide_categories.visibleIf(showCategoriesCheckBox) downloaded.setState(preferences.filterDownloaded()) completed.setState(preferences.filterCompleted()) @@ -255,11 +255,10 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri } } } - } } - override fun onFilterClicked(view: FilterTagGroup, index: Int, updatePreference:Boolean) { + override fun onFilterClicked(view: FilterTagGroup, index: Int, updatePreference: Boolean) { if (updatePreference) { if (view == trackers) { FILTER_TRACKER = view.nameOf(index) ?: "" @@ -279,8 +278,7 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri trackers != null && trackers?.parent == null) { filter_layout.addView(trackers) filterItems.add(trackers!!) - } - else if (preferences.filterTracked().getOrDefault() != 1 && + } else if (preferences.filterTracked().getOrDefault() != 1 && trackers?.parent != null) { filter_layout.removeView(trackers) trackers?.reset() @@ -334,4 +332,4 @@ class FilterBottomSheet @JvmOverloads constructor(context: Context, attrs: Attri var FILTER_TRACKER = "" private set } -} \ No newline at end of file +} 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 955cae809a..3386b9c190 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 @@ -14,7 +14,7 @@ import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.filter_buttons.view.* -class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null): LinearLayout +class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout (context, attrs) { private var listener: FilterTagGroupListener? = null @@ -22,7 +22,7 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute var itemCount = 0 private set - private var root:ViewGroup? = null + private var root: ViewGroup? = null private val buttons by lazy { arrayOf(firstButton, secondButton, thirdButton) } private val separators by lazy { arrayOf(separator1, separator2) } @@ -31,7 +31,7 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute return buttons.any { it.isActivated } } - fun nameOf(index: Int):String? = buttons.getOrNull(index)?.text as? String + fun nameOf(index: Int): String? = buttons.getOrNull(index)?.text as? String fun setup(root: ViewGroup, firstText: Int, secondText: Int? = null, thirdText: Int? = null) { val text1 = context.getString(firstText) @@ -40,8 +40,13 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute setup(root, text1, text2, text3) } - fun setup(root: ViewGroup, firstText: String, secondText: String? = null, thirdText: String? = - null) { + fun setup( + root: ViewGroup, + firstText: String, + secondText: String? = null, + thirdText: String? = + null + ) { listener = root as? FilterTagGroupListener (layoutParams as? MarginLayoutParams)?.rightMargin = 5.dpToPx (layoutParams as? MarginLayoutParams)?.leftMargin = 5.dpToPx @@ -52,13 +57,11 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute if (thirdText != null) { thirdButton.text = thirdText itemCount = 3 - } - else { + } else { thirdButton.gone() separator2.gone() } - } - else { + } else { itemCount = 1 secondButton.gone() separator1.gone() @@ -66,9 +69,9 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute separator2.gone() } this.root = root - firstButton.setOnClickListener {toggleButton(0) } - secondButton.setOnClickListener {toggleButton(1) } - thirdButton.setOnClickListener {toggleButton(2) } + firstButton.setOnClickListener { toggleButton(0) } + secondButton.setOnClickListener { toggleButton(1) } + thirdButton.setOnClickListener { toggleButton(2) } } fun setState(preference: Preference) { @@ -87,7 +90,7 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute buttons.forEach { it.isActivated = false } - for (i in 0 until itemCount) { + for (i in 0 until itemCount) { buttons[i].visible() buttons[i].setTextColor(context.getResourceColor(android.R.attr.textColorPrimary)) } @@ -122,12 +125,11 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute listener?.onFilterClicked(this, -1, callBack) if (itemCount >= 3) separator2.visible() - buttons.forEach{ it.visible() } - } - else { + buttons.forEach { it.visible() } + } else { mainButton.isActivated = true listener?.onFilterClicked(this, index, callBack) - buttons.forEach{ it.gone() } + buttons.forEach { it.gone() } separator1.gone() if (itemCount >= 3) { separator2.gone() @@ -139,5 +141,5 @@ class FilterTagGroup@JvmOverloads constructor(context: Context, attrs: Attribute } interface FilterTagGroupListener { - fun onFilterClicked(view: FilterTagGroup, index: Int, updatePreference:Boolean) -} \ No newline at end of file + fun onFilterClicked(view: FilterTagGroup, index: Int, updatePreference: Boolean) +} 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 5294948455..882a549e6b 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 @@ -45,7 +45,6 @@ import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi import eu.kanade.tachiyomi.ui.base.activity.BaseActivity import eu.kanade.tachiyomi.ui.base.controller.BaseController import eu.kanade.tachiyomi.ui.base.controller.DialogController -import eu.kanade.tachiyomi.ui.base.controller.NoToolbarElevationController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.catalogue.CatalogueController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController @@ -80,19 +79,19 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { protected lateinit var router: Router protected var drawerArrow: DrawerArrowDrawable? = null - private var searchDrawable:Drawable? = null - private var currentGestureDelegate:SwipeGestureInterface? = null - private lateinit var gestureDetector:GestureDetectorCompat + private var searchDrawable: Drawable? = null + private var currentGestureDelegate: SwipeGestureInterface? = null + private lateinit var gestureDetector: GestureDetectorCompat private var secondaryDrawer: ViewGroup? = null - private var snackBar:Snackbar? = null - private var extraViewForUndo:View? = null + private var snackBar: Snackbar? = null + private var extraViewForUndo: View? = null private var canDismissSnackBar = false private var animationSet: AnimatorSet? = null - private var bottomNavHeight = 0 + private var bottomNavHeight = 0 fun setUndoSnackBar(snackBar: Snackbar?, extraViewToCheck: View? = null) { this.snackBar = snackBar @@ -132,10 +131,9 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { drawerArrow = DrawerArrowDrawable(this) drawerArrow?.color = getResourceColor(R.attr.actionBarTintColor) - searchDrawable = ContextCompat.getDrawable(this, R.drawable - .ic_search_white_24dp) - - // tabAnimator = TabsAnimator(tabs) + searchDrawable = ContextCompat.getDrawable( + this, R.drawable.ic_search_white_24dp + ) var continueSwitchingTabs = false bottom_nav.setOnNavigationItemSelectedListener { item -> @@ -143,29 +141,30 @@ 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 val currentRoot = router.backstack.firstOrNull() if (currentRoot?.tag()?.toIntOrNull() != id) { when (id) { R.id.nav_library -> setRoot( - if (preferences.libraryAsSingleList().getOrDefault()) - LibraryListController() - else - LibraryController(), id) - R.id.nav_recents -> { - if (preferences.showRecentUpdates().getOrDefault()) - setRoot(RecentChaptersController(), id) - else - setRoot(RecentlyReadController(), id) + if (preferences.libraryAsSingleList() + .getOrDefault() + ) LibraryListController() + else LibraryController(), id + ) + R.id.nav_recents -> { + if (preferences.showRecentUpdates().getOrDefault()) setRoot( + RecentChaptersController(), + id + ) + else setRoot(RecentlyReadController(), id) } R.id.nav_catalogues -> setRoot(CatalogueController(), id) } - } - else if (currentRoot.tag()?.toIntOrNull() == id) { + } else if (currentRoot.tag()?.toIntOrNull() == id) { if (router.backstackSize == 1) { when (id) { R.id.nav_recents -> { @@ -194,22 +193,18 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { val content: ViewGroup = findViewById(R.id.main_content) DownloadService.addListener(this) - content.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or - View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or - View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - container.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or - View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or - View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + content.systemUiVisibility = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + container.systemUiVisibility = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION updateRecentsIcon() content.viewTreeObserver.addOnGlobalLayoutListener { val heightDiff: Int = content.rootView.height - content.height - if (heightDiff > 200 && - window.attributes.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { - //keyboard is open, hide layout + if (heightDiff > 200 && window.attributes.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { + // keyboard is open, hide layout bottom_nav.gone() - } else if (bottom_nav.visibility == View.GONE - && window.attributes.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { - //keyboard is hidden, show layout + } else if (bottom_nav.visibility == View.GONE && window.attributes.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) { + // keyboard is hidden, show layout // use coroutine to delay so the bottom bar doesn't flash on top of the keyboard launchUI { bottom_nav.visible() @@ -219,39 +214,38 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { supportActionBar?.setDisplayShowCustomEnabled(true) - window.statusBarColor = ColorUtils.setAlphaComponent(getResourceColor(android.R.attr - .colorBackground), 175) + window.statusBarColor = ColorUtils.setAlphaComponent( + getResourceColor( + android.R.attr.colorBackground + ), 175 + ) content.setOnApplyWindowInsetsListener { v, insets -> - // if device doesn't support light nav bar + // if device doesn't support light nav bar window.navigationBarColor = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { - // basically if in landscape on a phone - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && - (v.rootWindowInsets.systemWindowInsetLeft > 0 || - v.rootWindowInsets.systemWindowInsetRight > 0)) - // For lollipop, draw opaque nav bar - Color.BLACK - else Color.argb(179, 0, 0, 0) - } - /*else { - getColor(android.R.color.transparent) - }*/ - // if the android q+ device has gesture nav, transparent nav bar - // this is here incase some crazy with a notch uses landscape - else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q - && (v.rootWindowInsets.systemWindowInsetBottom != v.rootWindowInsets - .tappableElementInsets.bottom)) { - getColor(android.R.color.transparent) - } - // if in landscape with 2/3 button mode, fully opaque nav bar - else if (v.rootWindowInsets.systemWindowInsetLeft > 0 - || v.rootWindowInsets.systemWindowInsetRight > 0) { - getResourceColor( android.R.attr.colorPrimary ) - } - // if in portrait with 2/3 button mode, translucent nav bar - else { - ColorUtils.setAlphaComponent( - getResourceColor(android.R.attr.colorPrimary), 179) - } + // basically if in landscape on a phone + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (v.rootWindowInsets.systemWindowInsetLeft > 0 || v.rootWindowInsets.systemWindowInsetRight > 0)) + // For lollipop, draw opaque nav bar + Color.BLACK + else Color.argb(179, 0, 0, 0) + } + /*else { + getColor(android.R.color.transparent) + }*/ + // if the android q+ device has gesture nav, transparent nav bar + // this is here incase some crazy with a notch uses landscape + else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && (v.rootWindowInsets.systemWindowInsetBottom != v.rootWindowInsets.tappableElementInsets.bottom)) { + getColor(android.R.color.transparent) + } + // if in landscape with 2/3 button mode, fully opaque nav bar + else if (v.rootWindowInsets.systemWindowInsetLeft > 0 || v.rootWindowInsets.systemWindowInsetRight > 0) { + getResourceColor(android.R.attr.colorPrimary) + } + // if in portrait with 2/3 button mode, translucent nav bar + else { + ColorUtils.setAlphaComponent( + getResourceColor(android.R.attr.colorPrimary), 179 + ) + } val contextView = window?.decorView?.findViewById(R.id.action_mode_bar) contextView?.updateLayoutParams { leftMargin = insets.systemWindowInsetLeft @@ -260,8 +254,7 @@ 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 @@ -279,24 +272,23 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { height = 0//insets.systemWindowInsetBottom }*/ insets.replaceSystemWindowInsets( - 0, insets.systemWindowInsetTop, - 0, insets.systemWindowInsetBottom + 0, insets.systemWindowInsetTop, 0, insets.systemWindowInsetBottom ) insets } val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK - if (Build.VERSION.SDK_INT >= 26 && currentNightMode == Configuration.UI_MODE_NIGHT_NO && - preferences.theme() >= 8) { - content.systemUiVisibility = content.systemUiVisibility.or(View - .SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) + if (Build.VERSION.SDK_INT >= 26 && currentNightMode == Configuration.UI_MODE_NIGHT_NO && preferences.theme() >= 8) { + content.systemUiVisibility = content.systemUiVisibility.or( + View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + ) } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && currentNightMode == Configuration - .UI_MODE_NIGHT_NO) - content.systemUiVisibility = content.systemUiVisibility.or(View - .SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && currentNightMode == Configuration.UI_MODE_NIGHT_NO) content.systemUiVisibility = + content.systemUiVisibility.or( + View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR + ) - //val drawerContainer: FrameLayout = findViewById(R.id.drawer_container) + // val drawerContainer: FrameLayout = findViewById(R.id.drawer_container) router = Conductor.attachRouter(this, container, savedInstanceState) if (!router.hasRootController()) { @@ -310,25 +302,33 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { val rootSearchController = router.backstack.lastOrNull()?.controller() if (rootSearchController is RootSearchInterface) { toolbar.menu.findItem(R.id.action_search)?.expandActionView() - } - else onBackPressed() + } else onBackPressed() } bottom_nav.visibility = if (router.backstackSize > 1) View.GONE else View.VISIBLE bottom_nav.alpha = if (router.backstackSize > 1) 0f else 1f router.addChangeListener(object : ControllerChangeHandler.ControllerChangeListener { - override fun onChangeStarted(to: Controller?, from: Controller?, isPush: Boolean, - container: ViewGroup, handler: ControllerChangeHandler) { + override fun onChangeStarted( + to: Controller?, + from: Controller?, + isPush: Boolean, + container: ViewGroup, + handler: ControllerChangeHandler + ) { syncActivityViewWithController(to, from, isPush) appbar.y = 0f } - override fun onChangeCompleted(to: Controller?, from: Controller?, isPush: Boolean, - container: ViewGroup, handler: ControllerChangeHandler) { + override fun onChangeCompleted( + to: Controller?, + from: Controller?, + isPush: Boolean, + container: ViewGroup, + handler: ControllerChangeHandler + ) { appbar.y = 0f } - }) syncActivityViewWithController(router.backstack.lastOrNull()?.controller()) @@ -341,20 +341,10 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { // Show changelog if needed if (Migrations.upgrade(preferences)) { if (BuildConfig.DEBUG) { - MaterialDialog(this) - .title(text = "Welcome to the J2K MD2 Beta") - .message(text = "This beta is for testing the upcoming " + - "release. Requests for new additions this beta will ignored (however" + - " suggestions on how to better implement a feature in this beta are " + - "welcome).\n\nFor any bugs you come across, there is a bug report " + - "button in settings.\n\nAs a reminder this is a *BETA* build and bugs" + - " may happen and features may be missing/not implemented yet." + - "\n\nEnjoy and thanks for testing!") - .positiveButton(android.R.string.ok) - .cancelOnTouchOutside(false) - .show() - } - else ChangelogDialogController().showDialog(router) + MaterialDialog(this).title(text = "Welcome to the J2K MD2 Beta").message( + text = "This beta is for testing the upcoming " + "release. Requests for new additions this beta will ignored (however" + " suggestions on how to better implement a feature in this beta are " + "welcome).\n\nFor any bugs you come across, there is a bug report " + "button in settings.\n\nAs a reminder this is a *BETA* build and bugs" + " may happen and features may be missing/not implemented yet." + "\n\nEnjoy and thanks for testing!" + ).positiveButton(android.R.string.ok).cancelOnTouchOutside(false).show() + } else ChangelogDialogController().showDialog(router) } } preferences.extensionUpdatesCount().asObservable().subscribe { @@ -364,15 +354,18 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { } fun updateRecentsIcon() { - bottom_nav.menu.findItem(R.id.nav_recents).icon = - AppCompatResources.getDrawable(this, - if (preferences.showRecentUpdates().getOrDefault()) R.drawable.recent_updates_selector_24dp - else R.drawable.recent_read_selector_24dp) + bottom_nav.menu.findItem(R.id.nav_recents).icon = AppCompatResources.getDrawable( + this, + if (preferences.showRecentUpdates() + .getOrDefault() + ) R.drawable.recent_updates_selector_24dp + else R.drawable.recent_read_selector_24dp + ) } override fun startSupportActionMode(callback: androidx.appcompat.view.ActionMode.Callback): androidx.appcompat.view.ActionMode? { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) - window?.statusBarColor = getResourceColor(R.attr.colorPrimary) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) window?.statusBarColor = + getResourceColor(R.attr.colorPrimary) return super.startSupportActionMode(callback) } @@ -384,9 +377,12 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { val duration = resources.getInteger(android.R.integer.config_mediumAnimTime) * scale delay(duration.toLong()) delay(100) - if (Color.alpha(window?.statusBarColor ?: Color.BLACK) >= 255) - window?.statusBarColor = ColorUtils.setAlphaComponent(getResourceColor(android.R.attr - .colorBackground), 175) + if (Color.alpha(window?.statusBarColor ?: Color.BLACK) >= 255) window?.statusBarColor = + ColorUtils.setAlphaComponent( + getResourceColor( + android.R.attr.colorBackground + ), 175 + ) } super.onSupportActionModeFinished(mode) } @@ -398,8 +394,7 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { badge.number = updates badge.backgroundColor = getResourceColor(R.attr.badgeColor) badge.badgeTextColor = Color.WHITE - } - else { + } else { bottom_nav.removeBadge(R.id.nav_catalogues) } } @@ -412,15 +407,15 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { } private fun getExtensionUpdates() { - if (Date().time >= preferences.lastExtCheck().getOrDefault() + - TimeUnit.HOURS.toMillis(1)) { + if (Date().time >= preferences.lastExtCheck().getOrDefault() + TimeUnit.HOURS.toMillis(1)) { GlobalScope.launch(Dispatchers.IO) { val preferences: PreferencesHelper by injectLazy() try { val pendingUpdates = ExtensionGithubApi().checkForUpdates(this@MainActivity) preferences.extensionUpdatesCount().set(pendingUpdates.size) preferences.lastExtCheck().set(Date().time) - } catch (e: java.lang.Exception) { } + } catch (e: java.lang.Exception) { + } } } } @@ -445,14 +440,14 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { } SHORTCUT_CATALOGUES -> bottom_nav.selectedItemId = R.id.nav_catalogues SHORTCUT_EXTENSIONS -> { - if (router.backstack.isEmpty()) { - bottom_nav.selectedItemId = R.id.nav_catalogues - bottom_nav.post { - val controller = - router.backstack.firstOrNull()?.controller() as? CatalogueController - controller?.showExtensions() - } + if (router.backstack.isEmpty()) { + bottom_nav.selectedItemId = R.id.nav_catalogues + bottom_nav.post { + val controller = + router.backstack.firstOrNull()?.controller() as? CatalogueController + controller?.showExtensions() } + } } SHORTCUT_MANGA -> { val extras = intent.extras ?: return false @@ -465,20 +460,21 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { if (router.backstack.none { it.controller() is DownloadController }) { if (router.backstack.isEmpty()) { bottom_nav.selectedItemId = R.id.nav_library - router.pushController(RouterTransaction.with(DownloadController()) - .pushChangeHandler(SimpleSwapChangeHandler()) - .popChangeHandler(FadeChangeHandler())) - } - else { + router.pushController( + RouterTransaction.with(DownloadController()) + .pushChangeHandler(SimpleSwapChangeHandler()) + .popChangeHandler(FadeChangeHandler()) + ) + } else { router.pushController(DownloadController().withFadeTransaction()) } } } Intent.ACTION_SEARCH, "com.google.android.gms.actions.SEARCH_ACTION" -> { - //If the intent match the "standard" Android search intent + // If the intent match the "standard" Android search intent // or the Google-specific search intent (triggered by saying or typing "search *query* on *Tachiyomi*" in Google Search/Google Assistant) - //Get the search query provided in extras, and if not null, perform a global search with it. + // Get the search query provided in extras, and if not null, perform a global search with it. val query = intent.getStringExtra(SearchManager.QUERY) if (query != null && query.isNotEmpty()) { if (router.backstackSize > 1) { @@ -494,7 +490,12 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { if (router.backstackSize > 1) { router.popToRoot() } - router.pushController(CatalogueSearchController(query, filter).withFadeTransaction()) + router.pushController( + CatalogueSearchController( + query, + filter + ).withFadeTransaction() + ) } } else -> return false @@ -516,13 +517,14 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { /*if (drawer.isDrawerOpen(GravityCompat.START) || drawer.isDrawerOpen(GravityCompat.END)) { drawer.closeDrawers() } else {*/ - val baseController = router.backstack.last().controller() as? BaseController - if (if (router.backstackSize == 1) !(baseController?.handleRootBack() ?: false) - else !router.handleBack()) { - SecureActivityDelegate.locked = true - super.onBackPressed() - } - //} + val baseController = router.backstack.last().controller() as? BaseController + if (if (router.backstackSize == 1) !(baseController?.handleRootBack() ?: false) + else !router.handleBack() + ) { + SecureActivityDelegate.locked = true + super.onBackPressed() + } + // } } private fun setRoot(controller: Controller, id: Int) { @@ -533,9 +535,11 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { when (item.itemId) { // Initialize option to open catalogue settings. R.id.action_settings -> { - router.pushController((RouterTransaction.with(SettingsMainController())) - .popChangeHandler(FadeChangeHandler()) - .pushChangeHandler(FadeChangeHandler())) + router.pushController( + (RouterTransaction.with(SettingsMainController())).popChangeHandler( + FadeChangeHandler() + ).pushChangeHandler(FadeChangeHandler()) + ) } else -> return super.onOptionsItemSelected(item) } @@ -545,26 +549,26 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { gestureDetector.onTouchEvent(ev) val controller = router.backstack.lastOrNull()?.controller() - if (controller is OnTouchEventInterface) - controller.onTouchEvent(ev) + if (controller is OnTouchEventInterface) controller.onTouchEvent(ev) if (ev?.action == MotionEvent.ACTION_DOWN) { if (snackBar != null && snackBar!!.isShown) { val sRect = Rect() snackBar!!.view.getGlobalVisibleRect(sRect) - val extRect:Rect? = if (extraViewForUndo != null) Rect() else null + val extRect: Rect? = if (extraViewForUndo != null) Rect() else null 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()))) { + // 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())) + ) { snackBar?.dismiss() snackBar = null extraViewForUndo = null } - } - else if (snackBar != null) { + } else if (snackBar != null) { snackBar = null extraViewForUndo = null } @@ -572,8 +576,11 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { return super.dispatchTouchEvent(ev) } - protected open fun syncActivityViewWithController(to: Controller?, from: Controller? = null, - isPush: Boolean = false) { + protected open fun syncActivityViewWithController( + to: Controller?, + from: Controller? = null, + isPush: Boolean = false + ) { if (from is DialogController || to is DialogController) { return } @@ -602,43 +609,30 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { } else newDrawer }*/ - if (to is NoToolbarElevationController) { - appbar.disableElevation() - /*controller_container.updateLayoutParams { - behavior = null - }*/ - } else { - appbar.enableElevation() - /*controller_container.updateLayoutParams { - behavior = AppBarLayout.ScrollingViewBehavior() - }*/ - } - if (to !is SpinnerTitleInterface) toolbar.removeSpinner() if (to !is DialogController) { - bottom_nav.visibility = if (router.backstackSize == 0 || - (router.backstackSize <= 1 && !isPush)) - View.VISIBLE else bottom_nav.visibility + bottom_nav.visibility = + if (router.backstackSize == 0 || (router.backstackSize <= 1 && !isPush)) View.VISIBLE else bottom_nav.visibility animationSet?.cancel() animationSet = AnimatorSet() val alphaAnimation = ValueAnimator.ofFloat( - bottom_nav.alpha, - if (router.backstackSize > 1) 0f else 1f + bottom_nav.alpha, if (router.backstackSize > 1) 0f else 1f ) alphaAnimation.addUpdateListener { valueAnimator -> bottom_nav.alpha = valueAnimator.animatedValue as Float } alphaAnimation.addListener(object : Animator.AnimatorListener { override fun onAnimationEnd(animation: Animator?) { - bottom_nav.visibility = if (router.backstackSize > 1) View.GONE else View.VISIBLE + bottom_nav.visibility = + if (router.backstackSize > 1) View.GONE else View.VISIBLE } - override fun onAnimationCancel(animation: Animator?) { } + override fun onAnimationCancel(animation: Animator?) {} - override fun onAnimationRepeat(animation: Animator?) { } + override fun onAnimationRepeat(animation: Animator?) {} - override fun onAnimationStart(animation: Animator?) { } + override fun onAnimationStart(animation: Animator?) {} }) alphaAnimation.duration = 200 alphaAnimation.startDelay = 50 @@ -661,14 +655,16 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { }*/ } - private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { return true } override fun onFling( - e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float + e1: MotionEvent, + e2: MotionEvent, + velocityX: Float, + velocityY: Float ): Boolean { if (currentGestureDelegate == null) return false var result = false @@ -676,14 +672,14 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { - if (abs(diffX) > Companion.SWIPE_THRESHOLD && - abs(velocityX) > Companion.SWIPE_VELOCITY_THRESHOLD - && abs(diffY) <= Companion.SWIPE_THRESHOLD * 0.75f + if (abs(diffX) > Companion.SWIPE_THRESHOLD && abs(velocityX) > Companion.SWIPE_VELOCITY_THRESHOLD && abs( + diffY + ) <= Companion.SWIPE_THRESHOLD * 0.75f ) { if (diffX > 0) { - currentGestureDelegate?.onSwipeRight(velocityX, e1.y) + currentGestureDelegate?.onSwipeRight(velocityX, e1.y) } else { - currentGestureDelegate?.onSwipeLeft(velocityX, e1.y) + currentGestureDelegate?.onSwipeLeft(velocityX, e1.y) } result = true } @@ -692,10 +688,10 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { ) > Companion.SWIPE_VELOCITY_THRESHOLD ) { if (diffY > 0) { - currentGestureDelegate?.onSwipeBottom(e1.x, e1.y) - //onSwipeBottom() + currentGestureDelegate?.onSwipeBottom(e1.x, e1.y) + // onSwipeBottom() } else { - currentGestureDelegate?.onSwipeTop(e1.x, e1.y) + currentGestureDelegate?.onSwipeTop(e1.x, e1.y) } result = true } @@ -704,13 +700,13 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { } return result } - } companion object { private const val SWIPE_THRESHOLD = 100 private const val SWIPE_VELOCITY_THRESHOLD = 100 + // Shortcut actions const val SHORTCUT_LIBRARY = "eu.kanade.tachiyomi.SHOW_LIBRARY" const val SHORTCUT_RECENTLY_UPDATED = "eu.kanade.tachiyomi.SHOW_RECENTLY_UPDATED" @@ -723,7 +719,6 @@ open class MainActivity : BaseActivity(), DownloadServiceListener { const val INTENT_SEARCH = "eu.kanade.tachiyomi.SEARCH" const val INTENT_SEARCH_QUERY = "query" const val INTENT_SEARCH_FILTER = "filter" - } } @@ -743,4 +738,4 @@ interface SwipeGestureInterface { fun onSwipeLeft(x: Float, y: Float) fun onSwipeTop(x: Float, y: Float) fun onSwipeBottom(x: Float, y: Float) -} \ No newline at end of file +} 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 e187f6effa..3791efba76 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 @@ -6,14 +6,13 @@ import android.os.Bundle import com.bluelinelabs.conductor.Controller import eu.kanade.tachiyomi.data.notification.NotificationReceiver import eu.kanade.tachiyomi.ui.base.controller.DialogController -import eu.kanade.tachiyomi.ui.base.controller.NoToolbarElevationController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController import eu.kanade.tachiyomi.ui.security.SecureActivityDelegate import eu.kanade.tachiyomi.util.view.gone import kotlinx.android.synthetic.main.main_activity.* -class SearchActivity: MainActivity() { +class SearchActivity : MainActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -39,8 +38,12 @@ class SearchActivity: MainActivity() { } } - override fun syncActivityViewWithController(to: Controller?, from: Controller?, isPush: - Boolean) { + override fun syncActivityViewWithController( + to: Controller?, + from: Controller?, + isPush: + Boolean + ) { if (from is DialogController || to is DialogController) { return } @@ -48,12 +51,6 @@ class SearchActivity: MainActivity() { drawerArrow?.progress = 1f if (to !is SpinnerTitleInterface) toolbar.removeSpinner() - - if (to is NoToolbarElevationController) { - appbar.disableElevation() - } else { - appbar.enableElevation() - } bottom_nav.gone() } @@ -64,10 +61,10 @@ class SearchActivity: MainActivity() { ) when (intent.action) { Intent.ACTION_SEARCH, "com.google.android.gms.actions.SEARCH_ACTION" -> { - //If the intent match the "standard" Android search intent + // If the intent match the "standard" Android search intent // or the Google-specific search intent (triggered by saying or typing "search *query* on *Tachiyomi*" in Google Search/Google Assistant) - //Get the search query provided in extras, and if not null, perform a global search with it. + // Get the search query provided in extras, and if not null, perform a global search with it. val query = intent.getStringExtra(SearchManager.QUERY) if (query != null && query.isNotEmpty()) { router.replaceTopController(CatalogueSearchController(query).withFadeTransaction()) @@ -87,4 +84,4 @@ class SearchActivity: MainActivity() { } return true } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/main/TabsAnimator.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/main/TabsAnimator.kt index 9cd5393704..78f3f37086 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/main/TabsAnimator.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/main/TabsAnimator.kt @@ -102,5 +102,4 @@ class TabsAnimator(val tabs: TabLayout) { */ private val isMeasured: Boolean get() = tabsHeight > 0 - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChaptersSortBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChaptersSortBottomSheet.kt index 106f60b8f7..b6b5e243b3 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChaptersSortBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChaptersSortBottomSheet.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.ui.manga - import android.os.Build import android.os.Bundle import android.view.View @@ -46,7 +45,6 @@ class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetD } } }) - } override fun onStart() { @@ -79,7 +77,6 @@ class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetD } } - private fun initGeneralPreferences() { show_read.isChecked = presenter.onlyRead() show_unread.isChecked = presenter.onlyUnread() @@ -123,14 +120,12 @@ class ChaptersSortBottomSheet(controller: MangaDetailsController) : BottomSheetD show_unread.isChecked = false show_download.isChecked = false show_bookmark.isChecked = false - } - else { + } else { show_all.isChecked = false if (show_read == checkBox) show_unread.isChecked = false else if (show_unread == checkBox) show_read.isChecked = false } - } - else if (!show_read.isChecked && !show_unread.isChecked && + } else if (!show_read.isChecked && !show_unread.isChecked && !show_download.isChecked && !show_bookmark.isChecked) { show_all.isChecked = true } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChooseShapeDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChooseShapeDialog.kt index 0f8271de3c..6f5a5836ab 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChooseShapeDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/ChooseShapeDialog.kt @@ -26,12 +26,11 @@ class ChooseShapeDialog(bundle: Bundle? = null) : DialogController(bundle) { return MaterialDialog(activity!!) .title(R.string.icon_shape) .negativeButton(android.R.string.cancel) - .listItemsSingleChoice ( + .listItemsSingleChoice( items = modes.map { activity?.getString(it) as CharSequence }, - waitForPositiveButton = false) - { _, i, _ -> + waitForPositiveButton = false) { _, i, _ -> (targetController as? MangaDetailsController)?.createShortcutForShape(i) dismissDialog() } } -} \ No newline at end of file +} 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 985f16655b..e36656ed9e 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 @@ -71,7 +71,6 @@ import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.base.controller.BaseController import eu.kanade.tachiyomi.ui.base.controller.DialogController -import eu.kanade.tachiyomi.ui.base.controller.NoToolbarElevationController import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.ui.catalogue.CatalogueController import eu.kanade.tachiyomi.ui.library.ChangeMangaCategoriesDialog @@ -96,6 +95,7 @@ import eu.kanade.tachiyomi.util.view.getText import eu.kanade.tachiyomi.util.view.snack import eu.kanade.tachiyomi.util.view.updateLayoutParams import eu.kanade.tachiyomi.util.view.updatePaddingRelative +import java.io.File import jp.wasabeef.glide.transformations.CropSquareTransformation import jp.wasabeef.glide.transformations.MaskTransformation import kotlinx.android.synthetic.main.main_activity.* @@ -104,20 +104,20 @@ import kotlinx.android.synthetic.main.manga_header_item.* import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File class MangaDetailsController : BaseController, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, ActionMode.Callback, ChaptersAdapter.MangaHeaderInterface, - ChangeMangaCategoriesDialog.Listener, - NoToolbarElevationController { + ChangeMangaCategoriesDialog.Listener { - constructor(manga: Manga?, + constructor( + manga: Manga?, fromCatalogue: Boolean = false, smartSearchConfig: CatalogueController.SmartSearchConfig? = null, - update: Boolean = false) : super(Bundle().apply { + update: Boolean = false + ) : super(Bundle().apply { putLong(MANGA_EXTRA, manga?.id ?: 0) putBoolean(FROM_CATALOGUE_EXTRA, fromCatalogue) putParcelable(SMART_SEARCH_CONFIG_EXTRA, smartSearchConfig) @@ -143,15 +143,15 @@ class MangaDetailsController : BaseController, private var manga: Manga? = null private var source: Source? = null - var colorAnimator:ValueAnimator? = null - val presenter:MangaDetailsPresenter - var coverColor:Int? = null + var colorAnimator: ValueAnimator? = null + val presenter: MangaDetailsPresenter + var coverColor: Int? = null var toolbarIsColored = false private var snack: Snackbar? = null val fromCatalogue = args.getBoolean(FROM_CATALOGUE_EXTRA, false) - var coverDrawable:Drawable? = null + var coverDrawable: Drawable? = null private var trackingBottomSheet: TrackingBottomSheet? = null - private var startingDLChapterPos:Int? = null + private var startingDLChapterPos: Int? = null /** * Adapter containing a list of chapters. @@ -204,7 +204,7 @@ class MangaDetailsController : BaseController, swipe_refresh.setProgressViewOffset(false, (-40).dpToPx, headerHeight + offset) (recycler.findViewHolderForAdapterPosition(0) as? MangaHeaderHolder) ?.setTopHeight(headerHeight) - fast_scroller?.updateLayoutParams { + fast_scroller?.updateLayoutParams { topMargin = headerHeight bottomMargin = insets.systemWindowInsetBottom } @@ -264,7 +264,8 @@ class MangaDetailsController : BaseController, .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .signature(ObjectKey(MangaImpl.getLastCoverFetch(manga!!.id!!).toString())) .into(object : CustomTarget() { - override fun onResourceReady(resource: Drawable, + override fun onResourceReady( + resource: Drawable, transition: Transition? ) { coverDrawable = resource @@ -303,7 +304,7 @@ class MangaDetailsController : BaseController, presenter.fetchChapters() val isCurrentController = router?.backstack?.lastOrNull()?.controller() == this - if (isCurrentController) { + if (isCurrentController) { setStatusBarAndToolbar() } } @@ -326,8 +327,7 @@ class MangaDetailsController : BaseController, super.onChangeStarted(handler, type) if (type == ControllerChangeType.PUSH_ENTER || type == ControllerChangeType.POP_ENTER) { setStatusBarAndToolbar() - } - else if (type == ControllerChangeType.PUSH_EXIT || type == ControllerChangeType.POP_EXIT) { + } else if (type == ControllerChangeType.PUSH_EXIT || type == ControllerChangeType.POP_EXIT) { if (router.backstack.lastOrNull()?.controller() is DialogController) return if (type == ControllerChangeType.POP_EXIT) setHasOptionsMenu(false) @@ -376,8 +376,7 @@ class MangaDetailsController : BaseController, ?.toggleActivation() startingDLChapterPos = position actionMode?.invalidate() - } - else { + } else { val startingPosition = startingDLChapterPos ?: return false var chapterList = listOf() when { @@ -737,8 +736,7 @@ class MangaDetailsController : BaseController, } if (chapter.status != Download.NOT_DOWNLOADED && chapter.status != Download.ERROR) { presenter.deleteChapters(listOf(chapter)) - } - else { + } else { if (chapter.status == Download.ERROR) DownloadService.start(view.context) else @@ -782,14 +780,12 @@ class MangaDetailsController : BaseController, ChangeMangaCategoriesDialog(this, listOf(manga), categories, preselected) .showDialog(router) } - } - else { + } else { if (!manga.favorite) { toggleMangaFavorite() - } - else { - val headerHolder = recycler.findViewHolderForAdapterPosition(0) as? MangaHeaderHolder ?: - return + } else { + val headerHolder = recycler.findViewHolderForAdapterPosition(0) as? MangaHeaderHolder + ?: return val popup = PopupMenu(view!!.context, headerHolder.favorite_button) popup.menu.add(R.string.remove_from_library) @@ -888,8 +884,7 @@ class MangaDetailsController : BaseController, } override fun handleBack(): Boolean { - if (manga_cover_full?.visibility == View.VISIBLE) - { + if (manga_cover_full?.visibility == View.VISIBLE) { manga_cover_full?.performClick() return true } @@ -1131,4 +1126,4 @@ class MangaDetailsController : BaseController, const val FROM_CATALOGUE_EXTRA = "from_catalogue" const val MANGA_EXTRA = "manga" } -} \ No newline at end of file +} 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 c1afbeb655..0198ddd543 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 @@ -30,6 +30,10 @@ import eu.kanade.tachiyomi.ui.manga.track.TrackItem import eu.kanade.tachiyomi.ui.security.SecureActivityDelegate import eu.kanade.tachiyomi.util.chapter.syncChaptersWithSource import eu.kanade.tachiyomi.util.storage.DiskUtil +import java.io.File +import java.io.FileOutputStream +import java.io.OutputStream +import java.util.Date import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -39,20 +43,16 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.io.FileOutputStream -import java.io.OutputStream -import java.util.Date -class MangaDetailsPresenter(private val controller: MangaDetailsController, +class MangaDetailsPresenter( + private val controller: MangaDetailsController, val manga: Manga, val source: Source, val preferences: PreferencesHelper = Injekt.get(), private val coverCache: CoverCache = Injekt.get(), private val db: DatabaseHelper = Injekt.get(), - private val downloadManager: DownloadManager = Injekt.get()): - DownloadQueue.DownloadListener, - LibraryServiceListener { + private val downloadManager: DownloadManager = Injekt.get() +) : DownloadQueue.DownloadListener, LibraryServiceListener { private var scope = CoroutineScope(Job() + Dispatchers.Default) @@ -65,7 +65,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, var trackList: List = emptyList() - var chapters:List = emptyList() + var chapters: List = emptyList() private set var headerItem = MangaHeaderItem(manga, controller.fromCatalogue) @@ -81,8 +81,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, controller.setRefresh(true) controller.updateHeader() refreshAll() - } - else { + } else { updateChapters() controller.updateChapters(this.chapters) } @@ -113,12 +112,11 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, // Store the last emission this.chapters = applyChapterFilters(chapters) - } private fun updateChapters(fetchedChapters: List? = null) { - val chapters = (fetchedChapters ?: - db.getChapters(manga).executeAsBlocking()).map { it.toModel() } + val chapters = + (fetchedChapters ?: db.getChapters(manga).executeAsBlocking()).map { it.toModel() } // Find downloaded chapters setDownloadedChapters(chapters) @@ -164,6 +162,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, } return model } + /** * Sets the active display mode. * @param hide set title to hidden @@ -181,7 +180,6 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, fun setSorting(sort: Int) { manga.sorting = sort db.updateFlags(manga).executeAsBlocking() - // refreshChapters() } /** @@ -261,10 +259,9 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, fun allUnread(): Boolean = chapters.none { it.read } - fun getUnreadChaptersSorted() = chapters - .filter { !it.read && it.status == Download.NOT_DOWNLOADED } - .distinctBy { it.name } - .sortedByDescending { it.source_order } + fun getUnreadChaptersSorted() = + chapters.filter { !it.read && it.status == Download.NOT_DOWNLOADED }.distinctBy { it.name } + .sortedByDescending { it.source_order } /** * Returns the next unread chapter or null if everything is read. @@ -286,8 +283,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, } fun restartDownloads() { - if (downloadManager.isPaused()) - downloadManager.startDownloads() + if (downloadManager.isPaused()) downloadManager.startDownloads() } /** @@ -302,7 +298,6 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, } controller.updateChapters(this.chapters) - // if (onlyDownloaded()) refreshChapters() } } /** @@ -325,7 +320,6 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, val chapters = async(Dispatchers.IO) { try { source.fetchChapterList(manga).toBlocking().single() - } catch (e: Exception) { chapterError = e emptyList() @@ -354,13 +348,15 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, val finChapters = chapters.await() if (finChapters.isNotEmpty()) { syncChaptersWithSource(db, finChapters, manga, source) - withContext(Dispatchers.IO) { updateChapters() } + withContext(Dispatchers.IO) { updateChapters() } } isLoading = false - if (chapterError == null) - withContext(Dispatchers.Main) { controller.updateChapters(this@MangaDetailsPresenter.chapters) } - if (mangaError != null) - withContext(Dispatchers.Main) { controller.showError(trimException(mangaError!!)) } + if (chapterError == null) withContext(Dispatchers.Main) { controller.updateChapters(this@MangaDetailsPresenter.chapters) } + if (mangaError != null) withContext(Dispatchers.Main) { + controller.showError( + trimException(mangaError!!) + ) + } } } @@ -374,8 +370,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, scope.launch(Dispatchers.IO) { val chapters = try { source.fetchChapterList(manga).toBlocking().single() - } - catch(e: Exception) { + } catch (e: Exception) { withContext(Dispatchers.Main) { controller.showError(trimException(e)) } return@launch } ?: listOf() @@ -385,16 +380,15 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, updateChapters() withContext(Dispatchers.Main) { controller.updateChapters(this@MangaDetailsPresenter.chapters) } - } - catch(e: java.lang.Exception) { + } catch (e: java.lang.Exception) { controller.showError(trimException(e)) } } } private fun trimException(e: java.lang.Exception): String { - return (if (e.message?.contains(": ") == true) - e.message?.split(": ")?.drop(1)?.joinToString(": ") + return (if (e.message?.contains(": ") == true) e.message?.split(": ")?.drop(1) + ?.joinToString(": ") else e.message) ?: preferences.context.getString(R.string.unknown_error) } @@ -461,10 +455,11 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, asyncUpdateMangaAndChapters() } - private fun asyncUpdateMangaAndChapters(justChapters:Boolean = false) { + private fun asyncUpdateMangaAndChapters(justChapters: Boolean = false) { scope.launch { - if (!justChapters) - withContext(Dispatchers.IO) { db.updateFlags(manga).executeAsBlocking() } + if (!justChapters) withContext(Dispatchers.IO) { + db.updateFlags(manga).executeAsBlocking() + } updateChapters() withContext(Dispatchers.Main) { controller.updateChapters(chapters) } } @@ -556,15 +551,14 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, destDir.deleteRecursively() try { val image = saveImage(cover, destDir, manga) - if (image != null) - controller.shareManga(image) + if (image != null) controller.shareManga(image) else controller.shareManga() + } catch (e: java.lang.Exception) { } - catch (e:java.lang.Exception) { } } } - private fun saveImage(cover:Bitmap, directory: File, manga: Manga): File? { + private fun saveImage(cover: Bitmap, directory: File, manga: Manga): File? { directory.mkdirs() // Build destination file. @@ -578,8 +572,14 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, return destFile } - fun updateManga(title:String?, author:String?, artist: String?, uri: Uri?, - description: String?, tags: Array?) { + fun updateManga( + title: String?, + author: String?, + artist: String?, + uri: Uri?, + description: String?, + tags: Array? + ) { if (manga.source == LocalSource.ID) { manga.title = if (title.isNullOrBlank()) manga.url else title.trim() manga.author = author?.trim() @@ -589,15 +589,13 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, manga.genre = if (tags.isNullOrEmpty()) null else tagsString?.trim() LocalSource(downloadManager.context).updateMangaInfo(manga) db.updateMangaInfo(manga).executeAsBlocking() - } - else { + } else { var changed = false val title = title?.trim() if (!title.isNullOrBlank() && manga.originalTitle().isBlank()) { manga.title = title changed = true - } - else if (title.isNullOrBlank() && manga.currentTitle() != manga.originalTitle()) { + } else if (title.isNullOrBlank() && manga.currentTitle() != manga.originalTitle()) { manga.title = manga.originalTitle() changed = true } else if (!title.isNullOrBlank() && title != manga.currentTitle()) { @@ -633,8 +631,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, } var tagsString = tags?.joinToString(", ") - if ((tagsString.isNullOrBlank() && manga.currentGenres() != manga.originalGenres()) - || tagsString == manga.originalGenres()) { + if ((tagsString.isNullOrBlank() && manga.currentGenres() != manga.originalGenres()) || tagsString == manga.originalGenres()) { manga.genre = manga.originalGenres() changed = true } else if (!tagsString.isNullOrBlank() && tagsString != manga.currentGenres()) { @@ -649,8 +646,8 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, } private fun editCoverWithStream(uri: Uri): Boolean { - val inputStream = downloadManager.context.contentResolver.openInputStream(uri) ?: - return false + val inputStream = + downloadManager.context.contentResolver.openInputStream(uri) ?: return false if (manga.source == LocalSource.ID) { LocalSource.updateCover(downloadManager.context, manga, inputStream) return true @@ -665,11 +662,11 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, return false } - fun isTracked(): Boolean = loggedServices.any { service -> tracks.any { it.sync_id == service.id } } + fun isTracked(): Boolean = + loggedServices.any { service -> tracks.any { it.sync_id == service.id } } fun hasTrackers(): Boolean = loggedServices.isNotEmpty() - // Tracking private fun fetchTrackings() { scope.launch { @@ -700,9 +697,7 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, if (trackItem != null) { db.insertTrack(trackItem).executeAsBlocking() trackItem - } - else - item.track + } else item.track } } refreshTracking() @@ -728,19 +723,22 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, item.manga_id = manga.id!! scope.launch { - val binding = try { service.bind(item) } - catch (e: Exception) { + val binding = try { + service.bind(item) + } catch (e: Exception) { trackError(e) null } withContext(Dispatchers.IO) { - if (binding != null) db.insertTrack(binding).executeAsBlocking() } + if (binding != null) db.insertTrack(binding).executeAsBlocking() + } refreshTracking() } } else { scope.launch { - withContext(Dispatchers.IO) { db.deleteTrackForManga(manga, service) - .executeAsBlocking() } + withContext(Dispatchers.IO) { + db.deleteTrackForManga(manga, service).executeAsBlocking() + } refreshTracking() } } @@ -748,16 +746,16 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, private fun updateRemote(track: Track, service: TrackService) { scope.launch { - val binding = try { service.update(track) } - catch (e: Exception) { + val binding = try { + service.update(track) + } catch (e: Exception) { trackError(e) null } if (binding != null) { withContext(Dispatchers.IO) { db.insertTrack(binding).executeAsBlocking() } refreshTracking() - } - else trackRefreshDone() + } else trackRefreshDone() } } @@ -786,4 +784,4 @@ class MangaDetailsPresenter(private val controller: MangaDetailsController, track.last_chapter_read = chapterNumber updateRemote(track, item.service) } -} \ No newline at end of file +} 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 da47fa5ff9..9247154c99 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 @@ -23,14 +23,14 @@ import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.updateLayoutParams import eu.kanade.tachiyomi.util.view.visible import eu.kanade.tachiyomi.util.view.visibleIf -import kotlinx.android.synthetic.main.manga_header_item.* import java.util.Locale +import kotlinx.android.synthetic.main.manga_header_item.* class MangaHeaderHolder( private val view: View, private val adapter: ChaptersAdapter, startExpanded: Boolean -) : BaseFlexibleViewHolder(view, adapter) { +) : BaseFlexibleViewHolder(view, adapter) { init { start_reading_button.setOnClickListener { adapter.coverListener.readNextChapter() } @@ -103,11 +103,10 @@ class MangaHeaderHolder( .no_description) manga_summary.post { - if ((manga_summary.lineCount < 3 && manga.currentGenres().isNullOrBlank()) - || less_button.visibility == View.VISIBLE) { + if ((manga_summary.lineCount < 3 && manga.currentGenres().isNullOrBlank()) || + less_button.visibility == View.VISIBLE) { more_button_group.gone() - } - else + } else more_button_group.visible() } manga_summary_label.text = itemView.context.getString(R.string.about_this, @@ -137,8 +136,8 @@ class MangaHeaderHolder( ) checked(!item.isLocked && manga.favorite) } - true_backdrop.setBackgroundColor(adapter.coverListener.coverColor() ?: - itemView.context.getResourceColor(android.R.attr.colorBackground)) + true_backdrop.setBackgroundColor(adapter.coverListener.coverColor() + ?: itemView.context.getResourceColor(android.R.attr.colorBackground)) val tracked = presenter.isTracked() && !item.isLocked @@ -169,8 +168,7 @@ class MangaHeaderHolder( else R.string.start_reading ) } - } - else { + } else { text = resources.getString(R.string.start_reading) } } @@ -182,7 +180,7 @@ class MangaHeaderHolder( height = adapter.coverListener.topCoverHeight() } - manga_status.text = (itemView.context.getString( when (manga.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 @@ -253,4 +251,4 @@ class MangaHeaderHolder( super.onLongClick(view) return false } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderItem.kt index 50a66082d9..083c5b51ce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaHeaderItem.kt @@ -9,8 +9,8 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.manga.chapter.ChaptersAdapter -class MangaHeaderItem(val manga: Manga, private val startExpanded: Boolean): - AbstractFlexibleItem(){ +class MangaHeaderItem(val manga: Manga, private val startExpanded: Boolean) : + AbstractFlexibleItem() { var isLocked = false @@ -26,10 +26,12 @@ class MangaHeaderItem(val manga: Manga, private val startExpanded: Boolean): return MangaHeaderHolder(view, adapter as ChaptersAdapter, startExpanded) } - override fun bindViewHolder(adapter: FlexibleAdapter>, + override fun bindViewHolder( + adapter: FlexibleAdapter>, holder: MangaHeaderHolder, position: Int, - payloads: MutableList?) { + payloads: MutableList? + ) { holder.bind(this, manga) } @@ -40,5 +42,4 @@ class MangaHeaderItem(val manga: Manga, private val startExpanded: Boolean): override fun hashCode(): Int { return manga.id!!.hashCode() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/TrackingBottomSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/TrackingBottomSheet.kt index 6a13f11870..7c18f56195 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/TrackingBottomSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/TrackingBottomSheet.kt @@ -62,7 +62,6 @@ class TrackingBottomSheet(private val controller: MangaDetailsController) : Bott } } }) - } override fun onStart() { @@ -164,7 +163,7 @@ class TrackingBottomSheet(private val controller: MangaDetailsController) : Bott fun refreshTrack(item: TrackService?) { val index = adapter?.indexOf(item) ?: -1 - if (index > -1 ){ + if (index > -1) { (track_recycler.findViewHolderForAdapterPosition(index) as? TrackHolder) ?.setProgress(true) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterItem.kt index d16d7efa77..863b4be078 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterItem.kt @@ -45,10 +45,12 @@ class ChapterItem(val chapter: Chapter, val manga: Manga) : return ChapterMatHolder(view, adapter as ChaptersAdapter) } - override fun bindViewHolder(adapter: FlexibleAdapter>, - holder: ChapterMatHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: ChapterMatHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this, manga) } @@ -63,5 +65,4 @@ class ChapterItem(val chapter: Chapter, val manga: Manga) : override fun hashCode(): Int { return chapter.id!!.hashCode() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterMatHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterMatHolder.kt index 3ac3dbd09e..d32c2f301d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterMatHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChapterMatHolder.kt @@ -10,14 +10,14 @@ import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visibleIf +import java.util.Date import kotlinx.android.synthetic.main.chapters_mat_item.* import kotlinx.android.synthetic.main.download_button.* -import java.util.Date class ChapterMatHolder( private val view: View, private val adapter: ChaptersAdapter -) : BaseFlexibleViewHolder(view, adapter) { +) : BaseFlexibleViewHolder(view, adapter) { private var localSource = false init { @@ -73,7 +73,6 @@ class ChapterMatHolder( if (isLocked) download_button.gone() - // Set correct text color chapter_title.setTextColor(if (chapter.read && !isLocked) adapter.readColor else adapter.unreadColor) @@ -89,8 +88,7 @@ class ChapterMatHolder( if (!chapter.read && chapter.last_page_read > 0 && chapter.pages_left > 0 && !isLocked) { statuses.add(itemView.resources.getQuantityString(R.plurals.pages_left, chapter .pages_left, chapter.pages_left)) - } - else if (!chapter.read && chapter.last_page_read > 0 && !isLocked) { + } else if (!chapter.read && chapter.last_page_read > 0 && !isLocked) { statuses.add(itemView.context.getString(R.string.chapter_progress, chapter .last_page_read + 1)) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt index c6168821f2..04049ca204 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt @@ -11,13 +11,13 @@ import eu.kanade.tachiyomi.ui.manga.MangaDetailsController import eu.kanade.tachiyomi.ui.manga.MangaDetailsPresenter import eu.kanade.tachiyomi.ui.security.SecureActivityDelegate import eu.kanade.tachiyomi.util.system.getResourceColor -import uy.kohesive.injekt.injectLazy import java.text.DecimalFormat import java.text.DecimalFormatSymbols +import uy.kohesive.injekt.injectLazy class ChaptersAdapter( - val controller: MangaDetailsController, - context: Context + val controller: MangaDetailsController, + context: Context ) : FlexibleAdapter>(null, controller, true) { val preferences: PreferencesHelper by injectLazy() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/EditMangaDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/EditMangaDialog.kt index bd43f6ce0c..63db8af64a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/EditMangaDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/EditMangaDialog.kt @@ -20,11 +20,11 @@ import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.manga.MangaDetailsController import eu.kanade.tachiyomi.util.lang.chop import eu.kanade.tachiyomi.util.system.toast +import java.io.IOException import kotlinx.android.synthetic.main.edit_manga_dialog.view.* import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.IOException class EditMangaDialog : DialogController { @@ -32,7 +32,7 @@ class EditMangaDialog : DialogController { private val manga: Manga - private var customCoverUri:Uri? = null + private var customCoverUri: Uri? = null private val infoController get() = targetController as MangaDetailsController @@ -84,8 +84,7 @@ class EditMangaDialog : DialogController { view.manga_artist.append(manga.artist ?: "") view.manga_description.append(manga.description ?: "") view.manga_genres_tags.setTags(manga.genre?.split(", ") ?: emptyList()) - } - else { + } else { if (manga.currentTitle() != manga.originalTitle()) view.manga_full_title.append(manga.currentTitle()) view.manga_full_title.hint = "${resources?.getString(R.string.title)}: ${manga @@ -158,7 +157,6 @@ class EditMangaDialog : DialogController { } } - override fun onDestroyView(view: View) { super.onDestroyView(view) dialogView = null @@ -174,5 +172,4 @@ class EditMangaDialog : DialogController { private companion object { const val KEY_MANGA = "manga_id" } - } 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 5f59acea52..b8571ef561 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 @@ -17,7 +17,7 @@ class SetTrackChaptersDialog : DialogController where T : SetTrackChaptersDialog.Listener { private val item: TrackItem - private lateinit var listener: Listener + private lateinit var listener: Listener constructor(target: T, item: TrackItem) : super(Bundle().apply { putSerializable(KEY_ITEM_TRACK, item.track) @@ -55,7 +55,6 @@ class SetTrackChaptersDialog : DialogController // Don't allow to go from 0 to 9999 np.wrapSelectorWheel = false - return dialog } @@ -66,5 +65,4 @@ class SetTrackChaptersDialog : DialogController private companion object { const val KEY_ITEM_TRACK = "SetTrackChaptersDialog.item.track" } - -} \ No newline at end of file +} 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 b85280289f..ed67018864 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 @@ -6,7 +6,6 @@ import android.widget.NumberPicker import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.customview.getCustomView -import com.bluelinelabs.conductor.Controller import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager @@ -14,8 +13,7 @@ import eu.kanade.tachiyomi.ui.base.controller.DialogController import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -class SetTrackScoreDialog : DialogController - where T : SetTrackScoreDialog.Listener { +class SetTrackScoreDialog : DialogController where T : SetTrackScoreDialog.Listener { private val item: TrackItem private lateinit var listener: Listener @@ -37,20 +35,17 @@ class SetTrackScoreDialog : DialogController override fun onCreateDialog(savedViewState: Bundle?): Dialog { val item = item - val dialog = MaterialDialog(activity!!) - .title(R.string.score) + val dialog = MaterialDialog(activity!!).title(R.string.score) .customView(R.layout.track_score_dialog, scrollable = false) - .negativeButton(android.R.string.cancel) - .positiveButton(android.R.string.ok) { dialog -> + .negativeButton(android.R.string.cancel).positiveButton(android.R.string.ok) { dialog -> val view = dialog.getCustomView() // Remove focus to update selected number val np: NumberPicker = view.findViewById(R.id.score_picker) np.clearFocus() - listener.setScore(item, np.value) + listener.setScore(item, np.value) } - val view = dialog.getCustomView() val np: NumberPicker = view.findViewById(R.id.score_picker) val scores = item.service.getScoreList().toTypedArray() @@ -74,5 +69,4 @@ class SetTrackScoreDialog : DialogController private companion object { const val KEY_ITEM_TRACK = "SetTrackScoreDialog.item.track" } - -} \ No newline at end of file +} 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 7047b8f39c..dc621058b6 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 @@ -21,7 +21,6 @@ class SetTrackStatusDialog : DialogController putSerializable(KEY_ITEM_TRACK, item.track) }) { listener = target - // targetController = target this.item = item } @@ -42,8 +41,7 @@ class SetTrackStatusDialog : DialogController .title(R.string.status) .negativeButton(android.R.string.cancel) .listItemsSingleChoice(items = statusString, initialSelection = selectedIndex, - waitForPositiveButton = false) - { dialog, position, _ -> + waitForPositiveButton = false) { dialog, position, _ -> listener.setStatus(item, position) dialog.dismiss() } @@ -56,5 +54,4 @@ class SetTrackStatusDialog : DialogController private companion object { const val KEY_ITEM_TRACK = "SetTrackStatusDialog.item.track" } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackAdapter.kt index 9d8599e516..f4c6d54ff1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackAdapter.kt @@ -35,7 +35,7 @@ class TrackAdapter(controller: OnClickListener) : RecyclerView.Adapter(context, R.layout.track_search_item, ArrayList()) { +class TrackSearchAdapter(context: Context) : + ArrayAdapter(context, R.layout.track_search_item, ArrayList()) { override fun getView(position: Int, view: View?, parent: ViewGroup): View { var v = view 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 2cb775a555..ec72867acd 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 @@ -18,13 +18,13 @@ import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.manga.MangaDetailsPresenter import eu.kanade.tachiyomi.ui.manga.TrackingBottomSheet import eu.kanade.tachiyomi.util.lang.plusAssign +import java.util.concurrent.TimeUnit import kotlinx.android.synthetic.main.track_search_dialog.view.* import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.concurrent.TimeUnit class TrackSearchDialog : DialogController { @@ -41,15 +41,11 @@ class TrackSearchDialog : DialogController { private var searchTextSubscription: Subscription? = null private lateinit var bottomSheet: TrackingBottomSheet - //private val trackController - // get() = targetController as TrackController + private var wasPreviouslyTracked: Boolean = false + private lateinit var presenter: MangaDetailsPresenter - - private var wasPreviouslyTracked:Boolean = false - private lateinit var presenter:MangaDetailsPresenter - - constructor(target: TrackingBottomSheet, service: TrackService, wasTracked:Boolean) : super(Bundle() + constructor(target: TrackingBottomSheet, service: TrackService, wasTracked: Boolean) : super(Bundle() .apply { putInt(KEY_SERVICE, service.id) }) { @@ -70,7 +66,7 @@ class TrackSearchDialog : DialogController { negativeButton(android.R.string.cancel) positiveButton( if (wasPreviouslyTracked) R.string.action_clear - else R.string.action_track){ onPositiveButtonClick() } + else R.string.action_track) { onPositiveButtonClick() } setActionButtonEnabled(WhichButton.POSITIVE, wasPreviouslyTracked) } @@ -157,7 +153,6 @@ class TrackSearchDialog : DialogController { } private fun onPositiveButtonClick() { - // trackController.swipe_refresh.isRefreshing = true bottomSheet.refreshTrack(service) presenter.registerTracking(selectedItem, service) @@ -166,5 +161,4 @@ class TrackSearchDialog : DialogController { private companion object { const val KEY_SERVICE = "service_id" } - } 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 0fb2c24f8a..a2860c2e58 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 @@ -14,4 +14,4 @@ class MangaAdapter(controller: MigrationController) : super.updateDataSet(items) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaHolder.kt index bd84561c2e..48539b1015 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaHolder.kt @@ -1,17 +1,17 @@ package eu.kanade.tachiyomi.ui.migration import android.view.View +import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.load.engine.DiskCacheStrategy import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.data.glide.GlideApp import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import kotlinx.android.synthetic.main.catalogue_list_item.* -import androidx.recyclerview.widget.RecyclerView -import eu.davidea.flexibleadapter.items.IFlexible class MangaHolder( - private val view: View, - private val adapter: FlexibleAdapter> + private val view: View, + private val adapter: FlexibleAdapter> ) : BaseFlexibleViewHolder(view, adapter) { fun bind(item: MangaItem) { @@ -27,5 +27,4 @@ class MangaHolder( .dontAnimate() .into(cover_thumbnail) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaItem.kt index 824a05fd8e..76636b7d8e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MangaItem.kt @@ -18,10 +18,12 @@ class MangaItem(val manga: Manga) : AbstractFlexibleItem() { return MangaHolder(view, adapter) } - override fun bindViewHolder(adapter: FlexibleAdapter>, - holder: MangaHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: MangaHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this) } 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 2ee0fed2f5..e3cfd09881 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 @@ -48,7 +48,7 @@ class MigrationController : NucleusController(), return inflater.inflate(R.layout.migration_controller, container, false) } - fun searchController(manga:Manga): SearchController { + fun searchController(manga: Manga): SearchController { val controller = SearchController(manga) controller.targetController = this diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationFlags.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationFlags.kt index 8843e4ce4a..adc20377b7 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationFlags.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationFlags.kt @@ -4,13 +4,13 @@ import eu.kanade.tachiyomi.R object MigrationFlags { - const val CHAPTERS = 0b001 + const val CHAPTERS = 0b001 const val CATEGORIES = 0b010 - const val TRACK = 0b100 + const val TRACK = 0b100 - private const val CHAPTERS2 = 0x1 + private const val CHAPTERS2 = 0x1 private const val CATEGORIES2 = 0x2 - private const val TRACK2 = 0x4 + private const val TRACK2 = 0x4 val titles get() = arrayOf(R.string.chapters, R.string.categories, R.string.tracking) 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 60f72ac836..e84c57800f 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 @@ -36,4 +36,4 @@ class MigrationMangaDialog(bundle: Bundle? = null) : DialogController(bundle) negativeButton(android.R.string.no) } } -} \ No newline at end of file +} 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 8d7b2cab1a..0c7e94fc63 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 @@ -21,9 +21,9 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class MigrationPresenter( - private val sourceManager: SourceManager = Injekt.get(), - private val db: DatabaseHelper = Injekt.get(), - private val preferences: PreferencesHelper = Injekt.get() + private val sourceManager: SourceManager = Injekt.get(), + private val db: DatabaseHelper = Injekt.get(), + private val preferences: PreferencesHelper = Injekt.get() ) : BasePresenter() { var state = ViewState() @@ -37,27 +37,19 @@ class MigrationPresenter( override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) - db.getFavoriteMangas() - .asRxObservable() - .observeOn(AndroidSchedulers.mainThread()) - .doOnNext { state = state.copy(sourcesWithManga = findSourcesWithManga(it)) } - .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()) - .doOnNext { state = state.copy(mangaForSource = it) } - .subscribe() + db.getFavoriteMangas().asRxObservable().observeOn(AndroidSchedulers.mainThread()) + .doOnNext { state = state.copy(sourcesWithManga = findSourcesWithManga(it)) } + .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()) + .doOnNext { state = state.copy(mangaForSource = it) }.subscribe() stateRelay - // Render the view when any field other than isReplacingManga changes - .distinctUntilChanged { t1, t2 -> t1.isReplacingManga != t2.isReplacingManga } - .subscribeLatestCache(MigrationController::render) - - /* stateRelay.distinctUntilChanged { state -> state.isReplacingManga } - .subscribeLatestCache(MigrationController::renderIsReplacingManga)*/ + // Render the view when any field other than isReplacingManga changes + .distinctUntilChanged { t1, t2 -> t1.isReplacingManga != t2.isReplacingManga } + .subscribeLatestCache(MigrationController::render) } fun setSelectedSource(source: Source) { @@ -71,8 +63,8 @@ class MigrationPresenter( private fun findSourcesWithManga(library: List): List { val header = SelectionHeader() return library.map { it.source }.toSet() - .mapNotNull { if (it != LocalSource.ID) sourceManager.getOrStub(it) else null } - .map { SourceItem(it, header) } + .mapNotNull { if (it != LocalSource.ID) sourceManager.getOrStub(it) else null } + .map { SourceItem(it, header) } } private fun libraryToMigrationItem(library: List, sourceId: Long): List { @@ -84,18 +76,20 @@ class MigrationPresenter( state = state.copy(isReplacingManga = true) - Observable.defer { source.fetchChapterList(manga) } - .onErrorReturn { emptyList() } - .doOnNext { migrateMangaInternal(source, it, prevManga, manga, replace) } - .onErrorReturn { emptyList() } - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnUnsubscribe { state = state.copy(isReplacingManga = false) } - .subscribe() + Observable.defer { source.fetchChapterList(manga) }.onErrorReturn { emptyList() } + .doOnNext { migrateMangaInternal(source, it, prevManga, manga, replace) } + .onErrorReturn { emptyList() }.subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnUnsubscribe { state = state.copy(isReplacingManga = false) }.subscribe() } - private fun migrateMangaInternal(source: Source, sourceChapters: List, - prevManga: Manga, manga: Manga, replace: Boolean) { + private fun migrateMangaInternal( + source: Source, + sourceChapters: List, + prevManga: Manga, + manga: Manga, + replace: Boolean + ) { val flags = preferences.migrateFlags().getOrDefault() val migrateChapters = MigrationFlags.hasChapters(flags) @@ -112,8 +106,8 @@ class MigrationPresenter( } val prevMangaChapters = db.getChapters(prevManga).executeAsBlocking() - val maxChapterRead = prevMangaChapters.filter { it.read } - .maxBy { it.chapter_number }?.chapter_number + val maxChapterRead = + prevMangaChapters.filter { it.read }.maxBy { it.chapter_number }?.chapter_number if (maxChapterRead != null) { val dbChapters = db.getChapters(manga).executeAsBlocking() for (chapter in dbChapters) { 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 2119503112..f96cdd3195 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 @@ -23,8 +23,8 @@ import eu.kanade.tachiyomi.ui.migration.manga.process.MigrationListController import uy.kohesive.injekt.injectLazy class SearchController( - private var manga: Manga? = null -) : CatalogueSearchController(manga?.originalTitle()), BottomNavBarInterface{ + private var manga: Manga? = null +) : CatalogueSearchController(manga?.originalTitle()), BottomNavBarInterface { private var newManga: Manga? = null private var progress = 1 @@ -37,12 +37,10 @@ class SearchController( setHasOptionsMenu(true) } - override fun getTitle(): String? { if (totalProgress > 1) { return "($progress/$totalProgress) ${super.getTitle()}" - } - else + } else return super.getTitle() } @@ -101,7 +99,7 @@ class SearchController( private fun replaceWithNewSearchController(manga: Manga?) { if (manga != null) { - //router.popCurrentController() + // router.popCurrentController() val searchController = SearchController(manga) searchController.targetController = targetController searchController.progress = progress + 1 @@ -143,7 +141,7 @@ class SearchController( .message(R.string.migration_dialog_what_to_include) .listItemsMultiChoice(items = MigrationFlags.titles.map { resources?.getString(it) as CharSequence }, - initialSelection = preselected.toIntArray()) { _, positions, _ -> + initialSelection = preselected.toIntArray()) { _, positions, _ -> val newValue = MigrationFlags.getFlagsFromPositions(positions.toTypedArray()) preferences.migrateFlags().set(newValue) } @@ -154,7 +152,6 @@ class SearchController( (targetController as? SearchController)?.copyManga() } } - } /** 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 941e99c2e8..78177dd944 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 @@ -2,14 +2,13 @@ package eu.kanade.tachiyomi.ui.migration import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.source.CatalogueSource -import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchCardItem import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchItem import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchPresenter class SearchPresenter( - initialQuery: String? = "", - private val manga: Manga + initialQuery: String? = "", + private val manga: Manga ) : CatalogueSearchPresenter(initialQuery) { override fun getEnabledSources(): List { @@ -19,7 +18,7 @@ class SearchPresenter( } override fun createCatalogueSearchItem(source: CatalogueSource, results: List?): CatalogueSearchItem { - //Set the catalogue search item as highlighted if the source matches that of the selected manga + // Set the catalogue search item as highlighted if the source matches that of the selected manga return CatalogueSearchItem(source, results, source.id == manga.source) } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SelectionHeader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SelectionHeader.kt index d88f7bdf66..36418730fa 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SelectionHeader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/SelectionHeader.kt @@ -31,8 +31,12 @@ class SelectionHeader : AbstractHeaderItem() { /** * Binds this item to the given view holder. */ - override fun bindViewHolder(adapter: FlexibleAdapter>, holder: Holder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: Holder, + position: Int, + payloads: MutableList? + ) { // Intentionally empty } 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 959381f0cc..f6c7571433 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 @@ -39,7 +39,7 @@ class SourceHolder(view: View, override val adapter: SourceAdapter) : // Set circle letter image. itemView.post { - edit_button.setImageDrawable(edit_button.getRound(source.name.take(1).toUpperCase(),false)) + edit_button.setImageDrawable(edit_button.getRound(source.name.take(1).toUpperCase(), false)) } } } 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 4d0b9f383b..6668d252dd 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 @@ -34,10 +34,13 @@ data class SourceItem(val source: Source, val header: SelectionHeader? = null) : /** * Binds this item to the given view holder. */ - override fun bindViewHolder(adapter: FlexibleAdapter>, holder: SourceHolder, - position: Int, payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: SourceHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/ViewState.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/ViewState.kt index 7caa5e9ecc..0481ed6037 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/ViewState.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/ViewState.kt @@ -3,8 +3,8 @@ package eu.kanade.tachiyomi.ui.migration import eu.kanade.tachiyomi.source.Source data class ViewState( - val selectedSource: Source? = null, - val mangaForSource: List = emptyList(), - val sourcesWithManga: List = emptyList(), - val isReplacingManga: Boolean = false -) \ No newline at end of file + val selectedSource: Source? = null, + val mangaForSource: List = emptyList(), + val sourcesWithManga: List = emptyList(), + val isReplacingManga: Boolean = false +) 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 d6ad69e583..ae0dd02cae 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 @@ -4,7 +4,6 @@ import android.app.Activity import android.content.res.Configuration import android.os.Build import android.os.Bundle -import android.view.ViewGroup import android.view.WindowManager import android.widget.CompoundButton import android.widget.LinearLayout @@ -28,19 +27,18 @@ import eu.kanade.tachiyomi.util.view.visible import kotlinx.android.synthetic.main.migration_bottom_sheet.* import uy.kohesive.injekt.injectLazy -class MigrationBottomSheetDialog(activity: Activity, private val listener: -StartMigrationListener) : - BottomSheetDialog(activity, R.style.BottomSheetDialogTheme) { +class MigrationBottomSheetDialog( + activity: Activity, + private val listener: StartMigrationListener +) : BottomSheetDialog(activity, R.style.BottomSheetDialogTheme) { + /** * Preferences helper. */ private val preferences by injectLazy() init { - // Use activity theme for this layout val view = activity.layoutInflater.inflate(R.layout.migration_bottom_sheet, null) - //val scroll = NestedScrollView(context) - // scroll.addView(view) setContentView(view) if (activity.resources.configuration?.orientation == Configuration.ORIENTATION_LANDSCAPE) { @@ -57,21 +55,19 @@ StartMigrationListener) : } skip_step.layoutParams = params - val params2 = extra_search_param_text.layoutParams as ConstraintLayout.LayoutParams params2.bottomToBottom = options_layout.id extra_search_param_text.layoutParams = params2 - val params3 = extra_search_param.layoutParams as ConstraintLayout.LayoutParams params3.endToEnd = -1 extra_search_param.layoutParams = params3 - } setEdgeToEdge(activity, constraint_layout, view, false) setBottomEdge( if (activity.resources.configuration?.orientation == Configuration.ORIENTATION_LANDSCAPE) extra_search_param_text - else skip_step, activity) + else skip_step, activity + ) } /** @@ -86,12 +82,11 @@ StartMigrationListener) : window?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) } - fab.setOnClickListener { preferences.skipPreMigration().set(skip_step.isChecked) listener.startMigration( - if (extra_search_param.isChecked && extra_search_param_text.text.isNotBlank()) - extra_search_param_text.text.toString() else null) + if (extra_search_param.isChecked && extra_search_param_text.text.isNotBlank()) extra_search_param_text.text.toString() else null + ) dismiss() } } @@ -122,17 +117,17 @@ StartMigrationListener) : skip_step.isChecked = preferences.skipPreMigration().getOrDefault() skip_step.setOnCheckedChangeListener { _, isChecked -> - if (isChecked) - (listener as? Controller)?.activity?.toast(R.string.pre_migration_skip_toast, - Toast.LENGTH_LONG) + if (isChecked) (listener as? Controller)?.activity?.toast( + R.string.pre_migration_skip_toast, Toast.LENGTH_LONG + ) } } private fun setFlags() { var flags = 0 - if(mig_chapters.isChecked) flags = flags or MigrationFlags.CHAPTERS - if(mig_categories.isChecked) flags = flags or MigrationFlags.CATEGORIES - if(mig_tracking.isChecked) flags = flags or MigrationFlags.TRACK + if (mig_chapters.isChecked) flags = flags or MigrationFlags.CHAPTERS + if (mig_categories.isChecked) flags = flags or MigrationFlags.CATEGORIES + if (mig_tracking.isChecked) flags = flags or MigrationFlags.TRACK preferences.migrateFlags().set(flags) } @@ -156,11 +151,8 @@ StartMigrationListener) : } private fun Boolean.toInt() = if (this) 1 else 0 - - - } interface StartMigrationListener { - fun startMigration(extraParam:String?) -} \ No newline at end of file + fun startMigration(extraParam: String?) +} 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 f35b3a5db3..7056d18da2 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 @@ -5,9 +5,10 @@ import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.source.SourceManager import uy.kohesive.injekt.injectLazy -class MigrationSourceAdapter(var items: List, - val controllerPre: PreMigrationController -): FlexibleAdapter( +class MigrationSourceAdapter( + var items: List, + val controllerPre: PreMigrationController +) : FlexibleAdapter( items, controllerPre, true @@ -21,7 +22,7 @@ class MigrationSourceAdapter(var items: List, } override fun onRestoreInstanceState(savedInstanceState: Bundle) { - val sourceManager:SourceManager by injectLazy() + val sourceManager: SourceManager by injectLazy() savedInstanceState.getParcelableArrayList( SELECTED_SOURCES_KEY )?.let { @@ -38,4 +39,4 @@ class MigrationSourceAdapter(var items: List, companion object { private const val SELECTED_SOURCES_KEY = "selected_sources" } -} \ No newline at end of file +} 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 687eb41687..7e075e62f7 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 @@ -10,7 +10,7 @@ import eu.kanade.tachiyomi.util.view.getRound import kotlinx.android.synthetic.main.migration_source_item.* import uy.kohesive.injekt.injectLazy -class MigrationSourceHolder(view: View, val adapter: MigrationSourceAdapter): +class MigrationSourceHolder(view: View, val adapter: MigrationSourceAdapter) : BaseFlexibleViewHolder(view, adapter) { init { setDragHandleView(reorder) @@ -24,10 +24,10 @@ class MigrationSourceHolder(view: View, val adapter: MigrationSourceAdapter): title.text = sourceName // Update circle letter image. itemView.post { - edit_button.setImageDrawable(edit_button.getRound(source.name.take(1).toUpperCase(),false)) + edit_button.setImageDrawable(edit_button.getRound(source.name.take(1).toUpperCase(), false)) } - if(sourceEnabled) { + if (sourceEnabled) { title.alpha = 1.0f edit_button.alpha = 1.0f title.paintFlags = title.paintFlags and STRIKE_THRU_TEXT_FLAG.inv() @@ -51,4 +51,4 @@ class MigrationSourceHolder(view: View, val adapter: MigrationSourceAdapter): companion object { private const val DISABLED_ALPHA = 0.3f } -} \ No newline at end of file +} 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 c01b40890e..de66151e41 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 @@ -11,7 +11,7 @@ import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.android.parcel.Parcelize -class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean): AbstractFlexibleItem() { +class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean) : AbstractFlexibleItem() { override fun getLayoutRes() = R.layout.migration_source_item override fun createViewHolder(view: View, adapter: FlexibleAdapter>): MigrationSourceHolder { @@ -26,10 +26,12 @@ class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean): A * @param position The position of this item in the adapter. * @param payloads List of partial changes. */ - override fun bindViewHolder(adapter: FlexibleAdapter>, - holder: MigrationSourceHolder, - position: Int, - payloads: List?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: MigrationSourceHolder, + position: Int, + payloads: List? + ) { holder.bind(source, sourceEnabled) } @@ -53,7 +55,7 @@ class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean): A } @Parcelize - data class ParcelableSI(val sourceId: Long, val sourceEnabled: Boolean): Parcelable + data class ParcelableSI(val sourceId: Long, val sourceEnabled: Boolean) : Parcelable fun asParcelable(): ParcelableSI { return ParcelableSI(source.id, sourceEnabled) @@ -69,4 +71,4 @@ class MigrationSourceItem(val source: HttpSource, var sourceEnabled: Boolean): A ) } } -} \ No newline at end of file +} 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 03743ad1f2..3ae96ce00a 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 @@ -37,7 +37,7 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F private var showingOptions = false - private var dialog:BottomSheetDialog? = null + private var dialog: BottomSheetDialog? = null override fun getTitle() = "Select target sources" @@ -63,7 +63,7 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F val fabBaseMarginBottom = fab?.marginBottom ?: 0 recycler.doOnApplyWindowInsets { v, insets, padding -> - fab?.updateLayoutParams { + fab?.updateLayoutParams { bottomMargin = fabBaseMarginBottom + insets.systemWindowInsetBottom } // offset the recycler by the fab's inset + some inset on top @@ -73,7 +73,7 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F fab.setOnClickListener { if (dialog?.isShowing != true) { - dialog = MigrationBottomSheetDialog(activity!!, this) + dialog = MigrationBottomSheetDialog(activity!!, this) dialog?.show() val bottomSheet = dialog?.findViewById( com.google.android.material.R.id.design_bottom_sheet @@ -87,7 +87,7 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F } } - override fun startMigration(extraParam:String?) { + override fun startMigration(extraParam: String?) { val listOfSources = adapter?.items?.filter { it.sourceEnabled }?.joinToString("/") { it.source.id.toString() } @@ -113,7 +113,6 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F adapter?.onRestoreInstanceState(savedInstanceState) } - override fun onItemClick(view: View, position: Int): Boolean { adapter?.getItem(position)?.let { it.sourceEnabled = !it.sourceEnabled @@ -136,14 +135,14 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F .sortedBy { "(${it.lang}) ${it.name}" } sources = sources.filter { isEnabled(it.id.toString()) }.sortedBy { sourcesSaved.indexOf(it.id - .toString() ) + .toString()) } + sources.filterNot { isEnabled(it.id.toString()) } return sources } - fun isEnabled(id:String): Boolean { + fun isEnabled(id: String): Boolean { val sourcesSaved = prefs.migrationSources().getOrDefault() val hiddenCatalogues = prefs.hiddenCatalogues().getOrDefault() return if (sourcesSaved.isEmpty()) id !in hiddenCatalogues @@ -159,4 +158,4 @@ class PreMigrationController(bundle: Bundle? = null) : BaseController(bundle), F }) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigratingManga.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigratingManga.kt index a78823639d..519b0e4b71 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigratingManga.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigratingManga.kt @@ -5,15 +5,17 @@ import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.util.view.DeferredField +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.ConflatedBroadcastChannel -import kotlin.coroutines.CoroutineContext -class MigratingManga(private val db: DatabaseHelper, - private val sourceManager: SourceManager, - val mangaId: Long, - parentContext: CoroutineContext) { +class MigratingManga( + private val db: DatabaseHelper, + private val sourceManager: SourceManager, + val mangaId: Long, + parentContext: CoroutineContext +) { val searchResult = DeferredField() // @@ -21,12 +23,12 @@ class MigratingManga(private val db: DatabaseHelper, val migrationJob = parentContext + SupervisorJob() + Dispatchers.Default - var migrationStatus:Int = MigrationStatus.RUNNUNG + var migrationStatus: Int = MigrationStatus.RUNNUNG @Volatile private var manga: Manga? = null suspend fun manga(): Manga? { - if(manga == null) manga = db.getManga(mangaId).executeAsBlocking() + if (manga == null) manga = db.getManga(mangaId).executeAsBlocking() return manga } @@ -46,4 +48,4 @@ class MigrationStatus { val MANGA_FOUND = 1 val MANGA_NOT_FOUND = 2 } -} \ No newline at end of file +} 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 ce07638781..2eca42a464 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 @@ -36,6 +36,8 @@ import eu.kanade.tachiyomi.util.system.launchUI import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.util.view.RecyclerWindowInsetsListener import eu.kanade.tachiyomi.util.view.applyWindowInsetsForController +import java.util.concurrent.atomic.AtomicInteger +import kotlin.coroutines.CoroutineContext import kotlinx.android.synthetic.main.chapters_controller.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -50,12 +52,9 @@ import kotlinx.coroutines.withContext import rx.schedulers.Schedulers import timber.log.Timber 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 { + MigrationProcessAdapter.MigrationProcessInterface, BottomNavBarInterface, CoroutineScope { init { setHasOptionsMenu(true) @@ -76,7 +75,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), var migrationsJob: Job? = null private set private var migratingManga: MutableList? = null - private var selectedPosition:Int? = null + private var selectedPosition: Int? = null private var manaulMigrations = 0 override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { @@ -84,8 +83,9 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), } override fun getTitle(): String? { - return resources?.getString(R.string.migration) + " (${adapter?.items?.count { it.manga - .migrationStatus != MigrationStatus.RUNNUNG }}/${adapter?.itemCount ?: 0})" + return resources?.getString(R.string.migration) + " (${adapter?.items?.count { + it.manga.migrationStatus != MigrationStatus.RUNNUNG + }}/${adapter?.itemCount ?: 0})" } override fun onViewCreated(view: View) { @@ -110,23 +110,24 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), recycler.setHasFixedSize(true) recycler.setOnApplyWindowInsetsListener(RecyclerWindowInsetsListener) - adapter?.updateDataSet(newMigratingManga.map { it.toModal() } ) + adapter?.updateDataSet(newMigratingManga.map { it.toModal() }) - if(migrationsJob == null) { + if (migrationsJob == null) { migrationsJob = launch { runMigrations(newMigratingManga) } } } - suspend fun runMigrations(mangas: List) { + private suspend fun runMigrations(mangas: List) { val useSourceWithMost = preferences.useSourceWithMost().getOrDefault() val sources = preferences.migrationSources().getOrDefault().split("/").mapNotNull { val value = it.toLongOrNull() ?: return - sourceManager.get(value) as? CatalogueSource } + sourceManager.get(value) as? CatalogueSource + } if (config == null) return - for(manga in mangas) { + for (manga in mangas) { if (migrationsJob?.isCancelled == true) { break } @@ -134,10 +135,10 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), if (manga.mangaId !in config.mangaIds) { continue } - if(!manga.searchResult.initialized && manga.migrationJob.isActive) { + if (!manga.searchResult.initialized && manga.migrationJob.isActive) { val mangaObj = manga.manga() - if(mangaObj == null) { + if (mangaObj == null) { manga.searchResult.initialize(null) continue } @@ -149,7 +150,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), val validSources = sources.filter { it.id != mangaSource.id } - if(useSourceWithMost) { + if (useSourceWithMost) { val sourceSemaphore = Semaphore(3) val processedSources = AtomicInteger() @@ -157,20 +158,33 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), async { sourceSemaphore.withPermit { try { - /* val searchResult = if (useSmartSearch) { - smartSearchEngine.smartSearch(source, mangaObj.title) - } else {*/ - val searchResult = smartSearchEngine - .normalSearch(source, mangaObj.originalTitle()) + /* val searchResult = if (useSmartSearch) { + smartSearchEngine.smartSearch(source, mangaObj.title) + } else {*/ + val searchResult = smartSearchEngine.normalSearch( + source, + mangaObj.originalTitle() + ) - if(searchResult != null) { - val localManga = smartSearchEngine.networkToLocalManga(searchResult, source.id) - val chapters = source.fetchChapterList(localManga).toSingle().await( - Schedulers.io()) + if (searchResult != null) { + val localManga = + smartSearchEngine.networkToLocalManga( + searchResult, + source.id + ) + val chapters = + source.fetchChapterList(localManga).toSingle() + .await( + Schedulers.io() + ) try { - syncChaptersWithSource(db, chapters, localManga, source) - } - catch (e: Exception) { + syncChaptersWithSource( + db, + chapters, + localManga, + source + ) + } catch (e: Exception) { return@async null } manga.progress.send(validSources.size to processedSources.incrementAndGet()) @@ -178,10 +192,10 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), } else { null } - } catch(e: CancellationException) { + } catch (e: CancellationException) { // Ignore cancellations throw e - } catch(e: Exception) { + } catch (e: Exception) { null } } @@ -190,15 +204,20 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), } else { validSources.forEachIndexed { index, source -> val searchResult = try { - val searchResult = smartSearchEngine - .normalSearch(source, mangaObj.originalTitle()) + val searchResult = smartSearchEngine.normalSearch( + source, + mangaObj.originalTitle() + ) if (searchResult != null) { - val localManga = smartSearchEngine.networkToLocalManga(searchResult, source.id) + val localManga = smartSearchEngine.networkToLocalManga( + searchResult, + source.id + ) val chapters = try { - source.fetchChapterList(localManga) - .toSingle().await(Schedulers.io()) } - catch (e: java.lang.Exception) { + source.fetchChapterList(localManga).toSingle() + .await(Schedulers.io()) + } catch (e: java.lang.Exception) { Timber.e(e) emptyList() } ?: emptyList() @@ -207,44 +226,43 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), } localManga } else null - } catch(e: CancellationException) { + } catch (e: CancellationException) { // Ignore cancellations throw e - } catch(e: Exception) { + } catch (e: Exception) { null } manga.progress.send(validSources.size to (index + 1)) - if(searchResult != null) return@async searchResult + if (searchResult != null) return@async searchResult } null } }.await() - } catch(e: CancellationException) { + } catch (e: CancellationException) { // Ignore canceled migrations continue } - if(result != null && result.thumbnail_url == null) { + if (result != null && result.thumbnail_url == null) { try { - val newManga = sourceManager.getOrStub(result.source) - .fetchMangaDetails(result) - .toSingle() - .await() + val newManga = + sourceManager.getOrStub(result.source).fetchMangaDetails(result) + .toSingle().await() result.copyFrom(newManga) db.insertManga(result).executeAsBlocking() - } catch(e: CancellationException) { + } catch (e: CancellationException) { // Ignore cancellations throw e - } catch(e: Exception) { + } catch (e: Exception) { } } - manga.migrationStatus = if (result == null) MigrationStatus.MANGA_NOT_FOUND else - MigrationStatus.MANGA_FOUND + manga.migrationStatus = + if (result == null) MigrationStatus.MANGA_NOT_FOUND else MigrationStatus.MANGA_FOUND adapter?.sourceFinished() manga.searchResult.initialize(result?.id) } @@ -276,8 +294,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), ids.removeAt(index) config.mangaIds = ids val index2 = migratingManga?.indexOf(item.manga) ?: return - if (index2 > -1) - migratingManga?.removeAt(index2) + if (index2 > -1) migratingManga?.removeAt(index2) } } @@ -308,7 +325,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), } } R.id.action_skip -> adapter?.removeManga(position) - R.id.action_migrate_now -> { + R.id.action_migrate_now -> { adapter?.migrateManga(position, false) manaulMigrations++ } @@ -381,7 +398,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), activity?.let { MaterialDialog(it).show { title(R.string.stop_migration) - positiveButton (R.string.action_stop) { + positiveButton(R.string.action_stop) { router.popCurrentController() migrationsJob?.cancel() } @@ -427,10 +444,18 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), val totalManga = adapter?.itemCount ?: 0 val mangaSkipped = adapter?.mangasSkipped() ?: 0 when (item.itemId) { - R.id.action_copy_manga -> MigrationMangaDialog(this, true, totalManga, mangaSkipped) - .showDialog(router) - R.id.action_migrate_manga -> MigrationMangaDialog(this, false, totalManga, mangaSkipped) - .showDialog(router) + R.id.action_copy_manga -> MigrationMangaDialog( + this, + true, + totalManga, + mangaSkipped + ).showDialog(router) + R.id.action_migrate_manga -> MigrationMangaDialog( + this, + false, + totalManga, + mangaSkipped + ).showDialog(router) else -> return super.onOptionsItemSelected(item) } return true @@ -441,7 +466,7 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), activity?.let { MaterialDialog(it).show { title(R.string.stop_migration) - positiveButton (R.string.action_stop) { + positiveButton(R.string.action_stop) { block() migrationsJob?.cancel() } @@ -463,4 +488,4 @@ class MigrationListController(bundle: Bundle? = null) : BaseController(bundle), }) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcedureConfig.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcedureConfig.kt index 75e7e57fce..1c26143d25 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcedureConfig.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcedureConfig.kt @@ -5,6 +5,6 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class MigrationProcedureConfig( - var mangaIds: List, - val extraSearchParams: String? -): Parcelable \ No newline at end of file + var mangaIds: List, + val extraSearchParams: String? +) : Parcelable 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 ce1521d9fe..a38d05c589 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 @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.ui.migration.manga.process -import android.content.Context import android.view.MenuItem import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.data.database.DatabaseHelper @@ -19,10 +18,9 @@ class MigrationProcessAdapter( val controller: MigrationListController ) : FlexibleAdapter(null, controller, true) { - private val db: DatabaseHelper by injectLazy() var items: List = emptyList() - val preferences:PreferencesHelper by injectLazy() + val preferences: PreferencesHelper by injectLazy() val menuItemListener: MigrationProcessInterface = controller @@ -46,7 +44,7 @@ class MigrationProcessAdapter( } fun allMangasDone() = (items.all { it.manga.migrationStatus != MigrationStatus - .RUNNUNG } && items.any { it.manga.migrationStatus == MigrationStatus.MANGA_FOUND }) + .RUNNUNG } && items.any { it.manga.migrationStatus == MigrationStatus.MANGA_FOUND }) fun mangasSkipped() = (items.count { it.manga.migrationStatus == MigrationStatus.MANGA_NOT_FOUND }) @@ -93,9 +91,11 @@ class MigrationProcessAdapter( sourceFinished() } - private fun migrateMangaInternal(prevManga: Manga, + private fun migrateMangaInternal( + prevManga: Manga, manga: Manga, - replace: Boolean) { + replace: Boolean + ) { if (controller.config == null) return val flags = preferences.migrateFlags().getOrDefault() // Update chapters read @@ -138,6 +138,6 @@ class MigrationProcessAdapter( // SearchPresenter#networkToLocalManga may have updated the manga title, so ensure db gets updated title db.updateMangaTitle(manga).executeAsBlocking() - //} + // } } -} \ No newline at end of file +} 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 884fe2cb9d..aa66dcd91b 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 @@ -21,13 +21,13 @@ import eu.kanade.tachiyomi.util.view.invisible import eu.kanade.tachiyomi.util.view.setVectorCompat import eu.kanade.tachiyomi.util.view.visible import eu.kanade.tachiyomi.widget.StateImageViewTarget +import java.text.DecimalFormat import kotlinx.android.synthetic.main.catalogue_grid_item.view.* import kotlinx.android.synthetic.main.migration_process_item.* import kotlinx.android.synthetic.main.unread_download_badge.view.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import uy.kohesive.injekt.injectLazy -import java.text.DecimalFormat class MigrationProcessHolder( private val view: View, @@ -36,8 +36,7 @@ class MigrationProcessHolder( private val db: DatabaseHelper by injectLazy() private val sourceManager: SourceManager by injectLazy() - private var item:MigrationProcessItem? = null - + private var item: MigrationProcessItem? = null init { // We need to post a Runnable to show the popup to make sure that the PopupMenu is @@ -139,8 +138,7 @@ class MigrationProcessHolder( if (isTo) { transition(DrawableTransitionOptions.withCrossFade()) .into(StateImageViewTarget(cover_thumbnail, progress)) - } - else + } else into(cover_thumbnail) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessItem.kt index 70b0ebdcf7..df77a57cc5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/migration/manga/process/MigrationProcessItem.kt @@ -18,10 +18,12 @@ class MigrationProcessItem(val manga: MigratingManga) : return MigrationProcessHolder(view, adapter as MigrationProcessAdapter) } - override fun bindViewHolder(adapter: FlexibleAdapter>, + override fun bindViewHolder( + adapter: FlexibleAdapter>, holder: MigrationProcessHolder, position: Int, - payloads: MutableList?) { + payloads: MutableList? + ) { holder.bind(this) } @@ -36,5 +38,4 @@ class MigrationProcessItem(val manga: MigratingManga) : override fun hashCode(): Int { return manga.mangaId.toInt() } - -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/PageIndicatorTextView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/PageIndicatorTextView.kt index d7383723bb..df6dca5e05 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/PageIndicatorTextView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/PageIndicatorTextView.kt @@ -15,8 +15,8 @@ import eu.kanade.tachiyomi.widget.OutlineSpan * Page indicator found at the bottom of the reader */ class PageIndicatorTextView( - context: Context, - attrs: AttributeSet? = null + context: Context, + attrs: AttributeSet? = null ) : AppCompatTextView(context, attrs) { init { @@ -32,7 +32,7 @@ class PageIndicatorTextView( // Also add a bit of spacing between each character, as the stroke overlaps them val finalText = SpannableString(currText.asIterable().joinToString("\u00A0")).apply { // Apply text outline - setSpan(spanOutline, 1, length-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + setSpan(spanOutline, 1, length - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) for (i in 1..lastIndex step 2) { setSpan(ScaleXSpan(0.2f), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) 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 ca467108d4..05a1981af7 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 @@ -54,6 +54,10 @@ import eu.kanade.tachiyomi.util.view.snack import eu.kanade.tachiyomi.util.view.visible import eu.kanade.tachiyomi.widget.SimpleAnimationListener import eu.kanade.tachiyomi.widget.SimpleSeekBarListener +import java.io.File +import java.util.Locale +import java.util.concurrent.TimeUnit +import kotlin.math.abs import kotlinx.android.synthetic.main.reader_activity.* import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -65,10 +69,6 @@ import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.io.File -import java.util.Locale -import java.util.concurrent.TimeUnit -import kotlin.math.abs /** * Activity containing the reader of Tachiyomi. This activity is mostly a container of the @@ -128,7 +128,7 @@ class ReaderActivity : BaseRxActivity(), @Suppress("DEPRECATION") private var progressDialog: ProgressDialog? = null - private var snackbar:Snackbar? = null + private var snackbar: Snackbar? = null companion object { @Suppress("unused") @@ -365,8 +365,7 @@ class ReaderActivity : BaseRxActivity(), val bottomAnimation = AnimationUtils.loadAnimation(this, R.anim.exit_to_bottom) reader_menu_bottom.startAnimation(bottomAnimation) } - } - else + } else reader_menu.visibility = View.GONE } menuStickyVisible = false @@ -634,8 +633,7 @@ class ReaderActivity : BaseRxActivity(), }) toolbar.startAnimation(toolbarAnimation) } - } - else { + } else { if (menuStickyVisible && !menuVisible) { setMenuVisibility(false, animate = false) } @@ -643,7 +641,6 @@ class ReaderActivity : BaseRxActivity(), } } - /** * Class that handles the user preferences of the reader. */ @@ -849,7 +846,5 @@ class ReaderActivity : BaseRxActivity(), color_overlay.visibility = View.VISIBLE color_overlay.setFilterColor(value, preferences.colorFilterMode().getOrDefault()) } - } - } 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 eaeb398cd6..0ee65dfc46 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 @@ -16,14 +16,14 @@ import eu.kanade.tachiyomi.util.view.setBottomEdge import eu.kanade.tachiyomi.util.view.setEdgeToEdge import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener import eu.kanade.tachiyomi.widget.SimpleSeekBarListener +import java.util.concurrent.TimeUnit +import kotlin.math.abs import kotlinx.android.synthetic.main.reader_color_filter.* import kotlinx.android.synthetic.main.reader_color_filter_sheet.* import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.injectLazy -import java.util.concurrent.TimeUnit -import kotlin.math.abs /** * Color filter sheet to toggle custom filter and brightness overlay. @@ -198,7 +198,7 @@ class ReaderColorFilterSheet(activity: ReaderActivity) : BottomSheetDialog val green = getGreenFromColor(color) val blue = getBlueFromColor(color) - //Initialize values + // Initialize values with(view) { txt_color_filter_alpha_value.text = alpha.toString() @@ -341,5 +341,4 @@ class ReaderColorFilterSheet(activity: ReaderActivity) : BottomSheetDialog /** Integer mask of blue value **/ const val BLUE_MASK: Long = 0x000000FF } - } 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 4c833bbd08..eb04c10133 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 @@ -1,13 +1,16 @@ package eu.kanade.tachiyomi.ui.reader import android.content.Context -import android.graphics.* +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.PorterDuff +import android.graphics.PorterDuffXfermode import android.util.AttributeSet import android.view.View class ReaderColorFilterView( - context: Context, - attrs: AttributeSet? = null + context: Context, + attrs: AttributeSet? = null ) : View(context, attrs) { private val colorFilterPaint: Paint = Paint() diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPageSheet.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPageSheet.kt index a74e825cf6..8f1ea6bfce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPageSheet.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPageSheet.kt @@ -3,9 +3,9 @@ package eu.kanade.tachiyomi.ui.reader import android.os.Build import android.os.Bundle import android.view.View -import com.google.android.material.bottomsheet.BottomSheetDialog import android.view.ViewGroup import com.afollestad.materialdialogs.MaterialDialog +import com.google.android.material.bottomsheet.BottomSheetDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault @@ -21,8 +21,8 @@ import uy.kohesive.injekt.api.get * Sheet to show when a page is long clicked. */ class ReaderPageSheet( - private val activity: ReaderActivity, - private val page: ReaderPage + private val activity: ReaderActivity, + private val page: ReaderPage ) : BottomSheetDialog(activity, R.style.BottomSheetDialogTheme) { /** @@ -41,7 +41,6 @@ class ReaderPageSheet( setBottomEdge(save_layout, activity) - set_as_cover_layout.setOnClickListener { setAsCover() } share_layout.setOnClickListener { share() } save_layout.setOnClickListener { save() } @@ -86,5 +85,4 @@ class ReaderPageSheet( activity.saveImage(page) dismiss() } - } 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 674702dd29..65fd125e34 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 @@ -24,7 +24,9 @@ import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters import eu.kanade.tachiyomi.util.storage.DiskUtil import eu.kanade.tachiyomi.util.system.ImageUtil -import kotlinx.coroutines.CoroutineScope +import java.io.File +import java.util.Date +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -37,9 +39,6 @@ import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.io.File -import java.util.Date -import java.util.concurrent.TimeUnit /** * Presenter used by the activity to perform background operations. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSeekBar.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSeekBar.kt index 48aeb56d32..31576a4266 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSeekBar.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSeekBar.kt @@ -4,16 +4,16 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.os.Build -import androidx.appcompat.widget.AppCompatSeekBar import android.util.AttributeSet import android.view.MotionEvent +import androidx.appcompat.widget.AppCompatSeekBar /** * Seekbar to show current chapter progress. */ class ReaderSeekBar @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null + context: Context, + attrs: AttributeSet? = null ) : AppCompatSeekBar(context, attrs) { /** 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 31375df7dd..77129cacd2 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 @@ -28,8 +28,8 @@ import uy.kohesive.injekt.injectLazy /** * Sheet to show reader and viewer preferences. */ -class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDialog - (activity, R.style.BottomSheetDialogTheme) { +class ReaderSettingsSheet(private val activity: ReaderActivity) : + BottomSheetDialog(activity, R.style.BottomSheetDialogTheme) { /** * Preferences helper. @@ -38,7 +38,7 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDia private var sheetBehavior: BottomSheetBehavior<*> - val scroll:NestedScrollView + val scroll: NestedScrollView init { // Use activity theme for this layout @@ -48,28 +48,29 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDia setContentView(scroll) sheetBehavior = BottomSheetBehavior.from(scroll.parent as ViewGroup) - setEdgeToEdge(activity, constraint_layout, scroll, - context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && - preferences.readerTheme().getOrDefault() == 0 && - activity.window.decorView.rootWindowInsets.systemWindowInsetRight == 0 && - activity.window.decorView.rootWindowInsets.systemWindowInsetLeft == 0) - window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + setEdgeToEdge( + activity, + constraint_layout, + scroll, + context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE + ) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && preferences.readerTheme() + .getOrDefault() == 0 && activity.window.decorView.rootWindowInsets.systemWindowInsetRight == 0 && activity.window.decorView.rootWindowInsets.systemWindowInsetLeft == 0 + ) window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR val height = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.window.decorView.rootWindowInsets.systemWindowInsetBottom } else 0 sheetBehavior.peekHeight = 200.dpToPx + height sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onSlide(bottomSheet: View, progress: Float) { } + override fun onSlide(bottomSheet: View, progress: Float) {} override fun onStateChanged(p0: View, state: Int) { if (state == BottomSheetBehavior.STATE_EXPANDED) { - sheetBehavior.skipCollapsed = true + sheetBehavior.skipCollapsed = true } } }) - } /** @@ -92,7 +93,6 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDia close_button.setOnClickListener { dismiss() } - } override fun onStart() { @@ -150,15 +150,15 @@ class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDia /** * Binds a spinner to an int preference with an optional offset for the value. */ - private fun Spinner.bindToPreference(pref: Preference, offset: Int = 0, shouldDismiss: - Boolean - = false) { + private fun Spinner.bindToPreference( + pref: Preference, + offset: Int = 0, + shouldDismiss: Boolean = false + ) { onItemSelectedListener = IgnoreFirstSpinnerListener { position -> pref.set(position + offset) - if (shouldDismiss) - dismiss() + if (shouldDismiss) dismiss() } setSelection(pref.getOrDefault() - offset, false) } - } 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 aae8d8c1f7..6c38a5e66b 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 @@ -102,5 +102,4 @@ class SaveImageNotifier(private val context: Context) { } updateNotification() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt index 2bc91b0630..cab73c2844 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt @@ -16,9 +16,9 @@ import timber.log.Timber * Loader used to retrieve the [PageLoader] for a given chapter. */ class ChapterLoader( - private val downloadManager: DownloadManager, - private val manga: Manga, - private val source: Source + private val downloadManager: DownloadManager, + private val manga: Manga, + private val source: Source ) { /** @@ -80,5 +80,4 @@ class ChapterLoader( else -> error("Loader not implemented") } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DirectoryPageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DirectoryPageLoader.kt index ebbc3d2d37..95e7c6e5ea 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DirectoryPageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/DirectoryPageLoader.kt @@ -4,9 +4,9 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder import eu.kanade.tachiyomi.util.system.ImageUtil -import rx.Observable import java.io.File import java.io.FileInputStream +import rx.Observable /** * Loader used to load a chapter from a directory given on [file]. @@ -37,5 +37,4 @@ class DirectoryPageLoader(val file: File) : PageLoader() { override fun getPage(page: ReaderPage): Observable { return Observable.just(Page.READY) } - } 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 a21993a787..25eabe291a 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 @@ -15,10 +15,10 @@ import uy.kohesive.injekt.injectLazy * Loader used to load a chapter from the downloaded chapters. */ class DownloadPageLoader( - private val chapter: ReaderChapter, - private val manga: Manga, - private val source: Source, - private val downloadManager: DownloadManager + private val chapter: ReaderChapter, + private val manga: Manga, + private val source: Source, + private val downloadManager: DownloadManager ) : PageLoader() { /** @@ -45,5 +45,4 @@ class DownloadPageLoader( override fun getPage(page: ReaderPage): Observable { return Observable.just(Page.READY) // TODO maybe check if file still exists? } - } 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 43e9348c3b..d4df5c190d 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 @@ -3,8 +3,8 @@ package eu.kanade.tachiyomi.ui.reader.loader import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.storage.EpubFile -import rx.Observable import java.io.File +import rx.Observable /** * Loader used to load a chapter from a .epub file. @@ -50,5 +50,4 @@ class EpubPageLoader(file: File) : PageLoader() { 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 c34799d8e3..099a094dfe 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 @@ -8,8 +8,11 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderPage -import eu.kanade.tachiyomi.util.system.ImageUtil import eu.kanade.tachiyomi.util.lang.plusAssign +import eu.kanade.tachiyomi.util.system.ImageUtil +import java.util.concurrent.PriorityBlockingQueue +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.min import rx.Completable import rx.Observable import rx.schedulers.Schedulers @@ -20,17 +23,14 @@ import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy -import java.util.concurrent.PriorityBlockingQueue -import java.util.concurrent.atomic.AtomicInteger -import kotlin.math.min /** * Loader used to load chapters from an online source. */ class HttpPageLoader( - private val chapter: ReaderChapter, - private val source: HttpSource, - private val chapterCache: ChapterCache = Injekt.get() + private val chapter: ReaderChapter, + private val source: HttpSource, + private val chapterCache: ChapterCache = Injekt.get() ) : PageLoader() { /** @@ -173,9 +173,9 @@ class HttpPageLoader( * Data class used to keep ordering of pages in order to maintain priority. */ private class PriorityPage( - val page: ReaderPage, - val priority: Int - ): Comparable { + val page: ReaderPage, + val priority: Int + ) : Comparable { companion object { private val idGenerator = AtomicInteger() @@ -187,7 +187,6 @@ class HttpPageLoader( val p = other.priority.compareTo(priority) return if (p != 0) p else identifier.compareTo(other.identifier) } - } /** diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/PageLoader.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/PageLoader.kt index b0b872b6d7..de7e4e5410 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/PageLoader.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/PageLoader.kt @@ -42,5 +42,4 @@ abstract class PageLoader { * online source is used. */ open fun retryPage(page: ReaderPage) {} - } 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 51f25da0d9..14e0221276 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 @@ -4,14 +4,14 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder import eu.kanade.tachiyomi.util.system.ImageUtil -import junrar.Archive -import junrar.rarfile.FileHeader -import rx.Observable import java.io.File import java.io.InputStream import java.io.PipedInputStream import java.io.PipedOutputStream import java.util.concurrent.Executors +import junrar.Archive +import junrar.rarfile.FileHeader +import rx.Observable /** * Loader used to load a chapter from a .rar or .cbr file. @@ -83,5 +83,4 @@ class RarPageLoader(file: File) : PageLoader() { } return pipeIn } - } 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..dcf704ffe9 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 @@ -4,10 +4,10 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder import eu.kanade.tachiyomi.util.system.ImageUtil -import rx.Observable import java.io.File import java.util.zip.ZipEntry import java.util.zip.ZipFile +import rx.Observable /** * Loader used to load a chapter from a .zip or .cbz file. diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ChapterTransition.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ChapterTransition.kt index 892eceab04..41b6a3d787 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ChapterTransition.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ChapterTransition.kt @@ -6,10 +6,12 @@ sealed class ChapterTransition { abstract val to: ReaderChapter? class Prev( - override val from: ReaderChapter, override val to: ReaderChapter? + override val from: ReaderChapter, + override val to: ReaderChapter? ) : ChapterTransition() class Next( - override val from: ReaderChapter, override val to: ReaderChapter? + override val from: ReaderChapter, + override val to: ReaderChapter? ) : ChapterTransition() override fun equals(other: Any?): Boolean { @@ -29,5 +31,4 @@ sealed class ChapterTransition { override fun toString(): String { return "${javaClass.simpleName}(from=${from.chapter.url}, to=${to?.chapter?.url})" } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderPage.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderPage.kt index 48e3540425..eab73a60a4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderPage.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ReaderPage.kt @@ -5,14 +5,13 @@ import eu.kanade.tachiyomi.source.model.Page import java.io.InputStream class ReaderPage( - index: Int, - url: String = "", - imageUrl: String? = null, - var stream: (() -> InputStream)? = null, - var bg: Drawable? = null, - var bgAlwaysWhite: Boolean? = null + index: Int, + url: String = "", + imageUrl: String? = null, + var stream: (() -> InputStream)? = null, + var bg: Drawable? = null, + var bgAlwaysWhite: Boolean? = null ) : Page(index, url, imageUrl, null) { lateinit var chapter: ReaderChapter - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ViewerChapters.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ViewerChapters.kt index 1e950c6c70..9d43048409 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ViewerChapters.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/model/ViewerChapters.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.ui.reader.model data class ViewerChapters( - val currChapter: ReaderChapter, - val prevChapter: ReaderChapter?, - val nextChapter: ReaderChapter? + val currChapter: ReaderChapter, + val prevChapter: ReaderChapter?, + val nextChapter: ReaderChapter? ) { fun ref() { @@ -17,5 +17,4 @@ data class ViewerChapters( prevChapter?.unref() nextChapter?.unref() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/BaseViewer.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/BaseViewer.kt index 7420db5188..223cb087f5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/BaseViewer.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/BaseViewer.kt @@ -42,5 +42,4 @@ interface BaseViewer { * return true if the event was handled, false otherwise. */ fun handleGenericMotionEvent(event: MotionEvent): Boolean - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/GestureDetectorWithLongTap.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/GestureDetectorWithLongTap.kt index a96392b52f..52e1ab9bce 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/GestureDetectorWithLongTap.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/GestureDetectorWithLongTap.kt @@ -12,8 +12,8 @@ import kotlin.math.abs * one conflicts with the quick scale feature. */ open class GestureDetectorWithLongTap( - context: Context, - listener: Listener + context: Context, + listener: Listener ) : GestureDetector(context, listener) { private val handler = Handler() @@ -71,5 +71,4 @@ open class GestureDetectorWithLongTap( open fun onLongTapConfirmed(ev: MotionEvent) { } } - } 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 704577bb2b..ed215bf812 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 @@ -24,9 +24,9 @@ import kotlin.math.min * user also approximately knows how much the operation will take. */ class ReaderProgressBar @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null, - defStyleAttr: Int = 0 + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { /** @@ -157,7 +157,7 @@ class ReaderProgressBar @JvmOverloads constructor( if (!animate) { visibility = View.GONE } else { - ObjectAnimator.ofFloat(this, "alpha", 1f, 0f).apply { + ObjectAnimator.ofFloat(this, "alpha", 1f, 0f).apply { interpolator = DecelerateInterpolator() duration = 1000 addListener(object : AnimatorListenerAdapter() { @@ -209,5 +209,4 @@ class ReaderProgressBar @JvmOverloads constructor( start() } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/Pager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/Pager.kt index a256a5c6e0..b89bc9ee0c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/Pager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/Pager.kt @@ -13,8 +13,8 @@ import eu.kanade.tachiyomi.ui.reader.viewer.GestureDetectorWithLongTap * pager can also be declared to be vertical by creating it with [isHorizontal] to false. */ open class Pager( - context: Context, - isHorizontal: Boolean = true + context: Context, + isHorizontal: Boolean = true ) : DirectionalViewPager(context, isHorizontal) { /** @@ -104,5 +104,4 @@ open class Pager( fun setGestureDetectorEnabled(enabled: Boolean) { isGestureDetectorEnabled = enabled } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerButton.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerButton.kt index f184031a40..57cef1c8a0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerButton.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerButton.kt @@ -2,8 +2,8 @@ package eu.kanade.tachiyomi.ui.reader.viewer.pager import android.annotation.SuppressLint import android.content.Context -import androidx.appcompat.widget.AppCompatButton import android.view.MotionEvent +import androidx.appcompat.widget.AppCompatButton /** * A button class to be used by child views of the pager viewer. All tap gestures are handled by @@ -21,5 +21,4 @@ class PagerButton(context: Context, viewer: PagerViewer) : AppCompatButton(conte false } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt index 495290ccb7..62a970ec76 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt @@ -89,8 +89,8 @@ class PagerConfig(private val viewer: PagerViewer, preferences: PreferencesHelpe } private fun Preference.register( - valueAssignment: (T) -> Unit, - onChanged: (T) -> Unit = {} + valueAssignment: (T) -> Unit, + onChanged: (T) -> Unit = {} ) { asObservable() .doOnNext(valueAssignment) @@ -121,5 +121,4 @@ class PagerConfig(private val viewer: PagerViewer, preferences: PreferencesHelpe enum class ZoomType { Left, Center, Right } - } 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 52a20b8c92..86056bf5fa 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 @@ -35,12 +35,14 @@ import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.viewer.ReaderProgressBar import eu.kanade.tachiyomi.ui.reader.viewer.pager.PagerConfig.ZoomType -import eu.kanade.tachiyomi.util.system.launchUI import eu.kanade.tachiyomi.util.system.ImageUtil import eu.kanade.tachiyomi.util.system.dpToPx +import eu.kanade.tachiyomi.util.system.launchUI import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visible import eu.kanade.tachiyomi.widget.ViewPagerAdapter +import java.io.InputStream +import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers.Default import kotlinx.coroutines.withContext import rx.Observable @@ -48,16 +50,14 @@ import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy -import java.io.InputStream -import java.util.concurrent.TimeUnit /** * View of the ViewPager that contains a page of a chapter. */ @SuppressLint("ViewConstructor") class PagerPageHolder( - val viewer: PagerViewer, - val page: ReaderPage + val viewer: PagerViewer, + val page: ReaderPage ) : FrameLayout(viewer.activity), ViewPagerAdapter.PositionableView { /** @@ -271,8 +271,7 @@ class PagerPageHolder( page.bgAlwaysWhite = viewer.config.readerTheme == 2 } } - } - else { + } else { initSubsamplingImageView().setImage(ImageSource.inputStream(openStream!!)) } } else { @@ -484,21 +483,21 @@ class PagerPageHolder( .transition(DrawableTransitionOptions.with(NoTransition.getFactory())) .listener(object : RequestListener { override fun onLoadFailed( - e: GlideException?, - model: Any?, - target: Target?, - isFirstResource: Boolean + e: GlideException?, + model: Any?, + target: Target?, + isFirstResource: Boolean ): Boolean { onImageDecodeError() return false } override fun onResourceReady( - resource: Drawable?, - model: Any?, - target: Target?, - dataSource: DataSource?, - isFirstResource: Boolean + resource: Drawable?, + model: Any?, + target: Target?, + dataSource: DataSource?, + isFirstResource: Boolean ): Boolean { if (resource is GifDrawable) { resource.setLoopCount(GifDrawable.LOOP_INTRINSIC) @@ -509,5 +508,4 @@ class PagerPageHolder( }) .into(this) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerTransitionHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerTransitionHolder.kt index 1798eb55a3..ad0a7a92fb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerTransitionHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerTransitionHolder.kt @@ -27,8 +27,8 @@ import rx.android.schedulers.AndroidSchedulers */ @SuppressLint("ViewConstructor") class PagerTransitionHolder( - val viewer: PagerViewer, - val transition: ChapterTransition + val viewer: PagerViewer, + val transition: ChapterTransition ) : LinearLayout(viewer.activity), ViewPagerAdapter.PositionableView { /** @@ -46,8 +46,8 @@ class PagerTransitionHolder( * Text view used to display the text of the current and next/prev chapters. */ private var textView = TextView(context).apply { - //if (Build.VERSION.SDK_INT >= 23) - //setTextColor(context.getResourceColor(R.attr.)) + // if (Build.VERSION.SDK_INT >= 23) + // setTextColor(context.getResourceColor(R.attr.)) textSize = 17.5F wrapContent() } @@ -206,5 +206,4 @@ class PagerTransitionHolder( private fun View.wrapContent() { layoutParams = ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) } - } 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 537efb4197..57c48b6cec 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 @@ -1,11 +1,11 @@ package eu.kanade.tachiyomi.ui.reader.viewer.pager -import androidx.viewpager.widget.ViewPager import android.view.InputDevice import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.ViewGroup.LayoutParams +import androidx.viewpager.widget.ViewPager import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.ui.reader.model.ChapterTransition @@ -85,7 +85,7 @@ abstract class PagerViewer(val activity: ReaderActivity) : BaseViewer { else -> activity.toggleMenu() } } - pager.longTapListener = f@ { + pager.longTapListener = f@{ if (activity.menuVisible || config.longTapEnabled) { val item = adapter.items.getOrNull(pager.currentItem) if (item is ReaderPage) { @@ -326,5 +326,4 @@ abstract class PagerViewer(val activity: ReaderActivity) : BaseViewer { } return false } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewerAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewerAdapter.kt index d579d177d0..a23f4cac6a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewerAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewerAdapter.kt @@ -111,5 +111,4 @@ class PagerViewerAdapter(private val viewer: PagerViewer) : ViewPagerAdapter() { } return POSITION_NONE } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonAdapter.kt index b80f6d5782..2ca1e3d8d4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonAdapter.kt @@ -1,10 +1,10 @@ package eu.kanade.tachiyomi.ui.reader.viewer.webtoon -import androidx.recyclerview.widget.DiffUtil -import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.RecyclerView import eu.kanade.tachiyomi.ui.reader.model.ChapterTransition import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderPage @@ -129,8 +129,8 @@ class WebtoonAdapter(val viewer: WebtoonViewer) : androidx.recyclerview.widget.R * Diff util callback used to dispatch delta updates instead of full dataset changes. */ private class Callback( - private val oldItems: List, - private val newItems: List + private val oldItems: List, + private val newItems: List ) : DiffUtil.Callback() { /** @@ -176,5 +176,4 @@ class WebtoonAdapter(val viewer: WebtoonViewer) : androidx.recyclerview.widget.R */ const val TRANSITION_VIEW = 1 } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonBaseHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonBaseHolder.kt index 293127cb38..10a01b1377 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonBaseHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonBaseHolder.kt @@ -7,8 +7,8 @@ import eu.kanade.tachiyomi.ui.base.holder.BaseViewHolder import rx.Subscription abstract class WebtoonBaseHolder( - view: View, - protected val viewer: WebtoonViewer + view: View, + protected val viewer: WebtoonViewer ) : BaseViewHolder(view) { /** @@ -42,5 +42,4 @@ abstract class WebtoonBaseHolder( protected fun View.wrapContent() { layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonConfig.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonConfig.kt index 224cba589b..f467047e4c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonConfig.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonConfig.kt @@ -65,8 +65,8 @@ class WebtoonConfig(preferences: PreferencesHelper = Injekt.get()) { } private fun Preference.register( - valueAssignment: (T) -> Unit, - onChanged: (T) -> Unit = {} + valueAssignment: (T) -> Unit, + onChanged: (T) -> Unit = {} ) { asObservable() .doOnNext(valueAssignment) @@ -76,5 +76,4 @@ class WebtoonConfig(preferences: PreferencesHelper = Injekt.get()) { .subscribe() .addTo(subscriptions) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonFrame.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonFrame.kt index 955dc898e9..3f919569ca 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonFrame.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonFrame.kt @@ -68,13 +68,12 @@ class WebtoonFrame(context: Context) : FrameLayout(context) { } override fun onFling( - e1: MotionEvent?, - e2: MotionEvent?, - velocityX: Float, - velocityY: Float + e1: MotionEvent?, + e2: MotionEvent?, + velocityX: Float, + velocityY: Float ): Boolean { return recycler?.zoomFling(velocityX.toInt(), velocityY.toInt()) ?: false } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonLayoutManager.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonLayoutManager.kt index 34f9898a66..f6a00d2d49 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonLayoutManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonLayoutManager.kt @@ -51,5 +51,4 @@ class WebtoonLayoutManager(activity: ReaderActivity) : LinearLayoutManager(activ return if (child == null) NO_POSITION else getPosition(child) } - } 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 3d171800c2..55ba1950cd 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 @@ -4,8 +4,6 @@ import android.annotation.SuppressLint import android.content.Intent import android.graphics.drawable.Drawable import android.net.Uri -import androidx.appcompat.widget.AppCompatButton -import androidx.appcompat.widget.AppCompatImageView import android.view.Gravity import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT @@ -14,6 +12,8 @@ import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView +import androidx.appcompat.widget.AppCompatButton +import androidx.appcompat.widget.AppCompatImageView import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException @@ -33,12 +33,12 @@ import eu.kanade.tachiyomi.util.system.ImageUtil import eu.kanade.tachiyomi.util.system.dpToPx import eu.kanade.tachiyomi.util.view.gone import eu.kanade.tachiyomi.util.view.visible +import java.io.InputStream +import java.util.concurrent.TimeUnit import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers -import java.io.InputStream -import java.util.concurrent.TimeUnit /** * Holder of the webtoon reader for a single page of a chapter. @@ -48,8 +48,8 @@ import java.util.concurrent.TimeUnit * @constructor creates a new webtoon holder. */ class WebtoonPageHolder( - private val frame: FrameLayout, - viewer: WebtoonViewer + private val frame: FrameLayout, + viewer: WebtoonViewer ) : WebtoonBaseHolder(frame, viewer) { /** @@ -328,7 +328,7 @@ class WebtoonPageHolder( val size = 48.dpToPx layoutParams = FrameLayout.LayoutParams(size, size).apply { gravity = Gravity.CENTER_HORIZONTAL - setMargins(0, parentHeight/4, 0, 0) + setMargins(0, parentHeight / 4, 0, 0) } } progressContainer.addView(progress) @@ -389,7 +389,7 @@ class WebtoonPageHolder( AppCompatButton(context).apply { layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { gravity = Gravity.CENTER_HORIZONTAL - setMargins(0, parentHeight/4, 0, 0) + setMargins(0, parentHeight / 4, 0, 0) } setText(R.string.action_retry) setOnClickListener { @@ -411,7 +411,7 @@ class WebtoonPageHolder( val decodeLayout = LinearLayout(context).apply { layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, parentHeight).apply { - setMargins(0, parentHeight/6, 0, 0) + setMargins(0, parentHeight / 6, 0, 0) } gravity = Gravity.CENTER_HORIZONTAL orientation = LinearLayout.VERTICAL @@ -482,21 +482,21 @@ class WebtoonPageHolder( .transition(DrawableTransitionOptions.with(NoTransition.getFactory())) .listener(object : RequestListener { override fun onLoadFailed( - e: GlideException?, - model: Any?, - target: Target?, - isFirstResource: Boolean + e: GlideException?, + model: Any?, + target: Target?, + isFirstResource: Boolean ): Boolean { onImageDecodeError() return false } override fun onResourceReady( - resource: Drawable?, - model: Any?, - target: Target?, - dataSource: DataSource?, - isFirstResource: Boolean + resource: Drawable?, + model: Any?, + target: Target?, + dataSource: DataSource?, + isFirstResource: Boolean ): Boolean { if (resource is GifDrawable) { resource.setLoopCount(GifDrawable.LOOP_INTRINSIC) @@ -507,5 +507,4 @@ class WebtoonPageHolder( }) .into(this) } - } 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 2744d91d6e..88ee1cbd7f 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 @@ -18,9 +18,9 @@ import kotlin.math.abs * Implementation of a [RecyclerView] used by the webtoon reader. */ open class WebtoonRecyclerView @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null, - defStyle: Int = 0 + context: Context, + attrs: AttributeSet? = null, + defStyle: Int = 0 ) : androidx.recyclerview.widget.RecyclerView(context, attrs, defStyle) { private var isZooming = false @@ -77,12 +77,12 @@ open class WebtoonRecyclerView @JvmOverloads constructor( } private fun zoom( - fromRate: Float, - toRate: Float, - fromX: Float, - toX: Float, - fromY: Float, - toY: Float + fromRate: Float, + toRate: Float, + fromX: Float, + toX: Float, + fromY: Float, + toY: Float ) { isZooming = true val animatorSet = AnimatorSet() @@ -102,7 +102,6 @@ open class WebtoonRecyclerView @JvmOverloads constructor( animatorSet.start() animatorSet.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { - } override fun onAnimationEnd(animation: Animator) { @@ -111,11 +110,9 @@ open class WebtoonRecyclerView @JvmOverloads constructor( } override fun onAnimationCancel(animation: Animator) { - } override fun onAnimationRepeat(animation: Animator) { - } }) } @@ -222,7 +219,6 @@ open class WebtoonRecyclerView @JvmOverloads constructor( performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } } - } inner class Detector : GestureDetectorWithLongTap(context, listener) { @@ -310,7 +306,6 @@ open class WebtoonRecyclerView @JvmOverloads constructor( } return super.onTouchEvent(ev) } - } private companion object { @@ -318,5 +313,4 @@ open class WebtoonRecyclerView @JvmOverloads constructor( const val DEFAULT_RATE = 1f const val MAX_SCALE_RATE = 3f } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonSubsamplingImageView.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonSubsamplingImageView.kt index 692c0596ba..88f916161d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonSubsamplingImageView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonSubsamplingImageView.kt @@ -10,12 +10,11 @@ import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView * webtoon viewer handles all the gestures. */ class WebtoonSubsamplingImageView @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null + context: Context, + attrs: AttributeSet? = null ) : SubsamplingScaleImageView(context, attrs) { override fun onTouchEvent(event: MotionEvent): Boolean { return false } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonTransitionHolder.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonTransitionHolder.kt index 9d033f6bfb..af615f0273 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonTransitionHolder.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonTransitionHolder.kt @@ -24,8 +24,8 @@ import rx.android.schedulers.AndroidSchedulers * Holder of the webtoon viewer that contains a chapter transition. */ class WebtoonTransitionHolder( - val layout: LinearLayout, - viewer: WebtoonViewer + val layout: LinearLayout, + viewer: WebtoonViewer ) : WebtoonBaseHolder(layout, viewer) { /** @@ -211,5 +211,4 @@ class WebtoonTransitionHolder( pagesContainer.addView(textView) pagesContainer.addView(retryBtn) } - } 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 f83b2d4a91..d177ba3b16 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 @@ -1,12 +1,12 @@ package eu.kanade.tachiyomi.ui.reader.viewer.webtoon -import androidx.recyclerview.widget.RecyclerView -import androidx.recyclerview.widget.WebtoonLayoutManager import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.WebtoonLayoutManager import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.ui.reader.model.ChapterTransition import eu.kanade.tachiyomi.ui.reader.model.ReaderPage @@ -98,7 +98,7 @@ class WebtoonViewer(val activity: ReaderActivity) : BaseViewer { else -> activity.toggleMenu() } } - recycler.longTapListener = f@ { event -> + recycler.longTapListener = f@{ event -> if (activity.menuVisible || config.longTapEnabled) { val child = recycler.findChildViewUnder(event.x, event.y) if (child != null) { @@ -255,5 +255,4 @@ class WebtoonViewer(val activity: ReaderActivity) : BaseViewer { override fun handleGenericMotionEvent(event: MotionEvent): Boolean { return false } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/ConfirmDeleteChaptersDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/ConfirmDeleteChaptersDialog.kt index c5e8c3bf59..e8721b7b0c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/ConfirmDeleteChaptersDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/ConfirmDeleteChaptersDialog.kt @@ -29,4 +29,4 @@ class ConfirmDeleteChaptersDialog(bundle: Bundle? = null) : DialogController( interface Listener { fun deleteChapters(chaptersToDelete: List) } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterItem.kt index aeb7106a6d..d1888732a4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChapterItem.kt @@ -29,13 +29,15 @@ class RecentChapterItem(val chapter: Chapter, val manga: Manga, header: DateItem } override fun createViewHolder(view: View, adapter: FlexibleAdapter>): RecentChapterHolder { - return RecentChapterHolder(view , adapter as RecentChaptersAdapter) + return RecentChapterHolder(view, adapter as RecentChaptersAdapter) } - override fun bindViewHolder(adapter: FlexibleAdapter>, - holder: RecentChapterHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: RecentChapterHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(this) } @@ -56,5 +58,4 @@ class RecentChapterItem(val chapter: Chapter, val manga: Manga, header: DateItem override fun hashCode(): Int { return chapter.id!!.hashCode() } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersAdapter.kt index 995bb3ee55..691776593a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersAdapter.kt @@ -11,7 +11,7 @@ class RecentChaptersAdapter(val controller: RecentChaptersController) : init { setDisplayHeadersAtStartUp(true) - //setStickyHeaders(true) + // setStickyHeaders(true) } fun setItems(recents: List) { @@ -23,8 +23,7 @@ class RecentChaptersAdapter(val controller: RecentChaptersController) : val s = getFilter(String::class.java) if (s.isNullOrBlank()) { updateDataSet(recents) - } - else { + } else { updateDataSet(recents.filter { it.filter(s) }) } } @@ -32,4 +31,4 @@ class RecentChaptersAdapter(val controller: RecentChaptersController) : interface OnCoverClickListener { fun onCoverClick(position: Int) } -} \ No newline at end of file +} 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 73253c64a4..50e24675ca 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 @@ -87,7 +87,7 @@ class RecentChaptersController : NucleusController(), override fun onViewCreated(view: View) { super.onViewCreated(view) view.applyWindowInsetsForRootController(activity!!.bottom_nav) - + view.context.notificationManager.cancel(Notifications.ID_NEW_CHAPTERS) // Init RecyclerView and adapter val layoutManager = LinearLayoutManager(view.context) @@ -275,7 +275,6 @@ class RecentChaptersController : NucleusController(), override fun onCoverClick(position: Int) { val chapterClicked = adapter?.getItem(position) as? RecentChapterItem ?: return openManga(chapterClicked) - } fun openManga(chapter: RecentChapterItem) { @@ -346,7 +345,6 @@ class RecentChaptersController : NucleusController(), actionMode = null } - override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.recent_updates, menu) val searchItem = menu.findItem(R.id.action_search) 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 d80a2de2c2..638b1810eb 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 @@ -8,21 +8,21 @@ import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter +import java.util.Calendar +import java.util.Date +import java.util.TreeMap import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.Calendar -import java.util.Date -import java.util.TreeMap class RecentChaptersPresenter( - val preferences: PreferencesHelper = Injekt.get(), - private val db: DatabaseHelper = Injekt.get(), - private val downloadManager: DownloadManager = Injekt.get(), - private val sourceManager: SourceManager = Injekt.get() + val preferences: PreferencesHelper = Injekt.get(), + private val db: DatabaseHelper = Injekt.get(), + private val downloadManager: DownloadManager = Injekt.get(), + private val sourceManager: SourceManager = Injekt.get() ) : BasePresenter() { /** @@ -203,5 +203,4 @@ class RecentChaptersPresenter( } } } - } 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 962cf5f617..76109a8a6e 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 @@ -5,10 +5,10 @@ import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.SourceManager -import uy.kohesive.injekt.injectLazy import java.text.DateFormat import java.text.DecimalFormat import java.text.DecimalFormatSymbols +import uy.kohesive.injekt.injectLazy /** * Adapter of RecentlyReadHolder. @@ -18,8 +18,8 @@ import java.text.DecimalFormatSymbols * @param controller a RecentlyReadController object * @constructor creates an instance of the adapter. */ -class RecentlyReadAdapter(controller: RecentlyReadController) -: FlexibleAdapter>(null, controller, true) { +class RecentlyReadAdapter(controller: RecentlyReadController) : +FlexibleAdapter>(null, controller, true) { val sourceManager 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 2ef1fe5ac2..ae77ecfa9b 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 @@ -62,13 +62,12 @@ class RecentlyReadController(bundle: Bundle? = null) : BaseController(bundle), * Endless loading item. */ private var progressItem: ProgressItem? = null - private var observeLater:Boolean = false + private var observeLater: Boolean = false private var query = "" private var presenter = RecentlyReadPresenter(this) private var recentItems: MutableList? = null - override fun getTitle(): String? { return resources?.getString(R.string.label_recent_manga) } 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 0ff8526309..d93b7bfeb3 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 @@ -9,9 +9,9 @@ import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory import eu.kanade.tachiyomi.data.glide.GlideApp import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder import eu.kanade.tachiyomi.util.lang.toTimestampString -import kotlinx.android.synthetic.main.recently_read_item.* import java.util.Date import kotlin.math.max +import kotlinx.android.synthetic.main.recently_read_item.* /** * Holder that contains recent manga item @@ -23,8 +23,8 @@ import kotlin.math.max * @constructor creates a new recent chapter holder. */ class RecentlyReadHolder( - view: View, - val adapter: RecentlyReadAdapter + view: View, + val adapter: RecentlyReadAdapter ) : BaseFlexibleViewHolder(view, adapter) { private var lastTouchUpY = 0f @@ -82,6 +82,4 @@ class RecentlyReadHolder( .into(cover) } } - - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadItem.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadItem.kt index 633903fd52..527a4f21bc 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadItem.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadItem.kt @@ -18,10 +18,12 @@ class RecentlyReadItem(val mch: MangaChapterHistory) : AbstractFlexibleItem>, - holder: RecentlyReadHolder, - position: Int, - payloads: MutableList?) { + override fun bindViewHolder( + adapter: FlexibleAdapter>, + holder: RecentlyReadHolder, + position: Int, + payloads: MutableList? + ) { holder.bind(mch) } 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 aaebfd5032..d828d6900e 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 @@ -5,12 +5,12 @@ import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.util.system.launchUI -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import uy.kohesive.injekt.injectLazy import java.util.Calendar import java.util.Comparator import java.util.Date +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import uy.kohesive.injekt.injectLazy /** * Presenter of RecentlyReadFragment. @@ -126,5 +126,4 @@ class RecentlyReadPresenter(private val view: RecentlyReadController) { 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 e3bea08f14..72757b8b58 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 @@ -5,16 +5,14 @@ import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.checkbox.checkBoxPrompt import com.afollestad.materialdialogs.checkbox.isCheckPromptChecked -import com.afollestad.materialdialogs.customview.customView import com.bluelinelabs.conductor.Controller import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.controller.DialogController -import eu.kanade.tachiyomi.widget.DialogCheckboxView class RemoveHistoryDialog(bundle: Bundle? = null) : DialogController(bundle) - where T : Controller, T: RemoveHistoryDialog.Listener { + where T : Controller, T : RemoveHistoryDialog.Listener { private var manga: Manga? = null @@ -32,7 +30,7 @@ class RemoveHistoryDialog(bundle: Bundle? = null) : DialogController(bundle) return MaterialDialog(activity) .title(R.string.action_remove) .message(R.string.dialog_with_checkbox_remove_description) - .checkBoxPrompt(res = R.string.dialog_with_checkbox_reset){} + .checkBoxPrompt(res = R.string.dialog_with_checkbox_reset) {} .negativeButton(android.R.string.cancel) .positiveButton(R.string.action_remove) { onPositive(it.isCheckPromptChecked()) @@ -50,5 +48,4 @@ class RemoveHistoryDialog(bundle: Bundle? = null) : DialogController(bundle) interface Listener { fun removeHistory(manga: Manga, history: History, all: Boolean) } - -} \ No newline at end of file +} 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 0cab38e2be..944b3e1f3c 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 @@ -38,5 +38,4 @@ class BiometricActivity : BaseActivity() { biometricPrompt.authenticate(promptInfo) } - -} \ No newline at end of file +} 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 1974ddd730..e46b264d4e 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 @@ -7,8 +7,8 @@ import androidx.biometric.BiometricManager import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.main.SearchActivity -import uy.kohesive.injekt.injectLazy import java.util.Date +import uy.kohesive.injekt.injectLazy object SecureActivityDelegate { @@ -16,7 +16,7 @@ object SecureActivityDelegate { var locked: Boolean = true - fun setSecure(activity: Activity?, force:Boolean? = null) { + fun setSecure(activity: Activity?, force: Boolean? = null) { val enabled = force ?: preferences.secureScreen().getOrDefault() if (enabled) { activity?.window?.setFlags( @@ -51,9 +51,8 @@ object SecureActivityDelegate { private fun isAppLocked(): Boolean { return locked && - (preferences.lockAfter().getOrDefault() <= 0 - || Date().time >= preferences.lastUnlock().getOrDefault() + 60 * 1000 * preferences + (preferences.lockAfter().getOrDefault() <= 0 || + Date().time >= preferences.lastUnlock().getOrDefault() + 60 * 1000 * preferences .lockAfter().getOrDefault()) } - -} \ No newline at end of file +} 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 0447043caa..909de934ac 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 @@ -34,7 +34,6 @@ inline fun PreferenceGroup.extensionPreference(block: (@DSL Preference).() -> Un return initThenAdd(ExtensionPreference(context), block) } - inline fun PreferenceGroup.switchPreference(block: (@DSL SwitchPreferenceCompat).() -> Unit): SwitchPreferenceCompat { return initThenAdd(SwitchPreferenceCompat(context), block) } @@ -52,21 +51,30 @@ inline fun PreferenceGroup.dropDownPreference(block: (@DSL DropDownPreference).( return initThenAdd(DropDownPreference(context), block).also(::initDialog) } -inline fun PreferenceGroup.listPreference(activity: Activity?, block: (@DSL ListMatPreference).() --> Unit): +inline fun PreferenceGroup.listPreference( + activity: Activity?, + block: (@DSL ListMatPreference).() + -> Unit +): ListMatPreference { return initThenAdd(ListMatPreference(activity, context), block) } -inline fun PreferenceGroup.intListPreference(activity: Activity?, block: (@DSL -IntListMatPreference).() -> Unit): +inline fun PreferenceGroup.intListPreference( + activity: Activity?, + block: (@DSL + IntListMatPreference).() -> Unit +): IntListMatPreference { return initThenAdd(IntListMatPreference(activity, context), block) } -inline fun PreferenceGroup.multiSelectListPreferenceMat(activity: Activity?, block: (@DSL -MultiListMatPreference).() --> Unit): MultiListMatPreference { +inline fun PreferenceGroup.multiSelectListPreferenceMat( + activity: Activity?, + block: (@DSL + MultiListMatPreference).() + -> Unit +): MultiListMatPreference { return initThenAdd(MultiListMatPreference(activity, context), block) } @@ -98,7 +106,7 @@ inline fun

PreferenceGroup.initThenAdd(p: P, block: P.() -> Uni inline fun

PreferenceGroup.addThenInit(p: P, block: P.() -> Unit): P { return p.apply { - this.isIconSpaceReserved = false + this.isIconSpaceReserved = false addPreference(this) block() } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAboutController.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAboutController.kt index 019fda27aa..0ae729b454 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAboutController.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAboutController.kt @@ -17,6 +17,11 @@ import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.main.ChangelogDialogController import eu.kanade.tachiyomi.util.lang.toTimestampString import eu.kanade.tachiyomi.util.system.toast +import java.text.DateFormat +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.Locale +import java.util.TimeZone import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -24,11 +29,6 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber import uy.kohesive.injekt.injectLazy -import java.text.DateFormat -import java.text.ParseException -import java.text.SimpleDateFormat -import java.util.Locale -import java.util.TimeZone class SettingsAboutController : SettingsController() { @@ -140,7 +140,7 @@ class SettingsAboutController : SettingsController() { return MaterialDialog(activity!!) .title(R.string.update_check_title) .message(text = args.getString(BODY_KEY) ?: "") - .positiveButton(R.string.update_check_confirm) { + .positiveButton(R.string.update_check_confirm) { val appContext = applicationContext if (appContext != null) { // Start download 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 b03823115f..0a5e6dff3f 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 @@ -115,7 +115,6 @@ class SettingsAdvancedController : SettingsController() { activity.toast(cleanupString, Toast.LENGTH_LONG) } } - } private fun clearChapterCache() { 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 393839ce55..3e38f3652d 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 @@ -3,7 +3,11 @@ package eu.kanade.tachiyomi.ui.setting import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.Activity import android.app.Dialog -import android.content.* +import android.content.ActivityNotFoundException +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter import android.net.Uri import android.os.Bundle import android.view.View @@ -17,6 +21,7 @@ import eu.kanade.tachiyomi.data.backup.BackupCreateService import eu.kanade.tachiyomi.data.backup.BackupCreatorJob import eu.kanade.tachiyomi.data.backup.BackupRestoreService import eu.kanade.tachiyomi.data.backup.models.Backup +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.popControllerWithTag @@ -25,7 +30,6 @@ import eu.kanade.tachiyomi.util.system.getFilePicker import eu.kanade.tachiyomi.util.system.registerLocalReceiver import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.util.system.unregisterLocalReceiver -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsBackupController : SettingsController() { @@ -105,10 +109,10 @@ class SettingsBackupController : SettingsController() { onClick { val currentDir = preferences.backupsDirectory().getOrDefault() - try{ + try { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) startActivityForResult(intent, CODE_BACKUP_DIR) - } catch (e: ActivityNotFoundException){ + } catch (e: ActivityNotFoundException) { // Fall back to custom picker on error startActivityForResult(preferences.context.getFilePicker(currentDir), CODE_BACKUP_DIR) } @@ -134,7 +138,6 @@ class SettingsBackupController : SettingsController() { backupNumber.isVisible = it > 0 } } - } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { @@ -210,8 +213,7 @@ class SettingsBackupController : SettingsController() { .title(R.string.pref_create_backup) .message(R.string.backup_choice) .listItemsMultiChoice(items = options, disabledIndices = intArrayOf(0), - initialSelection = intArrayOf(0)) - { _, positions, _ -> + initialSelection = intArrayOf(0)) { _, positions, _ -> var flags = 0 for (i in 1 until positions.size) { when (positions[i]) { @@ -307,5 +309,4 @@ class SettingsBackupController : SettingsController() { const val TAG_CREATING_BACKUP_DIALOG = "CreatingBackupDialog" const val TAG_RESTORING_BACKUP_DIALOG = "RestoringBackupDialog" } - } 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 60a0f4377e..7a6e61d4eb 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 @@ -14,17 +14,17 @@ import com.afollestad.materialdialogs.list.listItemsSingleChoice import com.hippo.unifile.UniFile import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.download.DownloadController import eu.kanade.tachiyomi.util.system.getFilePicker +import java.io.File import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy -import java.io.File -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsDownloadController : SettingsController() { @@ -158,8 +158,7 @@ class SettingsDownloadController : SettingsController() { val selectedIndex = externalDirs.map(File::toString).indexOfFirst { it in currentDir } return MaterialDialog(activity) - .listItemsSingleChoice(items = externalDirs.map { it.path }, initialSelection = selectedIndex) - { _, position, text -> + .listItemsSingleChoice(items = externalDirs.map { it.path }, initialSelection = selectedIndex) { _, position, text -> val target = targetController as? SettingsDownloadController if (position == externalDirs.lastIndex) { target?.customDirectorySelected(currentDir) 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 24cf730de5..fdd66ce45e 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 @@ -4,12 +4,12 @@ import androidx.biometric.BiometricManager import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.BuildConfig import eu.kanade.tachiyomi.R +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.updater.UpdaterJob import eu.kanade.tachiyomi.ui.security.SecureActivityDelegate import eu.kanade.tachiyomi.util.system.LocaleHelper import eu.kanade.tachiyomi.widget.preference.IntListMatPreference -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsGeneralController : SettingsController() { @@ -26,8 +26,8 @@ class SettingsGeneralController : SettingsController() { "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) + locale?.getDisplayName(locale)?.capitalize() + ?: context.getString(R.string.system_default) } defaultValue = "" summary = "%s" @@ -59,7 +59,7 @@ class SettingsGeneralController : SettingsController() { } listPreference(activity) { - key= Keys.dateFormat + key = Keys.dateFormat titleRes = R.string.pref_date_format entryValues = listOf("", "MM/dd/yy", "dd/MM/yy", "yyyy-MM-dd") entries = entryValues.map { value -> 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 5954042787..ab2f1656fa 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 @@ -11,6 +11,7 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.library.LibraryUpdateJob +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController @@ -19,7 +20,6 @@ import eu.kanade.tachiyomi.ui.category.CategoryController import kotlinx.android.synthetic.main.pref_library_columns.view.* import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsLibraryController : SettingsController() { @@ -43,7 +43,6 @@ class SettingsLibraryController : SettingsController() { summaryRes = R.string.pref_remove_articles_summary defaultValue = false } - } val dbCategories = db.getCategories().executeAsBlocking() @@ -235,7 +234,5 @@ class SettingsLibraryController : SettingsController() { } } } - } - } 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 8f4f3f2cb1..33f6771394 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 @@ -141,5 +141,4 @@ class SettingsReaderController : SettingsController() { }.apply { dependency = Keys.readWithVolumeKeys } } } - } 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 dc12f13669..20330edfa8 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 @@ -18,9 +18,9 @@ import eu.kanade.tachiyomi.util.system.LocaleHelper import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory +import java.util.TreeMap import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import java.util.TreeMap class SettingsSourcesController : SettingsController(), SourceLoginDialog.Listener { @@ -35,7 +35,7 @@ class SettingsSourcesController : SettingsController(), private var orderedLangs = listOf() private var langPrefs = mutableListOf>() - private var sourcesByLang:TreeMap> = TreeMap() + private var sourcesByLang: TreeMap> = TreeMap() private var sorting = SourcesSort.Alpha override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { 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 0f94f90453..8cd3b3c4b9 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 @@ -5,16 +5,16 @@ import android.content.Intent import androidx.browser.customtabs.CustomTabsIntent import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R +import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.anilist.AnilistApi -import eu.kanade.tachiyomi.data.track.shikimori.ShikimoriApi import eu.kanade.tachiyomi.data.track.bangumi.BangumiApi +import eu.kanade.tachiyomi.data.track.shikimori.ShikimoriApi import eu.kanade.tachiyomi.util.system.getResourceColor import eu.kanade.tachiyomi.widget.preference.LoginPreference import eu.kanade.tachiyomi.widget.preference.TrackLoginDialog import uy.kohesive.injekt.injectLazy -import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsTrackingController : SettingsController(), TrackLoginDialog.Listener { @@ -77,8 +77,8 @@ class SettingsTrackingController : SettingsController(), } inline fun PreferenceScreen.trackPreference( - service: TrackService, - block: (@DSL LoginPreference).() -> Unit + service: TrackService, + block: (@DSL LoginPreference).() -> Unit ): LoginPreference { return initThenAdd(LoginPreference(context).apply { key = Keys.trackUsername(service.id) @@ -101,5 +101,4 @@ class SettingsTrackingController : SettingsController(), override fun trackDialogClosed(service: TrackService) { updatePreference(service.id) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/track/BangumiLoginActivity.kt b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/track/BangumiLoginActivity.kt index da60c68d1d..2987245515 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/ui/setting/track/BangumiLoginActivity.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/ui/setting/track/BangumiLoginActivity.kt @@ -13,9 +13,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import rx.android.schedulers.AndroidSchedulers -import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy class BangumiLoginActivity : AppCompatActivity() { 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 f1fb4b9aaa..904926e965 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 @@ -15,7 +15,6 @@ import android.webkit.WebChromeClient import android.webkit.WebView import android.widget.LinearLayout import androidx.appcompat.app.AppCompatDelegate -import androidx.core.content.ContextCompat import androidx.core.graphics.ColorUtils import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.SourceManager @@ -25,7 +24,6 @@ import eu.kanade.tachiyomi.util.system.WebViewClientCompat import eu.kanade.tachiyomi.util.system.getResourceColor import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.system.toast -import eu.kanade.tachiyomi.util.view.doOnApplyWindowInsets import eu.kanade.tachiyomi.util.view.invisible import eu.kanade.tachiyomi.util.view.marginBottom import eu.kanade.tachiyomi.util.view.updateLayoutParams @@ -37,14 +35,14 @@ import uy.kohesive.injekt.injectLazy class WebViewActivity : BaseActivity() { private val sourceManager by injectLazy() - private var bundle:Bundle? = null + private var bundle: Bundle? = null companion object { const val SOURCE_KEY = "source_key" const val URL_KEY = "url_key" const val TITLE_KEY = "title_key" - fun newIntent(context: Context, sourceId: Long, url: String, title:String?): Intent { + fun newIntent(context: Context, sourceId: Long, url: String, title: String?): Intent { val intent = Intent(context, WebViewActivity::class.java) intent.putExtra(SOURCE_KEY, sourceId) intent.putExtra(URL_KEY, url) @@ -70,7 +68,7 @@ class WebViewActivity : BaseActivity() { } toolbar.navigationIcon?.setTint(getResourceColor(R.attr.actionBarTintColor)) - val container:ViewGroup = findViewById(R.id.web_view_layout) + val container: ViewGroup = findViewById(R.id.web_view_layout) val content: LinearLayout = findViewById(R.id.web_linear_layout) container.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or @@ -166,7 +164,7 @@ class WebViewActivity : BaseActivity() { override fun onPageCommitVisible(view: WebView?, url: String?) { super.onPageCommitVisible(view, url) - nested_view.scrollTo(0,0) + nested_view.scrollTo(0, 0) } } val marginB = webview.marginBottom @@ -182,8 +180,7 @@ class WebViewActivity : BaseActivity() { webview.settings.javaScriptEnabled = true webview.settings.userAgentString = source.headers["User-Agent"] webview.loadUrl(url, headers) - } - else { + } else { webview.restoreState(bundle) } } @@ -259,7 +256,7 @@ class WebViewActivity : BaseActivity() { override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_web_back -> webview.goBack() - R.id.action_web_forward -> webview.goForward() + R.id.action_web_forward -> webview.goForward() R.id.action_web_share -> shareWebpage() R.id.action_web_browser -> openInBrowser() } 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..f6b85b33e4 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/PreferenceExtensions.kt @@ -1,13 +1,13 @@ package eu.kanade.tachiyomi.util import android.content.SharedPreferences +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flowOn -import kotlin.coroutines.CoroutineContext @ExperimentalCoroutinesApi inline fun SharedPreferences.getKey(key: String, default: T, dispatcher: CoroutineContext = Dispatchers.Default): Flow { diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterRecognition.kt b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterRecognition.kt index 3601905556..21f0efab7b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterRecognition.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterRecognition.kt @@ -140,5 +140,4 @@ object ChapterRecognition { private fun parseAlphaPostFix(alpha: Char): Float { return ("0." + (alpha.toInt() - 96).toString()).toFloat() } - } 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 3f88cc7160..168dc94e03 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 @@ -6,7 +6,8 @@ import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.online.HttpSource -import java.util.* +import java.util.Date +import java.util.TreeSet /** * Helper method for syncing the list of chapters from the source with the ones from the database. @@ -17,10 +18,12 @@ import java.util.* * @param source the source of the chapters. * @return a pair of new insertions and deletions. */ -fun syncChaptersWithSource(db: DatabaseHelper, - rawSourceChapters: List, - manga: Manga, - source: Source): Pair, List> { +fun syncChaptersWithSource( + db: DatabaseHelper, + rawSourceChapters: List, + manga: Manga, + source: Source +): Pair, List> { if (rawSourceChapters.isEmpty()) { throw Exception("No chapters found") @@ -50,7 +53,7 @@ fun syncChaptersWithSource(db: DatabaseHelper, if (dbChapter == null) { toAdd.add(sourceChapter) } else { - //this forces metadata update for the main viewable things in the chapter list + // this forces metadata update for the main viewable things in the chapter list if (source is HttpSource) { source.prepareNewChapter(sourceChapter, manga) } @@ -139,15 +142,14 @@ fun syncChaptersWithSource(db: DatabaseHelper, if (dateFetch == 0L) { if (toAdd.isNotEmpty()) manga.last_update = Date().time - } - else manga.last_update = dateFetch + } else manga.last_update = dateFetch db.updateLastUpdated(manga).executeAsBlocking() } return Pair(toAdd.subtract(readded).toList(), toDelete.subtract(readded).toList()) } -//checks if the chapter in db needs updated +// 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 || diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt b/app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt index 7cdef09b13..a14825a4b5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt @@ -1,15 +1,15 @@ package eu.kanade.tachiyomi.util.lang +import java.util.concurrent.TimeUnit.MILLISECONDS import rx.Observable import rx.Scheduler import rx.functions.Func1 import rx.schedulers.Schedulers -import java.util.concurrent.TimeUnit.MILLISECONDS class RetryWithDelay( - private val maxRetries: Int = 1, - private val retryStrategy: (Int) -> Int = { 1000 }, - private val scheduler: Scheduler = Schedulers.computation() + private val maxRetries: Int = 1, + private val retryStrategy: (Int) -> Int = { 1000 }, + private val scheduler: Scheduler = Schedulers.computation() ) : Func1, Observable<*>> { private var retryCount = 0 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 d9f1772691..4ad9f57b4c 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 @@ -114,4 +114,3 @@ object DiskUtil { } } } - diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/storage/EpubFile.kt b/app/src/main/java/eu/kanade/tachiyomi/util/storage/EpubFile.kt index 4727e56351..0763abb2e2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/storage/EpubFile.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/storage/EpubFile.kt @@ -1,12 +1,12 @@ package eu.kanade.tachiyomi.util.storage -import org.jsoup.Jsoup -import org.jsoup.nodes.Document import java.io.Closeable import java.io.File import java.io.InputStream import java.util.zip.ZipEntry import java.util.zip.ZipFile +import org.jsoup.Jsoup +import org.jsoup.nodes.Document /** * Wrapper over ZipFile to load files in epub format. @@ -113,5 +113,4 @@ class EpubFile(file: File) : Closeable { } } } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/storage/FileExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/storage/FileExtensions.kt index 2b2ad5843c..53523c6d4c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/storage/FileExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/storage/FileExtensions.kt @@ -17,4 +17,3 @@ fun File.getUriCompat(context: Context): Uri { FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", this) else Uri.fromFile(this) } - diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/storage/OkioExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/storage/OkioExtensions.kt index 85bd0c3245..0eac12d482 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/storage/OkioExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/storage/OkioExtensions.kt @@ -1,11 +1,10 @@ package eu.kanade.tachiyomi.util.storage -import okio.BufferedSource -import okio.Okio -import okio.buffer -import okio.sink import java.io.File import java.io.OutputStream +import okio.BufferedSource +import okio.buffer +import okio.sink /** * Saves the given source to a file and closes it. Directories will be created if needed. 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 4abcf2eb6b..45c160cb47 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 @@ -74,8 +74,8 @@ fun Context.getFilePicker(currentDir: String): Intent { * @param permission the permission to check. * @return true if it has permissions. */ -fun Context.hasPermission(permission: String) - = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED +fun Context.hasPermission(permission: String) = + ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED /** * Returns the color for the given attribute. diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/CoroutinesExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/CoroutinesExtensions.kt index 2753390544..b3ef44617f 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/CoroutinesExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/CoroutinesExtensions.kt @@ -2,11 +2,10 @@ package eu.kanade.tachiyomi.util.system import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.Job import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.Job import kotlinx.coroutines.launch -import kotlin.coroutines.EmptyCoroutineContext fun launchUI(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT, block) 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 0f1ca55bf6..3ab159237c 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 @@ -2,7 +2,9 @@ package eu.kanade.tachiyomi.util.system import android.graphics.Bitmap import android.graphics.Color -import android.graphics.drawable.* +import android.graphics.drawable.ColorDrawable +import android.graphics.drawable.Drawable +import android.graphics.drawable.GradientDrawable import java.io.InputStream import java.net.URLConnection import kotlin.math.abs @@ -48,7 +50,7 @@ object ImageUtil { if (bytes.compareWith("RIFF".toByteArray())) { return ImageType.WEBP } - } catch(e: Exception) { + } catch (e: Exception) { } return null } @@ -73,8 +75,8 @@ object ImageUtil { val botLeftIsDark = isDark(image.getPixel(left, bot)) val botRightIsDark = isDark(image.getPixel(right, bot)) - var darkBG = (topLeftIsDark && (botLeftIsDark || botRightIsDark || topRightIsDark || midLeftIsDark || topMidIsDark)) - || (topRightIsDark && (botRightIsDark || botLeftIsDark || midRightIsDark || topMidIsDark)) + var darkBG = (topLeftIsDark && (botLeftIsDark || botRightIsDark || topRightIsDark || midLeftIsDark || 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)) && @@ -114,7 +116,7 @@ object ImageUtil { val notOffset = x == left || x == right for ((index, y) in (0 until image.height step image.height / 25).withIndex()) { val pixel = image.getPixel(x, y) - val pixelOff = image.getPixel(x + (if (x < image.width/2) -offsetX else offsetX), y) + val pixelOff = image.getPixel(x + (if (x < image.width / 2) -offsetX else offsetX), y) if (isWhite(pixel)) { whitePixelsStreak++ whitePixels++ @@ -139,7 +141,6 @@ object ImageUtil { if (blackPixelsStreak > 6 && blackPixelsStreak >= index - 1) topBlackStreak = blackPixelsStreak blackPixelsStreak = 0 - } if (blackPixelsStreak > 6) botBlackStreak = blackPixelsStreak @@ -187,14 +188,14 @@ object ImageUtil { 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))) + 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))) + 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) @@ -206,7 +207,7 @@ object ImageUtil { } private fun pixelIsClose(color1: Int, color2: Int): Boolean { - return abs(Color.red(color1) - Color.red(color2)) < 30 && + 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 } @@ -236,5 +237,4 @@ object ImageUtil { GIF("image/gif", "gif"), WEBP("image/webp", "webp") } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/LocaleHelper.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/LocaleHelper.kt index 420fb135ae..154f5c40b0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/LocaleHelper.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/LocaleHelper.kt @@ -7,8 +7,8 @@ import android.os.Build import android.view.ContextThemeWrapper import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper -import uy.kohesive.injekt.injectLazy import java.util.Locale +import uy.kohesive.injekt.injectLazy /** * Utility class to change the application's language in runtime. @@ -141,5 +141,4 @@ object LocaleHelper { } return newConfig } - } 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 a1d583ef89..4e2c6ddada 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 @@ -1,10 +1,10 @@ package eu.kanade.tachiyomi.util.system +import kotlin.coroutines.resumeWithException import kotlinx.coroutines.suspendCancellableCoroutine import rx.Scheduler import rx.Single import rx.Subscription -import kotlin.coroutines.resumeWithException suspend fun Single.await(subscribeOn: Scheduler? = null): T { return suspendCancellableCoroutine { continuation -> @@ -23,4 +23,4 @@ suspend fun Single.await(subscribeOn: Scheduler? = null): T { sub.unsubscribe() } } -} \ No newline at end of file +} 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 7e1f840cdc..0699214c88 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 @@ -2,7 +2,11 @@ package eu.kanade.tachiyomi.util.system import android.annotation.TargetApi import android.os.Build -import android.webkit.* +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient @Suppress("OverridingDeprecatedMember") abstract class WebViewClientCompat : WebViewClient() { @@ -16,18 +20,18 @@ abstract class WebViewClientCompat : WebViewClient() { } open fun onReceivedErrorCompat( - view: WebView, - errorCode: Int, - description: String?, - failingUrl: String, - isMainFrame: Boolean) { - + view: WebView, + errorCode: Int, + description: String?, + failingUrl: String, + isMainFrame: Boolean + ) { } @TargetApi(Build.VERSION_CODES.N) final override fun shouldOverrideUrlLoading( - view: WebView, - request: WebResourceRequest + view: WebView, + request: WebResourceRequest ): Boolean { return shouldOverrideUrlCompat(view, request.url.toString()) } @@ -37,46 +41,45 @@ abstract class WebViewClientCompat : WebViewClient() { } final override fun shouldInterceptRequest( - view: WebView, - request: WebResourceRequest + view: WebView, + request: WebResourceRequest ): WebResourceResponse? { return shouldInterceptRequestCompat(view, request.url.toString()) } final override fun shouldInterceptRequest( - view: WebView, - url: String + view: WebView, + url: String ): WebResourceResponse? { return shouldInterceptRequestCompat(view, url) } @TargetApi(Build.VERSION_CODES.M) final override fun onReceivedError( - view: WebView, - request: WebResourceRequest, - error: WebResourceError + view: WebView, + request: WebResourceRequest, + error: WebResourceError ) { onReceivedErrorCompat(view, error.errorCode, error.description?.toString(), request.url.toString(), request.isForMainFrame) } final override fun onReceivedError( - view: WebView, - errorCode: Int, - description: String?, - failingUrl: String + view: WebView, + errorCode: Int, + description: String?, + failingUrl: String ) { onReceivedErrorCompat(view, errorCode, description, failingUrl, failingUrl == view.url) } @TargetApi(Build.VERSION_CODES.M) final override fun onReceivedHttpError( - view: WebView, - request: WebResourceRequest, - error: WebResourceResponse + view: WebView, + request: WebResourceRequest, + error: WebResourceResponse ) { onReceivedErrorCompat(view, error.statusCode, error.reasonPhrase, request.url .toString(), request.isForMainFrame) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/view/DeferredField.kt b/app/src/main/java/eu/kanade/tachiyomi/util/view/DeferredField.kt index 1283c6a86a..9fa71df28b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/view/DeferredField.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/view/DeferredField.kt @@ -1,6 +1,5 @@ package eu.kanade.tachiyomi.util.view - import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/view/ImageViewExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/view/ImageViewExtensions.kt index e27f28dd5e..69335bc5b5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/view/ImageViewExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/view/ImageViewExtensions.kt @@ -1,8 +1,8 @@ package eu.kanade.tachiyomi.util.view +import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat -import android.widget.ImageView /** * Set a vector on a [ImageView]. 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 0c56b76d5d..965178e407 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 @@ -35,11 +35,11 @@ import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.system.dpToPx import eu.kanade.tachiyomi.util.system.getResourceColor +import kotlin.math.abs +import kotlin.math.min import kotlinx.android.synthetic.main.main_activity.* import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -import kotlin.math.abs -import kotlin.math.min /** * Returns coordinates of view. @@ -56,19 +56,22 @@ fun View.getCoordinates() = Point((left + right) / 2, (top + bottom) / 2) * @param length the duration of the snack. * @param f a function to execute in the snack, allowing for example to define a custom action. */ -fun View.snack(message: String, length: Int = Snackbar.LENGTH_SHORT, f: (Snackbar.() -> -Unit)? = null): Snackbar { +fun View.snack( + message: String, + length: Int = Snackbar.LENGTH_SHORT, + f: (Snackbar.() -> Unit)? = null +): Snackbar { val snack = Snackbar.make(this, message, length) - /* when { - Build.VERSION.SDK_INT >= 23 -> { - val leftM = if (this is CoordinatorLayout) 0 else rootWindowInsets.systemWindowInsetLeft - val rightM = if (this is CoordinatorLayout) 0 - else rootWindowInsets.systemWindowInsetRight - snack.config(context, rootWindowInsets - .systemWindowInsetBottom, rightM, leftM) - } - else -> snack.config(context) - }*/ + /* when { + Build.VERSION.SDK_INT >= 23 -> { + val leftM = if (this is CoordinatorLayout) 0 else rootWindowInsets.systemWindowInsetLeft + val rightM = if (this is CoordinatorLayout) 0 + else rootWindowInsets.systemWindowInsetRight + snack.config(context, rootWindowInsets + .systemWindowInsetBottom, rightM, leftM) + } + else -> snack.config(context) + }*/ if (f != null) { snack.f() } @@ -82,28 +85,24 @@ Unit)? = null): Snackbar { button?.setTextColor(context.getResourceColor(R.attr.snackbar_text)) snack.config(context) } - // if (Build.VERSION.SDK_INT < 23) { -/* val view = if (this !is CoordinatorLayout) this else snack.view - view.doOnApplyWindowInsets { _, insets, _ -> - snack.view.updateLayoutParams { - bottomMargin = 12 + insets.systemWindowInsetBottom - } - }*/ - /*} - else { - snack.view.doOnApplyWindowInsets { _,_,_ -> } - }*/ snack.show() return snack } -fun View.snack(resource: Int, length: Int = Snackbar.LENGTH_SHORT, f: (Snackbar.() -> -Unit)? = null): Snackbar { +fun View.snack( + resource: Int, + length: Int = Snackbar.LENGTH_SHORT, + f: (Snackbar.() -> Unit)? = null +): Snackbar { return snack(context.getString(resource), length, f) } -fun Snackbar.config(context: Context, bottomMargin: Int = 0, rightMargin: Int = 0, leftMargin: -Int = 0) { +fun Snackbar.config( + context: Context, + bottomMargin: Int = 0, + rightMargin: Int = 0, + leftMargin: Int = 0 +) { val params = this.view.layoutParams as ViewGroup.MarginLayoutParams params.setMargins(12 + leftMargin, 12, 12 + rightMargin, 12 + bottomMargin) this.view.layoutParams = params @@ -143,16 +142,15 @@ inline fun View.visibleIf(show: Boolean) { * @param text text of [TextDrawable] * @param random random color */ -fun View.getRound(text: String, random : Boolean = true): TextDrawable { +fun View.getRound(text: String, random: Boolean = true): TextDrawable { val size = min(this.width, this.height) - return TextDrawable.builder() - .beginConfig() - .width(size) - .height(size) - .textColor(Color.WHITE) - .useFont(Typeface.DEFAULT) - .endConfig() - .buildRound(text, if (random) ColorGenerator.MATERIAL.randomColor else ColorGenerator.MATERIAL.getColor(text)) + return TextDrawable.builder().beginConfig().width(size).height(size).textColor(Color.WHITE) + .useFont(Typeface.DEFAULT).endConfig().buildRound( + text, + if (random) ColorGenerator.MATERIAL.randomColor else ColorGenerator.MATERIAL.getColor( + text + ) + ) } inline val View.marginTop: Int @@ -170,7 +168,7 @@ inline val View.marginLeft: Int object RecyclerWindowInsetsListener : View.OnApplyWindowInsetsListener { override fun onApplyWindowInsets(v: View, insets: WindowInsets): WindowInsets { v.updatePaddingRelative(bottom = insets.systemWindowInsetBottom) - //v.updatePaddingRelative(bottom = v.paddingBottom + insets.systemWindowInsetBottom) + // v.updatePaddingRelative(bottom = v.paddingBottom + insets.systemWindowInsetBottom) return insets } } @@ -190,7 +188,7 @@ object ControllerViewWindowInsetsListener : View.OnApplyWindowInsetsListener { object HeightTopWindowInsetsListener : View.OnApplyWindowInsetsListener { override fun onApplyWindowInsets(v: View, insets: WindowInsets): WindowInsets { val topInset = insets.systemWindowInsetTop - v.setPadding(0,topInset,0,0) + v.setPadding(0, topInset, 0, 0) if (v.layoutParams.height != topInset) { v.layoutParams.height = topInset v.requestLayout() @@ -215,40 +213,36 @@ 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 { - val attrsArray = intArrayOf(android.R.attr.actionBarSize) - val array = view.context.obtainStyledAttributes(attrsArray) - //topMargin = insets.systemWindowInsetTop + array - //.getDimensionPixelSize(0, 0) - bottomMargin = bottomNav.height - array.recycle() - } - insets + viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { + override fun onGlobalLayout() { + if (bottomNav.height > 0) { + viewTreeObserver.removeOnGlobalLayoutListener(this) + setOnApplyWindowInsetsListener { view, insets -> + view.updateLayoutParams { + val attrsArray = intArrayOf(android.R.attr.actionBarSize) + val array = view.context.obtainStyledAttributes(attrsArray) + // topMargin = insets.systemWindowInsetTop + array + // .getDimensionPixelSize(0, 0) + bottomMargin = bottomNav.height + array.recycle() } - requestApplyInsetsWhenAttached() + insets } + requestApplyInsetsWhenAttached() } } - ) + }) } fun View.requestApplyInsetsWhenAttached() { @@ -280,8 +274,14 @@ inline fun View.updatePadding( setPadding(left, top, right, bottom) } -private fun createStateForView(view: View) = ViewPaddingState(view.paddingLeft, - view.paddingTop, view.paddingRight, view.paddingBottom, view.paddingStart, view.paddingEnd) +private fun createStateForView(view: View) = ViewPaddingState( + view.paddingLeft, + view.paddingTop, + view.paddingRight, + view.paddingBottom, + view.paddingStart, + view.paddingEnd +) data class ViewPaddingState( val left: Int, @@ -292,13 +292,16 @@ data class ViewPaddingState( val end: Int ) - -fun Controller.setOnQueryTextChangeListener(searchView: SearchView, onlyOnSubmit:Boolean = false, - f: (text: String?) -> Boolean) { +fun Controller.setOnQueryTextChangeListener( + searchView: SearchView, + onlyOnSubmit: Boolean = false, + f: (text: String?) -> Boolean +) { searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String?): Boolean { - if (!onlyOnSubmit && router.backstack.lastOrNull()?.controller() == - this@setOnQueryTextChangeListener) { + if (!onlyOnSubmit && router.backstack.lastOrNull() + ?.controller() == this@setOnQueryTextChangeListener + ) { return f(newText) } return false @@ -317,7 +320,8 @@ fun Controller.scrollViewWith( recycler: RecyclerView, padBottom: Boolean = false, swipeRefreshLayout: SwipeRefreshLayout? = null, - afterInsets: ((WindowInsets) -> Unit)? = null) { + afterInsets: ((WindowInsets) -> Unit)? = null +) { var statusBarHeight = -1 activity?.appbar?.y = 0f val attrsArray = intArrayOf(android.R.attr.actionBarSize) @@ -339,15 +343,12 @@ fun Controller.scrollViewWith( 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) { + if (router?.backstack?.lastOrNull() + ?.controller() == this@scrollViewWith && statusBarHeight > -1 && activity != null && activity!!.appbar.height > 0 + ) { activity!!.appbar.y -= dy activity!!.appbar.y = clamp( - activity!!.appbar.y, - -activity!!.appbar.height.toFloat(), - 0f + activity!!.appbar.y, -activity!!.appbar.height.toFloat(), 0f ) } } @@ -355,22 +356,20 @@ fun Controller.scrollViewWith( 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) { + if (router?.backstack?.lastOrNull() + ?.controller() == this@scrollViewWith && statusBarHeight > -1 && activity != null && activity!!.appbar.height > 0 + ) { 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.layoutManager as LinearLayoutManager) - .findFirstVisibleItemPosition() < 2 - activity!!.appbar.animate() - .y(if (closerToTop && !atTop) - (-activity!!.appbar.height.toFloat()) - else 0f) - .setDuration(shortAnimationDuration.toLong()) - .start() + val closerToTop = abs(activity!!.appbar.y) - halfWay > 0 + val atTop = + (recycler.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition() < 2 + activity!!.appbar.animate().y( + if (closerToTop && !atTop) (-activity!!.appbar.height.toFloat()) + else 0f + ).setDuration(shortAnimationDuration.toLong()).start() } } } @@ -386,42 +385,42 @@ inline fun View.updatePaddingRelative( setPaddingRelative(start, top, end, bottom) } -fun BottomSheetDialog.setEdgeToEdge(activity: Activity, layout: View, contentView: View, - setTopMargin: Boolean) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) - window?.setBackgroundDrawable(null) - val currentNightMode = activity.resources.configuration.uiMode and Configuration - .UI_MODE_NIGHT_MASK - if (currentNightMode == Configuration.UI_MODE_NIGHT_NO) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - if (activity.window.decorView.rootWindowInsets.systemWindowInsetRight == 0 && - activity.window.decorView.rootWindowInsets.systemWindowInsetLeft == 0) - window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR - } - else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && layout is ConstraintLayout) { - val nView = View(context) - val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom - val params = ConstraintLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, height +fun BottomSheetDialog.setEdgeToEdge( + activity: Activity, + layout: View, + contentView: View, + setTopMargin: Boolean +) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) window?.setBackgroundDrawable(null) + val currentNightMode = + activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK + if (currentNightMode == Configuration.UI_MODE_NIGHT_NO) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + if (activity.window.decorView.rootWindowInsets.systemWindowInsetRight == 0 && activity.window.decorView.rootWindowInsets.systemWindowInsetLeft == 0) window?.decorView?.systemUiVisibility = + View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && layout is ConstraintLayout) { + val nView = View(context) + val height = activity.window.decorView.rootWindowInsets.systemWindowInsetBottom + val params = ConstraintLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, height + ) + params.bottomToBottom = layout.id + params.startToStart = layout.id + params.endToEnd = layout.id + nView.layoutParams = params + nView.background = GradientDrawable( + GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf( + ColorUtils.setAlphaComponent(Color.BLACK, 179), Color.TRANSPARENT ) - params.bottomToBottom = layout.id - params.startToStart = layout.id - params.endToEnd = layout.id - nView.layoutParams = params - nView.background = GradientDrawable( - GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf( - ColorUtils.setAlphaComponent(Color.BLACK, 179), Color.TRANSPARENT - ) - ) - layout.addView(nView) - } + ) + layout.addView(nView) + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - //window?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) + // window?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) window?.findViewById(com.google.android.material.R.id.container)?.fitsSystemWindows = false contentView.updateLayoutParams { - if (setTopMargin) - topMargin = activity.window.decorView.rootWindowInsets.systemWindowInsetTop + if (setTopMargin) topMargin = + activity.window.decorView.rootWindowInsets.systemWindowInsetTop leftMargin = activity.window.decorView.rootWindowInsets.systemWindowInsetLeft rightMargin = activity.window.decorView.rootWindowInsets.systemWindowInsetRight } @@ -432,8 +431,8 @@ fun setBottomEdge(view: View, activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val marginB = view.marginBottom view.updateLayoutParams { - bottomMargin = marginB + - activity.window.decorView.rootWindowInsets.systemWindowInsetBottom + bottomMargin = + marginB + activity.window.decorView.rootWindowInsets.systemWindowInsetBottom } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewGroupExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewGroupExtensions.kt index 1da0b4d986..64c71200a0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewGroupExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/view/ViewGroupExtensions.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.util.view -import androidx.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.annotation.LayoutRes /** * Extension method to inflate a view directly from its parent. 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 53a8ab4285..28836aaacd 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt @@ -16,11 +16,10 @@ class AutofitRecyclerView @JvmOverloads constructor(context: Context, attrs: Att if (value > 0 && measuredWidth > 0) { val count = max(1, measuredWidth / value) spanCount = count - //manager.spanCount = count + // manager.spanCount = count } } - var spanCount = 0 set(value) { field = value @@ -46,7 +45,7 @@ class AutofitRecyclerView @JvmOverloads constructor(context: Context, attrs: Att layoutManager = manager } - private fun getTempSpan():Int { + private fun getTempSpan(): Int { if (spanCount == 0 && columnWidth > 0) { return max(1, measuredWidth / columnWidth) } @@ -60,5 +59,4 @@ class AutofitRecyclerView @JvmOverloads constructor(context: Context, attrs: Att spanCount = count } } - } 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 ccefd385c4..2f71a21077 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/CustomLayoutPicker.kt @@ -1,7 +1,7 @@ package eu.kanade.tachiyomi.widget -import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView import com.nononsenseapps.filepicker.AbstractFilePickerFragment import com.nononsenseapps.filepicker.FilePickerActivity import com.nononsenseapps.filepicker.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 b6195a7d9a..f85efff784 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCheckboxView.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.widget import android.content.Context -import androidx.annotation.StringRes import android.util.AttributeSet import android.widget.LinearLayout +import androidx.annotation.StringRes import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.view.inflate import kotlinx.android.synthetic.main.common_dialog_with_checkbox.view.checkbox_option @@ -16,11 +16,11 @@ class DialogCheckboxView @JvmOverloads constructor(context: Context, attrs: Attr addView(inflate(R.layout.common_dialog_with_checkbox)) } - fun setDescription(@StringRes id: Int){ + fun setDescription(@StringRes id: Int) { description.text = context.getString(id) } - fun setOptionDescription(@StringRes id: Int){ + fun setOptionDescription(@StringRes id: Int) { checkbox_option.text = context.getString(id) } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCustomDownloadView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCustomDownloadView.kt index 883755cff6..5e05cdb5c9 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCustomDownloadView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/DialogCustomDownloadView.kt @@ -37,7 +37,6 @@ class DialogCustomDownloadView @JvmOverloads constructor(context: Context, attrs addView(inflate(R.layout.download_custom_amount)) } - /** * Called when view is added * diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/DrawerSwipeCloseListener.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/DrawerSwipeCloseListener.kt index e9a6696a5f..dad74a771a 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/DrawerSwipeCloseListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/DrawerSwipeCloseListener.kt @@ -1,12 +1,12 @@ package eu.kanade.tachiyomi.widget -import androidx.drawerlayout.widget.DrawerLayout import android.view.View import android.view.ViewGroup +import androidx.drawerlayout.widget.DrawerLayout class DrawerSwipeCloseListener( - private val drawer: androidx.drawerlayout.widget.DrawerLayout, - private val navigationView: ViewGroup + private val drawer: androidx.drawerlayout.widget.DrawerLayout, + private val navigationView: ViewGroup ) : androidx.drawerlayout.widget.DrawerLayout.SimpleDrawerListener() { override fun onDrawerOpened(drawerView: View) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/ElevationAppBarLayout.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/ElevationAppBarLayout.kt deleted file mode 100644 index c2b6ccbcbb..0000000000 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/ElevationAppBarLayout.kt +++ /dev/null @@ -1,34 +0,0 @@ -package eu.kanade.tachiyomi.widget - -import android.animation.StateListAnimator -import android.content.Context -import android.util.AttributeSet -import com.google.android.material.appbar.AppBarLayout - -class ElevationAppBarLayout @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null -) : AppBarLayout(context, attrs) { - - private var origStateAnimator: StateListAnimator? = null - private var origElevation: Float - - init { - origStateAnimator = stateListAnimator - origElevation = elevation - } - - fun enableElevation() { - /* if (stateListAnimator == null) { - stateListAnimator = origStateAnimator - elevation = origElevation - }*/ - } - - fun disableElevation() { - // stateListAnimator = null - //elevation = 0f - //translationZ = 0.1f.dpToPx - } - -} 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 95d5c1f273..0e1e2977ff 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/EmptyView.kt @@ -11,7 +11,7 @@ import kotlinx.android.synthetic.main.common_view_empty.view.image_view import kotlinx.android.synthetic.main.common_view_empty.view.text_label class EmptyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - RelativeLayout (context, attrs) { + RelativeLayout(context, attrs) { init { inflate(context, R.layout.common_view_empty, this) diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/ExtendedNavigationView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/ExtendedNavigationView.kt index c06759b304..e5e5bb9ff2 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/ExtendedNavigationView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/ExtendedNavigationView.kt @@ -2,13 +2,13 @@ package eu.kanade.tachiyomi.widget import android.content.Context import android.graphics.drawable.Drawable -import androidx.annotation.CallSuper -import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat -import androidx.core.content.ContextCompat -import androidx.recyclerview.widget.RecyclerView import android.util.AttributeSet import android.view.View import android.view.ViewGroup +import androidx.annotation.CallSuper +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView +import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.getResourceColor @@ -17,10 +17,11 @@ import eu.kanade.tachiyomi.util.system.getResourceColor * inflation and allowing customizable items (multiple selections, custom views, etc). */ open class ExtendedNavigationView @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null, - defStyleAttr: Int = 0) - : SimpleNavigationView(context, attrs, defStyleAttr) { + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0 +) : + SimpleNavigationView(context, attrs, defStyleAttr) { /** * Every item of the nav view. Generic items must belong to this list, custom items could be @@ -46,15 +47,15 @@ open class ExtendedNavigationView @JvmOverloads constructor( /** * A checkbox belonging to a group. The group must handle selections and restrictions. */ - class CheckboxGroup(resTitle: Int, override val group: Group, checked: Boolean = false) - : Checkbox(resTitle, checked), GroupedItem + class CheckboxGroup(resTitle: Int, override val group: Group, checked: Boolean = false) : + Checkbox(resTitle, checked), GroupedItem /** * A radio belonging to a group (a sole radio makes no sense). The group must handle * selections and restrictions. */ - class Radio(val resTitle: Int, override val group: Group, var checked: Boolean = false) - : Item(), GroupedItem + class Radio(val resTitle: Int, override val group: Group, var checked: Boolean = false) : + Item(), GroupedItem /** * An item with which needs more than two states (selected/deselected). @@ -95,8 +96,8 @@ open class ExtendedNavigationView @JvmOverloads constructor( * An item with which needs more than two states (selected/deselected) belonging to a group. * The group must handle selections and restrictions. */ - abstract class MultiStateGroup(resTitle: Int, override val group: Group, state: Int = 0) - : MultiState(resTitle, state), GroupedItem + abstract class MultiStateGroup(resTitle: Int, override val group: Group, state: Int = 0) : + MultiState(resTitle, state), GroupedItem /** * A multistate item for sorting lists (unselected, ascending, descending). @@ -117,7 +118,6 @@ open class ExtendedNavigationView @JvmOverloads constructor( else -> null } } - } class TriStateGroup(resId: Int, group: Group) : MultiStateGroup(resId, group) { @@ -130,7 +130,7 @@ open class ExtendedNavigationView @JvmOverloads constructor( } override fun getStateDrawable(context: Context): Drawable? { - return when(state) { + return when (state) { STATE_INCLUDE -> tintVector(context, R.drawable.ic_check_box_24dp) STATE_EXCLUDE -> tintVector(context, R.drawable.ic_check_box_x_24dp, android.R.attr.textColorSecondary) @@ -185,7 +185,6 @@ open class ExtendedNavigationView @JvmOverloads constructor( * selections of its items. */ fun onItemClicked(item: Item) - } /** @@ -264,7 +263,5 @@ open class ExtendedNavigationView @JvmOverloads constructor( } abstract fun onItemClicked(item: Item) - } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/FABMoveBehaviour.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/FABMoveBehaviour.kt index 6cee334986..0beb02e4e0 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/FABMoveBehaviour.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/FABMoveBehaviour.kt @@ -38,4 +38,4 @@ class FABMoveBehaviour(context: Context, attrs: AttributeSet) : } return minOffset } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/IgnoreFirstSpinnerListener.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/IgnoreFirstSpinnerListener.kt index eab856562a..107e6fa558 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/IgnoreFirstSpinnerListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/IgnoreFirstSpinnerListener.kt @@ -4,7 +4,7 @@ import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener -class IgnoreFirstSpinnerListener(private val block: (Int) -> Unit): OnItemSelectedListener { +class IgnoreFirstSpinnerListener(private val block: (Int) -> Unit) : OnItemSelectedListener { private var firstEvent = true @@ -17,6 +17,5 @@ class IgnoreFirstSpinnerListener(private val block: (Int) -> Unit): OnItemSelect } override fun onNothingSelected(parent: AdapterView<*>?) { - } -} \ No newline at end of file +} 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 07adb8d0c5..bdc7d79d14 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/MinMaxNumberPicker.kt @@ -20,4 +20,3 @@ class MinMaxNumberPicker @JvmOverloads constructor(context: Context, attrs: Attr } } } - 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 30e0eac7c5..9ab0cc9c11 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/NegativeSeekBar.kt @@ -7,7 +7,6 @@ import android.widget.SeekBar import eu.kanade.tachiyomi.R import kotlin.math.abs - class NegativeSeekBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SeekBar(context, attrs) { @@ -66,5 +65,4 @@ class NegativeSeekBar @JvmOverloads constructor(context: Context, attrs: Attribu super.onRestoreInstanceState(state) super.setProgress(origProgress) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/OutlineSpan.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/OutlineSpan.kt index 79b2057778..b7ab3a82fb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/OutlineSpan.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/OutlineSpan.kt @@ -12,30 +12,30 @@ import androidx.annotation.Dimension * A class that draws the outlines of a text when given a stroke color and stroke width. */ class OutlineSpan( - @ColorInt private val strokeColor: Int, - @Dimension private val strokeWidth: Float + @ColorInt private val strokeColor: Int, + @Dimension private val strokeWidth: Float ) : ReplacementSpan() { override fun getSize( - paint: Paint, - text: CharSequence, - start: Int, - end: Int, - fm: Paint.FontMetricsInt? + paint: Paint, + text: CharSequence, + start: Int, + end: Int, + fm: Paint.FontMetricsInt? ): Int { return paint.measureText(text.toString().substring(start until end)).toInt() } override fun draw( - canvas: Canvas, - text: CharSequence, - start: Int, - end: Int, - x: Float, - top: Int, - y: Int, - bottom: Int, - paint: Paint + canvas: Canvas, + text: CharSequence, + start: Int, + end: Int, + x: Float, + top: Int, + y: Int, + bottom: Int, + paint: Paint ) { val originTextColor = paint.color @@ -53,5 +53,4 @@ class OutlineSpan( canvas.drawText(text, start, end, x, y.toFloat(), paint) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/PTSansTextView.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/PTSansTextView.kt index 8bbf4ad243..be672fde1b 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/PTSansTextView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/PTSansTextView.kt @@ -4,13 +4,12 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Typeface import android.util.AttributeSet -import android.widget.TextView +import androidx.appcompat.widget.AppCompatTextView import eu.kanade.tachiyomi.R -import java.util.* - +import java.util.HashMap class PTSansTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : - TextView(context, attrs) { + AppCompatTextView(context, attrs) { companion object { const val PTSANS_NARROW = 0 @@ -43,5 +42,4 @@ class PTSansTextView @JvmOverloads constructor(context: Context, attrs: Attribut super.onDraw(canvas) super.onDraw(canvas) } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/PreCachingLayoutManager.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/PreCachingLayoutManager.kt index 9469c5e8cd..5f9be21630 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/PreCachingLayoutManager.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/PreCachingLayoutManager.kt @@ -22,5 +22,4 @@ class PreCachingLayoutManager(context: Context) : androidx.recyclerview.widget.L } return DEFAULT_EXTRA_LAYOUT_SPACE } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/RecyclerViewPagerAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/RecyclerViewPagerAdapter.kt index f644e3fdd5..2e1d51c2f5 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/RecyclerViewPagerAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/RecyclerViewPagerAdapter.kt @@ -3,7 +3,7 @@ package eu.kanade.tachiyomi.widget import android.view.View import android.view.ViewGroup import com.nightlynexus.viewstatepageradapter.ViewStatePagerAdapter -import java.util.* +import java.util.Stack abstract class RecyclerViewPagerAdapter : ViewStatePagerAdapter() { @@ -31,6 +31,4 @@ abstract class RecyclerViewPagerAdapter : ViewStatePagerAdapter() { recycleView(view, position) if (recycle) pool.push(view) } - - -} \ No newline at end of file +} 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 a78a678034..9a79b0c68c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/RevealAnimationView.kt @@ -64,5 +64,4 @@ class RevealAnimationView @JvmOverloads constructor(context: Context, attrs: Att anim.start() return true } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleAnimationListener.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleAnimationListener.kt index 12a2b4ef22..853e8ba0bf 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleAnimationListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleAnimationListener.kt @@ -8,4 +8,4 @@ open class SimpleAnimationListener : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) {} override fun onAnimationStart(animation: Animation) {} -} \ No newline at end of file +} 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 49e396efd6..46b8c27ead 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleNavigationView.kt @@ -16,17 +16,18 @@ import androidx.core.view.ViewCompat import com.google.android.material.R import com.google.android.material.internal.ScrimInsetsFrameLayout import com.google.android.material.textfield.TextInputLayout +import eu.kanade.tachiyomi.R as TR import eu.kanade.tachiyomi.util.view.inflate import kotlin.math.min -import eu.kanade.tachiyomi.R as TR @Suppress("LeakingThis") @SuppressLint("PrivateResource", "RestrictedApi") open class SimpleNavigationView @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null, - defStyleAttr: Int = 0) - : ScrimInsetsFrameLayout(context, attrs, defStyleAttr) { + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0 +) : + ScrimInsetsFrameLayout(context, attrs, defStyleAttr) { /** * Max width of the navigation view. @@ -87,19 +88,18 @@ open class SimpleNavigationView @JvmOverloads constructor( /** * Separator view holder. */ - class SeparatorHolder(parent: ViewGroup) - : Holder(parent.inflate(R.layout.design_navigation_item_separator)) + class SeparatorHolder(parent: ViewGroup) : + Holder(parent.inflate(R.layout.design_navigation_item_separator)) /** * Header view holder. */ - class HeaderHolder(parent: ViewGroup) - : Holder(parent.inflate(TR.layout.navigation_view_group)){ + class HeaderHolder(parent: ViewGroup) : + Holder(parent.inflate(TR.layout.navigation_view_group)) { val title: TextView = itemView.findViewById(TR.id.title) } - /** * Clickable view holder. */ @@ -112,8 +112,8 @@ open class SimpleNavigationView @JvmOverloads constructor( /** * Radio view holder. */ - class RadioHolder(parent: ViewGroup, listener: View.OnClickListener?) - : ClickableHolder(parent.inflate(TR.layout.navigation_view_radio), listener) { + class RadioHolder(parent: ViewGroup, listener: View.OnClickListener?) : + ClickableHolder(parent.inflate(TR.layout.navigation_view_radio), listener) { val radio: RadioButton = itemView.findViewById(TR.id.nav_view_item) } @@ -121,8 +121,8 @@ open class SimpleNavigationView @JvmOverloads constructor( /** * Checkbox view holder. */ - class CheckboxHolder(parent: ViewGroup, listener: View.OnClickListener?) - : ClickableHolder(parent.inflate(TR.layout.navigation_view_checkbox), listener) { + class CheckboxHolder(parent: ViewGroup, listener: View.OnClickListener?) : + ClickableHolder(parent.inflate(TR.layout.navigation_view_checkbox), listener) { val check: CheckBox = itemView.findViewById(TR.id.nav_view_item) } @@ -130,21 +130,21 @@ open class SimpleNavigationView @JvmOverloads constructor( /** * Multi state view holder. */ - class MultiStateHolder(parent: ViewGroup, listener: View.OnClickListener?) - : ClickableHolder(parent.inflate(TR.layout.navigation_view_checkedtext), listener) { + class MultiStateHolder(parent: ViewGroup, listener: View.OnClickListener?) : + ClickableHolder(parent.inflate(TR.layout.navigation_view_checkedtext), listener) { val text: CheckedTextView = itemView.findViewById(TR.id.nav_view_item) } - class SpinnerHolder(parent: ViewGroup, listener: OnClickListener? = null) - : ClickableHolder(parent.inflate(TR.layout.navigation_view_spinner), listener) { + class SpinnerHolder(parent: ViewGroup, listener: OnClickListener? = null) : + ClickableHolder(parent.inflate(TR.layout.navigation_view_spinner), listener) { val text: TextView = itemView.findViewById(TR.id.nav_view_item_text) val spinner: Spinner = itemView.findViewById(TR.id.nav_view_item) } - class EditTextHolder(parent: ViewGroup) - : Holder(parent.inflate(TR.layout.navigation_view_text)) { + class EditTextHolder(parent: ViewGroup) : + Holder(parent.inflate(TR.layout.navigation_view_text)) { val wrapper: TextInputLayout = itemView.findViewById(TR.id.nav_view_item_wrapper) val edit: EditText = itemView.findViewById(TR.id.nav_view_item) @@ -159,5 +159,4 @@ open class SimpleNavigationView @JvmOverloads constructor( const val VIEW_TYPE_TEXT = 105 const val VIEW_TYPE_LIST = 106 } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleSeekBarListener.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleSeekBarListener.kt index 77f815bd34..12e903bfb1 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleSeekBarListener.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/SimpleSeekBarListener.kt @@ -10,4 +10,4 @@ open class SimpleSeekBarListener : SeekBar.OnSeekBarChangeListener { override fun onStopTrackingTouch(seekBar: SeekBar) { } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/StateImageViewTarget.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/StateImageViewTarget.kt index 5768afe90c..0613e330b6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/StateImageViewTarget.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/StateImageViewTarget.kt @@ -1,10 +1,10 @@ package eu.kanade.tachiyomi.widget import android.graphics.drawable.Drawable -import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import android.view.View import android.widget.ImageView import android.widget.ImageView.ScaleType +import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.bumptech.glide.request.target.ImageViewTarget import com.bumptech.glide.request.transition.Transition import eu.kanade.tachiyomi.R @@ -21,10 +21,12 @@ import eu.kanade.tachiyomi.util.view.visible * @param errorDrawableRes the error drawable resource to show. * @param errorScaleType the scale type for the error drawable, [ScaleType.CENTER] by default. */ -class StateImageViewTarget(view: ImageView, - val progress: View? = null, - val errorDrawableRes: Int = R.drawable.ic_broken_image_grey_24dp, - val errorScaleType: ScaleType = ScaleType.CENTER) : +class StateImageViewTarget( + view: ImageView, + val progress: View? = null, + val errorDrawableRes: Int = R.drawable.ic_broken_image_grey_24dp, + val errorScaleType: ScaleType = ScaleType.CENTER +) : ImageViewTarget(view) { diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/ViewPagerAdapter.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/ViewPagerAdapter.kt index 6b101e17ee..520721104d 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/ViewPagerAdapter.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/ViewPagerAdapter.kt @@ -1,8 +1,8 @@ package eu.kanade.tachiyomi.widget -import androidx.viewpager.widget.PagerAdapter import android.view.View import android.view.ViewGroup +import androidx.viewpager.widget.PagerAdapter abstract class ViewPagerAdapter : androidx.viewpager.widget.PagerAdapter() { @@ -30,5 +30,4 @@ abstract class ViewPagerAdapter : androidx.viewpager.widget.PagerAdapter() { interface PositionableView { val item: Any } - } diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ExtensionPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ExtensionPreference.kt index b57e4528df..c5ab98662e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ExtensionPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/ExtensionPreference.kt @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.widget.preference import android.content.Context +import android.util.AttributeSet import androidx.preference.Preference import androidx.preference.PreferenceViewHolder -import android.util.AttributeSet import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault @@ -30,15 +30,13 @@ class ExtensionPreference @JvmOverloads constructor(context: Context, attrs: Att extUpdateText.text = context.resources.getQuantityString(R.plurals .updates_available, updates, updates) extUpdateText.visible() - } - else { + } else { extUpdateText.text = null extUpdateText.gone() } } - override public fun notifyChanged() { + public override fun notifyChanged() { super.notifyChanged() } - } 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 f98bf0966f..0a92734dae 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 @@ -7,20 +7,23 @@ import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItemsSingleChoice import eu.kanade.tachiyomi.data.preference.getOrDefault -class IntListMatPreference @JvmOverloads constructor(activity: Activity?, context: Context, +class IntListMatPreference @JvmOverloads constructor( + activity: Activity?, + context: Context, attrs: AttributeSet? = - null) : + null +) : MatPreference(activity, context, attrs) { - var entryValues:List = emptyList() - var entryRange:IntRange + var entryValues: List = emptyList() + var entryRange: IntRange get() = 0..0 set(value) { entryValues = value.toList() } - var entriesRes:Array + var entriesRes: Array get() = emptyArray() set(value) { entries = value.map { context.getString(it) } } - private var defValue:Int = 0 - var entries:List = emptyList() + private var defValue: Int = 0 + var entries: List = emptyList() override fun onSetInitialValue(defaultValue: Any?) { super.onSetInitialValue(defaultValue) @@ -50,4 +53,4 @@ AttributeSet? = } } } -} \ No newline at end of file +} 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 3e3000a003..37873398f9 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 @@ -1,8 +1,8 @@ package eu.kanade.tachiyomi.widget.preference import android.content.Context -import androidx.preference.ListPreference import android.util.AttributeSet +import androidx.preference.ListPreference class IntListPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs) { 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 56103c5b5a..352484eada 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 @@ -9,19 +9,22 @@ import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItemsSingleChoice import eu.kanade.tachiyomi.data.preference.getOrDefault -open class ListMatPreference @JvmOverloads constructor(activity: Activity?, context: Context, +open class ListMatPreference @JvmOverloads constructor( + activity: Activity?, + context: Context, attrs: AttributeSet? = - null) : + null +) : MatPreference(activity, context, attrs) { - var sharedPref:String? = null - var otherPref:Preference? = null - var entryValues:List = emptyList() - var entriesRes:Array + var sharedPref: String? = null + var otherPref: Preference? = null + var entryValues: List = emptyList() + var entriesRes: Array get() = emptyArray() set(value) { entries = value.map { context.getString(it) } } - protected var defValue:String = "" - var entries:List = emptyList() + protected var defValue: String = "" + var entries: List = emptyList() override fun onSetInitialValue(defaultValue: Any?) { super.onSetInitialValue(defaultValue) @@ -45,8 +48,7 @@ open class ListMatPreference @JvmOverloads constructor(activity: Activity?, cont val default = entryValues.indexOf(if (sharedPref != null) { val settings = context.getSharedPreferences(sharedPref, Context.MODE_PRIVATE) settings.getString(key, "") - } - else prefs.getStringPref(key, defValue).getOrDefault()) + } else prefs.getStringPref(key, defValue).getOrDefault()) listItemsSingleChoice(items = entries, waitForPositiveButton = false, initialSelection = default) { _, pos, _ -> @@ -63,8 +65,7 @@ open class ListMatPreference @JvmOverloads constructor(activity: Activity?, cont else otherPref?.summary = otherPref?.summary?.toString()?.replace(oldDef, entries[pos] ) ?: entries[pos] - } - else { + } else { prefs.getStringPref(key, defValue).set(value) this@ListMatPreference.summary = this@ListMatPreference.summary callChangeListener(value) @@ -72,4 +73,4 @@ open class ListMatPreference @JvmOverloads constructor(activity: Activity?, cont dismiss() } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginCheckBoxPreference.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginCheckBoxPreference.kt index 460cc377cd..d80ffaa86c 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginCheckBoxPreference.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginCheckBoxPreference.kt @@ -2,10 +2,10 @@ package eu.kanade.tachiyomi.widget.preference import android.content.Context import android.graphics.Color -import androidx.preference.CheckBoxPreference -import androidx.preference.PreferenceViewHolder import android.util.AttributeSet import android.view.View +import androidx.preference.CheckBoxPreference +import androidx.preference.PreferenceViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.source.online.LoginSource @@ -15,9 +15,9 @@ import kotlinx.android.synthetic.main.pref_item_source.view.login import kotlinx.android.synthetic.main.pref_item_source.view.login_frame class LoginCheckBoxPreference @JvmOverloads constructor( - context: Context, - val source: HttpSource, - attrs: AttributeSet? = null + context: Context, + val source: HttpSource, + attrs: AttributeSet? = null ) : CheckBoxPreference(context, attrs) { init { @@ -54,5 +54,4 @@ class LoginCheckBoxPreference @JvmOverloads constructor( public override fun notifyChanged() { super.notifyChanged() } - } 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 a778196d61..fc175c84fd 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 @@ -1,9 +1,9 @@ package eu.kanade.tachiyomi.widget.preference import android.content.Context +import android.util.AttributeSet import androidx.preference.Preference import androidx.preference.PreferenceViewHolder -import android.util.AttributeSet import eu.kanade.tachiyomi.R import kotlinx.android.synthetic.main.pref_widget_imageview.view.* @@ -23,8 +23,7 @@ class LoginPreference @JvmOverloads constructor(context: Context, attrs: Attribu R.drawable.ic_done_green_24dp) } - override public fun notifyChanged() { + public override fun notifyChanged() { super.notifyChanged() } - } 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 2763838a7b..e503ee6b6d 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 @@ -10,15 +10,18 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get -open class MatPreference @JvmOverloads constructor(val activity: Activity?, context: Context, +open class MatPreference @JvmOverloads constructor( + val activity: Activity?, + context: Context, attrs: AttributeSet? = - null) : + null +) : Preference(context, attrs) { protected val prefs: PreferencesHelper = Injekt.get() private var isShowing = false - var customSummary:String? = null + var customSummary: String? = null override fun onClick() { if (!isShowing) @@ -39,4 +42,4 @@ open class MatPreference @JvmOverloads constructor(val activity: Activity?, cont negativeButton(android.R.string.cancel) } } -} \ No newline at end of file +} 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 406fc0ba0f..1d35f5bf0b 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 @@ -11,13 +11,16 @@ import com.afollestad.materialdialogs.list.listItemsMultiChoice import com.afollestad.materialdialogs.list.uncheckItem import eu.kanade.tachiyomi.data.preference.getOrDefault -class MultiListMatPreference @JvmOverloads constructor(activity: Activity?, context: Context, +class MultiListMatPreference @JvmOverloads constructor( + activity: Activity?, + context: Context, attrs: AttributeSet? = - null) : + null +) : ListMatPreference(activity, context, attrs) { - var allSelectionRes:Int? = null - var customSummaryRes:Int + var allSelectionRes: Int? = null + var customSummaryRes: Int get() = 0 set(value) { customSummary = context.getString(value) } @@ -63,4 +66,4 @@ class MultiListMatPreference @JvmOverloads constructor(activity: Activity?, cont } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SourceLoginDialog.kt b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SourceLoginDialog.kt index e546204a60..346de39768 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SourceLoginDialog.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/widget/preference/SourceLoginDialog.kt @@ -68,5 +68,4 @@ class SourceLoginDialog(bundle: Bundle? = null) : LoginDialogPreference(bundle = interface Listener { fun loginDialogClosed(source: LoginSource) } - } 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 24f9a68218..a4ed0194a5 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 @@ -4,21 +4,22 @@ import android.annotation.TargetApi import android.content.Context import android.content.res.TypedArray import android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH -import androidx.preference.PreferenceCategory -import androidx.preference.PreferenceViewHolder -import androidx.appcompat.widget.SwitchCompat import android.util.AttributeSet import android.view.View import android.widget.Checkable import android.widget.CompoundButton import android.widget.TextView +import androidx.appcompat.widget.SwitchCompat +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.getResourceColor class SwitchPreferenceCategory @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null) -: PreferenceCategory( + context: Context, + attrs: AttributeSet? = null +) : +PreferenceCategory( context, attrs, R.attr.switchPreferenceCompatStyle), @@ -121,5 +122,4 @@ CompoundButton.OnCheckedChangeListener { else defaultValue as Boolean) } - } diff --git a/app/src/main/res/layout/main_activity.xml b/app/src/main/res/layout/main_activity.xml index e5daaf6b4a..834a7f3dc7 100644 --- a/app/src/main/res/layout/main_activity.xml +++ b/app/src/main/res/layout/main_activity.xml @@ -20,7 +20,7 @@ - - + ) : RobolectricTestRunner override fun getAppManifest(config: Config): AndroidManifest { return super.getAppManifest(config).apply { packageName = "eu.kanade.tachiyomi" } } -} \ No newline at end of file +} diff --git a/app/src/test/java/eu/kanade/tachiyomi/data/backup/BackupTest.kt b/app/src/test/java/eu/kanade/tachiyomi/data/backup/BackupTest.kt index 3b83814f9e..a7944a1eb0 100644 --- a/app/src/test/java/eu/kanade/tachiyomi/data/backup/BackupTest.kt +++ b/app/src/test/java/eu/kanade/tachiyomi/data/backup/BackupTest.kt @@ -11,7 +11,12 @@ import eu.kanade.tachiyomi.CustomRobolectricGradleTestRunner import eu.kanade.tachiyomi.data.backup.models.Backup import eu.kanade.tachiyomi.data.backup.models.DHistory import eu.kanade.tachiyomi.data.database.DatabaseHelper -import eu.kanade.tachiyomi.data.database.models.* +import eu.kanade.tachiyomi.data.database.models.Category +import eu.kanade.tachiyomi.data.database.models.Chapter +import eu.kanade.tachiyomi.data.database.models.ChapterImpl +import eu.kanade.tachiyomi.data.database.models.Manga +import eu.kanade.tachiyomi.data.database.models.MangaImpl +import eu.kanade.tachiyomi.data.database.models.TrackImpl import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.coroutines.GlobalScope @@ -22,7 +27,10 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito -import org.mockito.Mockito.* +import org.mockito.Mockito.RETURNS_DEEP_STUBS +import org.mockito.Mockito.`when` +import org.mockito.Mockito.anyLong +import org.mockito.Mockito.mock import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import rx.Observable @@ -213,7 +221,6 @@ class BackupTest { } } - // Check if restore successful val dbCats = backupManager.databaseHelper.getFavoriteMangas().executeAsBlocking() assertThat(dbCats).hasSize(1) @@ -233,7 +240,6 @@ class BackupTest { val manga = getSingleManga("One Piece") manga.id = backupManager.databaseHelper.insertManga(manga).executeAsBlocking().insertedId() - // Create restore list val chapters = ArrayList() for (i in 1..8) { @@ -330,7 +336,7 @@ class BackupTest { // Check parser and restore already in database var trackList = listOf(track) - //Check parser + // Check parser var trackListJson = backupManager.parser.toJsonTree(trackList) var trackListRestore = backupManager.parser.fromJson>(trackListJson) backupManager.restoreTrackForManga(manga, trackListRestore) @@ -353,7 +359,7 @@ class BackupTest { // Check parser and restore, track not in database trackList = listOf(track2) - //Check parser + // Check parser trackListJson = backupManager.parser.toJsonTree(trackList) trackListRestore = backupManager.parser.fromJson>(trackListJson) backupManager.restoreTrackForManga(manga2, trackListRestore) diff --git a/app/src/test/java/eu/kanade/tachiyomi/data/database/CategoryTest.kt b/app/src/test/java/eu/kanade/tachiyomi/data/database/CategoryTest.kt index 61057b440f..6e12314eae 100644 --- a/app/src/test/java/eu/kanade/tachiyomi/data/database/CategoryTest.kt +++ b/app/src/test/java/eu/kanade/tachiyomi/data/database/CategoryTest.kt @@ -106,5 +106,4 @@ class CategoryTest { c.name = name db.insertCategory(c).executeAsBlocking() } - } diff --git a/app/src/test/java/eu/kanade/tachiyomi/data/database/ChapterRecognitionTest.kt b/app/src/test/java/eu/kanade/tachiyomi/data/database/ChapterRecognitionTest.kt index 35715bf8ce..33a0f2d176 100644 --- a/app/src/test/java/eu/kanade/tachiyomi/data/database/ChapterRecognitionTest.kt +++ b/app/src/test/java/eu/kanade/tachiyomi/data/database/ChapterRecognitionTest.kt @@ -471,7 +471,6 @@ class ChapterRecognitionTest { assertThat(chapter.chapter_number).isEqualTo(7f) } - /** * Test for chapters in format sx - chapter xx */ 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 8f41a6697d..f3ab4a4f20 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 @@ -11,13 +11,16 @@ import eu.kanade.tachiyomi.data.database.models.LibraryManga import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.online.HttpSource +import java.util.ArrayList import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers.anyLong import org.mockito.Mockito -import org.mockito.Mockito.* +import org.mockito.Mockito.RETURNS_DEEP_STUBS +import org.mockito.Mockito.`when` +import org.mockito.Mockito.mock import org.robolectric.Robolectric import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @@ -26,7 +29,6 @@ import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.InjektModule import uy.kohesive.injekt.api.InjektRegistrar import uy.kohesive.injekt.api.addSingleton -import java.util.ArrayList @Config(constants = BuildConfig::class, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP)) @RunWith(CustomRobolectricGradleTestRunner::class)