Cleanup Code

This commit is contained in:
tarsin committed 2022-12-04 18:23:15 +08:00
1 parent a59fbcc9c8
commit 8f36cecc7a
22 files changed
+52 -1193

No files matched your search

@@ -1,28 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD})
public @interface Implemented {
Class value();
}
@@ -246,6 +246,10 @@ public final class DiskLruCache implements Closeable {
if (!from.renameTo(to)) {
throw new IOException();
}
}
private static String inputStreamToString(InputStream in) throws IOException {
return Util.readFully(new InputStreamReader(in, Util.UTF_8));
} private final Callable<Void> cleanupCallable = new Callable<>() {
public Void call() throws Exception {
synchronized (DiskLruCache.this) {
@@ -262,10 +266,6 @@ public final class DiskLruCache implements Closeable {
}
};
private static String inputStreamToString(InputStream in) throws IOException {
return Util.readFully(new InputStreamReader(in, Util.UTF_8));
}
private void readJournal() throws IOException {
StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
try {
@@ -62,15 +62,11 @@ public class Settings {
public static final String KEY_DETAIL_SIZE = "detail_size";
public static final String KEY_THUMB_SIZE = "thumb_size_";
public static final String KEY_THUMB_RESOLUTION = "thumb_resolution";
private static final String KEY_SHOW_COMMENTS = "show_gallery_comments";
private static final boolean DEFAULT_SHOW_COMMENTS = true;
public static final String KEY_SHOW_TAG_TRANSLATIONS = "show_tag_translations";
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
public static final String KEY_EXCLUDED_TAG_NAMESPACES = "excluded_tag_namespaces";
public static final String KEY_EXCLUDED_LANGUAGES = "excluded_languages";
private static final String KEY_PREVIEW_NUM = "preview_num";
private static final int DEFAULT_PREVIEW_NUM = 60;
/********************
****** Privacy and Security
********************/
@@ -82,7 +78,6 @@ public class Settings {
public static final String KEY_DOWNLOAD_SAVE_SCHEME = "image_scheme";
public static final String KEY_DOWNLOAD_SAVE_AUTHORITY = "image_authority";
public static final String KEY_DOWNLOAD_SAVE_PATH = "image_path";
public static final String KEY_NOTIFICATION_REQUIRED = "notification_required";
public static final String KEY_DOWNLOAD_SAVE_QUERY = "image_query";
public static final String KEY_DOWNLOAD_SAVE_FRAGMENT = "image_fragment";
@@ -105,6 +100,10 @@ public class Settings {
public static final String KEY_DOMAIN_FRONTING = "domain_fronting";
public static final String KEY_APP_LANGUAGE = "app_language";
public static final String KEY_LIST_THUMB_SIZE = "list_tile_size";
private static final String KEY_SHOW_COMMENTS = "show_gallery_comments";
private static final boolean DEFAULT_SHOW_COMMENTS = true;
private static final String KEY_PREVIEW_NUM = "preview_num";
private static final int DEFAULT_PREVIEW_NUM = 60;
private static final String TAG = Settings.class.getSimpleName();
private static final String KEY_VERSION_CODE = "version_code";
private static final int DEFAULT_VERSION_CODE = 0;
@@ -511,6 +511,15 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
mSeekBar = null;
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
}
@Override
protected void onPause() {
super.onPause();
if (mGLRootView != null) {
mGLRootView.onPause();
}
} ActivityResultLauncher<String> requestStoragePermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
result -> {
@@ -522,15 +531,6 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
mSavingPage = -1;
});
@Override
protected void onPause() {
super.onPause();
if (mGLRootView != null) {
mGLRootView.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
@@ -15,12 +15,10 @@
*/
package com.hippo.ehviewer.ui
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
@@ -316,7 +316,7 @@ public class DownloadsScene extends ToolbarScene
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
// Workaround
((ViewGroup)mFabLayout.getParent()).removeView(mFabLayout);
((ViewGroup) mFabLayout.getParent()).removeView(mFabLayout);
container.addView(mFabLayout);
mTip = (TextView) ViewUtils.$$(view, R.id.tip);
@@ -394,7 +394,7 @@ public class DownloadsScene extends ToolbarScene
}
if (null != mFabLayout) {
removeAboveSnackView(mFabLayout);
((ViewGroup)mFabLayout.getParent()).removeView(mFabLayout);
((ViewGroup) mFabLayout.getParent()).removeView(mFabLayout);
mFabLayout = null;
}
@@ -47,7 +47,6 @@ import com.google.android.material.datepicker.DateValidatorPointBackward;
import com.google.android.material.datepicker.DateValidatorPointForward;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.hippo.annotation.Implemented;
import com.hippo.app.BaseDialogBuilder;
import com.hippo.drawable.AddDeleteDrawable;
import com.hippo.drawable.DrawerArrowDrawable;
@@ -452,14 +451,12 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(FastScroller.OnDragHandlerListener.class)
public void onStartDragHandler() {
// Lock right drawer
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
}
@Override
@Implemented(FastScroller.OnDragHandlerListener.class)
public void onEndDragHandler() {
// Restore right drawer
if (null != mRecyclerView && !mRecyclerView.isInCustomChoice()) {
@@ -535,25 +532,21 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(SearchBarMover.Helper.class)
public boolean isValidView(RecyclerView recyclerView) {
return recyclerView == mRecyclerView;
}
@Override
@Implemented(SearchBarMover.Helper.class)
public RecyclerView getValidRecyclerView() {
return mRecyclerView;
}
@Override
@Implemented(SearchBarMover.Helper.class)
public boolean forceShowSearchBar() {
return false;
}
@Override
@Implemented(SearchBar.Helper.class)
public void onClickTitle() {
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
@@ -566,7 +559,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(SearchBar.Helper.class)
public void onClickLeftIcon() {
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
@@ -581,7 +573,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(SearchBar.Helper.class)
public void onClickRightIcon() {
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
@@ -600,12 +591,10 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(SearchBar.Helper.class)
public void onSearchEditTextClick() {
}
@Override
@Implemented(SearchBar.Helper.class)
public void onApplySearch(String query) {
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
@@ -629,7 +618,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(SearchBar.Helper.class)
public void onSearchEditTextBackPressed() {
onBackPressed();
}
@@ -644,7 +632,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(FabLayout.OnClickFabListener.class)
public void onClickPrimaryFab(FabLayout view, FloatingActionButton fab) {
if (mRecyclerView != null && mFabLayout != null) {
if (mRecyclerView.isInCustomChoice()) {
@@ -686,7 +673,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(FabLayout.OnClickFabListener.class)
public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) {
Context context = getContext();
if (null == context || null == mRecyclerView || null == mHelper) {
@@ -785,7 +771,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(EasyRecyclerView.CustomChoiceListener.class)
public void onIntoCustomChoice(EasyRecyclerView view) {
if (mFabLayout != null) {
showSelectionFabs();
@@ -802,7 +787,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(EasyRecyclerView.CustomChoiceListener.class)
public void onOutOfCustomChoice(EasyRecyclerView view) {
if (mFabLayout != null) {
showNormalFabs();
@@ -818,7 +802,6 @@ public class FavoritesScene extends BaseScene implements
}
@Override
@Implemented(EasyRecyclerView.CustomChoiceListener.class)
public void onItemCheckedStateChanged(EasyRecyclerView view, int position, long id, boolean checked) {
if (view.getCheckedItemCount() == 0) {
@@ -115,15 +115,11 @@ import com.hippo.widget.ObservedTextView;
import com.hippo.widget.SimpleGridAutoSpanLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.IntList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
@@ -1098,7 +1094,6 @@ public class GalleryDetailScene extends CollapsingToolbarScene implements View.O
}
File temp = AppConfig.createTempFile();
if (null == temp) {
return;
}
/*
@@ -330,7 +330,12 @@ class SearchLayout @JvmOverloads constructor(
inner class IdentifiedChip @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : Chip(ContextThemeWrapper(context, com.google.android.material.R.style.Widget_Material3_Chip_Filter), attrs) {
) : Chip(
ContextThemeWrapper(
context,
com.google.android.material.R.style.Widget_Material3_Chip_Filter
), attrs
) {
var idt = 0
}
@@ -35,7 +35,6 @@ import androidx.core.graphics.drawable.toDrawable
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import kotlin.jvm.Throws
import kotlin.math.max
class Image private constructor(
@@ -18,7 +18,6 @@ package com.hippo.scene;
import android.app.assist.AssistContent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
@@ -1,122 +0,0 @@
/*
* Copyright 2022 Tarsin Norbin
*
* This file is part of EhViewer
*
* EhViewer is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* EhViewer is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with EhViewer.
* If not, see <https://www.gnu.org/licenses/>.
*/
package com.hippo.util;
import java.util.Comparator;
/**
* Compares each path segment in natural sort order.
* {@code \} and {@code /} are the same. Duplicate {@code \} and {@code /} are ignored.
* Leading {@code \} and {@code /} are ignored, so there is no difference between
* relative path and absolute path.
* {@code /./} and {@code /../} are treated as normal path.
*/
public class PathNaturalComparator implements Comparator<String> {
private static final boolean TYPE_SEPARATOR = false;
private static final boolean TYPE_NORMAL = true;
private final Comparator<String> naturalComparator = new NaturalComparator();
private static int nextSegmentStart(String str, int index) {
if (index >= str.length()) {
return index;
}
boolean type = getType(str.charAt(index));
int i = index + 1;
while (i < str.length() && type == getType(str.charAt(i))) {
i += 1;
}
return i;
}
private static boolean getType(char c) {
if (c == '/' || c == '\\') {
return TYPE_SEPARATOR;
} else {
return TYPE_NORMAL;
}
}
@Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
int index1 = 0;
int index2 = 0;
while (true) {
String data1;
String data2;
for (; ; ) {
int newIndex1 = nextSegmentStart(o1, index1);
if (newIndex1 == index1) {
data1 = null;
break;
}
if (getType(o1.charAt(newIndex1 - 1)) == TYPE_NORMAL) {
data1 = o1.substring(index1, newIndex1);
index1 = newIndex1;
break;
}
index1 = newIndex1;
}
for (; ; ) {
int newIndex2 = nextSegmentStart(o2, index2);
if (newIndex2 == index2) {
data2 = null;
break;
}
if (getType(o2.charAt(newIndex2 - 1)) == TYPE_NORMAL) {
data2 = o2.substring(index2, newIndex2);
index2 = newIndex2;
break;
}
index2 = newIndex2;
}
if (data1 == null && data2 == null) {
return 0;
}
if (data1 == null) {
return -1;
}
if (data2 == null) {
return 1;
}
int result = naturalComparator.compare(data1, data2);
if (result != 0) {
return result;
}
}
}
}
@@ -107,6 +107,17 @@ public class BatteryView extends AppCompatTextView {
registerReceiver();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {
unregisterReceiver();
stopCharger();
mAttached = false;
}
} private final Runnable mCharger = new Runnable() {
private int level = 0;
@@ -122,17 +133,6 @@ public class BatteryView extends AppCompatTextView {
}
};
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {
unregisterReceiver();
stopCharger();
mAttached = false;
}
}
private void registerReceiver() {
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
@@ -112,6 +112,13 @@ public class TextClock extends AppCompatTextView {
public CharSequence getFormat24Hour() {
return mFormat24;
}
public void setFormat24Hour(CharSequence format) {
mFormat24 = format;
chooseFormat();
onTimeChanged();
} private final Runnable mTicker = new Runnable() {
@Override
public void run() {
@@ -124,13 +131,6 @@ public class TextClock extends AppCompatTextView {
}
};
public void setFormat24Hour(CharSequence format) {
mFormat24 = format;
chooseFormat();
onTimeChanged();
}
public boolean is24HourModeEnabled() {
return DateFormat.is24HourFormat(getContext());
}
@@ -227,6 +227,15 @@ public class TextClock extends AppCompatTextView {
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
}
private void registerObserver() {
final ContentResolver resolver = getContext().getContentResolver();
resolver.registerContentObserver(Settings.System.CONTENT_URI, true, mFormatChangeObserver);
}
private void unregisterReceiver() {
getContext().unregisterReceiver(mIntentReceiver);
} private final ContentObserver mFormatChangeObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
@@ -241,15 +250,6 @@ public class TextClock extends AppCompatTextView {
}
};
private void registerObserver() {
final ContentResolver resolver = getContext().getContentResolver();
resolver.registerContentObserver(Settings.System.CONTENT_URI, true, mFormatChangeObserver);
}
private void unregisterReceiver() {
getContext().unregisterReceiver(mIntentReceiver);
}
private void unregisterObserver() {
final ContentResolver resolver = getContext().getContentResolver();
resolver.unregisterContentObserver(mFormatChangeObserver);
@@ -1,51 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya;
import java.util.concurrent.atomic.AtomicLong;
public final class LongIdGenerator {
public static final long INVALID_ID = -1L;
private final AtomicLong mId = new AtomicLong();
public LongIdGenerator() {
}
public LongIdGenerator(long init) {
setNextId(init);
}
@SuppressWarnings("StatementWithEmptyBody")
public long nextId() {
long id;
while ((id = mId.getAndIncrement()) == INVALID_ID) ;
return id;
}
public void setNextId(long id) {
checkInValidId(id);
mId.set(id);
}
private void checkInValidId(long id) {
if (INVALID_ID == id) {
throw new IllegalStateException("Can't set INVALID_ID");
}
}
}
@@ -1,94 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public final class Messenger {
private static Messenger sInstance;
private final IntIdGenerator mIdGenerator;
private final SparseArray<List<Receiver>> mReceiverListMap;
private Messenger() {
mIdGenerator = new IntIdGenerator();
mReceiverListMap = new SparseArray<>();
}
public static Messenger getInstance() {
if (sInstance == null) {
sInstance = new Messenger();
}
return sInstance;
}
public int newId() {
return mIdGenerator.nextId();
}
private void notifyInternal(int id, Object obj) {
List<Receiver> receiverList = mReceiverListMap.get(id);
if (receiverList != null) {
List<Receiver> temp = new LinkedList<>(receiverList);
for (Receiver r : temp) {
r.onReceive(id, obj);
}
}
}
public void notify(final int id, final Object obj) {
// Make sure do it in UI thread
SimpleHandler.getInstance().post(new Runnable() {
@Override
public void run() {
notifyInternal(id, obj);
}
});
}
public void notifyAtOnce(int id, Object obj) {
notifyInternal(id, obj);
}
public void register(int id, Receiver receiver) {
List<Receiver> receiverList = mReceiverListMap.get(id);
if (receiverList == null) {
receiverList = new ArrayList<>();
mReceiverListMap.put(id, receiverList);
}
receiverList.add(receiver);
}
public void unregister(int id, Receiver receiver) {
List<Receiver> receiverList = mReceiverListMap.get(id);
if (receiverList != null) {
receiverList.remove(receiver);
if (receiverList.isEmpty()) {
mReceiverListMap.remove(id);
}
}
}
public interface Receiver {
void onReceive(final int id, final Object obj);
}
}
@@ -1,34 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya;
import android.view.animation.Animation;
public class SimpleAnimationListener implements Animation.AnimationListener {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
@@ -1,185 +0,0 @@
/*
* Copyright (C) 2014-2015 Markus Junginger, greenrobot (http://greenrobot.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya.collect;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Combines a Map with List values to provide simple way to store multiple values for a key (multimap).
* <p/>
* Threading note: All methods are synchronized
*/
public abstract class AbstractMultimap<K, V, C extends Collection<V>> implements Map<K, C> {
protected final boolean threadSafeCollections;
protected Map<K, C> map;
protected AbstractMultimap(Map<K, C> map, boolean threadSafeCollections) {
this.map = map;
this.threadSafeCollections = threadSafeCollections;
}
abstract protected C createNewCollection();
@Override
public void putAll(Map<? extends K, ? extends C> m) {
map.putAll(m);
}
@Override
public synchronized int size() {
return map.size();
}
@Override
public synchronized boolean isEmpty() {
return map.isEmpty();
}
@Override
public synchronized boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public synchronized boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public synchronized C get(Object key) {
return map.get(key);
}
@Override
public synchronized C remove(Object key) {
return map.remove(key);
}
@Override
public synchronized void clear() {
map.clear();
}
@Override
public synchronized Set<K> keySet() {
return map.keySet();
}
@Override
public synchronized Collection<C> values() {
return map.values();
}
@Override
public synchronized boolean equals(Object o) {
return map.equals(o);
}
@Override
public synchronized int hashCode() {
return map.hashCode();
}
/**
* @return number of elements stored for given key after storing the given value.
*/
public synchronized int putElement(K key, V value) {
C collection = map.get(key);
if (collection == null) {
collection = createNewCollection();
map.put(key, collection);
}
collection.add(value);
return collection.size();
}
@Override
public synchronized C put(K key, C value) {
return map.put(key, value);
}
@Override
public synchronized Set<Entry<K, C>> entrySet() {
return map.entrySet();
}
/**
* @return true if the collection was changed.
*/
public synchronized boolean putElements(K key, Collection<V> values) {
C collection = map.get(key);
if (collection == null) {
collection = createNewCollection();
map.put(key, collection);
}
return collection.addAll(values);
}
/**
* @return true if the given element was removed.
*/
public synchronized boolean removeElement(K key, V value) {
C collection = map.get(key);
if (collection == null) {
return false;
} else {
boolean removed = collection.remove(value);
if (collection.isEmpty()) {
map.remove(key);
}
return removed;
}
}
public synchronized int countElements(K key) {
C collection = map.get(key);
if (collection == null) {
return 0;
} else {
return collection.size();
}
}
public synchronized boolean containsElement(K key, V value) {
C collection = map.get(key);
if (collection == null) {
return false;
} else {
return collection.contains(value);
}
}
public synchronized boolean containsElement(V value) {
for (C collection : map.values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
public synchronized C valuesElements() {
C all = createNewCollection();
for (C collection : map.values()) {
all.addAll(collection);
}
return all;
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2022 Tarsin Norbin
*
* This file is part of EhViewer
*
* EhViewer is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* EhViewer is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with EhViewer.
* If not, see <https://www.gnu.org/licenses/>.
*/
package com.hippo.yorozuya.collect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Combines a Map with List values to provide simple way to store multiple values for a key.
*/
// Top level class to get rid of 3rd generic collection parameter for more convenient usage.
public class Multimap<K, V> extends AbstractMultimap<K, V, List<V>> {
protected Multimap(Map<K, List<V>> map, boolean threadSafeCollections) {
super(map, threadSafeCollections);
}
public static <K, V> Multimap<K, V> create() {
return new Multimap<>(new HashMap<K, List<V>>(), false);
}
public static <K, V> Multimap<K, V> createWithThreadSafeLists() {
return new Multimap<>(new HashMap<K, List<V>>(), true);
}
protected List<V> createNewCollection() {
return threadSafeCollections ? new CopyOnWriteArrayList<V>() : new ArrayList<V>();
}
}
@@ -1,49 +0,0 @@
/*
* Copyright 2022 Tarsin Norbin
*
* This file is part of EhViewer
*
* EhViewer is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* EhViewer is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with EhViewer.
* If not, see <https://www.gnu.org/licenses/>.
*/
package com.hippo.yorozuya.collect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Combines a Map with Set values to provide simple way to store multiple values for a key.
* Like {@link com.hippo.yorozuya.collect.Multimap}, but element values are stored in Sets.
*/
// Top level class to get rid of 3rd generic collection parameter for more convenient usage.
public class MultimapSet<K, V> extends AbstractMultimap<K, V, Set<V>> {
protected MultimapSet(Map<K, Set<V>> map, boolean threadSafeSets) {
super(map, threadSafeSets);
}
public static <K, V> MultimapSet<K, V> create() {
return new MultimapSet<>(new HashMap<K, Set<V>>(), false);
}
public static <K, V> MultimapSet<K, V> createWithThreadSafeLists() {
return new MultimapSet<>(new HashMap<K, Set<V>>(), true);
}
protected Set<V> createNewCollection() {
return threadSafeCollections ? new CopyOnWriteArraySet<V>() : new HashSet<V>();
}
}
@@ -1,408 +0,0 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya.collect;
/**
* SparseILArrays map integers to Objects. Unlike a normal array of Objects,
* there can be gaps in the indices. It is intended to be more memory efficient
* than using a HashMap to map Integers to Objects, both because it avoids
* auto-boxing keys and its data structure doesn't rely on an extra entry object
* for each mapping.
*
* <p>Note that this container keeps its mappings in an array data structure,
* using a binary search to find keys. The implementation is not intended to be appropriate for
* data structures
* that may contain large numbers of items. It is generally slower than a traditional
* HashMap, since lookups require a binary search and adds and removes require inserting
* and deleting entries in the array. For containers holding up to hundreds of items,
* the performance difference is not significant, less than 50%.</p>
*
* <p>To help with performance, the container includes an optimization when removing
* keys: instead of compacting its array immediately, it leaves the removed entry marked
* as deleted. The entry can then be re-used for the same key, or compacted later in
* a single garbage collection step of all removed entries. This garbage collection will
* need to be performed at any time the array needs to be grown or the the map size or
* entry values are retrieved.</p>
*
* <p>It is possible to iterate over the items in this container using
* {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
* <code>keyAt(int)</code> with ascending values of the index will return the
* keys in ascending order, or the values corresponding to the keys in ascending
* order in the case of <code>valueAt(int)</code>.</p>
*/
public class SparseILArray<E> implements Cloneable {
private static final Object DELETED = new Object();
private boolean mGarbage = false;
private int[] mKeys;
private Object[] mValues;
private int mSize;
/**
* Creates a new SparseILArray containing no mappings.
*/
public SparseILArray() {
this(10);
}
/**
* Creates a new SparseILArray containing no mappings that will not
* require any additional memory allocation to store the specified
* number of mappings. If you supply an initial capacity of 0, the
* sparse array will be initialized with a light-weight representation
* not requiring any additional array allocations.
*/
public SparseILArray(int initialCapacity) {
if (initialCapacity == 0) {
mKeys = CollectionUtils.EMPTY_INT_ARRAY;
mValues = CollectionUtils.EMPTY_OBJECT_ARRAY;
} else {
mKeys = new int[initialCapacity];
mValues = new Object[initialCapacity];
}
mSize = 0;
}
@Override
@SuppressWarnings("unchecked")
public SparseILArray<E> clone() {
SparseILArray<E> clone = null;
try {
clone = (SparseILArray<E>) super.clone();
clone.mKeys = mKeys.clone();
clone.mValues = mValues.clone();
} catch (CloneNotSupportedException e) {
/* ignore */
}
return clone;
}
/**
* Gets the Object mapped from the specified key, or <code>null</code>
* if no such mapping has been made.
*/
public E get(int key) {
return get(key, null);
}
/**
* Gets the Object mapped from the specified key, or the specified Object
* if no such mapping has been made.
*/
@SuppressWarnings("unchecked")
public E get(int key, E valueIfKeyNotFound) {
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i < 0 || mValues[i] == DELETED) {
return valueIfKeyNotFound;
} else {
return (E) mValues[i];
}
}
/**
* Removes the mapping from the specified key, if there was any.
*/
@SuppressWarnings("unchecked")
public E delete(int key) {
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) {
E deleted = (E) mValues[i];
if (deleted != DELETED) {
mValues[i] = DELETED;
mGarbage = true;
return deleted;
}
}
return null;
}
/**
* Removes the mapping from the specified key, if there was any, returning the old value.
*/
@SuppressWarnings("unchecked")
public E removeReturnOld(int key) {
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) {
if (mValues[i] != DELETED) {
final E old = (E) mValues[i];
mValues[i] = DELETED;
mGarbage = true;
return old;
}
}
return null;
}
/**
* Alias for {@link #delete(int)}.
*/
public E remove(int key) {
return delete(key);
}
/**
* Removes the mapping at the specified index.
*/
public void removeAt(int index) {
if (mValues[index] != DELETED) {
mValues[index] = DELETED;
mGarbage = true;
}
}
/**
* Remove a range of mappings as a batch.
*
* @param index Index to begin at
* @param size Number of mappings to remove
*/
public void removeAtRange(int index, int size) {
final int end = Math.min(mSize, index + size);
for (int i = index; i < end; i++) {
removeAt(i);
}
}
private void gc() {
// Log.e("SparseILArray", "gc start with " + mSize);
int n = mSize;
int o = 0;
int[] keys = mKeys;
Object[] values = mValues;
for (int i = 0; i < n; i++) {
Object val = values[i];
if (val != DELETED) {
if (i != o) {
keys[o] = keys[i];
values[o] = val;
values[i] = null;
}
o++;
}
}
mGarbage = false;
mSize = o;
// Log.e("SparseILArray", "gc end with " + mSize);
}
/**
* Adds a mapping from the specified key to the specified value,
* replacing the previous mapping from the specified key if there
* was one.
*/
public void put(int key, E value) {
int i = ContainerHelpers.binarySearch(mKeys, mSize, key);
if (i >= 0) {
mValues[i] = value;
} else {
i = ~i;
if (i < mSize && mValues[i] == DELETED) {
mKeys[i] = key;
mValues[i] = value;
return;
}
if (mGarbage && mSize >= mKeys.length) {
gc();
// Search again because indices may have changed.
i = ~ContainerHelpers.binarySearch(mKeys, mSize, key);
}
mKeys = CollectionUtils.insert(mKeys, mSize, i, key);
mValues = CollectionUtils.insert(mValues, mSize, i, value);
mSize++;
}
}
/**
* Returns the number of key-value mappings that this SparseILArray
* currently stores.
*/
public int size() {
if (mGarbage) {
gc();
}
return mSize;
}
/**
* Given an index in the range <code>0...size()-1</code>, returns
* the key from the <code>index</code>th key-value mapping that this
* SparseILArray stores.
*
* <p>The keys corresponding to indices in ascending order are guaranteed to
* be in ascending order, e.g., <code>keyAt(0)</code> will return the
* smallest key and <code>keyAt(size()-1)</code> will return the largest
* key.</p>
*/
public int keyAt(int index) {
if (mGarbage) {
gc();
}
return mKeys[index];
}
/**
* Given an index in the range <code>0...size()-1</code>, returns
* the value from the <code>index</code>th key-value mapping that this
* SparseILArray stores.
*
* <p>The values corresponding to indices in ascending order are guaranteed
* to be associated with keys in ascending order, e.g.,
* <code>valueAt(0)</code> will return the value associated with the
* smallest key and <code>valueAt(size()-1)</code> will return the value
* associated with the largest key.</p>
*/
@SuppressWarnings("unchecked")
public E valueAt(int index) {
if (mGarbage) {
gc();
}
return (E) mValues[index];
}
/**
* Given an index in the range <code>0...size()-1</code>, sets a new
* value for the <code>index</code>th key-value mapping that this
* SparseILArray stores.
*/
public void setValueAt(int index, E value) {
if (mGarbage) {
gc();
}
mValues[index] = value;
}
/**
* Returns the index for which {@link #keyAt} would return the
* specified key, or a negative number if the specified
* key is not mapped.
*/
public int indexOfKey(int key) {
if (mGarbage) {
gc();
}
return ContainerHelpers.binarySearch(mKeys, mSize, key);
}
/**
* Returns an index for which {@link #valueAt} would return the
* specified key, or a negative number if no keys map to the
* specified value.
* <p>Beware that this is a linear search, unlike lookups by key,
* and that multiple keys can map to the same value and this will
* find only one of them.
* <p>Note also that unlike most collections' {@code indexOf} methods,
* this method compares values using {@code ==} rather than {@code equals}.
*/
public int indexOfValue(E value) {
if (mGarbage) {
gc();
}
for (int i = 0; i < mSize; i++)
if (mValues[i] == value)
return i;
return -1;
}
/**
* Removes all key-value mappings from this SparseILArray.
*/
public void clear() {
int n = mSize;
Object[] values = mValues;
for (int i = 0; i < n; i++) {
values[i] = null;
}
mSize = 0;
mGarbage = false;
}
/**
* Puts a key/value pair into the array, optimizing for the case where
* the key is greater than all existing keys in the array.
*/
public void append(int key, E value) {
if (mSize != 0 && key <= mKeys[mSize - 1]) {
put(key, value);
return;
}
if (mGarbage && mSize >= mKeys.length) {
gc();
}
mKeys = CollectionUtils.append(mKeys, mSize, key);
mValues = CollectionUtils.append(mValues, mSize, value);
mSize++;
}
/**
* {@inheritDoc}
*
* <p>This implementation composes a string by iterating over its mappings. If
* this map contains itself as a value, the string "(this Map)"
* will appear in its place.
*/
@Override
public String toString() {
if (size() <= 0) {
return "{}";
}
StringBuilder buffer = new StringBuilder(mSize * 28);
buffer.append('{');
for (int i = 0; i < mSize; i++) {
if (i > 0) {
buffer.append(", ");
}
int key = keyAt(i);
buffer.append(key);
buffer.append('=');
Object value = valueAt(i);
if (value != this) {
buffer.append(value);
} else {
buffer.append("(this Map)");
}
}
buffer.append('}');
return buffer.toString();
}
}
@@ -1,101 +0,0 @@
/*
* Copyright 2015-2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.yorozuya.thread;
import androidx.annotation.NonNull;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SerialThreadExecutor implements Executor, Runnable {
private final Lock mThreadLock = new ReentrantLock();
private final Object mWaitLock = new Object();
private final long mKeepAliveMillis;
private final Queue<Runnable> mWorkQueue;
private final ThreadFactory mThreadFactory;
// The worker
private Thread mThread;
public SerialThreadExecutor(long keepAliveMillis,
Queue<Runnable> workQueue, ThreadFactory threadFactory) {
mKeepAliveMillis = keepAliveMillis;
mWorkQueue = workQueue;
mThreadFactory = threadFactory;
}
@Override
public void execute(@NonNull Runnable command) {
mThreadLock.lock();
mWorkQueue.add(command);
// Ensure thread
if (mThread == null) {
mThread = mThreadFactory.newThread(this);
mThread.start();
} else {
synchronized (mWaitLock) {
mWaitLock.notify();
}
}
mThreadLock.unlock();
}
@Override
public void run() {
// It tell whether has waited
boolean hasWaited = false;
for (; ; ) {
mThreadLock.lock();
Runnable runnable = mWorkQueue.poll();
if (runnable == null) {
if (hasWaited) {
// Have waited enough time
mThread = null;
mThreadLock.unlock();
break;
} else {
mThreadLock.unlock();
hasWaited = true;
synchronized (mWaitLock) {
try {
mWaitLock.wait(mKeepAliveMillis);
} catch (InterruptedException e) {
// Ignore
}
}
continue;
}
} else {
mThreadLock.unlock();
}
hasWaited = false;
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}