Compare commits

...
110 Commits
Author SHA1 Message Date
seven332 d1cac3c1ac Merge branch 'axlecho-master' into dict 2016-04-14 20:49:03 +08:00
seven332 fbeaf3d5ea Add anr watch dog 2016-04-14 19:10:38 +08:00
seven332 b4d8168457 Bump gradle tool version 2016-04-14 14:50:23 +08:00
seven332 9561fcf662 requestLayout when set different-size ImageTexture in ImageView 2016-04-14 02:40:25 +08:00
seven332 453a56aa23 Use hotspot and ripple library 2016-04-14 00:58:38 +08:00
seven332 df108f9678 Adjust build instruction for Linux 2016-04-13 14:04:26 +08:00
seven332 a835ca9547 Remove some @TargetApi 2016-04-13 01:54:45 +08:00
seven332 3f4cc46bc1 Do not show animation for image has no valid rect 2016-04-12 01:09:13 +08:00
seven332 27bc38ae8b Fix gif delay calculation 2016-04-12 00:55:36 +08:00
seven332 fd1aca48d6 Update UniFile library 2016-04-12 00:22:44 +08:00
seven332 adbb1f11a5 Use SystemClock.currentThreadTimeMillis to calculate gif delay 2016-04-12 00:21:58 +08:00
seven332 4b8e46d220 Use drawerLayout library 2016-04-11 15:36:00 +08:00
seven332 1c45c4b042 Add thumb resolution option 2016-04-11 14:28:01 +08:00
seven332 d33e3c27fc Rename image_size to image_resolution 2016-04-11 13:59:35 +08:00
seven332 189a95e49c Use RefreshLayout from jitpack 2016-04-11 00:05:17 +08:00
seven332 4e3717fa69 Avoid write null in SpiderInfo 2016-04-10 15:58:41 +08:00
seven332 97d51b1fc3 Start home page when can't recognize the intent 2016-04-10 15:41:17 +08:00
seven332 ba5a554ca8 Use unifile library for jitpack 2016-04-10 15:22:48 +08:00
seven332 b4095449c1 Fix mDownloadingDelay NullPointerException 2016-04-09 22:36:20 +08:00
seven332 05f9ce59f3 Update giflib to 5.1.4 2016-04-09 21:42:50 +08:00
seven332 793dca3674 Set APP_PLATFORM to android-15 2016-04-09 21:42:23 +08:00
seven332 e10172c09c Hide ime in go to dialog 2016-04-09 20:41:52 +08:00
seven332 2d65b71fff Rename ActivityHelper to AppHelper 2016-04-09 20:35:57 +08:00
seven332 7693275967 Use card for gallery thumb 2016-04-09 18:40:31 +08:00
seven332 9d4eadffac Add up react to SnackBar 2016-04-09 16:52:27 +08:00
seven332 1bf826a923 Clean up 2016-04-09 13:44:12 +08:00
seven332 4866e963de 1.0.6 2016-04-09 02:01:02 +08:00
seven332 2b15c8f620 Use clipRect instead of clipPath in SearchBar 2016-04-09 01:54:47 +08:00
seven332 d9265610c3 Check pages in read SpiderInfo 2016-04-08 22:44:09 +08:00
seven332 81dce7d297 Remove customtabs, set minSdkVersion to 14 2016-04-08 22:40:36 +08:00
seven332 078d086362 1.0.5 2016-04-08 22:09:15 +08:00
seven332 492d483467 Request again if image missing in cache 2016-04-08 21:19:57 +08:00
seven332 d9c1b81eb3 Add support zip file support for GalleryActivity 2016-04-08 20:46:07 +08:00
seven332 a2a9dbcb02 Add media scan config 2016-04-08 20:28:05 +08:00
seven332 97c28c04c5 Fix typo 2016-04-08 19:53:08 +08:00
seven332 f4d8cbf3a4 Add back icon callback in SetSecurityActivity 2016-04-08 19:49:58 +08:00
seven332 4291493256 Fix status bar background color above NavigationView 2016-04-08 19:33:13 +08:00
seven332 ce6cb19e73 Rename SlidingDrawerLayout to DrawerLayout 2016-04-08 18:59:36 +08:00
seven332 574d09302e Bump libraries version 2016-04-08 16:36:41 +08:00
seven332 f37b479400 Adjust table layout 2016-04-08 15:30:11 +08:00
seven332 87c27b6256 Avoid showing download path warning for the first time 2016-04-08 02:02:09 +08:00
seven332 b3881f8562 Adjust layout for table 2016-04-07 20:45:20 +08:00
seven332 3f8e872d55 Apply new MarginItemDecoration 2016-04-07 19:33:09 +08:00
seven332 3924de80b7 Add DictActivity 2016-04-07 16:27:36 +08:00
seven332 7e62673e5a Improve SpiderQueen 2016-04-07 02:23:52 +08:00
seven332 69be0c48fb Put save parse error to AppConfig 2016-04-07 02:23:10 +08:00
seven332 9d783fa86d Use GetText in ExceptionUtils 2016-04-07 02:22:06 +08:00
seven332 28b81a0db0 Fix parse gallery page error in e-hentai 2016-04-07 02:16:13 +08:00
seven332 3ac1964069 Adjust download thumb guide 2016-04-07 00:53:35 +08:00
seven332 a2241e62a3 Fix SwipeProgressBar finish animation 2016-04-07 00:33:50 +08:00
seven332 100a3d872e Set minSdkVersion to 15 2016-04-06 18:24:33 +08:00
seven332 413a17acf1 Update icon 2016-04-06 18:05:49 +08:00
seven332 79bc2bcd22 Apply thumb size settings to preview size 2016-04-06 14:53:33 +08:00
seven332 c6e45cc080 Update EasyRecyclerView 2016-04-06 01:53:05 +08:00
seven332 dc1e327caa Add busy flag to protect dict db when importing 2016-04-05 23:16:08 +08:00
seven332 7a215acd18 Add progress in GalleryActivity 2016-04-05 20:38:26 +08:00
seven332 84808429cf Clean up 2016-04-05 16:45:37 +08:00
seven332 766c265cd6 Use utf4 table to speed up 2016-04-05 16:45:15 +08:00
seven332 4cce07e0aa Control import dict log with DEBUG variable 2016-04-05 15:23:03 +08:00
seven332 e56467dd4d Add missing icon 2016-04-05 15:21:32 +08:00
seven332 90c0d832d7 Add missing string 2016-04-05 15:21:05 +08:00
seven332 729bef38fb Improve import dict notification 2016-04-05 15:16:14 +08:00
seven332 59aab0498e Make import dict safer 2016-04-05 14:43:00 +08:00
seven332 863170e013 Fix typo and clean up Import Dict 2016-04-05 14:36:25 +08:00
seven332 e62b86bf7d Improve importing dict speed 2016-04-05 14:29:03 +08:00
seven332 0e018581a0 Fix cancel import dict Null error 2016-04-05 14:18:25 +08:00
seven332 a19f1e2d6d Improve dict import layout 2016-04-05 14:16:06 +08:00
seven332 987ef9ecf4 Improve dict import intent-filter and text 2016-04-05 13:58:16 +08:00
seven332 3de272ae5e Merge branch 'master' of https://github.com/axlecho/EhViewer into axlecho-master 2016-04-05 13:12:07 +08:00
seven332 3ca6b69984 Add image size option 2016-04-05 02:07:08 +08:00
seven332 084f352d71 Add favorites sort, image size, gallery title, popular for EhConfig 2016-04-05 00:47:11 +08:00
seven332 f4a16b3edd Only show error when no cookie saved 2016-04-04 22:20:58 +08:00
seven332 e8d8ee8501 1.0.4 2016-04-04 21:08:53 +08:00
seven332 9a87701ad6 Fix memory leak which due to GalleryView.onDetachFromRootInternal not called 2016-04-04 15:20:26 +08:00
seven332 cdc8a7aea6 Adjust GLView attachToRoot detachFromRoot 2016-04-04 15:12:33 +08:00
axlecho 247bbec87d merge fix 2016-04-04 14:16:52 +08:00
axlecho e839c1e9b5 change the proxy 2016-04-04 14:01:16 +08:00
axlecho d756b0e451 delete test file 2016-04-04 13:47:57 +08:00
axlecho 663cb2b5b6 do the refactoring 2016-04-04 13:47:57 +08:00
axlecho 3e16c02e50 change the file associations 2016-04-04 13:47:57 +08:00
axlecho 80ca110702 add en pattern 2016-04-04 13:47:57 +08:00
axlecho 5f6a589dd8 when task done or abort,service will go to die 2016-04-04 13:47:57 +08:00
axlecho 342028eef1 add background notification 2016-04-04 13:47:57 +08:00
axlecho 0e96ee7eeb dict function ok 2016-04-04 13:47:57 +08:00
axlecho 3bd52e00d9 add async task for import dict 2016-04-04 13:47:57 +08:00
axlecho f612c912a7 add dict import service 2016-04-04 13:47:57 +08:00
axlecho 5dee677ce3 add dict test 2016-04-04 13:46:24 +08:00
axlecho 19ab3adc9a for my setting 2016-04-04 13:42:28 +08:00
seven332 90bfd445d1 Do not show warning after get profile error 2016-04-04 13:24:20 +08:00
seven332 7493bd57f4 Fix not showing click-thumb-detail guide 2016-04-04 13:15:52 +08:00
seven332 629c2bb80d Fix add to favorites failed 2016-04-03 23:59:17 +08:00
seven332 4d45d717e2 1.0.3 2016-04-03 20:18:38 +08:00
seven332 b8e80c6c8c Make identity live long 2016-04-03 20:15:58 +08:00
seven332 efed7776d3 Remove cancel button in sign in failed dialog 2016-04-03 19:24:57 +08:00
seven332 56cfc0669b Add set read cache max size 2016-04-03 19:19:20 +08:00
seven332 6d9ed41382 Don't scroll vertically unloaded page when scaling for ScrollLayoutManager 2016-04-03 18:20:46 +08:00
seven332 505efbdef6 Avoid unnecessary invalidate in GalleryView 2016-04-03 17:18:41 +08:00
seven332 52ab8cebb0 Improve ScrollLayoutManager 2016-04-03 17:12:13 +08:00
seven332 e8251ee521 Improve PageLayoutManager scale 2016-04-03 02:37:28 +08:00
seven332 d4195c6e5b Add scale for ScrollLayoutManager 2016-04-03 02:36:51 +08:00
seven332 f50975d767 Adjust search bar size 2016-04-02 23:11:56 +08:00
seven332 4d9452c791 Add thumb size option 2016-04-02 21:12:17 +08:00
seven332 474eea094d Add remove download redundancy 2016-04-02 19:14:42 +08:00
seven332 bbb6b634ff Remove unused resources 2016-04-02 16:59:32 +08:00
seven332 d5da97141f Remove unsupported language 2016-04-02 16:59:03 +08:00
seven332 a12f9ba595 Add fullscreen option 2016-04-02 16:36:37 +08:00
seven332 75944e5a8b Improve EhGalleryProvider 2016-04-02 16:03:49 +08:00
seven332 1aa51a5934 Bump gradle version 2016-04-02 15:49:35 +08:00
seven332 092fd6779c Bump build tools version 2016-04-02 15:42:14 +08:00
seven332 618dc2b180 Adjust SlidingDrawerLayout min margin 2016-04-02 14:05:21 +08:00
156 changed files with 3337 additions and 4952 deletions

No files matched your search

