diff --git a/app/src/main/java/com/hippo/ehviewer/ui/scene/DownloadsScene.kt b/app/src/main/java/com/hippo/ehviewer/ui/scene/DownloadsScene.kt index 029ea0df3..15b9a79af 100644 --- a/app/src/main/java/com/hippo/ehviewer/ui/scene/DownloadsScene.kt +++ b/app/src/main/java/com/hippo/ehviewer/ui/scene/DownloadsScene.kt @@ -13,1332 +13,1180 @@ * 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.annotation.SuppressLint; -import android.app.Activity; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.res.Resources; -import android.graphics.drawable.Drawable; -import android.os.AsyncTask; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; -import android.util.SparseBooleanArray; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.ProgressBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.widget.Toolbar; -import androidx.core.content.ContextCompat; -import androidx.core.view.GravityCompat; -import androidx.core.view.ViewCompat; -import androidx.drawerlayout.widget.DrawerLayout; -import androidx.recyclerview.widget.ItemTouchHelper; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.SimpleItemAnimator; -import androidx.recyclerview.widget.StaggeredGridLayoutManager; - -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.hippo.app.BaseDialogBuilder; -import com.hippo.app.CheckBoxDialogBuilder; -import com.hippo.app.EditTextDialogBuilder; -import com.hippo.easyrecyclerview.EasyRecyclerView; -import com.hippo.easyrecyclerview.FastScroller; -import com.hippo.easyrecyclerview.HandlerDrawable; -import com.hippo.easyrecyclerview.MarginItemDecoration; -import com.hippo.ehviewer.EhApplication; -import com.hippo.ehviewer.EhDB; -import com.hippo.ehviewer.R; -import com.hippo.ehviewer.Settings; -import com.hippo.ehviewer.client.EhCacheKeyFactory; -import com.hippo.ehviewer.client.EhUtils; -import com.hippo.ehviewer.dao.DownloadInfo; -import com.hippo.ehviewer.dao.DownloadLabel; -import com.hippo.ehviewer.download.DownloadManager; -import com.hippo.ehviewer.download.DownloadService; -import com.hippo.ehviewer.spider.SpiderDen; -import com.hippo.ehviewer.widget.SimpleRatingView; -import com.hippo.scene.Announcer; -import com.hippo.unifile.UniFile; -import com.hippo.util.IoThreadPoolExecutor; -import com.hippo.view.ViewTransition; -import com.hippo.widget.FabLayout; -import com.hippo.widget.LoadImageView; -import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager; -import com.hippo.yorozuya.AssertUtils; -import com.hippo.yorozuya.FileUtils; -import com.hippo.yorozuya.ObjectUtils; -import com.hippo.yorozuya.ViewUtils; -import com.hippo.yorozuya.collect.LongList; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import eu.kanade.tachiyomi.ui.reader.ReaderActivity; -import rikka.core.res.ResourcesKt; +import android.annotation.SuppressLint +import android.app.Activity +import android.content.DialogInterface +import android.content.Intent +import android.os.Bundle +import android.text.TextUtils +import android.util.Log +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.ImageView +import android.widget.ProgressBar +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.widget.Toolbar +import androidx.core.content.ContextCompat +import androidx.core.view.GravityCompat +import androidx.core.view.ViewCompat +import androidx.drawerlayout.widget.DrawerLayout +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.SimpleItemAnimator +import androidx.recyclerview.widget.StaggeredGridLayoutManager +import com.google.android.material.floatingactionbutton.FloatingActionButton +import com.hippo.app.BaseDialogBuilder +import com.hippo.app.CheckBoxDialogBuilder +import com.hippo.app.EditTextDialogBuilder +import com.hippo.easyrecyclerview.EasyRecyclerView +import com.hippo.easyrecyclerview.EasyRecyclerView.CustomChoiceListener +import com.hippo.easyrecyclerview.FastScroller +import com.hippo.easyrecyclerview.FastScroller.OnDragHandlerListener +import com.hippo.easyrecyclerview.HandlerDrawable +import com.hippo.easyrecyclerview.MarginItemDecoration +import com.hippo.ehviewer.EhApplication.Companion.downloadManager +import com.hippo.ehviewer.EhDB +import com.hippo.ehviewer.R +import com.hippo.ehviewer.Settings +import com.hippo.ehviewer.client.EhCacheKeyFactory +import com.hippo.ehviewer.client.EhUtils +import com.hippo.ehviewer.dao.DownloadInfo +import com.hippo.ehviewer.download.DownloadManager +import com.hippo.ehviewer.download.DownloadManager.DownloadInfoListener +import com.hippo.ehviewer.download.DownloadService +import com.hippo.ehviewer.download.DownloadService.Companion.clear +import com.hippo.ehviewer.spider.SpiderDen +import com.hippo.ehviewer.widget.SimpleRatingView +import com.hippo.scene.Announcer +import com.hippo.unifile.UniFile +import com.hippo.view.ViewTransition +import com.hippo.widget.FabLayout +import com.hippo.widget.FabLayout.OnClickFabListener +import com.hippo.widget.FabLayout.OnExpandListener +import com.hippo.widget.LoadImageView +import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager +import com.hippo.yorozuya.AssertUtils +import com.hippo.yorozuya.FileUtils +import com.hippo.yorozuya.ObjectUtils +import com.hippo.yorozuya.ViewUtils +import com.hippo.yorozuya.collect.LongList +import eu.kanade.tachiyomi.ui.reader.ReaderActivity +import eu.kanade.tachiyomi.util.lang.launchIO +import rikka.core.res.resolveColor +import java.util.LinkedList @SuppressLint("RtlHardcoded") -public class DownloadsScene extends BaseToolbarScene - implements DownloadManager.DownloadInfoListener, - FabLayout.OnClickFabListener, FastScroller.OnDragHandlerListener { - - public static final String KEY_GID = "gid"; - public static final String KEY_ACTION = "action"; - public static final String ACTION_CLEAR_DOWNLOAD_SERVICE = "clear_download_service"; - private static final String TAG = DownloadsScene.class.getSimpleName(); - private static final String KEY_LABEL = "label"; +class DownloadsScene : BaseToolbarScene(), DownloadInfoListener, OnClickFabListener, + OnDragHandlerListener { /*--------------- Whole life cycle ---------------*/ - @Nullable - private DownloadManager mDownloadManager; - @Nullable - private String mLabel; - @Nullable - private List mList; + private var mDownloadManager: DownloadManager? = null + private var mLabel: String? = null + private var mList: MutableList? = null /*--------------- View life cycle ---------------*/ - @Nullable - private TextView mTip; - @Nullable - private FastScroller mFastScroller; - @Nullable - private EasyRecyclerView mRecyclerView; - @Nullable - private ViewTransition mViewTransition; - @Nullable - private FabLayout mFabLayout; - @Nullable - private DownloadAdapter mAdapter; - @Nullable - private AutoStaggeredGridLayoutManager mLayoutManager; - - private int mInitPosition = -1; - - private DownloadLabelAdapter mLabelAdapter; - - private List mLabels; - - private int mType = -1; - - 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 mTip: TextView? = null + private var mFastScroller: FastScroller? = null + private var mRecyclerView: EasyRecyclerView? = null + private var mViewTransition: ViewTransition? = null + private var mFabLayout: FabLayout? = null + private var mAdapter: DownloadAdapter? = null + private var mLayoutManager: AutoStaggeredGridLayoutManager? = null + private var mInitPosition = -1 + private var mLabelAdapter: DownloadLabelAdapter? = null + private lateinit var mLabels: MutableList + private var mType = -1 + override fun getNavCheckedItem(): Int { + return R.id.nav_downloads } - @Override - public int getNavCheckedItem() { - return R.id.nav_downloads; - } - - private void initLabels() { - final Context context = getContext(); - if (context == null) { - return; - } - List listLabel = EhApplication.getDownloadManager().getLabelList(); - mLabels = new ArrayList<>(listLabel.size() + 1); + private fun initLabels() { + context ?: return + val listLabel = downloadManager.labelList + mLabels = ArrayList(listLabel.size + 1) // Add default label name - mLabels.add(getString(R.string.default_download_label_name)); - for (DownloadLabel raw : listLabel) { - mLabels.add(raw.getLabel()); + mLabels.add(getString(R.string.default_download_label_name)) + for ((_, label) in listLabel) { + mLabels.add(label!!) } } - private boolean handleArguments(Bundle args) { + private fun handleArguments(args: Bundle?): Boolean { if (null == args) { - return false; + return false } - - if (ACTION_CLEAR_DOWNLOAD_SERVICE.equals(args.getString(KEY_ACTION))) { - DownloadService.clear(); + if (ACTION_CLEAR_DOWNLOAD_SERVICE == args.getString(KEY_ACTION)) { + clear() } - - long gid; - if (null != mDownloadManager && -1L != (gid = args.getLong(KEY_GID, -1L))) { - DownloadInfo info = mDownloadManager.getDownloadInfo(gid); + val gid = args.getLong(KEY_GID, -1L) + if (null != mDownloadManager && -1L != gid) { + val info = mDownloadManager!!.getDownloadInfo(gid) if (null != info) { - mLabel = info.label; - updateForLabel(); - updateView(); + mLabel = info.label + updateForLabel() + updateView() // Get position if (null != mList) { - int position = mList.indexOf(info); + val position = mList!!.indexOf(info) if (position >= 0 && null != mRecyclerView) { - mRecyclerView.scrollToPosition(position); + mRecyclerView!!.scrollToPosition(position) } else { - mInitPosition = position; + mInitPosition = position } } - return true; + return true } } - return false; + return false } - @Override - public void onNewArguments(@NonNull Bundle args) { - handleArguments(args); + override fun onNewArguments(args: Bundle) { + handleArguments(args) } - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Context context = getContext(); - AssertUtils.assertNotNull(context); - mDownloadManager = EhApplication.getDownloadManager(); - mDownloadManager.addDownloadInfoListener(this); - + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val context = context + AssertUtils.assertNotNull(context) + mDownloadManager = downloadManager + mDownloadManager!!.addDownloadInfoListener(this) if (savedInstanceState == null) { - onInit(); + onInit() } else { - onRestore(savedInstanceState); + onRestore(savedInstanceState) } } - @Override - public void onDestroy() { - super.onDestroy(); - mList = null; - - DownloadManager manager = mDownloadManager; + override fun onDestroy() { + super.onDestroy() + mList = null + var manager = mDownloadManager if (null == manager) { - Context context = getContext(); + val context = context if (null != context) { - manager = EhApplication.getDownloadManager(); + manager = downloadManager } } else { - mDownloadManager = null; - } - - if (null != manager) { - manager.removeDownloadInfoListener(this); - } else { - Log.e(TAG, "Can't removeDownloadInfoListener"); + mDownloadManager = null } + manager?.removeDownloadInfoListener(this) + ?: Log.e(TAG, "Can't removeDownloadInfoListener") } - private void updateForLabel() { + private fun updateForLabel() { if (null == mDownloadManager) { - return; + return } - List list; + var list: MutableList? if (mLabel == null) { - list = mDownloadManager.getDefaultDownloadInfoList(); + list = mDownloadManager!!.defaultDownloadInfoList } else { - list = mDownloadManager.getLabelDownloadInfoList(mLabel); + list = mDownloadManager!!.getLabelDownloadInfoList(mLabel) if (list == null) { - mLabel = null; - list = mDownloadManager.getDefaultDownloadInfoList(); + mLabel = null + list = mDownloadManager!!.defaultDownloadInfoList } } - if (mType != -1) { - mList = new ArrayList<>(); - for (DownloadInfo info : list) { + mList = ArrayList() + for (info in list) { if (info.state == mType) { - mList.add(info); + mList!!.add(info) } } } else { - mList = list; + mList = list } - if (mAdapter != null) { - mAdapter.notifyDataSetChanged(); + mAdapter!!.notifyDataSetChanged() } - Settings.putRecentDownloadLabel(mLabel); + Settings.putRecentDownloadLabel(mLabel) } - private void updateTitle() { - setTitle(getString(R.string.scene_download_title, - mLabel != null ? mLabel : getString(R.string.default_download_label_name))); + private fun updateTitle() { + setTitle( + getString( + R.string.scene_download_title, + if (mLabel != null) mLabel else getString(R.string.default_download_label_name) + ) + ) } - private void onInit() { - if (!handleArguments(getArguments())) { - mLabel = Settings.getRecentDownloadLabel(); - updateForLabel(); + private fun onInit() { + if (!handleArguments(arguments)) { + mLabel = Settings.getRecentDownloadLabel() + updateForLabel() } } - private void onRestore(@NonNull Bundle savedInstanceState) { - mLabel = savedInstanceState.getString(KEY_LABEL); - updateForLabel(); + private fun onRestore(savedInstanceState: Bundle) { + mLabel = savedInstanceState.getString(KEY_LABEL) + updateForLabel() } - @Override - public void onSaveInstanceState(@NonNull Bundle outState) { - super.onSaveInstanceState(outState); - outState.putString(KEY_LABEL, mLabel); + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putString(KEY_LABEL, mLabel) } - @Nullable - @Override - public View onCreateViewWithToolbar(LayoutInflater inflater, - @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.scene_download, container, false); - - View content = ViewUtils.$$(view, R.id.content); - mRecyclerView = (EasyRecyclerView) ViewUtils.$$(content, R.id.recycler_view); - setLiftOnScrollTargetView(mRecyclerView); - mFastScroller = (FastScroller) ViewUtils.$$(content, R.id.fast_scroller); - mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout); + override fun onCreateViewWithToolbar( + inflater: LayoutInflater, + container: ViewGroup?, savedInstanceState: Bundle? + ): View { + val view = inflater.inflate(R.layout.scene_download, container, false) + val content = ViewUtils.`$$`(view, R.id.content) + mRecyclerView = ViewUtils.`$$`(content, R.id.recycler_view) as EasyRecyclerView + setLiftOnScrollTargetView(mRecyclerView) + mFastScroller = ViewUtils.`$$`(content, R.id.fast_scroller) as FastScroller + mFabLayout = ViewUtils.`$$`(view, R.id.fab_layout) as FabLayout // Workaround - ((ViewGroup) mFabLayout.getParent()).removeView(mFabLayout); - container.addView(mFabLayout); - - mTip = (TextView) ViewUtils.$$(view, R.id.tip); - mViewTransition = new ViewTransition(content, mTip); - - Context context = getContext(); - AssertUtils.assertNotNull(content); - Resources resources = context.getResources(); - - Drawable drawable = ContextCompat.getDrawable(context, R.drawable.big_download); - drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); - mTip.setCompoundDrawables(null, drawable, null, null); - - mAdapter = new DownloadAdapter(); - mAdapter.setHasStableIds(true); - mRecyclerView.setAdapter(mAdapter); - mLayoutManager = new AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL); - mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId())); - mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE); - mRecyclerView.setLayoutManager(mLayoutManager); + (mFabLayout!!.parent as ViewGroup).removeView(mFabLayout) + container!!.addView(mFabLayout) + mTip = ViewUtils.`$$`(view, R.id.tip) as TextView + mViewTransition = ViewTransition(content, mTip) + val context = context + AssertUtils.assertNotNull(content) + val resources = context!!.resources + val drawable = ContextCompat.getDrawable(context, R.drawable.big_download) + drawable!!.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight) + mTip!!.setCompoundDrawables(null, drawable, null, null) + mAdapter = DownloadAdapter() + mAdapter!!.setHasStableIds(true) + mRecyclerView!!.adapter = mAdapter + mLayoutManager = AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL) + mLayoutManager!!.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId())) + mLayoutManager!!.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE) + mRecyclerView!!.layoutManager = mLayoutManager //mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, !ResourcesKt.resolveColor(getTheme(), .getAttrBoolean(context, R.attr.isLightTheme), new ColorDrawable(Color.TRANSPARENT))); //mRecyclerView.setDrawSelectorOnTop(true); - mRecyclerView.setClipToPadding(false); - mRecyclerView.setClipChildren(false); + mRecyclerView!!.clipToPadding = false + mRecyclerView!!.clipChildren = false //mRecyclerView.setOnItemClickListener(this); //mRecyclerView.setOnItemLongClickListener(this); - mRecyclerView.setChoiceMode(EasyRecyclerView.CHOICE_MODE_MULTIPLE_CUSTOM); - mRecyclerView.setCustomCheckedListener(new DownloadChoiceListener()); + mRecyclerView!!.setChoiceMode(EasyRecyclerView.CHOICE_MODE_MULTIPLE_CUSTOM) + mRecyclerView!!.setCustomCheckedListener(DownloadChoiceListener()) // Cancel change animation - RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator(); - if (itemAnimator instanceof SimpleItemAnimator) { - ((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false); + val itemAnimator = mRecyclerView!!.itemAnimator + if (itemAnimator is SimpleItemAnimator) { + itemAnimator.supportsChangeAnimations = false } - int interval = resources.getDimensionPixelOffset(R.dimen.gallery_list_interval); - int paddingH = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_h); - int paddingV = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_v); - MarginItemDecoration decoration = new MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV); - mRecyclerView.addItemDecoration(decoration); + val interval = resources.getDimensionPixelOffset(R.dimen.gallery_list_interval) + val paddingH = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_h) + val paddingV = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_v) + val decoration = MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV) + mRecyclerView!!.addItemDecoration(decoration) if (mInitPosition >= 0) { - mRecyclerView.scrollToPosition(mInitPosition); - mInitPosition = -1; + mRecyclerView!!.scrollToPosition(mInitPosition) + mInitPosition = -1 } - - mFastScroller.attachToRecyclerView(mRecyclerView); - HandlerDrawable handlerDrawable = new HandlerDrawable(); - handlerDrawable.setColor(ResourcesKt.resolveColor(getTheme(), com.google.android.material.R.attr.colorPrimary)); - mFastScroller.setHandlerDrawable(handlerDrawable); - mFastScroller.setOnDragHandlerListener(this); - - mFabLayout.addOnExpandListener(new FabLayoutListener()); - mFabLayout.setExpanded(false, false); - mFabLayout.setHidePrimaryFab(true); - mFabLayout.setAutoCancel(false); - mFabLayout.setOnClickFabListener(this); - addAboveSnackView(mFabLayout); - - updateView(); - - return view; + mFastScroller!!.attachToRecyclerView(mRecyclerView) + val handlerDrawable = HandlerDrawable() + handlerDrawable.setColor(theme.resolveColor(com.google.android.material.R.attr.colorPrimary)) + mFastScroller!!.setHandlerDrawable(handlerDrawable) + mFastScroller!!.setOnDragHandlerListener(this) + mFabLayout!!.addOnExpandListener(FabLayoutListener()) + mFabLayout!!.setExpanded(expanded = false, animation = false) + mFabLayout!!.setHidePrimaryFab(true) + mFabLayout!!.setAutoCancel(false) + mFabLayout!!.setOnClickFabListener(this) + addAboveSnackView(mFabLayout) + updateView() + return view } - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - updateTitle(); - setNavigationIcon(R.drawable.ic_baseline_menu_24); + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + updateTitle() + setNavigationIcon(R.drawable.ic_baseline_menu_24) } - @Override - public void onDestroyView() { - super.onDestroyView(); - + override fun onDestroyView() { + super.onDestroyView() if (null != mRecyclerView) { - mRecyclerView.stopScroll(); - mRecyclerView = null; + mRecyclerView!!.stopScroll() + mRecyclerView = null } if (null != mFabLayout) { - removeAboveSnackView(mFabLayout); - ((ViewGroup) mFabLayout.getParent()).removeView(mFabLayout); - mFabLayout = null; + removeAboveSnackView(mFabLayout) + (mFabLayout!!.parent as ViewGroup).removeView(mFabLayout) + mFabLayout = null } - - mRecyclerView = null; - mViewTransition = null; - mAdapter = null; - mLayoutManager = null; + mRecyclerView = null + mViewTransition = null + mAdapter = null + mLayoutManager = null } - @Override - public void onNavigationClick() { - toggleDrawer(GravityCompat.START); + override fun onNavigationClick() { + toggleDrawer(GravityCompat.START) } - @Override - public int getMenuResId() { - return R.menu.scene_download; + override fun getMenuResId(): Int { + return R.menu.scene_download } - @Override - public boolean onMenuItemClick(MenuItem item) { + override fun onMenuItemClick(item: MenuItem): Boolean { // Skip when in choice mode - Activity activity = getMainActivity(); - if (null == activity || null == mRecyclerView || mRecyclerView.isInCustomChoice()) { - return false; + val activity: Activity? = mainActivity + if (null == activity || null == mRecyclerView || mRecyclerView!!.isInCustomChoice) { + return false } - - int id = item.getItemId(); - if (id == R.id.action_filter) { - new BaseDialogBuilder(requireActivity()) - .setSingleChoiceItems(R.array.download_state, mType + 1, (dialog, which) -> { - mType = which - 1; - updateForLabel(); - updateView(); - dialog.dismiss(); - }) - .show(); - return true; - } else if (id == R.id.action_start_all) { - Intent intent = new Intent(activity, DownloadService.class); - intent.setAction(DownloadService.ACTION_START_ALL); - ContextCompat.startForegroundService(activity, intent); - return true; - } else if (id == R.id.action_stop_all) { - if (null != mDownloadManager) { - mDownloadManager.stopAllDownload(); + when (item.itemId) { + R.id.action_filter -> { + BaseDialogBuilder(requireActivity()) + .setSingleChoiceItems( + R.array.download_state, + mType + 1 + ) { dialog: DialogInterface, which: Int -> + mType = which - 1 + updateForLabel() + updateView() + dialog.dismiss() + } + .show() + return true } - return true; - } else if (id == R.id.action_open_download_labels) { - openDrawer(GravityCompat.END); - return true; - } else if (id == R.id.action_reset_reading_progress) { - new BaseDialogBuilder(requireContext()) + + R.id.action_start_all -> { + val intent = Intent(activity, DownloadService::class.java) + intent.action = DownloadService.ACTION_START_ALL + ContextCompat.startForegroundService(activity, intent) + return true + } + + R.id.action_stop_all -> { + if (null != mDownloadManager) { + mDownloadManager!!.stopAllDownload() + } + return true + } + + R.id.action_open_download_labels -> { + openDrawer(GravityCompat.END) + return true + } + + R.id.action_reset_reading_progress -> { + BaseDialogBuilder(requireContext()) .setMessage(R.string.reset_reading_progress_message) .setNegativeButton(android.R.string.cancel, null) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { + .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> if (mDownloadManager != null) { - mDownloadManager.resetAllReadingProgress(); + mDownloadManager!!.resetAllReadingProgress() } - }).show(); - return true; - } else if (id == R.id.action_start_all_reversed) { - List list = mList; - if (list == null) { - return true; + }.show() + return true } - LongList gidList = new LongList(); - for (int i = list.size() - 1; i > -1; i--) { - DownloadInfo info = list.get(i); - if (info.state != DownloadInfo.STATE_FINISH) { - gidList.add(info.getGid()); + + R.id.action_start_all_reversed -> { + val list = mList ?: return true + val gidList = LongList() + for (i in list.size - 1 downTo -1 + 1) { + val info = list[i] + if (info.state != DownloadInfo.STATE_FINISH) { + gidList.add(info.gid) + } } + val intent = Intent(activity, DownloadService::class.java) + intent.action = DownloadService.ACTION_START_RANGE + intent.putExtra(DownloadService.KEY_GID_LIST, gidList) + ContextCompat.startForegroundService(activity, intent) + return true } - Intent intent = new Intent(activity, DownloadService.class); - intent.setAction(DownloadService.ACTION_START_RANGE); - intent.putExtra(DownloadService.KEY_GID_LIST, gidList); - ContextCompat.startForegroundService(activity, intent); - return true; + + else -> return false } - return false; } - public void updateView() { + fun updateView() { if (mViewTransition != null) { - if (mList == null || mList.size() == 0) { - mViewTransition.showView(1); + if (mList == null || mList!!.size == 0) { + mViewTransition!!.showView(1) } else { - mViewTransition.showView(0); + mViewTransition!!.showView(0) } } - updateTitle(); + updateTitle() } - @Override - public View onCreateDrawerView(LayoutInflater inflater, - @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.drawer_list_rv, container, false); - - final Context context = getContext(); - AssertUtils.assertNotNull(context); - - Toolbar toolbar = view.findViewById(R.id.toolbar); - toolbar.setTitle(R.string.download_labels); - toolbar.inflateMenu(R.menu.drawer_download); - toolbar.setOnMenuItemClickListener(item -> { - int id = item.getItemId(); + override fun onCreateDrawerView( + inflater: LayoutInflater, + container: ViewGroup?, savedInstanceState: Bundle? + ): View { + val view = inflater.inflate(R.layout.drawer_list_rv, container, false) + val context = context + AssertUtils.assertNotNull(context) + val toolbar = view.findViewById(R.id.toolbar) + toolbar.setTitle(R.string.download_labels) + toolbar.inflateMenu(R.menu.drawer_download) + toolbar.setOnMenuItemClickListener { item: MenuItem -> + val id = item.itemId if (id == R.id.action_add) { - EditTextDialogBuilder builder = new EditTextDialogBuilder(context, null, getString(R.string.download_labels)); - builder.setTitle(R.string.new_label_title); - builder.setPositiveButton(android.R.string.ok, null); - AlertDialog dialog = builder.show(); - new NewLabelDialogHelper(builder, dialog); - return true; + val builder = + EditTextDialogBuilder(context!!, null, getString(R.string.download_labels)) + builder.setTitle(R.string.new_label_title) + builder.setPositiveButton(android.R.string.ok, null) + val dialog = builder.show() + NewLabelDialogHelper(builder, dialog) + return@setOnMenuItemClickListener true } else if (id == R.id.action_default_download_label) { - DownloadManager dm = mDownloadManager; - if (null == dm) { - return true; + val dm = mDownloadManager ?: return@setOnMenuItemClickListener true + val list = dm.labelList + val items = arrayOfNulls(list.size + 2) + items[0] = getString(R.string.let_me_select) + items[1] = getString(R.string.default_download_label_name) + var i = 0 + val n = list.size + while (i < n) { + items[i + 2] = list[i].label + i++ } - - List list = dm.getLabelList(); - final String[] items = new String[list.size() + 2]; - items[0] = getString(R.string.let_me_select); - items[1] = getString(R.string.default_download_label_name); - for (int i = 0, n = list.size(); i < n; i++) { - items[i + 2] = list.get(i).getLabel(); - } - new BaseDialogBuilder(context) - .setTitle(R.string.default_download_label) - .setItems(items, (dialog1, which) -> { - if (which == 0) { - Settings.putHasDefaultDownloadLabel(false); + BaseDialogBuilder(context!!) + .setTitle(R.string.default_download_label) + .setItems(items) { _: DialogInterface?, which: Int -> + if (which == 0) { + Settings.putHasDefaultDownloadLabel(false) + } else { + Settings.putHasDefaultDownloadLabel(true) + val label: String? = if (which == 1) { + null } else { - Settings.putHasDefaultDownloadLabel(true); - String label; - if (which == 1) { - label = null; - } else { - label = items[which]; - } - Settings.putDefaultDownloadLabel(label); + items[which] } - }).show(); - return true; + Settings.putDefaultDownloadLabel(label) + } + }.show() + return@setOnMenuItemClickListener true } - return false; - }); - - initLabels(); - - mLabelAdapter = new DownloadLabelAdapter(inflater); - final EasyRecyclerView recyclerView = view.findViewById(R.id.recycler_view_drawer); - recyclerView.setLayoutManager(new LinearLayoutManager(context)); - mLabelAdapter.setHasStableIds(true); - ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new DownloadLabelItemTouchHelperCallback()); - itemTouchHelper.attachToRecyclerView(recyclerView); - recyclerView.setAdapter(mLabelAdapter); - - return view; + false + } + initLabels() + mLabelAdapter = DownloadLabelAdapter(inflater) + val recyclerView = view.findViewById(R.id.recycler_view_drawer) + recyclerView.layoutManager = LinearLayoutManager(context) + mLabelAdapter!!.setHasStableIds(true) + val itemTouchHelper = ItemTouchHelper(DownloadLabelItemTouchHelperCallback()) + itemTouchHelper.attachToRecyclerView(recyclerView) + recyclerView.adapter = mLabelAdapter + return view } - @Override - public void onStartDragHandler() { + override fun onStartDragHandler() { // Lock right drawer - setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); + setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END) } - @Override - public void onEndDragHandler() { + override fun onEndDragHandler() { // Restore right drawer - if (null != mRecyclerView && !mRecyclerView.isInCustomChoice()) { - setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END); + if (null != mRecyclerView && !mRecyclerView!!.isInCustomChoice) { + setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END) } } - public boolean onItemClick(int position) { - Activity activity = getMainActivity(); - EasyRecyclerView recyclerView = mRecyclerView; + fun onItemClick(position: Int): Boolean { + val activity: Activity? = mainActivity + val recyclerView = mRecyclerView if (null == activity || null == recyclerView) { - return false; + return false } - - if (recyclerView.isInCustomChoice()) { - recyclerView.toggleItemChecked(position); - return true; + return if (recyclerView.isInCustomChoice) { + recyclerView.toggleItemChecked(position) + true } else { - List list = mList; - if (list == null) { - return false; + val list = mList ?: return false + if (position < 0 || position >= list.size) { + return false } - if (position < 0 || position >= list.size()) { - return false; - } - - Intent intent = new Intent(activity, ReaderActivity.class); - intent.setAction(ReaderActivity.ACTION_EH); - intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, list.get(position)); - startActivity(intent); - return true; + val intent = Intent(activity, ReaderActivity::class.java) + intent.action = ReaderActivity.ACTION_EH + intent.putExtra(ReaderActivity.KEY_GALLERY_INFO, list[position]) + startActivity(intent) + true } } - public boolean onItemLongClick(int position) { - EasyRecyclerView recyclerView = mRecyclerView; - if (recyclerView == null) { - return false; + fun onItemLongClick(position: Int): Boolean { + val recyclerView = mRecyclerView ?: return false + if (!recyclerView.isInCustomChoice) { + recyclerView.intoCustomChoiceMode() } - - if (!recyclerView.isInCustomChoice()) { - recyclerView.intoCustomChoiceMode(); - } - recyclerView.toggleItemChecked(position); - - return true; + recyclerView.toggleItemChecked(position) + return true } - @Override - public void onClickPrimaryFab(FabLayout view, FloatingActionButton fab) { - if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) { - mRecyclerView.outOfCustomChoiceMode(); + override fun onClickPrimaryFab(view: FabLayout, fab: FloatingActionButton) { + if (mRecyclerView != null && mRecyclerView!!.isInCustomChoice) { + mRecyclerView!!.outOfCustomChoiceMode() } } - @Override - public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) { - Context context = getContext(); - Activity activity = getMainActivity(); - EasyRecyclerView recyclerView = mRecyclerView; + override fun onClickSecondaryFab(view: FabLayout, fab: FloatingActionButton, position: Int) { + val context = context + val activity: Activity? = mainActivity + val recyclerView = mRecyclerView if (null == context || null == activity || null == recyclerView) { - return; + return } - if (0 == position) { - recyclerView.checkAll(); + recyclerView.checkAll() } else { - List list = mList; - if (list == null) { - return; - } - - LongList gidList = null; - List downloadInfoList = null; - boolean collectGid = position == 1 || position == 2 || position == 3; // Start, Stop, Delete - boolean collectDownloadInfo = position == 3 || position == 4; // Delete or Move + val list = mList ?: return + var gidList: LongList? = null + var downloadInfoList: MutableList? = null + val collectGid = position == 1 || position == 2 || position == 3 // Start, Stop, Delete + val collectDownloadInfo = position == 3 || position == 4 // Delete or Move if (collectGid) { - gidList = new LongList(); + gidList = LongList() } if (collectDownloadInfo) { - downloadInfoList = new LinkedList<>(); + downloadInfoList = LinkedList() } - - SparseBooleanArray stateArray = recyclerView.getCheckedItemPositions(); - for (int i = 0, n = stateArray.size(); i < n; i++) { + val stateArray = recyclerView.checkedItemPositions + var i = 0 + val n = stateArray.size() + while (i < n) { if (stateArray.valueAt(i)) { - DownloadInfo info = list.get(stateArray.keyAt(i)); + val info = list[stateArray.keyAt(i)] if (collectDownloadInfo) { - downloadInfoList.add(info); + downloadInfoList!!.add(info) } if (collectGid) { - gidList.add(info.getGid()); + gidList!!.add(info.gid) } } + i++ } - - switch (position) { - case 1: { // Start - Intent intent = new Intent(activity, DownloadService.class); - intent.setAction(DownloadService.ACTION_START_RANGE); - intent.putExtra(DownloadService.KEY_GID_LIST, gidList); - ContextCompat.startForegroundService(activity, intent); + when (position) { + 1 -> { + // Start + val intent = Intent(activity, DownloadService::class.java) + intent.action = DownloadService.ACTION_START_RANGE + intent.putExtra(DownloadService.KEY_GID_LIST, gidList) + ContextCompat.startForegroundService(activity, intent) // Cancel check mode - recyclerView.outOfCustomChoiceMode(); - break; + recyclerView.outOfCustomChoiceMode() } - case 2: { // Stop + + 2 -> { + // Stop if (null != mDownloadManager) { - mDownloadManager.stopRangeDownload(gidList); + mDownloadManager!!.stopRangeDownload(gidList) } // Cancel check mode - recyclerView.outOfCustomChoiceMode(); - break; + recyclerView.outOfCustomChoiceMode() } - case 3: { // Delete - CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(context, - getString(R.string.download_remove_dialog_message_2, gidList.size()), - getString(R.string.download_remove_dialog_check_text), - Settings.getRemoveImageFiles()); - DeleteRangeDialogHelper helper = new DeleteRangeDialogHelper( - downloadInfoList, gidList, builder); + + 3 -> { + // Delete + val builder = CheckBoxDialogBuilder( + context, + getString(R.string.download_remove_dialog_message_2, gidList!!.size()), + getString(R.string.download_remove_dialog_check_text), + Settings.getRemoveImageFiles() + ) + val helper = DeleteRangeDialogHelper( + downloadInfoList, gidList, builder + ) builder.setTitle(R.string.download_remove_dialog_title) - .setPositiveButton(android.R.string.ok, helper) - .show(); - break; + .setPositiveButton(android.R.string.ok, helper) + .show() } - case 4: {// Move - List labelRawList = EhApplication.getDownloadManager().getLabelList(); - List labelList = new ArrayList<>(labelRawList.size() + 1); - labelList.add(getString(R.string.default_download_label_name)); - for (int i = 0, n = labelRawList.size(); i < n; i++) { - labelList.add(labelRawList.get(i).getLabel()); + + 4 -> { + // Move + val labelRawList = downloadManager.labelList + val labelList: MutableList = ArrayList(labelRawList.size + 1) + labelList.add(getString(R.string.default_download_label_name)) + var i = 0 + val n = labelRawList.size + while (i < n) { + labelRawList[i].label?.let { labelList.add(it) } + i++ } - String[] labels = labelList.toArray(new String[0]); - - MoveDialogHelper helper = new MoveDialogHelper(labels, downloadInfoList); - - new BaseDialogBuilder(context) - .setTitle(R.string.download_move_dialog_title) - .setItems(labels, helper) - .show(); - break; + val labels = labelList.toTypedArray() + val helper = MoveDialogHelper(labels, downloadInfoList!!) + BaseDialogBuilder(context) + .setTitle(R.string.download_move_dialog_title) + .setItems(labels, helper) + .show() } } } } - @Override - public void onAdd(@NonNull DownloadInfo info, @NonNull List list, int position) { - if (mList != list) { - return; + override fun onAdd(info: DownloadInfo, list: List, position: Int) { + if (mList !== list) { + return } if (mAdapter != null) { - mAdapter.notifyItemInserted(position); + mAdapter!!.notifyItemInserted(position) } - updateView(); + updateView() } - @Override - public void onUpdate(@NonNull DownloadInfo info, @NonNull List list) { - if (mList != list) { - return; + override fun onUpdate(info: DownloadInfo, list: List) { + if (mList !== list) { + return } - - int index = list.indexOf(info); + val index = list.indexOf(info) if (index >= 0 && mAdapter != null) { - mAdapter.notifyItemChanged(index); + mAdapter!!.notifyItemChanged(index) } } - @Override - public void onUpdateAll() { + override fun onUpdateAll() { if (mAdapter != null) { - mAdapter.notifyDataSetChanged(); + mAdapter!!.notifyDataSetChanged() } } - @Override - public void onReload() { + override fun onReload() { if (mAdapter != null) { - mAdapter.notifyDataSetChanged(); + mAdapter!!.notifyDataSetChanged() } - updateView(); + updateView() } - @Override - public void onChange() { - mLabel = null; - updateForLabel(); - updateView(); + override fun onChange() { + mLabel = null + updateForLabel() + updateView() } - @Override - public void onRenameLabel(String from, String to) { + override fun onRenameLabel(from: String, to: String) { if (!ObjectUtils.equal(mLabel, from)) { - return; + return } - - mLabel = to; - updateForLabel(); - updateView(); + mLabel = to + updateForLabel() + updateView() } - @Override - public void onRemove(@NonNull DownloadInfo info, @NonNull List list, int position) { - if (mList != list) { - return; + override fun onRemove(info: DownloadInfo, list: List, position: Int) { + if (mList !== list) { + return } if (mAdapter != null) { - mAdapter.notifyItemRemoved(position); + mAdapter!!.notifyItemRemoved(position) } - updateView(); + updateView() } - @Override - public void onUpdateLabels() { + override fun onUpdateLabels() { // TODO } - private void bindForState(DownloadHolder holder, DownloadInfo info) { - Context context = getContext(); - if (null == context) { - return; - } + private fun bindForState(holder: DownloadHolder, info: DownloadInfo) { + val context = context ?: return + when (info.state) { + DownloadInfo.STATE_NONE -> bindState( + holder, + info, + context.getString(R.string.download_state_none) + ) - switch (info.state) { - case DownloadInfo.STATE_NONE: - bindState(holder, info, context.getString(R.string.download_state_none)); - break; - case DownloadInfo.STATE_WAIT: - bindState(holder, info, context.getString(R.string.download_state_wait)); - break; - case DownloadInfo.STATE_DOWNLOAD: - bindProgress(holder, info); - break; - case DownloadInfo.STATE_FAILED: - String text; - if (info.legacy <= 0) { - text = context.getString(R.string.download_state_failed); + DownloadInfo.STATE_WAIT -> bindState( + holder, + info, + context.getString(R.string.download_state_wait) + ) + + DownloadInfo.STATE_DOWNLOAD -> bindProgress(holder, info) + DownloadInfo.STATE_FAILED -> { + val text: String = if (info.legacy <= 0) { + context.getString(R.string.download_state_failed) } else { - text = context.getString(R.string.download_state_failed_2, info.legacy); + context.getString(R.string.download_state_failed_2, info.legacy) } - bindState(holder, info, text); - break; - case DownloadInfo.STATE_FINISH: - bindState(holder, info, context.getString(R.string.download_state_finish)); - break; + bindState(holder, info, text) + } + + DownloadInfo.STATE_FINISH -> bindState( + holder, + info, + context.getString(R.string.download_state_finish) + ) } } - private void bindState(DownloadHolder holder, DownloadInfo info, String state) { - holder.uploader.setVisibility(View.VISIBLE); - holder.rating.setVisibility(View.VISIBLE); - holder.category.setVisibility(View.VISIBLE); - holder.state.setVisibility(View.VISIBLE); - holder.progressBar.setVisibility(View.GONE); - holder.percent.setVisibility(View.GONE); - holder.speed.setVisibility(View.GONE); + private fun bindState(holder: DownloadHolder, info: DownloadInfo, state: String) { + holder.uploader.visibility = View.VISIBLE + holder.rating.visibility = View.VISIBLE + holder.category.visibility = View.VISIBLE + holder.state.visibility = View.VISIBLE + holder.progressBar.visibility = View.GONE + holder.percent.visibility = View.GONE + holder.speed.visibility = View.GONE if (info.state == DownloadInfo.STATE_WAIT || info.state == DownloadInfo.STATE_DOWNLOAD) { - holder.start.setVisibility(View.GONE); - holder.stop.setVisibility(View.VISIBLE); + holder.start.visibility = View.GONE + holder.stop.visibility = View.VISIBLE } else { - holder.start.setVisibility(View.VISIBLE); - holder.stop.setVisibility(View.GONE); + holder.start.visibility = View.VISIBLE + holder.stop.visibility = View.GONE } - - holder.state.setText(state); + holder.state.text = state } @SuppressLint("SetTextI18n") - private void bindProgress(DownloadHolder holder, DownloadInfo info) { - holder.uploader.setVisibility(View.GONE); - holder.rating.setVisibility(View.GONE); - holder.category.setVisibility(View.GONE); - holder.state.setVisibility(View.GONE); - holder.progressBar.setVisibility(View.VISIBLE); - holder.percent.setVisibility(View.VISIBLE); - holder.speed.setVisibility(View.VISIBLE); + private fun bindProgress(holder: DownloadHolder, info: DownloadInfo) { + holder.uploader.visibility = View.GONE + holder.rating.visibility = View.GONE + holder.category.visibility = View.GONE + holder.state.visibility = View.GONE + holder.progressBar.visibility = View.VISIBLE + holder.percent.visibility = View.VISIBLE + holder.speed.visibility = View.VISIBLE if (info.state == DownloadInfo.STATE_WAIT || info.state == DownloadInfo.STATE_DOWNLOAD) { - holder.start.setVisibility(View.GONE); - holder.stop.setVisibility(View.VISIBLE); + holder.start.visibility = View.GONE + holder.stop.visibility = View.VISIBLE } else { - holder.start.setVisibility(View.VISIBLE); - holder.stop.setVisibility(View.GONE); + holder.start.visibility = View.VISIBLE + holder.stop.visibility = View.GONE } - if (info.total <= 0 || info.finished < 0) { - holder.percent.setText(null); - holder.progressBar.setIndeterminate(true); + holder.percent.text = null + holder.progressBar.isIndeterminate = true } else { - holder.percent.setText(info.finished + "/" + info.total); - holder.progressBar.setIndeterminate(false); - holder.progressBar.setMax(info.total); - holder.progressBar.setProgress(info.finished); + holder.percent.text = info.finished.toString() + "/" + info.total + holder.progressBar.isIndeterminate = false + holder.progressBar.max = info.total + holder.progressBar.progress = info.finished } - long speed = info.speed; + var speed = info.speed if (speed < 0) { - speed = 0; + speed = 0 } - holder.speed.setText(FileUtils.humanReadableByteCount(speed, false) + "/S"); + holder.speed.text = FileUtils.humanReadableByteCount(speed, false) + "/S" } - private static class DownloadLabelHolder extends RecyclerView.ViewHolder { + private class DownloadLabelHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { + val label: TextView + val edit: ImageView + val option: ImageView - private final TextView label; - private final ImageView edit; - private final ImageView option; - - private DownloadLabelHolder(View itemView) { - super(itemView); - label = (TextView) ViewUtils.$$(itemView, R.id.tv_key); - edit = (ImageView) ViewUtils.$$(itemView, R.id.iv_edit); - option = (ImageView) ViewUtils.$$(itemView, R.id.iv_option); + init { + label = ViewUtils.`$$`(itemView, R.id.tv_key) as TextView + edit = ViewUtils.`$$`(itemView, R.id.iv_edit) as ImageView + option = ViewUtils.`$$`(itemView, R.id.iv_option) as ImageView } } - private class DownloadLabelAdapter extends RecyclerView.Adapter { - - private final LayoutInflater mInflater; - - private DownloadLabelAdapter(LayoutInflater inflater) { - this.mInflater = inflater; - } - - @NonNull - @Override - public DownloadLabelHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new DownloadLabelHolder(mInflater.inflate(R.layout.item_drawer_list, parent, false)); + private inner class DownloadLabelAdapter(private val mInflater: LayoutInflater) : + RecyclerView.Adapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DownloadLabelHolder { + return DownloadLabelHolder(mInflater.inflate(R.layout.item_drawer_list, parent, false)) } @SuppressLint("SetTextI18n") - @Override - public void onBindViewHolder(@NonNull DownloadLabelHolder holder, int position) { - if (mLabels != null) { - Context context = getContext(); - String label = mLabels.get(position); - if (mDownloadManager == null) { + override fun onBindViewHolder(holder: DownloadLabelHolder, position: Int) { + val context = context + val label = mLabels[position] + if (mDownloadManager == null) { + if (context != null) { + mDownloadManager = downloadManager + } + } + var list: List? = null + if (mDownloadManager != null) { + list = if (position == 0) { + mDownloadManager!!.defaultDownloadInfoList + } else { + mDownloadManager!!.getLabelDownloadInfoList(label) + } + } + if (list != null) { + holder.label.text = label + " [" + list.size + "]" + } else { + holder.label.text = label + } + holder.itemView.setOnClickListener { + val label1: String? = if (position == 0) { + null + } else { + mLabels[position] + } + if (!ObjectUtils.equal(label1, mLabel)) { + mLabel = label1 + updateForLabel() + updateView() + closeDrawer(GravityCompat.END) + } + } + if (position > 0) { + holder.edit.visibility = View.VISIBLE + holder.edit.setOnClickListener { if (context != null) { - mDownloadManager = EhApplication.getDownloadManager(); + val builder = EditTextDialogBuilder( + context, label, getString(R.string.download_labels) + ) + builder.setTitle(R.string.rename_label_title) + builder.setPositiveButton(android.R.string.ok, null) + val dialog = builder.show() + RenameLabelDialogHelper(builder, dialog, label) } } - List list = null; - if (mDownloadManager != null) { - if (position == 0) { - list = mDownloadManager.getDefaultDownloadInfoList(); - } else { - list = mDownloadManager.getLabelDownloadInfoList(label); - } - } - if (list != null) { - holder.label.setText(label + " [" + list.size() + "]"); - } else { - holder.label.setText(label); - } - holder.itemView.setOnClickListener(v -> { - String label1; - if (position == 0) { - label1 = null; - } else { - label1 = mLabels.get(position); - } - if (!ObjectUtils.equal(label1, mLabel)) { - mLabel = label1; - updateForLabel(); - updateView(); - closeDrawer(GravityCompat.END); - } - }); - if (position > 0) { - holder.edit.setVisibility(View.VISIBLE); - holder.edit.setOnClickListener(v -> { - if (context != null) { - EditTextDialogBuilder builder = new EditTextDialogBuilder( - context, label, getString(R.string.download_labels)); - builder.setTitle(R.string.rename_label_title); - builder.setPositiveButton(android.R.string.ok, null); - AlertDialog dialog = builder.show(); - new RenameLabelDialogHelper(builder, dialog, label); - } - }); - } else { - holder.option.setVisibility(View.GONE); - } + } else { + holder.option.visibility = View.GONE } } - @Override - public long getItemId(int position) { - return mLabels != null ? mLabels.get(position).hashCode() : 0; + override fun getItemId(position: Int): Long { + return mLabels[position].hashCode().toLong() } - @Override - public int getItemCount() { - return mLabels != null ? mLabels.size() : 0; + override fun getItemCount(): Int { + return mLabels.size } } - private class DeleteRangeDialogHelper implements DialogInterface.OnClickListener { - - private final List mDownloadInfoList; - private final LongList mGidList; - private final CheckBoxDialogBuilder mBuilder; - - public DeleteRangeDialogHelper(List downloadInfoList, - LongList gidList, CheckBoxDialogBuilder builder) { - mDownloadInfoList = downloadInfoList; - mGidList = gidList; - mBuilder = builder; - } - - @Override - public void onClick(DialogInterface dialog, int which) { + private inner class DeleteRangeDialogHelper( + private val mDownloadInfoList: List?, + private val mGidList: LongList?, private val mBuilder: CheckBoxDialogBuilder + ) : DialogInterface.OnClickListener { + override fun onClick(dialog: DialogInterface, which: Int) { if (which != DialogInterface.BUTTON_POSITIVE) { - return; + return } // Cancel check mode if (mRecyclerView != null) { - mRecyclerView.outOfCustomChoiceMode(); + mRecyclerView!!.outOfCustomChoiceMode() } // Delete if (null != mDownloadManager) { - mDownloadManager.deleteRangeDownload(mGidList); + mDownloadManager!!.deleteRangeDownload(mGidList) } // Delete image files - boolean checked = mBuilder.isChecked(); - Settings.putRemoveImageFiles(checked); + val checked = mBuilder.isChecked + Settings.putRemoveImageFiles(checked) if (checked) { - UniFile[] files = new UniFile[mDownloadInfoList.size()]; - int i = 0; - for (DownloadInfo info : mDownloadInfoList) { + val files = arrayOfNulls(mDownloadInfoList!!.size) + for ((i, info) in mDownloadInfoList.withIndex()) { // Put file - files[i] = SpiderDen.getGalleryDownloadDir(info.getGid()); + files[i] = SpiderDen.getGalleryDownloadDir(info.gid) // Remove download path - EhDB.removeDownloadDirname(info.getGid()); - i++; + EhDB.removeDownloadDirname(info.gid) } // Delete file - deleteFileAsync(files); + lifecycleScope.launchIO { + files.forEach { it?.delete() } + } } } } - private class MoveDialogHelper implements DialogInterface.OnClickListener { - - private final String[] mLabels; - private final List mDownloadInfoList; - - public MoveDialogHelper(String[] labels, List downloadInfoList) { - mLabels = labels; - mDownloadInfoList = downloadInfoList; - } - - @Override - public void onClick(DialogInterface dialog, int which) { + private inner class MoveDialogHelper( + private val mLabels: Array, + private val mDownloadInfoList: List + ) : DialogInterface.OnClickListener { + override fun onClick(dialog: DialogInterface, which: Int) { // Cancel check mode - Context context = getContext(); - if (null == context) { - return; - } + context ?: return if (null != mRecyclerView) { - mRecyclerView.outOfCustomChoiceMode(); + mRecyclerView!!.outOfCustomChoiceMode() } - - String label; - if (which == 0) { - label = null; + val label: String? = if (which == 0) { + null } else { - label = mLabels[which]; + mLabels[which] } - EhApplication.getDownloadManager().changeLabel(mDownloadInfoList, label); + downloadManager.changeLabel(mDownloadInfoList, label) if (mLabelAdapter != null) { - mLabelAdapter.notifyDataSetChanged(); + mLabelAdapter!!.notifyDataSetChanged() } } } - private class DownloadHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + private inner class DownloadHolder(itemView: View) : RecyclerView.ViewHolder(itemView), + View.OnClickListener { + val thumb: LoadImageView + val title: TextView + val uploader: TextView + val rating: SimpleRatingView + val category: TextView + val start: View + val stop: View + val state: TextView + val progressBar: ProgressBar + val percent: TextView + val speed: TextView - public final LoadImageView thumb; - public final TextView title; - public final TextView uploader; - public final SimpleRatingView rating; - public final TextView category; - public final View start; - public final View stop; - public final TextView state; - public final ProgressBar progressBar; - public final TextView percent; - public final TextView speed; - - public DownloadHolder(View itemView) { - super(itemView); - - thumb = itemView.findViewById(R.id.thumb); - title = itemView.findViewById(R.id.title); - uploader = itemView.findViewById(R.id.uploader); - rating = itemView.findViewById(R.id.rating); - category = itemView.findViewById(R.id.category); - start = itemView.findViewById(R.id.start); - stop = itemView.findViewById(R.id.stop); - state = itemView.findViewById(R.id.state); - progressBar = itemView.findViewById(R.id.progress_bar); - percent = itemView.findViewById(R.id.percent); - speed = itemView.findViewById(R.id.speed); + init { + thumb = itemView.findViewById(R.id.thumb) + title = itemView.findViewById(R.id.title) + uploader = itemView.findViewById(R.id.uploader) + rating = itemView.findViewById(R.id.rating) + category = itemView.findViewById(R.id.category) + start = itemView.findViewById(R.id.start) + stop = itemView.findViewById(R.id.stop) + state = itemView.findViewById(R.id.state) + progressBar = itemView.findViewById(R.id.progress_bar) + percent = itemView.findViewById(R.id.percent) + speed = itemView.findViewById(R.id.speed) // TODO cancel on click listener when select items - thumb.setOnClickListener(this); - start.setOnClickListener(this); - stop.setOnClickListener(this); + thumb.setOnClickListener(this) + start.setOnClickListener(this) + stop.setOnClickListener(this) } - @Override - public void onClick(View v) { - Context context = getContext(); - Activity activity = getMainActivity(); - EasyRecyclerView recyclerView = mRecyclerView; - if (null == context || null == activity || null == recyclerView || recyclerView.isInCustomChoice()) { - return; + override fun onClick(v: View) { + val context = context + val activity: Activity? = mainActivity + val recyclerView = mRecyclerView + if (null == context || null == activity || null == recyclerView || recyclerView.isInCustomChoice) { + return } - List list = mList; - if (list == null) { - return; - } - int size = list.size(); - int index = recyclerView.getChildAdapterPosition(itemView); + val list = mList ?: return + val size = list.size + val index = recyclerView.getChildAdapterPosition(itemView) if (index < 0 || index >= size) { - return; + return } - - if (thumb == v) { - Bundle args = new Bundle(); - args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GALLERY_INFO); - args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, list.get(index)); - Announcer announcer = new Announcer(GalleryDetailScene.class).setArgs(args); - startScene(announcer); - } else if (start == v) { - Intent intent = new Intent(activity, DownloadService.class); - intent.setAction(DownloadService.ACTION_START); - intent.putExtra(DownloadService.KEY_GALLERY_INFO, list.get(index)); - ContextCompat.startForegroundService(activity, intent); - } else if (stop == v) { + if (thumb === v) { + val args = Bundle() + args.putString( + GalleryDetailScene.KEY_ACTION, + GalleryDetailScene.ACTION_GALLERY_INFO + ) + args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, list[index]) + val announcer = Announcer(GalleryDetailScene::class.java).setArgs(args) + startScene(announcer) + } else if (start === v) { + val intent = Intent(activity, DownloadService::class.java) + intent.action = DownloadService.ACTION_START + intent.putExtra(DownloadService.KEY_GALLERY_INFO, list[index]) + ContextCompat.startForegroundService(activity, intent) + } else if (stop === v) { if (null != mDownloadManager) { - mDownloadManager.stopDownload(list.get(index).getGid()); + mDownloadManager!!.stopDownload(list[index].gid) } } } } - private class DownloadAdapter extends RecyclerView.Adapter { + private inner class DownloadAdapter : RecyclerView.Adapter() { + private val mInflater: LayoutInflater = layoutInflater + private val mListThumbWidth: Int + private val mListThumbHeight: Int - private final LayoutInflater mInflater; - private final int mListThumbWidth; - private final int mListThumbHeight; - - public DownloadAdapter() { - mInflater = getLayoutInflater(); - AssertUtils.assertNotNull(mInflater); - - @SuppressLint("InflateParams") View calculator = mInflater.inflate(R.layout.item_gallery_list_thumb_height, null); - ViewUtils.measureView(calculator, 1024, ViewGroup.LayoutParams.WRAP_CONTENT); - mListThumbHeight = calculator.getMeasuredHeight(); - mListThumbWidth = mListThumbHeight * 2 / 3; + init { + AssertUtils.assertNotNull(mInflater) + @SuppressLint("InflateParams") val calculator = + mInflater.inflate(R.layout.item_gallery_list_thumb_height, null) + ViewUtils.measureView(calculator, 1024, ViewGroup.LayoutParams.WRAP_CONTENT) + mListThumbHeight = calculator.measuredHeight + mListThumbWidth = mListThumbHeight * 2 / 3 } - @Override - public long getItemId(int position) { - if (mList == null || position < 0 || position >= mList.size()) { - return 0; - } - return mList.get(position).getGid(); + override fun getItemId(position: Int): Long { + return if (mList == null || position < 0 || position >= mList!!.size) { + 0 + } else mList!![position].gid } - @NonNull - @Override - public DownloadHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - DownloadHolder holder = new DownloadHolder(mInflater.inflate(R.layout.item_download, parent, false)); - - ViewGroup.LayoutParams lp = holder.thumb.getLayoutParams(); - lp.width = mListThumbWidth; - lp.height = mListThumbHeight; - holder.thumb.setLayoutParams(lp); - - return holder; + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DownloadHolder { + val holder = DownloadHolder(mInflater.inflate(R.layout.item_download, parent, false)) + val lp = holder.thumb.layoutParams + lp.width = mListThumbWidth + lp.height = mListThumbHeight + holder.thumb.layoutParams = lp + return holder } - @Override - public void onBindViewHolder(@NonNull DownloadHolder holder, int position) { + override fun onBindViewHolder(holder: DownloadHolder, position: Int) { if (mList == null) { - return; + return } - DownloadInfo info = mList.get(position); - if (info.getThumb() != null) { - holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.getGid()), info.getThumb()); + val info = mList!![position] + if (info.thumb != null) { + holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb!!) } - holder.title.setText(EhUtils.getSuitableTitle(info)); - holder.uploader.setText(info.getUploader()); - holder.rating.setRating(info.getRating()); - TextView category = holder.category; - String newCategoryText = EhUtils.getCategory(info.getCategory()); - if (!newCategoryText.contentEquals(category.getText())) { - category.setText(newCategoryText); - category.setBackgroundColor(EhUtils.getCategoryColor(info.getCategory())); + holder.title.text = EhUtils.getSuitableTitle(info) + holder.uploader.text = info.uploader + holder.rating.rating = info.rating + val category = holder.category + val newCategoryText = EhUtils.getCategory(info.category) + if (!newCategoryText.contentEquals(category.text)) { + category.text = newCategoryText + category.setBackgroundColor(EhUtils.getCategoryColor(info.category)) } - bindForState(holder, info); + bindForState(holder, info) // Update transition name - ViewCompat.setTransitionName(holder.thumb, TransitionNameFactory.getThumbTransitionName(info.getGid())); - - holder.itemView.setOnClickListener(v -> onItemClick(position)); - holder.itemView.setOnLongClickListener(v -> onItemLongClick(position)); + ViewCompat.setTransitionName( + holder.thumb, + TransitionNameFactory.getThumbTransitionName(info.gid) + ) + holder.itemView.setOnClickListener { onItemClick(position) } + holder.itemView.setOnLongClickListener { onItemLongClick(position) } } - @Override - public int getItemCount() { - return mList == null ? 0 : mList.size(); + override fun getItemCount(): Int { + return if (mList == null) 0 else mList!!.size } } - private class FabLayoutListener implements FabLayout.OnExpandListener { - @Override - public void onExpand(boolean expanded) { - if (!expanded && mRecyclerView != null && mRecyclerView.isInCustomChoice()) - mRecyclerView.outOfCustomChoiceMode(); + private inner class FabLayoutListener : OnExpandListener { + override fun onExpand(expanded: Boolean) { + if (!expanded && mRecyclerView != null && mRecyclerView!!.isInCustomChoice) mRecyclerView!!.outOfCustomChoiceMode() } } - private class DownloadChoiceListener implements EasyRecyclerView.CustomChoiceListener { - - @Override - public void onIntoCustomChoice(EasyRecyclerView view) { + private inner class DownloadChoiceListener : CustomChoiceListener { + override fun onIntoCustomChoice(view: EasyRecyclerView) { if (mFabLayout != null) { - mFabLayout.setExpanded(true); + mFabLayout!!.isExpanded = true } // Lock drawer - setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.START); - setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); + setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.START) + setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END) } - @Override - public void onOutOfCustomChoice(EasyRecyclerView view) { + override fun onOutOfCustomChoice(view: EasyRecyclerView) { if (mFabLayout != null) { - mFabLayout.setExpanded(false); + mFabLayout!!.isExpanded = false } // Unlock drawer - setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.START); - setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END); + setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.START) + setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END) } - @Override - public void onItemCheckedStateChanged(EasyRecyclerView view, int position, long id, boolean checked) { - if (view.getCheckedItemCount() == 0) { - view.outOfCustomChoiceMode(); + override fun onItemCheckedStateChanged( + view: EasyRecyclerView, + position: Int, + id: Long, + checked: Boolean + ) { + if (view.checkedItemCount == 0) { + view.outOfCustomChoiceMode() } } } - private class RenameLabelDialogHelper implements View.OnClickListener { - - private final EditTextDialogBuilder mBuilder; - private final AlertDialog mDialog; - private final String mOriginalLabel; - - private RenameLabelDialogHelper(EditTextDialogBuilder builder, AlertDialog dialog, - String originalLabel) { - mBuilder = builder; - mDialog = dialog; - mOriginalLabel = originalLabel; - Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE); - if (button != null) { - button.setOnClickListener(this); - } + private inner class RenameLabelDialogHelper( + private val mBuilder: EditTextDialogBuilder, private val mDialog: AlertDialog, + private val mOriginalLabel: String? + ) : View.OnClickListener { + init { + val button: Button = mDialog.getButton(DialogInterface.BUTTON_POSITIVE) + button.setOnClickListener(this) } - @Override - public void onClick(View v) { - Context context = getContext(); - if (null == context) { - return; - } - - String text = mBuilder.getText(); + override fun onClick(v: View) { + context ?: return + val text = mBuilder.text if (TextUtils.isEmpty(text)) { - mBuilder.setError(getString(R.string.label_text_is_empty)); - } else if (getString(R.string.default_download_label_name).equals(text)) { - mBuilder.setError(getString(R.string.label_text_is_invalid)); - } else if (EhApplication.getDownloadManager().containLabel(text)) { - mBuilder.setError(getString(R.string.label_text_exist)); + mBuilder.setError(getString(R.string.label_text_is_empty)) + } else if (getString(R.string.default_download_label_name) == text) { + mBuilder.setError(getString(R.string.label_text_is_invalid)) + } else if (downloadManager.containLabel(text)) { + mBuilder.setError(getString(R.string.label_text_exist)) } else { - mBuilder.setError(null); - mDialog.dismiss(); - EhApplication.getDownloadManager().renameLabel(mOriginalLabel, text); + mBuilder.setError(null) + mDialog.dismiss() + downloadManager.renameLabel(mOriginalLabel!!, text) if (mLabelAdapter != null) { - initLabels(); - mLabelAdapter.notifyDataSetChanged(); + initLabels() + mLabelAdapter!!.notifyDataSetChanged() } } } } - private class NewLabelDialogHelper implements View.OnClickListener { - - private final EditTextDialogBuilder mBuilder; - private final AlertDialog mDialog; - - private NewLabelDialogHelper(EditTextDialogBuilder builder, AlertDialog dialog) { - mBuilder = builder; - mDialog = dialog; - Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE); - if (button != null) { - button.setOnClickListener(this); - } + private inner class NewLabelDialogHelper( + private val mBuilder: EditTextDialogBuilder, + private val mDialog: AlertDialog + ) : View.OnClickListener { + init { + val button: Button = mDialog.getButton(DialogInterface.BUTTON_POSITIVE) + button.setOnClickListener(this) } - @Override - public void onClick(View v) { - Context context = getContext(); - if (null == context) { - return; - } - - String text = mBuilder.getText(); + override fun onClick(v: View) { + context ?: return + val text = mBuilder.text if (TextUtils.isEmpty(text)) { - mBuilder.setError(getString(R.string.label_text_is_empty)); - } else if (getString(R.string.default_download_label_name).equals(text)) { - mBuilder.setError(getString(R.string.label_text_is_invalid)); - } else if (EhApplication.getDownloadManager().containLabel(text)) { - mBuilder.setError(getString(R.string.label_text_exist)); + mBuilder.setError(getString(R.string.label_text_is_empty)) + } else if (getString(R.string.default_download_label_name) == text) { + mBuilder.setError(getString(R.string.label_text_is_invalid)) + } else if (downloadManager.containLabel(text)) { + mBuilder.setError(getString(R.string.label_text_exist)) } else { - mBuilder.setError(null); - mDialog.dismiss(); - EhApplication.getDownloadManager().addLabel(text); - initLabels(); - if (mLabelAdapter != null && mLabels != null) { - mLabelAdapter.notifyItemInserted(mLabels.size() - 1); + mBuilder.setError(null) + mDialog.dismiss() + downloadManager.addLabel(text) + initLabels() + if (mLabelAdapter != null) { + mLabelAdapter!!.notifyItemInserted(mLabels.size - 1) } } } } - private class DownloadLabelItemTouchHelperCallback extends ItemTouchHelper.Callback { - - @Override - public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { - return makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT); + private inner class DownloadLabelItemTouchHelperCallback : ItemTouchHelper.Callback() { + override fun getMovementFlags( + recyclerView: RecyclerView, + viewHolder: RecyclerView.ViewHolder + ): Int { + return makeMovementFlags( + ItemTouchHelper.UP or ItemTouchHelper.DOWN, + ItemTouchHelper.LEFT + ) } @SuppressLint("NotifyDataSetChanged") - @Override - public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { - int fromPosition = viewHolder.getBindingAdapterPosition(); - int toPosition = target.getBindingAdapterPosition(); - Context context = getContext(); + override fun onMove( + recyclerView: RecyclerView, + viewHolder: RecyclerView.ViewHolder, + target: RecyclerView.ViewHolder + ): Boolean { + val fromPosition = viewHolder.bindingAdapterPosition + val toPosition = target.bindingAdapterPosition + val context = context if (null == context || fromPosition == toPosition || toPosition == 0 || fromPosition == 0) { - return false; + return false } - - EhApplication.getDownloadManager().moveLabel(fromPosition - 1, toPosition - 1); - final String item = mLabels.remove(fromPosition); - mLabels.add(toPosition, item); - mLabelAdapter.notifyDataSetChanged(); - return true; + downloadManager.moveLabel(fromPosition - 1, toPosition - 1) + val item = mLabels.removeAt(fromPosition) + mLabels.add(toPosition, item) + mLabelAdapter!!.notifyDataSetChanged() + return true } @SuppressLint("NotifyDataSetChanged") - @Override - public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { - int position = viewHolder.getBindingAdapterPosition(); - if (mDownloadManager == null) - return; + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { + val position = viewHolder.bindingAdapterPosition + if (mDownloadManager == null) return if (position != 0) { - String label = mLabels.get(position); - mDownloadManager.deleteLabel(label); + val label = mLabels[position] + mDownloadManager!!.deleteLabel(label) } - mLabels.remove(position); - mLabelAdapter.notifyDataSetChanged(); + mLabels.removeAt(position) + mLabelAdapter!!.notifyDataSetChanged() } } -} + + companion object { + const val KEY_GID = "gid" + const val KEY_ACTION = "action" + const val ACTION_CLEAR_DOWNLOAD_SERVICE = "clear_download_service" + private val TAG = DownloadsScene::class.java.simpleName + private const val KEY_LABEL = "label" + } +} \ No newline at end of file