From 13011ed4af43c647b45c098b49690ec7c468804c Mon Sep 17 00:00:00 2001 From: tarsin Date: Thu, 12 Jan 2023 10:32:49 +0800 Subject: [PATCH] Kotlinize GalleryDetailScene --- .../com/hippo/ehviewer/client/EhRequest.kt | 4 +- .../ehviewer/ui/scene/GalleryDetailScene.kt | 3035 ++++++++--------- 2 files changed, 1426 insertions(+), 1613 deletions(-) diff --git a/app/src/main/java/com/hippo/ehviewer/client/EhRequest.kt b/app/src/main/java/com/hippo/ehviewer/client/EhRequest.kt index f6f142dac..b3aa4ef3e 100644 --- a/app/src/main/java/com/hippo/ehviewer/client/EhRequest.kt +++ b/app/src/main/java/com/hippo/ehviewer/client/EhRequest.kt @@ -31,7 +31,7 @@ class EhRequest { get() = job?.isActive ?: false var method = 0 private set - var args: Array? = null + var args: Array? = null private set var callback: EhClient.Callback? = null private set @@ -41,7 +41,7 @@ class EhRequest { return this } - fun setArgs(vararg args: Any): EhRequest { + fun setArgs(vararg args: Any?): EhRequest { this.args = args return this } diff --git a/app/src/main/java/com/hippo/ehviewer/ui/scene/GalleryDetailScene.kt b/app/src/main/java/com/hippo/ehviewer/ui/scene/GalleryDetailScene.kt index d6c2e314b..f9a6f3eb0 100755 --- a/app/src/main/java/com/hippo/ehviewer/ui/scene/GalleryDetailScene.kt +++ b/app/src/main/java/com/hippo/ehviewer/ui/scene/GalleryDetailScene.kt @@ -13,1989 +13,1802 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.hippo.ehviewer.ui.scene -package com.hippo.ehviewer.ui.scene; +import android.Manifest +import android.annotation.SuppressLint +import android.app.Activity +import android.app.Dialog +import android.app.DownloadManager +import android.content.Context +import android.content.DialogInterface +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.ColorStateList +import android.graphics.Color +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Environment +import android.text.Html +import android.text.TextUtils +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.View.OnLongClickListener +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.LinearLayout +import android.widget.ListView +import android.widget.RatingBar +import android.widget.TextView +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.IntDef +import androidx.annotation.StringRes +import androidx.core.content.ContextCompat +import androidx.core.widget.NestedScrollView +import androidx.lifecycle.lifecycleScope +import coil.Coil.imageLoader +import coil.annotation.ExperimentalCoilApi +import com.google.android.material.progressindicator.CircularProgressIndicator +import com.google.android.material.snackbar.Snackbar +import com.hippo.app.BaseDialogBuilder +import com.hippo.app.CheckBoxDialogBuilder +import com.hippo.app.EditTextDialogBuilder +import com.hippo.ehviewer.EhApplication +import com.hippo.ehviewer.EhApplication.Companion.downloadManager +import com.hippo.ehviewer.EhApplication.Companion.ehCookieStore +import com.hippo.ehviewer.EhApplication.Companion.galleryDetailCache +import com.hippo.ehviewer.EhDB +import com.hippo.ehviewer.R +import com.hippo.ehviewer.Settings +import com.hippo.ehviewer.UrlOpener +import com.hippo.ehviewer.client.EhCacheKeyFactory +import com.hippo.ehviewer.client.EhClient +import com.hippo.ehviewer.client.EhFilter +import com.hippo.ehviewer.client.EhRequest +import com.hippo.ehviewer.client.EhTagDatabase +import com.hippo.ehviewer.client.EhTagDatabase.isTranslatable +import com.hippo.ehviewer.client.EhTagDatabase.namespaceToPrefix +import com.hippo.ehviewer.client.EhUrl +import com.hippo.ehviewer.client.EhUtils +import com.hippo.ehviewer.client.data.GalleryComment +import com.hippo.ehviewer.client.data.GalleryDetail +import com.hippo.ehviewer.client.data.GalleryInfo +import com.hippo.ehviewer.client.data.GalleryTagGroup +import com.hippo.ehviewer.client.data.ListUrlBuilder +import com.hippo.ehviewer.client.exception.NoHAtHClientException +import com.hippo.ehviewer.client.parser.ArchiveParser +import com.hippo.ehviewer.client.parser.RateGalleryParser +import com.hippo.ehviewer.client.parser.TorrentParser +import com.hippo.ehviewer.client.parser.VoteTagParser +import com.hippo.ehviewer.dao.DownloadInfo +import com.hippo.ehviewer.dao.Filter +import com.hippo.ehviewer.download.DownloadManager.DownloadInfoListener +import com.hippo.ehviewer.gallery.EhPageLoader +import com.hippo.ehviewer.gallery.PageLoader2 +import com.hippo.ehviewer.spider.SpiderDen +import com.hippo.ehviewer.ui.CommonOperations +import com.hippo.ehviewer.ui.GalleryInfoBottomSheet +import com.hippo.ehviewer.ui.MainActivity +import com.hippo.ehviewer.ui.annotation.WholeLifeCircle +import com.hippo.ehviewer.ui.scene.GalleryListScene.Companion.getStartArgs +import com.hippo.ehviewer.widget.GalleryRatingBar +import com.hippo.ehviewer.widget.GalleryRatingBar.OnUserRateListener +import com.hippo.text.URLImageGetter +import com.hippo.util.AppHelper +import com.hippo.util.ExceptionUtils +import com.hippo.util.ReadableTime +import com.hippo.util.addTextToClipboard +import com.hippo.view.ViewTransition +import com.hippo.widget.AutoWrapLayout +import com.hippo.widget.LoadImageView +import com.hippo.widget.ObservedTextView +import com.hippo.widget.SimpleGridAutoSpanLayout +import com.hippo.yorozuya.AssertUtils +import com.hippo.yorozuya.FileUtils +import com.hippo.yorozuya.IntIdGenerator +import com.hippo.yorozuya.ViewUtils +import com.hippo.yorozuya.collect.IntList +import eu.kanade.tachiyomi.ui.reader.ReaderActivity +import eu.kanade.tachiyomi.util.lang.launchIO +import okhttp3.HttpUrl.Companion.toHttpUrl +import rikka.core.res.resolveColor +import kotlin.math.roundToInt -import android.Manifest; -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.Dialog; -import android.app.DownloadManager; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.res.ColorStateList; -import android.content.res.Resources; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.text.Html; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.RatingBar; -import android.widget.TextView; - -import androidx.activity.result.ActivityResultLauncher; -import androidx.activity.result.contract.ActivityResultContracts; -import androidx.annotation.IntDef; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; -import androidx.appcompat.app.AlertDialog; -import androidx.core.content.ContextCompat; -import androidx.core.widget.NestedScrollView; - -import com.google.android.material.progressindicator.CircularProgressIndicator; -import com.google.android.material.snackbar.Snackbar; -import com.hippo.app.BaseDialogBuilder; -import com.hippo.app.CheckBoxDialogBuilder; -import com.hippo.app.EditTextDialogBuilder; -import com.hippo.ehviewer.EhApplication; -import com.hippo.ehviewer.EhDB; -import com.hippo.ehviewer.R; -import com.hippo.ehviewer.Settings; -import com.hippo.ehviewer.UrlOpener; -import com.hippo.ehviewer.client.EhCacheKeyFactory; -import com.hippo.ehviewer.client.EhClient; -import com.hippo.ehviewer.client.EhFilter; -import com.hippo.ehviewer.client.EhRequest; -import com.hippo.ehviewer.client.EhTagDatabase; -import com.hippo.ehviewer.client.EhUrl; -import com.hippo.ehviewer.client.EhUtils; -import com.hippo.ehviewer.client.data.GalleryComment; -import com.hippo.ehviewer.client.data.GalleryDetail; -import com.hippo.ehviewer.client.data.GalleryInfo; -import com.hippo.ehviewer.client.data.GalleryTagGroup; -import com.hippo.ehviewer.client.data.ListUrlBuilder; -import com.hippo.ehviewer.client.data.PreviewSet; -import com.hippo.ehviewer.client.exception.NoHAtHClientException; -import com.hippo.ehviewer.client.parser.ArchiveParser; -import com.hippo.ehviewer.client.parser.RateGalleryParser; -import com.hippo.ehviewer.client.parser.TorrentParser; -import com.hippo.ehviewer.client.parser.VoteTagParser; -import com.hippo.ehviewer.dao.DownloadInfo; -import com.hippo.ehviewer.dao.Filter; -import com.hippo.ehviewer.gallery.EhPageLoader; -import com.hippo.ehviewer.gallery.PageLoader2; -import com.hippo.ehviewer.spider.SpiderDen; -import com.hippo.ehviewer.ui.CommonOperations; -import com.hippo.ehviewer.ui.GalleryInfoBottomSheet; -import com.hippo.ehviewer.ui.MainActivity; -import com.hippo.ehviewer.ui.annotation.WholeLifeCircle; -import com.hippo.ehviewer.widget.GalleryRatingBar; -import com.hippo.text.URLImageGetter; -import com.hippo.unifile.UniFile; -import com.hippo.util.AppHelper; -import com.hippo.util.ClipboardUtilKt; -import com.hippo.util.ExceptionUtils; -import com.hippo.util.IoThreadPoolExecutor; -import com.hippo.util.ReadableTime; -import com.hippo.view.ViewTransition; -import com.hippo.widget.AutoWrapLayout; -import com.hippo.widget.LoadImageView; -import com.hippo.widget.ObservedTextView; -import com.hippo.widget.SimpleGridAutoSpanLayout; -import com.hippo.yorozuya.AssertUtils; -import com.hippo.yorozuya.FileUtils; -import com.hippo.yorozuya.IntIdGenerator; -import com.hippo.yorozuya.ViewUtils; -import com.hippo.yorozuya.collect.IntList; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.ArrayList; -import java.util.List; - -import coil.Coil; -import eu.kanade.tachiyomi.ui.reader.ReaderActivity; -import okhttp3.HttpUrl; -import rikka.core.res.ResourcesKt; - -public class GalleryDetailScene extends CollapsingToolbarScene implements View.OnClickListener, - com.hippo.ehviewer.download.DownloadManager.DownloadInfoListener, - View.OnLongClickListener { - public final static String KEY_ACTION = "action"; - public static final String ACTION_GALLERY_INFO = "action_gallery_info"; - public static final String ACTION_GID_TOKEN = "action_gid_token"; - public static final String KEY_GALLERY_INFO = "gallery_info"; - public static final String KEY_GID = "gid"; - public static final String KEY_TOKEN = "token"; - public static final String KEY_PAGE = "page"; - private static final int REQUEST_CODE_COMMENT_GALLERY = 0; - private static final int STATE_INIT = -1; - private static final int STATE_NORMAL = 0; - private static final int STATE_REFRESH = 1; - private static final int STATE_REFRESH_HEADER = 2; - private static final int STATE_FAILED = 3; - private static final String KEY_GALLERY_DETAIL = "gallery_detail"; - private static final String KEY_REQUEST_ID = "request_id"; - private static final boolean TRANSITION_ANIMATION_DISABLED = true; +class GalleryDetailScene : CollapsingToolbarScene(), View.OnClickListener, DownloadInfoListener, + OnLongClickListener { /*--------------- View life cycle ---------------*/ - @Nullable - private TextView mTip; - @Nullable - private ViewTransition mViewTransition; + private var mTip: TextView? = null + private var mViewTransition: ViewTransition? = null + // Header - @Nullable - private LinearLayout mHeader; - @Nullable - private LoadImageView mThumb; - @Nullable - private TextView mUploader; - @Nullable - private TextView mCategory; - @Nullable - private ViewGroup mActionGroup; - @Nullable - private TextView mDownload; - @Nullable - private TextView mRead; + private var mHeader: LinearLayout? = null + private var mThumb: LoadImageView? = null + private var mUploader: TextView? = null + private var mCategory: TextView? = null + private var mActionGroup: ViewGroup? = null + private var mDownload: TextView? = null + private var mRead: TextView? = null + // Below header - @Nullable - private View mBelowHeader; + private var mBelowHeader: View? = null + // Info - @Nullable - private View mInfo; - @Nullable - private TextView mLanguage; - @Nullable - private TextView mPages; - @Nullable - private TextView mSize; - @Nullable - private TextView mPosted; - @Nullable - private TextView mFavoredTimes; - @Nullable - private TextView mNewerVersion; + private var mInfo: View? = null + private var mLanguage: TextView? = null + private var mPages: TextView? = null + private var mSize: TextView? = null + private var mPosted: TextView? = null + private var mFavoredTimes: TextView? = null + private var mNewerVersion: TextView? = null + // Actions - @Nullable - private View mActions; - @Nullable - private TextView mRatingText; - @Nullable - private RatingBar mRating; - @Nullable - private TextView mHeart; - @Nullable - private TextView mHeartOutline; - @Nullable - private TextView mTorrent; - @Nullable - private TextView mArchive; - @Nullable - private TextView mShare; - @Nullable - private View mRate; - @Nullable - private TextView mSimilar; - @Nullable - private TextView mSearchCover; + private var mActions: View? = null + private var mRatingText: TextView? = null + private var mRating: RatingBar? = null + private var mHeart: TextView? = null + private var mHeartOutline: TextView? = null + private var mTorrent: TextView? = null + private var mArchive: TextView? = null + private var mShare: TextView? = null + private var mRate: View? = null + private var mSimilar: TextView? = null + private var mSearchCover: TextView? = null + // Tags - @Nullable - private LinearLayout mTags; - @Nullable - private TextView mNoTags; + private var mTags: LinearLayout? = null + private var mNoTags: TextView? = null + // Comments - @Nullable - private LinearLayout mComments; - @Nullable - private TextView mCommentsText; + private var mComments: LinearLayout? = null + private var mCommentsText: TextView? = null + // Previews - @Nullable - private View mPreviews; - @Nullable - private SimpleGridAutoSpanLayout mGridLayout; - @Nullable - private TextView mPreviewText; + private var mPreviews: View? = null + private var mGridLayout: SimpleGridAutoSpanLayout? = null + private var mPreviewText: TextView? = null + // Progress - @Nullable - private View mProgress; - @Nullable - private ViewTransition mViewTransition2; + private var mProgress: View? = null + private var mViewTransition2: ViewTransition? = null + @WholeLifeCircle - private int mDownloadState; - @Nullable - private String mAction; - @Nullable - private GalleryInfo mGalleryInfo; - private long mGid; - private String mToken; - private int mPage; - @Nullable - private GalleryDetail mGalleryDetail; - private int mRequestId = IntIdGenerator.INVALID_ID; - private List mTorrentList; - ActivityResultLauncher requestStoragePermissionLauncher = registerForActivityResult( - new ActivityResultContracts.RequestPermission(), - result -> { - if (result && mGalleryDetail != null) { - TorrentListDialogHelper helper = new TorrentListDialogHelper(); - Dialog dialog = new BaseDialogBuilder(requireActivity()) - .setTitle(R.string.torrents) - .setView(R.layout.dialog_torrent_list) - .setOnDismissListener(helper) - .show(); - helper.setDialog(dialog, mGalleryDetail.torrentUrl); - } - }); - private String mArchiveFormParamOr; - private List mArchiveList; + private var mDownloadState = 0 + private var mAction: String? = null + private var mGalleryInfo: GalleryInfo? = null + private var mGid: Long = 0 + private var mToken: String? = null + private var mPage = 0 + private var mGalleryDetail: GalleryDetail? = null + private var mRequestId = IntIdGenerator.INVALID_ID + private var mTorrentList: List? = null + private var requestStoragePermissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestPermission() + ) { result: Boolean -> + if (result && mGalleryDetail != null) { + val helper = TorrentListDialogHelper() + val dialog: Dialog = BaseDialogBuilder(requireActivity()) + .setTitle(R.string.torrents) + .setView(R.layout.dialog_torrent_list) + .setOnDismissListener(helper) + .show() + helper.setDialog(dialog, mGalleryDetail!!.torrentUrl) + } + } + private var mArchiveFormParamOr: String? = null + private var mArchiveList: List? = null + @State - private int mState = STATE_INIT; - private boolean mModifyingFavorites; - - @Nullable - private static String getArtist(GalleryTagGroup[] tagGroups) { - if (null == tagGroups) { - return null; - } - for (GalleryTagGroup tagGroup : tagGroups) { - if ("artist".equals(tagGroup.groupName) && tagGroup.size() > 0) { - return tagGroup.getTagAt(0); - } - } - return null; - } - - private static void deleteFileAsync(UniFile... files) { - //noinspection deprecation - new AsyncTask() { - @Override - protected Void doInBackground(UniFile... params) { - for (UniFile file : params) { - if (file != null) { - file.delete(); - } - } - return null; - } - }.executeOnExecutor(IoThreadPoolExecutor.getInstance(), files); - } + private var mState = STATE_INIT + private var mModifyingFavorites = false @StringRes - private int getRatingText(float rating) { - - return switch (Math.round(rating * 2)) { - case 0 -> R.string.rating0; - case 1 -> R.string.rating1; - case 2 -> R.string.rating2; - case 3 -> R.string.rating3; - case 4 -> R.string.rating4; - case 5 -> R.string.rating5; - case 6 -> R.string.rating6; - case 7 -> R.string.rating7; - case 8 -> R.string.rating8; - case 9 -> R.string.rating9; - case 10 -> R.string.rating10; - default -> R.string.rating_none; - }; + private fun getRatingText(rating: Float): Int { + return when ((rating * 2).roundToInt()) { + 0 -> R.string.rating0 + 1 -> R.string.rating1 + 2 -> R.string.rating2 + 3 -> R.string.rating3 + 4 -> R.string.rating4 + 5 -> R.string.rating5 + 6 -> R.string.rating6 + 7 -> R.string.rating7 + 8 -> R.string.rating8 + 9 -> R.string.rating9 + 10 -> R.string.rating10 + else -> R.string.rating_none + } } - private void handleArgs(Bundle args) { + private fun handleArgs(args: Bundle?) { if (args == null) { - return; + return } - - String action = args.getString(KEY_ACTION); - mAction = action; - if (ACTION_GALLERY_INFO.equals(action)) { - mGalleryInfo = args.getParcelable(KEY_GALLERY_INFO); + val action = args.getString(KEY_ACTION) + mAction = action + if (ACTION_GALLERY_INFO == action) { + mGalleryInfo = args.getParcelable(KEY_GALLERY_INFO) // Add history if (null != mGalleryInfo) { - EhDB.putHistoryInfo(mGalleryInfo); + EhDB.putHistoryInfo(mGalleryInfo) } - } else if (ACTION_GID_TOKEN.equals(action)) { - mGid = args.getLong(KEY_GID); - mToken = args.getString(KEY_TOKEN); - mPage = args.getInt(KEY_PAGE); + } else if (ACTION_GID_TOKEN == action) { + mGid = args.getLong(KEY_GID) + mToken = args.getString(KEY_TOKEN) + mPage = args.getInt(KEY_PAGE) } } - @Nullable - private String getGalleryDetailUrl() { - long gid; - String token; - if (mGalleryDetail != null) { - gid = mGalleryDetail.getGid(); - token = mGalleryDetail.getToken(); - } else if (mGalleryInfo != null) { - gid = mGalleryInfo.getGid(); - token = mGalleryInfo.getToken(); - } else if (ACTION_GID_TOKEN.equals(mAction)) { - gid = mGid; - token = mToken; - } else { - return null; + private val galleryDetailUrl: String? + get() { + val gid: Long + val token: String? + if (mGalleryDetail != null) { + gid = mGalleryDetail!!.gid + token = mGalleryDetail!!.token + } else if (mGalleryInfo != null) { + gid = mGalleryInfo!!.gid + token = mGalleryInfo!!.token + } else if (ACTION_GID_TOKEN == mAction) { + gid = mGid + token = mToken + } else { + return null + } + return EhUrl.getGalleryDetailUrl(gid, token, 0, false) } - return EhUrl.getGalleryDetailUrl(gid, token, 0, false); - } // -1 for error - private long getGid() { - if (mGalleryDetail != null) { - return mGalleryDetail.getGid(); + private val gid: Long + get() = if (mGalleryDetail != null) { + mGalleryDetail!!.gid } else if (mGalleryInfo != null) { - return mGalleryInfo.getGid(); - } else if (ACTION_GID_TOKEN.equals(mAction)) { - return mGid; + mGalleryInfo!!.gid + } else if (ACTION_GID_TOKEN == mAction) { + mGid } else { - return -1; + -1 } - } - - private String getUploader() { - if (mGalleryDetail != null) { - return mGalleryDetail.getUploader(); + private val uploader: String? + get() = if (mGalleryDetail != null) { + mGalleryDetail!!.uploader } else if (mGalleryInfo != null) { - return mGalleryInfo.getUploader(); + mGalleryInfo!!.uploader } else { - return null; + null } - } // Judging by the uploader to exclude the cooldown period - private boolean getDisowned() { - return getUploader().equals("(Disowned)"); - } + private val disowned: Boolean + get() = uploader == "(Disowned)" // -1 for error - private int getCategory() { - if (mGalleryDetail != null) { - return mGalleryDetail.getCategory(); + private val category: Int + get() = if (mGalleryDetail != null) { + mGalleryDetail!!.category } else if (mGalleryInfo != null) { - return mGalleryInfo.getCategory(); + mGalleryInfo!!.category } else { - return -1; + -1 } - } - - private GalleryInfo getGalleryInfo() { - if (null != mGalleryDetail) { - return mGalleryDetail; + private val galleryInfo: GalleryInfo? + get() = if (null != mGalleryDetail) { + mGalleryDetail } else if (null != mGalleryInfo) { - return mGalleryInfo; + mGalleryInfo } else { - return null; + null } - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) if (savedInstanceState == null) { - onInit(); + onInit() } else { - onRestore(savedInstanceState); + onRestore(savedInstanceState) } } - @Override - public void onResume() { - super.onResume(); + override fun onResume() { + super.onResume() if (mRead != null) { try { - PageLoader2 galleryProvider = new EhPageLoader(mGalleryInfo); - galleryProvider.start(); - int startPage = galleryProvider.getStartPage(); + val galleryProvider: PageLoader2 = EhPageLoader(mGalleryInfo) + galleryProvider.start() + val startPage = galleryProvider.startPage if (startPage != 0) { - mRead.setText(getString(R.string.read_from, startPage + 1)); + mRead!!.text = getString(R.string.read_from, startPage + 1) } - galleryProvider.stop(); - } catch (Exception ignore) { - + galleryProvider.stop() + } catch (ignore: Exception) { } } } - private void onInit() { - handleArgs(getArguments()); + private fun onInit() { + handleArgs(arguments) } - private void onRestore(Bundle savedInstanceState) { - mAction = savedInstanceState.getString(KEY_ACTION); - mGalleryInfo = savedInstanceState.getParcelable(KEY_GALLERY_INFO); - mGid = savedInstanceState.getLong(KEY_GID); - mToken = savedInstanceState.getString(KEY_TOKEN); - mGalleryDetail = savedInstanceState.getParcelable(KEY_GALLERY_DETAIL); - mRequestId = savedInstanceState.getInt(KEY_REQUEST_ID); + private fun onRestore(savedInstanceState: Bundle) { + mAction = savedInstanceState.getString(KEY_ACTION) + mGalleryInfo = savedInstanceState.getParcelable(KEY_GALLERY_INFO) + mGid = savedInstanceState.getLong(KEY_GID) + mToken = savedInstanceState.getString(KEY_TOKEN) + mGalleryDetail = savedInstanceState.getParcelable(KEY_GALLERY_DETAIL) + mRequestId = savedInstanceState.getInt(KEY_REQUEST_ID) } - @Override - public void onSaveInstanceState(@NonNull Bundle outState) { - super.onSaveInstanceState(outState); - + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) if (mAction != null) { - outState.putString(KEY_ACTION, mAction); + outState.putString(KEY_ACTION, mAction) } if (mGalleryInfo != null) { - outState.putParcelable(KEY_GALLERY_INFO, mGalleryInfo); + outState.putParcelable(KEY_GALLERY_INFO, mGalleryInfo) } - outState.putLong(KEY_GID, mGid); + outState.putLong(KEY_GID, mGid) if (mToken != null) { - outState.putString(KEY_TOKEN, mAction); + outState.putString(KEY_TOKEN, mAction) } if (mGalleryDetail != null) { - outState.putParcelable(KEY_GALLERY_DETAIL, mGalleryDetail); + outState.putParcelable(KEY_GALLERY_DETAIL, mGalleryDetail) } - outState.putInt(KEY_REQUEST_ID, mRequestId); + outState.putInt(KEY_REQUEST_ID, mRequestId) } - @Override - public int getMenuResId() { - return R.menu.scene_gallery_detail; + override fun getMenuResId(): Int { + return R.menu.scene_gallery_detail } - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setNavigationIcon(R.drawable.v_arrow_left_dark_x24); + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setNavigationIcon(R.drawable.v_arrow_left_dark_x24) } - @Override - public boolean onMenuItemClick(MenuItem item) { - int itemId = item.getItemId(); + override fun onMenuItemClick(item: MenuItem): Boolean { + val itemId = item.itemId if (itemId == R.id.action_open_in_other_app) { - String url = getGalleryDetailUrl(); - Activity activity = getMainActivity(); + val url = galleryDetailUrl + val activity: Activity? = mainActivity if (null != url && null != activity) { - UrlOpener.openUrl(activity, url, false); + UrlOpener.openUrl(activity, url, false) } } else if (itemId == R.id.action_refresh) { if (mState != STATE_REFRESH && mState != STATE_REFRESH_HEADER) { - adjustViewVisibility(STATE_REFRESH); - request(); + adjustViewVisibility(STATE_REFRESH) + request() } } else if (itemId == R.id.action_add_tag) { if (mGalleryDetail == null) { - return false; + return false } - if (mGalleryDetail.apiUid < 0) { - showTip(R.string.sign_in_first, LENGTH_LONG); - return false; + if (mGalleryDetail!!.apiUid < 0) { + showTip(R.string.sign_in_first, LENGTH_LONG) + return false } - EditTextDialogBuilder builder = new EditTextDialogBuilder(requireContext(), "", getString(R.string.action_add_tag_tip)); - builder.setPositiveButton(android.R.string.ok, null); - AlertDialog dialog = builder.setTitle(R.string.action_add_tag) - .show(); + val builder = + EditTextDialogBuilder(requireContext(), "", getString(R.string.action_add_tag_tip)) + builder.setPositiveButton(android.R.string.ok, null) + val dialog = builder.setTitle(R.string.action_add_tag) + .show() dialog.getButton(DialogInterface.BUTTON_POSITIVE) - .setOnClickListener(v -> { - voteTag(builder.getText().trim(), 1); - dialog.dismiss(); - }); + .setOnClickListener { + voteTag(builder.text.trim { it <= ' ' }, 1) + dialog.dismiss() + } } - return true; + return true } - @NonNull - @Override - public View onCreateViewWithToolbar(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { + override fun onCreateViewWithToolbar( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View { // Get download state - long gid = getGid(); - if (gid != -1) { - Context context = getContext(); - AssertUtils.assertNotNull(context); - mDownloadState = EhApplication.getDownloadManager().getDownloadState(gid); + val gid = gid + mDownloadState = if (gid != -1L) { + val context = context + AssertUtils.assertNotNull(context) + downloadManager.getDownloadState(gid) } else { - mDownloadState = DownloadInfo.STATE_INVALID; + DownloadInfo.STATE_INVALID } - - View view = inflater.inflate(R.layout.scene_gallery_detail, container, false); - - ViewGroup main = (ViewGroup) ViewUtils.$$(view, R.id.main); - NestedScrollView mainView = (NestedScrollView) ViewUtils.$$(main, R.id.scroll_view); - setLiftOnScrollTargetView(mainView); - View progressView = ViewUtils.$$(main, R.id.progress_view); - mTip = (TextView) ViewUtils.$$(main, R.id.tip); - mViewTransition = new ViewTransition(mainView, progressView, mTip); - - Context context = getContext(); - AssertUtils.assertNotNull(context); - - Drawable drawable = ContextCompat.getDrawable(context, R.drawable.big_sad_pandroid); - drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); - mTip.setCompoundDrawables(null, drawable, null, null); - mTip.setOnClickListener(this); - - mHeader = (LinearLayout) ViewUtils.$$(mainView, R.id.header); - mThumb = (LoadImageView) ViewUtils.$$(mHeader, R.id.thumb); - mUploader = (TextView) ViewUtils.$$(mHeader, R.id.uploader); - mCategory = (TextView) ViewUtils.$$(mHeader, R.id.category); - mActionGroup = (ViewGroup) ViewUtils.$$(mHeader, R.id.action_card); - mDownload = (TextView) ViewUtils.$$(mActionGroup, R.id.download); - mRead = (TextView) ViewUtils.$$(mActionGroup, R.id.read); - - mUploader.setOnClickListener(this); - mCategory.setOnClickListener(this); - mDownload.setOnClickListener(this); - mDownload.setOnLongClickListener(this); - mRead.setOnClickListener(this); - - mUploader.setOnLongClickListener(this); - - mBelowHeader = mainView.findViewById(R.id.below_header); - View belowHeader = mBelowHeader; - - mInfo = ViewUtils.$$(mHeader, R.id.info); - mLanguage = (TextView) ViewUtils.$$(mInfo, R.id.language); - mPages = (TextView) ViewUtils.$$(mInfo, R.id.pages); - mSize = (TextView) ViewUtils.$$(mInfo, R.id.size); - mPosted = (TextView) ViewUtils.$$(mInfo, R.id.posted); - mFavoredTimes = (TextView) ViewUtils.$$(mInfo, R.id.favoredTimes); - mInfo.setOnClickListener(this); - - mActions = ViewUtils.$$(belowHeader, R.id.actions); - mNewerVersion = (TextView) ViewUtils.$$(mActions, R.id.newerVersion); - mRatingText = (TextView) ViewUtils.$$(mActions, R.id.rating_text); - mRating = (RatingBar) ViewUtils.$$(mActions, R.id.rating); - mHeart = (TextView) ViewUtils.$$(mActions, R.id.heart); - mHeartOutline = (TextView) ViewUtils.$$(mActions, R.id.heart_outline); - mTorrent = (TextView) ViewUtils.$$(mActions, R.id.torrent); - mArchive = (TextView) ViewUtils.$$(mActions, R.id.archive); - mShare = (TextView) ViewUtils.$$(mActions, R.id.share); - mRate = ViewUtils.$$(mActions, R.id.rate); - mSimilar = (TextView) ViewUtils.$$(mActions, R.id.similar); - mSearchCover = (TextView) ViewUtils.$$(mActions, R.id.search_cover); - mNewerVersion.setOnClickListener(this); - mHeart.setOnClickListener(this); - mHeart.setOnLongClickListener(this); - mHeartOutline.setOnClickListener(this); - mHeartOutline.setOnLongClickListener(this); - mTorrent.setOnClickListener(this); - mArchive.setOnClickListener(this); - mShare.setOnClickListener(this); - mRate.setOnClickListener(this); - mSimilar.setOnClickListener(this); - mSearchCover.setOnClickListener(this); - - mTags = (LinearLayout) ViewUtils.$$(belowHeader, R.id.tags); - mNoTags = (TextView) ViewUtils.$$(mTags, R.id.no_tags); - - mComments = (LinearLayout) ViewUtils.$$(belowHeader, R.id.comments); + val view = inflater.inflate(R.layout.scene_gallery_detail, container, false) + val main = ViewUtils.`$$`(view, R.id.main) as ViewGroup + val mainView = ViewUtils.`$$`(main, R.id.scroll_view) as NestedScrollView + setLiftOnScrollTargetView(mainView) + val progressView = ViewUtils.`$$`(main, R.id.progress_view) + mTip = ViewUtils.`$$`(main, R.id.tip) as TextView + mViewTransition = ViewTransition(mainView, progressView, mTip) + val context = context + AssertUtils.assertNotNull(context) + val drawable = ContextCompat.getDrawable(context!!, R.drawable.big_sad_pandroid) + drawable!!.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight) + mTip!!.setCompoundDrawables(null, drawable, null, null) + mTip!!.setOnClickListener(this) + mHeader = ViewUtils.`$$`(mainView, R.id.header) as LinearLayout + mThumb = ViewUtils.`$$`(mHeader, R.id.thumb) as LoadImageView + mUploader = ViewUtils.`$$`(mHeader, R.id.uploader) as TextView + mCategory = ViewUtils.`$$`(mHeader, R.id.category) as TextView + mActionGroup = ViewUtils.`$$`(mHeader, R.id.action_card) as ViewGroup + mDownload = ViewUtils.`$$`(mActionGroup, R.id.download) as TextView + mRead = ViewUtils.`$$`(mActionGroup, R.id.read) as TextView + mUploader!!.setOnClickListener(this) + mCategory!!.setOnClickListener(this) + mDownload!!.setOnClickListener(this) + mDownload!!.setOnLongClickListener(this) + mRead!!.setOnClickListener(this) + mUploader!!.setOnLongClickListener(this) + mBelowHeader = mainView.findViewById(R.id.below_header) + val belowHeader = mBelowHeader + mInfo = ViewUtils.`$$`(mHeader, R.id.info) + mLanguage = ViewUtils.`$$`(mInfo, R.id.language) as TextView + mPages = ViewUtils.`$$`(mInfo, R.id.pages) as TextView + mSize = ViewUtils.`$$`(mInfo, R.id.size) as TextView + mPosted = ViewUtils.`$$`(mInfo, R.id.posted) as TextView + mFavoredTimes = ViewUtils.`$$`(mInfo, R.id.favoredTimes) as TextView + mInfo!!.setOnClickListener(this) + mActions = ViewUtils.`$$`(belowHeader, R.id.actions) + mNewerVersion = ViewUtils.`$$`(mActions, R.id.newerVersion) as TextView + mRatingText = ViewUtils.`$$`(mActions, R.id.rating_text) as TextView + mRating = ViewUtils.`$$`(mActions, R.id.rating) as RatingBar + mHeart = ViewUtils.`$$`(mActions, R.id.heart) as TextView + mHeartOutline = ViewUtils.`$$`(mActions, R.id.heart_outline) as TextView + mTorrent = ViewUtils.`$$`(mActions, R.id.torrent) as TextView + mArchive = ViewUtils.`$$`(mActions, R.id.archive) as TextView + mShare = ViewUtils.`$$`(mActions, R.id.share) as TextView + mRate = ViewUtils.`$$`(mActions, R.id.rate) + mSimilar = ViewUtils.`$$`(mActions, R.id.similar) as TextView + mSearchCover = ViewUtils.`$$`(mActions, R.id.search_cover) as TextView + mNewerVersion!!.setOnClickListener(this) + mHeart!!.setOnClickListener(this) + mHeart!!.setOnLongClickListener(this) + mHeartOutline!!.setOnClickListener(this) + mHeartOutline!!.setOnLongClickListener(this) + mTorrent!!.setOnClickListener(this) + mArchive!!.setOnClickListener(this) + mShare!!.setOnClickListener(this) + mRate!!.setOnClickListener(this) + mSimilar!!.setOnClickListener(this) + mSearchCover!!.setOnClickListener(this) + mTags = ViewUtils.`$$`(belowHeader, R.id.tags) as LinearLayout + mNoTags = ViewUtils.`$$`(mTags, R.id.no_tags) as TextView + mComments = ViewUtils.`$$`(belowHeader, R.id.comments) as LinearLayout if (Settings.getShowComments()) { - mCommentsText = (TextView) ViewUtils.$$(mComments, R.id.comments_text); - mComments.setOnClickListener(this); + mCommentsText = ViewUtils.`$$`(mComments, R.id.comments_text) as TextView + mComments!!.setOnClickListener(this) } else { - mComments.setVisibility(View.GONE); + mComments!!.visibility = View.GONE } - - mPreviews = ViewUtils.$$(belowHeader, R.id.previews); - mGridLayout = (SimpleGridAutoSpanLayout) ViewUtils.$$(mPreviews, R.id.grid_layout); - mPreviewText = (TextView) ViewUtils.$$(mPreviews, R.id.preview_text); - mPreviews.setOnClickListener(this); - - mProgress = ViewUtils.$$(mainView, R.id.progress); - - mViewTransition2 = new ViewTransition(mBelowHeader, mProgress); - + mPreviews = ViewUtils.`$$`(belowHeader, R.id.previews) + mGridLayout = ViewUtils.`$$`(mPreviews, R.id.grid_layout) as SimpleGridAutoSpanLayout + mPreviewText = ViewUtils.`$$`(mPreviews, R.id.preview_text) as TextView + mPreviews!!.setOnClickListener(this) + mProgress = ViewUtils.`$$`(mainView, R.id.progress) + mViewTransition2 = ViewTransition(mBelowHeader, mProgress) if (prepareData()) { if (mGalleryDetail != null) { - bindViewSecond(); - adjustViewVisibility(STATE_NORMAL); + bindViewSecond() + adjustViewVisibility(STATE_NORMAL) } else if (mGalleryInfo != null) { - bindViewFirst(); - adjustViewVisibility(STATE_REFRESH_HEADER); + bindViewFirst() + adjustViewVisibility(STATE_REFRESH_HEADER) } else { - adjustViewVisibility(STATE_REFRESH); + adjustViewVisibility(STATE_REFRESH) } } else { - mTip.setText(R.string.error_cannot_find_gallery); - adjustViewVisibility(STATE_FAILED); + mTip!!.setText(R.string.error_cannot_find_gallery) + adjustViewVisibility(STATE_FAILED) } - - EhApplication.getDownloadManager().addDownloadInfoListener(this); - ((MainActivity) requireActivity()).setMShareUrl(getGalleryDetailUrl()); - - return view; + downloadManager.addDownloadInfoListener(this) + (requireActivity() as MainActivity).mShareUrl = galleryDetailUrl + return view } - @Override - public void onDestroyView() { - super.onDestroyView(); - - Context context = getContext(); - AssertUtils.assertNotNull(context); - EhApplication.getDownloadManager().removeDownloadInfoListener(this); - ((MainActivity) requireActivity()).setMShareUrl(null); - - mTip = null; - mViewTransition = null; - - mHeader = null; - mThumb = null; - mUploader = null; - mCategory = null; - mActionGroup = null; - mDownload = null; - mRead = null; - mBelowHeader = null; - - mInfo = null; - mLanguage = null; - mPages = null; - mSize = null; - mPosted = null; - mFavoredTimes = null; - - mActions = null; - mNewerVersion = null; - mRatingText = null; - mRating = null; - mHeart = null; - mHeartOutline = null; - mTorrent = null; - mArchive = null; - mShare = null; - mRate = null; - mSimilar = null; - mSearchCover = null; - - mTags = null; - mNoTags = null; - - mComments = null; - mCommentsText = null; - - mPreviews = null; - mGridLayout = null; - mPreviewText = null; - - mProgress = null; - - mViewTransition2 = null; + override fun onDestroyView() { + super.onDestroyView() + val context = context + AssertUtils.assertNotNull(context) + downloadManager.removeDownloadInfoListener(this) + (requireActivity() as MainActivity).mShareUrl = null + mTip = null + mViewTransition = null + mHeader = null + mThumb = null + mUploader = null + mCategory = null + mActionGroup = null + mDownload = null + mRead = null + mBelowHeader = null + mInfo = null + mLanguage = null + mPages = null + mSize = null + mPosted = null + mFavoredTimes = null + mActions = null + mNewerVersion = null + mRatingText = null + mRating = null + mHeart = null + mHeartOutline = null + mTorrent = null + mArchive = null + mShare = null + mRate = null + mSimilar = null + mSearchCover = null + mTags = null + mNoTags = null + mComments = null + mCommentsText = null + mPreviews = null + mGridLayout = null + mPreviewText = null + mProgress = null + mViewTransition2 = null } - private boolean prepareData() { - Context context = getContext(); - AssertUtils.assertNotNull(context); - + private fun prepareData(): Boolean { + val context = context + AssertUtils.assertNotNull(context) if (mGalleryDetail != null) { - return true; + return true } - - long gid = getGid(); - if (gid == -1) { - return false; + val gid = gid + if (gid == -1L) { + return false } // Get from cache - mGalleryDetail = EhApplication.getGalleryDetailCache().get(gid); + mGalleryDetail = galleryDetailCache[gid] if (mGalleryDetail != null) { - return true; + return true } - - EhApplication application = (EhApplication) context.getApplicationContext(); - if (application.containGlobalStuff(mRequestId)) { + val application = context!!.applicationContext as EhApplication + return if (application.containGlobalStuff(mRequestId)) { // request exist - return true; - } + true + } else request() // Do request - return request(); } - private boolean request() { - Context context = getContext(); - MainActivity activity = getMainActivity(); - String url = getGalleryDetailUrl(); + private fun request(): Boolean { + val context = context + val activity = mainActivity + val url = galleryDetailUrl if (null == context || null == activity || null == url) { - return false; + return false } - - EhClient.Callback callback = new GetGalleryDetailListener(context); - mRequestId = ((EhApplication) context.getApplicationContext()).putGlobalStuff(callback); - EhRequest request = new EhRequest() - .setMethod(EhClient.METHOD_GET_GALLERY_DETAIL) - .setArgs(url) - .setCallback(callback); - request.enqueue(this); - - return true; + val callback: EhClient.Callback<*> = GetGalleryDetailListener(context) + mRequestId = (context.applicationContext as EhApplication).putGlobalStuff(callback) + val request = EhRequest() + .setMethod(EhClient.METHOD_GET_GALLERY_DETAIL) + .setArgs(url) + .setCallback(callback) + request.enqueue(this) + return true } - private void adjustViewVisibility(int state) { + private fun adjustViewVisibility(state: Int) { if (state == mState) { - return; + return } if (mViewTransition == null || mViewTransition2 == null) { - return; + return } - - mState = state; - - boolean animation = !TRANSITION_ANIMATION_DISABLED && animation; - - switch (state) { - case STATE_NORMAL -> { + mState = state + val animation = !TRANSITION_ANIMATION_DISABLED + when (state) { + STATE_NORMAL -> { // Show mMainView - mViewTransition.showView(0, animation); + mViewTransition!!.showView(0, animation) // Show mBelowHeader - mViewTransition2.showView(0, animation); + mViewTransition2!!.showView(0, animation) } - case STATE_REFRESH -> - // Show mProgressView - mViewTransition.showView(1, animation); - case STATE_REFRESH_HEADER -> { + + STATE_REFRESH -> // Show mProgressView + mViewTransition!!.showView(1, animation) + + STATE_REFRESH_HEADER -> { // Show mMainView - mViewTransition.showView(0, animation); + mViewTransition!!.showView(0, animation) // Show mProgress - mViewTransition2.showView(1, animation); + mViewTransition2!!.showView(1, animation) } - case STATE_INIT, STATE_FAILED -> - // Show mFailedView - mViewTransition.showView(2, animation); + + STATE_INIT, STATE_FAILED -> // Show mFailedView + mViewTransition!!.showView(2, animation) } } - private void bindViewFirst() { + private fun bindViewFirst() { if (mGalleryDetail != null) { - return; + return } if (mThumb == null || mUploader == null || mCategory == null) { - return; + return } - - if (ACTION_GALLERY_INFO.equals(mAction) && mGalleryInfo != null) { - GalleryInfo gi = mGalleryInfo; - mThumb.load(EhCacheKeyFactory.getThumbKey(gi.getGid()), gi.getThumb()); - setTitle(EhUtils.getSuitableTitle(gi)); - mUploader.setText(gi.getUploader()); - mUploader.setAlpha(gi.getDisowned() ? .5f : 1f); - mCategory.setText(EhUtils.getCategory(gi.getCategory())); - mCategory.setTextColor(EhUtils.getCategoryColor(gi.getCategory())); - updateDownloadText(); + if (ACTION_GALLERY_INFO == mAction && mGalleryInfo != null) { + val gi: GalleryInfo = mGalleryInfo!! + mThumb!!.load(EhCacheKeyFactory.getThumbKey(gi.gid), gi.thumb!!) + setTitle(EhUtils.getSuitableTitle(gi)) + mUploader!!.text = gi.uploader + mUploader!!.alpha = if (gi.disowned) .5f else 1f + mCategory!!.text = EhUtils.getCategory(gi.category) + mCategory!!.setTextColor(EhUtils.getCategoryColor(gi.category)) + updateDownloadText() } } - private void updateFavoriteDrawable() { - GalleryDetail gd = mGalleryDetail; - if (gd == null) { - return; - } + private fun updateFavoriteDrawable() { + val gd = mGalleryDetail ?: return if (mHeart == null || mHeartOutline == null) { - return; + return } - - if (gd.isFavorited || EhDB.containLocalFavorites(gd.getGid())) { - mHeart.setVisibility(View.VISIBLE); - if (gd.getFavoriteName() == null) { - mHeart.setText(R.string.local_favorites); + if (gd.isFavorited || EhDB.containLocalFavorites(gd.gid)) { + mHeart!!.visibility = View.VISIBLE + if (gd.favoriteName == null) { + mHeart!!.setText(R.string.local_favorites) } else { - mHeart.setText(gd.getFavoriteName()); + mHeart!!.text = gd.favoriteName } - mHeartOutline.setVisibility(View.GONE); + mHeartOutline!!.visibility = View.GONE } else { - mHeart.setVisibility(View.GONE); - mHeartOutline.setVisibility(View.VISIBLE); + mHeart!!.visibility = View.GONE + mHeartOutline!!.visibility = View.VISIBLE } } - private void bindViewSecond() { - GalleryDetail gd = mGalleryDetail; - if (gd == null) { - return; - } + private fun bindViewSecond() { + val gd = mGalleryDetail ?: return if (mPage != 0) { - Snackbar.make(requireActivity().findViewById(R.id.snackbar), getString(R.string.read_from, mPage), Snackbar.LENGTH_LONG) - .setAction(R.string.read, v -> { - Intent intent = new Intent(requireContext(), ReaderActivity.class); - intent.setAction(ReaderActivity.ACTION_EH); - intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, mGalleryDetail); - intent.putExtra(ReaderActivity.KEY_PAGE, mPage); - startActivity(intent); - }) - .show(); - } - if (mThumb == null || mUploader == null || mCategory == null || - mLanguage == null || mPages == null || mSize == null || mPosted == null || - mFavoredTimes == null || mRatingText == null || mRating == null || mTorrent == null || mNewerVersion == null) { - return; - } - - Resources resources = getResources(); - - mThumb.load(EhCacheKeyFactory.getThumbKey(gd.getGid()), gd.getThumb(), true); - setTitle(EhUtils.getSuitableTitle(gd)); - mUploader.setText(gd.getUploader()); - mUploader.setAlpha(gd.getDisowned() ? .5f : 1f); - mCategory.setText(EhUtils.getCategory(gd.getCategory())); - mCategory.setTextColor(EhUtils.getCategoryColor(gd.getCategory())); - updateDownloadText(); - - mLanguage.setText(gd.language); - mPages.setText(resources.getQuantityString( - R.plurals.page_count, gd.getPages(), gd.getPages())); - mSize.setText(gd.size); - mPosted.setText(gd.getPosted()); - mFavoredTimes.setText(resources.getString(R.string.favored_times, gd.favoriteCount)); - if (gd.newerVersions != null && gd.newerVersions.size() != 0) { - mNewerVersion.setVisibility(View.VISIBLE); - } - - mRatingText.setText(getAllRatingText(gd.getRating(), gd.ratingCount)); - mRating.setRating(gd.getRating()); - - updateFavoriteDrawable(); - - mTorrent.setText(resources.getString(R.string.torrent_count, gd.torrentCount)); - - bindTags(gd.tags); - bindComments(gd.comments.comments); - bindPreviews(gd); - } - - private void bindTags(GalleryTagGroup[] tagGroups) { - Context context = getContext(); - LayoutInflater inflater = getLayoutInflater(); - if (null == context || null == mTags || null == mNoTags) { - return; - } - - mTags.removeViews(1, mTags.getChildCount() - 1); - if (tagGroups == null || tagGroups.length == 0) { - mNoTags.setVisibility(View.VISIBLE); - return; - } else { - mNoTags.setVisibility(View.GONE); - } - - EhTagDatabase ehTags = Settings.getShowTagTranslations() && EhTagDatabase.INSTANCE.isTranslatable(context) ? EhTagDatabase.INSTANCE : null; - int colorTag = ResourcesKt.resolveColor(getTheme(), R.attr.tagBackgroundColor); - int colorName = ResourcesKt.resolveColor(getTheme(), R.attr.tagGroupBackgroundColor); - for (GalleryTagGroup tg : tagGroups) { - LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.gallery_tag_group, mTags, false); - ll.setOrientation(LinearLayout.HORIZONTAL); - mTags.addView(ll); - - String readableTagName = null; - if (ehTags != null && ehTags.isInitialized()) { - readableTagName = ehTags.getTranslation("n", tg.groupName); - } - - TextView tgName = (TextView) inflater.inflate(R.layout.item_gallery_tag, ll, false); - ll.addView(tgName); - tgName.setText(readableTagName != null ? readableTagName : tg.groupName); - tgName.setBackgroundTintList(ColorStateList.valueOf(colorName)); - - String prefix = EhTagDatabase.namespaceToPrefix(tg.groupName); - - AutoWrapLayout awl = new AutoWrapLayout(context); - ll.addView(awl, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - for (int j = 0, z = tg.size(); j < z; j++) { - TextView tag = (TextView) inflater.inflate(R.layout.item_gallery_tag, awl, false); - awl.addView(tag); - String tagStr = tg.getTagAt(j); - - String readableTag = null; - if (ehTags != null && ehTags.isInitialized()) { - readableTag = ehTags.getTranslation(prefix, tagStr); + Snackbar.make( + requireActivity().findViewById(R.id.snackbar), + getString(R.string.read_from, mPage), + Snackbar.LENGTH_LONG + ) + .setAction(R.string.read) { + val intent = Intent(requireContext(), ReaderActivity::class.java) + intent.action = ReaderActivity.ACTION_EH + intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, mGalleryDetail) + intent.putExtra(ReaderActivity.KEY_PAGE, mPage) + startActivity(intent) } + .show() + } + if (mThumb == null || mUploader == null || mCategory == null || mLanguage == null || mPages == null || mSize == null || mPosted == null || mFavoredTimes == null || mRatingText == null || mRating == null || mTorrent == null || mNewerVersion == null) { + return + } + val resources = resources + mThumb!!.load(EhCacheKeyFactory.getThumbKey(gd.gid), gd.thumb!!, true) + setTitle(EhUtils.getSuitableTitle(gd)) + mUploader!!.text = gd.uploader + mUploader!!.alpha = if (gd.disowned) .5f else 1f + mCategory!!.text = EhUtils.getCategory(gd.category) + mCategory!!.setTextColor(EhUtils.getCategoryColor(gd.category)) + updateDownloadText() + mLanguage!!.text = gd.language + mPages!!.text = resources.getQuantityString( + R.plurals.page_count, gd.pages, gd.pages + ) + mSize!!.text = gd.size + mPosted!!.text = gd.posted + mFavoredTimes!!.text = resources.getString(R.string.favored_times, gd.favoriteCount) + if (gd.newerVersions.size != 0) { + mNewerVersion!!.visibility = View.VISIBLE + } + mRatingText!!.text = getAllRatingText(gd.rating, gd.ratingCount) + mRating!!.rating = gd.rating + updateFavoriteDrawable() + mTorrent!!.text = resources.getString(R.string.torrent_count, gd.torrentCount) + bindTags(gd.tags) + bindComments(gd.comments!!.comments) + bindPreviews(gd) + } - tag.setText(readableTag != null ? readableTag : tagStr); - tag.setBackgroundTintList(ColorStateList.valueOf(colorTag)); - tag.setTag(R.id.tag, tg.groupName + ":" + tagStr); - tag.setOnClickListener(this); - tag.setOnLongClickListener(this); + private fun bindTags(tagGroups: Array?) { + val context = context + val inflater = layoutInflater + if (null == context || null == mTags || null == mNoTags) { + return + } + mTags!!.removeViews(1, mTags!!.childCount - 1) + if (tagGroups.isNullOrEmpty()) { + mNoTags!!.visibility = View.VISIBLE + return + } else { + mNoTags!!.visibility = View.GONE + } + val ehTags = + if (Settings.getShowTagTranslations() && isTranslatable(context)) EhTagDatabase else null + val colorTag = theme.resolveColor(R.attr.tagBackgroundColor) + val colorName = theme.resolveColor(R.attr.tagGroupBackgroundColor) + for (tg in tagGroups) { + val ll = inflater.inflate(R.layout.gallery_tag_group, mTags, false) as LinearLayout + ll.orientation = LinearLayout.HORIZONTAL + mTags!!.addView(ll) + var readableTagName: String? = null + if (ehTags != null && ehTags.isInitialized()) { + readableTagName = ehTags.getTranslation("n", tg.groupName) + } + val tgName = inflater.inflate(R.layout.item_gallery_tag, ll, false) as TextView + ll.addView(tgName) + tgName.text = readableTagName ?: tg.groupName + tgName.backgroundTintList = ColorStateList.valueOf(colorName) + val prefix = namespaceToPrefix(tg.groupName!!) + val awl = AutoWrapLayout(context) + ll.addView( + awl, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + var j = 0 + val z = tg.size() + while (j < z) { + val tag = inflater.inflate(R.layout.item_gallery_tag, awl, false) as TextView + awl.addView(tag) + val tagStr = tg.getTagAt(j) + var readableTag: String? = null + if (ehTags != null && ehTags.isInitialized()) { + readableTag = ehTags.getTranslation(prefix, tagStr) + } + tag.text = readableTag ?: tagStr + tag.backgroundTintList = ColorStateList.valueOf(colorTag) + tag.setTag(R.id.tag, tg.groupName + ":" + tagStr) + tag.setOnClickListener(this) + tag.setOnLongClickListener(this) + j++ } } } - private void bindComments(GalleryComment[] comments) { - Context context = getContext(); - LayoutInflater inflater = getLayoutInflater(); + private fun bindComments(comments: Array?) { + val context = context + val inflater = layoutInflater if (null == context || null == mComments || null == mCommentsText) { - return; + return } - - mComments.removeViews(0, mComments.getChildCount() - 1); - - final int maxShowCount = 2; - if (comments == null || comments.length == 0) { - mCommentsText.setText(R.string.no_comments); - return; - } else if (comments.length <= maxShowCount) { - mCommentsText.setText(R.string.no_more_comments); + mComments!!.removeViews(0, mComments!!.childCount - 1) + val maxShowCount = 2 + if (comments.isNullOrEmpty()) { + mCommentsText!!.setText(R.string.no_comments) + return + } else if (comments.size <= maxShowCount) { + mCommentsText!!.setText(R.string.no_more_comments) } else { - mCommentsText.setText(R.string.more_comment); + mCommentsText!!.setText(R.string.more_comment) } - - int length = Math.min(maxShowCount, comments.length); - for (int i = 0; i < length; i++) { - GalleryComment comment = comments[i]; - View v = inflater.inflate(R.layout.item_gallery_comment, mComments, false); - mComments.addView(v, i); - TextView user = v.findViewById(R.id.user); - user.setText(comment.user); - user.setBackgroundColor(Color.TRANSPARENT); - TextView time = v.findViewById(R.id.time); - time.setText(ReadableTime.getTimeAgo(comment.time)); - ObservedTextView c = v.findViewById(R.id.comment); - c.setMaxLines(5); - c.setText(Html.fromHtml(comment.comment, Html.FROM_HTML_MODE_LEGACY, - new URLImageGetter(c), null)); - v.setBackgroundColor(Color.TRANSPARENT); + val length = maxShowCount.coerceAtMost(comments.size) + for (i in 0 until length) { + val comment = comments[i] + val v = inflater.inflate(R.layout.item_gallery_comment, mComments, false) + mComments!!.addView(v, i) + val user = v.findViewById(R.id.user) + user.text = comment.user + user.setBackgroundColor(Color.TRANSPARENT) + val time = v.findViewById(R.id.time) + time.text = ReadableTime.getTimeAgo(comment.time) + val c = v.findViewById(R.id.comment) + c.maxLines = 5 + c.text = Html.fromHtml( + comment.comment, Html.FROM_HTML_MODE_LEGACY, + URLImageGetter(c), null + ) + v.setBackgroundColor(Color.TRANSPARENT) } } @SuppressLint("SetTextI18n") - private void bindPreviews(GalleryDetail gd) { - LayoutInflater inflater = getLayoutInflater(); - Resources resources = getResourcesOrNull(); - int previewNum = Settings.getPreviewNum(); + private fun bindPreviews(gd: GalleryDetail) { + val inflater = layoutInflater + val resources = resourcesOrNull + val previewNum = Settings.getPreviewNum() if (null == resources || null == mGridLayout || null == mPreviewText) { - return; + return } - - mGridLayout.removeAllViews(); - PreviewSet previewSet = gd.previewSet; + mGridLayout!!.removeAllViews() + val previewSet = gd.previewSet if (gd.previewPages <= 0 || previewSet == null || previewSet.size() == 0) { - mPreviewText.setText(R.string.no_previews); - return; + mPreviewText!!.setText(R.string.no_previews) + return } else if (gd.previewPages == 1 && previewSet.size() <= previewNum) { - mPreviewText.setText(R.string.no_more_previews); + mPreviewText!!.setText(R.string.no_more_previews) } else { - mPreviewText.setText(R.string.more_previews); + mPreviewText!!.setText(R.string.more_previews) } - - int columnWidth = Settings.getThumbSize(); - mGridLayout.setColumnSize(columnWidth); - mGridLayout.setStrategy(SimpleGridAutoSpanLayout.STRATEGY_SUITABLE_SIZE); - int size = Math.min(previewNum, previewSet.size()); - for (int i = 0; i < size; i++) { - View view = inflater.inflate(R.layout.item_gallery_preview, mGridLayout, false); - mGridLayout.addView(view); - - LoadImageView image = view.findViewById(R.id.image); - previewSet.load(image, gd.getGid(), i); - image.setTag(R.id.index, i); - image.setOnClickListener(this); - TextView text = view.findViewById(R.id.text); - text.setText(Integer.toString(previewSet.getPosition(i) + 1)); + val columnWidth = Settings.getThumbSize() + mGridLayout!!.setColumnSize(columnWidth) + mGridLayout!!.setStrategy(SimpleGridAutoSpanLayout.STRATEGY_SUITABLE_SIZE) + val size = previewNum.coerceAtMost(previewSet.size()) + for (i in 0 until size) { + val view = inflater.inflate(R.layout.item_gallery_preview, mGridLayout, false) + mGridLayout!!.addView(view) + val image = view.findViewById(R.id.image) + previewSet.load(image, gd.gid, i) + image.setTag(R.id.index, i) + image.setOnClickListener(this) + val text = view.findViewById(R.id.text) + text.text = (previewSet.getPosition(i) + 1).toString() } } - private String getAllRatingText(float rating, int ratingCount) { - return getString(R.string.rating_text, getString(getRatingText(rating)), rating, ratingCount); + private fun getAllRatingText(rating: Float, ratingCount: Int): String { + return getString( + R.string.rating_text, + getString(getRatingText(rating)), + rating, + ratingCount + ) } - private void showSimilarGalleryList() { - GalleryDetail gd = mGalleryDetail; - if (null == gd) { - return; - } - String keyword = EhUtils.extractTitle(gd.getTitle()); + private fun showSimilarGalleryList() { + val gd = mGalleryDetail ?: return + val keyword = EhUtils.extractTitle(gd.title) if (null != keyword) { - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_NORMAL); - lub.setKeyword("\"" + keyword + "\""); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - return; + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_NORMAL + lub.keyword = "\"" + keyword + "\"" + navigate(R.id.galleryListScene, getStartArgs(lub), true) + return } - String artist = getArtist(gd.tags); + val artist = getArtist(gd.tags) if (null != artist) { - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_TAG); - lub.setKeyword("artist:" + artist); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - return; + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_TAG + lub.keyword = "artist:$artist" + navigate(R.id.galleryListScene, getStartArgs(lub), true) + return } - if (null != gd.getUploader()) { - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_UPLOADER); - lub.setKeyword(gd.getUploader()); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); + if (null != gd.uploader) { + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_UPLOADER + lub.keyword = gd.uploader + navigate(R.id.galleryListScene, getStartArgs(lub), true) } } - private void showCoverGalleryList() { - Context context = getContext(); - if (null == context) { - return; - } - long gid = getGid(); + @OptIn(ExperimentalCoilApi::class) + private fun showCoverGalleryList() { + val context = context ?: return + val gid = gid if (-1L == gid) { - return; + return } - try { - var path = Coil.imageLoader(context).getDiskCache().get(EhCacheKeyFactory.getThumbKey(gid)).getData(); - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_IMAGE_SEARCH); - lub.setImagePath(path.toString()); - lub.setUseSimilarityScan(true); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - } catch (Throwable e) { - e.printStackTrace(); + val path = imageLoader(context).diskCache!![EhCacheKeyFactory.getThumbKey(gid)]!!.data + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_IMAGE_SEARCH + lub.imagePath = path.toString() + lub.isUseSimilarityScan = true + navigate(R.id.galleryListScene, getStartArgs(lub), true) + } catch (e: Throwable) { + e.printStackTrace() } } - @Override - public void onClick(View v) { - Context context = getContext(); - MainActivity activity = getMainActivity(); + override fun onClick(v: View) { + val context = context + val activity = mainActivity if (null == context || null == activity) { - return; + return } - - if (mTip == v) { + if (mTip === v) { if (request()) { - adjustViewVisibility(STATE_REFRESH); + adjustViewVisibility(STATE_REFRESH) } - } else if (mUploader == v) { - String uploader = getUploader(); - if (TextUtils.isEmpty(uploader) || getDisowned()) { - return; + } else if (mUploader === v) { + val uploader = uploader + if (TextUtils.isEmpty(uploader) || disowned) { + return } - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_UPLOADER); - lub.setKeyword(uploader); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - } else if (mCategory == v) { - int category = getCategory(); + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_UPLOADER + lub.keyword = uploader + navigate(R.id.galleryListScene, getStartArgs(lub), true) + } else if (mCategory === v) { + val category = this.category if (category == EhUtils.NONE || category == EhUtils.PRIVATE || category == EhUtils.UNKNOWN) { - return; + return } - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setCategory(category); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - } else if (mDownload == v) { - GalleryInfo galleryInfo = getGalleryInfo(); + val lub = ListUrlBuilder() + lub.category = category + navigate(R.id.galleryListScene, getStartArgs(lub), true) + } else if (mDownload === v) { + val galleryInfo = galleryInfo if (galleryInfo != null) { - if (EhApplication.getDownloadManager().getDownloadState(galleryInfo.getGid()) == DownloadInfo.STATE_INVALID) { - CommonOperations.startDownload(activity, galleryInfo, false); + if (downloadManager.getDownloadState(galleryInfo.gid) == DownloadInfo.STATE_INVALID) { + CommonOperations.startDownload(activity, galleryInfo, false) } else { - CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(context, - getString(R.string.download_remove_dialog_message, galleryInfo.getTitle()), - getString(R.string.download_remove_dialog_check_text), - Settings.getRemoveImageFiles()); - DeleteDialogHelper helper = new DeleteDialogHelper( - EhApplication.getDownloadManager(), galleryInfo, builder); + val builder = CheckBoxDialogBuilder( + context, + getString(R.string.download_remove_dialog_message, galleryInfo.title), + getString(R.string.download_remove_dialog_check_text), + Settings.getRemoveImageFiles() + ) + val helper = DeleteDialogHelper( + downloadManager, galleryInfo, builder + ) builder.setTitle(R.string.download_remove_dialog_title) - .setPositiveButton(android.R.string.ok, helper) - .show(); + .setPositiveButton(android.R.string.ok, helper) + .show() } } - } else if (mRead == v) { - GalleryInfo galleryInfo = null; + } else if (mRead === v) { + var galleryInfo: GalleryInfo? = null if (mGalleryInfo != null) { - galleryInfo = mGalleryInfo; + galleryInfo = mGalleryInfo } else if (mGalleryDetail != null) { - galleryInfo = mGalleryDetail; + galleryInfo = mGalleryDetail } if (galleryInfo != null) { - Intent intent = new Intent(activity, ReaderActivity.class); - intent.setAction(ReaderActivity.ACTION_EH); - intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, galleryInfo); - startActivity(intent); + val intent = Intent(activity, ReaderActivity::class.java) + intent.action = ReaderActivity.ACTION_EH + intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, galleryInfo) + startActivity(intent) } - } else if (mNewerVersion == v) { + } else if (mNewerVersion === v) { if (mGalleryDetail != null) { - ArrayList titles = new ArrayList<>(); - for (GalleryInfo newerVersion : mGalleryDetail.newerVersions) { - titles.add(getString(R.string.newer_version_title, newerVersion.getTitle(), newerVersion.getPosted())); + val titles = ArrayList() + for (newerVersion in mGalleryDetail!!.newerVersions) { + titles.add( + getString( + R.string.newer_version_title, + newerVersion.title, + newerVersion.posted + ) + ) } - new BaseDialogBuilder(requireContext()) - .setItems(titles.toArray(new CharSequence[0]), (dialog, which) -> { - GalleryInfo newerVersion = mGalleryDetail.newerVersions.get(which); - Bundle args = new Bundle(); - args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GID_TOKEN); - args.putLong(GalleryDetailScene.KEY_GID, newerVersion.getGid()); - args.putString(GalleryDetailScene.KEY_TOKEN, newerVersion.getToken()); - navigate(R.id.galleryDetailScene, args); - }) - .show(); + BaseDialogBuilder(requireContext()) + .setItems(titles.toTypedArray()) { _: DialogInterface?, which: Int -> + val newerVersion = mGalleryDetail!!.newerVersions[which] + val args = Bundle() + args.putString(KEY_ACTION, ACTION_GID_TOKEN) + args.putLong(KEY_GID, newerVersion.gid) + args.putString(KEY_TOKEN, newerVersion.token) + navigate(R.id.galleryDetailScene, args) + } + .show() } - } else if (mInfo == v) { - assert mGalleryDetail != null; - var galleryInfoBottomSheet = new GalleryInfoBottomSheet(mGalleryDetail); - galleryInfoBottomSheet.show(requireActivity().getSupportFragmentManager(), GalleryInfoBottomSheet.TAG); - } else if (mHeart == v || mHeartOutline == v) { + } else if (mInfo === v) { + assert(mGalleryDetail != null) + val galleryInfoBottomSheet = GalleryInfoBottomSheet(mGalleryDetail!!) + galleryInfoBottomSheet.show( + requireActivity().supportFragmentManager, + GalleryInfoBottomSheet.TAG + ) + } else if (mHeart === v || mHeartOutline === v) { if (mGalleryDetail != null && !mModifyingFavorites) { - boolean remove = false; - if (EhDB.containLocalFavorites(mGalleryDetail.getGid()) || mGalleryDetail.isFavorited) { - mModifyingFavorites = true; - CommonOperations.removeFromFavorites(activity, mGalleryDetail, - new ModifyFavoritesListener(context, true)); - remove = true; + var remove = false + if (EhDB.containLocalFavorites(mGalleryDetail!!.gid) || mGalleryDetail!!.isFavorited) { + mModifyingFavorites = true + CommonOperations.removeFromFavorites( + activity, mGalleryDetail, + ModifyFavoritesListener(context, true) + ) + remove = true } if (!remove) { - mModifyingFavorites = true; - CommonOperations.addToFavorites(activity, mGalleryDetail, - new ModifyFavoritesListener(context, false)); + mModifyingFavorites = true + CommonOperations.addToFavorites( + activity, mGalleryDetail, + ModifyFavoritesListener(context, false) + ) } // Update UI - updateFavoriteDrawable(); + updateFavoriteDrawable() } - } else if (mShare == v) { - String url = getGalleryDetailUrl(); + } else if (mShare === v) { + val url = galleryDetailUrl if (url != null) { - AppHelper.share(activity, url); + AppHelper.share(activity, url) } - } else if (mTorrent == v) { + } else if (mTorrent === v) { if (mGalleryDetail != null) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - requestStoragePermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE); + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission( + requireActivity(), + Manifest.permission.WRITE_EXTERNAL_STORAGE + ) + != PackageManager.PERMISSION_GRANTED + ) { + requestStoragePermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) } else { - TorrentListDialogHelper helper = new TorrentListDialogHelper(); - Dialog dialog = new BaseDialogBuilder(context) - .setTitle(R.string.torrents) - .setView(R.layout.dialog_torrent_list) - .setOnDismissListener(helper) - .show(); - helper.setDialog(dialog, mGalleryDetail.torrentUrl); + val helper = TorrentListDialogHelper() + val dialog: Dialog = BaseDialogBuilder(context) + .setTitle(R.string.torrents) + .setView(R.layout.dialog_torrent_list) + .setOnDismissListener(helper) + .show() + helper.setDialog(dialog, mGalleryDetail!!.torrentUrl) } } - } else if (mArchive == v) { + } else if (mArchive === v) { if (mGalleryDetail == null) { - return; + return } - if (mGalleryDetail.apiUid < 0) { - showTip(R.string.sign_in_first, LENGTH_LONG); - return; + if (mGalleryDetail!!.apiUid < 0) { + showTip(R.string.sign_in_first, LENGTH_LONG) + return } - ArchiveListDialogHelper helper = new ArchiveListDialogHelper(); - Dialog dialog = new BaseDialogBuilder(context) - .setTitle(R.string.settings_download) - .setView(R.layout.dialog_archive_list) - .setOnDismissListener(helper) - .show(); - helper.setDialog(dialog, mGalleryDetail.archiveUrl); - } else if (mRate == v) { + val helper = ArchiveListDialogHelper() + val dialog: Dialog = BaseDialogBuilder(context) + .setTitle(R.string.settings_download) + .setView(R.layout.dialog_archive_list) + .setOnDismissListener(helper) + .show() + helper.setDialog(dialog, mGalleryDetail!!.archiveUrl) + } else if (mRate === v) { if (mGalleryDetail == null) { - return; + return } - if (mGalleryDetail.apiUid < 0) { - showTip(R.string.sign_in_first, LENGTH_LONG); - return; + if (mGalleryDetail!!.apiUid < 0) { + showTip(R.string.sign_in_first, LENGTH_LONG) + return } - RateDialogHelper helper = new RateDialogHelper(); - Dialog dialog = new BaseDialogBuilder(context) - .setTitle(R.string.rate) - .setView(R.layout.dialog_rate) - .setNegativeButton(android.R.string.cancel, null) - .setPositiveButton(android.R.string.ok, helper) - .show(); - helper.setDialog(dialog, mGalleryDetail.getRating()); - } else if (mSimilar == v) { - showSimilarGalleryList(); - } else if (mSearchCover == v) { - showCoverGalleryList(); - } else if (mComments == v) { + val helper = RateDialogHelper() + val dialog: Dialog = BaseDialogBuilder(context) + .setTitle(R.string.rate) + .setView(R.layout.dialog_rate) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(android.R.string.ok, helper) + .show() + helper.setDialog(dialog, mGalleryDetail!!.rating) + } else if (mSimilar === v) { + showSimilarGalleryList() + } else if (mSearchCover === v) { + showCoverGalleryList() + } else if (mComments === v) { if (mGalleryDetail == null) { - return; + return } - Bundle args = new Bundle(); - args.putLong(GalleryCommentsScene.KEY_API_UID, mGalleryDetail.apiUid); - args.putString(GalleryCommentsScene.KEY_API_KEY, mGalleryDetail.apiKey); - args.putLong(GalleryCommentsScene.KEY_GID, mGalleryDetail.getGid()); - args.putString(GalleryCommentsScene.KEY_TOKEN, mGalleryDetail.getToken()); - args.putParcelable(GalleryCommentsScene.KEY_COMMENT_LIST, mGalleryDetail.comments); - args.putParcelable(GalleryCommentsScene.KEY_GALLERY_DETAIL, mGalleryDetail); - navigate(R.id.galleryCommentsScene, args); - } else if (mPreviews == v) { + val args = Bundle() + args.putLong(GalleryCommentsScene.KEY_API_UID, mGalleryDetail!!.apiUid) + args.putString(GalleryCommentsScene.KEY_API_KEY, mGalleryDetail!!.apiKey) + args.putLong(GalleryCommentsScene.KEY_GID, mGalleryDetail!!.gid) + args.putString(GalleryCommentsScene.KEY_TOKEN, mGalleryDetail!!.token) + args.putParcelable(GalleryCommentsScene.KEY_COMMENT_LIST, mGalleryDetail!!.comments) + args.putParcelable(GalleryCommentsScene.KEY_GALLERY_DETAIL, mGalleryDetail) + navigate(R.id.galleryCommentsScene, args) + } else if (mPreviews === v) { if (null != mGalleryDetail) { - Bundle args = new Bundle(); - args.putParcelable(GalleryPreviewsScene.KEY_GALLERY_INFO, mGalleryDetail); - navigate(R.id.galleryPreviewsScene, args); + val args = Bundle() + args.putParcelable(GalleryPreviewsScene.KEY_GALLERY_INFO, mGalleryDetail) + navigate(R.id.galleryPreviewsScene, args) } } else { - Object o = v.getTag(R.id.tag); - if (o instanceof String tag) { - ListUrlBuilder lub = new ListUrlBuilder(); - lub.setMode(ListUrlBuilder.MODE_TAG); - lub.setKeyword(tag); - navigate(R.id.galleryListScene, GalleryListScene.getStartArgs(lub), true); - return; + var o = v.getTag(R.id.tag) + if (o is String) { + val lub = ListUrlBuilder() + lub.mode = ListUrlBuilder.MODE_TAG + lub.keyword = o + navigate(R.id.galleryListScene, getStartArgs(lub), true) + return } - - GalleryInfo galleryInfo = getGalleryInfo(); - o = v.getTag(R.id.index); - if (null != galleryInfo && o instanceof Integer) { - int index = (Integer) o; - Intent intent = new Intent(context, ReaderActivity.class); - intent.setAction(ReaderActivity.ACTION_EH); - intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, galleryInfo); - intent.putExtra(ReaderActivity.KEY_PAGE, index); - startActivity(intent); + val galleryInfo = galleryInfo + o = v.getTag(R.id.index) + if (null != galleryInfo && o is Int) { + val intent = Intent(context, ReaderActivity::class.java) + intent.action = ReaderActivity.ACTION_EH + intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, galleryInfo) + intent.putExtra(ReaderActivity.KEY_PAGE, o) + startActivity(intent) } } } - private void showFilterUploaderDialog() { - Context context = getContext(); - String uploader = getUploader(); + private fun showFilterUploaderDialog() { + val context = context + val uploader = uploader if (context == null || uploader == null) { - return; + return } - - new BaseDialogBuilder(context) - .setMessage(getString(R.string.filter_the_uploader, uploader)) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - Filter filter = new Filter(); - filter.mode = EhFilter.MODE_UPLOADER; - filter.text = uploader; - EhFilter.getInstance().addFilter(filter); - - showTip(R.string.filter_added, LENGTH_SHORT); - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); + BaseDialogBuilder(context) + .setMessage(getString(R.string.filter_the_uploader, uploader)) + .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> + val filter = Filter() + filter.mode = EhFilter.MODE_UPLOADER + filter.text = uploader + EhFilter.getInstance().addFilter(filter) + showTip(R.string.filter_added, LENGTH_SHORT) + } + .setNegativeButton(android.R.string.cancel, null) + .show() } - private void showFilterTagDialog(String tag) { - Context context = getContext(); - if (context == null) { - return; - } - - new BaseDialogBuilder(context) - .setMessage(getString(R.string.filter_the_tag, tag)) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - Filter filter = new Filter(); - filter.mode = EhFilter.MODE_TAG; - filter.text = tag; - EhFilter.getInstance().addFilter(filter); - - showTip(R.string.filter_added, LENGTH_SHORT); - }) - .setNegativeButton(android.R.string.cancel, null) - .show(); + private fun showFilterTagDialog(tag: String) { + val context = context ?: return + BaseDialogBuilder(context) + .setMessage(getString(R.string.filter_the_tag, tag)) + .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> + val filter = Filter() + filter.mode = EhFilter.MODE_TAG + filter.text = tag + EhFilter.getInstance().addFilter(filter) + showTip(R.string.filter_added, LENGTH_SHORT) + } + .setNegativeButton(android.R.string.cancel, null) + .show() } - private void showTagDialog(TextView tv, final String tag) { - final Context context = getContext(); - if (null == context) { - return; - } - String temp; - int index = tag.indexOf(':'); - if (index >= 0) { - temp = tag.substring(index + 1); + private fun showTagDialog(tv: TextView, tag: String) { + val context = context ?: return + val temp: String + val index = tag.indexOf(':') + temp = if (index >= 0) { + tag.substring(index + 1) } else { - temp = tag; + tag } - final String tag2 = temp; - - List menu = new ArrayList<>(); - final IntList menuId = new IntList(); - Resources resources = context.getResources(); - - menu.add(resources.getString(android.R.string.copy)); - menuId.add(R.id.copy); - if (!tag2.equals(tv.getText().toString())) { - menu.add(resources.getString(R.string.copy_trans)); - menuId.add(R.id.copy_trans); + val menu: MutableList = ArrayList() + val menuId = IntList() + val resources = context.resources + menu.add(resources.getString(android.R.string.copy)) + menuId.add(R.id.copy) + if (temp != tv.text.toString()) { + menu.add(resources.getString(R.string.copy_trans)) + menuId.add(R.id.copy_trans) } - menu.add(resources.getString(R.string.show_definition)); - menuId.add(R.id.show_definition); - menu.add(resources.getString(R.string.add_filter)); - menuId.add(R.id.add_filter); - if (mGalleryDetail != null && mGalleryDetail.apiUid >= 0) { - menu.add(resources.getString(R.string.tag_vote_up)); - menuId.add(R.id.vote_up); - menu.add(resources.getString(R.string.tag_vote_down)); - menuId.add(R.id.vote_down); + menu.add(resources.getString(R.string.show_definition)) + menuId.add(R.id.show_definition) + menu.add(resources.getString(R.string.add_filter)) + menuId.add(R.id.add_filter) + if (mGalleryDetail != null && mGalleryDetail!!.apiUid >= 0) { + menu.add(resources.getString(R.string.tag_vote_up)) + menuId.add(R.id.vote_up) + menu.add(resources.getString(R.string.tag_vote_down)) + menuId.add(R.id.vote_down) } - - new BaseDialogBuilder(context) - .setTitle(tag) - .setItems(menu.toArray(new String[0]), (dialog, which) -> { - if (which < 0 || which >= menuId.size()) { - return; + BaseDialogBuilder(context) + .setTitle(tag) + .setItems(menu.toTypedArray()) { _: DialogInterface?, which: Int -> + if (which < 0 || which >= menuId.size()) { + return@setItems + } + when (menuId[which]) { + R.id.vote_up -> { + voteTag(tag, 1) } - int id = menuId.get(which); - if (id == R.id.vote_up) { - voteTag(tag, 1); - } else if (id == R.id.vote_down) { - voteTag(tag, -1); - } else if (id == R.id.show_definition) { - UrlOpener.openUrl(context, EhUrl.getTagDefinitionUrl(tag2), false); - } else if (id == R.id.add_filter) { - showFilterTagDialog(tag); - } else if (id == R.id.copy) { - ClipboardUtilKt.addTextToClipboard(requireActivity(), tag, false); - } else if (id == R.id.copy_trans) { - ClipboardUtilKt.addTextToClipboard(requireActivity(), tv.getText().toString(), false); + + R.id.vote_down -> { + voteTag(tag, -1) } - }).show(); + + R.id.show_definition -> { + UrlOpener.openUrl(context, EhUrl.getTagDefinitionUrl(temp), false) + } + + R.id.add_filter -> { + showFilterTagDialog(tag) + } + + R.id.copy -> { + requireActivity().addTextToClipboard(tag, false) + } + + R.id.copy_trans -> { + requireActivity().addTextToClipboard(tv.text.toString(), false) + } + } + }.show() } - private void voteTag(String tag, int vote) { - Context context = getContext(); - MainActivity activity = getMainActivity(); + private fun voteTag(tag: String, vote: Int) { + val context = context + val activity = mainActivity if (null == context || null == activity) { - return; + return } - - EhRequest request = new EhRequest() - .setMethod(EhClient.METHOD_VOTE_TAG) - .setArgs(mGalleryDetail.apiUid, mGalleryDetail.apiKey, mGalleryDetail.getGid(), mGalleryDetail.getToken(), tag, vote) - .setCallback(new VoteTagListener(context)); - request.enqueue(this); + val request = EhRequest() + .setMethod(EhClient.METHOD_VOTE_TAG) + .setArgs( + mGalleryDetail!!.apiUid, + mGalleryDetail!!.apiKey!!, + mGalleryDetail!!.gid, + mGalleryDetail!!.token!!, + tag, + vote + ) + .setCallback(VoteTagListener(context)) + request.enqueue(this) } - @Override - public boolean onLongClick(View v) { - MainActivity activity = getMainActivity(); - if (null == activity) { - return false; - } - - if (mUploader == v) { - if (TextUtils.isEmpty(getUploader()) || getDisowned()) { - return false; + override fun onLongClick(v: View): Boolean { + val activity = mainActivity ?: return false + if (mUploader === v) { + if (TextUtils.isEmpty(uploader) || disowned) { + return false } - showFilterUploaderDialog(); - } else if (mDownload == v) { - GalleryInfo galleryInfo = getGalleryInfo(); + showFilterUploaderDialog() + } else if (mDownload === v) { + val galleryInfo = galleryInfo if (galleryInfo != null) { - CommonOperations.startDownload(activity, galleryInfo, true); + CommonOperations.startDownload(activity, galleryInfo, true) } - return true; - } else if (mHeart == v || mHeartOutline == v) { + return true + } else if (mHeart === v || mHeartOutline === v) { if (mGalleryDetail != null && !mModifyingFavorites) { - boolean remove = false; - if (EhDB.containLocalFavorites(mGalleryDetail.getGid()) || mGalleryDetail.isFavorited) { - mModifyingFavorites = true; - CommonOperations.removeFromFavorites(activity, mGalleryDetail, - new ModifyFavoritesListener(activity, true)); - remove = true; + var remove = false + if (EhDB.containLocalFavorites(mGalleryDetail!!.gid) || mGalleryDetail!!.isFavorited) { + mModifyingFavorites = true + CommonOperations.removeFromFavorites( + activity, mGalleryDetail, + ModifyFavoritesListener(activity, true) + ) + remove = true } if (!remove) { - mModifyingFavorites = true; - CommonOperations.addToFavorites(activity, mGalleryDetail, - new ModifyFavoritesListener(activity, false), true); + mModifyingFavorites = true + CommonOperations.addToFavorites( + activity, mGalleryDetail, + ModifyFavoritesListener(activity, false), true + ) } // Update UI - updateFavoriteDrawable(); + updateFavoriteDrawable() } } else { - String tag = (String) v.getTag(R.id.tag); + val tag = v.getTag(R.id.tag) as? String if (null != tag) { - showTagDialog((TextView) v, tag); - return true; + showTagDialog(v as TextView, tag) + return true } } - return false; + return false } - private void updateDownloadText() { + private fun updateDownloadText() { if (null == mDownload) { - return; + return } - switch (mDownloadState) { - case DownloadInfo.STATE_INVALID -> mDownload.setText(R.string.download); - case DownloadInfo.STATE_NONE -> mDownload.setText(R.string.download_state_none); - case DownloadInfo.STATE_WAIT -> mDownload.setText(R.string.download_state_wait); - case DownloadInfo.STATE_DOWNLOAD -> - mDownload.setText(R.string.download_state_downloading); - case DownloadInfo.STATE_FINISH -> mDownload.setText(R.string.download_state_downloaded); - case DownloadInfo.STATE_FAILED -> mDownload.setText(R.string.download_state_failed); + when (mDownloadState) { + DownloadInfo.STATE_INVALID -> mDownload!!.setText(R.string.download) + DownloadInfo.STATE_NONE -> mDownload!!.setText(R.string.download_state_none) + DownloadInfo.STATE_WAIT -> mDownload!!.setText(R.string.download_state_wait) + DownloadInfo.STATE_DOWNLOAD -> mDownload!!.setText(R.string.download_state_downloading) + DownloadInfo.STATE_FINISH -> mDownload!!.setText(R.string.download_state_downloaded) + DownloadInfo.STATE_FAILED -> mDownload!!.setText(R.string.download_state_failed) } } - private void updateDownloadState() { - Context context = getContext(); - long gid = getGid(); + private fun updateDownloadState() { + val context = context + val gid = gid if (null == context || -1L == gid) { - return; + return } - - int downloadState = EhApplication.getDownloadManager().getDownloadState(gid); + val downloadState = downloadManager.getDownloadState(gid) if (downloadState == mDownloadState) { - return; + return } - mDownloadState = downloadState; - updateDownloadText(); + mDownloadState = downloadState + updateDownloadText() } - @Override - public void onAdd(@NonNull DownloadInfo info, @NonNull List list, int position) { - updateDownloadState(); + override fun onAdd(info: DownloadInfo, list: List, position: Int) { + updateDownloadState() } - @Override - public void onUpdate(@NonNull DownloadInfo info, @NonNull List list) { - updateDownloadState(); + override fun onUpdate(info: DownloadInfo, list: List) { + updateDownloadState() } - @Override - public void onUpdateAll() { - updateDownloadState(); + override fun onUpdateAll() { + updateDownloadState() } - @Override - public void onReload() { - updateDownloadState(); + override fun onReload() { + updateDownloadState() } - @Override - public void onChange() { - updateDownloadState(); + override fun onChange() { + updateDownloadState() } - @Override - public void onRemove(@NonNull DownloadInfo info, @NonNull List list, int position) { - updateDownloadState(); + override fun onRemove(info: DownloadInfo, list: List, position: Int) { + updateDownloadState() } - @Override - public void onRenameLabel(String from, String to) { + override fun onRenameLabel(from: String, to: String) {} + override fun onUpdateLabels() {} + private fun onGetGalleryDetailSuccess(result: GalleryDetail) { + mGalleryDetail = result + updateDownloadState() + adjustViewVisibility(STATE_NORMAL) + bindViewSecond() } - @Override - public void onUpdateLabels() { - } - - private void onGetGalleryDetailSuccess(GalleryDetail result) { - mGalleryDetail = result; - updateDownloadState(); - adjustViewVisibility(STATE_NORMAL); - bindViewSecond(); - } - - private void onGetGalleryDetailFailure(Exception e) { - e.printStackTrace(); - Context context = getContext(); + private fun onGetGalleryDetailFailure(e: Exception) { + e.printStackTrace() + val context = context if (null != context && null != mTip) { - String error = ExceptionUtils.getReadableString(e); - mTip.setText(error); - adjustViewVisibility(STATE_FAILED); + val error = ExceptionUtils.getReadableString(e) + mTip!!.text = error + adjustViewVisibility(STATE_FAILED) } } - private void onRateGallerySuccess(RateGalleryParser.Result result) { + private fun onRateGallerySuccess(result: RateGalleryParser.Result) { if (mGalleryDetail != null) { - mGalleryDetail.setRating(result.rating); - mGalleryDetail.ratingCount = result.ratingCount; + mGalleryDetail!!.rating = result.rating + mGalleryDetail!!.ratingCount = result.ratingCount } // Update UI if (mRatingText != null && mRating != null) { - mRatingText.setText(getAllRatingText(result.rating, result.ratingCount)); - mRating.setRating(result.rating); + mRatingText!!.text = getAllRatingText(result.rating, result.ratingCount) + mRating!!.rating = result.rating } } - private void onModifyFavoritesSuccess(boolean addOrRemove) { - mModifyingFavorites = false; + private fun onModifyFavoritesSuccess(addOrRemove: Boolean) { + mModifyingFavorites = false if (mGalleryDetail != null) { - mGalleryDetail.isFavorited = !addOrRemove && mGalleryDetail.getFavoriteName() != null; - updateFavoriteDrawable(); + mGalleryDetail!!.isFavorited = !addOrRemove && mGalleryDetail!!.favoriteName != null + updateFavoriteDrawable() } } - private void onModifyFavoritesFailure() { - mModifyingFavorites = false; + private fun onModifyFavoritesFailure() { + mModifyingFavorites = false } - private void onModifyFavoritesCancel() { - mModifyingFavorites = false; + private fun onModifyFavoritesCancel() { + mModifyingFavorites = false } - @IntDef({STATE_INIT, STATE_NORMAL, STATE_REFRESH, STATE_REFRESH_HEADER, STATE_FAILED}) - @Retention(RetentionPolicy.SOURCE) - private @interface State { - } - - private static class VoteTagListener extends EhCallback { - - public VoteTagListener(Context context) { - super(context); - } - - @Override - public void onSuccess(VoteTagParser.Result result) { + @IntDef(STATE_INIT, STATE_NORMAL, STATE_REFRESH, STATE_REFRESH_HEADER, STATE_FAILED) + @Retention(AnnotationRetention.SOURCE) + private annotation class State + private class VoteTagListener(context: Context?) : + EhCallback(context) { + override fun onSuccess(result: VoteTagParser.Result) { if (!TextUtils.isEmpty(result.error)) { - showTip(result.error, LENGTH_SHORT); + showTip(result.error, LENGTH_SHORT) } else { - showTip(R.string.tag_vote_successfully, LENGTH_SHORT); + showTip(R.string.tag_vote_successfully, LENGTH_SHORT) } } - @Override - public void onFailure(Exception e) { - showTip(R.string.vote_failed, LENGTH_LONG); + override fun onFailure(e: Exception) { + showTip(R.string.vote_failed, LENGTH_LONG) } - @Override - public void onCancel() { - } + override fun onCancel() {} } - private static class DownloadArchiveListener extends EhCallback { - - private final GalleryInfo mGalleryInfo; - - public DownloadArchiveListener(Context context, int stageId, String sceneTag, GalleryInfo galleryInfo) { - super(context); - mGalleryInfo = galleryInfo; - } - - @Override - public void onSuccess(String result) { - if (result != null) { - // TODO: Don't use buggy system download service - DownloadManager.Request r = new DownloadManager.Request(Uri.parse(result)); - var name = mGalleryInfo.getGid() + "-" + EhUtils.getSuitableTitle(mGalleryInfo) + ".zip"; - r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, - FileUtils.sanitizeFilename(name)); - r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - DownloadManager dm = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE); - if (dm != null) { - try { - dm.enqueue(r); - } catch (Throwable e) { - e.printStackTrace(); - ExceptionUtils.throwIfFatal(e); - } - } + private class DownloadArchiveListener( + context: Context?, + private val mGalleryInfo: GalleryInfo? + ) : EhCallback(context) { + override fun onSuccess(result: String) { + // TODO: Don't use buggy system download service + val r = DownloadManager.Request(Uri.parse(result)) + val name = + mGalleryInfo!!.gid.toString() + "-" + EhUtils.getSuitableTitle(mGalleryInfo) + ".zip" + r.setDestinationInExternalPublicDir( + Environment.DIRECTORY_DOWNLOADS, + FileUtils.sanitizeFilename(name) + ) + r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) + val dm = application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager + try { + dm.enqueue(r) + } catch (e: Throwable) { + e.printStackTrace() + ExceptionUtils.throwIfFatal(e) } - showTip(R.string.download_archive_started, LENGTH_SHORT); + showTip(R.string.download_archive_started, LENGTH_SHORT) } - @Override - public void onFailure(Exception e) { - if (e instanceof NoHAtHClientException) { - showTip(R.string.download_archive_failure_no_hath, LENGTH_LONG); + override fun onFailure(e: Exception) { + if (e is NoHAtHClientException) { + showTip(R.string.download_archive_failure_no_hath, LENGTH_LONG) } else { - showTip(R.string.download_archive_failure, LENGTH_LONG); + showTip(R.string.download_archive_failure, LENGTH_LONG) } } - @Override - public void onCancel() { - } + override fun onCancel() {} } - private static class DeleteDialogHelper implements DialogInterface.OnClickListener { - private final com.hippo.ehviewer.download.DownloadManager mDownloadManager; - private final GalleryInfo mGalleryInfo; - private final CheckBoxDialogBuilder mBuilder; - - public DeleteDialogHelper(com.hippo.ehviewer.download.DownloadManager downloadManager, - GalleryInfo galleryInfo, CheckBoxDialogBuilder builder) { - mDownloadManager = downloadManager; - mGalleryInfo = galleryInfo; - mBuilder = builder; - } - - @Override - public void onClick(DialogInterface dialog, int which) { + private inner class DeleteDialogHelper( + private val mDownloadManager: com.hippo.ehviewer.download.DownloadManager?, + private val mGalleryInfo: GalleryInfo, private val mBuilder: CheckBoxDialogBuilder + ) : DialogInterface.OnClickListener { + override fun onClick(dialog: DialogInterface, which: Int) { if (which != DialogInterface.BUTTON_POSITIVE) { - return; + return } // Delete - if (null != mDownloadManager) { - mDownloadManager.deleteDownload(mGalleryInfo.getGid()); - } + mDownloadManager?.deleteDownload(mGalleryInfo.gid) // Delete image files - boolean checked = mBuilder.isChecked(); - Settings.putRemoveImageFiles(checked); + val checked = mBuilder.isChecked + Settings.putRemoveImageFiles(checked) if (checked) { - UniFile file = SpiderDen.getGalleryDownloadDir(mGalleryInfo.getGid()); - EhDB.removeDownloadDirname(mGalleryInfo.getGid()); - deleteFileAsync(file); - } - } - } - - private class GetGalleryDetailListener extends EhCallback { - - public GetGalleryDetailListener(Context context) { - super(context); - } - - @Override - public void onSuccess(GalleryDetail result) { - getApplication().removeGlobalStuff(this); - - // Put gallery detail to cache - EhApplication.getGalleryDetailCache().put(result.getGid(), result); - - // Add history - EhDB.putHistoryInfo(result); - - // Notify success - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onGetGalleryDetailSuccess(result); - } - - @Override - public void onFailure(Exception e) { - getApplication().removeGlobalStuff(this); - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onGetGalleryDetailFailure(e); - } - - @Override - public void onCancel() { - getApplication().removeGlobalStuff(this); - } - } - - private class RateGalleryListener extends EhCallback { - - private final long mGid; - - public RateGalleryListener(Context context, int stageId, String sceneTag, long gid) { - super(context); - mGid = gid; - } - - @Override - public void onSuccess(RateGalleryParser.Result result) { - showTip(R.string.rate_successfully, LENGTH_SHORT); - - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onRateGallerySuccess(result); - } - - @Override - public void onFailure(Exception e) { - e.printStackTrace(); - showTip(R.string.rate_failed, LENGTH_LONG); - } - - @Override - public void onCancel() { - } - } - - private class ModifyFavoritesListener extends EhCallback { - - private final boolean mAddOrRemove; - - /** - * @param addOrRemove false for add, true for remove - */ - public ModifyFavoritesListener(Context context, boolean addOrRemove) { - super(context); - mAddOrRemove = addOrRemove; - } - - @Override - public void onSuccess(Void result) { - showTip(mAddOrRemove ? R.string.remove_from_favorite_success : - R.string.add_to_favorite_success, LENGTH_SHORT); - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onModifyFavoritesSuccess(mAddOrRemove); - } - - @Override - public void onFailure(Exception e) { - showTip(mAddOrRemove ? R.string.remove_from_favorite_failure : - R.string.add_to_favorite_failure, LENGTH_LONG); - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onModifyFavoritesFailure(); - } - - @Override - public void onCancel() { - GalleryDetailScene scene = GalleryDetailScene.this; - scene.onModifyFavoritesCancel(); - } - } - - private class ArchiveListDialogHelper implements AdapterView.OnItemClickListener, - DialogInterface.OnDismissListener, EhClient.Callback { - - @Nullable - private CircularProgressIndicator mProgressView; - @Nullable - private TextView mErrorText; - @Nullable - private ListView mListView; - @Nullable - private EhRequest mRequest; - @Nullable - private Dialog mDialog; - - public void setDialog(@Nullable Dialog dialog, String url) { - mDialog = dialog; - mProgressView = (CircularProgressIndicator) ViewUtils.$$(dialog, R.id.progress); - mErrorText = (TextView) ViewUtils.$$(dialog, R.id.text); - mListView = (ListView) ViewUtils.$$(dialog, R.id.list_view); - mListView.setOnItemClickListener(this); - - Context context = getContext(); - if (context != null) { - if (mArchiveList == null) { - mErrorText.setVisibility(View.GONE); - mListView.setVisibility(View.GONE); - mRequest = new EhRequest().setMethod(EhClient.METHOD_ARCHIVE_LIST) - .setArgs(url, mGid, mToken) - .setCallback(this); - mRequest.enqueue(GalleryDetailScene.this); - } else { - bind(mArchiveList); - } - } - } - - private void bind(List data) { - if (null == mDialog || null == mProgressView || null == mErrorText || null == mListView) { - return; - } - - if (null == data || 0 == data.size()) { - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.VISIBLE); - mListView.setVisibility(View.GONE); - mErrorText.setText(R.string.no_archives); - } else { - var nameArray = data.stream().map(archive -> archive.format(getResources()::getString)).toArray(String[]::new); - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.GONE); - mListView.setVisibility(View.VISIBLE); - mListView.setAdapter(new ArrayAdapter<>(mDialog.getContext(), R.layout.item_select_dialog, nameArray)); - } - } - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Context context = getContext(); - MainActivity activity = getMainActivity(); - if (null != context && null != activity && null != mArchiveList && position < mArchiveList.size()) { - String res = mArchiveList.get(position).res(); - boolean isHAtH = mArchiveList.get(position).isHAtH(); - EhRequest request = new EhRequest(); - request.setMethod(EhClient.METHOD_DOWNLOAD_ARCHIVE); - request.setArgs(mGalleryDetail.getGid(), mGalleryDetail.getToken(), mArchiveFormParamOr, res, isHAtH); - request.setCallback(new DownloadArchiveListener(context, 1, getTag(), mGalleryDetail)); - request.enqueue(GalleryDetailScene.this); - } - - if (mDialog != null) { - mDialog.dismiss(); - mDialog = null; - } - } - - @Override - public void onDismiss(DialogInterface dialog) { - if (mRequest != null) { - mRequest.cancel(); - mRequest = null; - } - mDialog = null; - mProgressView = null; - mErrorText = null; - mListView = null; - } - - @Override - public void onSuccess(ArchiveParser.Result result) { - if (mRequest != null) { - mRequest = null; - mArchiveFormParamOr = result.paramOr(); - mArchiveList = result.archiveList(); - bind(result.archiveList()); - } - } - - @Override - public void onFailure(Exception e) { - mRequest = null; - Context context = getContext(); - if (null != context && null != mProgressView && null != mErrorText && null != mListView) { - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.VISIBLE); - mListView.setVisibility(View.GONE); - mErrorText.setText(ExceptionUtils.getReadableString(e)); - } - } - - @Override - public void onCancel() { - mRequest = null; - } - } - - private class TorrentListDialogHelper implements AdapterView.OnItemClickListener, - DialogInterface.OnDismissListener, EhClient.Callback> { - - @Nullable - private CircularProgressIndicator mProgressView; - @Nullable - private TextView mErrorText; - @Nullable - private ListView mListView; - @Nullable - private EhRequest mRequest; - @Nullable - private Dialog mDialog; - - public void setDialog(@Nullable Dialog dialog, String url) { - mDialog = dialog; - mProgressView = (CircularProgressIndicator) ViewUtils.$$(dialog, R.id.progress); - mErrorText = (TextView) ViewUtils.$$(dialog, R.id.text); - mListView = (ListView) ViewUtils.$$(dialog, R.id.list_view); - mListView.setOnItemClickListener(this); - - Context context = getContext(); - if (context != null) { - if (mTorrentList == null) { - mErrorText.setVisibility(View.GONE); - mListView.setVisibility(View.GONE); - mRequest = new EhRequest().setMethod(EhClient.METHOD_GET_TORRENT_LIST) - .setArgs(url, mGid, mToken) - .setCallback(this); - mRequest.enqueue(GalleryDetailScene.this); - } else { - bind(mTorrentList); - } - } - } - - private void bind(List data) { - if (null == mDialog || null == mProgressView || null == mErrorText || null == mListView) { - return; - } - - if (null == data || 0 == data.size()) { - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.VISIBLE); - mListView.setVisibility(View.GONE); - mErrorText.setText(R.string.no_torrents); - } else { - var nameArray = data.stream().map(torrent -> torrent.format(getResources()::getString)).toArray(String[]::new); - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.GONE); - mListView.setVisibility(View.VISIBLE); - mListView.setAdapter(new ArrayAdapter<>(mDialog.getContext(), R.layout.item_select_dialog, nameArray)); - } - } - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Context context = getContext(); - if (null != context && null != mTorrentList && position < mTorrentList.size()) { - String url = mTorrentList.get(position).url(); - String name = mTorrentList.get(position).name(); - // TODO: Don't use buggy system download service - DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url.replace("exhentai.org", "ehtracker.org"))); - r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, - FileUtils.sanitizeFilename(name + ".torrent")); - r.allowScanningByMediaScanner(); - r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - r.addRequestHeader("Cookie", EhApplication.getEhCookieStore().getCookieHeader(HttpUrl.get(url))); - DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); - if (dm != null) { - try { - dm.enqueue(r); - showTip(R.string.download_torrent_started, LENGTH_SHORT); - } catch (Throwable e) { - e.printStackTrace(); - ExceptionUtils.throwIfFatal(e); - showTip(R.string.download_torrent_failure, LENGTH_SHORT); + val file = SpiderDen.getGalleryDownloadDir(mGalleryInfo.gid) + EhDB.removeDownloadDirname(mGalleryInfo.gid) + lifecycleScope.launchIO { + runCatching { + file?.delete() } } } + } + } + private inner class GetGalleryDetailListener(context: Context?) : + EhCallback(context) { + override fun onSuccess(result: GalleryDetail) { + application.removeGlobalStuff(this) + + // Put gallery detail to cache + galleryDetailCache.put(result.gid, result) + + // Add history + EhDB.putHistoryInfo(result) + + // Notify success + val scene = this@GalleryDetailScene + scene.onGetGalleryDetailSuccess(result) + } + + override fun onFailure(e: Exception) { + application.removeGlobalStuff(this) + val scene = this@GalleryDetailScene + scene.onGetGalleryDetailFailure(e) + } + + override fun onCancel() { + application.removeGlobalStuff(this) + } + } + + private inner class RateGalleryListener( + context: Context? + ) : EhCallback(context) { + override fun onSuccess(result: RateGalleryParser.Result) { + showTip(R.string.rate_successfully, LENGTH_SHORT) + val scene = this@GalleryDetailScene + scene.onRateGallerySuccess(result) + } + + override fun onFailure(e: Exception) { + e.printStackTrace() + showTip(R.string.rate_failed, LENGTH_LONG) + } + + override fun onCancel() {} + } + + private inner class ModifyFavoritesListener( + context: Context?, + private val mAddOrRemove: Boolean + ) : + EhCallback(context) { + override fun onSuccess(result: Void?) { + showTip( + if (mAddOrRemove) R.string.remove_from_favorite_success else R.string.add_to_favorite_success, + LENGTH_SHORT + ) + val scene = this@GalleryDetailScene + scene.onModifyFavoritesSuccess(mAddOrRemove) + } + + override fun onFailure(e: Exception) { + showTip( + if (mAddOrRemove) R.string.remove_from_favorite_failure else R.string.add_to_favorite_failure, + LENGTH_LONG + ) + val scene = this@GalleryDetailScene + scene.onModifyFavoritesFailure() + } + + override fun onCancel() { + val scene = this@GalleryDetailScene + scene.onModifyFavoritesCancel() + } + } + + private inner class ArchiveListDialogHelper : AdapterView.OnItemClickListener, + DialogInterface.OnDismissListener, EhClient.Callback { + private var mProgressView: CircularProgressIndicator? = null + private var mErrorText: TextView? = null + private var mListView: ListView? = null + private var mRequest: EhRequest? = null + private var mDialog: Dialog? = null + fun setDialog(dialog: Dialog?, url: String?) { + mDialog = dialog + mProgressView = ViewUtils.`$$`(dialog, R.id.progress) as CircularProgressIndicator + mErrorText = ViewUtils.`$$`(dialog, R.id.text) as TextView + mListView = ViewUtils.`$$`(dialog, R.id.list_view) as ListView + mListView!!.onItemClickListener = this + val context = context + if (context != null) { + if (mArchiveList == null) { + mErrorText!!.visibility = View.GONE + mListView!!.visibility = View.GONE + mRequest = EhRequest().setMethod(EhClient.METHOD_ARCHIVE_LIST) + .setArgs(url!!, mGid, mToken) + .setCallback(this) + mRequest!!.enqueue(this@GalleryDetailScene) + } else { + bind(mArchiveList) + } + } + } + + private fun bind(data: List?) { + if (null == mDialog || null == mProgressView || null == mErrorText || null == mListView) { + return + } + if (data.isNullOrEmpty()) { + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.VISIBLE + mListView!!.visibility = View.GONE + mErrorText!!.setText(R.string.no_archives) + } else { + val nameArray = data.stream().map { archive: ArchiveParser.Archive -> + archive.format { id: Int -> + resources.getString(id) + } + }.toArray() + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.GONE + mListView!!.visibility = View.VISIBLE + mListView!!.adapter = + ArrayAdapter(mDialog!!.context, R.layout.item_select_dialog, nameArray) + } + } + + override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + val context = context + val activity = mainActivity + if (null != context && null != activity && null != mArchiveList && position < mArchiveList!!.size) { + val res = mArchiveList!![position].res() + val isHAtH = mArchiveList!![position].isHAtH + val request = EhRequest() + request.setMethod(EhClient.METHOD_DOWNLOAD_ARCHIVE) + request.setArgs( + mGalleryDetail!!.gid, + mGalleryDetail!!.token!!, + mArchiveFormParamOr!!, + res, + isHAtH + ) + request.setCallback(DownloadArchiveListener(context, mGalleryDetail)) + request.enqueue(this@GalleryDetailScene) + } if (mDialog != null) { - mDialog.dismiss(); - mDialog = null; + mDialog!!.dismiss() + mDialog = null } } - @Override - public void onDismiss(DialogInterface dialog) { + override fun onDismiss(dialog: DialogInterface) { if (mRequest != null) { - mRequest.cancel(); - mRequest = null; + mRequest!!.cancel() + mRequest = null } - mDialog = null; - mProgressView = null; - mErrorText = null; - mListView = null; + mDialog = null + mProgressView = null + mErrorText = null + mListView = null } - @Override - public void onSuccess(List result) { + override fun onSuccess(result: ArchiveParser.Result) { if (mRequest != null) { - mRequest = null; - mTorrentList = result; - bind(result); + mRequest = null + mArchiveFormParamOr = result.paramOr() + mArchiveList = result.archiveList() + bind(result.archiveList()) } } - @Override - public void onFailure(Exception e) { - mRequest = null; - Context context = getContext(); + override fun onFailure(e: Exception) { + mRequest = null + val context = context if (null != context && null != mProgressView && null != mErrorText && null != mListView) { - mProgressView.setVisibility(View.GONE); - mErrorText.setVisibility(View.VISIBLE); - mListView.setVisibility(View.GONE); - mErrorText.setText(ExceptionUtils.getReadableString(e)); + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.VISIBLE + mListView!!.visibility = View.GONE + mErrorText!!.text = ExceptionUtils.getReadableString(e) } } - @Override - public void onCancel() { - mRequest = null; + override fun onCancel() { + mRequest = null } } - private class RateDialogHelper implements GalleryRatingBar.OnUserRateListener, - DialogInterface.OnClickListener { - - @Nullable - private GalleryRatingBar mRatingBar; - @Nullable - private TextView mRatingText; - - public void setDialog(Dialog dialog, float rating) { - mRatingText = (TextView) ViewUtils.$$(dialog, R.id.rating_text); - mRatingBar = (GalleryRatingBar) ViewUtils.$$(dialog, R.id.rating_view); - mRatingText.setText(getRatingText(rating)); - mRatingBar.setRating(rating); - mRatingBar.setOnUserRateListener(this); + private inner class TorrentListDialogHelper : AdapterView.OnItemClickListener, + DialogInterface.OnDismissListener, EhClient.Callback> { + private var mProgressView: CircularProgressIndicator? = null + private var mErrorText: TextView? = null + private var mListView: ListView? = null + private var mRequest: EhRequest? = null + private var mDialog: Dialog? = null + fun setDialog(dialog: Dialog?, url: String?) { + mDialog = dialog + mProgressView = ViewUtils.`$$`(dialog, R.id.progress) as CircularProgressIndicator + mErrorText = ViewUtils.`$$`(dialog, R.id.text) as TextView + mListView = ViewUtils.`$$`(dialog, R.id.list_view) as ListView + mListView!!.onItemClickListener = this + val context = context + if (context != null) { + if (mTorrentList == null) { + mErrorText!!.visibility = View.GONE + mListView!!.visibility = View.GONE + mRequest = EhRequest().setMethod(EhClient.METHOD_GET_TORRENT_LIST) + .setArgs(url!!, mGid, mToken) + .setCallback(this) + mRequest!!.enqueue(this@GalleryDetailScene) + } else { + bind(mTorrentList) + } + } } - @Override - public void onUserRate(float rating) { + private fun bind(data: List?) { + if (null == mDialog || null == mProgressView || null == mErrorText || null == mListView) { + return + } + if (data.isNullOrEmpty()) { + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.VISIBLE + mListView!!.visibility = View.GONE + mErrorText!!.setText(R.string.no_torrents) + } else { + val nameArray = data.stream().map { torrent: TorrentParser.Result -> + torrent.format { id: Int -> + resources.getString(id) + } + }.toArray() + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.GONE + mListView!!.visibility = View.VISIBLE + mListView!!.adapter = + ArrayAdapter(mDialog!!.context, R.layout.item_select_dialog, nameArray) + } + } + + override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + val context = context + if (null != context && null != mTorrentList && position < mTorrentList!!.size) { + val url = mTorrentList!![position].url() + val name = mTorrentList!![position].name() + // TODO: Don't use buggy system download service + val r = + DownloadManager.Request(Uri.parse(url.replace("exhentai.org", "ehtracker.org"))) + r.setDestinationInExternalPublicDir( + Environment.DIRECTORY_DOWNLOADS, + FileUtils.sanitizeFilename("$name.torrent") + ) + r.allowScanningByMediaScanner() + r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) + r.addRequestHeader("Cookie", ehCookieStore.getCookieHeader(url.toHttpUrl())) + val dm = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager + try { + dm.enqueue(r) + showTip(R.string.download_torrent_started, LENGTH_SHORT) + } catch (e: Throwable) { + e.printStackTrace() + ExceptionUtils.throwIfFatal(e) + showTip(R.string.download_torrent_failure, LENGTH_SHORT) + } + } + if (mDialog != null) { + mDialog!!.dismiss() + mDialog = null + } + } + + override fun onDismiss(dialog: DialogInterface) { + if (mRequest != null) { + mRequest!!.cancel() + mRequest = null + } + mDialog = null + mProgressView = null + mErrorText = null + mListView = null + } + + override fun onSuccess(result: List) { + if (mRequest != null) { + mRequest = null + mTorrentList = result + bind(result) + } + } + + override fun onFailure(e: Exception) { + mRequest = null + val context = context + if (null != context && null != mProgressView && null != mErrorText && null != mListView) { + mProgressView!!.visibility = View.GONE + mErrorText!!.visibility = View.VISIBLE + mListView!!.visibility = View.GONE + mErrorText!!.text = ExceptionUtils.getReadableString(e) + } + } + + override fun onCancel() { + mRequest = null + } + } + + private inner class RateDialogHelper : OnUserRateListener, DialogInterface.OnClickListener { + private var mRatingBar: GalleryRatingBar? = null + private var mRatingText: TextView? = null + fun setDialog(dialog: Dialog?, rating: Float) { + mRatingText = ViewUtils.`$$`(dialog, R.id.rating_text) as TextView + mRatingBar = ViewUtils.`$$`(dialog, R.id.rating_view) as GalleryRatingBar + mRatingText!!.setText(getRatingText(rating)) + mRatingBar!!.rating = rating + mRatingBar!!.setOnUserRateListener(this) + } + + override fun onUserRate(rating: Float) { if (null != mRatingText) { - mRatingText.setText(getRatingText(rating)); + mRatingText!!.setText(getRatingText(rating)) } } - @Override - public void onClick(DialogInterface dialog, int which) { - Context context = getContext(); - MainActivity activity = getMainActivity(); - if (null == context || null == activity || which != DialogInterface.BUTTON_POSITIVE || - null == mGalleryDetail || null == mRatingBar) { - return; + override fun onClick(dialog: DialogInterface, which: Int) { + val context = context + val activity = mainActivity + if (null == context || null == activity || which != DialogInterface.BUTTON_POSITIVE || null == mGalleryDetail || null == mRatingBar) { + return } - - EhRequest request = new EhRequest() - .setMethod(EhClient.METHOD_GET_RATE_GALLERY) - .setArgs(mGalleryDetail.apiUid, mGalleryDetail.apiKey, - mGalleryDetail.getGid(), mGalleryDetail.getToken(), mRatingBar.getRating()) - .setCallback(new RateGalleryListener(context, - 1, getTag(), mGalleryDetail.getGid())); - request.enqueue(GalleryDetailScene.this); + val request = EhRequest() + .setMethod(EhClient.METHOD_GET_RATE_GALLERY) + .setArgs( + mGalleryDetail!!.apiUid, mGalleryDetail!!.apiKey!!, + mGalleryDetail!!.gid, mGalleryDetail!!.token!!, mRatingBar!!.rating + ) + .setCallback( + RateGalleryListener( + context + ) + ) + request.enqueue(this@GalleryDetailScene) } } -} + + companion object { + const val KEY_ACTION = "action" + const val ACTION_GALLERY_INFO = "action_gallery_info" + const val ACTION_GID_TOKEN = "action_gid_token" + const val KEY_GALLERY_INFO = "gallery_info" + const val KEY_GID = "gid" + const val KEY_TOKEN = "token" + const val KEY_PAGE = "page" + private const val STATE_INIT = -1 + private const val STATE_NORMAL = 0 + private const val STATE_REFRESH = 1 + private const val STATE_REFRESH_HEADER = 2 + private const val STATE_FAILED = 3 + private const val KEY_GALLERY_DETAIL = "gallery_detail" + private const val KEY_REQUEST_ID = "request_id" + private const val TRANSITION_ANIMATION_DISABLED = true + private fun getArtist(tagGroups: Array?): String? { + if (null == tagGroups) { + return null + } + for (tagGroup in tagGroups) { + if ("artist" == tagGroup.groupName && tagGroup.size() > 0) { + return tagGroup.getTagAt(0) + } + } + return null + } + } +} \ No newline at end of file