-9
View File
@@ -1,9 +1,6 @@
[submodule "yorozuya"]
path = yorozuya
url = https://github.com/seven332/Yorozuya
[submodule "hotspot"]
path = hotspot
url = https://github.com/seven332/Hotspot
[submodule "easyrecyclerview"]
path = easyrecyclerview
url = https://github.com/seven332/EasyRecyclerView
@@ -13,9 +10,3 @@
[submodule "conaco"]
path = conaco
url = https://github.com/seven332/Conaco
[submodule "rippleold"]
path = rippleold
url = https://github.com/seven332/RippleOld
[submodule "unifile"]
path = unifile
url = https://github.com/seven332/UniFile
+14 -3
View File
@@ -14,12 +14,23 @@ An E-Hentai Application for Android.
# Build
Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> git submodule update --init
> gradlew app:copyNotice
> gradlew daogenerator:executeDaoGenerator
> gradlew app:assembleDebug
Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ git submodule update --init
$ gradlew app:copyNotice
$ gradlew daogenerator:executeDaoGenerator
$ gradlew app:assembleDebug
$ ./gradlew app:copyNotice
$ ./gradlew daogenerator:executeDaoGenerator
$ ./gradlew app:assembleDebug
生成的 apk 文件在 app\build\outputs\apk 目录下
+17 -11
View File
@@ -4,15 +4,20 @@ apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 16
minSdkVersion 14
targetSdkVersion 23
versionCode 55
versionName "1.0.2"
versionCode 59
versionName "1.0.6"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
}
lintOptions {
abortOnError true
}
buildTypes {
@@ -45,7 +50,7 @@ android {
} else {
ndkBuilder = 'ndk-build'
}
commandLine "$ndkDir\\$ndkBuilder",
commandLine "$ndkDir/$ndkBuilder",
'-C', file('src/main/jni').absolutePath,
'-j', Runtime.runtime.availableProcessors()
}
@@ -69,17 +74,18 @@ dependencies {
compile project(':beerbelly')
compile project(':conaco')
compile project(':easyrecyclerview')
compile project(':hotspot')
compile project(':okhttp3')
compile project(':rippleold')
compile project(':unifile')
compile project(':yorozuya')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:customtabs:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.1'
compile 'com.github.anrwatchdog:anrwatchdog:1.2.0'
compile 'com.github.seven332:unifile:0.1.2'
compile 'com.github.seven332:drawerLayout:0.1.0'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.0'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.7'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.jsoup:jsoup:1.8.3'
+56 -1
View File
@@ -105,11 +105,55 @@
</intent-filter>
</activity-alias>
<activity
android:name="com.hippo.ehviewer.ui.DictImportActivity"
android:configChanges="screenSize|uiMode"
android:icon="@mipmap/ic_launcher"
android:label="@string/dict_import"
android:launchMode="singleTask"
android:theme="@style/AppTheme.Dialog">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.GalleryActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Gallery"
android:launchMode="singleTask"/>
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.SettingsActivity"
@@ -134,6 +178,12 @@
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/license"/>
<activity
android:name="com.hippo.ehviewer.ui.DictActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/dict"/>
<activity
android:name="com.hippo.ehviewer.ui.FilterActivity"
android:configChanges="screenSize|uiMode"
@@ -151,5 +201,10 @@
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<service
android:name="com.hippo.dict.DictImportService"
android:icon="@mipmap/ic_launcher"
android:label="@string/import_dict_service">
</service>
</application>
</manifest>
@@ -0,0 +1,240 @@
package com.hippo.dict;
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.text.TextUtils;
import android.util.JsonReader;
import android.util.Log;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.ArrayUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class DictDatabase {
private static final String TAG = DictDatabase.class.getSimpleName();
private static final boolean DEBUG = false;
public static final String COLUMN_PARENT = "parent";
public static final String COLUMN_DATA = "data";
public static final String COLUMN_DICT = "dict_name";
private static final String DATABASE_NAME = "dict_database.db";
private static final String TABLE_DICT = "dictionary";
private static final String SEPARATOR = "@@@";
private final SQLiteDatabase mDatabase;
private static DictDatabase sInstance;
private String mDictName;
private boolean mAbortFlag = false;
private final AtomicBoolean mBusyFlag = new AtomicBoolean();
public static DictDatabase getInstance(Context context) {
if (sInstance == null) {
sInstance = new DictDatabase(context.getApplicationContext());
}
return sInstance;
}
private DictDatabase(Context context) {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
mDatabase = databaseHelper.getWritableDatabase();
}
public String[] getSuggestions(String prefix) {
if (TextUtils.isEmpty(prefix) || mBusyFlag.get()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
String command = "SELECT * FROM " + TABLE_DICT + " WHERE " + COLUMN_DATA +
" MATCH '" + SqlUtils.sqlEscapeString(prefix) + "' LIMIT 5;";
Cursor cursor = mDatabase.rawQuery(command, null);
Set<String> queryList = new HashSet<>();
int queryIndex = cursor.getColumnIndex(COLUMN_DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String datum = cursor.getString(queryIndex);
String data[] = datum.split(SEPARATOR);
for (String item : data) {
if (TextUtils.isEmpty(item) || datum.equals(prefix)) {
continue;
}
queryList.add(item);
}
cursor.moveToNext();
}
}
cursor.close();
return queryList.toArray(new String[queryList.size()]);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener) throws IOException, URISyntaxException {
mAbortFlag = false;
int itemNum = -1;
InputStream inputStream = context.getContentResolver().openInputStream(dictUri);
if (null == inputStream) {
throw new FileNotFoundException("Can't find " + dictUri);
}
JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String field = jsonReader.nextName();
if (field.equals("dict")) {
mDictName = jsonReader.nextString();
if (DEBUG) {
Log.d(TAG, "[importDict] parse the dict name -- " + mDictName);
}
} else if (field.equals("num")) {
if (TextUtils.isEmpty(mDictName)) {
break;
}
itemNum = jsonReader.nextInt();
listener.processTotal(itemNum);
if (DEBUG) {
Log.d(TAG, "[importDict] parse the item number -- " + itemNum);
}
} else if (field.equals("data")) {
if (TextUtils.isEmpty(mDictName) || itemNum <= 0) {
break;
}
deleteDict(mDictName);
parseData(jsonReader, listener);
}
}
jsonReader.endObject();
jsonReader.close();
listener.processComplete();
}
public void deleteDict(String dict) {
if (mBusyFlag.get()) {
return;
}
if (DEBUG) {
Log.d(TAG, "[deleteDict] dict:" + dict);
}
mDatabase.delete(TABLE_DICT, COLUMN_DICT + "=?", new String[]{dict});
}
public void importAbort() {
if (DEBUG) {
Log.d(TAG, "[importAbort] set mAbortFlag true");
}
mAbortFlag = true;
}
/**
* Builds the database. This version has extra support for using the version field
* as a mode flags field, and configures the database columns depending on the mode bits
* (features) requested by the extending class.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE VIRTUAL TABLE " + TABLE_DICT + " USING fts4 (" +
COLUMN_DATA +
", " + COLUMN_PARENT +
", " + COLUMN_DICT +
", tokenize=icu th_ZH" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DICT);
onCreate(db);
}
}
private void parseData(JsonReader jsonReader, final DictImportService.ProcessListener listener) throws IOException {
mBusyFlag.lazySet(true);
int process = 1;
SQLiteStatement insStmt = mDatabase.compileStatement("INSERT INTO " + TABLE_DICT + " VALUES (?, ?, ?);");
mDatabase.beginTransaction();
jsonReader.beginArray();
try {
while (jsonReader.hasNext()) {
synchronized (this) {
if (mAbortFlag) {
if (DEBUG) {
Log.d(TAG, "[parseData] import abort, delete the dict -- " + mDictName);
}
deleteDict(mDictName);
return;
}
}
parseSingleData(jsonReader, insStmt);
listener.process(process);
process++;
}
jsonReader.endArray();
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
mBusyFlag.lazySet(false);
}
}
private void parseSingleData(JsonReader jsonReader, SQLiteStatement insStmt) throws IOException {
StringBuilder sb = new StringBuilder();
String parent = "";
sb.append(SEPARATOR);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
String content = jsonReader.nextString();
if (name.equals("parent")) {
parent = content;
} else {
sb.append(content);
sb.append(SEPARATOR);
}
}
jsonReader.endObject();
if (DEBUG) {
Log.d(TAG, "[parseSingleData] item:" + parent + " " + sb.toString());
}
insStmt.bindString(1, sb.toString());
insStmt.bindString(2, parent);
insStmt.bindString(3, mDictName);
insStmt.executeInsert();
}
}
@@ -0,0 +1,218 @@
package com.hippo.dict;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.hippo.util.TextUrl;
import java.util.ArrayList;
import java.util.List;
public class DictImportService extends Service {
private static final String TAG = "DictImportService";
private static final boolean DEBUG = false;
private DictManager mDictManager;
private final List<ProcessListener> mListeners = new ArrayList<>();
private ProcessListener mDictProcessListener;
private AsyncTask mImportAsyncTask;
private DictNotification mDictNotification;
// current task information
private int mItemNum;
private Uri mDictUri;
private boolean mRunningFlag = false;
public DictImportService() {}
private final Binder serviceBinder = new DictImportServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onCreate() {
super.onCreate();
mDictManager = new DictManager(this);
mDictNotification = new DictNotification(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public interface ProcessListener {
void process(int progress);
void processTotal(int total);
void processComplete();
}
public class DictImportServiceBinder extends Binder {
public DictImportService getService() {
return DictImportService.this;
}
}
public void importDict(Uri dictUri) {
if (dictUri == null) {
// TODO error tip
if (DEBUG) {
Log.e(TAG, "[importDict] dictUri is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[importDict] start import async task");
}
mImportAsyncTask = new ImportAsyncTask(dictUri).execute();
}
public void abortImport() {
if (mImportAsyncTask == null) {
if (DEBUG) {
Log.e(TAG, "[abortImport] mImportAsyncTask is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[abortImport] import abort");
}
// fixme
// this i just set a flag to abort the parse thread,it may cause a exception
// it there may be a elegant way to shut the worker thread down
mDictManager.importAbort();
// just for service go die
mImportAsyncTask.cancel(true);
}
public Uri getUri() {
return mDictUri;
}
public int getItemNum() {
return mItemNum;
}
public boolean isRunning() {
return mRunningFlag;
}
public void setOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.add(onProgressListener);
mListeners.remove(mDictNotification.mNotificationListener);
mDictNotification.stopNotify();
}
}
public void removeOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.remove(onProgressListener);
}
// if there is no listener in listener list,we is in the background mostly
// we post the process progress information to a notification
if (mListeners.size() == 0 && null != mDictUri) {
mDictNotification.setMax(mItemNum);
mDictNotification.setFileName(TextUrl.getFileName(mDictUri.toString()));
mListeners.add(mDictNotification.mNotificationListener);
}
}
class ImportAsyncTask extends AsyncTask<Void, Integer, Void> {
public ImportAsyncTask(Uri dictUri) {
mDictUri = dictUri;
mRunningFlag = true;
mDictProcessListener = new ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.d(TAG, "[process] progress:" + progress);
}
publishProgress(progress);
}
@Override
public void processTotal(int total) {
if (DEBUG) {
Log.d(TAG, "process total " + total);
}
mItemNum = total;
for (ProcessListener listener : mListeners) {
listener.processTotal(total);
}
}
@Override
public void processComplete() {
// we don't do any thing here,let async task handle this
if (DEBUG) {
Log.d(TAG, "processComplete");
}
}
};
}
@Override
protected Void doInBackground(Void... voids) {
try {
mDictManager.importDict(DictImportService.this, mDictUri, mDictProcessListener);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (DEBUG) {
Log.d(TAG, "[onProgressUpdate] process item " + progress[0]);
}
for (ProcessListener listener : mListeners) {
listener.process(progress[0]);
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for (ProcessListener listener : mListeners) {
listener.processComplete();
}
mRunningFlag = false;
DictImportService.this.goDie();
}
@Override
protected void onCancelled() {
super.onCancelled();
DictImportService.this.goDie();
}
}
public void goDie() {
if (DEBUG) {
Log.d(TAG, "[goDie] task done or abort,go to die");
}
this.stopSelf();
}
}
@@ -0,0 +1,57 @@
package com.hippo.dict;
import android.content.Context;
import android.net.Uri;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO Singleton
// TODO Add add-dict callback for DictActivity
public class DictManager {
// pattern for language
private static final String enRegEx = "^[0-9a-zA-Z_\\s]+$";
// private static final String zhRegEx = "";
private final DictDatabase mDictDatabase;
public DictManager(Context context) {
mDictDatabase = DictDatabase.getInstance(context);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener)
throws IOException, URISyntaxException {
mDictDatabase.importDict(context, dictUri, listener);
}
public void deletDict(String dict) {
mDictDatabase.deleteDict(dict);
}
public String[] getSuggestions(String prefix) {
List<String> result = new ArrayList<>();
String databaseResult[] = mDictDatabase.getSuggestions(prefix);
for (String s : databaseResult) {
if (filter(s)) {
result.add(s);
}
}
return result.toArray(new String[result.size()]);
}
public void importAbort() {
mDictDatabase.importAbort();
}
public boolean filter(String item) {
// return true;
Pattern en = Pattern.compile(enRegEx);
Matcher m = en.matcher(item);
return m.matches();
}
}
@@ -0,0 +1,100 @@
package com.hippo.dict;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.support.v7.app.NotificationCompat;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.DictImportActivity;
import com.hippo.ehviewer.ui.MainActivity;
public class DictNotification {
private final Context mContext;
private final NotificationManager mNotifyManager;
private final NotificationCompat.Builder mBuilder;
private int mMax = 100;
private final int mId = 1;
private long mLastUpdateTime;
private final PendingIntent mImportIntent;
private final PendingIntent mDoneIntent;
public DictNotification(Context context) {
mContext = context;
mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(mContext);
mImportIntent = PendingIntent.getActivity(context, 0, new Intent(context, DictImportActivity.class), 0);
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
mDoneIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentTitle(mContext.getResources().getString(R.string.dict_import))
.setContentText("0/" + mMax)
.setSmallIcon(R.drawable.ic_stat_import)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setContentIntent(mImportIntent)
.setOngoing(true);
}
public DictImportService.ProcessListener mNotificationListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
DictNotification.this.notify(progress);
}
@Override
public void processTotal(int total) {
// this may useless
mMax = total;
}
@Override
public void processComplete() {
DictNotification.this.notifyDone();
}
};
public void setMax(int max) {
mMax = max;
mBuilder.setContentText("0/" + mMax);
}
public void setFileName(String fileName) {
mBuilder.setContentTitle(mContext.getString(R.string.dict_import) + " " + fileName);
}
public void notify(int progress) {
// Avoid update frequently
long now = SystemClock.currentThreadTimeMillis();
if (now - mLastUpdateTime < 500L) {
return;
}
mLastUpdateTime = now;
mBuilder.setContentIntent(mImportIntent);
mBuilder.setProgress(mMax, progress, false);
mBuilder.setContentText(progress + "/" + mMax);
mNotifyManager.notify(mId, mBuilder.build());
}
public void notifyDone() {
mBuilder.setContentIntent(mDoneIntent);
mBuilder.setContentTitle(mContext.getString(R.string.dict_import_successfully));
mBuilder.setContentText(mMax + "/" + mMax);
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mNotifyManager.notify(mId, mBuilder.build());
}
public void stopNotify() {
mNotifyManager.cancel(mId);
}
}
@@ -59,6 +59,7 @@ public class BatteryDrawable extends Drawable {
}
@Override
@SuppressWarnings("SuspiciousNameCombination")
protected void onBoundsChange(Rect bounds) {
int width = bounds.width();
int height = bounds.height();
@@ -89,8 +90,9 @@ public class BatteryDrawable extends Drawable {
*/
@Override
public void draw(Canvas canvas) {
if (mElect == -1)
if (mElect == -1) {
return;
}
mElectRect.right = MathUtils.lerp(mStart, mStop, mElect / 100.0f);
@@ -152,21 +154,22 @@ public class BatteryDrawable extends Drawable {
}
private void updatePaint(boolean warn) {
if (warn)
if (warn) {
mPaint.setColor(mWarningColor);
else
} else {
mPaint.setColor(mColor);
}
invalidateSelf();
}
@Override
public void setAlpha(int alpha) {
// Empty
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
// Empty
mPaint.setColorFilter(cf);
}
@Override
@@ -38,7 +38,7 @@ public class DrawerArrowDrawable extends Drawable {
private final Paint mPaint = new Paint();
// The angle in degress that the arrow head is inclined at.
// The angle in degrees that the arrow head is inclined at.
private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45);
private final float mBarThickness;
// The length of top and bottom bars when they merge into an arrow
@@ -61,7 +61,7 @@ public class DrawerArrowDrawable extends Drawable {
// The interpolated version of the original progress
private float mProgress;
// the amount that overlaps w/ bar size when rotation is max
private float mMaxCutForBarSize;
private final float mMaxCutForBarSize;
/**
* @param context used to get the configuration for the drawable from
@@ -20,9 +20,15 @@ import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class AppConfig {
@@ -129,4 +135,31 @@ public class AppConfig {
public static File createTempFile() {
return FileUtils.createTempFile(getTempDir(), null);
}
public static void saveParseErrorBody(ParseException e) {
File dir = getExternalParseErrorDir();
if (null == dir) {
return;
}
File file = new File(dir, ReadableTime.getFilenamableTime(System.currentTimeMillis()) + ".txt");
OutputStream os = null;
try {
os = new FileOutputStream(file);
String message = e.getMessage();
String body = e.getBody();
if (null != message) {
os.write(message.getBytes("utf-8"));
os.write('\n');
}
if (null != body) {
os.write(body.getBytes("utf-8"));
}
os.flush();
} catch (IOException e1) {
// Ignore
} finally {
IOUtils.closeQuietly(os);
}
}
}
@@ -29,11 +29,14 @@ import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderDen;
@@ -42,6 +45,7 @@ import com.hippo.network.StatusCodeException;
import com.hippo.okhttp.CookieDB;
import com.hippo.scene.SceneApplication;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
@@ -55,6 +59,8 @@ import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
public class EhApplication extends SceneApplication implements Thread.UncaughtExceptionHandler {
@@ -87,6 +93,15 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
// Start anr watch dog
new ANRWatchDog().setANRListener(new ANRWatchDog.ANRListener() {
@Override
public void onAppNotResponding(ANRError error) {
// Throw RuntimeException, let crash handler do it
throw new RuntimeException(error.getCause());
}
}).start();
super.onCreate();
GetText.initialize(this);
@@ -109,8 +124,18 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
Analytics.start(this);
}
CommonOperations.ensureNoMediaFile(Settings.getDownloadLocation());
// Check no media file
UniFile downloadLocation = Settings.getDownloadLocation();
if (Settings.getMediaScan()) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
// Clear temp dir
clearTempDir();
// Check app update
update();
// Update version code
@@ -142,6 +167,29 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (version < 52) {
Settings.putGuideGallery(true);
}
if (version < 56) { // Make cookie long live
HttpUrl eUrl = HttpUrl.parse(EhUrl.HOST_E);
HttpUrl exUrl = HttpUrl.parse(EhUrl.HOST_EX);
EhCookieStore cookieStore = getEhCookieStore(this);
Cookie c;
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
}
}
public void clearMemoryCache() {
@@ -307,6 +355,12 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
Activity activity = getTopActivity();
if (activity != null) {
activity.finish();
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
@@ -21,6 +21,7 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
@@ -55,6 +56,7 @@ public class Settings {
private static EhConfig loadEhConfig() {
EhConfig ehConfig= new EhConfig();
ehConfig.imageSize = getImageResolution();
ehConfig.excludedLanguages = getExcludedLanguages();
ehConfig.defaultCategories = getDefaultCategories();
ehConfig.excludedNamespaces = getExcludedTagNamespaces();
@@ -253,6 +255,33 @@ public class Settings {
return getIntFromStr(KEY_LIST_MODE, DEFAULT_LIST_MODE);
}
public static final String KEY_THUMB_SIZE = "thumb_size";
private static final int DEFAULT_THUMB_SIZE = 1;
public static int getThumbSize() {
return getIntFromStr(KEY_THUMB_SIZE, DEFAULT_THUMB_SIZE);
}
@DimenRes
public static int getThumbSizeResId() {
switch (getThumbSize()) {
case 0:
return R.dimen.gallery_grid_column_width_large;
default:
case 1:
return R.dimen.gallery_grid_column_width_middle;
case 2:
return R.dimen.gallery_grid_column_width_small;
}
}
public static final String KEY_THUMB_RESOLUTION = "thumb_resolution";
private static final int DEFAULT_THUMB_RESOLUTION = 0;
public static int getThumbResolution() {
return getIntFromStr(KEY_THUMB_RESOLUTION, DEFAULT_THUMB_RESOLUTION);
}
private static final String KEY_SHOW_JPN_TITLE = "show_jpn_title";
private static final boolean DEFAULT_SHOW_JPN_TITLE = false;
@@ -437,6 +466,17 @@ public class Settings {
putBoolean(KEY_SHOW_CLOCK, value);
}
private static final String KEY_SHOW_PROGRESS = "gallery_show_progress";
private static final boolean DEFAULT_SHOW_PROGRESS = true;
public static boolean getShowProgress() {
return getBoolean(KEY_SHOW_PROGRESS, DEFAULT_SHOW_PROGRESS);
}
public static void putShowProgress(boolean value) {
putBoolean(KEY_SHOW_PROGRESS, value);
}
private static final String KEY_SHOW_BATTERY = "gallery_show_battery";
private static final boolean DEFAULT_SHOW_BATTERY = true;
@@ -459,6 +499,17 @@ public class Settings {
putBoolean(KEY_VOLUME_PAGE, value);
}
private static final String KEY_READING_FULLSCREEN = "reading_fullscreen";
private static final boolean VALUE_READING_FULLSCREEN = true;
public static boolean getReadingFullscreen() {
return getBoolean(KEY_READING_FULLSCREEN, VALUE_READING_FULLSCREEN);
}
public static void putReadingFullscreen(boolean value) {
putBoolean(KEY_READING_FULLSCREEN, value);
}
private static final String KEY_CUSTOM_SCREEN_LIGHTNESS = "custom_screen_lightness";
private static final boolean DEFAULT_CUSTOM_SCREEN_LIGHTNESS = false;
@@ -515,7 +566,18 @@ public class Settings {
putString(KEY_DOWNLOAD_SAVE_QUERY, uri.getEncodedQuery());
putString(KEY_DOWNLOAD_SAVE_FRAGMENT, uri.getEncodedFragment());
CommonOperations.ensureNoMediaFile(location);
if (getMediaScan()) {
CommonOperations.removeNoMediaFile(location);
} else {
CommonOperations.ensureNoMediaFile(location);
}
}
public static final String KEY_MEDIA_SCAN = "media_scan";
private static final boolean DEFAULT_MEDIA_SCAN = false;
public static boolean getMediaScan() {
return getBoolean(KEY_MEDIA_SCAN, DEFAULT_MEDIA_SCAN);
}
private static final String KEY_RECENT_DOWNLOAD_LABEL = "recent_download_label";
@@ -573,6 +635,19 @@ public class Settings {
putIntToStr(KEY_PRELOAD_IMAGE, value);
}
public static final String KEY_IMAGE_RESOLUTION = "image_size";
public static final String DEFAULT_IMAGE_RESOLUTION = EhConfig.IMAGE_SIZE_AUTO;
public static String getImageResolution() {
return getString(KEY_IMAGE_RESOLUTION, DEFAULT_IMAGE_RESOLUTION);
}
public static void putImageResolution(String value) {
sEhConfig.imageSize = value;
sEhConfig.setDirty();
putString(KEY_IMAGE_RESOLUTION, value);
}
private static final String KEY_DOWNLOAD_ORIGIN_IMAGE = "download_origin_image";
private static final boolean DEFAULT_DOWNLOAD_ORIGIN_IMAGE = false;
@@ -804,6 +879,13 @@ public class Settings {
putString(KEY_SECURITY, value);
}
public static final String KEY_READ_CACHE_SIZE = "read_cache_size";
public static final int DEFAULT_READ_CACHE_SIZE = 160;
public static int getReadCacheSize() {
return getIntFromStr(KEY_READ_CACHE_SIZE, DEFAULT_READ_CACHE_SIZE);
}
/********************
****** Guide
********************/
@@ -16,14 +16,12 @@
package com.hippo.ehviewer;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
import android.text.TextUtils;
import android.widget.Toast;
@@ -31,14 +29,13 @@ 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.CustomTabsHelper;
public final class UrlOpener {
private UrlOpener() {
}
public static void openUrl(@NonNull Context context, String url, boolean ehUrl, boolean customTabs) {
public static void openUrl(@NonNull Context context, String url, boolean ehUrl) {
if (TextUtils.isEmpty(url)) {
return;
}
@@ -59,20 +56,6 @@ public final class UrlOpener {
}
}
// CustomTabs
if (customTabs && context instanceof Activity) {
Activity activity = (Activity) context;
String packageName = CustomTabsHelper.getPackageNameToUseFixed(activity);
if (packageName != null) {
new CustomTabsIntent.Builder()
.setToolbarColor(activity.getResources().getColor(R.color.colorPrimary))
.setShowTitle(true)
.build()
.launchUrl(activity, uri);
return;
}
}
// Intent.ACTION_VIEW
intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
@@ -30,8 +30,20 @@ public class EhConfig implements Cloneable {
/**
* The key of load images through the Hentai@Home Network
* @see #LOAD_FROM_HAH_YES
* @see #LOAD_FROM_HAH_NO
*/
private static final String KEY_LOAD_FROM_HAH = "uh";
/**
* The key of Image Size Settings
* @see #IMAGE_SIZE_AUTO
* @see #IMAGE_SIZE_780X
* @see #IMAGE_SIZE_980X
* @see #IMAGE_SIZE_1280X
* @see #IMAGE_SIZE_1600X
* @see #IMAGE_SIZE_2400X
*/
private static final String KEY_IMAGE_SIZE = "xr";
/**
* The key of scale images width
*/
@@ -40,18 +52,42 @@ public class EhConfig implements Cloneable {
* The key of scale images height
*/
private static final String KEY_SCALE_HEIGHT = "ry";
/**
* The key of Gallery Name Display
* @see #GALLERY_TITLE_DEFAULT
* @see #GALLERY_TITLE_JAPANESE
*/
private static final String KEY_GALLERY_TITLE = "tl";
/**
* The key of the behavior for downloading archiver
* @see #ARCHIVER_DOWNLOAD_MAMS
* @see #ARCHIVER_DOWNLOAD_MAAS
* @see #ARCHIVER_DOWNLOAD_AAMS
* @see #ARCHIVER_DOWNLOAD_AAAS
*/
private static final String KEY_ARCHIVER_DOWNLOAD = "ar";
/**
* The key of display mode would you like to use on the front and search pages
* @see #LAYOUT_MODE_LIST
* @see #LAYOUT_MODE_THUMB
*/
private static final String KEY_LAYOUT_MODE = "dm";
/**
* The key for show popular
* @see #POPULAR_YES
* @see #POPULAR_NO
*/
private static final String KEY_POPULAR = "prn";
/**
* The key of categories would you like to view as default on the front page
*/
private static final String KEY_DEFAULT_CATEGORIES = "cats";
/**
* The key for favorites sort
* @see #FAVORITES_SORT_GALLERY_UPDATE_TIME
* @see #FAVORITES_SORT_FAVORITED_TIME
*/
private static final String KEY_FAVORITES_SORT = "fs";
/**
* The key of exclude certain namespaces from a default tag search
*/
@@ -62,34 +98,55 @@ public class EhConfig implements Cloneable {
private static final String KEY_EXCLUDED_LANGUAGES = "xl";
/**
* The key of how many results would you like per page for the index/search page and torrent search pages
* @see #RESULT_COUNT_25
* @see #RESULT_COUNT_50
* @see #RESULT_COUNT_100
* @see #RESULT_COUNT_200
*/
private static final String KEY_RESULT_COUNT = "rc";
/**
* The key of mouse-over thumb
* @see #MOUSE_OVER_YES
* @see #MOUSE_OVER_NO
*/
private static final String KEY_MOUSE_OVER = "tl";
private static final String KEY_MOUSE_OVER = "lt";
/**
* The key of preview size
* @see #PREVIEW_SIZE_NORMAL
* @see #PREVIEW_SIZE_LARGE
*/
private static final String KEY_PREVIEW_SIZE = "ts";
/**
* The key of preview row per page
* @see #PREVIEW_ROW_4
* @see #PREVIEW_ROW_10
* @see #PREVIEW_ROW_20
* @see #PREVIEW_ROW_40
*/
private static final String KEY_PREVIEW_ROW = "tr";
/**
* The key of sort order for gallery comments
* @see #COMMENTS_SORT_OLDEST_FIRST
* @see #COMMENTS_SORT_RECENT_FIRST
* @see #COMMENTS_SORT_HIGHEST_SCORE_FIRST
*/
private static final String KEY_COMMENTS_SORT = "cs";
/**
* The key of show gallery comment votes
* @see #COMMENTS_VOTES_POP
* @see #COMMENTS_VOTES_ALWAYS
*/
private static final String KEY_COMMENTS_VOTES = "sc";
/**
* The key of sort order for gallery tags
* @see #TAGS_SORT_ALPHABETICAL
* @see #TAGS_SORT_POWER
*/
private static final String KEY_TAGS_SORT = "to";
/**
* The key of show gallery page numbers
* @see #SHOW_GALLERY_INDEX_NO
* @see #SHOW_GALLERY_INDEX_YES
*/
private static final String KEY_SHOW_GALLERY_INDEX = "pn";
/**
@@ -104,22 +161,33 @@ public class EhConfig implements Cloneable {
private static final String KEY_HAH_CLIENT_PASSKEY = "hk";
/**
* The key of enable Tag Flagging
* @see #ENABLE_TAG_FLAGGING_NO
* @see #ENABLE_TAG_FLAGGING_YES
*/
private static final String KEY_ENABLE_TAG_FLAGGING = "tf";
/**
* The key of always display the original images instead of the resampled versions
* @see #ALWAYS_ORIGINAL_NO
* @see #ALWAYS_ORIGINAL_YES
*/
private static final String KEY_ALWAYS_ORIGINAL = "oi";
/**
* The key of enable the multi-Page Viewer
* @see #MULTI_PAGE_NO
* @see #MULTI_PAGE_YES
*/
private static final String KEY_MULTI_PAGE = "qb";
/**
* The key of multi-Page Viewer Display Style
* @see #MULTI_PAGE_STYLE_C
* @see #MULTI_PAGE_STYLE_N
* @see #MULTI_PAGE_STYLE_Y
*/
private static final String KEY_MULTI_PAGE_STYLE = "ms";
/**
* The key of multi-Page Viewer Thumbnail Pane
* @see #MULTI_PAGE_THUMB_HIDE
* @see #MULTI_PAGE_THUMB_SHOW
*/
private static final String KEY_MULTI_PAGE_THUMB = "mt";
@@ -142,6 +210,40 @@ public class EhConfig implements Cloneable {
*/
public static final String LOAD_FROM_HAH_NO = "n";
/**
* Image Size Auto
*/
public static final String IMAGE_SIZE_AUTO = "a";
/**
* Image Size 780x
*/
public static final String IMAGE_SIZE_780X = "780";
/**
* Image Size 980x
*/
public static final String IMAGE_SIZE_980X = "980";
/**
* Image Size 1280x
*/
public static final String IMAGE_SIZE_1280X = "1280";
/**
* Image Size 1600x
*/
public static final String IMAGE_SIZE_1600X = "1600";
/**
* Image Size 2400x
*/
public static final String IMAGE_SIZE_2400X = "2400";
/**
* Default gallery title
*/
private static final String GALLERY_TITLE_DEFAULT = "r";
/**
* Japanese gallery title
*/
private static final String GALLERY_TITLE_JAPANESE = "j";
/**
* Manual Accept, Manual Start
*/
@@ -168,6 +270,15 @@ public class EhConfig implements Cloneable {
*/
public static final String LAYOUT_MODE_THUMB = "t";
/**
* Show popular
*/
private static final String POPULAR_YES = "y";
/**
* Don't show popular
*/
private static final String POPULAR_NO = "n";
public static final int MISC = 0x1;
public static final int DOUJINSHI = 0x2;
public static final int MANGA = 0x4;
@@ -239,6 +350,15 @@ public class EhConfig implements Cloneable {
public static final String OTHER_TRANSLATED = "1279";
public static final String OTHER_REWRITE = "2303";
/**
* Sort favorites by last gallery update time
*/
private static final String FAVORITES_SORT_GALLERY_UPDATE_TIME = "p";
/**
* Sort favorites by favorited time
*/
private static final String FAVORITES_SORT_FAVORITED_TIME = "f";
/**
* 25 results per page for the index/search page and torrent search pages
*/
@@ -412,6 +532,14 @@ public class EhConfig implements Cloneable {
*/
public String loadFromHAH = LOAD_FROM_HAH_YES;
/**
* Image Size<br/>
* key: {@link #KEY_IMAGE_SIZE}<br/>
* value: {@link #IMAGE_SIZE_AUTO}, {@link #IMAGE_SIZE_780X}, {@link #IMAGE_SIZE_980X},
* {@link #IMAGE_SIZE_1280X}, {@link #IMAGE_SIZE_1600X}, {@link #IMAGE_SIZE_2400X}
*/
public String imageSize = IMAGE_SIZE_AUTO;
/**
* Scale width<br/>
* key: {@link #KEY_SCALE_WIDTH}<br/>
@@ -426,6 +554,13 @@ public class EhConfig implements Cloneable {
*/
public int scaleHeight = 0;
/**
* Gallery title<br/>
* key: {@link #KEY_GALLERY_TITLE}<br/>
* value: {@link #GALLERY_TITLE_DEFAULT}, {@link #GALLERY_TITLE_JAPANESE}
*/
public String galleryTitle = GALLERY_TITLE_DEFAULT;
/**
* The default behavior for downloading an archiver<br/>
* key: {@link #KEY_ARCHIVER_DOWNLOAD}<br/>
@@ -442,6 +577,13 @@ public class EhConfig implements Cloneable {
*/
public String layoutMode = LAYOUT_MODE_LIST;
/**
* Show popular or not<br/>
* key: {@link #KEY_POPULAR}<br/>
* value: {@link #POPULAR_YES}, {@link #POPULAR_NO}
*/
public String popular = POPULAR_YES;
/**
* Default categories on the front page<br/>
* key: {@link #KEY_DEFAULT_CATEGORIES}<br/>
@@ -450,6 +592,13 @@ public class EhConfig implements Cloneable {
*/
public int defaultCategories = 0;
/**
* <br/>
* key: {@link #KEY_FAVORITES_SORT}<br/>
* value: {@link #FAVORITES_SORT_GALLERY_UPDATE_TIME}, {@link #FAVORITES_SORT_FAVORITED_TIME}
*/
public String favoritesSort = FAVORITES_SORT_FAVORITED_TIME;
/**
* Certain namespaces excluded from a default tag search<br/>
* key: {@link #KEY_EXCLUDED_NAMESPACES}<br/>
@@ -628,11 +777,15 @@ public class EhConfig implements Cloneable {
hahClientIp + "%3A" + hahClientPort : "";
String hahClientPasskey = null == this.hahClientPasskey ? "" : this.hahClientPasskey;
mUconfig = KEY_LOAD_FROM_HAH + "_" + loadFromHAH + "-" +
KEY_IMAGE_SIZE + "_" + imageSize + "-" +
KEY_SCALE_WIDTH + "_" + scaleWidth + "-" +
KEY_SCALE_HEIGHT + "_" + scaleHeight + "-" +
KEY_GALLERY_TITLE + "_" + galleryTitle + "-" +
KEY_ARCHIVER_DOWNLOAD + "_" + archiverDownload + "-" +
KEY_LAYOUT_MODE + "_" + layoutMode + "-" +
KEY_POPULAR + "_" + popular + "-" +
KEY_DEFAULT_CATEGORIES + "_" + defaultCategories + "-" +
KEY_FAVORITES_SORT + "_" + favoritesSort + "-" +
KEY_EXCLUDED_NAMESPACES + "_" + excludedNamespaces + "-" +
KEY_EXCLUDED_LANGUAGES + "_" + excludedLanguages + "-" +
KEY_RESULT_COUNT + "_" + resultCount + "-" +
@@ -49,11 +49,15 @@ public class EhCookieStore extends CookieDBStore {
contain(EhUrl.DOMAIN_EX, KEY_IPD_PASS_HASH);
}
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent, boolean forceNotHostOnly) {
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent,
boolean forceLongLive, boolean forceNotHostOnly) {
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookie.name());
builder.value(cookie.value());
if (cookie.persistent()) {
if (forceLongLive) {
builder.expiresAt(Long.MAX_VALUE);
} else if (cookie.persistent()) {
builder.expiresAt(cookie.expiresAt());
} else if (forcePersistent) {
builder.expiresAt(Long.MAX_VALUE);
@@ -125,7 +129,9 @@ public class EhCookieStore extends CookieDBStore {
// Save id and hash for exhentai
if (KEY_IPD_MEMBER_ID.equals(cookie.name()) ||
KEY_IPD_PASS_HASH.equals(cookie.name())) {
result.add(newCookie(cookie, EhUrl.DOMAIN_EX, false, false));
result.add(newCookie(cookie, EhUrl.DOMAIN_E, true, true, true));
result.add(newCookie(cookie, EhUrl.DOMAIN_EX, true, true, true));
continue;
}
}
@@ -36,6 +36,7 @@ import com.hippo.ehviewer.client.parser.ForumsParser;
import com.hippo.ehviewer.client.parser.GalleryApiParser;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryListParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryTokenApiParser;
import com.hippo.ehviewer.client.parser.ProfileParser;
import com.hippo.ehviewer.client.parser.RateGalleryParser;
@@ -44,9 +45,7 @@ import com.hippo.ehviewer.client.parser.TorrentParser;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.network.StatusCodeException;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -54,9 +53,6 @@ import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
@@ -87,33 +83,6 @@ public class EhEngine {
sEhFilter = EhFilter.getInstance();
}
private static void saveParseErrorBody(ParseException e) {
File dir = AppConfig.getExternalParseErrorDir();
if (null == dir) {
return;
}
File file = new File(dir, ReadableTime.getFilenamableTime(System.currentTimeMillis()) + ".txt");
OutputStream os = null;
try {
os = new FileOutputStream(file);
String message = e.getMessage();
String body = e.getBody();
if (null != message) {
os.write(message.getBytes("utf-8"));
os.write('\n');
}
if (null != body) {
os.write(body.getBytes("utf-8"));
}
os.flush();
} catch (IOException e1) {
// Ignore
} finally {
IOUtils.closeQuietly(os);
}
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
if (call.isCanceled()) {
@@ -132,7 +101,7 @@ public class EhEngine {
throw new EhException(body);
} else {
if (Settings.getSaveParseErrorBody()) {
saveParseErrorBody((ParseException) e);
AppConfig.saveParseErrorBody((ParseException) e);
}
throw new EhException(GetText.getString(R.string.error_parse_error));
}
@@ -500,6 +469,7 @@ public class EhEngine {
builder.add("favnote", note != null ? note : "");
// submit=Add+to+Favorites is not necessary, just use submit=Apply+Changes all the time
builder.add("submit", "Apply Changes");
builder.add("update", "1");
String url = EhUrl.getAddFavorites(gid, token);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
@@ -833,4 +803,30 @@ public class EhEngine {
return result;
}
public static GalleryPageParser.Result getGalleryPage(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
return GalleryPageParser.parse(body);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
}
@@ -31,6 +31,7 @@ public class EhUrl {
public static final String DOMAIN_G = "g.e-hentai.org";
public static final String DOMAIN_LOFI = "lofi.e-hentai.org";
public static final String HOST_E = "http://" + DOMAIN_E + "/";
public static final String HOST_EX = "http://" + DOMAIN_EX + "/";
public static final String HOST_G = "http://" + DOMAIN_G + "/";
@@ -168,4 +168,31 @@ public class EhUtils {
return title;
}
}
public static String handleThumbUrlResolution(String url) {
if (null == url) {
return null;
}
String resolution;
switch (Settings.getThumbResolution()) {
default:
case 0: // Auto
return url;
case 1: // 250
resolution = "250";
break;
case 2: // 300
resolution = "300";
break;
}
int index1 = url.lastIndexOf('_');
int index2 = url.lastIndexOf('.');
if (index1 >= 0 && index2 >= 0 && index1 < index2) {
return url.substring(0, index1 + 1) + resolution + url.substring(index2);
} else {
return url;
}
}
}
@@ -41,7 +41,7 @@ public class GalleryApiParser {
gi.title = ParserUtils.trim(g.getString("title"));
gi.titleJpn = ParserUtils.trim(g.getString("title_jpn"));
gi.category = EhUtils.getCategory(g.getString("category"));
gi.thumb = g.getString("thumb");
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"));
@@ -130,7 +130,7 @@ public class GalleryDetailParser {
// Thumb url
Element gd1 = gm.getElementById("gd1");
try {
gd.thumb = StringUtils.trim(gd1.child(0).attr("src"));
gd.thumb = EhUtils.handleThumbUrlResolution(StringUtils.trim(gd1.child(0).attr("src")));
} catch (Exception e) {
gd.thumb = "";
}
@@ -121,13 +121,14 @@ public class GalleryListParser {
// Thumb url
Elements es = it2.children();
if (null != es && es.size() >= 1) {
gi.thumb = es.get(0).attr("src");
gi.thumb = EhUtils.handleThumbUrlResolution(es.get(0).attr("src"));
} else {
String html = it2.html();
int index1 = html.indexOf('~');
int index2 = StringUtils.ordinalIndexOf(html, '~', 2);
if (index1 < index2) {
gi.thumb = "http://" +StringUtils.replace(html.substring(index1 + 1, index2), "~", "/");
gi.thumb = EhUtils.handleThumbUrlResolution(
"http://" +StringUtils.replace(html.substring(index1 + 1, index2), "~", "/"));
} else {
Log.w(TAG, "Can't parse gallery info thumb url");
gi.thumb = "";
@@ -26,9 +26,9 @@ import java.util.regex.Pattern;
public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<div id=\"i3\"><a[^>]+><img id=\"img\" src=\"([^\"]+)\"");
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<(?:/iframe|div id=\"i3\")[^>]*><a[^>]+><img[^>]*src=\"(.+?)\"");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<div id=\"i7\" class=\"if\"> &nbsp; <img[^>]+/> <a href=\"([^\"]+)\">");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
public static Result parse(String body) throws ParseException {
Matcher m;
@@ -43,9 +43,10 @@ public class GalleryPageParser {
}
m = PATTERN_ORIGIN_IMAGE_URL.matcher(body);
if (m.find()) {
result.originImageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
}
if (!TextUtils.isEmpty(result.imageUrl) && !TextUtils.isEmpty(result.skipHathKey)) {
if (!TextUtils.isEmpty(result.imageUrl)) {
return result;
} else {
throw new ParseException("Parse image url and skip hath key error", body);
@@ -16,6 +16,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.JsoupUtils;
@@ -47,7 +48,7 @@ public class WhatsHotParser {
galleryInfo.gid = result.gid;
galleryInfo.token = result.token;
temp = JsoupUtils.getElementByTag(temp, "img");
galleryInfo.thumb = temp.attr("src");
galleryInfo.thumb = EhUtils.handleThumbUrlResolution(temp.attr("src"));
galleryInfo.title = temp.attr("title");
galleryInfo.generateSLang();
galleryInfoList.add(galleryInfo);
@@ -345,7 +345,9 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
mDownloadingDelay.cancel();
if (null != mDownloadingDelay) {
mDownloadingDelay.cancel();
}
ensureDownloadedBuilder();
@@ -443,7 +445,10 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
mDownloadingDelay.cancel();
if (null != mDownloadingDelay) {
mDownloadingDelay.cancel();
}
checkStopSelf();
}
@@ -54,15 +54,9 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
if (mSpiderQueen != null) {
mSpiderQueen.removeOnSpiderListener(this);
final SpiderQueen spiderQueen = mSpiderQueen;
// Activity recreate may called, so wait 3000s
SimpleHandler.getInstance().postDelayed(new ReleaseTask(mSpiderQueen), 3000);
mSpiderQueen = null;
// Activity recreate may called
SimpleHandler.getInstance().postDelayed(new Runnable() {
@Override
public void run() {
SpiderQueen.releaseSpiderQueen(spiderQueen, SpiderQueen.MODE_READ);
}
}, 3000);
}
}
@@ -200,4 +194,21 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
public void onGetImageFailure(int index, String error) {
notifyPageFailed(index, error);
}
private static class ReleaseTask implements Runnable {
private SpiderQueen mSpiderQueen;
public ReleaseTask(SpiderQueen spiderQueen) {
mSpiderQueen = spiderQueen;
}
@Override
public void run() {
if (null != mSpiderQueen) {
SpiderQueen.releaseSpiderQueen(mSpiderQueen, SpiderQueen.MODE_READ);
mSpiderQueen = null;
}
}
}
}
@@ -121,7 +121,8 @@ public class GalleryPageView extends GLFrameLayout {
}
public void showInfo() {
mImage.setVisibility(GONE);
// For image valid rect
mImage.setVisibility(INVISIBLE);
mInfo.setVisibility(VISIBLE);
}
@@ -88,9 +88,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private static final int METHOD_SET_SCALE_MODE = 18;
private static final int METHOD_SET_START_POSITION = 19;
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private static final int METHOD_ON_DETACH_FROM_ROOT = 21;
private static final int METHOD_PAUSE = 22;
private static final int METHOD_RESUME = 23;
private final Context mContext;
private MovableTextTexture mPageTextTexture;
@@ -114,6 +111,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private boolean mEnableRequestFill = true;
private boolean mRequestFill = false;
private boolean mWillFill = false;
private boolean mScale = false;
private boolean mScroll = false;
@@ -247,40 +245,17 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
postMethod(METHOD_ON_ATTACH_TO_ROOT);
}
private void onDetachFromRootInternal() {
@Override
public void onDetachFromRoot() {
// When detached, render() will not be called. So do it here
detachLayoutManager();
if (null != mPageTextTexture) {
mPageTextTexture.recycle();
mPageTextTexture = null;
}
}
@Override
public void onDetachFromRoot() {
super.onDetachFromRoot();
mEdgeView.onDetachFromRoot();
postMethod(METHOD_ON_DETACH_FROM_ROOT);
}
private void pauseInternal() {
mPause = true;
}
public void pause() {
postMethod(METHOD_PAUSE);
}
private void resumeInternal() {
if (mPause) {
mPause = false;
if (null != mLayoutManager) {
mLayoutManager.bindUnloadedPage();
}
}
}
public void resume() {
postMethod(METHOD_RESUME);
}
@LayoutMode
@@ -311,7 +286,9 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
public void requestFill() {
if (mEnableRequestFill) {
mRequestFill = true;
invalidate();
if (!mWillFill) {
invalidate();
}
}
}
@@ -785,15 +762,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
case METHOD_ON_ATTACH_TO_ROOT:
onAttachToRootInternal();
break;
case METHOD_ON_DETACH_FROM_ROOT:
onDetachFromRootInternal();
break;
case METHOD_PAUSE:
pauseInternal();
break;
case METHOD_RESUME:
resumeInternal();
break;
}
}
@@ -803,6 +771,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
@Override
public void render(GLCanvas canvas) {
mWillFill = true;
int oldCurrentIndex = mCurrentIndex.get();
// Dispatch method
@@ -814,6 +783,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
}
fill();
mWillFill = false;
super.render(canvas);
mEdgeView.render(canvas);
@@ -975,8 +945,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
public abstract void onDataChanged();
public abstract void bindUnloadedPage();
public abstract void onPageLeft();
public abstract void onPageRight();
@@ -208,6 +208,9 @@ public class ImageView extends GLView implements ImageTexture.Callback {
mImageTexture.setCallback(null);
}
int oldTextureWidth = mTextureWidth;
int oldTextureHeight = mTextureHeight;
mImageTexture = imageTexture;
if (imageTexture != null) {
@@ -222,8 +225,9 @@ public class ImageView extends GLView implements ImageTexture.Callback {
mTextureHeight = 1;
}
// Start alpha animation
if (isAttachedToRoot()) {
// Start alpha animation, do not show animation for image has no valid rect
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
}
} else {
@@ -233,6 +237,10 @@ public class ImageView extends GLView implements ImageTexture.Callback {
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
if (oldTextureWidth != mTextureWidth || oldTextureHeight != mTextureHeight) {
requestLayout();
}
}
public ImageTexture getImageTexture() {
@@ -449,9 +449,8 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
image.getScaleDefault(scales);
float scale = image.getScale();
float endScale = scales[0];
for (int i = 0, size = scales.length; i < size; i++) {
float value = scales[i];
if (scale < value) {
for (float value: scales) {
if (scale < value - 0.01f) {
endScale = value;
break;
}
@@ -717,23 +716,6 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
mGalleryView.requestFill();
}
@Override
public void bindUnloadedPage() {
if (null == mAdapter) {
return;
}
if (null != mCurrent && !mCurrent.getImageView().isLoaded()) {
mAdapter.bind(mCurrent, mIndex);
}
if (null != mPrevious && !mPrevious.getImageView().isLoaded()) {
mAdapter.bind(mPrevious, mIndex - 1);
}
if (null != mNext && !mNext.getImageView().isLoaded()) {
mAdapter.bind(mNext, mIndex + 1);
}
}
@Override
public void onPageLeft() {
int size = mAdapter.size();
@@ -22,12 +22,15 @@ import android.support.annotation.NonNull;
import android.util.Log;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.gl.anim.Animation;
import com.hippo.gl.view.GLView;
import com.hippo.gl.widget.GLEdgeView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.MathUtils;
import java.util.Iterator;
import java.util.LinkedList;
@@ -39,7 +42,13 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
private static final int INTERVAL = 24;
private static final float RESERVATIONS = 0.5f;
private static final float RESERVATION = 1f;
private static final float MAX_SCALE = 2.0f;
private static final float MIN_SCALE = 1.0f;
private static final float SCALE_ERROR = 0.01f;
private static final int INVALID_TOP = Integer.MAX_VALUE;
private GalleryView.Adapter mAdapter;
@@ -49,16 +58,22 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
private final LinkedList<GalleryPageView> mPages = new LinkedList<>();
private final LinkedList<GalleryPageView> mTempPages = new LinkedList<>();
private int mOffset;
private float mScale = 0.5f;
private int mOffsetX;
private int mOffsetY;
private int mDeltaX;
private int mDeltaY;
private int mFirstShownLoadedPageIndex = GalleryPageView.INVALID_INDEX;
private int mKeepTopPageIndex = GalleryPageView.INVALID_INDEX;
private int mKeepTop = INVALID_TOP;
private int mFirstShownPageIndex = GalleryPageView.INVALID_INDEX;
private boolean mScrollUp;
private boolean mFlingUp;
private boolean mStopAnimationFinger;
private final int mInterval;
private final PageFling mPageFling;
private final SmoothScaler mSmoothScaler;
// Current index
private int mIndex;
@@ -71,14 +86,20 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
mInterval = LayoutUtils.dp2pix(context, INTERVAL);
mPageFling = new PageFling(context);
mSmoothScaler = new SmoothScaler();
}
private void resetParameters() {
mOffset = 0;
mScale = 1.0f;
mOffsetX = 0;
mOffsetY = 0;
mDeltaX = 0;
mDeltaY = 0;
mFirstShownLoadedPageIndex = GalleryPageView.INVALID_INDEX;
mKeepTopPageIndex = GalleryPageView.INVALID_INDEX;
mKeepTop = INVALID_TOP;
mFirstShownPageIndex = GalleryPageView.INVALID_INDEX;
mScrollUp = false;
mFlingUp = false;
mStopAnimationFinger = false;
}
@@ -166,6 +187,19 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
return null;
}
private boolean isInScreen(GalleryPageView page) {
int height = mGalleryView.getHeight();
Rect bound = page.bounds();
int pageTop = bound.top;
int pageBottom = bound.bottom;
return (pageTop >= 0 && pageTop < height) || (pageBottom > 0 && pageBottom <= height) ||
(pageTop < 0 && pageBottom > height);
}
private float getReservation() {
return Math.max(RESERVATION, (((1 + 2 * RESERVATION) * mScale) - 1) / 2);
}
private void fillPages(int startIndex, int startOffset) {
final GalleryView.Adapter adapter = mAdapter;
final GalleryView galleryView = mGalleryView;
@@ -173,11 +207,13 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
final LinkedList<GalleryPageView> tempPages = mTempPages;
final int width = galleryView.getWidth();
final int height = galleryView.getHeight();
final int pageWidth = (int) (width * mScale);
final int size = adapter.size();
final int interval = mInterval;
final int minY = (int) (-height * RESERVATIONS);
final int maxY = (int) (height * (1 + RESERVATIONS));
final int widthSpec = GLView.MeasureSpec.makeMeasureSpec(width, GLView.MeasureSpec.EXACTLY);
final float reservation = getReservation();
final int minY = (int) (-height * reservation);
final int maxY = (int) (height * (1 + reservation));
final int widthSpec = GLView.MeasureSpec.makeMeasureSpec(pageWidth, GLView.MeasureSpec.EXACTLY);
final int heightSpec = GLView.MeasureSpec.makeMeasureSpec(height, GLView.MeasureSpec.UNSPECIFIED);
// Fix start index and start offset
@@ -241,6 +277,14 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
tempPages.addAll(pages);
pages.clear();
// Sanitize offsetX
int margin = pageWidth - width;
if (margin >= 0) {
mOffsetX = MathUtils.clamp(mOffsetX, -margin, 0);
} else {
mOffsetX = -margin / 2;
}
// Layout start page
GalleryPageView page = getPageForIndex(tempPages, startIndex, true);
if (null == page) {
@@ -250,7 +294,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
}
pages.add(page);
page.measure(widthSpec, heightSpec);
page.layout(0, startOffset, width, startOffset + page.getMeasuredHeight());
page.layout(mOffsetX, startOffset, mOffsetX + pageWidth, startOffset + page.getMeasuredHeight());
// Prepare for check up and down
int bottomOffset = startOffset - interval;
@@ -267,7 +311,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
}
pages.addFirst(page);
page.measure(widthSpec, heightSpec);
page.layout(0, bottomOffset - page.getMeasuredHeight(), width, bottomOffset);
page.layout(mOffsetX, bottomOffset - page.getMeasuredHeight(), mOffsetX + pageWidth, bottomOffset);
// Update
bottomOffset -= page.getMeasuredHeight() + interval;
index--;
@@ -294,7 +338,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
}
pages.addLast(page);
page.measure(widthSpec, heightSpec);
page.layout(0, topOffset, width, topOffset + page.getMeasuredHeight());
page.layout(mOffsetX, topOffset, mOffsetX + pageWidth, topOffset + page.getMeasuredHeight());
// Update
topOffset += page.getMeasuredHeight() + interval;
index++;
@@ -330,7 +374,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
p.offsetTopAndBottom(offset);
}
int bottom = pagesTop - interval + offset;
page.layout(0, bottom - page.getMeasuredHeight(), width, bottom);
page.layout(mOffsetX, bottom - page.getMeasuredHeight(), mOffsetX + pageWidth, bottom);
}
}
@@ -344,7 +388,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
if (!pages.isEmpty()) {
page = pages.getFirst();
mIndex = page.getIndex();
mOffset = page.bounds().top;
mOffsetY = page.bounds().top;
}
}
@@ -354,7 +398,6 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
GalleryView galleryView = mGalleryView;
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", adapter, null);
int height = galleryView.getHeight();
int size = adapter.size();
String errorStr = adapter.getError();
@@ -418,45 +461,49 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
removeAllPages();
}
// Find first shown loaded page top
GalleryPageView firstShownLoadedPage = null;
int firstShownLoadedPageTop = mOffset;
if (mFirstShownLoadedPageIndex != GalleryPageView.INVALID_INDEX) {
// Find keep index and keep top
int keepTop = INVALID_TOP;
int keepTopIndex;
if (GalleryPageView.INVALID_INDEX != mKeepTopPageIndex) {
keepTopIndex = mKeepTopPageIndex;
keepTop = mKeepTop;
} else if (GalleryPageView.INVALID_INDEX != mFirstShownPageIndex) {
keepTopIndex = mFirstShownPageIndex;
} else {
keepTopIndex = GalleryPageView.INVALID_INDEX;
}
if (GalleryPageView.INVALID_INDEX != keepTopIndex && INVALID_TOP == keepTop) {
keepTop = mOffsetY;
for (GalleryPageView page : pages) {
// Check first shown loaded page
if (mFirstShownLoadedPageIndex == page.getIndex()) {
firstShownLoadedPage = page;
// Check keep page
if (keepTopIndex == page.getIndex()) {
break;
}
firstShownLoadedPageTop += page.getHeight() + mInterval;
keepTop += page.getHeight() + mInterval;
}
}
int startIndex;
int startOffset;
if (null != firstShownLoadedPage) {
startIndex = mFirstShownLoadedPageIndex;
startOffset = firstShownLoadedPageTop;
if (GalleryPageView.INVALID_INDEX != keepTopIndex) {
startIndex = keepTopIndex;
startOffset = keepTop;
} else {
startIndex = mIndex;
startOffset = mOffset;
startOffset = mOffsetY;
}
fillPages(startIndex, startOffset);
// Get first shown loaded image
mFirstShownLoadedPageIndex = GalleryPageView.INVALID_INDEX;
// Get first shown image
mFirstShownPageIndex = GalleryPageView.INVALID_INDEX;
for (GalleryPageView page : mPages) {
// Check first shown loaded page
if (!page.isLoaded()) {
if ((mScrollUp || mFlingUp) && !page.isLoaded()) {
continue;
}
Rect bound = page.bounds();
int pageTop = bound.top;
int pageBottom = bound.bottom;
if ((pageTop >= 0 && pageTop < height) || (pageBottom > 0 && pageBottom <= height) ||
(pageTop < 0 && pageBottom > height)) {
mFirstShownLoadedPageIndex = page.getIndex();
if (isInScreen(page)) {
mFirstShownPageIndex = page.getIndex();
break;
}
}
@@ -473,12 +520,25 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public void onUp() {
mScrollUp = false;
mGalleryView.getEdgeView().onRelease();
}
@Override
public void onDoubleTapConfirmed(float x, float y) {
if (mPages.size() <= 0) {
return;
}
float startScale = mScale;
float endScale;
if (startScale < MAX_SCALE - SCALE_ERROR) {
endScale = MAX_SCALE;
} else {
endScale = MIN_SCALE;
}
mSmoothScaler.startSmoothScaler(x, y, startScale, endScale, 300);
}
@Override
@@ -492,7 +552,6 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
mDeltaX += dx;
mDeltaY += dy;
/*
if (mDeltaX < 0) {
edgeView.onPull(-mDeltaX, y, GLEdgeView.LEFT);
if (!edgeView.isFinished(GLEdgeView.RIGHT)) {
@@ -504,7 +563,6 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
edgeView.onRelease(GLEdgeView.LEFT);
}
}
*/
if (mDeltaY < 0) {
edgeView.onPull(-mDeltaY, x, GLEdgeView.TOP);
@@ -521,7 +579,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
private void getBottomState() {
List<GalleryPageView> pages = mPages;
int bottom = mOffset;
int bottom = mOffsetY;
int i = 0;
for (GalleryPageView page : pages) {
if (i != 0) {
@@ -538,49 +596,70 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
// True for get top or bottom
private boolean scrollInternal(float dx, float dy, boolean fling, float x, float y) {
if (mPages.size() == 0) {
if (mPages.size() <= 0) {
return false;
}
GalleryView galleryView = mGalleryView;
int width = galleryView.getWidth();
int height = galleryView.getHeight();
int pageWidth = (int) (width * mScale);
final float reservation = getReservation();
boolean requestFill = false;
int remainY = (int) dy;
boolean result = false;
int margin = pageWidth - width;
int dxInt = (int) dx;
if (margin > 0 && 0 != dxInt) {
int oldOffsetX = mOffsetX;
int exceptOffsetX = oldOffsetX - dxInt;
mOffsetX = MathUtils.clamp(exceptOffsetX, -margin, 0);
if (mOffsetX != oldOffsetX) {
requestFill = true;
}
// Do not show over scroll effect for left and right
/*
int extraOffsetX = mOffsetX - exceptOffsetX;
if (0 != extraOffsetX) {
overScrollEdge(extraOffsetX, 0, x, y);
}
*/
}
int remainY = (int) dy;
while (remainY != 0) {
if (remainY < 0) { // Try to show top
int limit;
if (mIndex > 0) {
limit = (int) (-height * RESERVATIONS) + mInterval;
limit = (int) (-height * reservation) + mInterval;
} else {
limit = 0;
}
if (mOffset - remainY <= limit) {
mOffset -= remainY;
if (mOffsetY - remainY <= limit) {
mOffsetY -= remainY;
remainY = 0;
requestFill = true;
mDeltaX = 0;
mDeltaY = 0;
} else {
if (mIndex > 0) {
mOffset = limit;
remainY = remainY + limit - mOffset;
mOffsetY = limit;
remainY = remainY + limit - mOffsetY;
// Offset one pixel to avoid infinite loop
++mOffset;
++mOffsetY;
++remainY;
galleryView.forceFill();
requestFill = false;
mDeltaX = 0;
mDeltaY = 0;
} else {
if (mOffset != limit) {
mOffset = limit;
if (mOffsetY != limit) {
mOffsetY = limit;
requestFill = true;
}
if (!fling) {
overScrollEdge(0, remainY + limit - mOffset, x, y);
overScrollEdge(0, remainY + limit - mOffsetY, x, y);
}
remainY = 0;
result = true;
@@ -593,7 +672,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
int limit;
if (hasNext) {
limit = (int) (height * (1 + RESERVATIONS)) - mInterval;
limit = (int) (height * (1 + reservation)) - mInterval;
} else {
limit = height;
}
@@ -601,25 +680,25 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
limit = Math.min(bottom, limit);
if (bottom - remainY >= limit) {
mOffset -= remainY;
mOffsetY -= remainY;
remainY = 0;
requestFill = true;
mDeltaX = 0;
mDeltaY = 0;
} else {
if (hasNext) {
mOffset -= bottom - limit;
mOffsetY -= bottom - limit;
remainY = remainY + limit - bottom;
// Offset one pixel to avoid infinite loop
--mOffset;
--mOffsetY;
--remainY;
galleryView.forceFill();
requestFill = false;
mDeltaX = 0;
mDeltaY = 0;
} else {
if (mOffset != limit) {
mOffset -= bottom - limit;
if (mOffsetY != limit) {
mOffsetY -= bottom - limit;
requestFill = true;
}
if (!fling) {
@@ -641,6 +720,8 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public void onScroll(float dx, float dy, float totalX, float totalY, float x, float y) {
mKeepTopPageIndex = GalleryPageView.INVALID_INDEX;
mKeepTop = INVALID_TOP;
mScrollUp = dy < 0;
scrollInternal(dx, dy, false, x, y);
}
@@ -651,13 +732,28 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
return;
}
mScrollUp = velocityY > 0;
mKeepTopPageIndex = GalleryPageView.INVALID_INDEX;
mKeepTop = INVALID_TOP;
mFlingUp = velocityY > 0;
int maxX;
int minX;
int width = mGalleryView.getWidth();
int pageWidth = (int) (width * mScale);
int margin = pageWidth - width;
if (margin > 0) {
maxX = -mOffsetX;
minX = -margin + mOffsetX;
} else {
maxX = 0;
minX = 0;
}
int maxY;
if (mIndex > 0) {
maxY = Integer.MAX_VALUE;
} else {
maxY = -mOffset;
maxY = -mOffsetY;
}
getBottomState();
@@ -670,23 +766,66 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
minY = mGalleryView.getHeight() - bottom;
}
mPageFling.startFling((int) velocityX, 0, 0,
mPageFling.startFling((int) velocityX, minX, maxX,
(int) velocityY, minY, maxY);
}
@Override
public boolean canScale() {
return false;
return mPages.size() > 0;
}
@Override
public void onScale(float focusX, float focusY, float scale) {
if (mPages.isEmpty()) {
return;
}
float oldScale = mScale;
mScale = MathUtils.clamp(oldScale * scale, MIN_SCALE, MAX_SCALE);
scale = mScale / oldScale;
if (oldScale != mScale) {
GalleryPageView page = null;
// Keep scale page origin position
for (GalleryPageView p : mPages) {
if (p.bounds().top < focusY) {
page = p;
} else {
break;
}
}
if (null != page) {
mKeepTopPageIndex = page.getIndex();
mKeepTop = page.bounds().top;
mGalleryView.forceFill();
int oldKeepTop = mKeepTop;
mKeepTop = INVALID_TOP;
// Apply scroll
int newOffsetX = (int) (focusX - ((focusX - mOffsetX) * scale));
int newKeepTop;
if (page.isLoaded()) {
newKeepTop = (int) (focusY - ((focusY - oldKeepTop) * scale));
} else {
newKeepTop = oldKeepTop;
}
scrollInternal(mOffsetX - newOffsetX, oldKeepTop - newKeepTop, false, focusX, focusY);
} else {
Log.e(TAG, "Can't find target page");
mKeepTopPageIndex = GalleryPageView.INVALID_INDEX;
mKeepTop = INVALID_TOP;
mGalleryView.forceFill();
}
}
}
@Override
public boolean onUpdateAnimation(long time) {
boolean invalidate = mPageFling.calculate(time);
invalidate |= mSmoothScaler.calculate(time);
return invalidate;
}
@@ -705,21 +844,6 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
mGalleryView.requestFill();
}
@Override
public void bindUnloadedPage() {
if (null == mAdapter || 0 <= mPages.size()) {
return;
}
int index = mIndex;
for (GalleryPageView page: mPages) {
if (!page.getImageView().isLoaded()) {
mAdapter.bind(page, index);
}
index++;
}
}
@Override
public void onPageLeft() {
int size = mAdapter.size();
@@ -727,8 +851,11 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
return;
}
///////
// UP
///////
GalleryView galleryView = mGalleryView;
if (mIndex == 0 && mOffset >= 0) {
if (mIndex == 0 && mOffsetY >= 0) {
GLEdgeView edgeView = galleryView.getEdgeView();
edgeView.onPull(galleryView.getHeight(),
galleryView.getWidth() / 2, GLEdgeView.TOP);
@@ -736,13 +863,37 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
} else {
// Cancel all animations
cancelAllAnimations();
mOffset += galleryView.getHeight() / 2;
// Backup offset
int offset = mOffset;
// Reset parameters
resetParameters();
// Restore offset
mOffset = offset;
// Get first shown page
GalleryPageView previousPage = null;
GalleryPageView firstShownPage = null;
for (GalleryPageView p: mPages) {
if (isInScreen(p)) {
firstShownPage = p;
break;
}
previousPage = p;
}
int height = galleryView.getHeight();
int maxOffset = height - mInterval;
if (null == firstShownPage) {
Log.e(TAG, "Can't find first shown page when paging left");
mOffsetY += height / 2;
} else {
int firstShownTop = firstShownPage.bounds().top;
if (firstShownTop >= 0) {
if (null == previousPage) {
Log.e(TAG, "Can't find previous page when paging left and offsetY == 0");
mOffsetY += height / 2;
} else {
mOffsetY += Math.min(maxOffset, -previousPage.bounds().top);
}
} else {
mOffsetY += Math.min(maxOffset, -firstShownTop);
}
}
// Request fill
mGalleryView.requestFill();
}
@@ -755,6 +906,9 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
return;
}
/////////
// DOWN
/////////
GalleryView galleryView = mGalleryView;
getBottomState();
int bottom = mBottomStateBottom;
@@ -767,13 +921,38 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
} else {
// Cancel all animations
cancelAllAnimations();
mOffset -= galleryView.getHeight() / 2;
// Backup offset
int offset = mOffset;
// Reset parameters
resetParameters();
// Restore offset
mOffset = offset;
// Get first shown page
GalleryPageView lastShownPage = null;
GalleryPageView nextPage = null;
for (GalleryPageView p: mPages) {
if (isInScreen(p)) {
lastShownPage = p;
} else if (null != lastShownPage) {
nextPage = p;
break;
}
}
int height = galleryView.getHeight();
int maxOffset = height - mInterval;
if (null == lastShownPage) {
Log.e(TAG, "Can't find last shown page when paging left");
mOffsetY -= height / 2;
} else {
int lastShownBottom = lastShownPage.bounds().bottom;
if (lastShownBottom <= height) {
if (null == nextPage) {
Log.e(TAG, "Can't find previous page when paging left and offsetY == 0");
mOffsetY -= height / 2;
} else {
mOffsetY -= Math.min(maxOffset, nextPage.bounds().bottom - height);
}
} else {
mOffsetY -= Math.min(maxOffset, lastShownBottom - height);
}
}
// Request fill
mGalleryView.requestFill();
}
@@ -796,13 +975,8 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public int getCurrentIndex() {
int height = mGalleryView.getHeight();
for (GalleryPageView page : mPages) {
Rect bound = page.bounds();
int pageTop = bound.top;
int pageBottom = bound.bottom;
if ((pageTop >= 0 && pageTop < height) || (pageBottom > 0 && pageBottom <= height) ||
(pageTop < 0 && pageBottom > height)) {
if (isInScreen(page)) {
return page.getIndex();
}
}
@@ -816,9 +990,13 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
// Can't get size now, assume size is MAX
size = Integer.MAX_VALUE;
}
if (index == mIndex || index < 0 || index >= size) {
if (index < 0 || index >= size) {
return;
}
mKeepTopPageIndex = index;
mKeepTop = INVALID_TOP;
if (mPages.isEmpty()) {
mIndex = index;
} else {
@@ -834,25 +1012,18 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
if (targetPage != null) {
// Cancel all animations
cancelAllAnimations();
mOffset -= targetPage.bounds().top;
// Backup offset
int offset = mOffset;
// Reset parameters
resetParameters();
// Restore offset
mOffset = offset;
mOffsetY -= targetPage.bounds().top;
// Request fill
mGalleryView.requestFill();
} else {
mIndex = index;
mOffsetY = 0;
// Cancel all animations
cancelAllAnimations();
// Remove all view
removeProgress();
removeErrorView();
removeAllPages();
// Reset parameters
resetParameters();
// Request fill
mGalleryView.requestFill();
}
@@ -884,7 +1055,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
return currentIndex;
}
class PageFling extends Fling {
private class PageFling extends Fling {
private int mVelocityX;
private int mVelocityY;
@@ -950,9 +1121,11 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
protected void onFinish() {
mFlingUp = false;
int index = mIndex;
boolean topEdge = index <= 0 && mOffset >= 0;
boolean topEdge = index <= 0 && mOffsetY >= 0;
getBottomState();
int bottom = mBottomStateBottom;
@@ -971,4 +1144,40 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
}
}
}
private class SmoothScaler extends Animation {
private float mFocusX;
private float mFocusY;
private float mStartScale;
private float mEndScale;
private float mLastScale;
public SmoothScaler() {
setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
}
public void startSmoothScaler(float focusX, float focusY,
float startScale, float endScale, int duration) {
mFocusX = focusX;
mFocusY = focusY;
mStartScale = startScale;
mEndScale = endScale;
mLastScale = startScale;
setDuration(duration);
start();
mGalleryView.invalidate();
}
@Override
protected void onCalculate(float progress) {
if (mPages.size() <= 0) {
return;
}
float scale = MathUtils.lerp(mStartScale, mEndScale, progress);
onScale(mFocusX, mFocusY, scale / mLastScale);
mLastScale = scale;
}
}
}
@@ -0,0 +1,116 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.NumberUtils;
public class CleanRedundancyPreference extends TaskPreference {
public CleanRedundancyPreference(Context context) {
super(context);
}
public CleanRedundancyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CleanRedundancyPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@NonNull
@Override
protected Task onCreateTask() {
return new ClearTask(getContext());
}
private static class ClearTask extends Task {
private final EhApplication mApplication;
private final DownloadManager mManager;
public ClearTask(@NonNull Context context) {
super(context);
mApplication = (EhApplication) context.getApplicationContext();
mManager = EhApplication.getDownloadManager(mApplication);
}
// True for cleared
private boolean clearFile(UniFile file) {
String name = file.getName();
int index = name.indexOf('-');
if (index >= 0) {
name = name.substring(0, index);
}
long gid = NumberUtils.parseLongSafely(name, -1L);
if (-1L == gid) {
return false;
}
if (mManager.containDownloadInfo(gid)) {
return false;
}
file.delete();
return true;
}
@Override
protected Object doInBackground(Void... params) {
UniFile dir = Settings.getDownloadLocation();
if (null == dir) {
return 0;
}
UniFile[] files = dir.listFiles();
if (null == files) {
return 0;
}
int count = 0;
for (UniFile f: files) {
if (clearFile(f)) {
++count;
}
}
return count;
}
@Override
protected void onPostExecute(Object o) {
int count;
if (o instanceof Integer) {
count = (Integer) o;
} else {
count = 0;
}
Toast.makeText(mApplication, 0 == count ?
mApplication.getString(R.string.settings_download_clean_redundancy_no_redundancy):
mApplication.getString(R.string.settings_download_clean_redundancy_done, count), Toast.LENGTH_SHORT).show();
super.onPostExecute(o);
}
}
}
@@ -42,12 +42,6 @@ public class ClearDownloadPathCachePreference extends MessagePreference {
init(context);
}
public ClearDownloadPathCachePreference(Context context,
AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
public void init(Context context) {
setDialogMessage(context.getString(R.string.settings_advanced_clear_download_path_cache_message));
}
@@ -47,11 +47,6 @@ public class DefaultCategoryPreference extends DialogPreference {
init();
}
public DefaultCategoryPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setDialogLayoutResource(R.layout.preference_dialog_default_categories);
}
@@ -69,11 +69,6 @@ public class ExcludedTagNamespacesPreference extends DialogPreference {
init();
}
public ExcludedTagNamespacesPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setDialogLayoutResource(R.layout.preference_dialog_excluded_tag_namespaces);
}
@@ -66,11 +66,6 @@ public class HatHProxyPreference extends DialogPreference implements View.OnClic
init();
}
public HatHProxyPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setDialogLayoutResource(R.layout.preference_dialog_hath_proxy);
updateSummary(Settings.getHathProxy(), Settings.getHathIp(), Settings.getHathPort());
@@ -42,11 +42,6 @@ public class SignOutPreference extends MessagePreference {
init();
}
public SignOutPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setDialogMessage(getContext().getString(R.string.settings_eh_sign_out_warning));
}
@@ -34,6 +34,7 @@ import com.hippo.unifile.FilenameFilter;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Utilities;
import com.hippo.yorozuya.io.InputStreamPipe;
import com.hippo.yorozuya.io.OutputStreamPipe;
@@ -54,7 +55,8 @@ public final class SpiderDen {
private static SimpleDiskCache sCache;
public static void initialize(Context context) {
sCache = new SimpleDiskCache(new File(context.getCacheDir(), "image"), 160 * 1024 * 1024);
sCache = new SimpleDiskCache(new File(context.getCacheDir(), "image"),
MathUtils.clamp(Settings.getReadCacheSize(), 40, 640) * 1024 * 1024);
}
private static class StartWithFilenameFilter implements FilenameFilter {
@@ -18,6 +18,7 @@ package com.hippo.ehviewer.spider;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
@@ -102,6 +103,10 @@ public class SpiderInfo {
spiderInfo.previewPerPage = Integer.parseInt(IOUtils.readAsciiLine(is));
// Pages
spiderInfo.pages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Check pages
if (spiderInfo.pages <= 0) {
return null;
}
// PToken
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
while (true) { // EOFException will raise
@@ -110,7 +115,9 @@ public class SpiderInfo {
if (pos > 0 || pos < line.length() - 1) {
int index = Integer.parseInt(line.substring(0, pos));
String pToken = line.substring(pos + 1);
spiderInfo.pTokenMap.put(index, pToken);
if (!TextUtils.isEmpty(pToken)) {
spiderInfo.pTokenMap.put(index, pToken);
}
} else {
Log.e(TAG, "Can't parse index and pToken, index = " + pos);
}
@@ -147,12 +154,14 @@ public class SpiderInfo {
writer.write(Integer.toString(pages));
writer.write("\n");
for (int i = 0; i < pTokenMap.size(); i++) {
if (TOKEN_FAILED.equals(pTokenMap.valueAt(i))) {
Integer key = pTokenMap.keyAt(i);
String value = pTokenMap.valueAt(i);
if (TOKEN_FAILED.equals(value) || TextUtils.isEmpty(value)) {
continue;
}
writer.write(Integer.toString(pTokenMap.keyAt(i)));
writer.write(Integer.toString(key));
writer.write(" ");
writer.write(pTokenMap.valueAt(i));
writer.write(value);
writer.write("\n");
}
writer.flush();
@@ -35,6 +35,7 @@ import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhRequestBuilder;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.GalleryInfo;
@@ -48,6 +49,7 @@ import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
@@ -64,7 +66,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@@ -421,11 +422,11 @@ public class SpiderQueen implements Runnable {
}
public Object forceRequest(int index) {
return request(index, true);
return request(index, true, false);
}
public Object request(int index) {
return request(index, false);
return request(index, false, true);
}
private int getPageState(int index) {
@@ -471,7 +472,7 @@ public class SpiderQueen implements Runnable {
* Float for download percent<br>
* null for wait
*/
private Object request(int index, boolean force) {
private Object request(int index, boolean force, boolean addNeighbor) {
if (mQueenThread == null) {
return null;
}
@@ -494,8 +495,8 @@ public class SpiderQueen implements Runnable {
}
}
// For not force add, add next some pages to request queue
if (!force) {
// Add next some pages to request queue
if (addNeighbor) {
mRequestPageQueue2.clear();
int[] pageStateArray = mPageStateArray;
int size;
@@ -905,6 +906,55 @@ public class SpiderQueen implements Runnable {
}
}
private void updatePageState(int index, @State int state) {
updatePageState(index, state, null);
}
private boolean isStateDone(int state) {
return state == STATE_FINISHED || state == STATE_FAILED;
}
private void updatePageState(int index, @State int state, String error) {
int oldState;
synchronized (mPageStateLock) {
oldState = mPageStateArray[index];
mPageStateArray[index] = state;
if (!isStateDone(oldState) && isStateDone(state)) {
mDownloadedPages.incrementAndGet();
} else if (isStateDone(oldState) && !isStateDone(state)) {
mDownloadedPages.decrementAndGet();
}
if (oldState != STATE_FINISHED && state == STATE_FINISHED) {
mFinishedPages.incrementAndGet();
} else if (oldState == STATE_FINISHED && state != STATE_FINISHED) {
mFinishedPages.decrementAndGet();
}
// Clear
if (state == STATE_DOWNLOADING) {
mPageErrorMap.remove(index);
} else if (state == STATE_FINISHED || state == STATE_FAILED) {
mPagePercentMap.remove(index);
}
// Get default error
if (state == STATE_FAILED) {
if (error == null) {
error = GetText.getString(R.string.error_unknown);
}
mPageErrorMap.put(index, error);
}
}
// Notify listeners
if (state == STATE_FAILED) {
notifyPageFailure(index, error);
} else if (state == STATE_FINISHED) {
notifyPageSuccess(index);
}
}
private class SpiderWorker implements Runnable {
private final long mGid;
@@ -913,67 +963,14 @@ public class SpiderQueen implements Runnable {
mGid = mGalleryInfo.gid;
}
private void updatePageState(int index, @State int state) {
updatePageState(index, state, null);
}
private boolean isStateDone(int state) {
return state == STATE_FINISHED || state == STATE_FAILED;
}
private void updatePageState(int index, @State int state, String error) {
int oldState;
synchronized (mPageStateLock) {
oldState = mPageStateArray[index];
mPageStateArray[index] = state;
if (!isStateDone(oldState) && isStateDone(state)) {
mDownloadedPages.incrementAndGet();
} else if (isStateDone(oldState) && !isStateDone(state)) {
mDownloadedPages.decrementAndGet();
}
if (oldState != STATE_FINISHED && state == STATE_FINISHED) {
mFinishedPages.incrementAndGet();
} else if (oldState == STATE_FINISHED && state != STATE_FINISHED) {
mFinishedPages.decrementAndGet();
}
// Clear
if (state == STATE_DOWNLOADING) {
mPageErrorMap.remove(index);
} else if (state == STATE_FINISHED || state == STATE_FAILED) {
mPagePercentMap.remove(index);
}
// Get default error
if (state == STATE_FAILED) {
if (error == null) {
error = GetText.getString(R.string.error_unknown);
}
mPageErrorMap.put(index, error);
}
}
// Notify listeners
if (state == STATE_FAILED) {
notifyPageFailure(index, error);
} else if (state == STATE_FINISHED) {
notifyPageSuccess(index);
}
}
private GalleryPageParser.Result getImageUrl(long gid, int index, String pToken,
String skipHathKey) throws IOException, ParseException, Image509Exception {
String skipHathKey) throws Exception {
String url = EhUrl.getPageUrl(gid, index, pToken);
if (skipHathKey != null) {
url = url + "?nl=" + skipHathKey;
}
if (DEBUG_LOG) {
Log.d(TAG, url);
}
Response response = mHttpClient.newCall(new EhRequestBuilder(url).build()).execute();
String body = response.body().string();
GalleryPageParser.Result result = GalleryPageParser.parse(body);
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, url);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
@@ -993,17 +990,18 @@ public class SpiderQueen implements Runnable {
// Try twice
for (int i = 0; i < 2; i++) {
if (i > 0 && TextUtils.isEmpty(skipHathKey)) {
// No need to get image url twice without skip hath key
break;
}
GalleryPageParser.Result result = null;
try {
result = getImageUrl(gid, index, pToken, skipHathKey);
} catch (MalformedURLException e) {
error = GetText.getString(R.string.error_invalid_url);
} catch (IOException e) {
error = GetText.getString(R.string.error_socket);
} catch (ParseException e) {
error = GetText.getString(R.string.error_parse_error);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Exception e) {
error = ExceptionUtils.getReadableString(e);
}
if (result == null) {
// Get image url failed
@@ -1179,7 +1177,7 @@ public class SpiderQueen implements Runnable {
int i = mSpiderInfo.pTokenMap.indexOfKey(index);
String pToken = mSpiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
mSpiderInfo.pTokenMap.setValueAt(i, null);
mSpiderInfo.pTokenMap.remove(i);
}
}
}
@@ -1294,7 +1292,10 @@ public class SpiderQueen implements Runnable {
InputStreamPipe pipe = mSpiderDen.openInputStreamPipe(index);
if (pipe == null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_not_found));
// Can't find the file, it might be removed from cache,
// Reset it state and request it
updatePageState(index, STATE_NONE, null);
request(index, false, false);
continue;
}
@@ -117,7 +117,7 @@ public final class CommonOperations {
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UrlOpener.openUrl(mActivity, url, false, false);
UrlOpener.openUrl(mActivity, url, false);
}
}).show();
}
@@ -309,4 +309,15 @@ public final class CommonOperations {
IOUtils.closeQuietly(is);
}
}
public static void removeNoMediaFile(UniFile file) {
if (null == file) {
return;
}
UniFile noMedia = file.subFile(".nomedia");
if (null != noMedia && noMedia.isFile()) {
noMedia.delete();
}
}
}
@@ -0,0 +1,106 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.ViewUtils;
public class DictActivity extends ToolbarActivity {
private static final int REQUEST_CODE_SELECT_DICT_FILE = 0;
@Nullable
private EasyRecyclerView mRecyclerView;
@Nullable
private ViewTransition mViewTransition;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(this, R.id.recycler_view);
TextView tip = (TextView) ViewUtils.$$(this, R.id.tip);
mViewTransition = new ViewTransition(mRecyclerView, tip);
}
@Override
protected void onDestroy() {
super.onDestroy();
mRecyclerView = null;
mViewTransition = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_dict, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_import:
Intent intent = new Intent();
intent.setType("application/octet-stream");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getString(R.string.select_dict_file)), REQUEST_CODE_SELECT_DICT_FILE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (REQUEST_CODE_SELECT_DICT_FILE == requestCode) {
if (Activity.RESULT_OK != resultCode) {
return;
}
Uri uri = data.getData();
if (null == uri) {
return;
}
Intent intent = new Intent(this, DictImportActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
@@ -0,0 +1,213 @@
package com.hippo.ehviewer.ui;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hippo.dict.DictImportService;
import com.hippo.ehviewer.R;
import com.hippo.util.TextUrl;
public class DictImportActivity extends EhActivity {
private final static String TAG = "DictImportActivity";
private static final boolean DEBUG = false;
private DictImportService serviceBinder;
private int mItemNum = 0;
private Button mConfirmBtn;
private Button mCancelBtn;
private Button mHideBtn;
private ProgressBar mProgressBar;
private TextView mProgressTipView;
private TextView mTipView;
private Uri mDictUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict_improt);
Intent intent = new Intent(DictImportActivity.this, DictImportService.class);
if (DEBUG) {
Log.d(TAG, "[onCreate] bind service");
}
bindService(intent, conn, Context.BIND_AUTO_CREATE);
startService(intent);
mConfirmBtn = (Button) findViewById(R.id.btn_confirm);
mCancelBtn = (Button) findViewById(R.id.btn_cancel);
mHideBtn = (Button) findViewById(R.id.btn_hide);
mProgressBar = (ProgressBar) findViewById(R.id.bar_import);
mProgressTipView = (TextView) findViewById(R.id.tv_progress);
mTipView = (TextView) findViewById(R.id.tv_tip);
mConfirmBtn.setOnClickListener(confirmListener);
mCancelBtn.setOnClickListener(cancelListener);
mHideBtn.setOnClickListener(hideListener);
}
private final ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG) {
Log.w(TAG, "[onServiceConnected] disconnect to service");
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceBinder = ((DictImportService.DictImportServiceBinder) service).getService();
serviceBinder.setOnProgressListener(importListener);
// if we are doing a task,we load improt infomation from service
// and ignore the newer import task
if (serviceBinder.isRunning()) {
initFromService();
} else {
initFromIntent();
}
if (DEBUG) {
Log.d(TAG, "[onServiceConnected] connect to service");
}
}
};
private final DictImportService.ProcessListener importListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.i(TAG, "[process] " + progress);
}
mProgressBar.setProgress(progress);
mProgressTipView.setText(progress + "/" + mItemNum);
}
@Override
public void processTotal(int total) {
mItemNum = total;
mProgressBar.setMax(mItemNum);
}
@Override
public void processComplete() {
mCancelBtn.setText(getResources().getString(R.string.done));
mHideBtn.setVisibility(View.GONE);
}
};
private final View.OnClickListener cancelListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
DictImportActivity.this.finish();
}
};
private final View.OnClickListener abortListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] abort");
}
if (serviceBinder != null) {
serviceBinder.abortImport();
}
DictImportActivity.this.finish();
}
};
private final View.OnClickListener confirmListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] confirm");
}
if (serviceBinder == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] service is not connected");
}
return;
}
if (mDictUri == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] mDictUri is not be init");
}
return;
}
serviceBinder.importDict(mDictUri);
view.setVisibility(View.GONE);
mCancelBtn.setOnClickListener(abortListener);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
}
};
private final View.OnClickListener hideListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] hide");
}
DictImportActivity.this.finish();
}
};
@Override
protected void onDestroy() {
serviceBinder.removeOnProgressListener(importListener);
unbindService(conn);
super.onDestroy();
}
private void initFromService() {
mDictUri = serviceBinder.getUri();
if (mDictUri == null) {
if (DEBUG) {
Log.e(TAG, "[initFromService] error use of initFromService,you may use initFromIntent instead");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[initFromService] " + mDictUri.toString());
}
mItemNum = serviceBinder.getItemNum();
mProgressBar.setMax(mItemNum);
mConfirmBtn.setVisibility(View.GONE);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
mCancelBtn.setOnClickListener(abortListener);
}
private void initFromIntent() {
mDictUri = getIntent().getData();
if (DEBUG) {
Log.d(TAG, "[initFromIntent] " + mDictUri.toString());
}
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
}
}
@@ -16,10 +16,8 @@
package com.hippo.ehviewer.ui;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@@ -29,7 +27,7 @@ import android.widget.TextView;
import android.widget.Toast;
import com.hippo.ehviewer.R;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.widget.DirExplorer;
import com.hippo.yorozuya.ViewUtils;
@@ -52,7 +50,6 @@ public class DirPickerActivity extends ToolbarActivity
@Nullable
private View mOk;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -73,7 +70,7 @@ public class DirPickerActivity extends ToolbarActivity
mDirExplorer.setCurrentFile(file);
mDirExplorer.setOnChangeDirListener(this);
RippleSalon.addRipple(mOk, false);
Ripple.addRipple(mOk, false);
mOk.setOnClickListener(this);
@@ -30,7 +30,7 @@ import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.widget.SensitiveCheckBox;
import com.hippo.yorozuya.ViewUtils;
@@ -163,11 +163,11 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
mDeselectAll.setOnClickListener(this);
mInvertSelection.setOnClickListener(this);
RippleSalon.addRipple(mCancel, false);
RippleSalon.addRipple(mOk, false);
RippleSalon.addRipple(mSelectAll, false);
RippleSalon.addRipple(mDeselectAll, false);
RippleSalon.addRipple(mInvertSelection, false);
Ripple.addRipple(mCancel, false);
Ripple.addRipple(mOk, false);
Ripple.addRipple(mSelectAll, false);
Ripple.addRipple(mDeselectAll, false);
Ripple.addRipple(mInvertSelection, false);
}
private boolean isDecimal(String str) {
@@ -85,6 +85,7 @@ public class GalleryActivity extends EhActivity
public static final String KEY_ACTION = "action";
public static final String KEY_FILENAME = "filename";
public static final String KEY_URI = "uri";
public static final String KEY_GALLERY_INFO = "gallery_info";
public static final String KEY_PAGE = "page";
public static final String KEY_CURRENT_INDEX = "current_index";
@@ -94,6 +95,7 @@ public class GalleryActivity extends EhActivity
private String mAction;
private String mFilename;
private Uri mUri;
private GalleryInfo mGalleryInfo;
private int mPage;
@@ -114,6 +116,8 @@ public class GalleryActivity extends EhActivity
@Nullable
private View mClock;
@Nullable
private TextView mProgress;
@Nullable
private View mBattery;
@Nullable
private View mSeekBarPanel;
@@ -184,6 +188,11 @@ public class GalleryActivity extends EhActivity
if (mGalleryInfo != null) {
mGalleryProvider = new EhGalleryProvider(this, mGalleryInfo);
}
} else if (Intent.ACTION_VIEW.equals(mAction)) {
if (mUri != null) {
// Only support zip now
mGalleryProvider = new ZipGalleryProvider(new File(mUri.getPath()));
}
}
}
@@ -195,6 +204,7 @@ public class GalleryActivity extends EhActivity
mAction = intent.getAction();
mFilename = intent.getStringExtra(KEY_FILENAME);
mUri = intent.getData();
mGalleryInfo = intent.getParcelableExtra(KEY_GALLERY_INFO);
mPage = intent.getIntExtra(KEY_PAGE, -1);
buildProvider();
@@ -203,6 +213,7 @@ public class GalleryActivity extends EhActivity
private void onRestore(@NonNull Bundle savedInstanceState) {
mAction = savedInstanceState.getString(KEY_ACTION);
mFilename = savedInstanceState.getString(KEY_FILENAME);
mUri= savedInstanceState.getParcelable(KEY_URI);
mGalleryInfo = savedInstanceState.getParcelable(KEY_GALLERY_INFO);
mPage = savedInstanceState.getInt(KEY_PAGE, -1);
mCurrentIndex = savedInstanceState.getInt(KEY_CURRENT_INDEX);
@@ -214,6 +225,7 @@ public class GalleryActivity extends EhActivity
super.onSaveInstanceState(outState);
outState.putString(KEY_ACTION, mAction);
outState.putString(KEY_FILENAME, mFilename);
outState.putParcelable(KEY_URI, mUri);
if (mGalleryInfo != null) {
outState.putParcelable(KEY_GALLERY_INFO, mGalleryInfo);
}
@@ -223,6 +235,14 @@ public class GalleryActivity extends EhActivity
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (Settings.getReadingFullscreen() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
@@ -256,21 +276,25 @@ public class GalleryActivity extends EhActivity
glRootView.setContentPane(mGalleryView);
// System UI helper
int systemUiLevel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
systemUiLevel = SystemUiHelper.LEVEL_IMMERSIVE;
} else {
systemUiLevel = SystemUiHelper.LEVEL_HIDE_STATUS_BAR;
if (Settings.getReadingFullscreen()) {
int systemUiLevel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
systemUiLevel = SystemUiHelper.LEVEL_IMMERSIVE;
} else {
systemUiLevel = SystemUiHelper.LEVEL_HIDE_STATUS_BAR;
}
mSystemUiHelper = new SystemUiHelper(this, systemUiLevel,
SystemUiHelper.FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES | SystemUiHelper.FLAG_IMMERSIVE_STICKY);
mSystemUiHelper.hide();
mShowSystemUi = false;
}
mSystemUiHelper = new SystemUiHelper(this, systemUiLevel,
SystemUiHelper.FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES | SystemUiHelper.FLAG_IMMERSIVE_STICKY);
mSystemUiHelper.hide();
mShowSystemUi = false;
mMaskView = (ColorView) ViewUtils.$$(this, R.id.mask);
mClock = ViewUtils.$$(this, R.id.clock);
mProgress = (TextView) ViewUtils.$$(this, R.id.progress);
mBattery = ViewUtils.$$(this, R.id.battery);
mClock.setVisibility(Settings.getShowClock() ? View.VISIBLE : View.GONE);
mProgress.setVisibility(Settings.getShowProgress() ? View.VISIBLE : View.GONE);
mBattery.setVisibility(Settings.getShowBattery() ? View.VISIBLE : View.GONE);
mSeekBarPanel = ViewUtils.$$(this, R.id.seek_bar_panel);
@@ -332,6 +356,7 @@ public class GalleryActivity extends EhActivity
mMaskView = null;
mClock = null;
mProgress = null;
mBattery = null;
mSeekBarPanel = null;
mLeftText = null;
@@ -341,24 +366,6 @@ public class GalleryActivity extends EhActivity
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
}
@Override
protected void onPause() {
super.onPause();
if (null != mGalleryView) {
mGalleryView.pause();
}
}
@Override
protected void onResume() {
super.onResume();
if (null != mGalleryView) {
mGalleryView.resume();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
@@ -465,6 +472,18 @@ public class GalleryActivity extends EhActivity
}
}
@SuppressLint("SetTextI18n")
private void updateProgress() {
if (mProgress == null) {
return;
}
if (mSize <= 0 || mCurrentIndex < 0) {
mProgress.setText(null);
} else {
mProgress.setText((mCurrentIndex + 1) + "/" + mSize);
}
}
@SuppressLint("SetTextI18n")
private void updateSlider() {
if (mSeekBar == null || mRightText == null || mLeftText == null || mSize <= 0 || mCurrentIndex < 0) {
@@ -717,8 +736,10 @@ public class GalleryActivity extends EhActivity
private final Spinner mStartPosition;
private final SwitchCompat mKeepScreenOn;
private final SwitchCompat mShowClock;
private final SwitchCompat mShowProgress;
private final SwitchCompat mShowBattery;
private final SwitchCompat mVolumePage;
private final SwitchCompat mReadingFullscreen;
private final SwitchCompat mCustomScreenLightness;
private final SeekBar mScreenLightness;
@@ -731,8 +752,10 @@ public class GalleryActivity extends EhActivity
mStartPosition = (Spinner) mView.findViewById(R.id.start_position);
mKeepScreenOn = (SwitchCompat) mView.findViewById(R.id.keep_screen_on);
mShowClock = (SwitchCompat) mView.findViewById(R.id.show_clock);
mShowProgress = (SwitchCompat) mView.findViewById(R.id.show_progress);
mShowBattery = (SwitchCompat) mView.findViewById(R.id.show_battery);
mVolumePage = (SwitchCompat) mView.findViewById(R.id.volume_page);
mReadingFullscreen = (SwitchCompat) mView.findViewById(R.id.reading_fullscreen);
mCustomScreenLightness = (SwitchCompat) mView.findViewById(R.id.custom_screen_lightness);
mScreenLightness = (SeekBar) mView.findViewById(R.id.screen_lightness);
@@ -742,8 +765,10 @@ public class GalleryActivity extends EhActivity
mStartPosition.setSelection(Settings.getStartPosition());
mKeepScreenOn.setChecked(Settings.getKeepScreenOn());
mShowClock.setChecked(Settings.getShowClock());
mShowProgress.setChecked(Settings.getShowProgress());
mShowBattery.setChecked(Settings.getShowBattery());
mVolumePage.setChecked(Settings.getVolumePage());
mReadingFullscreen.setChecked(Settings.getReadingFullscreen());
mCustomScreenLightness.setChecked(Settings.getCustomScreenLightness());
mScreenLightness.setProgress(Settings.getScreenLightness());
mScreenLightness.setEnabled(Settings.getCustomScreenLightness());
@@ -768,19 +793,25 @@ public class GalleryActivity extends EhActivity
int startPosition = ImageView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
boolean keepScreenOn = mKeepScreenOn.isChecked();
boolean showClock = mShowClock.isChecked();
boolean showProgress = mShowProgress.isChecked();
boolean showBattery = mShowBattery.isChecked();
boolean volumePage = mVolumePage.isChecked();
boolean readingFullscreen = mReadingFullscreen.isChecked();
boolean customScreenLightness = mCustomScreenLightness.isChecked();
int screenLightness = mScreenLightness.getProgress();
boolean oldReadingFullscreen = Settings.getReadingFullscreen();
Settings.putScreenRotation(screenRotation);
Settings.putReadingDirection(layoutMode);
Settings.putPageScaling(scaleMode);
Settings.putStartPosition(startPosition);
Settings.putKeepScreenOn(keepScreenOn);
Settings.putShowClock(showClock);
Settings.putShowProgress(showProgress);
Settings.putShowBattery(showBattery);
Settings.putVolumePage(volumePage);
Settings.putReadingFullscreen(readingFullscreen);
Settings.putCustomScreenLightness(customScreenLightness);
Settings.putScreenLightness(screenLightness);
@@ -811,6 +842,9 @@ public class GalleryActivity extends EhActivity
if (mClock != null) {
mClock.setVisibility(showClock ? View.VISIBLE : View.GONE);
}
if (mProgress != null) {
mProgress.setVisibility(showProgress ? View.VISIBLE : View.GONE);
}
if (mBattery != null) {
mBattery.setVisibility(showBattery ? View.VISIBLE : View.GONE);
}
@@ -819,6 +853,10 @@ public class GalleryActivity extends EhActivity
// Update slider
mLayoutMode = layoutMode;
updateSlider();
if (oldReadingFullscreen != readingFullscreen) {
recreate();
}
}
}
@@ -953,10 +991,12 @@ public class GalleryActivity extends EhActivity
case KEY_SIZE:
GalleryActivity.this.mSize = mValue;
updateSlider();
updateProgress();
break;
case KEY_CURRENT_INDEX:
GalleryActivity.this.mCurrentIndex = mValue;
updateSlider();
updateProgress();
break;
case KEY_TAP_MENU_AREA:
onTapMenuArea();
@@ -30,7 +30,6 @@ import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
@@ -41,6 +40,7 @@ import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.R;
@@ -68,6 +68,7 @@ import com.hippo.ehviewer.ui.scene.SelectSiteScene;
import com.hippo.ehviewer.ui.scene.SignInScene;
import com.hippo.ehviewer.ui.scene.WarningScene;
import com.hippo.ehviewer.ui.scene.WebViewSignInScene;
import com.hippo.ehviewer.widget.EhDrawerLayout;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
@@ -76,7 +77,6 @@ import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
import com.hippo.util.PermissionRequester;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.slidingdrawerlayout.SlidingDrawerLayout;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
@@ -111,7 +111,7 @@ public final class MainActivity extends StageActivity
Whole life cycle
---------------*/
@Nullable
private SlidingDrawerLayout mDrawerLayout;
private EhDrawerLayout mDrawerLayout;
@Nullable
private NavigationView mNavView;
@Nullable
@@ -340,11 +340,20 @@ public final class MainActivity extends StageActivity
@Override
protected void onUnrecognizedIntent(@Nullable Intent intent) {
if (!handleIntent(intent)) {
boolean handleUrl = false;
if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
handleUrl = true;
Toast.makeText(this, R.string.error_cannot_parse_the_url, Toast.LENGTH_SHORT).show();
}
if (0 == getSceneCount()) {
finish();
if (handleUrl) {
finish();
} else {
Bundle args = new Bundle();
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(processAnnouncer(new Announcer(GalleryListScene.class).setArgs(args)));
}
}
}
}
@@ -359,7 +368,7 @@ public final class MainActivity extends StageActivity
protected void onCreate2(@Nullable Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
mDrawerLayout = (SlidingDrawerLayout) ViewUtils.$$(this, R.id.draw_view);
mDrawerLayout = (EhDrawerLayout) ViewUtils.$$(this, R.id.draw_view);
mNavView = (NavigationView) ViewUtils.$$(this, R.id.nav_view);
mRightDrawer = (FrameLayout) ViewUtils.$$(this, R.id.right_drawer);
View headerLayout = mNavView.getHeaderView(0);
@@ -390,7 +399,8 @@ public final class MainActivity extends StageActivity
private void checkDownloadLocation() {
UniFile uniFile = Settings.getDownloadLocation();
if (null != uniFile && uniFile.ensureDir()) {
// null == uniFile for first start
if (null == uniFile || uniFile.ensureDir()) {
return;
}
new AlertDialog.Builder(this)
@@ -457,9 +467,9 @@ public final class MainActivity extends StageActivity
baseScene.getLayoutInflater2(), mRightDrawer, savedInstanceState);
if (drawerView != null) {
mRightDrawer.addView(drawerView);
mDrawerLayout.setDrawerLockMode(SlidingDrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
} else {
mDrawerLayout.setDrawerLockMode(SlidingDrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
}
}
}
@@ -493,6 +503,18 @@ public final class MainActivity extends StageActivity
mDisplayName.setText(displayName);
}
public void addAboveSnackView(View view) {
if (mDrawerLayout != null) {
mDrawerLayout.addAboveSnackView(view);
}
}
public void removeAboveSnackView(View view) {
if (mDrawerLayout != null) {
mDrawerLayout.removeAboveSnackView(view);
}
}
public int getDrawerLockMode(int edgeGravity) {
if (mDrawerLayout != null) {
return mDrawerLayout.getDrawerLockMode(edgeGravity);
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import com.hippo.ehviewer.R;
@@ -62,6 +63,17 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
mPatternView = null;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View v) {
if (v == mCancel) {
@@ -26,7 +26,7 @@ import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.util.ActivityHelper;
import com.hippo.util.AppHelper;
public class AboutFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener,
@@ -72,7 +72,7 @@ public class AboutFragment extends PreferenceFragment
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (KEY_AUTHOR.equals(key)) {
ActivityHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
new AlertDialog.Builder(getActivity())
@@ -16,7 +16,6 @@
package com.hippo.ehviewer.ui.fragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
@@ -32,10 +31,13 @@ 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;
public class DownloadFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public class DownloadFragment extends PreferenceFragment implements
Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener {
public static final int REQUEST_CODE_PICK_IMAGE_DIR = 0;
public static final int REQUEST_CODE_PICK_IMAGE_DIR_L = 1;
@@ -50,10 +52,15 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.download_settings);
Preference mediaScan = findPreference(Settings.KEY_MEDIA_SCAN);
Preference imageResolution = findPreference(Settings.KEY_IMAGE_RESOLUTION);
mDownloadLocation = findPreference(KEY_DOWNLOAD_LOCATION);
onUpdateDownloadLocation();
mediaScan.setOnPreferenceChangeListener(this);
imageResolution.setOnPreferenceChangeListener(this);
if (mDownloadLocation != null) {
mDownloadLocation.setOnPreferenceClickListener(this);
}
@@ -133,18 +140,18 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_DIR);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void openDirPickerL() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_DIR_L);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_DIR_L);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
}
@Override
@TargetApi(Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_PICK_IMAGE_DIR: {
@@ -161,7 +168,7 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
break;
}
case REQUEST_CODE_PICK_IMAGE_DIR_L: {
if (resultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Uri treeUri = data.getData();
getActivity().getContentResolver().takePersistableUriPermission(
treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
@@ -181,4 +188,26 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
}
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (Settings.KEY_MEDIA_SCAN.equals(key)) {
if (newValue instanceof Boolean) {
UniFile downloadLocation = Settings.getDownloadLocation();
if ((Boolean) newValue) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
}
return true;
} else if (Settings.KEY_IMAGE_RESOLUTION.equals(key)) {
if (newValue instanceof String) {
Settings.putImageResolution((String) newValue);
}
return true;
}
return false;
}
}
@@ -34,9 +34,11 @@ public class EhFragment extends PreferenceFragment
Preference gallerySite = findPreference(Settings.KEY_GALLERY_SITE);
Preference listMode = findPreference(Settings.KEY_LIST_MODE);
Preference thumbSize = findPreference(Settings.KEY_THUMB_SIZE);
gallerySite.setOnPreferenceChangeListener(this);
listMode.setOnPreferenceChangeListener(this);
thumbSize.setOnPreferenceChangeListener(this);
}
@Override
@@ -48,6 +50,8 @@ public class EhFragment extends PreferenceFragment
} else if (Settings.KEY_LIST_MODE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
return true;
} else if (Settings.KEY_THUMB_SIZE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
}
return true;
}
@@ -33,7 +33,7 @@ import android.view.ViewGroup;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.SceneFragment;
import com.hippo.util.ActivityHelper;
import com.hippo.util.AppHelper;
public abstract class BaseScene extends SceneFragment {
@@ -49,6 +49,20 @@ public abstract class BaseScene extends SceneFragment {
}
}
public void addAboveSnackView(View view) {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).addAboveSnackView(view);
}
}
public void removeAboveSnackView(View view) {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).removeAboveSnackView(view);
}
}
public void setDrawerLockMode(int lockMode, int edgeGravity) {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
@@ -154,7 +168,7 @@ public abstract class BaseScene extends SceneFragment {
setNavCheckedItem(getNavCheckedItem());
// Hide soft ime
ActivityHelper.hideSoftInput(getActivity());
AppHelper.hideSoftInput(getActivity());
}
public void createThemeContext(@StyleRes int style) {
@@ -198,14 +212,14 @@ public abstract class BaseScene extends SceneFragment {
public void hideSoftInput() {
FragmentActivity activity = getActivity();
if (null != activity) {
ActivityHelper.hideSoftInput(activity);
AppHelper.hideSoftInput(activity);
}
}
public void showSoftInput(@Nullable View view) {
FragmentActivity activity = getActivity();
if (null != activity && null != view) {
ActivityHelper.showSoftInput(activity, view);
AppHelper.showSoftInput(activity, view);
}
}
}
@@ -26,8 +26,8 @@ import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.rippleold.RippleSalon;
import com.hippo.util.ActivityHelper;
import com.hippo.ripple.Ripple;
import com.hippo.util.AppHelper;
import com.hippo.yorozuya.ViewUtils;
public class CrashScene extends BaseScene implements View.OnClickListener {
@@ -70,8 +70,8 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
mCancel.setOnClickListener(this);
mSend.setOnClickListener(this);
RippleSalon.addRipple(mCancel, true);
RippleSalon.addRipple(mSend, true);
Ripple.addRipple(mCancel, true);
Ripple.addRipple(mSend, true);
return view;
}
@@ -81,7 +81,7 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
MainActivity activity = getActivity2();
if (mSend == v && null != mCrash && null != activity) {
ActivityHelper.sendEmail(activity, EhApplication.getDeveloperEmail(),
AppHelper.sendEmail(activity, EhApplication.getDeveloperEmail(),
"I found a bug in EhViewer !", mCrash);
}
Crash.resetCrashFile();
@@ -17,7 +17,6 @@
package com.hippo.ehviewer.ui.scene;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
@@ -33,9 +32,9 @@ import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
@@ -45,6 +44,7 @@ import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
@@ -59,6 +59,7 @@ import com.hippo.app.CheckBoxDialogBuilder;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
@@ -74,7 +75,7 @@ import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.widget.SimpleRatingView;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.unifile.UniFile;
import com.hippo.util.ApiHelper;
@@ -82,12 +83,12 @@ import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.LongList;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.util.ArrayList;
@@ -131,7 +132,7 @@ public class DownloadsScene extends ToolbarScene
@Nullable
private DownloadAdapter mAdapter;
@Nullable
private LinearLayoutManager mLayoutManager;
private AutoStaggeredGridLayoutManager mLayoutManager;
private ShowcaseView mShowcaseView;
@@ -278,6 +279,7 @@ public class DownloadsScene extends ToolbarScene
Context context = getContext2();
AssertUtils.assertNotNull(content);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_download);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -286,9 +288,11 @@ public class DownloadsScene extends ToolbarScene
mAdapter = new DownloadAdapter();
mAdapter.setHasStableIds(true);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(context);
mLayoutManager = new AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
@@ -301,9 +305,12 @@ public class DownloadsScene extends ToolbarScene
if (itemAnimator instanceof SimpleItemAnimator) {
((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
}
int paddingH = context.getResources().getDimensionPixelOffset(R.dimen.list_content_margin_h);
int paddingV = context.getResources().getDimensionPixelOffset(R.dimen.list_content_margin_v);
mRecyclerView.setPadding(paddingV, paddingH, paddingV, paddingH);
int interval = resources.getDimensionPixelOffset(R.dimen.gallery_list_interval);
int paddingH = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_h);
int paddingV = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_v);
MarginItemDecoration decoration = new MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV);
mRecyclerView.addItemDecoration(decoration);
decoration.applyPaddings(mRecyclerView);
if (mInitPosition >= 0) {
mRecyclerView.scrollToPosition(mInitPosition);
mInitPosition = -1;
@@ -319,6 +326,7 @@ public class DownloadsScene extends ToolbarScene
mFabLayout.setHidePrimaryFab(true);
mFabLayout.setAutoCancel(false);
mFabLayout.setOnClickFabListener(this);
addAboveSnackView(mFabLayout);
updateView();
@@ -328,11 +336,16 @@ public class DownloadsScene extends ToolbarScene
}
private void guide() {
if (Settings.getGuideDownloadThumb()) {
SimpleHandler.getInstance().post(new Runnable() {
if (Settings.getGuideDownloadThumb() && null != mRecyclerView) {
mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void run() {
guideDownloadThumb();
public void onGlobalLayout() {
if (Settings.getGuideDownloadThumb()) {
guideDownloadThumb();
}
if (null != mRecyclerView) {
ViewUtils.removeOnGlobalLayoutListener(mRecyclerView.getViewTreeObserver(), this);
}
}
});
} else {
@@ -346,7 +359,7 @@ public class DownloadsScene extends ToolbarScene
guideDownloadLabels();
return;
}
int position = mLayoutManager.findFirstCompletelyVisibleItemPosition();
int position = mLayoutManager.findFirstCompletelyVisibleItemPositions(null)[0];
if (position < 0) {
guideDownloadLabels();
return;
@@ -424,9 +437,12 @@ public class DownloadsScene extends ToolbarScene
mRecyclerView.stopScroll();
mRecyclerView = null;
}
if (null != mFabLayout) {
removeAboveSnackView(mFabLayout);
mFabLayout = null;
}
mRecyclerView = null;
mFabLayout = null;
mViewTransition = null;
mAdapter = null;
mLayoutManager = null;
@@ -1049,8 +1065,8 @@ public class DownloadsScene extends ToolbarScene
thumb.setOnClickListener(this);
start.setOnClickListener(this);
stop.setOnClickListener(this);
RippleSalon.addRipple(start, false);
RippleSalon.addRipple(stop, false);
Ripple.addRipple(start, false);
Ripple.addRipple(stop, false);
}
@Override
@@ -1115,7 +1131,6 @@ public class DownloadsScene extends ToolbarScene
return new DownloadHolder(mInflater.inflate(R.layout.item_download, parent, false));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(DownloadHolder holder, int position) {
if (mList == null) {
@@ -1135,7 +1150,7 @@ public class DownloadsScene extends ToolbarScene
bindForState(holder, info);
// Update transition name
if (ApiHelper.SUPPORT_TRANSITION) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
long gid = info.gid;
holder.thumb.setTransitionName(TransitionNameFactory.getThumbTransitionName(gid));
}
@@ -16,7 +16,6 @@
package com.hippo.ehviewer.ui.scene;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.Fragment;
@@ -27,7 +26,6 @@ import android.view.View;
import com.hippo.ehviewer.R;
import com.hippo.scene.TransitionHelper;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class EnterGalleryDetailTransaction implements TransitionHelper {
private final View mThumb;
@@ -43,15 +41,17 @@ class EnterGalleryDetailTransaction implements TransitionHelper {
return false;
}
exit.setSharedElementReturnTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
exit.setExitTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
enter.setSharedElementEnterTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
enter.setEnterTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
transaction.addSharedElement(mThumb, mThumb.getTransitionName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
exit.setSharedElementReturnTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
exit.setExitTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
enter.setSharedElementEnterTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
enter.setEnterTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
transaction.addSharedElement(mThumb, mThumb.getTransitionName());
}
return true;
}
}
@@ -71,7 +71,8 @@ import com.hippo.ehviewer.ui.annotation.DrawerLifeCircle;
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.ehviewer.widget.SearchBar;
import com.hippo.rippleold.RippleSalon;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.util.ApiHelper;
@@ -79,7 +80,6 @@ import com.hippo.util.DrawableManager;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.widget.refreshlayout.RefreshLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ObjectUtils;
@@ -244,7 +244,7 @@ public class FavoritesScene extends BaseScene implements
Context context = getContext2();
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.list_padding_top_search_bar);
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
mHelper = new FavoritesHelper();
mHelper.setEmptyString(resources.getString(R.string.gallery_list_empty_hit));
@@ -252,7 +252,7 @@ public class FavoritesScene extends BaseScene implements
contentLayout.getFastScroller().setOnDragHandlerListener(this);
mAdapter = new FavoritesAdapter(inflater, resources, mRecyclerView, Settings.getListMode());
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
@@ -260,8 +260,6 @@ public class FavoritesScene extends BaseScene implements
mRecyclerView.setOnItemLongClickListener(this);
mRecyclerView.setChoiceMode(EasyRecyclerView.CHOICE_MODE_MULTIPLE_CUSTOM);
mRecyclerView.setCustomCheckedListener(this);
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop() + paddingTopSB,
mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom());
fastScroller.setPadding(fastScroller.getPaddingLeft(), fastScroller.getPaddingTop() + paddingTopSB,
fastScroller.getPaddingRight(), fastScroller.getPaddingBottom());
@@ -280,6 +278,7 @@ public class FavoritesScene extends BaseScene implements
mFabLayout.setAutoCancel(false);
mFabLayout.setHidePrimaryFab(true);
mFabLayout.setOnClickFabListener(this);
addAboveSnackView(mFabLayout);
// Restore search mode
if (mSearchMode) {
@@ -395,11 +394,14 @@ public class FavoritesScene extends BaseScene implements
mRecyclerView.stopScroll();
mRecyclerView = null;
}
if (null != mFabLayout) {
removeAboveSnackView(mFabLayout);
mFabLayout = null;
}
mAdapter = null;
mSearchBar = null;
mFabLayout = null;
mSearchBarMover = null;
mLeftDrawable = null;
@@ -484,7 +486,7 @@ public class FavoritesScene extends BaseScene implements
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
rv.addItemDecoration(decoration);
rv.setSelector(RippleSalon.generateRippleDrawable(false));
rv.setSelector(Ripple.generateRippleDrawable(context, false));
rv.setClipToPadding(false);
builder.setView(rv).show();
}
@@ -16,7 +16,6 @@
package com.hippo.ehviewer.ui.scene;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
@@ -33,12 +32,11 @@ import android.widget.TextView;
import com.hippo.drawable.TriangleDrawable;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.widget.TileThumb;
import com.hippo.util.ApiHelper;
import com.hippo.widget.recyclerview.AutoGridLayoutManager;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import java.lang.annotation.Retention;
@@ -58,7 +56,9 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
private final Resources mResources;
private final RecyclerView mRecyclerView;
private final AutoStaggeredGridLayoutManager mLayoutManager;
private RecyclerView.ItemDecoration mGirdDecoration;
private final int mPaddingTopSB;
private MarginItemDecoration mListDecoration;
private MarginItemDecoration mGirdDecoration;
private int mType = TYPE_INVALID;
public GalleryAdapter(@NonNull LayoutInflater inflater, @NonNull Resources resources,
@@ -67,16 +67,20 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
mResources = resources;
mRecyclerView = recyclerView;
mLayoutManager = new AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL);
mPaddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
mRecyclerView.setAdapter(this);
mRecyclerView.setLayoutManager(mLayoutManager);
int paddingH = mResources.getDimensionPixelOffset(R.dimen.list_content_margin_h);
int paddingV = mResources.getDimensionPixelOffset(R.dimen.list_content_margin_v);
mRecyclerView.setPadding(paddingV, paddingH, paddingV, paddingH);
setType(type);
}
private void adjustPaddings() {
RecyclerView recyclerView = mRecyclerView;
recyclerView.setPadding(recyclerView.getPaddingLeft(), recyclerView.getPaddingTop() + mPaddingTopSB,
recyclerView.getPaddingRight(), recyclerView.getPaddingBottom());
}
public int getType() {
return mType;
}
@@ -87,27 +91,44 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
}
mType = type;
RecyclerView recyclerView = mRecyclerView;
switch (type) {
default:
case GalleryAdapter.TYPE_LIST: {
int columnWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_list_column_width);
mLayoutManager.setColumnSize(columnWidth);
mLayoutManager.setStrategy(AutoGridLayoutManager.STRATEGY_MIN_SIZE);
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
if (null != mGirdDecoration) {
mRecyclerView.removeItemDecoration(mGirdDecoration);
recyclerView.removeItemDecoration(mGirdDecoration);
}
if (null == mListDecoration) {
int interval = mResources.getDimensionPixelOffset(R.dimen.gallery_list_interval);
int paddingH = mResources.getDimensionPixelOffset(R.dimen.gallery_list_margin_h);
int paddingV = mResources.getDimensionPixelOffset(R.dimen.gallery_list_margin_v);
mListDecoration = new MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV);
}
recyclerView.addItemDecoration(mListDecoration);
mListDecoration.applyPaddings(recyclerView);
adjustPaddings();
notifyDataSetChanged();
break;
}
case GalleryAdapter.TYPE_GRID: {
int columnWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_grid_column_width);
int columnWidth = mResources.getDimensionPixelOffset(Settings.getThumbSizeResId());
mLayoutManager.setColumnSize(columnWidth);
mLayoutManager.setStrategy(AutoGridLayoutManager.STRATEGY_SUITABLE_SIZE);
if (null == mGirdDecoration) {
mGirdDecoration = new MarginItemDecoration(
mResources.getDimensionPixelOffset(R.dimen.gallery_grid_margin) / 2);
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_SUITABLE_SIZE);
if (null != mListDecoration) {
recyclerView.removeItemDecoration(mListDecoration);
}
mRecyclerView.addItemDecoration(mGirdDecoration);
if (null == mGirdDecoration) {
int interval = mResources.getDimensionPixelOffset(R.dimen.gallery_grid_interval);
int paddingH = mResources.getDimensionPixelOffset(R.dimen.gallery_grid_margin_h);
int paddingV = mResources.getDimensionPixelOffset(R.dimen.gallery_grid_margin_v);
mGirdDecoration = new MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV);
}
recyclerView.addItemDecoration(mGirdDecoration);
mGirdDecoration.applyPaddings(recyclerView);
adjustPaddings();
notifyDataSetChanged();
break;
}
@@ -138,7 +159,6 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
public abstract GalleryInfo getDataAt(int position);
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void onBindViewHolder(GalleryHolder holder, int position) {
GalleryInfo gi = getDataAt(position);
if (null == gi) {
@@ -170,7 +190,7 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
int color = EhUtils.getCategoryColor(gi.category);
if (!(drawable instanceof TriangleDrawable)) {
drawable = new TriangleDrawable(color);
category.setBackground(drawable);
category.setBackgroundDrawable(drawable);
} else {
((TriangleDrawable) drawable).setColor(color);
}
@@ -180,7 +200,7 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
}
// Update transition name
if (ApiHelper.SUPPORT_TRANSITION) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
long gid = gi.gid;
holder.thumb.setTransitionName(TransitionNameFactory.getThumbTransitionName(gid));
}
@@ -64,7 +64,7 @@ import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.reveal.ViewAnimationUtils;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.scene.SceneFragment;
import com.hippo.text.Html;
import com.hippo.text.URLImageGetter;
@@ -72,6 +72,7 @@ import com.hippo.util.DrawableManager;
import com.hippo.util.ReadableTime;
import com.hippo.util.TextUrl;
import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LinkifyTextView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
@@ -107,6 +108,8 @@ public final class GalleryCommentsScene extends ToolbarScene
@Nullable
private EasyRecyclerView mRecyclerView;
@Nullable
private FabLayout mFabLayout;
@Nullable
private FloatingActionButton mFab;
@Nullable
private View mEditPanel;
@@ -182,12 +185,13 @@ public final class GalleryCommentsScene extends ToolbarScene
mEditPanel = ViewUtils.$$(view, R.id.edit_panel);
mSendImage = (ImageView) ViewUtils.$$(mEditPanel, R.id.send);
mEditText = (EditText) ViewUtils.$$(mEditPanel, R.id.edit_text);
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
mFab = (FloatingActionButton) ViewUtils.$$(view, R.id.fab);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.list_padding_bottom_fab);
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -202,7 +206,7 @@ public final class GalleryCommentsScene extends ToolbarScene
LayoutUtils.dp2pix(context, 1));
decoration.setShowLastDivider(true);
mRecyclerView.addItemDecoration(decoration);
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setOnItemClickListener(this);
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop(),
@@ -216,6 +220,9 @@ public final class GalleryCommentsScene extends ToolbarScene
mSendImage.setOnClickListener(this);
mFab.setOnClickListener(this);
addAboveSnackView(mEditPanel);
addAboveSnackView(mFabLayout);
mViewTransition = new ViewTransition(mRecyclerView, tip);
updateView(false);
@@ -231,9 +238,16 @@ public final class GalleryCommentsScene extends ToolbarScene
mRecyclerView.stopScroll();
mRecyclerView = null;
}
if (null != mEditPanel) {
removeAboveSnackView(mEditPanel);
mEditPanel = null;
}
if (null != mFabLayout) {
removeAboveSnackView(mFabLayout);
mFabLayout = null;
}
mFab = null;
mEditPanel = null;
mSendImage = null;
mEditText = null;
mAdapter = null;
@@ -325,7 +339,7 @@ public final class GalleryCommentsScene extends ToolbarScene
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
rv.addItemDecoration(decoration);
rv.setSelector(RippleSalon.generateRippleDrawable(false));
rv.setSelector(Ripple.generateRippleDrawable(context, false));
rv.setClipToPadding(false);
builder.setView(rv).show();
}
@@ -400,7 +414,7 @@ public final class GalleryCommentsScene extends ToolbarScene
commentHolder.comment.clearCurrentSpan();
if (span instanceof URLSpan) {
UrlOpener.openUrl(activity, ((URLSpan) span).getURL(), true, true);
UrlOpener.openUrl(activity, ((URLSpan) span).getURL(), true);
return true;
}
}
@@ -17,7 +17,6 @@
package com.hippo.ehviewer.ui.scene;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
@@ -61,6 +60,7 @@ import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.UrlOpener;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhClient;
@@ -82,14 +82,14 @@ import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.reveal.ViewAnimationUtils;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.scene.TransitionHelper;
import com.hippo.text.Html;
import com.hippo.text.URLImageGetter;
import com.hippo.util.ActivityHelper;
import com.hippo.util.ApiHelper;
import com.hippo.util.AppHelper;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.ReadableTime;
@@ -431,9 +431,9 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mActionGroup = (ViewGroup) ViewUtils.$$(mHeader, R.id.action_card);
mDownload = (TextView) ViewUtils.$$(mActionGroup, R.id.download);
mRead = ViewUtils.$$(mActionGroup, R.id.read);
RippleSalon.addRipple(mOtherActions, false);
RippleSalon.addRipple(mDownload, false);
RippleSalon.addRipple(mRead, false);
Ripple.addRipple(mOtherActions, false);
Ripple.addRipple(mDownload, false);
Ripple.addRipple(mRead, false);
mUploader.setOnClickListener(this);
mCategory.setOnClickListener(this);
mOtherActions.setOnClickListener(this);
@@ -452,7 +452,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mSize = (TextView) ViewUtils.$$(mInfo, R.id.size);
mPosted = (TextView) ViewUtils.$$(mInfo, R.id.posted);
mFavoredTimes = (TextView) ViewUtils.$$(mInfo, R.id.favoredTimes);
RippleSalon.addRipple(mInfo, false);
Ripple.addRipple(mInfo, false);
mInfo.setOnClickListener(this);
mActions = ViewUtils.$$(belowHeader, R.id.actions);
@@ -466,12 +466,12 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mRate = (TextView) ViewUtils.$$(mActions, R.id.rate);
mSimilar = (TextView) ViewUtils.$$(mActions, R.id.similar);
mSearchCover = (TextView) ViewUtils.$$(mActions, R.id.search_cover);
RippleSalon.addRipple(mHeartGroup, false);
RippleSalon.addRipple(mTorrent, false);
RippleSalon.addRipple(mShare, false);
RippleSalon.addRipple(mRate, false);
RippleSalon.addRipple(mSimilar, false);
RippleSalon.addRipple(mSearchCover, false);
Ripple.addRipple(mHeartGroup, false);
Ripple.addRipple(mTorrent, false);
Ripple.addRipple(mShare, false);
Ripple.addRipple(mRate, false);
Ripple.addRipple(mSimilar, false);
Ripple.addRipple(mSearchCover, false);
mHeartGroup.setOnClickListener(this);
mTorrent.setOnClickListener(this);
mShare.setOnClickListener(this);
@@ -485,13 +485,13 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mComments = (LinearLayout) ViewUtils.$$(belowHeader, R.id.comments);
mCommentsText = (TextView) ViewUtils.$$(mComments, R.id.comments_text);
RippleSalon.addRipple(mComments, false);
Ripple.addRipple(mComments, false);
mComments.setOnClickListener(this);
mPreviews = ViewUtils.$$(belowHeader, R.id.previews);
mGridLayout = (SimpleGridAutoSpanLayout) ViewUtils.$$(mPreviews, R.id.grid_layout);
mPreviewText = (TextView) ViewUtils.$$(mPreviews, R.id.preview_text);
RippleSalon.addRipple(mPreviews, false);
Ripple.addRipple(mPreviews, false);
mPreviews.setOnClickListener(this);
mProgress = ViewUtils.$$(mainView, R.id.progress);
@@ -895,7 +895,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mPreviewText.setText(R.string.more_previews);
}
int columnWidth = resources.getDimensionPixelOffset(R.dimen.preview_grid_column_width);
int columnWidth = resources.getDimensionPixelOffset(Settings.getThumbSizeResId());
mGridLayout.setColumnSize(columnWidth);
mGridLayout.setStrategy(SimpleGridAutoSpanLayout.STRATEGY_SUITABLE_SIZE);
for (int i = 0, size = previewSet.size(); i < size; i++) {
@@ -956,12 +956,12 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
return resources.getString(R.string.rating_text, getRatingText(rating, resources), rating, ratingCount);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setTransitionName() {
long gid = getGid();
if (gid != -1 && ApiHelper.SUPPORT_TRANSITION && mThumb != null &&
mTitle != null && mUploader != null && mCategory != null) {
mTitle != null && mUploader != null && mCategory != null &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mThumb.setTransitionName(TransitionNameFactory.getThumbTransitionName(gid));
mTitle.setTransitionName(TransitionNameFactory.getTitleTransitionName(gid));
mUploader.setTransitionName(TransitionNameFactory.getUploaderTransitionName(gid));
@@ -987,7 +987,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
String url = getGalleryDetailUrl(false);
Activity activity = getActivity2();
if (null != url && null != activity) {
UrlOpener.openUrl(activity, url, false, false);
UrlOpener.openUrl(activity, url, false);
}
break;
case R.id.action_refresh:
@@ -1159,7 +1159,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
} else if (mShare == v) {
String url = getGalleryDetailUrl(false);
if (url != null) {
ActivityHelper.share(activity, url);
AppHelper.share(activity, url);
}
} else if (mTorrent == v) {
if (mGalleryDetail != null) {
@@ -1293,7 +1293,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
UrlOpener.openUrl(context, EhUrl.getTagDefinitionUrl(tag2), false, true);
UrlOpener.openUrl(context, EhUrl.getTagDefinitionUrl(tag2), false);
break;
case 1:
addTagFilter(tag);
@@ -1454,7 +1454,6 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onTransition(Context context,
FragmentTransaction transaction, Fragment exit, Fragment enter) {
if (!(enter instanceof GalleryListScene) && !(enter instanceof DownloadsScene) &&
@@ -1462,15 +1461,17 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
return false;
}
exit.setSharedElementReturnTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
exit.setExitTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
enter.setSharedElementEnterTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
enter.setEnterTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
transaction.addSharedElement(mThumb, mThumb.getTransitionName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
exit.setSharedElementReturnTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
exit.setExitTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
enter.setSharedElementEnterTransition(
TransitionInflater.from(context).inflateTransition(R.transition.trans_move));
enter.setEnterTransition(
TransitionInflater.from(context).inflateTransition(android.R.transition.fade));
transaction.addSharedElement(mThumb, mThumb.getTransitionName());
}
return true;
}
}
@@ -1486,7 +1487,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
e.printStackTrace();
Context context = getContext2();
if (null != context && null != mTip) {
String error = ExceptionUtils.getReadableString(context, e);
String error = ExceptionUtils.getReadableString(e);
mTip.setText(error);
adjustViewVisibility(STATE_FAILED, true);
}
@@ -1658,7 +1659,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mProgressView.setVisibility(View.GONE);
mErrorText.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
mErrorText.setText(ExceptionUtils.getReadableString(context, e));
mErrorText.setText(ExceptionUtils.getReadableString(e));
}
}
@@ -36,7 +36,7 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
@@ -166,7 +166,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(context.getResources().getDimensionPixelOffset(R.dimen.keyline_margin));
mRecyclerView.addItemDecoration(decoration);
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setClipToPadding(false);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setOnItemClickListener(this);
@@ -76,16 +76,17 @@ import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.widget.SearchBar;
import com.hippo.ehviewer.widget.SearchLayout;
import com.hippo.rippleold.RippleSalon;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.util.ApiHelper;
import com.hippo.util.AppHelper;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.widget.refreshlayout.RefreshLayout;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.MathUtils;
@@ -400,8 +401,8 @@ public final class GalleryListScene extends BaseScene
mFabLayout = (FabLayout) ViewUtils.$$(mainLayout, R.id.fab_layout);
mSearchFab = ViewUtils.$$(mainLayout, R.id.search_fab);
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.list_padding_top_search_bar);
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.list_padding_bottom_fab);
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
mViewTransition = new ViewTransition(contentLayout, mSearchLayout);
@@ -412,14 +413,12 @@ public final class GalleryListScene extends BaseScene
mAdapter = new GalleryListAdapter(inflater, resources,
mRecyclerView, Settings.getListMode());
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
mRecyclerView.setOnItemClickListener(this);
mRecyclerView.setOnItemLongClickListener(this);
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop() + paddingTopSB,
mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom());
mRecyclerView.addOnScrollListener(mOnScrollListener);
fastScroller.setPadding(fastScroller.getPaddingLeft(), fastScroller.getPaddingTop() + paddingTopSB,
@@ -444,6 +443,7 @@ public final class GalleryListScene extends BaseScene
mFabLayout.setHidePrimaryFab(false);
mFabLayout.setOnClickFabListener(this);
mFabLayout.setOnExpandListener(this);
addAboveSnackView(mFabLayout);
mActionFabDrawable = new AddDeleteDrawable(context);
mActionFabDrawable.setColor(resources.getColor(R.color.primary_drawable_dark));
@@ -523,11 +523,14 @@ public final class GalleryListScene extends BaseScene
mRecyclerView.stopScroll();
mRecyclerView = null;
}
if (null != mFabLayout) {
removeAboveSnackView(mFabLayout);
mFabLayout = null;
}
mAdapter = null;
mSearchLayout = null;
mSearchBar = null;
mFabLayout = null;
mSearchFab = null;
mViewTransition = null;
mLeftDrawable = null;
@@ -805,6 +808,7 @@ public final class GalleryListScene extends BaseScene
}
builder.setError(null);
mHelper.goTo(goTo);
AppHelper.hideSoftInput(dialog);
dialog.dismiss();
}
});
@@ -38,6 +38,7 @@ import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhRequest;
import com.hippo.ehviewer.client.EhUrl;
@@ -141,15 +142,16 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
mAdapter = new GalleryPreviewAdapter();
mRecyclerView.setAdapter(mAdapter);
int columnWidth = resources.getDimensionPixelOffset(R.dimen.preview_grid_column_width);
int columnWidth = resources.getDimensionPixelOffset(Settings.getThumbSizeResId());
AutoGridLayoutManager layoutManager = new AutoGridLayoutManager(context, columnWidth);
layoutManager.setStrategy(AutoGridLayoutManager.STRATEGY_SUITABLE_SIZE);
mRecyclerView.setLayoutManager(layoutManager);
int padding = LayoutUtils.dp2pix(context, 4);
mRecyclerView.setPadding(padding, padding, padding, padding);
mRecyclerView.setClipToPadding(false);
mRecyclerView.addItemDecoration(new MarginItemDecoration(padding));
mRecyclerView.setOnItemClickListener(this);
int padding = LayoutUtils.dp2pix(context, 4);
MarginItemDecoration decoration = new MarginItemDecoration(padding, padding, padding, padding, padding);
mRecyclerView.addItemDecoration(decoration);
decoration.applyPaddings(mRecyclerView);
mHelper = new GalleryPreviewHelper();
contentLayout.setHelper(mHelper);
@@ -16,7 +16,6 @@
package com.hippo.ehviewer.ui.scene;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
@@ -25,8 +24,8 @@ import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
@@ -46,6 +45,7 @@ import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractSwipeableItemView
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
@@ -55,13 +55,14 @@ import com.hippo.ehviewer.dao.HistoryInfo;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.widget.SimpleRatingView;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.util.ApiHelper;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
@@ -119,17 +120,23 @@ public class HistoryScene extends ToolbarScene
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
animator.setSupportsChangeAnimations(false);
mRecyclerView.setItemAnimator(animator);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
AutoStaggeredGridLayoutManager layoutManager = new AutoStaggeredGridLayoutManager(
0, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
layoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
mRecyclerView.setOnItemClickListener(this);
mRecyclerView.setOnItemLongClickListener(this);
int paddingH = resources.getDimensionPixelOffset(R.dimen.list_content_margin_h);
int paddingV = resources.getDimensionPixelOffset(R.dimen.list_content_margin_v);
mRecyclerView.setPadding(paddingV, paddingH, paddingV, paddingH);
int interval = resources.getDimensionPixelOffset(R.dimen.gallery_list_interval);
int paddingH = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_h);
int paddingV = resources.getDimensionPixelOffset(R.dimen.gallery_list_margin_v);
MarginItemDecoration decoration = new MarginItemDecoration(interval, paddingH, paddingV, paddingH, paddingV);
mRecyclerView.addItemDecoration(decoration);
decoration.applyPaddings(mRecyclerView);
guardManager.attachRecyclerView(mRecyclerView);
swipeManager.attachRecyclerView(mRecyclerView);
@@ -334,7 +341,6 @@ public class HistoryScene extends ToolbarScene
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void onBindViewHolder(HistoryHolder holder, int position) {
if (null == mLazyList) {
return;
@@ -355,7 +361,7 @@ public class HistoryScene extends ToolbarScene
holder.simpleLanguage.setText(gi.simpleLanguage);
// Update transition name
if (ApiHelper.SUPPORT_TRANSITION) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
long gid = gi.gid;
holder.thumb.setTransitionName(TransitionNameFactory.getThumbTransitionName(gid));
}
@@ -226,7 +226,7 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
if (null != context && null != mViewTransition && null != mTip) {
// Show tip
mError = ExceptionUtils.getReadableString(context, e);
mError = ExceptionUtils.getReadableString(e);
mViewTransition.showView(1);
mTip.setText(mError);
}
@@ -29,7 +29,6 @@ import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
@@ -43,7 +42,6 @@ import com.hippo.ehviewer.client.parser.ProfileParser;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
@@ -219,7 +217,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
}
if (mRegister == v) {
UrlOpener.openUrl(activity, EhUrl.URL_REGISTER, false, true);
UrlOpener.openUrl(activity, EhUrl.URL_REGISTER, false);
} else if (mSignIn == v) {
signIn();
} else if (mSignInViaWebView == v) {
@@ -329,12 +327,11 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
new AlertDialog.Builder(context)
.setTitle(R.string.sign_in_failed)
.setMessage(R.string.sign_in_failed_plain)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.get_it, null)
.show();
}
public void onSignInSuccess() {
public void onSignInEnd() {
Context context = getContext2();
if (null == context) {
return;
@@ -349,38 +346,12 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
}
}
public void onSignInFailure(Exception e) {
Context context = getContext2();
if (null == context) {
return;
}
mSigningIn = false;
Toast.makeText(context, ExceptionUtils.getReadableString(context, e),
Toast.LENGTH_SHORT).show();
hideProgress();
whetherToSkip();
}
public void onGetProfileSuccess() {
public void onGetProfileEnd() {
mSigningIn = false;
updateAvatar();
redirectTo();
}
public void onGetProfileFailure(Exception e) {
Context context = getContext2();
if (null == context) {
return;
}
mSigningIn = false;
Toast.makeText(context, ExceptionUtils.getReadableString(context, e),
Toast.LENGTH_SHORT).show();
hideProgress();
whetherToSkip();
}
private class SignInListener extends EhCallback<SignInScene, String> {
public SignInListener(Context context, int stageId, String sceneTag) {
@@ -394,7 +365,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
SignInScene scene = getScene();
if (scene != null) {
scene.onSignInSuccess();
scene.onSignInEnd();
}
}
@@ -405,7 +376,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
SignInScene scene = getScene();
if (scene != null) {
scene.onSignInFailure(e);
scene.onSignInEnd();
}
}
@@ -434,7 +405,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
SignInScene scene = getScene();
if (scene != null) {
scene.onGetProfileSuccess();
scene.onGetProfileEnd();
}
}
@@ -445,7 +416,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
SignInScene scene = getScene();
if (scene != null) {
scene.onGetProfileFailure(e);
scene.onGetProfileEnd();
}
}
@@ -121,7 +121,7 @@ public class WebViewSignInScene extends BaseScene {
}
private void addCookie(Context context, String domain, Cookie cookie) {
EhApplication.getEhCookieStore(context).add(EhCookieStore.newCookie(cookie, domain, true, true));
EhApplication.getEhCookieStore(context).add(EhCookieStore.newCookie(cookie, domain, true, true, true));
}
@Override
@@ -0,0 +1,166 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.AnimationUtils;
import java.util.ArrayList;
import java.util.List;
@CoordinatorLayout.DefaultBehavior(EhDrawerLayout.Behavior.class)
public class EhDrawerLayout extends DrawerLayout {
private List<View> mAboveSnackViewList;
public EhDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EhDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void addAboveSnackView(View view) {
if (null == mAboveSnackViewList) {
mAboveSnackViewList = new ArrayList<>();
}
mAboveSnackViewList.add(view);
}
public void removeAboveSnackView(View view) {
if (null == mAboveSnackViewList) {
return;
}
mAboveSnackViewList.remove(view);
}
public int getAboveSnackViewCount() {
return null == mAboveSnackViewList ? 0 : mAboveSnackViewList.size();
}
@Nullable
public View getAboveSnackViewAt(int index) {
if (null == mAboveSnackViewList || index < 0 || index >= mAboveSnackViewList.size()) {
return null;
} else {
return mAboveSnackViewList.get(index);
}
}
public static class Behavior extends CoordinatorLayout.Behavior<EhDrawerLayout> {
// We only support the FAB <> Snackbar shift movement on Honeycomb and above. This is
// because we can use view translation properties which greatly simplifies the code.
private static final boolean SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= 11;
@Override
public boolean layoutDependsOn(CoordinatorLayout parent,
EhDrawerLayout child, View dependency) {
// We're dependent on all SnackbarLayouts (if enabled)
return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, EhDrawerLayout child,
View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
for (int i = 0, n = child.getAboveSnackViewCount(); i < n; i++) {
View view = child.getAboveSnackViewAt(i);
updateChildTranslationForSnackbar(parent, child, view);
}
}
return false;
}
private void updateChildTranslationForSnackbar(CoordinatorLayout parent,
EhDrawerLayout view, final View child) {
final float targetTransY = getChildTranslationYForSnackbar(parent, view);
float childTranslationY = 0.0f;
Object obj = child.getTag(R.id.fab_translation_y);
if (obj instanceof Float) {
childTranslationY = (Float) obj;
}
if (childTranslationY == targetTransY) {
// We're already at (or currently animating to) the target value, return...
return;
}
ValueAnimator fabTranslationYAnimator = null;
obj = child.getTag(R.id.fab_translation_y_animator);
if (obj instanceof ValueAnimator) {
fabTranslationYAnimator = (ValueAnimator) obj;
}
// Make sure that any current animation is cancelled
if (fabTranslationYAnimator != null && fabTranslationYAnimator.isRunning()) {
fabTranslationYAnimator.cancel();
}
final float currentTransY = ViewCompat.getTranslationY(child);
if (child.isShown()
&& Math.abs(currentTransY - targetTransY) > (child.getHeight() * 0.667f)) {
// If the FAB will be travelling by more than 2/3 of it's height, let's animate
// it instead
if (fabTranslationYAnimator == null) {
fabTranslationYAnimator = ValueAnimator.ofFloat();
fabTranslationYAnimator.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
fabTranslationYAnimator.addUpdateListener(
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewCompat.setTranslationY(child, (Float) animation.getAnimatedValue());
}
});
child.setTag(R.id.fab_translation_y_animator, fabTranslationYAnimator);
}
fabTranslationYAnimator.setFloatValues(currentTransY, targetTransY);
fabTranslationYAnimator.start();
} else {
// Now update the translation Y
ViewCompat.setTranslationY(child, targetTransY);
}
child.setTag(R.id.fab_translation_y, targetTransY);
}
private float getChildTranslationYForSnackbar(CoordinatorLayout parent,
EhDrawerLayout child) {
float minOffset = 0;
final List<View> dependencies = parent.getDependencies(child);
for (int i = 0, z = dependencies.size(); i < z; i++) {
final View view = dependencies.get(i);
if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(child, view)) {
minOffset = Math.min(minOffset,
ViewCompat.getTranslationY(view) - view.getHeight());
}
}
return minOffset;
}
}
}
@@ -19,10 +19,10 @@ package com.hippo.ehviewer.widget;
import android.content.Context;
import android.util.AttributeSet;
import com.hippo.drawerlayout.DrawerLayoutChild;
import com.hippo.widget.DrawerView;
import com.hippo.widget.slidingdrawerlayout.SlidingDrawerLayoutChild;
public class EhDrawerView extends DrawerView implements SlidingDrawerLayoutChild {
public class EhDrawerView extends DrawerView implements DrawerLayoutChild {
private int mFitPaddingTop;
@@ -0,0 +1,84 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.util.AttributeSet;
import com.hippo.drawerlayout.DrawerLayoutChild;
public class EhNavigationView extends NavigationView 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;
public EhNavigationView(Context context) {
super(context);
init();
}
public EhNavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EhNavigationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
if (DRAW_SCRIM) {
setWillNotDraw(false);
}
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
if (DRAW_SCRIM && mFitPaddingTop > 0) {
if (null == mPaint) {
mPaint = new Paint();
mPaint.setColor(SCRIM_COLOR);
}
canvas.drawRect(0, 0, getWidth(), mFitPaddingTop, mPaint);
}
}
@Override
public void setFitPadding(int top, int bottom) {
mFitPaddingTop = top;
}
@Override
public int getLayoutPaddingTop() {
return 0;
}
@Override
public int getLayoutPaddingBottom() {
return 0;
}
}
@@ -19,10 +19,10 @@ package com.hippo.ehviewer.widget;
import android.content.Context;
import android.util.AttributeSet;
import com.hippo.drawerlayout.DrawerLayoutChild;
import com.hippo.scene.StageLayout;
import com.hippo.widget.slidingdrawerlayout.SlidingDrawerLayoutChild;
public class EhStageLayout extends StageLayout implements SlidingDrawerLayoutChild {
public class EhStageLayout extends StageLayout implements DrawerLayoutChild {
private int mFitPaddingTop;
@@ -16,12 +16,11 @@
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
@@ -60,15 +59,8 @@ public class GalleryGuideView extends ViewGroup implements View.OnClickListener
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public GalleryGuideView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
@SuppressWarnings("deprecation")
private void init(Context context) {
mBgColor = context.getResources().getColor(R.color.guide_bg);
mBgColor = ContextCompat.getColor(context, R.color.guide_bg);
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
@@ -20,7 +20,7 @@ import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
@@ -43,6 +43,7 @@ import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.dict.DictManager;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AnimationUtils;
@@ -69,7 +70,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private int mState = STATE_NORMAL;
private final Path mPath = new Path();
private final Rect mRect = new Rect();
private int mWidth;
private int mHeight;
private int mBaseHeight;
@@ -85,6 +86,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private ViewTransition mViewTransition;
private SearchDatabase mSearchDatabase;
private DictManager mDictManager;
private List<String> mSuggestionList;
private ArrayAdapter mSuggestionAdapter;
@@ -114,6 +116,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
setBackgroundResource(R.drawable.card_white_no_padding_2dp);
mSearchDatabase = SearchDatabase.getInstance(getContext());
mDictManager = new DictManager(getContext());
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.widget_search_bar, this);
@@ -170,8 +173,11 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private void updateSuggestions() {
String prefix = mEditText.getText().toString();
String[] dictSuggestions = mDictManager.getSuggestions(prefix);
String[] suggestions = mSearchDatabase.getSuggestions(prefix);
mSuggestionList.clear();
Collections.addAll(mSuggestionList, dictSuggestions);
Collections.addAll(mSuggestionList, suggestions);
if (mSuggestionList.size() == 0) {
removeListHeader();
@@ -425,10 +431,9 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
public void draw(@NonNull Canvas canvas) {
if (mInAnimation) {
final int state = canvas.save();
float bottom = MathUtils.lerp(mBaseHeight, mHeight, mProgress);
mPath.rewind();
mPath.addRect(0f, 0f, mWidth, bottom, Path.Direction.CW);
canvas.clipPath(mPath);
int bottom = MathUtils.lerp(mBaseHeight, mHeight, mProgress);
mRect.set(0, 0, mWidth, bottom);
canvas.clipRect(mRect);
super.draw(canvas);
canvas.restoreToCount(state);
} else {
@@ -480,10 +485,15 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
public interface Helper {
void onClickTitle();
void onClickLeftIcon();
void onClickRightIcon();
void onSearchEditTextClick();
void onApplySearch(String query);
void onSearchEditTextBackPressed();
}
@@ -60,7 +60,6 @@ public class SearchDatabase {
public String[] getSuggestions(String prefix) {
List<String> queryList = new LinkedList<>();
// TODO add limit
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ").append(TABLE_SUGGESTIONS);
if (!TextUtils.isEmpty(prefix)) {
@@ -18,12 +18,12 @@ package com.hippo.ehviewer.widget;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.EditText;
public class SearchEditText extends EditText {
public class SearchEditText extends AppCompatEditText {
private SearchEditTextListener mListener;
@@ -39,10 +39,11 @@ import android.widget.ImageView;
import android.widget.TextView;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.widget.RadioGridGroup;
import com.hippo.yorozuya.ViewUtils;
@@ -122,9 +123,13 @@ public class SearchLayout extends EasyRecyclerView implements CompoundButton.OnC
setAdapter(mAdapter);
setHasFixedSize(true);
setClipToPadding(false);
int paddingH = resources.getDimensionPixelOffset(R.dimen.list_content_margin_h);
int paddingV = resources.getDimensionPixelOffset(R.dimen.list_content_margin_v);
setPadding(paddingV, paddingH, paddingV, paddingH);
int interval = resources.getDimensionPixelOffset(R.dimen.search_layout_interval);
int paddingH = resources.getDimensionPixelOffset(R.dimen.search_layout_margin_h);
int paddingV = resources.getDimensionPixelOffset(R.dimen.search_layout_margin_v);
MarginItemDecoration decoration = new MarginItemDecoration(
interval, paddingH, paddingV, paddingH, paddingV);
addItemDecoration(decoration);
decoration.applyPaddings(this);
// Create normal view
View normalView = mInflater.inflate(R.layout.search_normal, null);
@@ -134,7 +139,7 @@ public class SearchLayout extends EasyRecyclerView implements CompoundButton.OnC
mNormalSearchModeHelp = (ImageView) normalView.findViewById(R.id.normal_search_mode_help);
mEnableAdvanceSwitch = (SwitchCompat) normalView.findViewById(R.id.search_enable_advance);
mNormalSearchModeHelp.setOnClickListener(this);
RippleSalon.addRipple(mNormalSearchModeHelp, false);
Ripple.addRipple(mNormalSearchModeHelp, false);
mEnableAdvanceSwitch.setOnCheckedChangeListener(SearchLayout.this);
mEnableAdvanceSwitch.setSwitchPadding(resources.getDimensionPixelSize(R.dimen.switch_padding));
@@ -240,7 +240,8 @@ public class ImageTexture implements Texture, Animatable {
private class AnimateRunnable implements Runnable {
public void doRun() {
long lastTime = SystemClock.currentThreadTimeMillis();
long lastTime = SystemClock.elapsedRealtime();
long lastDelay = -1L;
synchronized (mImage) {
// Check recycled
@@ -309,9 +310,12 @@ public class ImageTexture implements Texture, Animatable {
mImage.advance();
long delay = mImage.getDelay();
long time = System.currentTimeMillis();
delay -= time - lastTime;
long time = SystemClock.elapsedRealtime();
if (-1L != lastDelay) {
delay -= (time - lastTime) - lastDelay;
}
lastTime = time;
lastDelay = delay;
mFrameDirty.lazySet(true);
invalidateSelf();
@@ -573,28 +573,34 @@ public class GLRootView extends GLSurfaceView
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
unfreeze();
super.surfaceChanged(holder, format, w, h);
requestLayoutContentPane();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
unfreeze();
super.surfaceCreated(holder);
if (mContentView != null && !mContentView.isAttachedToRoot()) {
mContentView.attachToRoot(this);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
unfreeze();
super.surfaceDestroyed(holder);
if (mContentView != null && mContentView.isAttachedToRoot()) {
mContentView.detachFromRoot();
}
}
@Override
protected void onDetachedFromWindow() {
unfreeze();
super.onDetachedFromWindow();
if (mContentView != null) {
mContentView.detachFromRoot();
}
}
/**
@@ -16,6 +16,8 @@
package com.hippo.okhttp;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@@ -176,6 +178,35 @@ public class CookieDBStore implements CookieJar {
}
}
private Cookie getInternal(HttpUrl url, String name, List<CookieWithID> cookies) {
for (Iterator<CookieWithID> i = cookies.iterator(); i.hasNext();) {
CookieWithID cwi = i.next();
Cookie cookie = cwi.cookie;
// Check expired
if (hasExpired(cookie)) {
// Remove from list
i.remove();
// Remove from DB
CookieDB.removeCookie(cwi.id);
} else if (cookie.name().equals(name) && cookie.matches(url)) {
return cookie;
}
}
return null;
}
@Nullable
public synchronized Cookie get(HttpUrl url, String name) {
String host = url.host();
for (String key : map.keySet()) {
if (domainMatch(host, key)) {
List<CookieWithID> cookies = map.get(key);
return getInternal(url, name, cookies);
}
}
return null;
}
public synchronized List<Cookie> get(HttpUrl url) {
List<Cookie> result = new ArrayList<>();
@@ -185,6 +216,7 @@ public class CookieDBStore implements CookieJar {
List<CookieWithID> cookies = map.get(key);
// cookies can not be null
getInternal(url, cookies, result);
break;
}
}
@@ -16,11 +16,9 @@
package com.hippo.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Build;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
@@ -48,12 +46,6 @@ public class ActivityPreference extends Preference {
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ActivityPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ActivityPreference, defStyleAttr, defStyleRes);
String clazzName = a.getString(R.styleable.ActivityPreference_activity);
@@ -16,14 +16,12 @@
package com.hippo.preference;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
@@ -79,12 +77,6 @@ public abstract class DialogPreference extends Preference implements
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DialogPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DialogPreference, defStyleAttr, defStyleRes);
mDialogTitle = a.getString(R.styleable.DialogPreference_dialogTitle);
@@ -52,11 +52,6 @@ public class ListPreference extends DialogPreference {
init(context, attrs, defStyleAttr, 0);
}
public ListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
setNegativeButtonText(android.R.string.cancel);
@@ -16,10 +16,8 @@
package com.hippo.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
@@ -34,7 +32,6 @@ public class MessagePreference extends DialogPreference {
private CharSequence mDialogMessage;
private boolean mDialogMessageLinkify;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MessagePreference(Context context) {
super(context);
init(context, null, 0, 0);
@@ -50,12 +47,6 @@ public class MessagePreference extends DialogPreference {
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MessagePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MessagePreference, defStyleAttr, defStyleRes);
String message = a.getString(R.styleable.MessagePreference_dialogMessage);
@@ -16,10 +16,8 @@
package com.hippo.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.preference.TwoStatePreference;
import android.support.annotation.StringRes;
import android.support.v7.widget.SwitchCompat;
@@ -82,12 +80,6 @@ public class SwitchPreference extends TwoStatePreference {
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
setWidgetLayoutResource(R.layout.preference_widget_fixed_switch);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchPreference, defStyleAttr, defStyleRes);
@@ -60,6 +60,6 @@ public class UrlPreference extends Preference {
@Override
protected void onClick() {
UrlOpener.openUrl(getContext(), mUrl, true, true);
UrlOpener.openUrl(getContext(), mUrl, true);
}
}
@@ -223,7 +223,7 @@ public class LinkMovementMethod2 extends ScrollingMovementMethod {
if (action == MotionEvent.ACTION_UP) {
ClickableSpan span = link[0];
if (span instanceof URLSpan) {
UrlOpener.openUrl(widget.getContext(), ((URLSpan) span).getURL(), true, true);
UrlOpener.openUrl(widget.getContext(), ((URLSpan) span).getURL(), true);
} else {
span.onClick(widget);
}
@@ -17,6 +17,7 @@
package com.hippo.util;
import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.Context;
@@ -30,7 +31,7 @@ import android.widget.Toast;
import com.hippo.ehviewer.R;
public class ActivityHelper {
public class AppHelper {
public static boolean sendEmail(@NonNull Activity from, @NonNull String address,
@Nullable String subject, @Nullable String text) {
@@ -86,4 +87,12 @@ public class ActivityHelper {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public static void hideSoftInput(Dialog dialog) {
View view = dialog.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) dialog.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
@@ -1,167 +0,0 @@
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Helper class for Custom Tabs.
*/
public class CustomTabsHelper {
private static final String TAG = "CustomTabsHelper";
static final String STABLE_PACKAGE = "com.android.chrome";
static final String BETA_PACKAGE = "com.chrome.beta";
static final String DEV_PACKAGE = "com.chrome.dev";
static final String LOCAL_PACKAGE = "com.google.android.apps.chrome";
private static final String ACTION_CUSTOM_TABS_CONNECTION =
"android.support.customtabs.action.CustomTabsService";
private static final String UNINITIALIZED = "UNINITIALIZED";
private static String sPackageNameToUse = UNINITIALIZED;
private CustomTabsHelper() {}
/**
* The browser of smartisan is terrible
*/
public static String getPackageNameToUseFixed(Context context) {
if (!UNINITIALIZED.equals(sPackageNameToUse)) return sPackageNameToUse;
PackageManager pm = context.getPackageManager();
// Get all apps that can handle VIEW intents.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
List<String> packagesSupportingCustomTabs = new ArrayList<>();
for (ResolveInfo info : resolvedActivityList) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(serviceIntent, 0) != null) {
packagesSupportingCustomTabs.add(info.activityInfo.packageName);
}
}
// Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls.
if (packagesSupportingCustomTabs.isEmpty()) {
sPackageNameToUse = null;
} else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
sPackageNameToUse = STABLE_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
sPackageNameToUse = BETA_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
sPackageNameToUse = DEV_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
sPackageNameToUse = LOCAL_PACKAGE;
} else {
sPackageNameToUse = null;
}
return sPackageNameToUse;
}
/**
* Goes through all apps that handle VIEW intents and have a warmup service. Picks
* the one chosen by the user if there is one, otherwise makes a best effort to return a
* valid package name.
*
* This is <strong>not</strong> threadsafe.
*
* @param context {@link Context} to use for accessing {@link PackageManager}.
* @return The package name recommended to use for connecting to custom tabs related components.
*/
public static String getPackageNameToUse(Context context) {
if (sPackageNameToUse != null) return sPackageNameToUse;
PackageManager pm = context.getPackageManager();
// Get default VIEW intent handler.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
String defaultViewHandlerPackageName = null;
if (defaultViewHandlerInfo != null) {
defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
}
// Get all apps that can handle VIEW intents.
List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
List<String> packagesSupportingCustomTabs = new ArrayList<>();
for (ResolveInfo info : resolvedActivityList) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(serviceIntent, 0) != null) {
packagesSupportingCustomTabs.add(info.activityInfo.packageName);
}
}
// Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls.
if (packagesSupportingCustomTabs.isEmpty()) {
sPackageNameToUse = null;
} else if (packagesSupportingCustomTabs.size() == 1) {
sPackageNameToUse = packagesSupportingCustomTabs.get(0);
} else if (!TextUtils.isEmpty(defaultViewHandlerPackageName)
&& !hasSpecializedHandlerIntents(context, activityIntent)
&& packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
sPackageNameToUse = defaultViewHandlerPackageName;
} else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
sPackageNameToUse = STABLE_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
sPackageNameToUse = BETA_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
sPackageNameToUse = DEV_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
sPackageNameToUse = LOCAL_PACKAGE;
}
return sPackageNameToUse;
}
/**
* Used to check whether there is a specialized handler for a given intent.
* @param intent The intent to check with.
* @return Whether there is a specialized handler for the given intent.
*/
private static boolean hasSpecializedHandlerIntents(Context context, Intent intent) {
try {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> handlers = pm.queryIntentActivities(
intent,
PackageManager.GET_RESOLVED_FILTER);
if (handlers == null || handlers.size() == 0) {
return false;
}
for (ResolveInfo resolveInfo : handlers) {
IntentFilter filter = resolveInfo.filter;
if (filter == null) continue;
if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue;
if (resolveInfo.activityInfo == null) continue;
return true;
}
} catch (RuntimeException e) {
Log.e(TAG, "Runtime exception while getting specialized handlers");
}
return false;
}
}
@@ -17,15 +17,16 @@
package com.hippo.util;
import android.content.Context;
import android.support.annotation.NonNull;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.network.StatusCodeException;
import org.apache.http.conn.ConnectTimeoutException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
@@ -36,28 +37,30 @@ public final class ExceptionUtils {
private static final String TAG = ExceptionUtils.class.getSimpleName();
@NonNull
public static String getReadableString(@NonNull Context context, @NonNull Exception e) {
if (e instanceof ConnectTimeoutException ||
public static String getReadableString(@NonNull Exception e) {
if (e instanceof MalformedURLException) {
return GetText.getString(R.string.error_invalid_url);
} else if (e instanceof ConnectTimeoutException ||
e instanceof SocketTimeoutException) {
return context.getString(R.string.error_timeout);
return GetText.getString(R.string.error_timeout);
} else if (e instanceof UnknownHostException) {
return context.getString(R.string.error_unknown_host);
return GetText.getString(R.string.error_unknown_host);
} else if (e instanceof StatusCodeException) {
StatusCodeException sce = (StatusCodeException) e;
StringBuilder sb = new StringBuilder();
sb.append(context.getString(R.string.error_bad_status_code, sce.getResponseCode()));
sb.append(GetText.getString(R.string.error_bad_status_code, sce.getResponseCode()));
if (sce.isIdentifiedResponseCode()) {
sb.append(", ").append(sce.getMessage());
}
return sb.toString();
} else if (e instanceof ProtocolException && e.getMessage().startsWith("Too many follow-up requests:")) {
return context.getString(R.string.error_redirection);
return GetText.getString(R.string.error_redirection);
} else if (e instanceof ProtocolException || e instanceof SocketException) {
return context.getString(R.string.error_socket);
return GetText.getString(R.string.error_socket);
} else if (e instanceof EhException) {
return e.getMessage();
} else {
return context.getString(R.string.error_unknown);
return GetText.getString(R.string.error_unknown);
}
}
}
@@ -56,4 +56,13 @@ public final class TextUrl {
return spannable == null ? content : spannable;
}
public static String getFileName(String path) {
if (path == null) {
return path;
}
int start = path.lastIndexOf("/");
return start == -1 ? path : path.substring(start + 1);
}
}
@@ -34,7 +34,7 @@ import android.view.animation.Interpolator;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.hotspot.HotspotTouchHelper;
import com.hippo.hotspot.Hotspot;
import com.hippo.hotspot.Hotspotable;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.MathUtils;
@@ -81,7 +81,7 @@ public class CheckTextView extends TextView implements OnClickListener, Hotspota
setOnClickListener(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
HotspotTouchHelper.setHotspotTouchHelper(this, new HotspotTouchHelper(this));
Hotspot.addHotspotable(this, this);
}
}
@@ -111,7 +111,7 @@ public class CheckTextView extends TextView implements OnClickListener, Hotspota
return mRadius;
}
private Animator.AnimatorListener mAnimatorListener = new SimpleAnimatorListener() {
private final Animator.AnimatorListener mAnimatorListener = new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimator = null;
@@ -36,10 +36,10 @@ import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.LayoutManagerUtils;
import com.hippo.ehviewer.R;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.view.ViewTransition;
import com.hippo.widget.refreshlayout.RefreshLayout;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
@@ -670,7 +670,7 @@ public class ContentLayout extends FrameLayout {
String readableError;
if (e != null) {
e.printStackTrace();
readableError = ExceptionUtils.getReadableString(getContext(), e);
readableError = ExceptionUtils.getReadableString(e);
} else {
readableError = getContext().getString(R.string.error_unknown);
}
@@ -28,7 +28,7 @@ import android.widget.TextView;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
import com.hippo.ehviewer.R;
import com.hippo.rippleold.RippleSalon;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.LayoutUtils;
import java.io.File;
@@ -77,7 +77,7 @@ public class DirExplorer extends EasyRecyclerView implements EasyRecyclerView.On
LayoutUtils.dp2pix(context, 1));
decoration.setShowLastDivider(true);
addItemDecoration(decoration);
setSelector(RippleSalon.generateRippleDrawable(false));
setSelector(Ripple.generateRippleDrawable(context, false));
setOnItemClickListener(this);
mCurrentFile = Environment.getExternalStorageDirectory();
@@ -1,153 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.refreshlayout;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.v4.view.ViewCompat;
import android.view.animation.Animation;
import android.widget.ImageView;
/**
* Private class created to work around issues with AnimationListeners being
* called before the animation is actually complete and support shadows on older
* platforms.
*
* @hide
*/
class CircleImageView extends ImageView {
private static final int KEY_SHADOW_COLOR = 0x1E000000;
private static final int FILL_SHADOW_COLOR = 0x3D000000;
// PX
private static final float X_OFFSET = 0f;
private static final float Y_OFFSET = 1.75f;
private static final float SHADOW_RADIUS = 3.5f;
private static final int SHADOW_ELEVATION = 4;
private Animation.AnimationListener mListener;
private int mShadowRadius;
public CircleImageView(Context context, int color, final float radius) {
super(context);
final float density = getContext().getResources().getDisplayMetrics().density;
final int diameter = (int) (radius * density * 2);
final int shadowYOffset = (int) (density * Y_OFFSET);
final int shadowXOffset = (int) (density * X_OFFSET);
mShadowRadius = (int) (density * SHADOW_RADIUS);
ShapeDrawable circle;
if (elevationSupported()) {
circle = new ShapeDrawable(new OvalShape());
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
} else {
OvalShape oval = new OvalShadow(mShadowRadius, diameter);
circle = new ShapeDrawable(oval);
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint());
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
KEY_SHADOW_COLOR);
final int padding = mShadowRadius;
// set padding so the inner image sits correctly within the shadow.
setPadding(padding, padding, padding, padding);
}
circle.getPaint().setColor(color);
setBackgroundDrawable(circle);
}
private boolean elevationSupported() {
return android.os.Build.VERSION.SDK_INT >= 21;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!elevationSupported()) {
setMeasuredDimension(getMeasuredWidth() + mShadowRadius*2, getMeasuredHeight()
+ mShadowRadius*2);
}
}
public void setAnimationListener(Animation.AnimationListener listener) {
mListener = listener;
}
@Override
public void onAnimationStart() {
super.onAnimationStart();
if (mListener != null) {
mListener.onAnimationStart(getAnimation());
}
}
@Override
public void onAnimationEnd() {
super.onAnimationEnd();
if (mListener != null) {
mListener.onAnimationEnd(getAnimation());
}
}
/**
* Update the background color of the circle image view.
*
* @param colorRes Id of a color resource.
*/
public void setBackgroundColorRes(int colorRes) {
setBackgroundColor(getContext().getResources().getColor(colorRes));
}
@Override
public void setBackgroundColor(int color) {
if (getBackground() instanceof ShapeDrawable) {
((ShapeDrawable) getBackground()).getPaint().setColor(color);
}
}
private class OvalShadow extends OvalShape {
private RadialGradient mRadialGradient;
private Paint mShadowPaint;
private int mCircleDiameter;
public OvalShadow(int shadowRadius, int circleDiameter) {
super();
mShadowPaint = new Paint();
mShadowRadius = shadowRadius;
mCircleDiameter = circleDiameter;
mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2,
mShadowRadius, new int[] {
FILL_SHADOW_COLOR, Color.TRANSPARENT
}, null, Shader.TileMode.CLAMP);
mShadowPaint.setShader(mRadialGradient);
}
@Override
public void draw(Canvas canvas, Paint paint) {
final int viewWidth = CircleImageView.this.getWidth();
final int viewHeight = CircleImageView.this.getHeight();
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
mShadowPaint);
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
}
}
}
@@ -1,791 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.refreshlayout;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
* Fancy progress indicator for Material theme.
*
* @hide
*/
class MaterialProgressDrawable extends Drawable implements Animatable {
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
private static final float FULL_ROTATION = 1080.0f;
@Retention(RetentionPolicy.CLASS)
@IntDef({LARGE, DEFAULT})
public @interface ProgressDrawableSize {}
// Maps to ProgressBar.Large style
static final int LARGE = 0;
// Maps to ProgressBar default style
static final int DEFAULT = 1;
// Maps to ProgressBar default style
private static final int CIRCLE_DIAMETER = 40;
private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
private static final float STROKE_WIDTH = 2.5f;
// Maps to ProgressBar.Large style
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float CENTER_RADIUS_LARGE = 12.5f;
private static final float STROKE_WIDTH_LARGE = 3f;
private final int[] COLORS = new int[] {
Color.BLACK
};
/**
* The value in the linear interpolator for animating the drawable at which
* the color transition should start
*/
private static final float COLOR_START_DELAY_OFFSET = 0.75f;
private static final float END_TRIM_START_DELAY_OFFSET = 0.5f;
private static final float START_TRIM_DURATION_OFFSET = 0.5f;
/** The duration of a single progress spin in milliseconds. */
private static final int ANIMATION_DURATION = 1332;
/** The number of points in the progress "star". */
private static final float NUM_POINTS = 5f;
/** The list of animators operating on this drawable. */
private final ArrayList<Animation> mAnimators = new ArrayList<Animation>();
/** The indicator ring, used to manage animation state. */
private final Ring mRing;
/** Canvas rotation in degrees. */
private float mRotation;
/** Layout info for the arrowhead in dp */
private static final int ARROW_WIDTH = 10;
private static final int ARROW_HEIGHT = 5;
private static final float ARROW_OFFSET_ANGLE = 5;
/** Layout info for the arrowhead for the large spinner in dp */
private static final int ARROW_WIDTH_LARGE = 12;
private static final int ARROW_HEIGHT_LARGE = 6;
private static final float MAX_PROGRESS_ARC = .8f;
private Resources mResources;
private View mParent;
private Animation mAnimation;
private float mRotationCount;
private double mWidth;
private double mHeight;
boolean mFinishing;
public MaterialProgressDrawable(Context context, View parent) {
mParent = parent;
mResources = context.getResources();
mRing = new Ring(mCallback);
mRing.setColors(COLORS);
updateSizes(DEFAULT);
setupAnimators();
}
private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) {
final Ring ring = mRing;
final DisplayMetrics metrics = mResources.getDisplayMetrics();
final float screenDensity = metrics.density;
mWidth = progressCircleWidth * screenDensity;
mHeight = progressCircleHeight * screenDensity;
ring.setStrokeWidth((float) strokeWidth * screenDensity);
ring.setCenterRadius(centerRadius * screenDensity);
ring.setColorIndex(0);
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
ring.setInsets((int) mWidth, (int) mHeight);
}
/**
* Set the overall size for the progress spinner. This updates the radius
* and stroke width of the ring.
*
* @param size One of {@link #LARGE} or
* {@link #DEFAULT}
*/
public void updateSizes(@ProgressDrawableSize int size) {
if (size == LARGE) {
setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
} else {
setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
ARROW_WIDTH, ARROW_HEIGHT);
}
}
/**
* @param show Set to true to display the arrowhead on the progress spinner.
*/
public void showArrow(boolean show) {
mRing.setShowArrow(show);
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
mRing.setArrowScale(scale);
}
/**
* Set the start and end trim for the progress spinner arc.
*
* @param startAngle start angle
* @param endAngle end angle
*/
public void setStartEndTrim(float startAngle, float endAngle) {
mRing.setStartTrim(startAngle);
mRing.setEndTrim(endAngle);
}
/**
* Set the amount of rotation to apply to the progress spinner.
*
* @param rotation Rotation is from [0..1]
*/
public void setProgressRotation(float rotation) {
mRing.setRotation(rotation);
}
/**
* Update the background color of the circle image view.
*/
public void setBackgroundColor(int color) {
mRing.setBackgroundColor(color);
}
/**
* Set the colors used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
mRing.setColors(colors);
mRing.setColorIndex(0);
}
@Override
public int getIntrinsicHeight() {
return (int) mHeight;
}
@Override
public int getIntrinsicWidth() {
return (int) mWidth;
}
@Override
public void draw(Canvas c) {
final Rect bounds = getBounds();
final int saveCount = c.save();
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
mRing.draw(c, bounds);
c.restoreToCount(saveCount);
}
@Override
public void setAlpha(int alpha) {
mRing.setAlpha(alpha);
}
public int getAlpha() {
return mRing.getAlpha();
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mRing.setColorFilter(colorFilter);
}
@SuppressWarnings("unused")
void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
private float getRotation() {
return mRotation;
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public boolean isRunning() {
final ArrayList<Animation> animators = mAnimators;
final int N = animators.size();
for (int i = 0; i < N; i++) {
final Animation animator = animators.get(i);
if (animator.hasStarted() && !animator.hasEnded()) {
return true;
}
}
return false;
}
@Override
public void start() {
mAnimation.reset();
mRing.storeOriginals();
// Already showing some part of the ring
if (mRing.getEndTrim() != mRing.getStartTrim()) {
mFinishing = true;
mAnimation.setDuration(ANIMATION_DURATION/2);
mParent.startAnimation(mAnimation);
} else {
mRing.setColorIndex(0);
mRing.resetOriginals();
mAnimation.setDuration(ANIMATION_DURATION);
mParent.startAnimation(mAnimation);
}
}
@Override
public void stop() {
mParent.clearAnimation();
setRotation(0);
mRing.setShowArrow(false);
mRing.setColorIndex(0);
mRing.resetOriginals();
}
private float getMinProgressArc(Ring ring) {
return (float) Math.toRadians(
ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
}
// Adapted from ArgbEvaluator.java
private int evaluateColorChange(float fraction, int startValue, int endValue) {
int startInt = (Integer) startValue;
int startA = (startInt >> 24) & 0xff;
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24) & 0xff;
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int)((startA + (int)(fraction * (endA - startA))) << 24) |
(int)((startR + (int)(fraction * (endR - startR))) << 16) |
(int)((startG + (int)(fraction * (endG - startG))) << 8) |
(int)((startB + (int)(fraction * (endB - startB))));
}
/**
* Update the ring color if this is within the last 25% of the animation.
* The new ring color will be a translation from the starting ring color to
* the next color.
*/
private void updateRingColor(float interpolatedTime, Ring ring) {
if (interpolatedTime > COLOR_START_DELAY_OFFSET) {
// scale the interpolatedTime so that the full
// transformation from 0 - 1 takes place in the
// remaining time
ring.setColor(evaluateColorChange((interpolatedTime - COLOR_START_DELAY_OFFSET)
/ (1.0f - COLOR_START_DELAY_OFFSET), ring.getStartingColor(),
ring.getNextColor()));
}
}
private void applyFinishTranslation(float interpolatedTime, Ring ring) {
// shrink back down and complete a full rotation before
// starting other circles
// Rotation goes between [0..1].
updateRingColor(interpolatedTime, ring);
float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
+ 1f);
final float minProgressArc = getMinProgressArc(ring);
final float startTrim = ring.getStartingStartTrim()
+ (ring.getStartingEndTrim() - minProgressArc - ring.getStartingStartTrim())
* interpolatedTime;
ring.setStartTrim(startTrim);
ring.setEndTrim(ring.getStartingEndTrim());
final float rotation = ring.getStartingRotation()
+ ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
ring.setRotation(rotation);
}
private void setupAnimators() {
final Ring ring = mRing;
final Animation animation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
if (mFinishing) {
applyFinishTranslation(interpolatedTime, ring);
} else {
// The minProgressArc is calculated from 0 to create an
// angle that matches the stroke width.
final float minProgressArc = getMinProgressArc(ring);
final float startingEndTrim = ring.getStartingEndTrim();
final float startingTrim = ring.getStartingStartTrim();
final float startingRotation = ring.getStartingRotation();
updateRingColor(interpolatedTime, ring);
// Moving the start trim only occurs in the first 50% of a
// single ring animation
if (interpolatedTime <= START_TRIM_DURATION_OFFSET) {
// scale the interpolatedTime so that the full
// transformation from 0 - 1 takes place in the
// remaining time
final float scaledTime = (interpolatedTime)
/ (1.0f - START_TRIM_DURATION_OFFSET);
final float startTrim = startingTrim
+ ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR
.getInterpolation(scaledTime));
ring.setStartTrim(startTrim);
}
// Moving the end trim starts after 50% of a single ring
// animation completes
if (interpolatedTime > END_TRIM_START_DELAY_OFFSET) {
// scale the interpolatedTime so that the full
// transformation from 0 - 1 takes place in the
// remaining time
final float minArc = MAX_PROGRESS_ARC - minProgressArc;
float scaledTime = (interpolatedTime - START_TRIM_DURATION_OFFSET)
/ (1.0f - START_TRIM_DURATION_OFFSET);
final float endTrim = startingEndTrim
+ (minArc * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime));
ring.setEndTrim(endTrim);
}
final float rotation = startingRotation + (0.25f * interpolatedTime);
ring.setRotation(rotation);
float groupRotation = ((FULL_ROTATION / NUM_POINTS) * interpolatedTime)
+ (FULL_ROTATION * (mRotationCount / NUM_POINTS));
setRotation(groupRotation);
}
}
};
animation.setRepeatCount(Animation.INFINITE);
animation.setRepeatMode(Animation.RESTART);
animation.setInterpolator(LINEAR_INTERPOLATOR);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mRotationCount = 0;
}
@Override
public void onAnimationEnd(Animation animation) {
// do nothing
}
@Override
public void onAnimationRepeat(Animation animation) {
ring.storeOriginals();
ring.goToNextColor();
ring.setStartTrim(ring.getEndTrim());
if (mFinishing) {
// finished closing the last ring from the swipe gesture; go
// into progress mode
mFinishing = false;
animation.setDuration(ANIMATION_DURATION);
ring.setShowArrow(false);
} else {
mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
}
}
});
mAnimation = animation;
}
private final Callback mCallback = new Callback() {
@Override
public void invalidateDrawable(Drawable d) {
invalidateSelf();
}
@Override
public void scheduleDrawable(Drawable d, Runnable what, long when) {
scheduleSelf(what, when);
}
@Override
public void unscheduleDrawable(Drawable d, Runnable what) {
unscheduleSelf(what);
}
};
private static class Ring {
private final RectF mTempBounds = new RectF();
private final Paint mPaint = new Paint();
private final Paint mArrowPaint = new Paint();
private final Callback mCallback;
private float mStartTrim = 0.0f;
private float mEndTrim = 0.0f;
private float mRotation = 0.0f;
private float mStrokeWidth = 5.0f;
private float mStrokeInset = 2.5f;
private int[] mColors;
// mColorIndex represents the offset into the available mColors that the
// progress circle should currently display. As the progress circle is
// animating, the mColorIndex moves by one to the next available color.
private int mColorIndex;
private float mStartingStartTrim;
private float mStartingEndTrim;
private float mStartingRotation;
private boolean mShowArrow;
private Path mArrow;
private float mArrowScale;
private double mRingCenterRadius;
private int mArrowWidth;
private int mArrowHeight;
private int mAlpha;
private final Paint mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int mBackgroundColor;
private int mCurrentColor;
public Ring(Callback callback) {
mCallback = callback;
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setAntiAlias(true);
mPaint.setStyle(Style.STROKE);
mArrowPaint.setStyle(Style.FILL);
mArrowPaint.setAntiAlias(true);
}
public void setBackgroundColor(int color) {
mBackgroundColor = color;
}
/**
* Set the dimensions of the arrowhead.
*
* @param width Width of the hypotenuse of the arrow head
* @param height Height of the arrow point
*/
public void setArrowDimensions(float width, float height) {
mArrowWidth = (int) width;
mArrowHeight = (int) height;
}
/**
* Draw the progress spinner
*/
public void draw(Canvas c, Rect bounds) {
final RectF arcBounds = mTempBounds;
arcBounds.set(bounds);
arcBounds.inset(mStrokeInset, mStrokeInset);
final float startAngle = (mStartTrim + mRotation) * 360;
final float endAngle = (mEndTrim + mRotation) * 360;
float sweepAngle = endAngle - startAngle;
mPaint.setColor(mCurrentColor);
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
drawTriangle(c, startAngle, sweepAngle, bounds);
if (mAlpha < 255) {
mCirclePaint.setColor(mBackgroundColor);
mCirclePaint.setAlpha(255 - mAlpha);
c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2,
mCirclePaint);
}
}
private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
if (mShowArrow) {
if (mArrow == null) {
mArrow = new Path();
mArrow.setFillType(Path.FillType.EVEN_ODD);
} else {
mArrow.reset();
}
// Adjust the position of the triangle so that it is inset as
// much as the arc, but also centered on the arc.
float inset = (int) mStrokeInset / 2 * mArrowScale;
float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());
// Update the path each time. This works around an issue in SKIA
// where concatenating a rotation matrix to a scale matrix
// ignored a starting negative rotation. This appears to have
// been fixed as of API 21.
mArrow.moveTo(0, 0);
mArrow.lineTo(mArrowWidth * mArrowScale, 0);
mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
* mArrowScale));
mArrow.offset(x - inset, y);
mArrow.close();
// draw a triangle
mArrowPaint.setColor(mCurrentColor);
c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
bounds.exactCenterY());
c.drawPath(mArrow, mArrowPaint);
}
}
/**
* Set the colors the progress spinner alternates between.
*
* @param colors Array of integers describing the colors. Must be non-<code>null</code>.
*/
public void setColors(@NonNull int[] colors) {
mColors = colors;
// if colors are reset, make sure to reset the color index as well
setColorIndex(0);
}
/**
* Set the absolute color of the progress spinner. This is should only
* be used when animating between current and next color when the
* spinner is rotating.
*
* @param color int describing the color.
*/
public void setColor(int color) {
mCurrentColor = color;
}
/**
* @param index Index into the color array of the color to display in
* the progress spinner.
*/
public void setColorIndex(int index) {
mColorIndex = index;
mCurrentColor = mColors[mColorIndex];
}
/**
* @return int describing the next color the progress spinner should use when drawing.
*/
public int getNextColor() {
return mColors[getNextColorIndex()];
}
private int getNextColorIndex() {
return (mColorIndex + 1) % (mColors.length);
}
/**
* Proceed to the next available ring color. This will automatically
* wrap back to the beginning of colors.
*/
public void goToNextColor() {
setColorIndex(getNextColorIndex());
}
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
invalidateSelf();
}
/**
* @param alpha Set the alpha of the progress spinner and associated arrowhead.
*/
public void setAlpha(int alpha) {
mAlpha = alpha;
}
/**
* @return Current alpha of the progress spinner and arrowhead.
*/
public int getAlpha() {
return mAlpha;
}
/**
* @param strokeWidth Set the stroke width of the progress spinner in pixels.
*/
public void setStrokeWidth(float strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(strokeWidth);
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStrokeWidth() {
return mStrokeWidth;
}
@SuppressWarnings("unused")
public void setStartTrim(float startTrim) {
mStartTrim = startTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStartTrim() {
return mStartTrim;
}
public float getStartingStartTrim() {
return mStartingStartTrim;
}
public float getStartingEndTrim() {
return mStartingEndTrim;
}
public int getStartingColor() {
return mColors[mColorIndex];
}
@SuppressWarnings("unused")
public void setEndTrim(float endTrim) {
mEndTrim = endTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getEndTrim() {
return mEndTrim;
}
@SuppressWarnings("unused")
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getRotation() {
return mRotation;
}
public void setInsets(int width, int height) {
final float minEdge = (float) Math.min(width, height);
float insets;
if (mRingCenterRadius <= 0 || minEdge < 0) {
insets = (float) Math.ceil(mStrokeWidth / 2.0f);
} else {
insets = (float) (minEdge / 2.0f - mRingCenterRadius);
}
mStrokeInset = insets;
}
@SuppressWarnings("unused")
public float getInsets() {
return mStrokeInset;
}
/**
* @param centerRadius Inner radius in px of the circle the progress
* spinner arc traces.
*/
public void setCenterRadius(double centerRadius) {
mRingCenterRadius = centerRadius;
}
public double getCenterRadius() {
return mRingCenterRadius;
}
/**
* @param show Set to true to show the arrow head on the progress spinner.
*/
public void setShowArrow(boolean show) {
if (mShowArrow != show) {
mShowArrow = show;
invalidateSelf();
}
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
if (scale != mArrowScale) {
mArrowScale = scale;
invalidateSelf();
}
}
/**
* @return The amount the progress spinner is currently rotated, between [0..1].
*/
public float getStartingRotation() {
return mStartingRotation;
}
/**
* If the start / end trim are offset to begin with, store them so that
* animation starts from that offset.
*/
public void storeOriginals() {
mStartingStartTrim = mStartTrim;
mStartingEndTrim = mEndTrim;
mStartingRotation = mRotation;
}
/**
* Reset the progress spinner to default rotation, start and end angles.
*/
public void resetOriginals() {
mStartingStartTrim = 0;
mStartingEndTrim = 0;
mStartingRotation = 0;
setStartTrim(0);
setEndTrim(0);
setRotation(0);
}
private void invalidateSelf() {
mCallback.invalidateDrawable(null);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,277 +0,0 @@
/*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.refreshlayout;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
/**
* Custom progress bar that shows a cycle of colors as widening circles that
* overdraw each other. When finished, the bar is cleared from the inside out as
* the main cycle continues. Before running, this can also indicate how close
* the user is to triggering something (e.g. how far they need to pull down to
* trigger a refresh).
*/
final class SwipeProgressBar {
// Default progress animation colors are grays.
private final static int COLOR1 = 0xB3000000;
private final static int COLOR2 = 0x80000000;
private final static int COLOR3 = 0x4d000000;
private final static int COLOR4 = 0x1a000000;
// The duration of the animation cycle.
private static final int ANIMATION_DURATION_MS = 2000;
// The duration of the animation to clear the bar.
private static final int FINISH_ANIMATION_DURATION_MS = 1000;
// Interpolator for varying the speed of the animation.
private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
private final Paint mPaint = new Paint();
private final RectF mClipRect = new RectF();
private float mTriggerPercentage;
private long mStartTime;
private long mFinishTime;
private boolean mRunning;
// Colors used when rendering the animation,
private int mColor1;
private int mColor2;
private int mColor3;
private int mColor4;
private View mParent;
private Rect mBounds = new Rect();
public SwipeProgressBar(View parent) {
mParent = parent;
mColor1 = COLOR1;
mColor2 = COLOR2;
mColor3 = COLOR3;
mColor4 = COLOR4;
}
/**
* Set the four colors used in the progress animation. The first color will
* also be the color of the bar that grows in response to a user swipe
* gesture.
*
* @param color1 Integer representation of a color.
* @param color2 Integer representation of a color.
* @param color3 Integer representation of a color.
* @param color4 Integer representation of a color.
*/
void setColorScheme(int color1, int color2, int color3, int color4) {
mColor1 = color1;
mColor2 = color2;
mColor3 = color3;
mColor4 = color4;
}
/**
* Update the progress the user has made toward triggering the swipe
* gesture. and use this value to update the percentage of the trigger that
* is shown.
*/
void setTriggerPercentage(float triggerPercentage) {
mTriggerPercentage = triggerPercentage;
mStartTime = 0;
ViewCompat.postInvalidateOnAnimation(
mParent, mBounds.left, mBounds.top, mBounds.right, mBounds.bottom);
}
/**
* Start showing the progress animation.
*/
void start() {
if (!mRunning) {
mTriggerPercentage = 0;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = true;
mParent.postInvalidate();
}
}
/**
* Stop showing the progress animation.
*/
void stop() {
if (mRunning) {
mTriggerPercentage = 0;
mFinishTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = false;
mParent.postInvalidate();
}
}
/**
* @return Return whether the progress animation is currently running.
*/
boolean isRunning() {
return mRunning || mFinishTime > 0;
}
void draw(Canvas canvas) {
Rect bounds = mBounds;
final int width = bounds.width();
final int height = bounds.height();
final int cx = bounds.centerX();
final int cy = bounds.centerY();
boolean drawTriggerWhileFinishing = false;
int restoreCount = canvas.save();
canvas.clipRect(bounds);
if (mRunning || (mFinishTime > 0)) {
long now = AnimationUtils.currentAnimationTimeMillis();
long elapsed = (now - mStartTime) % ANIMATION_DURATION_MS;
long iterations = (now - mStartTime) / ANIMATION_DURATION_MS;
float rawProgress = (elapsed / (ANIMATION_DURATION_MS / 100f));
// If we're not running anymore, that means we're running through
// the finish animation.
if (!mRunning) {
// If the finish animation is done, don't draw anything, and
// don't repost.
if ((now - mFinishTime) >= FINISH_ANIMATION_DURATION_MS) {
mFinishTime = 0;
return;
}
// Otherwise, use a 0 opacity alpha layer to clear the animation
// from the inside out. This layer will prevent the circles from
// drawing within its bounds.
long finishElapsed = (now - mFinishTime) % FINISH_ANIMATION_DURATION_MS;
float finishProgress = (finishElapsed / (FINISH_ANIMATION_DURATION_MS / 100f));
float pct = (finishProgress / 100f);
// Radius of the circle is half of the screen.
float clearRadius = width / 2 * INTERPOLATOR.getInterpolation(pct);
mClipRect.set(cx - clearRadius, 0, cx + clearRadius, height);
canvas.saveLayerAlpha(mClipRect, 0, 0);
// Only draw the trigger if there is a space in the center of
// this refreshing view that needs to be filled in by the
// trigger. If the progress view is just still animating, let it
// continue animating.
drawTriggerWhileFinishing = true;
}
// First fill in with the last color that would have finished drawing.
if (iterations == 0) {
canvas.drawColor(mColor1);
} else {
if (rawProgress >= 0 && rawProgress < 25) {
canvas.drawColor(mColor4);
} else if (rawProgress >= 25 && rawProgress < 50) {
canvas.drawColor(mColor1);
} else if (rawProgress >= 50 && rawProgress < 75) {
canvas.drawColor(mColor2);
} else {
canvas.drawColor(mColor3);
}
}
// Then draw up to 4 overlapping concentric circles of varying radii, based on how far
// along we are in the cycle.
// progress 0-50 draw mColor2
// progress 25-75 draw mColor3
// progress 50-100 draw mColor4
// progress 75 (wrap to 25) draw mColor1
if ((rawProgress >= 0 && rawProgress <= 25)) {
float pct = (((rawProgress + 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (rawProgress >= 0 && rawProgress <= 50) {
float pct = ((rawProgress * 2) / 100f);
drawCircle(canvas, cx, cy, mColor2, pct);
}
if (rawProgress >= 25 && rawProgress <= 75) {
float pct = (((rawProgress - 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor3, pct);
}
if (rawProgress >= 50 && rawProgress <= 100) {
float pct = (((rawProgress - 50) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor4, pct);
}
if ((rawProgress >= 75 && rawProgress <= 100)) {
float pct = (((rawProgress - 75) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (mTriggerPercentage > 0 && drawTriggerWhileFinishing) {
// There is some portion of trigger to draw. Restore the canvas,
// then draw the trigger. Otherwise, the trigger does not appear
// until after the bar has finished animating and appears to
// just jump in at a larger width than expected.
canvas.restoreToCount(restoreCount);
restoreCount = canvas.save();
canvas.clipRect(bounds);
drawTrigger(canvas, cx, cy);
}
// Keep running until we finish out the last cycle.
ViewCompat.postInvalidateOnAnimation(
mParent, bounds.left, bounds.top, bounds.right, bounds.bottom);
} else {
// Otherwise if we're in the middle of a trigger, draw that.
if (mTriggerPercentage > 0 && mTriggerPercentage <= 1.0) {
drawTrigger(canvas, cx, cy);
}
}
canvas.restoreToCount(restoreCount);
}
private void drawTrigger(Canvas canvas, int cx, int cy) {
mPaint.setColor(mColor1);
canvas.drawCircle(cx, cy, cx * mTriggerPercentage, mPaint);
}
/**
* Draws a circle centered in the view.
*
* @param canvas the canvas to draw on
* @param cx the center x coordinate
* @param cy the center y coordinate
* @param color the color to draw
* @param pct the percentage of the view that the circle should cover
*/
private void drawCircle(Canvas canvas, float cx, float cy, int color, float pct) {
mPaint.setColor(color);
canvas.save();
canvas.translate(cx, cy);
float radiusScale = INTERPOLATOR.getInterpolation(pct);
canvas.scale(radiusScale, radiusScale);
canvas.drawCircle(0, 0, cx, mPaint);
canvas.restore();
}
/**
* Set the drawing bounds of this SwipeProgressBar.
*/
void setBounds(int left, int top, int right, int bottom) {
mBounds.left = left;
mBounds.top = top;
mBounds.right = right;
mBounds.bottom = bottom;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,26 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.slidingdrawerlayout;
public interface SlidingDrawerLayoutChild {
void setFitPadding(int top, int bottom);
int getLayoutPaddingTop();
int getLayoutPaddingBottom();
}
@@ -1,23 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.slidingdrawerlayout;
import android.view.View;
public interface SlidingDrawerLayoutInsetsHelper {
void setupForWindowInsets(View view);
}
@@ -1,32 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.widget.slidingdrawerlayout;
import android.support.v4.view.ViewCompat;
import android.view.View;
public class SlidingDrawerLayoutInsetsHelperL implements SlidingDrawerLayoutInsetsHelper {
@Override
public void setupForWindowInsets(View view) {
if (ViewCompat.getFitsSystemWindows(view)) {
// Now set the sys ui flags to enable us to lay out in the window insets
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
}
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more