Compare commits

..
71 Commits
Author SHA1 Message Date
seven332 bc2b21b0f5 1.4.0 2019-01-26 15:56:19 +08:00
seven332 ec132440e7 Close #514, extend the duration of SnackBar 2019-01-24 22:50:05 +08:00
seven332 9d49973504 Add new downloaded gallery to history 2019-01-22 22:23:07 +08:00
seven332 016ec23fbd Fix rating if the gallery has been rated by the user 2019-01-21 20:17:27 +08:00
seven332 59d141fc8e Improve ChromeRequestBuilder
Add request header Accept and Accept-Language.
Update User-Agent.
2019-01-21 16:46:41 +08:00
Tsuki 3d3c3a9273 Update License year 2019-01-21 12:19:41 +08:00
seven332 c580938806 Support tag translations 2019-01-20 00:49:54 +08:00
seven332 3904406d74 Add IoThreadPoolExecutor 2019-01-19 14:05:33 +08:00
seven332 879b8fa50a Support downloading galleries from FavoritesScene 2019-01-17 18:41:49 +08:00
seven332 7228736c95 Avoid crash in unbindService() 2019-01-16 18:46:47 +08:00
seven332 e8eb126135 Catch SQLException in SearchDatabase 2019-01-16 18:38:31 +08:00
seven332 0eb86e37e6 Android Studio 3.3.0 2019-01-16 18:20:12 +08:00
seven332 eff2ed94fe Update GLView
Support OpenGL ES 1.x
2019-01-14 19:38:37 +08:00
seven332 fb2011a408 Adjust thumbnail aspect 2019-01-14 15:32:13 +08:00
seven332 a442578927 Update okhttp 2019-01-14 00:56:11 +08:00
seven332 673735ab2e Update a7zip 2019-01-14 00:55:06 +08:00
seven332 f1bab7e3d4 Add FixedThumb to fix thumbnail size 2019-01-13 02:38:48 +08:00
seven332 1d5b26ee51 Update a7zip 2019-01-10 14:02:01 +08:00
seven332 a1a82b0ce9 Restrict GalleryDetailUrlParser token to 10 characters 2019-01-10 10:34:35 +08:00
seven332 5b961d71b8 Block drawer gesture if it's on ScrollView 2019-01-07 13:01:44 +08:00
seven332 0353c1cebb Update DrawerLayout 2019-01-07 11:49:07 +08:00
seven332 7b07bdc51f 1.3.5 2019-01-05 14:56:25 +08:00
seven332 cf1ac32e17 Add android.max_aspect 2019-01-05 13:37:24 +08:00
seven332 bb28dd97cc Ignore IllegalArgumentException in URLDecoder.decode() 2019-01-05 13:24:42 +08:00
seven332 a33bd63e6e Safe number string parsing 2019-01-05 13:13:37 +08:00
seven332 a0b786b2a6 Avoid NumberFormatException in Html.getHtmlColor() 2019-01-05 12:38:43 +08:00
seven332 9dd39412d4 Update a7zip 2019-01-04 21:55:08 +08:00
seven332 3fdf9453ef Fix Pipe stuck 2019-01-04 21:48:33 +08:00
seven332 116f30e496 1.3.4 2019-01-04 18:57:16 +08:00
seven332 e8d05c273f Update crashlytics sdk 2019-01-04 18:47:05 +08:00
seven332 29e3a50cd3 Update URL_PREFIX_THUMB_E 2019-01-04 13:41:49 +08:00
seven332 1409571ad8 Add ehgt.org and ul.ehgt.org to builtin hosts 2019-01-04 13:41:27 +08:00
seven332 8a7e72c412 Add repo.e-hentai.org to builtin hosts 2019-01-04 13:11:42 +08:00
seven332 948cb9ef9c Update GLView 2019-01-03 19:47:03 +08:00
seven332 926391a0fe Avoid NullPointerException in PrettyPreferenceActivity 2019-01-03 18:42:15 +08:00
seven332 24195430ab Use a7zip to extract archives 2019-01-03 18:03:15 +08:00
seven332 c9afa597d5 Avoid NullPointerException in StageActivity.onCreate() 2019-01-02 20:51:48 +08:00
seven332 adf38af673 Check updateCursorPositionMz method instead of device manufacturer 2019-01-02 18:40:14 +08:00
seven332 17f2bb670e Ignore Throwable in TextInputEditText.onDraw()
Ignore crash in updateCursorPositionMz.
2019-01-02 17:05:43 +08:00
seven332 2293654da8 Call notifyDataSetChanged() in ContentLayout restoring state 2019-01-02 16:37:20 +08:00
seven332 36067c9fac Ignore Throwable in ActivityCompat.requestPermissions() 2019-01-02 16:02:20 +08:00
seven332 8d20621ad4 Avoid crash in bindService() 2019-01-02 15:44:27 +08:00
seven332 a1d1db14c6 Override startService() instead of using SilentContextWrapper 2019-01-02 15:37:56 +08:00
seven332 44cf2b67d0 Set hint to TextInputLayout instead of TextInputEditText
It may avoid a bug of AssistStructure.
https://issuetracker.google.com/issues/62834931
2019-01-02 15:25:49 +08:00
seven332 74c0e478ef Avoid NullPointerException in MainActivity.handleIntent() 2019-01-02 14:53:41 +08:00
seven332 7496534b30 Exclude 64bit .so library
It may fix system .so missing, like "XXX.so is 32-bit instead of 64-bit"
2019-01-02 10:56:00 +08:00
seven332 415ffbc21d Avoid NullPointerException when restore items 2019-01-01 15:51:05 +08:00
seven332 ed4267cb36 Delay SystemUiHelper synchronizing in onWindowFocusChanged()
It fixes invalid SystemUiHelper synchronizing
on XiaoMi MIX2 MIUI 10 Android 8.0
2018-12-27 16:29:11 +08:00
seven332 2de859398b Fix big number causing NumberFormatException in NaturalComparator 2018-12-26 11:08:08 +08:00
seven332 62348433df Insert SilentContextWrapper to avoid crash in startService() 2018-12-25 22:36:10 +08:00
seven332 b64b14c69a Update Image
libjpeg-turbo neon runtime check
2018-12-25 10:52:29 +08:00
seven332 28e8e91303 Do io initialization tasks in new thread 2018-12-23 12:48:06 +08:00
seven332 44026f0ccc Avoid mysterious crash 2018-12-23 12:28:48 +08:00
seven332 95f2d46420 Avoid non-UI thread view touching on some devices 2018-12-23 12:20:10 +08:00
seven332 8f76f50526 Disable left drawer in GalleryDetailScene 2018-12-22 13:52:41 +08:00
seven332 ecd215d632 Avoid RecyclerView inconsistency in HistoryScene 2018-12-22 12:18:02 +08:00
seven332 b138de9563 Update GLView-Image 2018-12-22 00:29:15 +08:00
seven332 9bd344cc58 Avoid NullPointerException in deleteFileAsync() 2018-12-21 21:21:48 +08:00
seven332 ababfd57a6 Update GLView 2018-12-21 21:20:23 +08:00
seven332 45c760a507 Check mGalleryView null in GalleryMenuHelper 2018-12-21 19:51:44 +08:00
seven332 e721a6da1f 1.3.3 2018-12-21 19:35:40 +08:00
seven332 9eeba868d5 Update GLView-Image 2018-12-21 19:32:47 +08:00
seven332 8f3247bac4 Get update information from GitHub 2018-12-21 19:31:57 +08:00
seven332 e5a375c3fe Catch all throwable from startActivityForResult() 2018-12-21 18:53:50 +08:00
seven332 8d75752835 Catch all throwable while calling DownloadManager 2018-12-21 18:26:21 +08:00
seven332 8af786e687 Catch all throwable from startActivity() 2018-12-21 18:04:23 +08:00
seven332 4b1c516b3e Refresh if can't restore ContentLayout data 2018-12-21 17:01:37 +08:00
seven332 f32b79ba72 Save global stuff next id 2018-12-21 16:55:14 +08:00
seven332 92b5f2d766 Use notifyDataSetChanged() instead of notifyItemRemoved() to avoid crash 2018-12-21 16:22:01 +08:00
seven332 a5767e0fe6 Update UniFile 2018-12-21 15:04:03 +08:00
seven332 2fc48bb726 Update Image 2018-12-21 11:09:58 +08:00
89 changed files with 1889 additions and 954 deletions

No files matched your search

+1 -1
View File
@@ -57,7 +57,7 @@ Here is the libraries
# License
Copyright (C) 2014-2016 Hippo Seven
Copyright (C) 2014-2019 Hippo Seven
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+14 -12
View File
@@ -10,11 +10,14 @@ android {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 28
versionCode 89
versionName "1.3.2"
versionCode 93
versionName "1.4.0"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es", "ja", "ko", "fr", "de"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
compileOptions {
@@ -67,33 +70,32 @@ dependencies {
implementation "com.android.support:cardview-v7:$supportLibrary"
implementation "com.android.support:design:$supportLibrary"
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.7'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.8'
implementation 'com.github.amlcurran.showcaseview:library:5.4.3'
implementation 'com.github.seven332.a7zip:extract-lite:d4ddec5793'
implementation 'com.github.seven332:android-recaptcha:2bbb3459a8'
implementation 'com.github.seven332:android-resource:0.1.0'
implementation 'com.github.seven332:animator:0.1.0'
implementation 'com.github.seven332:beerbelly:0.1.4'
implementation 'com.github.seven332.commons-compress:android-lite:464e96d3b4'
implementation 'com.github.seven332:conaco:0.1.5-eh'
implementation 'com.github.seven332:drawerlayout:0.2.1'
implementation 'com.github.seven332:drawerlayout:ea2bb388f0'
implementation 'com.github.seven332:easyrecyclerview:0.1.1'
implementation 'com.github.seven332:glgallery:0.1.2'
implementation 'com.github.seven332:glview:0.1.0'
implementation 'com.github.seven332:glview-image:0.1.0'
implementation 'com.github.seven332:hotspot:0.1.0'
implementation 'com.github.seven332:image:0.1.12'
implementation 'com.github.seven332.junrar:android-lite:46ecc9630a'
implementation 'com.github.seven332:okhttp:3.5.0'
implementation 'com.github.seven332:refreshlayout:0.1.0'
implementation 'com.github.seven332:ripple:0.1.2'
implementation 'com.github.seven332:streampipe:0.1.0'
implementation 'com.github.seven332:tuxiang:0.1.2'
implementation 'com.github.seven332:unifile:a3571536be'
implementation 'com.github.seven332:unifile:9ec57bcd8f'
implementation 'com.github.seven332:yorozuya:0.1.2'
implementation 'com.github.seven332:yorozuya-thread:0.1.1'
implementation 'com.github.seven332:yorozuya-collect:0.1.4'
implementation 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.11.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
implementation 'org.greenrobot:greendao:2.2.1'
implementation 'org.jsoup:jsoup:1.11.3'
@@ -104,11 +106,11 @@ dependencies {
configurations.all {
resolutionStrategy {
force 'com.github.seven332:glgallery:c56b14c6fa'
force 'com.github.seven332:glview-image:4c744db'
force 'com.github.seven332:image:29266a3c7b'
force 'com.github.seven332:glgallery:bb2a43fdd5'
force 'com.github.seven332:glview:0b2bbb8032'
force 'com.github.seven332:glview-image:69930e924e'
force 'com.github.seven332:image:09b43c0c68'
exclude group: 'com.github.seven332', module: 'okhttp'
exclude group: 'com.squareup.okio', module: 'okio'
}
}
+2
View File
@@ -39,6 +39,8 @@
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config">
<meta-data android:name="android.max_aspect" android:value="2.1"/>
<activity
android:name="com.hippo.ehviewer.ui.MainActivity"
android:configChanges="screenSize|uiMode"
@@ -35,6 +35,11 @@ public abstract class PrettyPreferenceActivity extends AppCompatPreferenceActivi
@Override
public void setListAdapter(ListAdapter adapter) {
if (adapter == null) {
super.setListAdapter(null);
return;
}
int count = adapter.getCount();
List<PreferenceActivity.Header> headers = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
@@ -156,4 +156,19 @@ public class AppConfig {
IOUtils.closeQuietly(os);
}
}
@Nullable
public static File getFilesDir(String name) {
File dir = sContext.getFilesDir();
if (dir == null) {
return null;
}
dir = new File(dir, name);
if (dir.isDirectory() || dir.mkdirs()) {
return dir;
} else {
return null;
}
}
}
@@ -16,17 +16,24 @@
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.facebook.soloader.SoLoader;
import com.getkeepsafe.relinker.ReLinker;
import com.hippo.a7zip.A7Zip;
import com.hippo.a7zip.A7ZipExtractLite;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.content.RecordingApplication;
@@ -44,13 +51,14 @@ import com.hippo.network.StatusCodeException;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -61,6 +69,7 @@ import okhttp3.OkHttpClient;
public class EhApplication extends RecordingApplication {
private static final String TAG = EhApplication.class.getSimpleName();
private static final String KEY_GLOBAL_STUFF_NEXT_ID = "global_stuff_next_id";
public static final boolean BETA = false;
@@ -69,6 +78,8 @@ public class EhApplication extends RecordingApplication {
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
private static EhApplication instance;
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final HashMap<Integer, Object> mGlobalStuffMap = new HashMap<>();
private EhCookieStore mEhCookieStore;
@@ -83,15 +94,16 @@ public class EhApplication extends RecordingApplication {
private final List<Activity> mActivityList = new ArrayList<>();
public static EhApplication getInstance() {
return instance;
}
@SuppressLint("StaticFieldLeak")
@Override
public void onCreate() {
super.onCreate();
instance = this;
try {
SoLoader.init(this, 0);
} catch (IOException e) {
throw new RuntimeException("Could not initialize SoLoader", e);
}
super.onCreate();
GetText.initialize(this);
StatusCodeException.initialize(this);
@@ -103,6 +115,8 @@ public class EhApplication extends RecordingApplication {
EhDB.initialize(this);
EhEngine.initialize();
BitmapUtils.initialize(this);
Image.initialize(this);
A7Zip.loadLibrary(A7ZipExtractLite.LIBRARY, libname -> ReLinker.loadLibrary(EhApplication.this, libname));
if (EhDB.needMerge()) {
EhDB.mergeOldDB(this);
@@ -112,17 +126,32 @@ public class EhApplication extends RecordingApplication {
Analytics.start(this);
}
// Disable no media file checker for now. Some devices stuck here.
// // Check no media file
// UniFile downloadLocation = Settings.getDownloadLocation();
// if (Settings.getMediaScan()) {
// CommonOperations.removeNoMediaFile(downloadLocation);
// } else {
// CommonOperations.ensureNoMediaFile(downloadLocation);
// }
// Do io tasks in new thread
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
// Check no media file
try {
UniFile downloadLocation = Settings.getDownloadLocation();
if (Settings.getMediaScan()) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
// Clear temp dir
clearTempDir();
// Clear temp files
try {
clearTempDir();
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
return null;
}
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
// Check app update
update();
@@ -135,6 +164,8 @@ public class EhApplication extends RecordingApplication {
// Ignore
}
mIdGenerator.setNextId(Settings.getInt(KEY_GLOBAL_STUFF_NEXT_ID, 0));
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
}
@@ -198,6 +229,7 @@ public class EhApplication extends RecordingApplication {
public int putGlobalStuff(@NonNull Object o) {
int id = mIdGenerator.nextId();
mGlobalStuffMap.put(id, o);
Settings.putInt(KEY_GLOBAL_STUFF_NEXT_ID, mIdGenerator.nextId());
return id;
}
@@ -339,4 +371,36 @@ public class EhApplication extends RecordingApplication {
return null;
}
}
// Avoid crash on some "energy saving" devices
@Override
public ComponentName startService(Intent service) {
try {
return super.startService(service);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
return null;
}
}
// Avoid crash on some "energy saving" devices
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
try {
return super.bindService(service, conn, flags);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
return false;
}
}
// Avoid crash on some "energy saving" devices
@Override
public void unbindService(ServiceConnection conn) {
try {
super.unbindService(conn);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
}
}
@@ -340,6 +340,13 @@ public class Settings {
return getBoolean(KEY_SHOW_GALLERY_PAGES, DEFAULT_SHOW_GALLERY_PAGES);
}
public static final String KEY_SHOW_TAG_TRANSLATIONS = "show_tag_translations";
private static final boolean DEFAULT_SHOW_TAG_TRANSLATIONS = false;
public static boolean getShowTagTranslations() {
return getBoolean(KEY_SHOW_TAG_TRANSLATIONS, DEFAULT_SHOW_TAG_TRANSLATIONS);
}
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
@@ -16,7 +16,6 @@
package com.hippo.ehviewer;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
@@ -24,11 +23,11 @@ import android.provider.Browser;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.Announcer;
import com.hippo.scene.StageActivity;
import com.hippo.util.ExceptionUtils;
public final class UrlOpener {
@@ -61,7 +60,8 @@ public final class UrlOpener {
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(context, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
@@ -22,15 +22,11 @@ import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
@@ -64,12 +60,7 @@ public class EhClient {
private final OkHttpClient mOkHttpClient;
public EhClient(Context context) {
int poolSize = 3;
BlockingQueue<Runnable> requestWorkQueue = new LinkedBlockingQueue<>();
ThreadFactory threadFactory = new PriorityThreadFactory(TAG,
android.os.Process.THREAD_PRIORITY_BACKGROUND);
mRequestThreadPool = new ThreadPoolExecutor(poolSize, poolSize,
1L, TimeUnit.SECONDS, requestWorkQueue, threadFactory);
mRequestThreadPool = IoThreadPoolExecutor.getInstance();
mOkHttpClient = EhApplication.getOkHttpClient(context);
}
@@ -40,7 +40,10 @@ public class EhDns implements Dns {
static {
Map<String, InetAddress> map = new HashMap<>();
put(map, "e-hentai.org", "104.24.255.11");
put(map, "repo.e-hentai.org", "94.100.29.73");
put(map, "forums.e-hentai.org", "94.100.18.243");
put(map, "ehgt.org", "81.171.14.118");
put(map, "ul.ehgt.org", "94.100.24.82");
builtInHosts = map;
}
@@ -209,7 +209,22 @@ public class EhEngine {
}
}
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
boolean anyRated = false;
for (GalleryInfo info : list) {
if (info.rated) {
anyRated = true;
break;
}
}
boolean needFillByApi = list.size() > 0
&& (TextUtils.isEmpty(list.get(0).uploader)
|| anyRated
|| Settings.getShowJpnTitle()
|| Settings.getShowGalleryPages()
|| sEhFilter.needCallApi());
if (needFillByApi) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -0,0 +1,355 @@
/*
* Copyright 2019 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.ehviewer.client;
import android.support.annotation.Nullable;
import android.util.Base64;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.util.TextUrl;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
public class EhTagDatabase {
private final String name;
private final byte[] tags;
public EhTagDatabase(String name, BufferedSource source) throws IOException {
this.name = name;
int totalBytes = source.readInt();
tags = new byte[totalBytes];
source.readFully(tags);
}
public String getTranslation(String tag) {
return search(tags, tag.getBytes(TextUrl.UTF_8));
}
@Nullable
private String search(byte[] tags, byte[] tag) {
int low = 0;
int high = tags.length;
while (low < high) {
int start = (low + high) / 2;
// Look for the starting '\n'
while (start > -1 && tags[start] != '\n') {
start--;
}
start++;
// Look for the middle '\r'.
int middle = 1;
while (tags[start + middle] != '\r') {
middle++;
}
// Look for the ending '\n'
int end = middle + 1;
while (tags[start + end] != '\n') {
end++;
}
int compare;
int tagIndex = 0;
int curIndex = start;
for (;;) {
int tagByte = tag[tagIndex] & 0xff;
int curByte = tags[curIndex] & 0xff;
compare = tagByte - curByte;
if (compare != 0) {
break;
}
tagIndex++;
curIndex++;
if (tagIndex == tag.length && curIndex == start + middle) {
break;
}
if (tagIndex == tag.length) {
compare = -1;
break;
}
if (curIndex == start + middle) {
compare = 1;
break;
}
}
if (compare < 0) {
high = start - 1;
} else if (compare > 0) {
low = start + end + 1;
} else {
byte[] bytes = Base64.decode(tags, start + middle + 1, end - middle - 1, Base64.DEFAULT);
return new String(bytes, TextUrl.UTF_8);
}
}
return null;
}
private static final String[] METADATA_ZH_CN = new String[] {
"tag-translations-zh-rCN.sha1",
"https://github.com/seven332/EhViewer/raw/tag-translations/tag-translations/tag-translations-zh-rCN.sha1",
"tag-translations-zh-rCN",
"https://github.com/seven332/EhViewer/raw/tag-translations/tag-translations/tag-translations-zh-rCN",
};
private static final Map<String, String> NAMESPACE_TO_PREFIX = new HashMap<>();
static {
NAMESPACE_TO_PREFIX.put("artist", "a:");
NAMESPACE_TO_PREFIX.put("character", "c:");
NAMESPACE_TO_PREFIX.put("female", "f:");
NAMESPACE_TO_PREFIX.put("group", "g:");
NAMESPACE_TO_PREFIX.put("language", "l:");
NAMESPACE_TO_PREFIX.put("male", "m:");
NAMESPACE_TO_PREFIX.put("misc", "");
NAMESPACE_TO_PREFIX.put("parody", "p:");
NAMESPACE_TO_PREFIX.put("reclass", "r:");
}
private static volatile EhTagDatabase instance;
// TODO more lock for different language
private static Lock lock = new ReentrantLock();
@Nullable
public static EhTagDatabase getInstance() {
return instance;
}
@Nullable
public static String namespaceToPrefix(String namespace) {
return NAMESPACE_TO_PREFIX.get(namespace);
}
private static String[] getMetadata() {
Locale locale = Locale.getDefault();
if ("zh".equals(locale.getLanguage()) && "CN".equals(locale.getCountry())) {
return METADATA_ZH_CN;
}
return null;
}
public static boolean isPossible() {
return getMetadata() != null;
}
@Nullable
private static byte[] getFileContent(File file, int length) {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
byte[] content = new byte[length];
source.readFully(content);
return content;
} catch (IOException e) {
return null;
}
}
@Nullable
private static byte[] getFileSha1(File file) {
try (InputStream is = new FileInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
int n;
byte[] buffer = new byte[4 * 1024];
while ((n = is.read(buffer)) != -1) {
digest.update(buffer, 0, n);
}
return digest.digest();
} catch (IOException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static boolean equals(byte[] b1, byte[] b2) {
if (b1 == null && b2 == null) {
return true;
}
if (b1 == null || b2 == null) {
return false;
}
if (b1.length != b2.length) {
return false;
}
for (int i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
private static boolean checkData(File sha1File, File dataFile) {
byte[] s1 = getFileContent(sha1File, 20);
if (s1 == null) {
return false;
}
byte[] s2 = getFileSha1(dataFile);
if (s2 == null) {
return false;
}
return equals(s1, s2);
}
private static boolean save(OkHttpClient client, String url, File file) {
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
try (Response response = call.execute()) {
if (!response.isSuccessful()) {
return false;
}
ResponseBody body = response.body();
if (body == null) {
return false;
}
try (InputStream is = body.byteStream(); OutputStream os = new FileOutputStream(file)) {
IOUtils.copy(is, os);
}
return true;
} catch (IOException e) {
return false;
}
}
public static void update() {
String[] urls = getMetadata();
if (urls == null || urls.length != 4) {
// Clear tags if it's not possible
instance = null;
return;
}
String sha1Name = urls[0];
String sha1Url = urls[1];
String dataName = urls[2];
String dataUrl = urls[3];
// Clear tags if name if different
EhTagDatabase tmp = instance;
if (tmp != null && !tmp.name.equals(dataName)) {
instance = null;
}
IoThreadPoolExecutor.getInstance().execute(() -> {
if (!lock.tryLock()) {
return;
}
try {
File dir = AppConfig.getFilesDir("tag-translations");
if (dir == null) {
return;
}
// Check current sha1 and current data
File sha1File = new File(dir, sha1Name);
File dataFile = new File(dir, dataName);
if (!checkData(sha1File, dataFile)) {
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
}
// Read current EhTagDatabase
if (instance == null && dataFile.exists()) {
try (BufferedSource source = Okio.buffer(Okio.source(dataFile))) {
instance = new EhTagDatabase(dataName, source);
} catch (IOException e) {
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
}
}
OkHttpClient client = EhApplication.getOkHttpClient(EhApplication.getInstance());
// Save new sha1
File tempSha1File = new File(dir, sha1Name + ".tmp");
if (!save(client, sha1Url, tempSha1File)) {
FileUtils.delete(tempSha1File);
return;
}
// Check new sha1 and current data
if (checkData(tempSha1File, dataFile)) {
// The data is the same
FileUtils.delete(tempSha1File);
return;
}
// Save new data
File tempDataFile = new File(dir, dataName + ".tmp");
if (!save(client, dataUrl, tempDataFile)) {
FileUtils.delete(tempDataFile);
return;
}
// Check new sha1 and new data
if (!checkData(tempSha1File, tempDataFile)) {
FileUtils.delete(tempSha1File);
FileUtils.delete(tempDataFile);
return;
}
// Replace current sha1 and current data with new sha1 and new data
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
tempSha1File.renameTo(sha1File);
tempDataFile.renameTo(dataFile);
// Read new EhTagDatabase
try (BufferedSource source = Okio.buffer(Okio.source(dataFile))) {
instance = new EhTagDatabase(dataName, source);
} catch (IOException e) {
// Ignore
}
} finally {
lock.unlock();
}
});
}
}
@@ -52,7 +52,7 @@ public class EhUrl {
public static final String UCONFIG_E = HOST_E + "uconfig.php";
public static final String UCONFIG_EX = HOST_EX + "uconfig.php";
private static final String URL_PREFIX_THUMB_E = "https://ehgt.org/t/";
private static final String URL_PREFIX_THUMB_E = "https://ul.ehgt.org/";
private static final String URL_PREFIX_THUMB_EX = "https://exhentai.org/t/";
public static String getGalleryDetailUrl(long gid, String token) {
@@ -121,6 +121,8 @@ public class GalleryInfo implements Parcelable {
*/
public String simpleLanguage;
public boolean rated;
public final void generateSLang() {
if (simpleTags != null) {
generateSLangFromTags();
@@ -308,7 +308,7 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
} else if ("f_search".equals(key)) {
try {
keyword = URLDecoder.decode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
// Ignore
}
} else if ("advsearch".equals(key)) {
@@ -56,7 +56,7 @@ public class FavoritesParser {
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
countArray[i] = ParserUtils.parseInt(fp.child(0).text());
countArray[i] = ParserUtils.parseInt(fp.child(0).text(), 0);
catArray[i] = ParserUtils.trim(fp.child(2).text());
}
} catch (Throwable e) {
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.yorozuya.NumberUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -43,8 +44,8 @@ public class GalleryApiParser {
gi.category = EhUtils.getCategory(g.getString("category"));
gi.thumb = EhUtils.handleThumbUrlResolution(g.getString("thumb"));
gi.uploader = g.getString("uploader");
gi.posted = ParserUtils.formatDate(ParserUtils.parseLong(g.getString("posted")) * 1000);
gi.rating = Float.parseFloat(g.getString("rating"));
gi.posted = ParserUtils.formatDate(ParserUtils.parseLong(g.getString("posted"), 0) * 1000);
gi.rating = NumberUtils.parseFloatSafely(g.getString("rating"), 0.0f);
// tags
JSONArray tagJa = g.getJSONArray("tags");
int tagLength = tagJa.length();
@@ -53,7 +54,7 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = Integer.parseInt(g.getString("filecount"));
gi.pages = NumberUtils.parseIntSafely(g.getString("filecount"), 0);
gi.generateSLang();
}
}
@@ -109,13 +109,16 @@ public class GalleryDetailParser {
private static void parseDetail(GalleryDetail gd, Document d, String body) throws ParseException {
Matcher matcher = PATTERN_DETAIL.matcher(body);
if (matcher.find()) {
gd.gid = Long.parseLong(matcher.group(1));
gd.gid = NumberUtils.parseLongSafely(matcher.group(1), -1L);
gd.token = matcher.group(2);
gd.apiUid = NumberUtils.parseLongSafely(matcher.group(3), -1L);
gd.apiKey = matcher.group(4);
} else {
throw new ParseException("Can't parse gallery detail", body);
}
if (gd.gid == -1L) {
throw new ParseException("Can't parse gallery detail", body);
}
matcher = PATTERN_TORRENT.matcher(body);
if (matcher.find()) {
@@ -494,7 +497,7 @@ public class GalleryDetailParser {
Matcher m = PATTERN_PREVIEW_PAGES.matcher(body);
int previewPages = -1;
if (m.find()) {
previewPages = ParserUtils.parseInt(m.group(1));
previewPages = ParserUtils.parseInt(m.group(1), -1);
}
if (previewPages <= 0) {
@@ -508,12 +511,18 @@ public class GalleryDetailParser {
* Parse pages with regular expressions
*/
public static int parsePages(String body) throws ParseException {
int pages = -1;
Matcher m = PATTERN_PAGES.matcher(body);
if (m.find()) {
return ParserUtils.parseInt(m.group(1));
} else {
pages = ParserUtils.parseInt(m.group(1), -1);
}
if (pages < 0) {
throw new ParseException("Parse pages error", body);
}
return pages;
}
public static PreviewSet parsePreviewSet(Document d, String body) throws ParseException {
@@ -571,7 +580,10 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
int index = ParserUtils.parseInt(m.group(2)) - 1;
int index = ParserUtils.parseInt(m.group(2), 0) - 1;
if (index < 0) {
continue;
}
String imageUrl = ParserUtils.trim(m.group(3));
String pageUrl = ParserUtils.trim(m.group(1));
if (Settings.getFixThumbUrl()) {
@@ -594,10 +606,23 @@ public class GalleryDetailParser {
Matcher m = PATTERN_NORMAL_PREVIEW.matcher(body);
NormalPreviewSet normalPreviewSet = new NormalPreviewSet();
while (m.find()) {
normalPreviewSet.addItem(ParserUtils.parseInt(m.group(6)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.parseInt((m.group(4))), 0,
ParserUtils.parseInt(m.group(1)), ParserUtils.parseInt(m.group(2)),
ParserUtils.trim(m.group(5)));
int position = ParserUtils.parseInt(m.group(6), 0) - 1;
if (position < 0) {
continue;
}
String imageUrl = ParserUtils.trim(m.group(3));
int xOffset = ParserUtils.parseInt(m.group(4), 0);
int yOffset = 0;
int width = ParserUtils.parseInt(m.group(1), 0);
if (width <= 0) {
continue;
}
int height = ParserUtils.parseInt(m.group(2), 0);
if (height <= 0) {
continue;
}
String pageUrl = ParserUtils.trim(m.group(5));
normalPreviewSet.addItem(position, imageUrl, xOffset, yOffset, width, height, pageUrl);
}
if (normalPreviewSet.size() == 0) {
@@ -20,6 +20,7 @@ import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.yorozuya.NumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -33,7 +34,7 @@ public final class GalleryDetailUrlParser {
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/(?:g|mpv)/(\\d+)/([0-9a-f]{10})");
private static final Pattern URL_PATTERN = Pattern.compile(
"(\\d+)/([0-9a-f]{10})");
"(\\d+)/([0-9a-f]{10})(?:[^0-9a-f]|$)");
@Nullable
public static Result parse(String url) {
@@ -50,8 +51,11 @@ public final class GalleryDetailUrlParser {
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(1));
result.gid = NumberUtils.parseLongSafely(m.group(1), -1L);
result.token = m.group(2);
if (result.gid < 0) {
return null;
}
return result;
} else {
return null;
@@ -60,18 +60,17 @@ public class GalleryListParser {
private static String parseRating(String ratingStyle) {
Matcher m = PATTERN_RATING.matcher(ratingStyle);
int num1;
int num2;
int num1 = Integer.MIN_VALUE;
int num2 = Integer.MIN_VALUE;
int rate = 5;
String re;
if (m.find()) {
num1 = ParserUtils.parseInt(m.group().replace("px", ""));
} else {
return null;
num1 = ParserUtils.parseInt(m.group().replace("px", ""), Integer.MIN_VALUE);
}
if (m.find()) {
num2 = ParserUtils.parseInt(m.group().replace("px", ""));
} else {
num2 = ParserUtils.parseInt(m.group().replace("px", ""), Integer.MIN_VALUE);
}
if (num1 == Integer.MIN_VALUE || num2 == Integer.MIN_VALUE) {
return null;
}
rate = rate - num1 / 16;
@@ -163,6 +162,8 @@ public class GalleryListParser {
Element it4r = JsoupUtils.getElementByClass(e, "it4r");
if (null != it4r) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(it4r.attr("style")), -1.0f);
// TODO The gallery may be rated even if it has one of these classes
gi.rated = it4r.hasClass("irr") || it4r.hasClass("irg") || it4r.hasClass("irb");
} else {
Log.w(TAG, "Can't parse gallery info rating");
gi.rating = -1.0f;
@@ -18,6 +18,7 @@ package com.hippo.ehviewer.client.parser;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.yorozuya.NumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -47,9 +48,12 @@ public final class GalleryPageUrlParser {
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(2));
result.gid = NumberUtils.parseLongSafely(m.group(2), -1L);
result.pToken = m.group(1);
result.page = Integer.parseInt(m.group(3)) - 1;
result.page = NumberUtils.parseIntSafely(m.group(3), 0) - 1;
if (result.gid < 0 || result.page < 0) {
return null;
}
return result;
} else {
return null;
@@ -16,6 +16,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.text.DateFormat;
@@ -39,11 +40,15 @@ public class ParserUtils {
return StringUtils.unescapeXml(str).trim();
}
public static int parseInt(String str) {
return Integer.parseInt(trim(str).replace(",", ""));
public static int parseInt(String str, int defValue) {
return NumberUtils.parseIntSafely(trim(str).replace(",", ""), defValue);
}
public static long parseLong(String str) {
return Long.parseLong(trim(str).replace(",", ""));
public static long parseLong(String str, long defValue) {
return NumberUtils.parseLongSafely(trim(str).replace(",", ""), defValue);
}
public static float parseFloat(String str, float defValue) {
return NumberUtils.parseFloatSafely(trim(str).replace(",", ""), defValue);
}
}
@@ -32,6 +32,7 @@ import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ObjectUtils;
@@ -295,6 +296,9 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
// Make sure download is running
ensureDownload();
// Add it to history
EhDB.putHistoryInfo(info);
}
}
@@ -611,7 +615,7 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
return null;
}
}.execute();
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
// Update in DB
@@ -0,0 +1,156 @@
/*
* Copyright 2019 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.ehviewer.gallery;
import com.hippo.a7zip.ArchiveException;
import com.hippo.a7zip.InArchive;
import com.hippo.a7zip.InStream;
import com.hippo.a7zip.PropID;
import com.hippo.a7zip.PropType;
import com.hippo.a7zip.SequentialOutStream;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
class A7ZipArchive implements Closeable {
private InArchive archive;
private A7ZipArchive(InArchive archive) {
this.archive = archive;
}
@Override
public void close() {
archive.close();
}
private static boolean isSupportedFilename(String name) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
List<A7ZipArchiveEntry> getArchiveEntries() {
List<A7ZipArchiveEntry> entries = new ArrayList<>();
for (int i = 0, n = archive.getNumberOfEntries(); i < n; i++) {
if (!archive.getEntryBooleanProperty(i, PropID.ENCRYPTED)
&& !archive.getEntryBooleanProperty(i, PropID.IS_DIR)
&& !archive.getEntryBooleanProperty(i, PropID.IS_VOLUME)
&& !archive.getEntryBooleanProperty(i, PropID.SOLID)) {
String path = archive.getEntryPath(i);
if (isSupportedFilename(path.toLowerCase())) {
entries.add(new A7ZipArchiveEntry(archive, i, path));
}
}
}
return entries;
}
static A7ZipArchive create(UniRandomAccessFile file) throws ArchiveException {
InStream store = new UniRandomAccessFileInStream(file);
InArchive archive = InArchive.open(store);
if ((archive.getArchivePropertyType(PropID.ENCRYPTED) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.ENCRYPTED))
|| (archive.getArchivePropertyType(PropID.SOLID) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.SOLID))
|| (archive.getArchivePropertyType(PropID.IS_VOLUME) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.IS_VOLUME))) {
throw new ArchiveException("Unsupported archive");
}
return new A7ZipArchive(archive);
}
static class A7ZipArchiveEntry {
private InArchive archive;
private int index;
private String path;
private A7ZipArchiveEntry(InArchive archive, int index, String path) {
this.archive = archive;
this.index = index;
this.path = path;
}
String getPath() {
return path;
}
void extract(OutputStream os) throws ArchiveException {
archive.extractEntry(index, new OutputStreamSequentialOutStream(os));
}
}
private static class UniRandomAccessFileInStream implements InStream {
private UniRandomAccessFile file;
public UniRandomAccessFileInStream(UniRandomAccessFile file) {
this.file = file;
}
@Override
public void seek(long pos) throws IOException {
file.seek(pos);
}
@Override
public long tell() throws IOException {
return file.getFilePointer();
}
@Override
public long size() throws IOException {
return file.length();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return file.read(b, off, len);
}
@Override
public void close() throws IOException {
file.close();
}
}
private static class OutputStreamSequentialOutStream implements SequentialOutStream {
private OutputStream stream;
public OutputStreamSequentialOutStream(OutputStream stream) {
this.stream = stream;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
@Override
public void close() throws IOException {
stream.close();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2018 Hippo Seven
* Copyright 2019 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,38 +21,43 @@ import android.net.Uri;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.a7zip.ArchiveException;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.archive.Archive;
import com.hippo.ehviewer.gallery.archive.ArchiveEntry;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.unifile.UniRandomAccessFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable {
public class ArchiveGalleryProvider extends GalleryProvider2 {
private static final String TAG = ArchiveGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final UniFile file;
private final Stack<Integer> requests = new Stack<>();
private final AtomicInteger decodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@Nullable
private Thread bgThread;
private Thread archiveThread;
private Thread decodeThread;
private volatile int size = STATE_WAIT;
private String error;
private final Stack<Integer> requests = new Stack<>();
private final AtomicInteger extractingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final LinkedHashMap<Integer, InputStream> streams = new LinkedHashMap<>();
private final AtomicInteger decodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
public ArchiveGalleryProvider(Context context, Uri uri) {
file = UniFile.fromUri(context, uri);
}
@@ -61,18 +66,28 @@ public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable
public void start() {
super.start();
bgThread = new PriorityThread(this, TAG + '-' + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
bgThread.start();
int id = sIdGenerator.incrementAndGet();
archiveThread = new PriorityThread(
new ArchiveTask(), "ArchiveTask" + '-' + id, Process.THREAD_PRIORITY_BACKGROUND);
archiveThread.start();
decodeThread = new PriorityThread(
new DecodeTask(), "DecodeTask" + '-' + id, Process.THREAD_PRIORITY_BACKGROUND);
decodeThread.start();
}
@Override
public void stop() {
super.stop();
if (bgThread != null) {
bgThread.interrupt();
bgThread = null;
if (archiveThread != null) {
archiveThread.interrupt();
archiveThread = null;
}
if (decodeThread != null) {
decodeThread.interrupt();
decodeThread = null;
}
}
@@ -83,8 +98,14 @@ public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable
@Override
protected void onRequest(int index) {
boolean inDecodeTask;
synchronized (streams) {
inDecodeTask = streams.keySet().contains(index) || index == decodingIndex.get();
}
synchronized (requests) {
if (!requests.contains(index) && index != decodingIndex.get()) {
boolean inArchiveTask = requests.contains(index) || index == extractingIndex.get();
if (!inArchiveTask && !inDecodeTask) {
requests.add(index);
requests.notify();
}
@@ -129,90 +150,132 @@ public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable
return null;
}
@Override
public void run() {
UniRandomAccessFile uraf = null;
if (file != null) {
private class ArchiveTask implements Runnable {
@Override
public void run() {
UniRandomAccessFile uraf = null;
if (file != null) {
try {
uraf = file.createRandomAccessFile("r");
} catch (IOException e) {
e.printStackTrace();
}
}
if (uraf == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_reading_failed);
notifyDataChanged();
return;
}
A7ZipArchive archive = null;
try {
uraf = file.createRandomAccessFile("r");
} catch (IOException e) {
archive = A7ZipArchive.create(uraf);
} catch (ArchiveException e) {
e.printStackTrace();
}
}
if (uraf == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_reading_failed);
if (archive == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_invalid_archive);
notifyDataChanged();
return;
}
List<A7ZipArchive.A7ZipArchiveEntry> entries = archive.getArchiveEntries();
Collections.sort(entries, naturalComparator);
// Update size and notify changed
size = entries.size();
notifyDataChanged();
return;
}
Archive archive = null;
try {
archive = Archive.create(uraf);
} catch (IOException e) {
e.printStackTrace();
}
if (archive == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_invalid_archive);
notifyDataChanged();
return;
}
List<ArchiveEntry> entries = archive.getArchiveEntries();
Collections.sort(entries, naturalComparator);
// Update size and notify changed
size = entries.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (requests) {
if (requests.isEmpty()) {
try {
requests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (requests) {
if (requests.isEmpty()) {
try {
requests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = requests.pop();
extractingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= entries.size()) {
extractingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
index = requests.pop();
decodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= entries.size()) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
Pipe pipe = new Pipe(4 * 1024);
try {
InputStream is = entries.get(index).getInputStream();
Image image = Image.decode(is, true);
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
synchronized (streams) {
if (streams.get(index) != null) {
continue;
}
streams.put(index, pipe.getInputStream());
streams.notify();
}
try {
entries.get(index).extract(pipe.getOutputStream());
} catch (ArchiveException e) {
e.printStackTrace();
} finally {
extractingIndex.lazySet(GalleryPageView.INVALID_INDEX);
}
} catch (IOException e) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
}
// Clear
IOUtils.closeQuietly(archive);
}
private static Comparator<ArchiveEntry> naturalComparator = new Comparator<ArchiveEntry>() {
private class DecodeTask implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
int index;
InputStream stream;
synchronized (streams) {
if (streams.isEmpty()) {
try {
streams.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
Iterator<Map.Entry<Integer, InputStream>> iterator = streams.entrySet().iterator();
Map.Entry<Integer, InputStream> entry = iterator.next();
iterator.remove();
index = entry.getKey();
stream = entry.getValue();
decodingIndex.lazySet(index);
}
try {
Image image = Image.decode(stream, true);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} finally {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
}
}
}
}
private static Comparator<A7ZipArchive.A7ZipArchiveEntry> naturalComparator = new Comparator<A7ZipArchive.A7ZipArchiveEntry>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public int compare(ArchiveEntry o1, ArchiveEntry o2) {
return comparator.compare(o1.getName(), o2.getName());
public int compare(A7ZipArchive.A7ZipArchiveEntry o1, A7ZipArchive.A7ZipArchiveEntry o2) {
return comparator.compare(o1.getPath(), o2.getPath());
}
};
}
@@ -0,0 +1,162 @@
/*
* Copyright 2019 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.ehviewer.gallery;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
class Pipe {
private final int capacity;
private final byte[] buffer;
private int head = 0;
private int tail = 0;
private boolean full = false;
private boolean inClosed = false;
private boolean outClosed = false;
private InputStream inputStream = new InputStream() {
@Override
public int read() throws IOException {
synchronized (Pipe.this) {
byte[] bytes = new byte[1];
if (read(bytes, 0, 1) != -1) {
return bytes[0];
} else {
return -1;
}
}
}
@Override
public int read(@NonNull byte[] b, int off, int len) throws IOException {
synchronized (Pipe.this) {
for (;;) {
if (inClosed) {
throw new IOException("The InputStream is closed");
}
if (len == 0) {
return 0;
}
if (head == tail && !full) {
if (outClosed) {
// No bytes available and the OutputStream is closed. So it's the end.
return -1;
} else {
// Wait for OutputStream write bytes
try {
Pipe.this.wait();
} catch (InterruptedException e) {
throw new IOException("The thread interrupted", e);
}
}
} else {
int read = Math.min(len, (head < tail ? tail : capacity) - head);
System.arraycopy(buffer, head, b, off, read);
head += read;
if (head == capacity) {
head = 0;
}
full = false;
Pipe.this.notifyAll();
return read;
}
}
}
}
@Override
public void close() {
synchronized (Pipe.this) {
inClosed = true;
Pipe.this.notifyAll();
}
}
};
private OutputStream outputStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
synchronized (Pipe.this) {
byte[] bytes = new byte[] { (byte) b};
write(bytes, 0, 1);
}
}
@Override
public void write(@NonNull byte[] b, int off, int len) throws IOException {
synchronized (Pipe.this) {
while (len != 0) {
if (outClosed) {
throw new IOException("The OutputStream is closed");
}
if (inClosed) {
throw new IOException("The InputStream is closed");
}
if (head == tail && full) {
// The buffer is full, wait for InputStream read bytes
try {
Pipe.this.wait();
} catch (InterruptedException e) {
throw new IOException("The thread interrupted", e);
}
} else {
int write = Math.min(len, (head <= tail ? capacity : head) - tail);
System.arraycopy(b, off, buffer, tail, write);
off += write;
len -= write;
tail += write;
if (tail == capacity) {
tail = 0;
}
if (head == tail) {
full = true;
}
Pipe.this.notifyAll();
}
}
}
}
@Override
public void close() {
synchronized (Pipe.this) {
outClosed = true;
Pipe.this.notifyAll();
}
}
};
Pipe(int capacity) {
this.capacity = capacity;
this.buffer = new byte[capacity];
}
InputStream getInputStream() {
return inputStream;
}
OutputStream getOutputStream() {
return outputStream;
}
}
@@ -1,91 +0,0 @@
/*
* Copyright 2018 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.ehviewer.gallery.archive;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
public abstract class Archive implements Closeable {
private static final byte[] FILE_SIGNATURE_SEVEN_Z = { 0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C };
private static final byte[] FILE_SIGNATURE_ZIP = { 0x50, 0x4B };
private static final byte[] FILE_SIGNATURE_RAR = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00 };
public abstract List<ArchiveEntry> getArchiveEntries();
public static Archive create(UniRandomAccessFile file) throws IOException {
byte[] bytes = new byte[8];
readFully(file, bytes, 8);
file.seek(0);
if (equals(bytes, FILE_SIGNATURE_SEVEN_Z, FILE_SIGNATURE_SEVEN_Z.length)) {
return SevenZArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_ZIP, FILE_SIGNATURE_ZIP.length)) {
return ZipArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_RAR, FILE_SIGNATURE_RAR.length)) {
return RarArchive.create(file);
}
return null;
}
static boolean isSupportedFilename(String name) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
private static int readFully(UniRandomAccessFile file, byte[] bytes, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = file.read(bytes, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
private static boolean equals(byte[] b1, byte[] b2, int size) {
if (b1.length < size || b2.length < size) {
return false;
}
for (int i = 0; i < size; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
}
@@ -1,27 +0,0 @@
/*
* Copyright 2018 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.ehviewer.gallery.archive;
import java.io.IOException;
import java.io.InputStream;
public abstract class ArchiveEntry {
public abstract String getName();
public abstract InputStream getInputStream() throws IOException;
}
@@ -1,198 +0,0 @@
/*
* Copyright 2018 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.ehviewer.gallery.archive;
import com.github.junrar.Volume;
import com.github.junrar.VolumeManager;
import com.github.junrar.exception.RarException;
import com.github.junrar.io.IReadOnlyAccess;
import com.github.junrar.rarfile.FileHeader;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class RarArchive extends Archive {
private com.github.junrar.Archive file;
private RarArchive(com.github.junrar.Archive file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (FileHeader fileHeader : file.getFileHeaders()) {
if (isSupportedFilename(fileHeader.getFileNameString().toLowerCase())) {
result.add(new RarArchiveEntry(file, fileHeader));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
VolumeManager volumeManager = new UniRandomAccessFileVolumeManager(file);
com.github.junrar.Archive archive;
try {
archive = new com.github.junrar.Archive(volumeManager);
if (archive.getMainHeader().isSolid()) {
throw new IOException("Solid archive is not supported");
}
} catch (RarException e) {
throw new IOException("Invalid rar archive", e);
}
return new RarArchive(archive);
}
public static class RarArchiveEntry extends ArchiveEntry {
private com.github.junrar.Archive file;
private FileHeader header;
private RarArchiveEntry(com.github.junrar.Archive file, FileHeader header) {
this.file = file;
this.header = header;
}
@Override
public String getName() {
return header.getFileNameString();
}
@Override
public InputStream getInputStream() throws IOException {
try {
return file.getInputStream(header);
} catch (RarException e) {
throw new IOException("Can't getInputStream from rar archive", e);
}
}
}
private static class UniRandomAccessFileVolumeManager implements VolumeManager {
private UniRandomAccessFile file;
private UniRandomAccessFileVolumeManager(UniRandomAccessFile file) {
this.file = file;
}
@Override
public Volume nextArchive(com.github.junrar.Archive archive, Volume lastVolume) {
if (lastVolume == null) {
return new UniRandomAccessFileVolume(archive, file);
} else {
return null;
}
}
}
private static class UniRandomAccessFileVolume implements Volume {
private com.github.junrar.Archive archive;
private UniRandomAccessFile file;
private UniRandomAccessFileVolume(com.github.junrar.Archive archive, UniRandomAccessFile file) {
this.archive = archive;
this.file = file;
}
@Override
public IReadOnlyAccess getReadOnlyAccess() {
return new UniReadOnlyAccessFile(file);
}
@Override
public long getLength() throws IOException {
return file.length();
}
@Override
public com.github.junrar.Archive getArchive() {
return archive;
}
}
private static class UniReadOnlyAccessFile implements IReadOnlyAccess {
private UniRandomAccessFile file;
private UniReadOnlyAccessFile(UniRandomAccessFile file) {
this.file = file;
}
@Override
public long getPosition() throws IOException {
return file.getFilePointer();
}
@Override
public void setPosition(long pos) throws IOException {
file.seek(pos);
}
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (file.read(b) == -1) {
return -1;
} else {
return b[0];
}
}
@Override
public int read(byte[] buffer, int off, int count) throws IOException {
return file.read(buffer, off, count);
}
@Override
public int readFully(byte[] buffer, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = read(buffer, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
@Override
public void close() throws IOException {
file.close();
}
}
}
@@ -1,96 +0,0 @@
/*
* Copyright 2018 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.ehviewer.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
public class SevenZArchive extends Archive {
private SevenZFile file;
public SevenZArchive(SevenZFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry archive : file.getEntries()) {
if (archive.getSize() != 0
&& !archive.isDirectory()
&& isSupportedFilename(archive.getName().toLowerCase())) {
result.add(new SevenZArchiveEntry(file, archive));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
SevenZFile sevenZFile = new SevenZFile(store);
// Check whether the archive is solid
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry : sevenZFile.getEntries()) {
if (entry.getSize() != 0
&& !entry.isDirectory()
&& !entry.isFirstInFolder()) {
throw new IOException("Solid archive is not supported");
}
}
return new SevenZArchive(sevenZFile);
}
public static class SevenZArchiveEntry extends ArchiveEntry {
private SevenZFile file;
private org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry;
private SevenZArchiveEntry(
SevenZFile file,
org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
file.setEntry(entry);
return file.getInputStreamForCurrentEntry();
}
}
}
@@ -1,86 +0,0 @@
/*
* Copyright 2018 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.ehviewer.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.zip.ZipFile;
public class ZipArchive extends Archive {
private ZipFile file;
private ZipArchive(ZipFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
Enumeration<org.apache.commons.compress.archivers.zip.ZipArchiveEntry> entries = file.getEntries();
while (entries.hasMoreElements()) {
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry = entries.nextElement();
if (isSupportedFilename(entry.getName().toLowerCase())) {
result.add(new ZipArchiveEntry(file, entry));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
ZipFile zipFile = new ZipFile(store);
return new ZipArchive(zipFile);
}
public static class ZipArchiveEntry extends ArchiveEntry {
private ZipFile file;
private org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry;
private ZipArchiveEntry(
ZipFile file,
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
return file.getInputStream(entry);
}
}
}
@@ -118,6 +118,10 @@ public class RestoreDownloadPreference extends TaskPreference {
List<RestoreItem> restoreItemList = new ArrayList<>();
UniFile[] files = dir.listFiles();
if (files == null) {
return null;
}
for (UniFile file: files) {
RestoreItem restoreItem = getRestoreItem(file);
if (null != restoreItem) {
@@ -30,6 +30,7 @@ import android.util.AttributeSet;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.preference.DialogPreference;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.IntIdGenerator;
public abstract class TaskPreference extends DialogPreference {
@@ -62,7 +63,7 @@ public abstract class TaskPreference extends DialogPreference {
mTask = onCreateTask();
mTask.setPreference(this);
mTaskId = ((EhApplication) getContext().getApplicationContext()).putGlobalStuff(mTask);
mTask.execute();
mTask.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -53,6 +53,7 @@ import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
@@ -669,7 +670,7 @@ public final class SpiderQueen implements Runnable {
writeSpiderInfoToLocal(spiderInfo);
return null;
}
}.execute();
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -41,9 +41,14 @@ import com.hippo.ehviewer.download.DownloadService;
import com.hippo.ehviewer.ui.scene.BaseScene;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.collect.LongList;
import java.util.ArrayList;
import java.util.Collections;
import org.json.JSONException;
import org.json.JSONObject;
@@ -64,7 +69,7 @@ public final class CommonOperations {
public static void checkUpdate(Activity activity, boolean feedback) {
if (!UPDATING) {
UPDATING = true;
new UpdateTask(activity, feedback).execute();
new UpdateTask(activity, feedback).executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -80,23 +85,39 @@ public final class CommonOperations {
mFeedback = feedback;
}
private JSONObject fetchUpdateInfo(String url) throws IOException, JSONException {
Log.d(TAG, url);
Request request = new Request.Builder().url(url).build();
Response response = mHttpClient.newCall(request).execute();
return new JSONObject(response.body().string());
}
@Override
protected JSONObject doInBackground(Void... params) {
String url;
if (Settings.getBetaUpdateChannel()) {
url = "http://www.ehviewer.com/update_beta.json";
} else {
url = "http://www.ehviewer.com/update.json";
}
try {
String url;
return fetchUpdateInfo(url);
} catch (Throwable e1) {
ExceptionUtils.throwIfFatal(e1);
if (Settings.getBetaUpdateChannel()) {
url = "http://www.ehviewer.com/update_beta.json";
url = "https://raw.githubusercontent.com/seven332/EhViewer/api/update_beta.json";
} else {
url = "http://www.ehviewer.com/update.json";
url = "https://raw.githubusercontent.com/seven332/EhViewer/api/update.json";
}
try {
return fetchUpdateInfo(url);
} catch (Throwable e2) {
ExceptionUtils.throwIfFatal(e2);
return null;
}
Log.d(TAG, url);
Request request = new Request.Builder().url(url).build();
Response response = mHttpClient.newCall(request).execute();
return new JSONObject(response.body().string());
} catch (IOException e) {
return null;
} catch (JSONException e) {
return null;
}
}
@@ -153,7 +174,8 @@ public final class CommonOperations {
size = FileUtils.humanReadableByteCount(jo.getLong("size"), false);
info = Html.fromHtml(jo.getString("info"));
url = jo.getString("url");
} catch (PackageManager.NameNotFoundException | JSONException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return;
}
@@ -263,11 +285,37 @@ public final class CommonOperations {
}
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
startDownload(activity, Collections.singletonList(galleryInfo), forceDefault);
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final List<GalleryInfo> galleryInfos, boolean forceDefault) {
final DownloadManager dm = EhApplication.getDownloadManager(activity);
boolean justStart = forceDefault || dm.containDownloadInfo(galleryInfo.gid);
LongList toStart = new LongList();
List<GalleryInfo> toAdd = new ArrayList<>();
for (GalleryInfo gi : galleryInfos) {
if (dm.containDownloadInfo(gi.gid)) {
toStart.add(gi.gid);
} else {
toAdd.add(gi);
}
}
if (!toStart.isEmpty()) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START_RANGE);
intent.putExtra(DownloadService.KEY_GID_LIST, toStart);
activity.startService(intent);
}
if (toAdd.isEmpty()) {
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
return;
}
boolean justStart = forceDefault;
String label = null;
// Get default download label
if (!justStart && Settings.getHasDefaultDownloadLabel()) {
@@ -281,12 +329,14 @@ public final class CommonOperations {
}
if (justStart) {
// Already in download list or get default label
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, galleryInfo);
activity.startService(intent);
// Got default label
for (GalleryInfo gi : toAdd) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
activity.startService(intent);
}
// Notify
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
} else {
@@ -312,11 +362,13 @@ public final class CommonOperations {
}
}
// Start download
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, galleryInfo);
activity.startService(intent);
for (GalleryInfo gi : toAdd) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
activity.startService(intent);
}
// Save settings
if (builder.isChecked()) {
Settings.putHasDefaultDownloadLabel(true);
@@ -66,6 +66,7 @@ import com.hippo.glgallery.GalleryView;
import com.hippo.glgallery.SimpleAdapter;
import com.hippo.glview.view.GLRootView;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
import com.hippo.yorozuya.AnimationUtils;
@@ -429,13 +430,15 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mSystemUiHelper != null) {
if (mShowSystemUi) {
mSystemUiHelper.show();
} else {
mSystemUiHelper.hide();
SimpleHandler.getInstance().postDelayed(() -> {
if (hasFocus && mSystemUiHelper != null) {
if (mShowSystemUi) {
mSystemUiHelper.show();
} else {
mSystemUiHelper.hide();
}
}
}
}, 300);
}
@Override
@@ -780,6 +783,10 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
@Override
public void onClick(DialogInterface dialog, int which) {
if (mGalleryView == null) {
return;
}
int screenRotation = mScreenRotation.getSelectedItemPosition();
int layoutMode = GalleryView.sanitizeLayoutMode(mReadingDirection.getSelectedItemPosition());
int scaleMode = GalleryView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
@@ -824,11 +831,9 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
break;
}
setRequestedOrientation(orientation);
if (mGalleryView != null) {
mGalleryView.setLayoutMode(layoutMode);
mGalleryView.setScaleMode(scaleMode);
mGalleryView.setStartPosition(startPosition);
}
mGalleryView.setLayoutMode(layoutMode);
mGalleryView.setScaleMode(scaleMode);
mGalleryView.setStartPosition(startPosition);
if (keepScreenOn) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
@@ -895,7 +900,13 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType(mimeType);
startActivity(Intent.createChooser(intent, getString(R.string.share_image)));
try {
startActivity(Intent.createChooser(intent, getString(R.string.share_image)));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(this, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
private void saveImage(int page) {
@@ -940,7 +951,12 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TITLE, filename);
startActivityForResult(intent, WRITE_REQUEST_CODE);
try {
startActivityForResult(intent, WRITE_REQUEST_CODE);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(this, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
@Override
@@ -48,6 +48,7 @@ import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhTagDatabase;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
@@ -251,7 +252,11 @@ public final class MainActivity extends StageActivity
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
Announcer announcer = EhUrlOpener.parseUrl(intent.getData().toString());
Uri uri = intent.getData();
if (uri == null) {
return false;
}
Announcer announcer = EhUrlOpener.parseUrl(uri.toString());
if (announcer != null) {
startScene(processAnnouncer(announcer));
return true;
@@ -358,6 +363,8 @@ public final class MainActivity extends StageActivity
} else {
onRestore(savedInstanceState);
}
EhTagDatabase.update();
}
private String getThemeText() {
@@ -622,6 +629,20 @@ public final class MainActivity extends StageActivity
}
}
public void setDrawerGestureBlocker(DrawerLayout.GestureBlocker gestureBlocker) {
if (mDrawerLayout != null) {
mDrawerLayout.setGestureBlocker(gestureBlocker);
}
}
public boolean isDrawersVisible() {
if (mDrawerLayout != null) {
return mDrawerLayout.isDrawersVisible();
} else {
return false;
}
}
public void setNavCheckedItem(@IdRes int resId) {
mNavCheckedItem = resId;
if (mNavView != null) {
@@ -643,7 +664,7 @@ public final class MainActivity extends StageActivity
public void showTip(CharSequence message, int length) {
if (null != mDrawerLayout) {
Snackbar.make(mDrawerLayout, message,
length == BaseScene.LENGTH_LONG ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
length == BaseScene.LENGTH_LONG ? 5000 : 3000).show();
} else {
Toast.makeText(this, message,
length == BaseScene.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
@@ -17,7 +17,6 @@
package com.hippo.ehviewer.ui.fragment;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
@@ -28,12 +27,12 @@ import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.DirPickerActivity;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
public class DownloadFragment extends PreferenceFragment implements
Preference.OnPreferenceChangeListener,
@@ -145,7 +144,8 @@ public class DownloadFragment extends PreferenceFragment implements
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_DIR_L);
} catch (ActivityNotFoundException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(getActivity(), R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
@@ -24,6 +24,7 @@ import android.preference.PreferenceFragment;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhTagDatabase;
public class EhFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener {
@@ -39,6 +40,7 @@ public class EhFragment extends PreferenceFragment
Preference listMode = findPreference(Settings.KEY_LIST_MODE);
Preference detailSize = findPreference(Settings.KEY_DETAIL_SIZE);
Preference thumbSize = findPreference(Settings.KEY_THUMB_SIZE);
Preference showTagTranslations = findPreference(Settings.KEY_SHOW_TAG_TRANSLATIONS);
theme.setOnPreferenceChangeListener(this);
applyNavBarThemeColor.setOnPreferenceChangeListener(this);
@@ -46,10 +48,15 @@ public class EhFragment extends PreferenceFragment
listMode.setOnPreferenceChangeListener(this);
detailSize.setOnPreferenceChangeListener(this);
thumbSize.setOnPreferenceChangeListener(this);
showTagTranslations.setOnPreferenceChangeListener(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
getPreferenceScreen().removePreference(applyNavBarThemeColor);
}
if (!EhTagDatabase.isPossible()) {
getPreferenceScreen().removePreference(showTagTranslations);
}
}
@Override
@@ -71,6 +78,10 @@ public class EhFragment extends PreferenceFragment
getActivity().setResult(Activity.RESULT_OK);
} else if (Settings.KEY_THUMB_SIZE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
} else if (Settings.KEY_SHOW_TAG_TRANSLATIONS.equals(key)) {
if (Boolean.TRUE.equals(newValue)) {
EhTagDatabase.update();
}
}
return true;
}
@@ -26,13 +26,13 @@ import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.SparseArray;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.SceneFragment;
@@ -111,6 +111,22 @@ public abstract class BaseScene extends SceneFragment {
}
}
public void setDrawerGestureBlocker(DrawerLayout.GestureBlocker gestureBlocker) {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).setDrawerGestureBlocker(gestureBlocker);
}
}
public boolean isDrawersVisible() {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
return ((MainActivity) activity).isDrawersVisible();
} else {
return false;
}
}
/**
* @param resId 0 for clear
*/
@@ -84,6 +84,7 @@ import com.hippo.streampipe.InputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.util.ApiHelper;
import com.hippo.util.DrawableManager;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LoadImageView;
@@ -929,11 +930,13 @@ public class DownloadsScene extends ToolbarScene
@Override
protected Void doInBackground(UniFile... params) {
for (UniFile file: params) {
file.delete();
if (file != null) {
file.delete();
}
}
return null;
}
}.execute(files);
}.executeOnExecutor(IoThreadPoolExecutor.getInstance(), files);
}
private class DeleteDialogHelper implements DialogInterface.OnClickListener {
@@ -63,6 +63,7 @@ import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.parser.FavoritesParser;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.DrawerLifeCircle;
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
@@ -762,7 +763,18 @@ public class FavoritesScene extends BaseScene implements
}
switch (position) {
case 0: { // Delete
case 0: { // Download
Activity activity = getActivity2();
if (activity != null) {
CommonOperations.startDownload(getActivity2(), mModifyGiList, false);
}
mModifyGiList.clear();
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
mRecyclerView.outOfCustomChoiceMode();
}
break;
}
case 1: { // Delete
DeleteDialogHelper helper = new DeleteDialogHelper();
new AlertDialog.Builder(context)
.setTitle(R.string.delete_favorites_dialog_title)
@@ -772,7 +784,7 @@ public class FavoritesScene extends BaseScene implements
.show();
break;
}
case 1: { // Move
case 2: { // Move
MoveDialogHelper helper = new MoveDialogHelper();
// First is local favorite, the other 10 is cloud favorite
String[] array = new String[11];
@@ -27,6 +27,7 @@ import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@@ -505,6 +506,13 @@ public final class GalleryCommentsScene extends ToolbarScene
return;
}
if (Looper.myLooper() != Looper.getMainLooper()) {
// Some devices may run this block in non-UI thread.
// It might be a bug of Android OS.
// Check it here to avoid crash.
return;
}
mEditPanel.setVisibility(View.GONE);
((View) mFab).setVisibility(View.VISIBLE);
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
@@ -736,7 +744,7 @@ public final class GalleryCommentsScene extends ToolbarScene
@Override
public void onFailure(Exception e) {
showTip(getContent().getString(R.string.comment_failed) + "\n" + ExceptionUtils.getReadableString(e), LENGTH_SHORT);
showTip(getContent().getString(R.string.comment_failed) + "\n" + ExceptionUtils.getReadableString(e), LENGTH_LONG);
}
@Override
@@ -770,7 +778,7 @@ public final class GalleryCommentsScene extends ToolbarScene
@Override
public void onFailure(Exception e) {
showTip(R.string.vote_failed, LENGTH_SHORT);
showTip(R.string.vote_failed, LENGTH_LONG);
}
@Override
@@ -44,8 +44,10 @@ import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
@@ -56,6 +58,7 @@ import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.beerbelly.BeerBelly;
import com.hippo.drawable.RoundSideRectDrawable;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
@@ -66,6 +69,7 @@ import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhFilter;
import com.hippo.ehviewer.client.EhRequest;
import com.hippo.ehviewer.client.EhTagDatabase;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryComment;
@@ -424,6 +428,35 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
Context context = getContext2();
AssertUtils.assertNotNull(context);
View actionsScrollView = ViewUtils.$$(view, R.id.actions_scroll_view);
setDrawerGestureBlocker(new DrawerLayout.GestureBlocker() {
private void transformPointToViewLocal(int[] point, View child) {
ViewParent viewParent = child.getParent();
while (viewParent instanceof View) {
View view = (View) viewParent;
point[0] += view.getScrollX() - child.getLeft();
point[1] += view.getScrollY() - child.getTop();
if (view instanceof DrawerLayout) {
break;
}
child = view;
viewParent = child.getParent();
}
}
@Override
public boolean shouldBlockGesture(MotionEvent ev) {
int[] point = new int[] {(int) ev.getX(), (int) ev.getY()};
transformPointToViewLocal(point, actionsScrollView);
return !isDrawersVisible()
&& point[0] > 0 && point[0] < actionsScrollView.getWidth()
&& point[1] > 0 && point[1] < actionsScrollView.getHeight();
}
});
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_sad_pandroid);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
mTip.setCompoundDrawables(null, drawable, null, null);
@@ -545,6 +578,8 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
AssertUtils.assertNotNull(context);
EhApplication.getDownloadManager(context).removeDownloadInfoListener(this);
setDrawerGestureBlocker(null);
mTip = null;
mViewTransition = null;
@@ -834,6 +869,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mNoTags.setVisibility(View.GONE);
}
EhTagDatabase ehTags = Settings.getShowTagTranslations() ? EhTagDatabase.getInstance() : null;
int colorTag = AttrResources.getAttrColor(context, R.attr.tagBackgroundColor);
int colorName = AttrResources.getAttrColor(context, R.attr.tagGroupBackgroundColor);
for (GalleryTagGroup tg : tagGroups) {
@@ -841,18 +877,34 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
ll.setOrientation(LinearLayout.HORIZONTAL);
mTags.addView(ll);
String readableTagName = null;
if (ehTags != null) {
readableTagName = ehTags.getTranslation("n:" + tg.groupName);
}
TextView tgName = (TextView) inflater.inflate(R.layout.item_gallery_tag, ll, false);
ll.addView(tgName);
tgName.setText(tg.groupName);
tgName.setText(readableTagName != null ? readableTagName : tg.groupName);
tgName.setBackgroundDrawable(new RoundSideRectDrawable(colorName));
String prefix = EhTagDatabase.namespaceToPrefix(tg.groupName);
if (prefix == null) {
prefix = "";
}
AutoWrapLayout awl = new AutoWrapLayout(context);
ll.addView(awl, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
for (int j = 0, z = tg.size(); j < z; j++) {
TextView tag = (TextView) inflater.inflate(R.layout.item_gallery_tag, awl, false);
awl.addView(tag);
String tagStr = tg.getTagAt(j);
tag.setText(tagStr);
String readableTag = null;
if (ehTags != null) {
readableTag = ehTags.getTranslation(prefix + tagStr);
}
tag.setText(readableTag != null ? readableTag : tagStr);
tag.setBackgroundDrawable(new RoundSideRectDrawable(colorTag));
tag.setTag(R.id.tag, tg.groupName + ":" + tagStr);
tag.setOnClickListener(this);
@@ -1189,7 +1241,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
return;
}
if (mGalleryDetail.apiUid < 0) {
showTip(R.string.sign_in_first, LENGTH_SHORT);
showTip(R.string.sign_in_first, LENGTH_LONG);
return;
}
ArchiveListDialogHelper helper = new ArchiveListDialogHelper();
@@ -1204,7 +1256,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
return;
}
if (mGalleryDetail.apiUid < 0) {
showTip(R.string.sign_in_first, LENGTH_SHORT);
showTip(R.string.sign_in_first, LENGTH_LONG);
return;
}
RateDialogHelper helper = new RateDialogHelper();
@@ -1575,7 +1627,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
@Override
public void onFailure(Exception e) {
showTip(mAddOrRemove ? R.string.remove_from_favorite_failure :
R.string.add_to_favorite_failure, LENGTH_SHORT);
R.string.add_to_favorite_failure, LENGTH_LONG);
GalleryDetailScene scene = getScene();
if (scene != null) {
scene.onModifyFavoritesFailure(mAddOrRemove);
@@ -1610,9 +1662,9 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
@Override
public void onFailure(Exception e) {
if (e instanceof NoHAtHClientException) {
showTip(R.string.download_archive_failure_no_hath, LENGTH_SHORT);
showTip(R.string.download_archive_failure_no_hath, LENGTH_LONG);
} else {
showTip(R.string.download_archive_failure, LENGTH_SHORT);
showTip(R.string.download_archive_failure, LENGTH_LONG);
}
}
@@ -1811,7 +1863,13 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
r.allowScanningByMediaScanner();
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(r);
if (dm != null) {
try {
dm.enqueue(r);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
}
}
}
if (mDialog != null) {
@@ -1973,7 +2031,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
@Override
public void onFailure(Exception e) {
e.printStackTrace();
showTip(R.string.rate_failed, LENGTH_SHORT);
showTip(R.string.rate_failed, LENGTH_LONG);
}
@Override
@@ -655,14 +655,14 @@ public final class GalleryListScene extends BaseScene
// Can't add image search as quick search
if (ListUrlBuilder.MODE_IMAGE_SEARCH == urlBuilder.getMode()) {
showTip(R.string.image_search_not_quick_search, LENGTH_SHORT);
showTip(R.string.image_search_not_quick_search, LENGTH_LONG);
return;
}
// Check duplicate
for (QuickSearch q: list) {
if (urlBuilder.equalsQuickSearch(q)) {
showTip(getString(R.string.duplicate_quick_search, q.name), LENGTH_SHORT);
showTip(getString(R.string.duplicate_quick_search, q.name), LENGTH_LONG);
return;
}
}
@@ -1545,7 +1545,7 @@ public final class GalleryListScene extends BaseScene
@Override
public void onFailure(Exception e) {
showTip(R.string.add_to_favorite_failure, LENGTH_SHORT);
showTip(R.string.add_to_favorite_failure, LENGTH_LONG);
}
@Override
@@ -433,7 +433,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
mDialog = null;
}
} else {
showTip(R.string.error_out_of_range, LENGTH_SHORT);
showTip(R.string.error_out_of_range, LENGTH_LONG);
}
}
@@ -164,6 +164,9 @@ public class HistoryScene extends ToolbarScene
if (null != mLazyList) {
mLazyList.close();
mLazyList = null;
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
if (null != mRecyclerView) {
mRecyclerView.stopScroll();
@@ -429,7 +432,7 @@ public class HistoryScene extends ToolbarScene
HistoryInfo info = mLazyList.get(mPosition);
EhDB.deleteHistoryInfo(info);
updateLazyList();
mAdapter.notifyItemRemoved(mPosition);
mAdapter.notifyDataSetChanged();
updateView(true);
}
}
@@ -447,7 +450,7 @@ public class HistoryScene extends ToolbarScene
@Override
public void onFailure(Exception e) {
showTip(R.string.add_to_favorite_failure, LENGTH_SHORT);
showTip(R.string.add_to_favorite_failure, LENGTH_LONG);
}
@Override
@@ -24,7 +24,8 @@ import com.hippo.widget.DrawerView;
public class EhDrawerView extends DrawerView implements DrawerLayoutChild {
private int mFitPaddingTop;
private int mWindowPaddingTop;
private int mWindowPaddingBottom;
public EhDrawerView(Context context) {
super(context);
@@ -39,17 +40,18 @@ public class EhDrawerView extends DrawerView implements DrawerLayoutChild {
}
@Override
public void setFitPadding(int top, int bottom) {
mFitPaddingTop = top;
public void onGetWindowPadding(int top, int bottom) {
mWindowPaddingTop = top;
mWindowPaddingBottom = bottom;
}
@Override
public int getLayoutPaddingTop() {
return mFitPaddingTop;
public int getAdditionalTopMargin() {
return mWindowPaddingTop;
}
@Override
public int getLayoutPaddingBottom() {
return 0;
public int getAdditionalBottomMargin() {
return mWindowPaddingBottom;
}
}
@@ -30,7 +30,8 @@ public class EhNavigationView extends LinearLayout implements DrawerLayoutChild
private static final int SCRIM_COLOR = 0x44000000;
private static final boolean DRAW_SCRIM = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
private Paint mPaint;
private int mFitPaddingTop;
private int mWindowPaddingTop;
private int mWindowPaddingBottom;
public EhNavigationView(Context context) {
super(context);
@@ -57,27 +58,28 @@ public class EhNavigationView extends LinearLayout implements DrawerLayoutChild
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
if (DRAW_SCRIM && mFitPaddingTop > 0) {
if (DRAW_SCRIM && mWindowPaddingTop > 0) {
if (null == mPaint) {
mPaint = new Paint();
mPaint.setColor(SCRIM_COLOR);
}
canvas.drawRect(0, 0, getWidth(), mFitPaddingTop, mPaint);
canvas.drawRect(0, 0, getWidth(), mWindowPaddingTop, mPaint);
}
}
@Override
public void setFitPadding(int top, int bottom) {
mFitPaddingTop = top;
public void onGetWindowPadding(int top, int bottom) {
mWindowPaddingTop = top;
mWindowPaddingBottom = bottom;
}
@Override
public int getLayoutPaddingTop() {
public int getAdditionalTopMargin() {
return 0;
}
@Override
public int getLayoutPaddingBottom() {
return 0;
public int getAdditionalBottomMargin() {
return mWindowPaddingBottom;
}
}
@@ -24,7 +24,8 @@ import com.hippo.scene.StageLayout;
public class EhStageLayout extends StageLayout implements DrawerLayoutChild {
private int mFitPaddingTop;
private int mWindowPaddingTop;
private int mWindowPaddingBottom;
public EhStageLayout(Context context) {
super(context);
@@ -39,17 +40,18 @@ public class EhStageLayout extends StageLayout implements DrawerLayoutChild {
}
@Override
public void setFitPadding(int top, int bottom) {
mFitPaddingTop = top;
public void onGetWindowPadding(int top, int bottom) {
mWindowPaddingTop = top;
mWindowPaddingBottom = bottom;
}
@Override
public int getLayoutPaddingTop() {
return mFitPaddingTop;
public int getAdditionalTopMargin() {
return mWindowPaddingTop;
}
@Override
public int getLayoutPaddingBottom() {
return 0;
public int getAdditionalBottomMargin() {
return mWindowPaddingBottom;
}
}
@@ -0,0 +1,79 @@
/*
* Copyright 2019 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.ehviewer.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import com.hippo.ehviewer.R;
import com.hippo.widget.LoadImageView;
public class FixedThumb extends LoadImageView {
private float minAspect;
private float maxAspect;
public FixedThumb(Context context) {
super(context);
init(context, null, 0, 0);
}
public FixedThumb(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public FixedThumb(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle, 0);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedThumb, defStyleAttr, defStyleRes);
minAspect = a.getFloat(R.styleable.FixedThumb_minAspect, 0.0f);
maxAspect = a.getFloat(R.styleable.FixedThumb_maxAspect, 0.0f);
a.recycle();
}
public void setFix(float minAspect, float maxAspect) {
this.minAspect = minAspect;
this.maxAspect = maxAspect;
}
@Override
public void onPreSetImageDrawable(Drawable drawable, boolean isTarget) {
if (isTarget && drawable != null) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
if (width > 0 && height > 0) {
float aspect = (float) width / (float) height;
if (aspect < maxAspect && aspect > minAspect) {
setScaleType(ScaleType.CENTER_CROP);
return;
}
}
}
setScaleType(ScaleType.FIT_CENTER);
}
@Override
public void onPreSetImageResource(int resId, boolean isTarget) {
setScaleType(ScaleType.FIT_CENTER);
}
}
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.widget;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
@@ -69,19 +70,24 @@ public final class SearchDatabase {
}
sb.append(" ORDER BY ").append(COLUMN_DATE).append(" DESC")
.append(" LIMIT ").append(limit);
Cursor cursor = mDatabase.rawQuery(sb.toString(), null);
int queryIndex = cursor.getColumnIndex(COLUMN_QUERY);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String suggestion = cursor.getString(queryIndex);
if (!prefix.equals(suggestion)) {
queryList.add(suggestion);
try {
Cursor cursor = mDatabase.rawQuery(sb.toString(), null);
int queryIndex = cursor.getColumnIndex(COLUMN_QUERY);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String suggestion = cursor.getString(queryIndex);
if (!prefix.equals(suggestion)) {
queryList.add(suggestion);
}
cursor.moveToNext();
}
cursor.moveToNext();
}
cursor.close();
return queryList.toArray(new String[queryList.size()]);
} catch (SQLException e) {
return new String[0];
}
cursor.close();
return queryList.toArray(new String[queryList.size()]);
}
public void addQuery(final String query) {
@@ -22,6 +22,7 @@ import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.hippo.util.ExceptionUtils;
public class SearchEditText extends AppCompatEditText {
@@ -76,7 +77,14 @@ public class SearchEditText extends AppCompatEditText {
if (event.getAction() == MotionEvent.ACTION_UP && mListener != null) {
mListener.onClick();
}
return super.onTouchEvent(event);
try {
return super.onTouchEvent(event);
} catch (Throwable t) {
// Some devices crash here.
// I don't why.
ExceptionUtils.throwIfFatal(t);
return false;
}
}
public interface SearchEditTextListener {
@@ -23,11 +23,20 @@ import okhttp3.Request;
public class ChromeRequestBuilder extends Request.Builder {
private static final String CHROME_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36";
private static final String CHROME_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
private static final String CHROME_ACCEPT =
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
private static final String CHROME_ACCEPT_LANGUAGE =
"en-US,en;q=0.5";
public ChromeRequestBuilder(String url) throws MalformedURLException {
url(new URL(url));
addHeader("User-Agent", CHROME_USER_AGENT);
addHeader("Accept", CHROME_ACCEPT);
addHeader("Accept-Language", CHROME_ACCEPT_LANGUAGE);
}
}
@@ -22,8 +22,9 @@ import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Toast;
import com.hippo.ehviewer.R;
import com.hippo.util.ExceptionUtils;
public class ActivityPreference extends Preference {
@@ -68,6 +69,11 @@ public class ActivityPreference extends Preference {
Context context = getContext();
Intent intent = new Intent(context, mActivityClazz);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
try {
context.startActivity(intent);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(context, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
}
@@ -161,8 +161,10 @@ public abstract class StageActivity extends EhActivity {
if (savedInstanceState != null) {
mStageId = savedInstanceState.getInt(KEY_STAGE_ID, IntIdGenerator.INVALID_ID);
ArrayList<String> list = savedInstanceState.getStringArrayList(KEY_SCENE_TAG_LIST);
mSceneTagList.addAll(list);
mDelaySceneTagList.addAll(list);
if (list != null) {
mSceneTagList.addAll(list);
mDelaySceneTagList.addAll(list);
}
mIdGenerator.lazySet(savedInstanceState.getInt(KEY_NEXT_ID));
}
+12 -7
View File
@@ -713,11 +713,13 @@ class HtmlToSpannedConverter implements ContentHandler {
where, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
int c = getHtmlColor(f.mColor);
if (c != -1) {
try {
int c = getHtmlColor(f.mColor);
text.setSpan(new ForegroundColorSpan(c | 0xFF000000),
where, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (IllegalArgumentException e) {
// Ignore
}
}
}
@@ -906,16 +908,19 @@ class HtmlToSpannedConverter implements ContentHandler {
*/
@ColorInt
public static int getHtmlColor(@NonNull String colorString) {
if (colorString.charAt(0) == '#') {
if ((colorString.length() == 7 || colorString.length() == 9) && colorString.charAt(0) == '#') {
// Use a long to avoid rollovers on #ffXXXXXX
long color = Long.parseLong(colorString.substring(1), 16);
long color;
try {
color = Long.parseLong(colorString.substring(1), 16);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unknown color: " + colorString);
}
if (colorString.length() == 7) {
// Set the alpha value
color |= 0x00000000ff000000;
} else if (colorString.length() != 9) {
throw new IllegalArgumentException("Unknown color: " + colorString);
}
return (int)color;
return (int) color;
} else if (colorString.startsWith("rgb(") && colorString.endsWith(")")) {
String str = colorString.substring(4, colorString.length() - 1);
String[] colors = str.split("[\\s]*,[\\s]*");
@@ -19,7 +19,6 @@ package com.hippo.util;
import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
@@ -28,7 +27,6 @@ import android.support.annotation.Nullable;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.hippo.ehviewer.R;
public class AppHelper {
@@ -47,7 +45,8 @@ public class AppHelper {
try {
from.startActivity(i);
return true;
} catch (ActivityNotFoundException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(from, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
return false;
}
@@ -63,7 +62,8 @@ public class AppHelper {
try {
from.startActivity(chooser);
return true;
} catch (ActivityNotFoundException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(from, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
return false;
}
@@ -0,0 +1,90 @@
/*
* Copyright 2019 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.util;
import android.support.annotation.NonNull;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class IoThreadPoolExecutor extends ThreadPoolExecutor {
private final static ThreadPoolExecutor INSTANCE =
IoThreadPoolExecutor.newInstance(3, 32, 1L, TimeUnit.SECONDS,
new PriorityThreadFactory("IO",android.os.Process.THREAD_PRIORITY_BACKGROUND));
private IoThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
public static ThreadPoolExecutor getInstance() {
return INSTANCE;
}
private static ThreadPoolExecutor newInstance(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
ThreadFactory threadFactory
) {
ThreadQueue queue = new ThreadQueue();
PutRunnableBackHandler handler = new PutRunnableBackHandler();
IoThreadPoolExecutor executor = new IoThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime, unit, queue, threadFactory, handler);
queue.setThreadPoolExecutor(executor);
return executor;
}
private static class ThreadQueue extends LinkedBlockingQueue<Runnable> {
private ThreadPoolExecutor executor;
void setThreadPoolExecutor(ThreadPoolExecutor executor) {
this.executor = executor;
}
@Override
public boolean offer(@NonNull Runnable o) {
int allWorkingThreads = executor.getActiveCount() + super.size();
return allWorkingThreads < executor.getPoolSize() && super.offer(o);
}
}
public static class PutRunnableBackHandler implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
}
}
}
@@ -56,10 +56,7 @@ public class NaturalComparator implements Comparator<String> {
int result;
if (isDigit(data1) && isDigit(data2)) {
result = Long.compare(Long.valueOf(data1), Long.valueOf(data2));
if (result == 0) {
result = -Integer.compare(data1.length(), data2.length());
}
result = compareNumberString(data1, data2);
} else {
result = data1.compareToIgnoreCase(data2);
}
@@ -111,4 +108,45 @@ public class NaturalComparator implements Comparator<String> {
}
return index;
}
private static String removeLeadingZero(String s) {
if (s.length() < 1) {
return s;
}
// At least keep the last number
for (int i = 0, n = s.length() - 1; i < n; i++) {
if (s.charAt(i) != '0') {
return s.substring(i);
}
}
return s.substring(s.length() - 1);
}
private static int compareNumberString(String s1, String s2) {
String p1 = removeLeadingZero(s1);
String p2 = removeLeadingZero(s2);
int l1 = p1.length();
int l2 = p2.length();
if (l1 > l2) {
return 1;
} else if (l1 < l2) {
return -1;
} else {
for (int i = 0; i < l1; i++) {
char c1 = p1.charAt(i);
char c2 = p2.charAt(i);
if (c1 > c2) {
return 1;
} else if (c1 < c2) {
return -1;
}
}
}
return -Integer.compare(s1.length(), s2.length());
}
}
@@ -44,18 +44,28 @@ public class PermissionRequester {
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity,
new String[]{permission},
requestCode);
requestPermissions(activity, new String[]{permission}, requestCode);
}
}).setNegativeButton(android.R.string.cancel, null)
.show();
} else {
ActivityCompat.requestPermissions(activity,
new String[]{permission},
requestCode);
return requestPermissions(activity, new String[]{permission}, requestCode);
}
return false;
}
private static boolean requestPermissions(
final Activity activity,
final String[] permissions,
int requestCode
) {
try {
ActivityCompat.requestPermissions(activity, permissions, requestCode);
return true;
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
return false;
}
}
}
@@ -20,11 +20,14 @@ import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.URLSpan;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class TextUrl {
public static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Pattern URL_PATTERN = Pattern.compile("(http|https)://[a-z0-9A-Z%-]+(\\.[a-z0-9A-Z%-]+)+(:\\d{1,5})?(/[a-zA-Z0-9-_~:#@!&',;=%/\\*\\.\\?\\+\\$\\[\\]\\(\\)]+)?/?");
public static CharSequence handleTextUrl(CharSequence content) {
@@ -898,12 +898,13 @@ public class ContentLayout extends FrameLayout {
mTipView.setText(bundle.getString(KEY_TIP));
mSavedDataId = bundle.getInt(KEY_DATA);
ArrayList<E> newData = null;
EhApplication app = (EhApplication) getContext().getApplicationContext();
if (mSavedDataId != IntIdGenerator.INVALID_ID) {
ArrayList<E> data = (ArrayList<E>) app.removeGlobalStuff(mSavedDataId);
newData = (ArrayList<E>) app.removeGlobalStuff(mSavedDataId);
mSavedDataId = IntIdGenerator.INVALID_ID;
if (data != null) {
mData = data;
if (newData != null) {
mData = newData;
}
}
@@ -912,6 +913,17 @@ public class ContentLayout extends FrameLayout {
mStartPage = bundle.getInt(KEY_START_PAGE);
mEndPage = bundle.getInt(KEY_END_PAGE);
mPages = bundle.getInt(KEY_PAGES);
notifyDataSetChanged();
if (newData == null) {
mPageDivider.clear();
mStartPage = 0;
mEndPage = 0;
mPages = 0;
firstRefresh();
}
return bundle.getParcelable(KEY_SUPER);
} else {
return state;
@@ -17,28 +17,56 @@
package com.hippo.widget;
import android.content.Context;
import android.os.Build;
import android.support.design.widget.TextInputEditText;
import android.util.AttributeSet;
import android.widget.TextView;
import com.hippo.util.ExceptionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// Avoid crash on some Meizu devices
// https://github.com/android-in-china/Compatibility/issues/11
// https://stackoverflow.com/questions/51891415/nullpointerexception-on-meizu-devices-in-editor-updatecursorpositionmz/52001305
public class HackyTextInputEditText extends TextInputEditText {
private static final boolean HAS_METHOD_UPDATE_CURSOR_POSITION_MZ;
private static final Field FIELD_M_HINT;
static {
boolean hasMethodUpdateCursorPositionMz = false;
try {
Class<?> clazz = ClassLoader.getSystemClassLoader().loadClass("android.widget.Editor");
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if ("updateCursorPositionMz".equals(method.getName())) {
hasMethodUpdateCursorPositionMz = true;
}
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
}
Field fieldMHint = null;
if (hasMethodUpdateCursorPositionMz) {
try {
fieldMHint = TextView.class.getDeclaredField("mHint");
fieldMHint.setAccessible(true);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
}
}
HAS_METHOD_UPDATE_CURSOR_POSITION_MZ = hasMethodUpdateCursorPositionMz;
FIELD_M_HINT = fieldMHint;
}
public HackyTextInputEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public CharSequence getHint() {
boolean isMeizu = Build.MANUFACTURER.toLowerCase().contains("meizu");
boolean isPreP = Build.VERSION.SDK_INT < Build.VERSION_CODES.P;
if (isMeizu && isPreP) {
if (HAS_METHOD_UPDATE_CURSOR_POSITION_MZ && FIELD_M_HINT != null) {
try {
return getSuperHint();
} catch (Throwable e) {
@@ -50,9 +78,7 @@ public class HackyTextInputEditText extends TextInputEditText {
}
}
public CharSequence getSuperHint() throws NoSuchFieldException, IllegalAccessException {
Field field = TextView.class.getDeclaredField("mHint");
field.setAccessible(true);
return (CharSequence) field.get(this);
private CharSequence getSuperHint() throws IllegalAccessException {
return (CharSequence) FIELD_M_HINT.get(this);
}
}
@@ -239,11 +239,13 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Image
public void load(Drawable drawable) {
unload();
onPreSetImageDrawable(drawable, true);
setImageDrawable(drawable);
}
public void load(@DrawableRes int id) {
unload();
onPreSetImageResource(id, true);
setImageResource(id);
}
@@ -290,6 +292,7 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Image
drawable = new PreciselyClipDrawable(drawable, mOffsetX, mOffsetY, mClipWidth, mClipHeight);
}
onPreSetImageDrawable(drawable, true);
if ((source == Conaco.SOURCE_DISK || source == Conaco.SOURCE_NETWORK) && isShown()) {
Drawable[] layers = new Drawable[2];
layers[0] = new ColorDrawable(Color.TRANSPARENT);
@@ -308,7 +311,9 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Image
public void onFailure() {
mFailed = true;
clearDrawable();
setImageDrawable(DrawableManager.getVectorDrawable(getContext(), R.drawable.image_failed));
Drawable drawable = DrawableManager.getVectorDrawable(getContext(), R.drawable.image_failed);
onPreSetImageDrawable(drawable, true);
setImageDrawable(drawable);
if (mRetryType == RETRY_TYPE_CLICK) {
setOnClickListener(this);
} else if (mRetryType == RETRY_TYPE_LONG_CLICK) {
@@ -362,4 +367,8 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Image
load(mKey, mUrl, mContainer, true);
return true;
}
public void onPreSetImageDrawable(Drawable drawable, boolean isTarget) { }
public void onPreSetImageResource(int resId, boolean isTarget) { }
}
@@ -1,99 +0,0 @@
/*
* Copyright 2018 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 okio;
import static okio.Util.checkOffsetAndCount;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
public class UniRandomAccessFileStore implements Store {
private UniRandomAccessFile file;
private Timeout timeout;
public UniRandomAccessFileStore(UniRandomAccessFile file) {
this(file, new Timeout());
}
public UniRandomAccessFileStore(UniRandomAccessFile file, Timeout timeout) {
this.file = file;
this.timeout = timeout;
}
@Override
public void seek(long position) throws IOException {
file.seek(position);
}
@Override
public long tell() throws IOException {
return file.getFilePointer();
}
@Override
public long size() throws IOException {
return file.length();
}
@Override
public long read(Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount);
if (byteCount == 0) return 0;
timeout.throwIfReached();
Segment tail = sink.writableSegment(1);
int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit);
int bytesRead = file.read(tail.data, tail.limit, maxToCopy);
if (bytesRead == -1) return -1;
tail.limit += bytesRead;
sink.size += bytesRead;
return bytesRead;
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
checkOffsetAndCount(source.size, 0, byteCount);
while (byteCount > 0) {
timeout.throwIfReached();
Segment head = source.head;
int toCopy = (int) Math.min(byteCount, head.limit - head.pos);
file.write(head.data, head.pos, toCopy);
head.pos += toCopy;
byteCount -= toCopy;
source.size -= toCopy;
if (head.pos == head.limit) {
source.head = head.pop();
SegmentPool.recycle(head);
}
}
}
@Override
public void flush() { }
@Override
public Timeout timeout() {
return timeout;
}
@Override
public void close() throws IOException {
file.close();
}
}
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2019 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.
-->
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/primary_drawable_dark"
android:pathData="@string/pd_download"/>
</vector>
@@ -35,13 +35,13 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp">
android:layout_marginTop="16dp"
android:hint="@string/filter_text">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/filter_text"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
+4 -4
View File
@@ -27,13 +27,13 @@
<android.support.design.widget.TextInputLayout
android:id="@+id/host_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:hint="@string/hosts_host">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hosts_host"
android:inputType="text"/>
</android.support.design.widget.TextInputLayout>
@@ -41,13 +41,13 @@
<android.support.design.widget.TextInputLayout
android:id="@+id/ip_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:hint="@string/hosts_ip">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hosts_ip"
android:inputType="text"/>
</android.support.design.widget.TextInputLayout>
@@ -25,14 +25,14 @@
android:paddingBottom="@dimen/keyline_margin">
<HorizontalScrollView
android:id="@+id/actions_scroll_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingLeft="@dimen/keyline_margin"
android:paddingRight="@dimen/keyline_margin"
android:clipToPadding="false"
android:scrollbars="none"
android:overScrollMode="never">
android:scrollbars="none">
<LinearLayout
android:layout_width="wrap_content"
+5 -2
View File
@@ -27,10 +27,13 @@
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.hippo.widget.LoadImageView
<com.hippo.ehviewer.widget.FixedThumb
android:id="@+id/thumb"
android:layout_width="@dimen/gallery_list_thumb_width"
android:layout_height="@dimen/gallery_list_thumb_height"/>
android:layout_height="@dimen/gallery_list_thumb_height"
app:retryType="longClick"
app:minAspect="0.333"
app:maxAspect="1.333"/>
<TextView
android:id="@+id/title"
@@ -26,11 +26,13 @@
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.hippo.widget.LoadImageView
<com.hippo.ehviewer.widget.FixedThumb
android:id="@+id/thumb"
android:layout_width="@dimen/gallery_list_thumb_width"
android:layout_height="@dimen/gallery_list_thumb_height"
app:retryType="click"/>
app:retryType="click"
app:minAspect="0.333"
app:maxAspect="1.333"/>
<TextView
android:id="@+id/title"
@@ -21,13 +21,15 @@
android:layout_height="wrap_content"
android:orientation="vertical">
<com.hippo.widget.LoadImageView
<com.hippo.ehviewer.widget.FixedThumb
xmlns:auto="http://schemas.android.com/apk/res-auto"
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
auto:aspect="0.667"
auto:retryType="longClick"/>
auto:retryType="longClick"
auto:minAspect="0.5"
auto:maxAspect="0.8"/>
<TextView
android:id="@+id/text"
@@ -33,13 +33,13 @@
<android.support.design.widget.TextInputLayout
android:id="@+id/ip_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:hint="@string/ip">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/ip"
android:inputType="text"/>
</android.support.design.widget.TextInputLayout>
@@ -47,13 +47,13 @@
<android.support.design.widget.TextInputLayout
android:id="@+id/port_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:hint="@string/port">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/port"
android:inputType="numberDecimal"/>
</android.support.design.widget.TextInputLayout>
@@ -61,13 +61,13 @@
<android.support.design.widget.TextInputLayout
android:id="@+id/passkey_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
android:hint="@string/Passkey">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/passkey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/Passkey"
android:inputType="text"/>
</android.support.design.widget.TextInputLayout>
@@ -65,13 +65,13 @@
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/keyline_margin"
android:minWidth="@dimen/single_max_width">
android:minWidth="@dimen/single_max_width"
android:hint="ipb_member_id">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/ipb_member_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ipb_member_id"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLines="1"
@@ -85,13 +85,13 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width">
android:minWidth="@dimen/single_max_width"
android:hint="ipb_pass_hash">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/ipb_pass_hash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ipb_pass_hash"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLines="1"
@@ -105,13 +105,13 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width">
android:minWidth="@dimen/single_max_width"
android:hint="igneous">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/igneous"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="igneous"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
@@ -44,6 +44,13 @@
android:paddingRight="@dimen/corner_fab_margin"
android:paddingBottom="@dimen/corner_fab_margin">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_download_dark_x24"
app:backgroundTint="?attr/widgetColorThemeAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
+22 -22
View File
@@ -46,13 +46,13 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width">
android:minWidth="@dimen/single_max_width"
android:hint="@string/username">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/username"
android:imeOptions="actionNext"
android:inputType="text"
android:maxLines="1"
@@ -66,13 +66,13 @@
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width"
android:hint="@string/password"
app:passwordToggleEnabled="true">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:imeOptions="actionNext"
android:inputType="textPassword"
android:maxLines="1"
@@ -81,31 +81,31 @@
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/recaptcha_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width">
android:id="@+id/recaptcha_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width"
android:hint="@string/recaptcha">
<com.hippo.widget.HackyTextInputEditText
android:id="@+id/recaptcha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/recaptcha"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"/>
android:id="@+id/recaptcha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<com.hippo.ehviewer.widget.RecaptchaView
android:id="@+id/recaptcha_image"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width"
android:scaleType="fitCenter"/>
android:id="@+id/recaptcha_image"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:minWidth="@dimen/single_max_width"
android:scaleType="fitCenter"/>
<android.support.v4.widget.Space
android:layout_width="wrap_content"
@@ -433,6 +433,8 @@
<string name="settings_eh_show_jpn_title_summary_off">显示默认标题。一般是英文标题</string>
<string name="settings_eh_show_gallery_pages">显示画廊页数</string>
<string name="settings_eh_show_gallery_pages_summary">在画廊列表中显示页数。这会使获取画廊列表花费更多时间</string>
<string name="settings_eh_show_tag_translations">显示标签翻译</string>
<string name="settings_eh_show_tag_translations_summary">显示翻译后的标签而非原始文字(需花费时间来下载数据文件)</string>
<string name="settings_eh_filter">过滤</string>
<string name="settings_eh_filter_summary">过滤标题,上传者,标签和标签组</string>
<string name="settings_eh_cellular_network_warning">移动网络警告</string>
@@ -432,6 +432,8 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示默認標題。一般是英文標題</string>
<string name="settings_eh_show_gallery_pages">顯示畫廊頁數</string>
<string name="settings_eh_show_gallery_pages_summary">在畫廊列表中顯示頁數。這會使獲取畫廊列表花費更多時間</string>
<string name="settings_eh_show_tag_translations">顯示標籤翻譯</string>
<string name="settings_eh_show_tag_translations_summary">顯示翻譯後的標籤而非原始文字(需花費時間來下載數據文件)</string>
<string name="settings_eh_filter">過濾</string>
<string name="settings_eh_filter_summary">過濾標題,上傳者,標籤和標籤組</string>
<string name="settings_eh_cellular_network_warning">移動網絡警告</string>
@@ -432,6 +432,8 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示預設的標題。通常是英文的</string>
<string name="settings_eh_show_gallery_pages">顯示圖庫頁數</string>
<string name="settings_eh_show_gallery_pages_summary">在圖庫列表中顯示頁數。這會使取得圖庫列表時間增加</string>
<string name="settings_eh_show_tag_translations">顯示標籤翻譯</string>
<string name="settings_eh_show_tag_translations_summary">顯示翻譯後的標籤而非原始文字(需花費時間來下載資料檔案)</string>
<string name="settings_eh_filter">篩選</string>
<string name="settings_eh_filter_summary">篩選標題,上傳者,標籤和標籤命名空間</string>
<string name="settings_eh_cellular_network_warning">行動數據警告</string>
+5
View File
@@ -92,6 +92,11 @@
</attr>
</declare-styleable>
<declare-styleable name="FixedThumb">
<attr name="minAspect" format="float"/>
<attr name="maxAspect" format="float"/>
</declare-styleable>
<declare-styleable name="CheckTextView">
<attr name="maskColor" format="color"/>
</declare-styleable>
+2
View File
@@ -476,6 +476,8 @@
<string name="settings_eh_show_jpn_title_summary_off">Show default titles, which are usually in English.</string>
<string name="settings_eh_show_gallery_pages">Show gallery pages</string>
<string name="settings_eh_show_gallery_pages_summary">Display the number of pages in the gallery list. It takes more time to load the gallery list</string>
<string name="settings_eh_show_tag_translations">Show tag translations</string>
<string name="settings_eh_show_tag_translations_summary">Show tag translations instead of the original text (It takes time to download the data file)</string>
<string name="settings_eh_filter">Filter</string>
<string name="settings_eh_filter_summary">Filter by title, uploader, tag and tag namespace</string>
<string name="settings_eh_cellular_network_warning">Cellular network warning</string>
+6
View File
@@ -106,6 +106,12 @@
android:summary="@string/settings_eh_show_gallery_pages_summary"
android:defaultValue="false"/>
<com.hippo.preference.SwitchPreference
android:key="show_tag_translations"
android:title="@string/settings_eh_show_tag_translations"
android:summary="@string/settings_eh_show_tag_translations_summary"
android:defaultValue="false"/>
<com.hippo.preference.ActivityPreference
android:key="filter"
android:title="@string/settings_eh_filter"
@@ -0,0 +1,55 @@
/*
* Copyright 2019 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.ehviewer.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.io.InputStream;
import okio.BufferedSource;
import okio.Okio;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class EhTagDatabaseTest {
@Test
public void readTheList() throws IOException {
InputStream resource = EhTagDatabaseTest.class.getResourceAsStream("EhTagDatabaseTest");
if (resource == null) return;
EhTagDatabase db;
try (BufferedSource source = Okio.buffer(Okio.source(resource))) {
db = new EhTagDatabase("EhTagDatabaseTest", source);
}
assertEquals("a", db.getTranslation("1"));
assertEquals("ab", db.getTranslation("12"));
assertEquals("abc", db.getTranslation("123"));
assertEquals("abcd", db.getTranslation("1234"));
assertEquals("1", db.getTranslation("a"));
assertEquals("12", db.getTranslation("ab"));
assertEquals("123", db.getTranslation("abc"));
assertEquals("1234", db.getTranslation("abcd"));
assertNull(db.getTranslation("21"));
}
}
@@ -43,6 +43,7 @@ public class GalleryDetailUrlParserTest {
{ "530350/8b3c7e4a21", false, false, 530350, "8b3c7e4a21" },
{ "g/530350/8b3c7e4a21", false, false, 530350, "8b3c7e4a21" },
{ "530350b/8b3c7e4a21", false, true, 0, null },
{ "530350/8b3c7e4a211", false, true, 0, null },
});
}
@@ -54,6 +54,19 @@ public class NaturalComparatorTest {
assertOrder(null, "1");
}
@Test
public void testBigNumber() {
assertOrder("1", "22222222222222222222222222222222222222222222222222222222222222222222222");
}
@Test
public void testLeadingZero() {
assertOrder("000000000000000001", "1");
assertOrder("000000000000000001", "0001");
assertOrder("00000000000000000", "0");
assertOrder("00000000000000000", "000");
}
private void assertOrder(String s1, String s2) {
NaturalComparator comparator = new NaturalComparator();
assertTrue(comparator.compare(s1, s2) < 0);
+1 -1
View File
@@ -8,7 +8,7 @@ buildscript {
maven { url "https://jitpack.io" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'
classpath 'io.fabric.tools:gradle:1.26.1'
classpath 'com.github.seven332:android-chinese-string-gradle-plugin:0.1.0'
+6 -6
View File
@@ -1,6 +1,6 @@
#Sat Oct 06 17:54:20 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
#Wed Jan 16 18:10:40 CST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-all.zip