mirror of
https://github.com/seven332/EhViewer
synced 2026-11-30 11:08:04 +08:00
Compare commits
273
Commits
0.9.1
...
feature/dict
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1cac3c1ac | ||
|
|
fbeaf3d5ea | ||
|
|
b4d8168457 | ||
|
|
9561fcf662 | ||
|
|
453a56aa23 | ||
|
|
df108f9678 | ||
|
|
a835ca9547 | ||
|
|
3f4cc46bc1 | ||
|
|
27bc38ae8b | ||
|
|
fd1aca48d6 | ||
|
|
adbb1f11a5 | ||
|
|
4b8e46d220 | ||
|
|
1c45c4b042 | ||
|
|
d33e3c27fc | ||
|
|
189a95e49c | ||
|
|
4e3717fa69 | ||
|
|
97d51b1fc3 | ||
|
|
ba5a554ca8 | ||
|
|
b4095449c1 | ||
|
|
05f9ce59f3 | ||
|
|
793dca3674 | ||
|
|
e10172c09c | ||
|
|
2d65b71fff | ||
|
|
7693275967 | ||
|
|
9d4eadffac | ||
|
|
1bf826a923 | ||
|
|
4866e963de | ||
|
|
2b15c8f620 | ||
|
|
d9265610c3 | ||
|
|
81dce7d297 | ||
|
|
078d086362 | ||
|
|
492d483467 | ||
|
|
d9c1b81eb3 | ||
|
|
a2a9dbcb02 | ||
|
|
97c28c04c5 | ||
|
|
f4d8cbf3a4 | ||
|
|
4291493256 | ||
|
|
ce6cb19e73 | ||
|
|
574d09302e | ||
|
|
f37b479400 | ||
|
|
87c27b6256 | ||
|
|
b3881f8562 | ||
|
|
3f8e872d55 | ||
|
|
3924de80b7 | ||
|
|
7e62673e5a | ||
|
|
69be0c48fb | ||
|
|
9d783fa86d | ||
|
|
28b81a0db0 | ||
|
|
3ac1964069 | ||
|
|
a2241e62a3 | ||
|
|
100a3d872e | ||
|
|
413a17acf1 | ||
|
|
79bc2bcd22 | ||
|
|
c6e45cc080 | ||
|
|
dc1e327caa | ||
|
|
7a215acd18 | ||
|
|
84808429cf | ||
|
|
766c265cd6 | ||
|
|
4cce07e0aa | ||
|
|
e56467dd4d | ||
|
|
90c0d832d7 | ||
|
|
729bef38fb | ||
|
|
59aab0498e | ||
|
|
863170e013 | ||
|
|
e62b86bf7d | ||
|
|
0e018581a0 | ||
|
|
a19f1e2d6d | ||
|
|
987ef9ecf4 | ||
|
|
3de272ae5e | ||
|
|
3ca6b69984 | ||
|
|
084f352d71 | ||
|
|
f4a16b3edd | ||
|
|
e8d8ee8501 | ||
|
|
9a87701ad6 | ||
|
|
cdc8a7aea6 | ||
|
|
247bbec87d | ||
|
|
e839c1e9b5 | ||
|
|
d756b0e451 | ||
|
|
663cb2b5b6 | ||
|
|
3e16c02e50 | ||
|
|
80ca110702 | ||
|
|
5f6a589dd8 | ||
|
|
342028eef1 | ||
|
|
0e96ee7eeb | ||
|
|
3bd52e00d9 | ||
|
|
f612c912a7 | ||
|
|
5dee677ce3 | ||
|
|
19ab3adc9a | ||
|
|
90bfd445d1 | ||
|
|
7493bd57f4 | ||
|
|
629c2bb80d | ||
|
|
4d45d717e2 | ||
|
|
b8e80c6c8c | ||
|
|
efed7776d3 | ||
|
|
56cfc0669b | ||
|
|
6d9ed41382 | ||
|
|
505efbdef6 | ||
|
|
52ab8cebb0 | ||
|
|
e8251ee521 | ||
|
|
d4195c6e5b | ||
|
|
f50975d767 | ||
|
|
4d9452c791 | ||
|
|
474eea094d | ||
|
|
bbb6b634ff | ||
|
|
d5da97141f | ||
|
|
a12f9ba595 | ||
|
|
75944e5a8b | ||
|
|
1aa51a5934 | ||
|
|
092fd6779c | ||
|
|
618dc2b180 | ||
|
|
44a84f2bc2 | ||
|
|
5fb3b61669 | ||
|
|
57a9865d99 | ||
|
|
250e1256b9 | ||
|
|
015bcce8a3 | ||
|
|
b874a259fe | ||
|
|
c8ab84aa9e | ||
|
|
d6efe2c7ba | ||
|
|
46915fed3a | ||
|
|
5d1f599f48 | ||
|
|
9d5877e867 | ||
|
|
e998f80574 | ||
|
|
4faefb3f34 | ||
|
|
c48f282a2d | ||
|
|
d0ad3c158f | ||
|
|
c285562971 | ||
|
|
53ba692375 | ||
|
|
6879c5ea71 | ||
|
|
fa1348860b | ||
|
|
efe4955836 | ||
|
|
ad83f4d3ee | ||
|
|
be129a6147 | ||
|
|
89b224e397 | ||
|
|
97f82d4962 | ||
|
|
4453ddbf07 | ||
|
|
3b9d040881 | ||
|
|
b62b6c7b35 | ||
|
|
045218f8ca | ||
|
|
8b426c72d1 | ||
|
|
51eaa73b9c | ||
|
|
ad081d8192 | ||
|
|
19daaf7ee4 | ||
|
|
643412e11b | ||
|
|
389119c468 | ||
|
|
9b60cdc612 | ||
|
|
203d6134c2 | ||
|
|
87e714aff6 | ||
|
|
125fe0e691 | ||
|
|
0485d9690e | ||
|
|
d7b01d455b | ||
|
|
d7d0c4e250 | ||
|
|
231e463605 | ||
|
|
311185825e | ||
|
|
325cf311df | ||
|
|
cddb51b399 | ||
|
|
c2c98003f1 | ||
|
|
dd6f02395c | ||
|
|
f419264540 | ||
|
|
d7565ce0bb | ||
|
|
095ccf1b55 | ||
|
|
8abefdb6d4 | ||
|
|
0aad8ca1e8 | ||
|
|
0bc4569084 | ||
|
|
337c859040 | ||
|
|
e0cb0fca18 | ||
|
|
b8d5a7d80d | ||
|
|
2ddb234e72 | ||
|
|
19ebd4c28f | ||
|
|
e6367055fb | ||
|
|
ba72dbff7c | ||
|
|
df41c62269 | ||
|
|
a1cea27cdc | ||
|
|
173f01853b | ||
|
|
8568f1c7a0 | ||
|
|
400f92ebb5 | ||
|
|
dcac616391 | ||
|
|
10c814fc2b | ||
|
|
8a1c0c0766 | ||
|
|
5c179a4e5d | ||
|
|
e72dfae998 | ||
|
|
fd4a535701 | ||
|
|
d01370e480 | ||
|
|
e110647a17 | ||
|
|
4edc7f082b | ||
|
|
3a01dd6b5b | ||
|
|
6ef208db91 | ||
|
|
d25ea0957e | ||
|
|
c8030c6454 | ||
|
|
e608d8e142 | ||
|
|
df01343c97 | ||
|
|
2ee792c6a8 | ||
|
|
e601fc85d1 | ||
|
|
bbceb4e493 | ||
|
|
43df2a5887 | ||
|
|
be8e03e99d | ||
|
|
3cac88362c | ||
|
|
cf0659db85 | ||
|
|
72c1190aa9 | ||
|
|
6986a84cf6 | ||
|
|
9c11ffde3c | ||
|
|
492fcd56a0 | ||
|
|
481499c124 | ||
|
|
3f11ad9f53 | ||
|
|
e36c3fe796 | ||
|
|
7c235d2a33 | ||
|
|
727eb73721 | ||
|
|
42f5e6ae4e | ||
|
|
7515303e87 | ||
|
|
281af4140a | ||
|
|
4fa6a1f544 | ||
|
|
53f8cc4488 | ||
|
|
0f980a5cee | ||
|
|
6e06cca962 | ||
|
|
ba884f8c99 | ||
|
|
44c2d25218 | ||
|
|
cd33a557cd | ||
|
|
2c4daa447e | ||
|
|
6659fefc21 | ||
|
|
48face0e9e | ||
|
|
fe16ccd8b9 | ||
|
|
99fedf4e3c | ||
|
|
7924b53d00 | ||
|
|
ed15f403cc | ||
|
|
2c69b67731 | ||
|
|
ed8073eebf | ||
|
|
c03b33fe2f | ||
|
|
1fe7500251 | ||
|
|
8900b0fa4a | ||
|
|
7626c8e89e | ||
|
|
81428446d9 | ||
|
|
d6b6976277 | ||
|
|
b5f15cbbd2 | ||
|
|
075fe52b4e | ||
|
|
0d8054b59d | ||
|
|
5706771c88 | ||
|
|
6c08f068d0 | ||
|
|
9ad1c9b050 | ||
|
|
3ac64cd973 | ||
|
|
27660f448f | ||
|
|
c5c01b3a48 | ||
|
|
1166c0d547 | ||
|
|
9e2c5715ed | ||
|
|
a4f9580171 | ||
|
|
e84a060194 | ||
|
|
5d858501b0 | ||
|
|
cf24c86981 | ||
|
|
ed67831156 | ||
|
|
43d7e532db | ||
|
|
c8f38c0079 | ||
|
|
249960825a | ||
|
|
cdaf2b80b6 | ||
|
|
d345512caa | ||
|
|
ec2cc5b13a | ||
|
|
9a5f6ccb74 | ||
|
|
42c4c4cfda | ||
|
|
5325c0c4f7 | ||
|
|
ff8bf2be64 | ||
|
|
5b4ee608b8 | ||
|
|
2aadad487e | ||
|
|
e97c82dbd7 | ||
|
|
d56c429175 | ||
|
|
47e8f73296 | ||
|
|
2c50429ef9 | ||
|
|
933f51c96b | ||
|
|
59e704c992 | ||
|
|
fb4c79a722 | ||
|
|
644113ba56 | ||
|
|
2160deb34a | ||
|
|
d4a39990ed | ||
|
|
6e315ea94d | ||
|
|
25d75deb3c | ||
|
|
275a0766fa | ||
|
|
4b2801190c |
No files matched your search
@@ -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,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 目录下
|
||||
|
||||
@@ -72,3 +83,5 @@ Here is the libraries
|
||||
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.
|
||||
|
||||
ic_launcher 图标为 Hippo Seven 所有,所有权利保留
|
||||
+18
-13
@@ -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 49
|
||||
versionName "0.9.1"
|
||||
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,19 +74,19 @@ 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.0'
|
||||
compile 'com.android.support:customtabs:23.2.0'
|
||||
compile 'com.android.support:design:23.2.0'
|
||||
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.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.6'
|
||||
compile 'de.greenrobot:greendao:2.0.0'
|
||||
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'
|
||||
}
|
||||
Binary file not shown.
@@ -27,42 +27,133 @@
|
||||
|
||||
<application
|
||||
android:name="com.hippo.ehviewer.EhApplication"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme">
|
||||
android:theme="@style/AppTheme"
|
||||
android:allowBackup="true"
|
||||
android:fullBackupContent="@xml/backup_scheme"
|
||||
android:largeHeap="true">
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.MainActivity"
|
||||
android:configChanges="screenSize|uiMode"
|
||||
android:theme="@style/AppTheme.Main"
|
||||
android:launchMode="singleTask">
|
||||
android:launchMode="singleTask"
|
||||
android:windowSoftInputMode="stateHidden">
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
</intent-filter>
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
<data android:scheme="http"/>
|
||||
<data android:host="exhentai.org"/>
|
||||
<data android:host="g.e-hentai.org"/>
|
||||
<data android:host="lofi.e-hentai.org"/>
|
||||
</intent-filter>
|
||||
|
||||
<intent-filter android:label="@string/keyword_search">
|
||||
<action android:name="android.intent.action.SEND"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent-filter>
|
||||
|
||||
<intent-filter android:label="@string/image_search">
|
||||
<action android:name="android.intent.action.SEND"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<data android:mimeType="image/*"/>
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity"
|
||||
android:configChanges="screenSize|uiMode"
|
||||
android:theme="@style/AppTheme.NoActionBar">
|
||||
|
||||
<intent-filter android:priority="-10">
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
<data android:scheme="http"/>
|
||||
<data android:host="exhentai.org"/>
|
||||
<data android:host="g.e-hentai.org"/>
|
||||
<data android:host="lofi.e-hentai.org"/>
|
||||
<data android:pathPrefix="/g/"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity-alias
|
||||
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity2"
|
||||
android:targetActivity="com.hippo.ehviewer.ui.DumpBrowsableActivity"
|
||||
android:configChanges="screenSize|uiMode"
|
||||
android:theme="@style/AppTheme.NoActionBar">
|
||||
|
||||
<intent-filter android:priority="-10">
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
<data android:scheme="http"/>
|
||||
<data android:host="exhentai.org"/>
|
||||
<data android:host="g.e-hentai.org"/>
|
||||
<data android:host="lofi.e-hentai.org"/>
|
||||
<data android:pathPrefix="/s/"/>
|
||||
</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"
|
||||
@@ -87,10 +178,33 @@
|
||||
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"
|
||||
android:theme="@style/AppTheme.NoActionBar"
|
||||
android:label="@string/filter"/>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.SetSecurityActivity"
|
||||
android:configChanges="screenSize|uiMode"
|
||||
android:theme="@style/AppTheme.NoActionBar"
|
||||
android:label="@string/set_pattern_protection"/>
|
||||
|
||||
<service
|
||||
android:name="com.hippo.ehviewer.download.DownloadService"
|
||||
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>
|
||||
@@ -44,10 +44,15 @@ public class EditTextDialogBuilder extends AlertDialog.Builder implements EditTe
|
||||
mTextInputLayout = (TextInputLayout) view;
|
||||
mEditText = (EditText) view.findViewById(R.id.edit_text);
|
||||
mEditText.setText(text);
|
||||
mEditText.setSelection(mEditText.getText().length());
|
||||
mEditText.setOnEditorActionListener(this);
|
||||
mTextInputLayout.setHint(hint);
|
||||
}
|
||||
|
||||
public EditText getEditText() {
|
||||
return mEditText;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return mEditText.getText().toString();
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* 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.drawable;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.support.v7.graphics.drawable.DrawableWrapper;
|
||||
|
||||
import com.hippo.yorozuya.MathUtils;
|
||||
|
||||
public class PreciselyClipDrawable extends DrawableWrapper {
|
||||
|
||||
private final boolean mClip;
|
||||
private RectF mScale;
|
||||
private Rect mTemp;
|
||||
|
||||
public PreciselyClipDrawable(Drawable drawable, int offsetX, int offsetY, int width, int height) {
|
||||
super(drawable);
|
||||
float originWidth = drawable.getIntrinsicWidth();
|
||||
float originHeight = drawable.getIntrinsicHeight();
|
||||
|
||||
if (originWidth <= 0 || originHeight <= 0) {
|
||||
// Can not clip
|
||||
mClip = false;
|
||||
} else {
|
||||
mClip = true;
|
||||
mScale = new RectF();
|
||||
mScale.set(MathUtils.clamp(offsetX / originWidth, 0.0f, 1.0f),
|
||||
MathUtils.clamp(offsetY / originHeight, 0.0f, 1.0f),
|
||||
MathUtils.clamp((offsetX + width) / originWidth, 0.0f, 1.0f),
|
||||
MathUtils.clamp((offsetY + height) / originHeight, 0.0f, 1.0f));
|
||||
mTemp = new Rect();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
if (mClip) {
|
||||
if (!mScale.isEmpty()) {
|
||||
mTemp.left = (int) ((mScale.left * bounds.right - mScale.right * bounds.left) /
|
||||
(mScale.left * (1 - mScale.right) - mScale.right * (1 - mScale.left)));
|
||||
mTemp.right = (int) (((1 - mScale.right) * bounds.left - (1 - mScale.left) * bounds.right) /
|
||||
(mScale.left * (1 - mScale.right) - mScale.right * (1 - mScale.left)));
|
||||
mTemp.top = (int) ((mScale.top * bounds.bottom - mScale.bottom * bounds.top) /
|
||||
(mScale.top * (1 - mScale.bottom) - mScale.bottom * (1 - mScale.top)));
|
||||
mTemp.bottom = (int) (((1 - mScale.bottom) * bounds.top - (1 - mScale.top) * bounds.bottom) /
|
||||
(mScale.top * (1 - mScale.bottom) - mScale.bottom * (1 - mScale.top)));
|
||||
super.onBoundsChange(mTemp);
|
||||
}
|
||||
} else {
|
||||
super.onBoundsChange(bounds);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicWidth() {
|
||||
if (mClip) {
|
||||
return (int) (super.getIntrinsicWidth() * mScale.width());
|
||||
} else {
|
||||
return super.getIntrinsicWidth();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicHeight() {
|
||||
if (mClip) {
|
||||
return (int) (super.getIntrinsicHeight() * mScale.height());
|
||||
} else {
|
||||
return super.getIntrinsicHeight();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
if (mClip) {
|
||||
if (!mScale.isEmpty()) {
|
||||
int saveCount = canvas.save();
|
||||
canvas.clipRect(getBounds());
|
||||
super.draw(canvas);
|
||||
canvas.restoreToCount(saveCount);
|
||||
}
|
||||
} else {
|
||||
super.draw(canvas);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -34,6 +40,7 @@ public class AppConfig {
|
||||
private static final String CRASH = "crash";
|
||||
private static final String PARSE_ERROR = "parse_error";
|
||||
private static final String LOGCAT = "logcat";
|
||||
private static final String DATA = "data";
|
||||
|
||||
private static Context sContext;
|
||||
|
||||
@@ -103,8 +110,56 @@ public class AppConfig {
|
||||
return getDirInExternalAppDir(LOGCAT);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static File getExternalDataDir() {
|
||||
return getDirInExternalAppDir(DATA);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static File createExternalTempFile() {
|
||||
return FileUtils.createTempFile(getExternalTempDir(), null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static File getTempDir() {
|
||||
File dir = sContext.getCacheDir();
|
||||
File file;
|
||||
if (null != dir && FileUtils.ensureDirectory(file = new File(dir, TEMP))) {
|
||||
return file;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,14 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.hippo.scene.StageActivity;
|
||||
import com.hippo.util.PackageUtils;
|
||||
import com.hippo.util.ReadableTime;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
@@ -34,6 +37,12 @@ import java.io.PrintWriter;
|
||||
|
||||
public class Crash {
|
||||
|
||||
@NonNull
|
||||
private static String avoidNull(String str) {
|
||||
return null != str ? str : "null";
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private static void collectInfo(Context context, FileWriter fw) throws IOException {
|
||||
try {
|
||||
PackageManager pm = context.getPackageManager();
|
||||
@@ -55,6 +64,25 @@ public class Crash {
|
||||
fw.write("\r\n");
|
||||
}
|
||||
|
||||
// Runtime
|
||||
String topActivityClazzName = null;
|
||||
String topSceneClazzName = null;
|
||||
try {
|
||||
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
|
||||
if (null != topActivity) {
|
||||
topActivityClazzName = topActivity.getClass().getName();
|
||||
if (topActivity instanceof StageActivity) {
|
||||
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
// Ignore
|
||||
}
|
||||
fw.write("======== Runtime ========\r\n");
|
||||
fw.write("TopActivity=");fw.write(avoidNull(topActivityClazzName));fw.write("\r\n");
|
||||
fw.write("TopScene=");fw.write(avoidNull(topSceneClazzName));fw.write("\r\n");
|
||||
fw.write("\r\n");
|
||||
|
||||
// Device info
|
||||
fw.write("======== DeviceInfo ========\r\n");
|
||||
fw.write("BOARD=");fw.write(Build.BOARD);fw.write("\r\n");
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.ActivityManager;
|
||||
import android.content.ComponentCallbacks2;
|
||||
import android.content.Context;
|
||||
@@ -24,62 +25,83 @@ import android.content.pm.PackageManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Debug;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.util.LruCache;
|
||||
import android.util.Log;
|
||||
import android.util.SparseArray;
|
||||
|
||||
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.client.data.LargePreviewSet;
|
||||
import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.ehviewer.spider.SpiderDen;
|
||||
import com.hippo.ehviewer.ui.CommonOperations;
|
||||
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;
|
||||
import com.hippo.yorozuya.IntIdGenerator;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import okhttp3.Cookie;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
public class EhApplication extends SceneApplication implements Thread.UncaughtExceptionHandler {
|
||||
|
||||
private static final String TAG = EhApplication.class.getSimpleName();
|
||||
|
||||
public static final boolean BETA = true;
|
||||
public static final boolean BETA = false;
|
||||
|
||||
private static final boolean DEBUG_CONACO = false;
|
||||
private static final boolean DEBUG_NATIVE_MEMORY = false;
|
||||
|
||||
private Thread.UncaughtExceptionHandler mDefaultHandler;
|
||||
|
||||
private final AtomicInteger mIdGenerator = new AtomicInteger();
|
||||
private final SparseArray<Object> mGlobalStuffMap = new SparseArray<>();
|
||||
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
|
||||
private final WeakHashMap<Integer, Object> mGlobalStuffMap = new WeakHashMap<>();
|
||||
private EhCookieStore mEhCookieStore;
|
||||
private EhClient mEhClient;
|
||||
private OkHttpClient mOkHttpClient;
|
||||
private BitmapHelper mBitmapHelper;
|
||||
private Conaco<Bitmap> mConaco;
|
||||
private LruCache<Long, GalleryDetail> mGalleryDetailCache;
|
||||
private LruCache<String, LargePreviewSet> mLargePreviewSetCache;
|
||||
private LruCache<Long, Integer> mPreviewPagesCache;
|
||||
private SimpleDiskCache mSpiderInfoCache;
|
||||
private DownloadManager mDownloadManager;
|
||||
|
||||
private final List<Activity> mActivityList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
// Prepare to catch crash
|
||||
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);
|
||||
@@ -91,6 +113,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
AppConfig.initialize(this);
|
||||
SpiderDen.initialize(this);
|
||||
EhDB.initialize(this);
|
||||
EhEngine.initialize();
|
||||
BitmapUtils.initialize(this);
|
||||
|
||||
if (EhDB.needMerge()) {
|
||||
EhDB.mergeOldDB(this);
|
||||
@@ -100,6 +124,20 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
Analytics.start(this);
|
||||
}
|
||||
|
||||
// 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
|
||||
try {
|
||||
PackageInfo pi= getPackageManager().getPackageInfo(getPackageName(), 0);
|
||||
@@ -113,23 +151,62 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
}
|
||||
}
|
||||
|
||||
private void clearTempDir() {
|
||||
File dir = AppConfig.getTempDir();
|
||||
if (null != dir) {
|
||||
FileUtils.deleteContent(dir);
|
||||
}
|
||||
dir = AppConfig.getExternalTempDir();
|
||||
if (null != dir) {
|
||||
FileUtils.deleteContent(dir);
|
||||
}
|
||||
}
|
||||
|
||||
private void update() {
|
||||
int version = Settings.getVersionCode();
|
||||
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() {
|
||||
if (null != mConaco) {
|
||||
mConaco.clearMemoryCache();
|
||||
}
|
||||
if (null != mGalleryDetailCache) {
|
||||
mGalleryDetailCache.evictAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTrimMemory(int level) {
|
||||
super.onTrimMemory(level);
|
||||
|
||||
if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) {
|
||||
if (null != mConaco) {
|
||||
mConaco.clearMemoryCache();
|
||||
}
|
||||
if (null != mGalleryDetailCache) {
|
||||
mGalleryDetailCache.evictAll();
|
||||
}
|
||||
if (null != mLargePreviewSetCache) {
|
||||
mLargePreviewSetCache.evictAll();
|
||||
}
|
||||
if (null != mPreviewPagesCache) {
|
||||
mPreviewPagesCache.evictAll();
|
||||
}
|
||||
clearMemoryCache();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,13 +222,13 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
}
|
||||
|
||||
public int putGlobalStuff(@NonNull Object o) {
|
||||
int id = mIdGenerator.getAndDecrement();
|
||||
int id = mIdGenerator.nextId();
|
||||
mGlobalStuffMap.put(id, o);
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean containGlobalStuff(int id) {
|
||||
return mGlobalStuffMap.indexOfKey(id) >= 0;
|
||||
return mGlobalStuffMap.containsKey(id);
|
||||
}
|
||||
|
||||
public Object getGlobalStuff(int id) {
|
||||
@@ -159,24 +236,11 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
}
|
||||
|
||||
public Object removeGlobalStuff(int id) {
|
||||
int index = mGlobalStuffMap.indexOfKey(id);
|
||||
if (index >= 0) {
|
||||
Object o = mGlobalStuffMap.valueAt(index);
|
||||
mGlobalStuffMap.removeAt(index);
|
||||
return o;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return mGlobalStuffMap.remove(id);
|
||||
}
|
||||
|
||||
public boolean removeGlobalStuff(Object o) {
|
||||
int index = mGlobalStuffMap.indexOfValue(o);
|
||||
if (index >= 0) {
|
||||
mGlobalStuffMap.removeAt(index);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return mGlobalStuffMap.values().removeAll(Collections.singleton(o));
|
||||
}
|
||||
|
||||
public static EhCookieStore getEhCookieStore(@NonNull Context context) {
|
||||
@@ -254,26 +318,6 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
return application.mGalleryDetailCache;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static LruCache<String, LargePreviewSet> getLargePreviewSetCache(@NonNull Context context) {
|
||||
EhApplication application = ((EhApplication) context.getApplicationContext());
|
||||
if (application.mLargePreviewSetCache == null) {
|
||||
// Max size 50, 3 min timeout
|
||||
application.mLargePreviewSetCache = new LruCache<>(50);
|
||||
}
|
||||
return application.mLargePreviewSetCache;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static LruCache<Long, Integer> getPreviewPagesCache(@NonNull Context context) {
|
||||
EhApplication application = ((EhApplication) context.getApplicationContext());
|
||||
if (application.mPreviewPagesCache == null) {
|
||||
// Max size 50, 3 min timeout
|
||||
application.mPreviewPagesCache = new LruCache<>(50);
|
||||
}
|
||||
return application.mPreviewPagesCache;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static SimpleDiskCache getSpiderInfoCache(@NonNull Context context) {
|
||||
EhApplication application = ((EhApplication) context.getApplicationContext());
|
||||
@@ -311,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);
|
||||
}
|
||||
@@ -319,4 +369,21 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
|
||||
public static String getDeveloperEmail() {
|
||||
return "ehviewersu$gmail.com".replace('$', '@');
|
||||
}
|
||||
|
||||
public void registerActivity(Activity activity) {
|
||||
mActivityList.add(activity);
|
||||
}
|
||||
|
||||
public void unregisterActivity(Activity activity) {
|
||||
mActivityList.remove(activity);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Activity getTopActivity() {
|
||||
if (!mActivityList.isEmpty()) {
|
||||
return mActivityList.get(mActivityList.size() - 1);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,14 +34,27 @@ import com.hippo.ehviewer.dao.DownloadInfo;
|
||||
import com.hippo.ehviewer.dao.DownloadLabel;
|
||||
import com.hippo.ehviewer.dao.DownloadLabelDao;
|
||||
import com.hippo.ehviewer.dao.DownloadsDao;
|
||||
import com.hippo.ehviewer.dao.Filter;
|
||||
import com.hippo.ehviewer.dao.FilterDao;
|
||||
import com.hippo.ehviewer.dao.HistoryDao;
|
||||
import com.hippo.ehviewer.dao.HistoryInfo;
|
||||
import com.hippo.ehviewer.dao.LocalFavoriteInfo;
|
||||
import com.hippo.ehviewer.dao.LocalFavoritesDao;
|
||||
import com.hippo.ehviewer.dao.QuickSearch;
|
||||
import com.hippo.ehviewer.dao.QuickSearchDao;
|
||||
import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.util.SqlUtils;
|
||||
import com.hippo.yorozuya.FileUtils;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
import com.hippo.yorozuya.ObjectUtils;
|
||||
import com.hippo.yorozuya.sparse.SparseJLArray;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -72,6 +85,14 @@ public class EhDB {
|
||||
|
||||
@Override
|
||||
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
||||
upgradeDB(db, oldVersion);
|
||||
}
|
||||
}
|
||||
|
||||
private static void upgradeDB(SQLiteDatabase db, int oldVersion) {
|
||||
switch (oldVersion) {
|
||||
case 1: // 1 to 2
|
||||
FilterDao.createTable(db, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +162,12 @@ public class EhDB {
|
||||
gi.category = cursor.getInt(4);
|
||||
gi.thumb = cursor.getString(5);
|
||||
gi.uploader = cursor.getString(6);
|
||||
gi.rating = cursor.getFloat(7);
|
||||
try {
|
||||
// In 0.6.x version, NaN is stored
|
||||
gi.rating = cursor.getFloat(7);
|
||||
} catch (Exception e) {
|
||||
gi.rating = -1.0f;
|
||||
}
|
||||
|
||||
map.put(gi.gid, gi);
|
||||
|
||||
@@ -277,7 +303,7 @@ public class EhDB {
|
||||
continue;
|
||||
}
|
||||
|
||||
HistoryInfo info = new HistoryInfo();
|
||||
HistoryInfo info = new HistoryInfo(gi);
|
||||
info.setMode(cursor.getInt(1));
|
||||
info.setTime(cursor.getLong(2));
|
||||
dao.insert(info);
|
||||
@@ -358,6 +384,11 @@ public class EhDB {
|
||||
dao.deleteByKey(gid);
|
||||
}
|
||||
|
||||
public static synchronized void clearDownloadDirname() {
|
||||
DownloadDirnameDao dao = sDaoSession.getDownloadDirnameDao();
|
||||
dao.deleteAll();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static synchronized List<DownloadLabel> getAllDownloadLabelList() {
|
||||
DownloadLabelDao dao = sDaoSession.getDownloadLabelDao();
|
||||
@@ -373,6 +404,14 @@ public class EhDB {
|
||||
return raw;
|
||||
}
|
||||
|
||||
public static synchronized DownloadLabel addDownloadLabel(DownloadLabel raw) {
|
||||
// Reset id
|
||||
raw.setId(null);
|
||||
DownloadLabelDao dao = sDaoSession.getDownloadLabelDao();
|
||||
raw.setId(dao.insert(raw));
|
||||
return raw;
|
||||
}
|
||||
|
||||
public static synchronized void updateDownloadLabel(DownloadLabel raw) {
|
||||
DownloadLabelDao dao = sDaoSession.getDownloadLabelDao();
|
||||
dao.update(raw);
|
||||
@@ -417,9 +456,10 @@ public class EhDB {
|
||||
}
|
||||
|
||||
public static synchronized List<GalleryInfo> searchLocalFavorites(String query) {
|
||||
query = SqlUtils.sqlEscapeString("%" + query+ "%");
|
||||
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
|
||||
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time)
|
||||
.where(LocalFavoritesDao.Properties.Title.like("%" + query+ "%")).list();
|
||||
.where(LocalFavoritesDao.Properties.Title.like(query)).list();
|
||||
List<GalleryInfo> result = new ArrayList<>();
|
||||
result.addAll(list);
|
||||
return result;
|
||||
@@ -468,6 +508,7 @@ public class EhDB {
|
||||
|
||||
public static synchronized void insertQuickSearch(QuickSearch quickSearch) {
|
||||
QuickSearchDao dao = sDaoSession.getQuickSearchDao();
|
||||
quickSearch.id = null;
|
||||
quickSearch.time = System.currentTimeMillis();
|
||||
quickSearch.id = dao.insert(quickSearch);
|
||||
}
|
||||
@@ -528,4 +569,148 @@ public class EhDB {
|
||||
dao.deleteInTx(list);
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void putHistoryInfo(List<HistoryInfo> historyInfoList) {
|
||||
HistoryDao dao = sDaoSession.getHistoryDao();
|
||||
for (HistoryInfo info: historyInfoList) {
|
||||
if (null == dao.load(info.gid)) {
|
||||
dao.insert(info);
|
||||
}
|
||||
}
|
||||
|
||||
List<HistoryInfo> list = dao.queryBuilder().orderDesc(HistoryDao.Properties.Time)
|
||||
.limit(-1).offset(MAX_HISTORY_COUNT).list();
|
||||
dao.deleteInTx(list);
|
||||
}
|
||||
|
||||
public static synchronized void deleteHistoryInfo(HistoryInfo info) {
|
||||
HistoryDao dao = sDaoSession.getHistoryDao();
|
||||
dao.delete(info);
|
||||
}
|
||||
|
||||
public static synchronized void clearHistoryInfo() {
|
||||
HistoryDao dao = sDaoSession.getHistoryDao();
|
||||
dao.deleteAll();
|
||||
}
|
||||
|
||||
public static synchronized List<Filter> getAllFilter() {
|
||||
return sDaoSession.getFilterDao().queryBuilder().list();
|
||||
}
|
||||
|
||||
public static synchronized void addFilter(Filter filter) {
|
||||
filter.setId(null);
|
||||
filter.setId(sDaoSession.getFilterDao().insert(filter));
|
||||
}
|
||||
|
||||
public static synchronized void deleteFilter(Filter filter) {
|
||||
sDaoSession.getFilterDao().delete(filter);
|
||||
}
|
||||
|
||||
public static synchronized boolean exportDB(Context context, File file) {
|
||||
File dbFile = context.getDatabasePath("eh.db");
|
||||
if (null == dbFile || !dbFile.isFile()) {
|
||||
return false;
|
||||
}
|
||||
if (null == file || !FileUtils.ensureFile(file)) {
|
||||
return false;
|
||||
}
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
try {
|
||||
is = new FileInputStream(dbFile);
|
||||
os = new FileOutputStream(file);
|
||||
IOUtils.copy(is, os);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
IOUtils.closeQuietly(is);
|
||||
IOUtils.closeQuietly(os);
|
||||
}
|
||||
// Delete failed file
|
||||
file.delete();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param file The db file
|
||||
* @return error string, null for no error
|
||||
*/
|
||||
public static synchronized String importDB(Context context, File file) {
|
||||
try {
|
||||
SQLiteDatabase db = SQLiteDatabase.openDatabase(
|
||||
file.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
|
||||
int newVersion = DaoMaster.SCHEMA_VERSION;
|
||||
int oldVersion = db.getVersion();
|
||||
if (oldVersion < newVersion) {
|
||||
upgradeDB(db, oldVersion);
|
||||
db.setVersion(newVersion);
|
||||
} else if (oldVersion > newVersion) {
|
||||
return context.getString(R.string.cant_read_the_file);
|
||||
}
|
||||
|
||||
DaoMaster daoMaster = new DaoMaster(db);
|
||||
DaoSession session = daoMaster.newSession();
|
||||
|
||||
// Downloads
|
||||
DownloadManager manager = EhApplication.getDownloadManager(context);
|
||||
List<DownloadInfo> downloadInfoList = session.getDownloadsDao().queryBuilder().list();
|
||||
manager.addDownload(downloadInfoList);
|
||||
|
||||
// Download label
|
||||
List<DownloadLabel> downloadLabelList = session.getDownloadLabelDao().queryBuilder().list();
|
||||
manager.addDownloadLabel(downloadLabelList);
|
||||
|
||||
// Download dirname
|
||||
List<DownloadDirname> downloadDirnameList = session.getDownloadDirnameDao().queryBuilder().list();
|
||||
for (DownloadDirname dirname: downloadDirnameList) {
|
||||
putDownloadDirname(dirname.getGid(), dirname.getDirname());
|
||||
}
|
||||
|
||||
// History
|
||||
List<HistoryInfo> historyInfoList = session.getHistoryDao().queryBuilder().list();
|
||||
putHistoryInfo(historyInfoList);
|
||||
|
||||
// QuickSearch
|
||||
List<QuickSearch> quickSearchList = session.getQuickSearchDao().queryBuilder().list();
|
||||
List<QuickSearch> currentQuickSearchList = sDaoSession.getQuickSearchDao().queryBuilder().list();
|
||||
for (QuickSearch quickSearch: quickSearchList) {
|
||||
String name = quickSearch.name;
|
||||
for (QuickSearch q: currentQuickSearchList) {
|
||||
if (ObjectUtils.equal(q.name, name)) {
|
||||
// The same name
|
||||
name = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (null == name) {
|
||||
continue;
|
||||
}
|
||||
insertQuickSearch(quickSearch);
|
||||
}
|
||||
|
||||
// LocalFavorites
|
||||
List<LocalFavoriteInfo> localFavoriteInfoList = session.getLocalFavoritesDao().queryBuilder().list();
|
||||
for (LocalFavoriteInfo info: localFavoriteInfoList) {
|
||||
putLocalFavorites(info);
|
||||
}
|
||||
|
||||
// Bookmarks
|
||||
// TODO
|
||||
|
||||
// Filter
|
||||
List<Filter> filterList = session.getFilterDao().queryBuilder().list();
|
||||
List<Filter> currentFilterList = sDaoSession.getFilterDao().queryBuilder().list();
|
||||
for (Filter filter: filterList) {
|
||||
if (!currentFilterList.contains(filter)) {
|
||||
addFilter(filter);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
// Ignore
|
||||
return context.getString(R.string.cant_read_the_file);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,15 +21,17 @@ 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;
|
||||
|
||||
import com.hippo.ehviewer.client.EhConfig;
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
|
||||
import com.hippo.ehviewer.client.data.ListUrlBuilder;
|
||||
import com.hippo.ehviewer.gallery.gl.GalleryView;
|
||||
import com.hippo.ehviewer.gallery.gl.ImageView;
|
||||
import com.hippo.ehviewer.ui.CommonOperations;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.FileUtils;
|
||||
@@ -54,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();
|
||||
@@ -198,9 +201,53 @@ public class Settings {
|
||||
return sEhConfig;
|
||||
}
|
||||
|
||||
private static final String KEY_NEED_SIGN_IN = "need_sign_in";
|
||||
private static final boolean DEFAULT_NEED_SIGN_IN = true;
|
||||
|
||||
public static boolean getNeedSignIn() {
|
||||
return getBoolean(KEY_NEED_SIGN_IN, DEFAULT_NEED_SIGN_IN);
|
||||
}
|
||||
|
||||
public static void putNeedSignIn(boolean value) {
|
||||
putBoolean(KEY_NEED_SIGN_IN, value);
|
||||
}
|
||||
|
||||
private static final String KEY_SELECT_SITE = "select_site";
|
||||
private static final boolean DEFAULT_SELECT_SITE = true;
|
||||
|
||||
public static boolean getSelectSite() {
|
||||
return getBoolean(KEY_SELECT_SITE, DEFAULT_SELECT_SITE);
|
||||
}
|
||||
|
||||
public static void putSelectSite(boolean value) {
|
||||
putBoolean(KEY_SELECT_SITE, value);
|
||||
}
|
||||
|
||||
private static final String KEY_QUICK_SEARCH_TIP = "quick_search_tip";
|
||||
private static final boolean DEFAULT_QUICK_SEARCH_TIP = true;
|
||||
|
||||
public static boolean getQuickSearchTip() {
|
||||
return getBoolean(KEY_QUICK_SEARCH_TIP, DEFAULT_QUICK_SEARCH_TIP);
|
||||
}
|
||||
|
||||
public static void putQuickSearchTip(boolean value) {
|
||||
putBoolean(KEY_QUICK_SEARCH_TIP, value);
|
||||
}
|
||||
|
||||
/********************
|
||||
****** Eh
|
||||
********************/
|
||||
public static final String KEY_GALLERY_SITE = "gallery_site";
|
||||
private static final int DEFAULT_GALLERY_SITE = 1;
|
||||
|
||||
public static int getGallerySite() {
|
||||
return getIntFromStr(KEY_GALLERY_SITE, DEFAULT_GALLERY_SITE);
|
||||
}
|
||||
|
||||
public static void putGallerySite(int value) {
|
||||
putIntToStr(KEY_GALLERY_SITE, value);
|
||||
}
|
||||
|
||||
public static final String KEY_LIST_MODE = "list_mode";
|
||||
private static final int DEFAULT_LIST_MODE = 0;
|
||||
|
||||
@@ -208,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;
|
||||
|
||||
@@ -216,7 +290,7 @@ public class Settings {
|
||||
}
|
||||
|
||||
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
|
||||
public static final int DEFAULT_DEFAULT_CATEGORIES = ListUrlBuilder.ALL_CATEGORT;
|
||||
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
|
||||
|
||||
public static int getDefaultCategories() {
|
||||
return getInt(KEY_DEFAULT_CATEGORIES, DEFAULT_DEFAULT_CATEGORIES);
|
||||
@@ -254,9 +328,86 @@ public class Settings {
|
||||
putString(KEY_EXCLUDED_LANGUAGES, value);
|
||||
}
|
||||
|
||||
private static final String KEY_HATH_PROXY = "hath_proxy";
|
||||
private static final boolean DEFAULT_HATH_PROXY = false;
|
||||
|
||||
public static boolean getHathProxy() {
|
||||
return getBoolean(KEY_HATH_PROXY, DEFAULT_HATH_PROXY);
|
||||
}
|
||||
|
||||
public static void putHathProxy(boolean value) {
|
||||
if (value) {
|
||||
sEhConfig.hahClientIp = Settings.getHathIp();
|
||||
sEhConfig.hahClientPort = Settings.getHathPort();
|
||||
sEhConfig.hahClientPasskey = Settings.getHathPasskey();
|
||||
} else {
|
||||
sEhConfig.hahClientIp = DEFAULT_HATH_IP;
|
||||
sEhConfig.hahClientPort = DEFAULT_HATH_PORT;
|
||||
sEhConfig.hahClientPasskey = DEFAULT_HATH_PASSKEY;
|
||||
}
|
||||
sEhConfig.setDirty();
|
||||
putBoolean(KEY_HATH_PROXY, value);
|
||||
}
|
||||
|
||||
private static final String KEY_HATH_IP = "hath_ip";
|
||||
private static final String DEFAULT_HATH_IP = null;
|
||||
|
||||
public static String getHathIp() {
|
||||
return getString(KEY_HATH_IP, DEFAULT_HATH_IP);
|
||||
}
|
||||
|
||||
public static void putHathIp(String value) {
|
||||
if (Settings.getHathProxy()) {
|
||||
sEhConfig.hahClientIp = value;
|
||||
sEhConfig.setDirty();
|
||||
}
|
||||
putString(KEY_HATH_IP, value);
|
||||
}
|
||||
|
||||
private static final String KEY_HATH_PORT = "hath_port";
|
||||
private static final int DEFAULT_HATH_PORT = -1;
|
||||
|
||||
public static int getHathPort() {
|
||||
return getInt(KEY_HATH_PORT, DEFAULT_HATH_PORT);
|
||||
}
|
||||
|
||||
public static void putHathPort(int value) {
|
||||
if (Settings.getHathProxy()) {
|
||||
sEhConfig.hahClientPort = value;
|
||||
sEhConfig.setDirty();
|
||||
}
|
||||
putInt(KEY_HATH_PORT, value);
|
||||
}
|
||||
|
||||
private static final String KEY_HATH_PASSKEY = "hath_passkey";
|
||||
private static final String DEFAULT_HATH_PASSKEY = null;
|
||||
|
||||
public static String getHathPasskey() {
|
||||
return getString(KEY_HATH_PASSKEY, DEFAULT_HATH_PASSKEY);
|
||||
}
|
||||
|
||||
public static void putHathPasskey(String value) {
|
||||
if (Settings.getHathProxy()) {
|
||||
sEhConfig.hahClientPasskey = value;
|
||||
sEhConfig.setDirty();
|
||||
}
|
||||
putString(KEY_HATH_PASSKEY, value);
|
||||
}
|
||||
|
||||
/********************
|
||||
****** Read
|
||||
********************/
|
||||
private static final String KEY_SCREEN_ROTATION = "screen_rotation";
|
||||
private static final int DEFAULT_SCREEN_ROTATION = 0;
|
||||
|
||||
public static int getScreenRotation() {
|
||||
return getIntFromStr(KEY_SCREEN_ROTATION, DEFAULT_SCREEN_ROTATION);
|
||||
}
|
||||
|
||||
public static void putScreenRotation(int value) {
|
||||
putIntToStr(KEY_SCREEN_ROTATION, value);
|
||||
}
|
||||
|
||||
private static final String KEY_READING_DIRECTION = "reading_direction";
|
||||
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
|
||||
|
||||
@@ -315,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;
|
||||
|
||||
@@ -337,6 +499,39 @@ 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;
|
||||
|
||||
public static boolean getCustomScreenLightness() {
|
||||
return getBoolean(KEY_CUSTOM_SCREEN_LIGHTNESS, DEFAULT_CUSTOM_SCREEN_LIGHTNESS);
|
||||
}
|
||||
|
||||
public static void putCustomScreenLightness(boolean value) {
|
||||
putBoolean(KEY_CUSTOM_SCREEN_LIGHTNESS, value);
|
||||
}
|
||||
|
||||
private static final String KEY_SCREEN_LIGHTNESS = "screen_lightness";
|
||||
private static final int DEFAULT_SCREEN_LIGHTNESS = 50;
|
||||
|
||||
public static int getScreenLightness() {
|
||||
return getInt(KEY_SCREEN_LIGHTNESS, DEFAULT_SCREEN_LIGHTNESS);
|
||||
}
|
||||
|
||||
public static void putScreenLightness(int value) {
|
||||
putInt(KEY_SCREEN_LIGHTNESS, value);
|
||||
}
|
||||
|
||||
/********************
|
||||
****** Download
|
||||
********************/
|
||||
@@ -370,6 +565,19 @@ public class Settings {
|
||||
putString(KEY_DOWNLOAD_SAVE_PATH, uri.getEncodedPath());
|
||||
putString(KEY_DOWNLOAD_SAVE_QUERY, uri.getEncodedQuery());
|
||||
putString(KEY_DOWNLOAD_SAVE_FRAGMENT, uri.getEncodedFragment());
|
||||
|
||||
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";
|
||||
@@ -427,6 +635,30 @@ 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;
|
||||
|
||||
public static boolean getDownloadOriginImage() {
|
||||
return getBoolean(KEY_DOWNLOAD_ORIGIN_IMAGE, DEFAULT_DOWNLOAD_ORIGIN_IMAGE);
|
||||
}
|
||||
|
||||
public static void putDownloadOriginImage(boolean value) {
|
||||
putBoolean(KEY_DOWNLOAD_ORIGIN_IMAGE, value);
|
||||
}
|
||||
|
||||
/********************
|
||||
****** Favorites
|
||||
********************/
|
||||
@@ -636,6 +868,24 @@ public class Settings {
|
||||
putBoolean(KEY_SAVE_PARSE_ERROR_BODY, value);
|
||||
}
|
||||
|
||||
public static final String KEY_SECURITY = "security";
|
||||
public static final String DEFAULT_SECURITY = "";
|
||||
|
||||
public static String getSecurity() {
|
||||
return getString(KEY_SECURITY, DEFAULT_SECURITY);
|
||||
}
|
||||
|
||||
public static void putSecurity(String value) {
|
||||
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
|
||||
********************/
|
||||
@@ -682,4 +932,15 @@ public class Settings {
|
||||
public static void puttGuideDownloadLabels(boolean value) {
|
||||
putBoolean(KEY_GUIDE_DOWNLOAD_LABELS, value);
|
||||
}
|
||||
|
||||
private static final String KEY_GUIDE_GALLERY = "guide_gallery";
|
||||
private static final boolean DEFAULT_GUIDE_GALLERY = true;
|
||||
|
||||
public static boolean getGuideGallery() {
|
||||
return getBoolean(KEY_GUIDE_GALLERY, DEFAULT_GUIDE_GALLERY);
|
||||
}
|
||||
|
||||
public static void putGuideGallery(boolean value) {
|
||||
putBoolean(KEY_GUIDE_GALLERY, value);
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,12 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.net.Uri;
|
||||
import android.support.customtabs.CustomTabsIntent;
|
||||
import android.provider.Browser;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.text.TextUtils;
|
||||
import android.widget.Toast;
|
||||
|
||||
@@ -29,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(Activity activity, String url, boolean ehUrl, boolean customTabs) {
|
||||
public static void openUrl(@NonNull Context context, String url, boolean ehUrl) {
|
||||
if (TextUtils.isEmpty(url)) {
|
||||
return;
|
||||
}
|
||||
@@ -47,38 +46,23 @@ public final class UrlOpener {
|
||||
if (ehUrl) {
|
||||
Announcer announcer = EhUrlOpener.parseUrl(url);
|
||||
if (null != announcer) {
|
||||
intent = new Intent(activity, MainActivity.class);
|
||||
intent = new Intent(context, MainActivity.class);
|
||||
intent.setAction(StageActivity.ACTION_START_SCENE);
|
||||
intent.putExtra(StageActivity.KEY_SCENE_NAME, announcer.getClazz().getName());
|
||||
intent.putExtra(StageActivity.KEY_SCENE_ARGS, announcer.getArgs());
|
||||
activity.startActivity(intent);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// CustomTabs
|
||||
if (customTabs) {
|
||||
String packageName = CustomTabsHelper.getPackageNameToUseFixed(activity);
|
||||
if (packageName != null) {
|
||||
new CustomTabsIntent.Builder()
|
||||
.setToolbarColor(activity.getResources().getColor(R.color.colorPrimary))
|
||||
.setShowTitle(true)
|
||||
.build()
|
||||
.launchUrl(activity, uri);
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
context.startActivity(intent);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Intent.ACTION_VIEW
|
||||
intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(uri);
|
||||
PackageManager pm = activity.getPackageManager();
|
||||
ResolveInfo ri = pm.resolveActivity(intent, 0);
|
||||
if (ri != null) {
|
||||
activity.startActivity(intent);
|
||||
return;
|
||||
intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
|
||||
try {
|
||||
context.startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Toast.makeText(context, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
Toast.makeText(activity, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import com.hippo.ehviewer.client.exception.CancelledException;
|
||||
import com.hippo.yorozuya.PriorityThreadFactory;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
@@ -45,7 +46,7 @@ public class EhClient {
|
||||
public static final int METHOD_GET_GALLERY_LIST = 1;
|
||||
public static final int METHOD_FILL_GALLERY_LIST_BY_API = 2;
|
||||
public static final int METHOD_GET_GALLERY_DETAIL = 3;
|
||||
public static final int METHOD_GET_LARGE_PREVIEW_SET = 4;
|
||||
public static final int METHOD_GET_PREVIEW_SET = 4;
|
||||
public static final int METHOD_GET_RATE_GALLERY = 5;
|
||||
public static final int METHOD_GET_COMMENT_GALLERY = 6;
|
||||
public static final int METHOD_GET_GALLERY_TOKEN = 7;
|
||||
@@ -56,6 +57,8 @@ public class EhClient {
|
||||
public static final int METHOD_GET_TORRENT_LIST = 12;
|
||||
public static final int METHOD_GET_WHATS_HOT = 13;
|
||||
public static final int METHOD_GET_PROFILE = 14;
|
||||
public static final int METHOD_VOTE_COMMENT = 15;
|
||||
public static final int METHOD_IMAGE_SEARCH = 16;
|
||||
|
||||
private final ThreadPoolExecutor mRequestThreadPool;
|
||||
private final OkHttpClient mOkHttpClient;
|
||||
@@ -150,15 +153,15 @@ public class EhClient {
|
||||
case METHOD_SIGN_IN:
|
||||
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1]);
|
||||
case METHOD_GET_GALLERY_LIST:
|
||||
return EhEngine.getGalleryList(this, mOkHttpClient, (String) params[0], (Boolean) params[1]);
|
||||
return EhEngine.getGalleryList(this, mOkHttpClient, (String) params[0]);
|
||||
case METHOD_FILL_GALLERY_LIST_BY_API:
|
||||
return EhEngine.fillGalleryListByApi(this, mOkHttpClient, (List<GalleryInfo>) params[0]);
|
||||
case METHOD_GET_GALLERY_DETAIL:
|
||||
return EhEngine.getGalleryDetail(this, mOkHttpClient, (String) params[0]);
|
||||
case METHOD_GET_LARGE_PREVIEW_SET:
|
||||
return EhEngine.getLargePreviewSet(this, mOkHttpClient, (String) params[0]);
|
||||
case METHOD_GET_PREVIEW_SET:
|
||||
return EhEngine.getPreviewSet(this, mOkHttpClient, (String) params[0]);
|
||||
case METHOD_GET_RATE_GALLERY:
|
||||
return EhEngine.rateGallery(this, mOkHttpClient, (Long) params[0], (String) params[1], (Float) params[2]);
|
||||
return EhEngine.rateGallery(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Float) params[4]);
|
||||
case METHOD_GET_COMMENT_GALLERY:
|
||||
return EhEngine.commentGallery(this, mOkHttpClient, (String) params[0], (String) params[1]);
|
||||
case METHOD_GET_GALLERY_TOKEN:
|
||||
@@ -177,6 +180,10 @@ public class EhClient {
|
||||
return EhEngine.getWhatsHot(this, mOkHttpClient);
|
||||
case METHOD_GET_PROFILE:
|
||||
return EhEngine.getProfile(this, mOkHttpClient);
|
||||
case METHOD_VOTE_COMMENT:
|
||||
return EhEngine.voteComment(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Long) params[4], (Integer) params[5]);
|
||||
case METHOD_IMAGE_SEARCH:
|
||||
return EhEngine.imageSearch(this, mOkHttpClient, (File) params[0], (Boolean) params[1], (Boolean) params[2], (Boolean) params[3]);
|
||||
default:
|
||||
return new IllegalStateException("Can't detect method " + mMethod);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.client;
|
||||
|
||||
import android.text.TextUtils;
|
||||
import com.hippo.network.InetValidator;
|
||||
|
||||
/**
|
||||
* Some configurable stuff about EH. It ends up cookie.
|
||||
@@ -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
|
||||
*/
|
||||
@@ -398,12 +518,12 @@ public class EhConfig implements Cloneable {
|
||||
/**
|
||||
* show warning
|
||||
*/
|
||||
private static final String CONTENT_WARNING_SHOW = "0";
|
||||
public static final String CONTENT_WARNING_SHOW = "0";
|
||||
|
||||
/**
|
||||
* not show warning
|
||||
*/
|
||||
private static final String CONTENT_WARNING_NOT_SHOW = "1";
|
||||
public static final String CONTENT_WARNING_NOT_SHOW = "1";
|
||||
|
||||
/**
|
||||
* Load images through the Hentai@Home Network<br/>
|
||||
@@ -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/>
|
||||
@@ -618,19 +767,25 @@ public class EhConfig implements Cloneable {
|
||||
}
|
||||
}
|
||||
|
||||
public void setDirty() {
|
||||
public synchronized void setDirty() {
|
||||
mDirty = true;
|
||||
}
|
||||
|
||||
private void updateUconfig() {
|
||||
String hahClientIpPort = (TextUtils.isEmpty(hahClientIp) || hahClientPort == -1) ?
|
||||
"" : hahClientIp + "%3A" + hahClientPort;
|
||||
String hahClientIpPort = (InetValidator.isValidInet4Address(hahClientIp) &&
|
||||
InetValidator.isValidInetPort(hahClientPort)) ?
|
||||
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 + "-" +
|
||||
@@ -650,7 +805,7 @@ public class EhConfig implements Cloneable {
|
||||
KEY_MULTI_PAGE_THUMB + "_" + multiPageThumb;
|
||||
}
|
||||
|
||||
public String uconfig() {
|
||||
public synchronized String uconfig() {
|
||||
if (mDirty) {
|
||||
mDirty = false;
|
||||
updateUconfig();
|
||||
|
||||
@@ -31,6 +31,15 @@ public class EhCookieStore extends CookieDBStore {
|
||||
public static final String KEY_IPD_MEMBER_ID = "ipb_member_id";
|
||||
public static final String KEY_IPD_PASS_HASH = "ipb_pass_hash";
|
||||
|
||||
public static final Cookie sTipsCookie =
|
||||
new Cookie.Builder()
|
||||
.name(EhConfig.KEY_CONTENT_WARNING)
|
||||
.value(EhConfig.CONTENT_WARNING_NOT_SHOW)
|
||||
.domain(EhUrl.DOMAIN_G)
|
||||
.path("/")
|
||||
.expiresAt(Long.MAX_VALUE)
|
||||
.build();
|
||||
|
||||
public void signOut() {
|
||||
removeAll();
|
||||
}
|
||||
@@ -40,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);
|
||||
@@ -68,27 +81,39 @@ public class EhCookieStore extends CookieDBStore {
|
||||
public List<Cookie> loadForRequest(HttpUrl url, Request request) {
|
||||
List<Cookie> cookies = super.loadForRequest(url, request);
|
||||
Object tag = request.tag();
|
||||
String host = url.host();
|
||||
|
||||
if (url.host().equals(EhUrl.DOMAIN_EX) && tag instanceof EhConfig) {
|
||||
EhConfig ehConfig = (EhConfig) tag;
|
||||
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_G);
|
||||
boolean checkUconfig = (domainMatch(host, EhUrl.DOMAIN_E) || domainMatch(host, EhUrl.DOMAIN_EX)) && tag instanceof EhConfig;
|
||||
|
||||
if (checkTips || checkUconfig) {
|
||||
List<Cookie> result = new ArrayList<>(cookies.size() + 1);
|
||||
// Add all but skip uconfig
|
||||
// Add all but skip some
|
||||
for (Cookie cookie: cookies) {
|
||||
if (EhConfig.KEY_UCONFIG.equals(cookie.name())) {
|
||||
String name = cookie.name();
|
||||
if (checkTips && EhConfig.KEY_CONTENT_WARNING.equals(name)) {
|
||||
continue;
|
||||
}
|
||||
if (checkUconfig && EhConfig.KEY_UCONFIG.equals(name)) {
|
||||
continue;
|
||||
}
|
||||
result.add(cookie);
|
||||
}
|
||||
// Add uconfig from EhConfig
|
||||
Cookie uconfigCookie = new Cookie.Builder()
|
||||
.name(EhConfig.KEY_UCONFIG)
|
||||
.value(ehConfig.uconfig())
|
||||
.domain(EhUrl.DOMAIN_EX)
|
||||
.path("/")
|
||||
.build();
|
||||
result.add(uconfigCookie);
|
||||
|
||||
// Add some
|
||||
if (checkTips) {
|
||||
result.add(sTipsCookie);
|
||||
}
|
||||
if (checkUconfig) {
|
||||
EhConfig ehConfig = (EhConfig) tag;
|
||||
Cookie uconfigCookie = new Cookie.Builder()
|
||||
.name(EhConfig.KEY_UCONFIG)
|
||||
.value(ehConfig.uconfig())
|
||||
.domain(host)
|
||||
.path("/")
|
||||
.expiresAt(Long.MAX_VALUE)
|
||||
.build();
|
||||
result.add(uconfigCookie);
|
||||
}
|
||||
return Collections.unmodifiableList(result);
|
||||
} else {
|
||||
return cookies;
|
||||
@@ -104,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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.data.GalleryComment;
|
||||
import com.hippo.ehviewer.client.data.GalleryDetail;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.data.LargePreviewSet;
|
||||
import com.hippo.ehviewer.client.data.PreviewSet;
|
||||
import com.hippo.ehviewer.client.exception.CancelledException;
|
||||
import com.hippo.ehviewer.client.exception.EhException;
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
@@ -36,24 +36,23 @@ 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;
|
||||
import com.hippo.ehviewer.client.parser.SignInParser;
|
||||
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;
|
||||
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;
|
||||
|
||||
@@ -61,6 +60,7 @@ import okhttp3.Call;
|
||||
import okhttp3.FormBody;
|
||||
import okhttp3.Headers;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
@@ -74,36 +74,13 @@ public class EhEngine {
|
||||
private static final String SAD_PANDA_TYPE = "image/gif";
|
||||
private static final String SAD_PANDA_LENGTH = "9615";
|
||||
|
||||
public static final long APIUID = 1363542;
|
||||
public static final String APIKEY = "f4b5407ab1727b9d08d7";
|
||||
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
|
||||
private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
|
||||
|
||||
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
|
||||
public static EhFilter sEhFilter;
|
||||
|
||||
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);
|
||||
}
|
||||
public static void initialize() {
|
||||
sEhFilter = EhFilter.getInstance();
|
||||
}
|
||||
|
||||
private static void throwException(Call call, int code, @Nullable Headers headers,
|
||||
@@ -124,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));
|
||||
}
|
||||
@@ -135,7 +112,7 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static String signIn(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static String signIn(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String username, String password) throws Exception {
|
||||
FormBody.Builder builder = new FormBody.Builder()
|
||||
.add("UserName", username)
|
||||
@@ -145,13 +122,15 @@ public class EhEngine {
|
||||
.add("temporary_https", "off");
|
||||
String url = EhUrl.API_SIGN_IN;
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(builder.build())
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -168,14 +147,16 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static GalleryListParser.Result getGalleryList(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url, boolean callApi) throws Exception {
|
||||
public static GalleryListParser.Result getGalleryList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -192,15 +173,37 @@ public class EhEngine {
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (callApi && result.galleryInfos.size() > 0) {
|
||||
fillGalleryListByApi(task, okHttpClient, result.galleryInfos);
|
||||
// Filter title and uploader
|
||||
List<GalleryInfo> list = result.galleryInfoList;
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
GalleryInfo info = list.get(i);
|
||||
if (!sEhFilter.filterTitle(info) || !sEhFilter.filterUploader(info)) {
|
||||
list.remove(i);
|
||||
i--;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
|
||||
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
|
||||
// Fill by api
|
||||
fillGalleryListByApi(task, okHttpClient, list);
|
||||
|
||||
// Filter tag
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
GalleryInfo info = list.get(i);
|
||||
if (!sEhFilter.filterTag(info) || !sEhFilter.filterTagNamespace(info)) {
|
||||
list.remove(i);
|
||||
i--;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// At least, GalleryInfo contain valid gid and token
|
||||
public static List<GalleryInfo> fillGalleryListByApi(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static List<GalleryInfo> fillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
List<GalleryInfo> galleryInfoList) throws Exception {
|
||||
// We can only request 25 items one time at most
|
||||
final int MAX_REQUEST_SIZE = 25;
|
||||
@@ -215,7 +218,7 @@ public class EhEngine {
|
||||
return galleryInfoList;
|
||||
}
|
||||
|
||||
private static void doFillGalleryListByApi(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
private static void doFillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
List<GalleryInfo> galleryInfoList) throws Exception {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("method", "gdata");
|
||||
@@ -229,15 +232,17 @@ public class EhEngine {
|
||||
}
|
||||
json.put("gidlist", ja);
|
||||
json.put("namespace", 1);
|
||||
String url = EhUrl.API_EX;
|
||||
String url = EhUrl.getApiUrl();
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url)
|
||||
.post(RequestBody.create(JSON, json.toString()))
|
||||
.post(RequestBody.create(MEDIA_TYPE_JSON, json.toString()))
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -254,14 +259,16 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static GalleryDetail getGalleryDetail(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static GalleryDetail getGalleryDetail(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -279,14 +286,16 @@ public class EhEngine {
|
||||
}
|
||||
|
||||
|
||||
public static Pair<LargePreviewSet, Integer> getLargePreviewSet(
|
||||
EhClient.Task task, OkHttpClient okHttpClient, String url) throws Exception {
|
||||
public static Pair<PreviewSet, Integer> getPreviewSet(
|
||||
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -296,7 +305,7 @@ public class EhEngine {
|
||||
code = response.code();
|
||||
headers = response.headers();
|
||||
body = response.body().string();
|
||||
return Pair.create(GalleryDetailParser.parseLargePreview(body),
|
||||
return Pair.create(GalleryDetailParser.parsePreviewSet(body),
|
||||
GalleryDetailParser.parsePreviewPages(body));
|
||||
} catch (Exception e) {
|
||||
throwException(call, code, headers, body, e);
|
||||
@@ -304,25 +313,28 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static RateGalleryParser.Result rateGallery(EhClient.Task task,
|
||||
OkHttpClient okHttpClient, long gid, String token, float rating) throws Exception {
|
||||
public static RateGalleryParser.Result rateGallery(@Nullable EhClient.Task task,
|
||||
OkHttpClient okHttpClient, long apiUid, String apiKey, long gid,
|
||||
String token, float rating) throws Exception {
|
||||
final JSONObject json = new JSONObject();
|
||||
json.put("method", "rategallery");
|
||||
json.put("apiuid", APIUID);
|
||||
json.put("apikey", APIKEY);
|
||||
json.put("apiuid", apiUid);
|
||||
json.put("apikey", apiKey);
|
||||
json.put("gid", gid);
|
||||
json.put("token", token);
|
||||
json.put("rating", (int) Math.ceil(rating * 2));
|
||||
final RequestBody requestBody = RequestBody.create(JSON, json.toString());
|
||||
String url = EhUrl.API_EX;
|
||||
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
|
||||
String url = EhUrl.getApiUrl();
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(requestBody)
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -339,19 +351,21 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static GalleryComment[] commentGallery(EhClient.Task task,
|
||||
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
|
||||
OkHttpClient okHttpClient, String url, String comment) throws Exception {
|
||||
FormBody.Builder builder = new FormBody.Builder()
|
||||
.add("commenttext", comment)
|
||||
.add("postcomment", "Post New");
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(builder.build())
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -361,29 +375,32 @@ public class EhEngine {
|
||||
code = response.code();
|
||||
headers = response.headers();
|
||||
body = response.body().string();
|
||||
return GalleryDetailParser.parseComment(body);
|
||||
Document document = Jsoup.parse(body);
|
||||
return GalleryDetailParser.parseComments(document);
|
||||
} catch (Exception e) {
|
||||
throwException(call, code, headers, body, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getGalleryToken(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static String getGalleryToken(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
long gid, String gtoken, int page) throws Exception {
|
||||
JSONObject json = new JSONObject()
|
||||
.put("method", "gtoken")
|
||||
.put("pagelist", new JSONArray().put(
|
||||
new JSONArray().put(gid).put(gtoken).put(page + 1)));
|
||||
final RequestBody requestBody = RequestBody.create(JSON, json.toString());
|
||||
String url = EhUrl.API_EX;
|
||||
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
|
||||
String url = EhUrl.getApiUrl();
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(requestBody)
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -400,14 +417,16 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static FavoritesParser.Result getFavorites(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static FavoritesParser.Result getFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url, boolean callApi) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -435,7 +454,7 @@ public class EhEngine {
|
||||
* @param dstCat -1 for delete, 0 - 9 for cloud favorite, others throw Exception
|
||||
* @param note max 250 characters
|
||||
*/
|
||||
public static Void addFavorites(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static Void addFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
long gid, String token, int dstCat, String note) throws Exception {
|
||||
String catStr;
|
||||
if (dstCat == -1) {
|
||||
@@ -450,15 +469,18 @@ 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, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(builder.build())
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -477,7 +499,7 @@ public class EhEngine {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Void addFavoritesRange(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
|
||||
AssertUtils.assertEqualsEx(gidArray.length, tokenArray.length);
|
||||
for (int i = 0, n = gidArray.length; i < n; i++) {
|
||||
@@ -486,7 +508,7 @@ public class EhEngine {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static FavoritesParser.Result modifyFavorites(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static FavoritesParser.Result modifyFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url, long[] gidArray, int dstCat, boolean callApi) throws Exception {
|
||||
String catStr;
|
||||
if (dstCat == -1) {
|
||||
@@ -503,13 +525,15 @@ public class EhEngine {
|
||||
}
|
||||
builder.add("apply", "Apply");
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig())
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(builder.build())
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -533,14 +557,16 @@ public class EhEngine {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Pair<String, String>[] getTorrentList(EhClient.Task task, OkHttpClient okHttpClient,
|
||||
public static Pair<String, String>[] getTorrentList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
String url) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -560,41 +586,51 @@ public class EhEngine {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<GalleryInfo> getWhatsHot(EhClient.Task task,
|
||||
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
|
||||
OkHttpClient okHttpClient) throws Exception {
|
||||
String url = EhUrl.HOST_G;
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
List<GalleryInfo> list;
|
||||
int code = -1;
|
||||
try {
|
||||
Response response = call.execute();
|
||||
code = response.code();
|
||||
headers = response.headers();
|
||||
body = response.body().string();
|
||||
List<GalleryInfo> list = WhatsHotParser.parse(body);
|
||||
fillGalleryListByApi(task, okHttpClient, list);
|
||||
return list;
|
||||
list = WhatsHotParser.parse(body);
|
||||
} catch (Exception e) {
|
||||
throwException(call, code, headers, body, e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (list.size() > 0) {
|
||||
// Fill by api
|
||||
fillGalleryListByApi(task, okHttpClient, list);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static ProfileParser.Result getProfileInternal(EhClient.Task task,
|
||||
private static ProfileParser.Result getProfileInternal(@Nullable EhClient.Task task,
|
||||
OkHttpClient okHttpClient, String url) throws Exception {
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -611,15 +647,17 @@ public class EhEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public static ProfileParser.Result getProfile(EhClient.Task task,
|
||||
public static ProfileParser.Result getProfile(@Nullable EhClient.Task task,
|
||||
OkHttpClient okHttpClient) throws Exception {
|
||||
String url = EhUrl.URL_FORUMS;
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, task.getEhConfig()).build();
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
task.setCall(call);
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
@@ -635,4 +673,160 @@ public class EhEngine {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public static VoteCommentParser.Result voteComment(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Exception {
|
||||
final JSONObject json = new JSONObject();
|
||||
json.put("method", "votecomment");
|
||||
json.put("apiuid", apiUid);
|
||||
json.put("apikey", apiKey);
|
||||
json.put("gid", gid);
|
||||
json.put("token", token);
|
||||
json.put("comment_id", commentId);
|
||||
json.put("comment_vote", commentVote);
|
||||
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
|
||||
String url = EhUrl.getApiUrl();
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(requestBody)
|
||||
.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 VoteCommentParser.parse(body, commentVote);
|
||||
} catch (Exception e) {
|
||||
throwException(call, code, headers, body, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param image Must be jpeg
|
||||
*/
|
||||
public static GalleryListParser.Result imageSearch(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
|
||||
File image, boolean uss, boolean osc, boolean se) throws Exception {
|
||||
MultipartBody.Builder builder = new MultipartBody.Builder();
|
||||
builder.setType(MultipartBody.FORM);
|
||||
builder.addPart(
|
||||
Headers.of("Content-Disposition", "form-data; name=\"sfile\"; filename=\"a.jpg\""),
|
||||
RequestBody.create(MEDIA_TYPE_JPEG, image)
|
||||
);
|
||||
if (uss) {
|
||||
builder.addPart(
|
||||
Headers.of("Content-Disposition", "form-data; name=\"fs_similar\""),
|
||||
RequestBody.create(null, "on")
|
||||
);
|
||||
}
|
||||
if (osc) {
|
||||
builder.addPart(
|
||||
Headers.of("Content-Disposition", "form-data; name=\"fs_covers\""),
|
||||
RequestBody.create(null, "on")
|
||||
);
|
||||
}
|
||||
if (se) {
|
||||
builder.addPart(
|
||||
Headers.of("Content-Disposition", "form-data; name=\"fs_exp\""),
|
||||
RequestBody.create(null, "on")
|
||||
);
|
||||
}
|
||||
builder.addPart(
|
||||
Headers.of("Content-Disposition", "form-data; name=\"f_sfile\""),
|
||||
RequestBody.create(null, "File Search")
|
||||
);
|
||||
String url = EhUrl.getImageSearchUrl();
|
||||
Log.d(TAG, url);
|
||||
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
|
||||
.post(builder.build())
|
||||
.build();
|
||||
Call call = okHttpClient.newCall(request);
|
||||
|
||||
// Put call
|
||||
if (null != task) {
|
||||
task.setCall(call);
|
||||
}
|
||||
|
||||
String body = null;
|
||||
Headers headers = null;
|
||||
GalleryListParser.Result result;
|
||||
int code = -1;
|
||||
try {
|
||||
Response response = call.execute();
|
||||
|
||||
Log.d(TAG, "" + response.request().url().toString());
|
||||
|
||||
code = response.code();
|
||||
headers = response.headers();
|
||||
body = response.body().string();
|
||||
result = GalleryListParser.parse(body);
|
||||
} catch (Exception e) {
|
||||
throwException(call, code, headers, body, e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Filter title and uploader
|
||||
List<GalleryInfo> list = result.galleryInfoList;
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
GalleryInfo info = list.get(i);
|
||||
if (!sEhFilter.filterTitle(info) || !sEhFilter.filterUploader(info)) {
|
||||
list.remove(i);
|
||||
i--;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
|
||||
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
|
||||
// Fill by api
|
||||
fillGalleryListByApi(task, okHttpClient, list);
|
||||
|
||||
// Filter tag
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
GalleryInfo info = list.get(i);
|
||||
if (!sEhFilter.filterTag(info) || !sEhFilter.filterTagNamespace(info)) {
|
||||
list.remove(i);
|
||||
i--;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
* 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.client;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.EhDB;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.dao.Filter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class EhFilter {
|
||||
|
||||
private static final String TAG = EhFilter.class.getSimpleName();
|
||||
|
||||
public static final int MODE_TITLE = 0;
|
||||
public static final int MODE_UPLOADER = 1;
|
||||
public static final int MODE_TAG = 2;
|
||||
public static final int MODE_TAG_NAMESPACE = 3;
|
||||
|
||||
private final List<Filter> mTitleFilterList = new ArrayList<>();
|
||||
private final List<Filter> mUploaderFilterList = new ArrayList<>();
|
||||
private final List<Filter> mTagFilterList = new ArrayList<>();
|
||||
private final List<Filter> mTagNamespaceFilterList = new ArrayList<>();
|
||||
|
||||
private static EhFilter sInstance;
|
||||
|
||||
public static EhFilter getInstance() {
|
||||
if (sInstance == null) {
|
||||
sInstance = new EhFilter();
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
private EhFilter() {
|
||||
List<Filter> list = EhDB.getAllFilter();
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
Filter filter = list.get(i);
|
||||
switch (filter.mode) {
|
||||
case MODE_TITLE:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTitleFilterList.add(filter);
|
||||
break;
|
||||
case MODE_UPLOADER:
|
||||
mUploaderFilterList.add(filter);
|
||||
break;
|
||||
case MODE_TAG:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTagFilterList.add(filter);
|
||||
break;
|
||||
case MODE_TAG_NAMESPACE:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTagNamespaceFilterList.add(filter);
|
||||
break;
|
||||
default:
|
||||
Log.d(TAG, "Unknown mode: " + filter.mode);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<Filter> getTitleFilterList() {
|
||||
return mTitleFilterList;
|
||||
}
|
||||
|
||||
public List<Filter> getUploaderFilterList() {
|
||||
return mUploaderFilterList;
|
||||
}
|
||||
|
||||
public List<Filter> getTagFilterList() {
|
||||
return mTagFilterList;
|
||||
}
|
||||
|
||||
public List<Filter> getTagNamespaceFilterList() {
|
||||
return mTagNamespaceFilterList;
|
||||
}
|
||||
|
||||
public synchronized void addFilter(Filter filter) {
|
||||
EhDB.addFilter(filter);
|
||||
|
||||
switch (filter.mode) {
|
||||
case MODE_TITLE:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTitleFilterList.add(filter);
|
||||
break;
|
||||
case MODE_UPLOADER:
|
||||
mUploaderFilterList.add(filter);
|
||||
break;
|
||||
case MODE_TAG:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTagFilterList.add(filter);
|
||||
break;
|
||||
case MODE_TAG_NAMESPACE:
|
||||
filter.text = filter.text.toLowerCase();
|
||||
mTagNamespaceFilterList.add(filter);
|
||||
break;
|
||||
default:
|
||||
Log.d(TAG, "Unknown mode: " + filter.mode);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void deleteFilter(Filter filter) {
|
||||
EhDB.deleteFilter(filter);
|
||||
|
||||
switch (filter.mode) {
|
||||
case MODE_TITLE:
|
||||
mTitleFilterList.remove(filter);
|
||||
break;
|
||||
case MODE_UPLOADER:
|
||||
mUploaderFilterList.remove(filter);
|
||||
break;
|
||||
case MODE_TAG:
|
||||
mTagFilterList.remove(filter);
|
||||
break;
|
||||
case MODE_TAG_NAMESPACE:
|
||||
mTagNamespaceFilterList.remove(filter);
|
||||
break;
|
||||
default:
|
||||
Log.d(TAG, "Unknown mode: " + filter.mode);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean needCallApi() {
|
||||
return 0 != mTagFilterList.size() || 0 != mTagNamespaceFilterList.size();
|
||||
}
|
||||
|
||||
public synchronized boolean filterTitle(GalleryInfo info) {
|
||||
if (null == info) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Title
|
||||
String title = info.title;
|
||||
List<Filter> filters = mTitleFilterList;
|
||||
if (null != title && filters.size() > 0) {
|
||||
title = title.toLowerCase();
|
||||
for (int i = 0, n = filters.size(); i < n; i++) {
|
||||
if (title.contains(filters.get(i).text)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean filterUploader(GalleryInfo info) {
|
||||
if (null == info) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Uploader
|
||||
String uploader = info.uploader;
|
||||
List<Filter> filters = mUploaderFilterList;
|
||||
if (null != uploader && filters.size() > 0) {
|
||||
for (int i = 0, n = filters.size(); i < n; i++) {
|
||||
if (uploader.equals(filters.get(i).text)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean matchTag(String tag, String filter) {
|
||||
if (null == tag || null == filter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String tagNamespace;
|
||||
String tagName;
|
||||
String filterNamespace;
|
||||
String filterName;
|
||||
int index = tag.indexOf(':');
|
||||
if (index < 0) {
|
||||
tagNamespace = null;
|
||||
tagName = tag;
|
||||
} else {
|
||||
tagNamespace = tag.substring(0, index);
|
||||
tagName = tag.substring(index + 1);
|
||||
}
|
||||
index = filter.indexOf(':');
|
||||
if (index < 0) {
|
||||
filterNamespace = null;
|
||||
filterName = filter;
|
||||
} else {
|
||||
filterNamespace = filter.substring(0, index);
|
||||
filterName = filter.substring(index + 1);
|
||||
}
|
||||
|
||||
if (null != tagNamespace && null != filterNamespace &&
|
||||
!tagNamespace.equals(filterNamespace)) {
|
||||
return false;
|
||||
}
|
||||
if (!tagName.equals(filterName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean filterTag(GalleryInfo info) {
|
||||
if (null == info) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tag
|
||||
String[] tags = info.simpleTags;
|
||||
List<Filter> filters = mTagFilterList;
|
||||
if (null != tags && filters.size() > 0) {
|
||||
for (String tag: tags) {
|
||||
for (int i = 0, n = filters.size(); i < n; i++) {
|
||||
if (matchTag(tag, filters.get(i).text)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean matchTagNamespace(String tag, String filter) {
|
||||
if (null == tag || null == filter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String tagNamespace;
|
||||
int index = tag.indexOf(':');
|
||||
if (index >= 0) {
|
||||
tagNamespace = tag.substring(0, index);
|
||||
return tagNamespace.equals(filter);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean filterTagNamespace(GalleryInfo info) {
|
||||
if (null == info) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] tags = info.simpleTags;
|
||||
List<Filter> filters = mTagNamespaceFilterList;
|
||||
if (null != tags && filters.size() > 0) {
|
||||
for (String tag: tags) {
|
||||
for (int i = 0, n = filters.size(); i < n; i++) {
|
||||
if (matchTagNamespace(tag, filters.get(i).text)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -16,33 +16,72 @@
|
||||
|
||||
package com.hippo.ehviewer.client;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.network.UrlBuilder;
|
||||
|
||||
public class EhUrl {
|
||||
|
||||
public static final int SITE_G = 0;
|
||||
public static final int SITE_EX = 1;
|
||||
|
||||
public static final String DOMAIN_EX = "exhentai.org";
|
||||
public static final String DOMAIN_E = "e-hentai.org";
|
||||
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 + "/";
|
||||
|
||||
public static final String API_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
|
||||
|
||||
public static final String API_G = HOST_G + "api.php";
|
||||
public static final String API_EX = HOST_EX + "api.php";
|
||||
|
||||
public static final String URL_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login";
|
||||
public static final String URL_REGISTER = "http://forums.e-hentai.org/index.php?act=Reg&CODE=00";
|
||||
public static final String URL_FAVORITES = HOST_EX + "favorites.php";
|
||||
public static final String URL_FAVORITES_G = HOST_G + "favorites.php";
|
||||
public static final String URL_FAVORITES_EX = HOST_EX + "favorites.php";
|
||||
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
|
||||
|
||||
public static String getGalleryDetailUrl(long gid, String token) {
|
||||
return getGalleryDetailUrl(gid, token, 0, false);
|
||||
}
|
||||
|
||||
public static String getHost() {
|
||||
switch (Settings.getGallerySite()) {
|
||||
default:
|
||||
case SITE_G:
|
||||
return HOST_G;
|
||||
case SITE_EX:
|
||||
return HOST_EX;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getFavoritesUrl() {
|
||||
switch (Settings.getGallerySite()) {
|
||||
default:
|
||||
case SITE_G:
|
||||
return URL_FAVORITES_G;
|
||||
case SITE_EX:
|
||||
return URL_FAVORITES_EX;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getApiUrl() {
|
||||
switch (Settings.getGallerySite()) {
|
||||
default:
|
||||
case SITE_G:
|
||||
return API_G;
|
||||
case SITE_EX:
|
||||
return API_EX;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getGalleryDetailUrl(long gid, String token, int index, boolean allComment) {
|
||||
UrlBuilder builder = new UrlBuilder(HOST_EX + "g/" + gid + '/' + token + '/');
|
||||
UrlBuilder builder = new UrlBuilder(getHost() + "g/" + gid + '/' + token + '/');
|
||||
if (index != 0) {
|
||||
builder.addQuery("p", index);
|
||||
}
|
||||
@@ -53,10 +92,25 @@ public class EhUrl {
|
||||
}
|
||||
|
||||
public static String getPageUrl(long gid, int index, String pToken) {
|
||||
return HOST_EX + "s/" + pToken + '/' + gid + '-' + (index + 1);
|
||||
return getHost() + "s/" + pToken + '/' + gid + '-' + (index + 1);
|
||||
}
|
||||
|
||||
public static String getAddFavorites(long gid, String token) {
|
||||
return HOST_EX + "gallerypopups.php?gid=" + gid + "&t=" + token + "&act=addfav";
|
||||
return getHost() + "gallerypopups.php?gid=" + gid + "&t=" + token + "&act=addfav";
|
||||
}
|
||||
|
||||
public static String getTagDefinitionUrl(String tag) {
|
||||
return "https://ehwiki.org/wiki/" + tag.replace(' ', '_');
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static String getImageSearchUrl() {
|
||||
switch (Settings.getGallerySite()) {
|
||||
default:
|
||||
case SITE_G:
|
||||
return "http://ul.e-hentai.org/image_lookup.php";
|
||||
case SITE_EX:
|
||||
return "http://ul.exhentai.org/image_lookup.php";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,17 +18,23 @@ package com.hippo.ehviewer.client;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class EhUtils {
|
||||
|
||||
public static final int NONE = -1; // Use it for homepage
|
||||
public static final int UNKNOWN = 0x400;
|
||||
|
||||
public static final int ALL_CATEGORY = EhUtils.UNKNOWN - 1;
|
||||
//DOUJINSHI|MANGA|ARTIST_CG|GAME_CG|WESTERN|NON_H|IMAGE_SET|COSPLAY|ASIAN_PORN|MISC;
|
||||
|
||||
public static final int BG_COLOR_DOUJINSHI = 0xfff44336;
|
||||
public static final int BG_COLOR_MANGA = 0xffff9800;
|
||||
public static final int BG_COLOR_ARTIST_CG = 0xfffbc02d;
|
||||
@@ -41,6 +47,14 @@ public class EhUtils {
|
||||
public static final int BG_COLOR_MISC = 0xfff06292;
|
||||
public static final int BG_COLOR_UNKNOWN = Color.BLACK;
|
||||
|
||||
// Remove [XXX], (XXX), {XXX}, ~XXX~ stuff
|
||||
public static final Pattern PATTERN_TITLE_PREFIX = Pattern.compile(
|
||||
"^(?:(?:\\([^\\)]*\\))|(?:\\[[^\\]]*\\])|(?:\\{[^\\}]*\\})|(?:~[^~]*~)|\\s+)*");
|
||||
// Remove [XXX], (XXX), {XXX}, ~XXX~ stuff and something like ch. 1-23
|
||||
public static final Pattern PATTERN_TITLE_SUFFIX = Pattern.compile(
|
||||
"(?:\\s+ch.[\\s\\d-]+)?(?:(?:\\([^\\)]*\\))|(?:\\[[^\\]]*\\])|(?:\\{[^\\}]*\\})|(?:~[^~]*~)|\\s+)*$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final int[] CATEGORY_VALUES = {
|
||||
EhConfig.MISC,
|
||||
EhConfig.DOUJINSHI,
|
||||
@@ -119,10 +133,11 @@ public class EhUtils {
|
||||
EhApplication.getEhCookieStore(context).signOut();
|
||||
Settings.putAvatar(null);
|
||||
Settings.putDisplayName(null);
|
||||
Settings.putNeedSignIn(true);
|
||||
}
|
||||
|
||||
public static boolean hasSignedIn(Context context) {
|
||||
return EhApplication.getEhCookieStore(context).hasSignedIn();
|
||||
public static boolean needSignedIn(Context context) {
|
||||
return Settings.getNeedSignIn() && !EhApplication.getEhCookieStore(context).hasSignedIn();
|
||||
}
|
||||
|
||||
public static String getSuitableTitle(GalleryInfo gi) {
|
||||
@@ -132,4 +147,52 @@ public class EhUtils {
|
||||
return TextUtils.isEmpty(gi.title) ? gi.titleJpn : gi.title;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static String extractTitle(String title) {
|
||||
if (null == title) {
|
||||
return null;
|
||||
}
|
||||
title = PATTERN_TITLE_PREFIX.matcher(title).replaceFirst("");
|
||||
title = PATTERN_TITLE_SUFFIX.matcher(title).replaceFirst("");
|
||||
// Sometimes title is combined by romaji and english translation.
|
||||
// Only need romaji.
|
||||
// TODO But not sure every '|' means that
|
||||
int index = title.indexOf('|');
|
||||
if (index >= 0) {
|
||||
title = title.substring(0, index);
|
||||
}
|
||||
if (title.isEmpty()) {
|
||||
return null;
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ public class FavListUrlBuilder implements Parcelable {
|
||||
}
|
||||
|
||||
public String build() {
|
||||
UrlBuilder ub = new UrlBuilder(EhUrl.URL_FAVORITES);
|
||||
UrlBuilder ub = new UrlBuilder(EhUrl.getFavoritesUrl());
|
||||
if (isValidFavCat(mFavCat)) {
|
||||
ub.addQuery("favcat", Integer.toString(mFavCat));
|
||||
}
|
||||
|
||||
@@ -21,6 +21,12 @@ import android.os.Parcelable;
|
||||
|
||||
public class GalleryComment implements Parcelable {
|
||||
|
||||
// 0 for uploader comment. can't vote
|
||||
public long id;
|
||||
public int score;
|
||||
public boolean voteUp;
|
||||
public boolean voteDown;
|
||||
public String voteState;
|
||||
public long time;
|
||||
public String user;
|
||||
public String comment;
|
||||
@@ -32,6 +38,11 @@ public class GalleryComment implements Parcelable {
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeLong(this.id);
|
||||
dest.writeInt(this.score);
|
||||
dest.writeByte(voteUp ? (byte) 1 : (byte) 0);
|
||||
dest.writeByte(voteDown ? (byte) 1 : (byte) 0);
|
||||
dest.writeString(this.voteState);
|
||||
dest.writeLong(this.time);
|
||||
dest.writeString(this.user);
|
||||
dest.writeString(this.comment);
|
||||
@@ -41,16 +52,23 @@ public class GalleryComment implements Parcelable {
|
||||
}
|
||||
|
||||
protected GalleryComment(Parcel in) {
|
||||
this.id = in.readLong();
|
||||
this.score = in.readInt();
|
||||
this.voteUp = in.readByte() != 0;
|
||||
this.voteDown = in.readByte() != 0;
|
||||
this.voteState = in.readString();
|
||||
this.time = in.readLong();
|
||||
this.user = in.readString();
|
||||
this.comment = in.readString();
|
||||
}
|
||||
|
||||
public static final Creator<GalleryComment> CREATOR = new Creator<GalleryComment>() {
|
||||
@Override
|
||||
public GalleryComment createFromParcel(Parcel source) {
|
||||
return new GalleryComment(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryComment[] newArray(int size) {
|
||||
return new GalleryComment[size];
|
||||
}
|
||||
|
||||
@@ -23,22 +23,22 @@ import java.util.Arrays;
|
||||
|
||||
public class GalleryDetail extends GalleryInfo {
|
||||
|
||||
public long apiUid = -1L;
|
||||
public String apiKey;
|
||||
public int torrentCount;
|
||||
public String torrentUrl;
|
||||
public String parent;
|
||||
public String visible;
|
||||
public String language;
|
||||
public String size;
|
||||
public String resize;
|
||||
public int pages;
|
||||
public int favoredTimes;
|
||||
public boolean isFavored;
|
||||
public int ratedTimes;
|
||||
public int favoriteCount;
|
||||
public boolean isFavorited;
|
||||
public int ratingCount;
|
||||
public GalleryTagGroup[] tags;
|
||||
public GalleryComment[] comments;
|
||||
public int previewPages;
|
||||
public LargePreviewSet previewSet;
|
||||
|
||||
public PreviewSet previewSet;
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
@@ -54,11 +54,10 @@ public class GalleryDetail extends GalleryInfo {
|
||||
dest.writeString(this.visible);
|
||||
dest.writeString(this.language);
|
||||
dest.writeString(this.size);
|
||||
dest.writeString(this.resize);
|
||||
dest.writeInt(this.pages);
|
||||
dest.writeInt(this.favoredTimes);
|
||||
dest.writeByte(isFavored ? (byte) 1 : (byte) 0);
|
||||
dest.writeInt(this.ratedTimes);
|
||||
dest.writeInt(this.favoriteCount);
|
||||
dest.writeByte(isFavorited ? (byte) 1 : (byte) 0);
|
||||
dest.writeInt(this.ratingCount);
|
||||
dest.writeParcelableArray(this.tags, 0);
|
||||
dest.writeParcelableArray(this.comments, 0);
|
||||
dest.writeInt(this.previewPages);
|
||||
@@ -76,11 +75,10 @@ public class GalleryDetail extends GalleryInfo {
|
||||
this.visible = in.readString();
|
||||
this.language = in.readString();
|
||||
this.size = in.readString();
|
||||
this.resize = in.readString();
|
||||
this.pages = in.readInt();
|
||||
this.favoredTimes = in.readInt();
|
||||
this.isFavored = in.readByte() != 0;
|
||||
this.ratedTimes = in.readInt();
|
||||
this.favoriteCount = in.readInt();
|
||||
this.isFavorited = in.readByte() != 0;
|
||||
this.ratingCount = in.readInt();
|
||||
Parcelable[] array = in.readParcelableArray(GalleryTagGroup.class.getClassLoader());
|
||||
if (array != null) {
|
||||
this.tags = Arrays.copyOf(array, array.length, GalleryTagGroup[].class);
|
||||
@@ -94,7 +92,7 @@ public class GalleryDetail extends GalleryInfo {
|
||||
this.comments = null;
|
||||
}
|
||||
this.previewPages = in.readInt();
|
||||
this.previewSet = in.readParcelable(LargePreviewSet.class.getClassLoader());
|
||||
this.previewSet = in.readParcelable(PreviewSet.class.getClassLoader());
|
||||
}
|
||||
|
||||
public static final Creator<GalleryDetail> CREATOR = new Creator<GalleryDetail>() {
|
||||
|
||||
@@ -63,7 +63,7 @@ public class GalleryInfo implements Parcelable {
|
||||
|
||||
public static final Pattern[] S_LANG_PATTERNS = {
|
||||
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
|
||||
Pattern.compile("[((\\[]chinese[))\\]]|[汉漢]化|中[国國][语語]|中文|[(\\[]CN[)\\]]", Pattern.CASE_INSENSITIVE),
|
||||
Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文", Pattern.CASE_INSENSITIVE),
|
||||
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]", Pattern.CASE_INSENSITIVE),
|
||||
Pattern.compile("[(\\[]korean?[)\\]]", Pattern.CASE_INSENSITIVE),
|
||||
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]", Pattern.CASE_INSENSITIVE),
|
||||
@@ -90,6 +90,13 @@ public class GalleryInfo implements Parcelable {
|
||||
@Nullable
|
||||
public String[] simpleTags;
|
||||
|
||||
public int thumbWidth;
|
||||
public int thumbHeight;
|
||||
|
||||
public int spanSize;
|
||||
public int spanIndex;
|
||||
public int spanGroupIndex;
|
||||
|
||||
/**
|
||||
* language from title
|
||||
*/
|
||||
@@ -123,6 +130,11 @@ public class GalleryInfo implements Parcelable {
|
||||
dest.writeFloat(this.rating);
|
||||
dest.writeString(this.simpleLanguage);
|
||||
dest.writeStringArray(this.simpleTags);
|
||||
dest.writeInt(this.thumbWidth);
|
||||
dest.writeInt(this.thumbHeight);
|
||||
dest.writeInt(this.spanSize);
|
||||
dest.writeInt(this.spanIndex);
|
||||
dest.writeInt(this.spanGroupIndex);
|
||||
}
|
||||
|
||||
public GalleryInfo() {}
|
||||
@@ -139,6 +151,11 @@ public class GalleryInfo implements Parcelable {
|
||||
this.rating = in.readFloat();
|
||||
this.simpleLanguage = in.readString();
|
||||
this.simpleTags = in.createStringArray();
|
||||
this.thumbWidth = in.readInt();
|
||||
this.thumbHeight = in.readInt();
|
||||
this.spanSize = in.readInt();
|
||||
this.spanIndex = in.readInt();
|
||||
this.spanGroupIndex = in.readInt();
|
||||
}
|
||||
|
||||
public static final Parcelable.Creator<GalleryInfo> CREATOR = new Parcelable.Creator<GalleryInfo>() {
|
||||
|
||||
@@ -19,11 +19,27 @@ package com.hippo.ehviewer.client.data;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
import com.hippo.widget.LoadImageView;
|
||||
|
||||
public class GalleryPreview implements Parcelable {
|
||||
|
||||
public String imageUrl;
|
||||
public String pageUrl;
|
||||
public int index;
|
||||
String imageKey;
|
||||
String imageUrl;
|
||||
String pageUrl;
|
||||
int position;
|
||||
int offsetX = Integer.MIN_VALUE;
|
||||
int offsetY = Integer.MIN_VALUE;
|
||||
int clipWidth = Integer.MIN_VALUE;
|
||||
int clipHeight = Integer.MIN_VALUE;
|
||||
|
||||
public int getPosition() {
|
||||
return position;
|
||||
}
|
||||
|
||||
public void load(LoadImageView view) {
|
||||
view.setClip(offsetX, offsetY, clipWidth, clipHeight);
|
||||
view.load(imageKey, imageUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
@@ -34,7 +50,11 @@ public class GalleryPreview implements Parcelable {
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeString(this.imageUrl);
|
||||
dest.writeString(this.pageUrl);
|
||||
dest.writeInt(this.index);
|
||||
dest.writeInt(this.position);
|
||||
dest.writeInt(this.offsetX);
|
||||
dest.writeInt(this.offsetY);
|
||||
dest.writeInt(this.clipWidth);
|
||||
dest.writeInt(this.clipHeight);
|
||||
}
|
||||
|
||||
public GalleryPreview() {
|
||||
@@ -43,14 +63,20 @@ public class GalleryPreview implements Parcelable {
|
||||
protected GalleryPreview(Parcel in) {
|
||||
this.imageUrl = in.readString();
|
||||
this.pageUrl = in.readString();
|
||||
this.index = in.readInt();
|
||||
this.position = in.readInt();
|
||||
this.offsetX = in.readInt();
|
||||
this.offsetY = in.readInt();
|
||||
this.clipWidth = in.readInt();
|
||||
this.clipHeight = in.readInt();
|
||||
}
|
||||
|
||||
public static final Parcelable.Creator<GalleryPreview> CREATOR = new Parcelable.Creator<GalleryPreview>() {
|
||||
@Override
|
||||
public GalleryPreview createFromParcel(Parcel source) {
|
||||
return new GalleryPreview(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryPreview[] newArray(int size) {
|
||||
return new GalleryPreview[size];
|
||||
}
|
||||
|
||||
@@ -21,10 +21,11 @@ import android.os.Parcelable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
// TODO Add url field?
|
||||
public class GalleryTagGroup implements Parcelable {
|
||||
|
||||
public String groupName;
|
||||
private ArrayList<String> mTagList;
|
||||
private final ArrayList<String> mTagList;
|
||||
|
||||
public void addTag(String tag) {
|
||||
mTagList.add(tag);
|
||||
|
||||
@@ -19,38 +19,56 @@ package com.hippo.ehviewer.client.data;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
import com.hippo.ehviewer.client.EhCacheKeyFactory;
|
||||
import com.hippo.widget.LoadImageView;
|
||||
import com.hippo.yorozuya.IntList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class LargePreviewSet implements Parcelable {
|
||||
public class LargePreviewSet extends PreviewSet {
|
||||
|
||||
private IntList mIndexList;
|
||||
private ArrayList<String> mImageUrlList;
|
||||
private ArrayList<String> mPageUrlList;
|
||||
|
||||
public int size() {
|
||||
return mImageUrlList.size();
|
||||
}
|
||||
private final IntList mPositionList;
|
||||
private final ArrayList<String> mImageUrlList;
|
||||
private final ArrayList<String> mPageUrlList;
|
||||
|
||||
public void addItem(int index, String imageUrl, String pageUrl) {
|
||||
mIndexList.add(index);
|
||||
mPositionList.add(index);
|
||||
mImageUrlList.add(imageUrl);
|
||||
mPageUrlList.add(pageUrl);
|
||||
}
|
||||
|
||||
public int getIndexAt(int index) {
|
||||
return mIndexList.get(index);
|
||||
@Override
|
||||
public int size() {
|
||||
return mImageUrlList.size();
|
||||
}
|
||||
|
||||
public String getImageUrlAt(int index) {
|
||||
return mImageUrlList.get(index);
|
||||
@Override
|
||||
public int getPosition(int index) {
|
||||
return mPositionList.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPageUrlAt(int index) {
|
||||
return mPageUrlList.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryPreview getGalleryPreview(long gid, int index) {
|
||||
GalleryPreview galleryPreview = new GalleryPreview();
|
||||
galleryPreview.position = mPositionList.get(index);
|
||||
galleryPreview.imageKey = EhCacheKeyFactory.getLargePreviewKey(gid, galleryPreview.position);
|
||||
galleryPreview.imageUrl = mImageUrlList.get(index);
|
||||
galleryPreview.pageUrl = mPageUrlList.get(index);
|
||||
return galleryPreview;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(LoadImageView view, long gid, int index) {
|
||||
view.resetClip();
|
||||
view.load(EhCacheKeyFactory.getLargePreviewKey(gid, mPositionList.get(index)),
|
||||
mImageUrlList.get(index));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
@@ -58,19 +76,19 @@ public class LargePreviewSet implements Parcelable {
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeParcelable(this.mIndexList, flags);
|
||||
dest.writeParcelable(this.mPositionList, flags);
|
||||
dest.writeStringList(this.mImageUrlList);
|
||||
dest.writeStringList(this.mPageUrlList);
|
||||
}
|
||||
|
||||
public LargePreviewSet() {
|
||||
mIndexList = new IntList();
|
||||
mPositionList = new IntList();
|
||||
mImageUrlList = new ArrayList<>();
|
||||
mPageUrlList = new ArrayList<>();
|
||||
}
|
||||
|
||||
protected LargePreviewSet(Parcel in) {
|
||||
this.mIndexList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mPositionList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mImageUrlList = in.createStringArrayList();
|
||||
this.mPageUrlList = in.createStringArrayList();
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.client.data;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
import android.support.annotation.IntDef;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.client.EhConfig;
|
||||
@@ -48,9 +49,6 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
public static final int MODE_WHATS_HOT = 0x3;
|
||||
public static final int MODE_IMAGE_SEARCH = 0x4;
|
||||
|
||||
public static final int ALL_CATEGORT = EhUtils.UNKNOWN - 1;
|
||||
//DOUJINSHI|MANGA|ARTIST_CG|GAME_CG|WESTERN|NON_H|IMAGE_SET|COSPLAY|ASIAN_PORN|MISC;
|
||||
|
||||
public static final int DEFAULT_ADVANCE = AdvanceSearchTable.SNAME | AdvanceSearchTable.STAGS;
|
||||
public static final int DEFAULT_MIN_RATING = 2;
|
||||
|
||||
@@ -65,6 +63,11 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
private int mAdvanceSearch = -1;
|
||||
private int mMinRating = -1;
|
||||
|
||||
private String mImagePath;
|
||||
private boolean mUseSimilarityScan;
|
||||
private boolean mOnlySearchCovers;
|
||||
private boolean mShowExpunged;
|
||||
|
||||
/**
|
||||
* Make this ListUrlBuilder point to homepage
|
||||
*/
|
||||
@@ -75,6 +78,10 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
mKeyword = null;
|
||||
mAdvanceSearch = -1;
|
||||
mMinRating = -1;
|
||||
mImagePath = null;
|
||||
mUseSimilarityScan = false;
|
||||
mOnlySearchCovers = false;
|
||||
mShowExpunged = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -135,6 +142,39 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
mMinRating = minRating;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getImagePath() {
|
||||
return mImagePath;
|
||||
}
|
||||
|
||||
public void setImagePath(String imagePath) {
|
||||
mImagePath = imagePath;
|
||||
}
|
||||
|
||||
public boolean isUseSimilarityScan() {
|
||||
return mUseSimilarityScan;
|
||||
}
|
||||
|
||||
public void setUseSimilarityScan(boolean useSimilarityScan) {
|
||||
mUseSimilarityScan = useSimilarityScan;
|
||||
}
|
||||
|
||||
public boolean isOnlySearchCovers() {
|
||||
return mOnlySearchCovers;
|
||||
}
|
||||
|
||||
public void setOnlySearchCovers(boolean onlySearchCovers) {
|
||||
mOnlySearchCovers = onlySearchCovers;
|
||||
}
|
||||
|
||||
public boolean isShowExpunged() {
|
||||
return mShowExpunged;
|
||||
}
|
||||
|
||||
public void setShowExpunged(boolean showExpunged) {
|
||||
mShowExpunged = showExpunged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make them the same
|
||||
* @param lub The template
|
||||
@@ -146,6 +186,10 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
mKeyword = lub.mKeyword;
|
||||
mAdvanceSearch = lub.mAdvanceSearch;
|
||||
mMinRating = lub.mMinRating;
|
||||
mImagePath = lub.mImagePath;
|
||||
mUseSimilarityScan = lub.mUseSimilarityScan;
|
||||
mOnlySearchCovers = lub.mOnlySearchCovers;
|
||||
mShowExpunged = lub.mShowExpunged;
|
||||
}
|
||||
|
||||
public void set(QuickSearch q) {
|
||||
@@ -154,6 +198,10 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
mKeyword = q.keyword;
|
||||
mAdvanceSearch = q.advanceSearch;
|
||||
mMinRating = q.minRating;
|
||||
mImagePath = null;
|
||||
mUseSimilarityScan = false;
|
||||
mOnlySearchCovers = false;
|
||||
mShowExpunged = false;
|
||||
}
|
||||
|
||||
public QuickSearch toQuickSearch() {
|
||||
@@ -166,6 +214,30 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
return q;
|
||||
}
|
||||
|
||||
public boolean equalsQuickSearch(QuickSearch q) {
|
||||
if (null == q) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (q.mode != mMode) {
|
||||
return false;
|
||||
}
|
||||
if (q.category != mCategory) {
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.equals(q.keyword, mKeyword)) {
|
||||
return false;
|
||||
}
|
||||
if (q.advanceSearch != mAdvanceSearch) {
|
||||
return false;
|
||||
}
|
||||
if (q.minRating != mMinRating) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param query xxx=yyy&mmm=nnn
|
||||
*/
|
||||
@@ -315,7 +387,7 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
default:
|
||||
case MODE_NORMAL: {
|
||||
boolean filter = false;
|
||||
UrlBuilder ub = new UrlBuilder(EhUrl.HOST_EX);
|
||||
UrlBuilder ub = new UrlBuilder(EhUrl.getHost());
|
||||
if (mCategory != EhUtils.NONE) {
|
||||
ub.addQuery("f_doujinshi", ((mCategory & EhConfig.DOUJINSHI) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_manga", ((mCategory & EhConfig.MANGA) == 0) ? "0" : "1");
|
||||
@@ -367,7 +439,7 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
return ub.build();
|
||||
}
|
||||
case MODE_UPLOADER: {
|
||||
StringBuilder sb = new StringBuilder(EhUrl.HOST_EX);
|
||||
StringBuilder sb = new StringBuilder(EhUrl.getHost());
|
||||
sb.append("uploader/");
|
||||
try {
|
||||
sb.append(URLEncoder.encode(mKeyword, "UTF-8"));
|
||||
@@ -380,7 +452,7 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
return sb.toString();
|
||||
}
|
||||
case MODE_TAG: {
|
||||
StringBuilder sb = new StringBuilder(EhUrl.HOST_EX);
|
||||
StringBuilder sb = new StringBuilder(EhUrl.getHost());
|
||||
sb.append("tag/");
|
||||
try {
|
||||
sb.append(URLEncoder.encode(mKeyword, "UTF-8"));
|
||||
@@ -392,6 +464,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
case MODE_IMAGE_SEARCH:
|
||||
return EhUrl.getImageSearchUrl();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,22 +482,30 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
|
||||
dest.writeString(this.mKeyword);
|
||||
dest.writeInt(this.mAdvanceSearch);
|
||||
dest.writeInt(this.mMinRating);
|
||||
dest.writeString(this.mImagePath);
|
||||
dest.writeByte(mUseSimilarityScan ? (byte) 1 : (byte) 0);
|
||||
dest.writeByte(mOnlySearchCovers ? (byte) 1 : (byte) 0);
|
||||
dest.writeByte(mShowExpunged ? (byte) 1 : (byte) 0);
|
||||
}
|
||||
|
||||
public ListUrlBuilder() {}
|
||||
public ListUrlBuilder() {
|
||||
}
|
||||
|
||||
@SuppressWarnings("WrongConstant")
|
||||
protected ListUrlBuilder(Parcel in) {
|
||||
mMode = in.readInt();
|
||||
mPageIndex = in.readInt();
|
||||
mCategory = in.readInt();
|
||||
mKeyword = in.readString();
|
||||
mAdvanceSearch = in.readInt();
|
||||
mMinRating = in.readInt();
|
||||
this.mMode = in.readInt();
|
||||
this.mPageIndex = in.readInt();
|
||||
this.mCategory = in.readInt();
|
||||
this.mKeyword = in.readString();
|
||||
this.mAdvanceSearch = in.readInt();
|
||||
this.mMinRating = in.readInt();
|
||||
this.mImagePath = in.readString();
|
||||
this.mUseSimilarityScan = in.readByte() != 0;
|
||||
this.mOnlySearchCovers = in.readByte() != 0;
|
||||
this.mShowExpunged = in.readByte() != 0;
|
||||
}
|
||||
|
||||
public static final Parcelable.Creator<ListUrlBuilder> CREATOR = new Parcelable.Creator<ListUrlBuilder>() {
|
||||
|
||||
public static final Creator<ListUrlBuilder> CREATOR = new Creator<ListUrlBuilder>() {
|
||||
@Override
|
||||
public ListUrlBuilder createFromParcel(Parcel source) {
|
||||
return new ListUrlBuilder(source);
|
||||
|
||||
@@ -16,40 +16,121 @@
|
||||
|
||||
package com.hippo.ehviewer.client.data;
|
||||
|
||||
import android.os.Parcel;
|
||||
|
||||
import com.hippo.widget.LoadImageView;
|
||||
import com.hippo.yorozuya.IntList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class NormalPreviewSet {
|
||||
public class NormalPreviewSet extends PreviewSet {
|
||||
|
||||
private IntList mIndexList = new IntList();
|
||||
private IntList mPositionList = new IntList();
|
||||
private ArrayList<String> mImageKeyList = new ArrayList<>();
|
||||
private ArrayList<String> mImageUrlList = new ArrayList<>();
|
||||
private IntList mXOffsetList = new IntList();
|
||||
private IntList mYOffsetList = new IntList();
|
||||
private IntList mWidthList = new IntList();
|
||||
private IntList mHeightList = new IntList();
|
||||
private IntList mOffsetXList = new IntList();
|
||||
private IntList mOffsetYList = new IntList();
|
||||
private IntList mClipWidthList = new IntList();
|
||||
private IntList mClipHeightList = new IntList();
|
||||
private ArrayList<String> mPageUrlList = new ArrayList<>();
|
||||
|
||||
public void addItem(int index, String imageUrl, int xOffset, int yOffset, int width,
|
||||
private String getImageKey(String imageUrl) {
|
||||
int index = imageUrl.indexOf('/');
|
||||
if (index >= 0) {
|
||||
return imageUrl.substring(index + 1);
|
||||
} else {
|
||||
return imageUrl;
|
||||
}
|
||||
}
|
||||
|
||||
public void addItem(int position, String imageUrl, int xOffset, int yOffset, int width,
|
||||
int height, String pageUrl) {
|
||||
mIndexList.add(index);
|
||||
mPositionList.add(position);
|
||||
mImageKeyList.add(getImageKey(imageUrl));
|
||||
mImageUrlList.add(imageUrl);
|
||||
mXOffsetList.add(xOffset);
|
||||
mYOffsetList.add(yOffset);
|
||||
mWidthList.add(width);
|
||||
mHeightList.add(height);
|
||||
mOffsetXList.add(xOffset);
|
||||
mOffsetYList.add(yOffset);
|
||||
mClipWidthList.add(width);
|
||||
mClipHeightList.add(height);
|
||||
mPageUrlList.add(pageUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return mIndexList.size();
|
||||
return mPositionList.size();
|
||||
}
|
||||
|
||||
public int getIndexAt(int index) {
|
||||
return mIndexList.get(index);
|
||||
@Override
|
||||
public int getPosition(int index) {
|
||||
return mPositionList.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPageUrlAt(int index) {
|
||||
return mPageUrlList.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryPreview getGalleryPreview(long gid, int index) {
|
||||
GalleryPreview galleryPreview = new GalleryPreview();
|
||||
galleryPreview.position = mPositionList.get(index);
|
||||
galleryPreview.imageKey = mImageKeyList.get(index);
|
||||
galleryPreview.imageUrl = mImageUrlList.get(index);
|
||||
galleryPreview.pageUrl = mPageUrlList.get(index);
|
||||
galleryPreview.offsetX = mOffsetXList.get(index);
|
||||
galleryPreview.offsetY = mOffsetYList.get(index);
|
||||
galleryPreview.clipWidth = mClipWidthList.get(index);
|
||||
galleryPreview.clipHeight = mClipHeightList.get(index);
|
||||
return galleryPreview;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(LoadImageView view, long gid, int index) {
|
||||
view.setClip(mOffsetXList.get(index), mOffsetYList.get(index),
|
||||
mClipWidthList.get(index), mClipHeightList.get(index));
|
||||
view.load(mImageKeyList.get(index), mImageUrlList.get(index));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeParcelable(this.mPositionList, flags);
|
||||
dest.writeStringList(this.mImageKeyList);
|
||||
dest.writeStringList(this.mImageUrlList);
|
||||
dest.writeParcelable(this.mOffsetXList, flags);
|
||||
dest.writeParcelable(this.mOffsetYList, flags);
|
||||
dest.writeParcelable(this.mClipWidthList, flags);
|
||||
dest.writeParcelable(this.mClipHeightList, flags);
|
||||
dest.writeStringList(this.mPageUrlList);
|
||||
}
|
||||
|
||||
public NormalPreviewSet() {
|
||||
}
|
||||
|
||||
protected NormalPreviewSet(Parcel in) {
|
||||
this.mPositionList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mImageKeyList = in.createStringArrayList();
|
||||
this.mImageUrlList = in.createStringArrayList();
|
||||
this.mOffsetXList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mOffsetYList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mClipWidthList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mClipHeightList = in.readParcelable(IntList.class.getClassLoader());
|
||||
this.mPageUrlList = in.createStringArrayList();
|
||||
}
|
||||
|
||||
public static final Creator<NormalPreviewSet> CREATOR = new Creator<NormalPreviewSet>() {
|
||||
@Override
|
||||
public NormalPreviewSet createFromParcel(Parcel source) {
|
||||
return new NormalPreviewSet(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NormalPreviewSet[] newArray(int size) {
|
||||
return new NormalPreviewSet[size];
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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.client.data;
|
||||
|
||||
import android.os.Parcelable;
|
||||
|
||||
import com.hippo.widget.LoadImageView;
|
||||
|
||||
public abstract class PreviewSet implements Parcelable {
|
||||
|
||||
public abstract int size();
|
||||
|
||||
public abstract int getPosition(int index);
|
||||
|
||||
public abstract String getPageUrlAt(int index);
|
||||
|
||||
public abstract GalleryPreview getGalleryPreview(long gid, int index);
|
||||
|
||||
public abstract void load(LoadImageView view, long gid, int index);
|
||||
}
|
||||
@@ -16,8 +16,10 @@
|
||||
|
||||
package com.hippo.ehviewer.client.parser;
|
||||
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
import com.hippo.ehviewer.GetText;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.exception.EhException;
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
import com.hippo.util.JsoupUtils;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
@@ -28,32 +30,27 @@ import org.jsoup.nodes.Element;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class FavoritesParser {
|
||||
|
||||
private static final Pattern LIMIT_PATTERN = Pattern.compile("Currently Used Favorite Slots: ([\\d,]+) / ([\\d,]+)");
|
||||
|
||||
public static class Result {
|
||||
public String[] catArray; // Size 10
|
||||
public int[] countArray; // Size 10
|
||||
public int current; // -1 for error
|
||||
public int limit; // -1 for error
|
||||
public int pages;
|
||||
public List<GalleryInfo> galleryInfoList;
|
||||
}
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
public static Result parse(String body) throws Exception {
|
||||
if (body.contains("This page requires you to log on.</p>")) {
|
||||
throw new EhException(GetText.getString(R.string.need_sign_in));
|
||||
}
|
||||
String[] catArray = new String[10];
|
||||
int[] countArray = new int[10];
|
||||
int current;
|
||||
int limit;
|
||||
|
||||
try {
|
||||
Document d = Jsoup.parse(body, EhUrl.HOST_EX);
|
||||
Document d = Jsoup.parse(body);
|
||||
Element ido = JsoupUtils.getElementByClass(d, "ido");
|
||||
//noinspection ConstantConditions
|
||||
Elements fps = ido.getElementsByClass("fp");
|
||||
// Last one is "fp fps"
|
||||
AssertUtils.assertEqualsEx(11, fps.size());
|
||||
@@ -63,15 +60,6 @@ public class FavoritesParser {
|
||||
countArray[i] = ParserUtils.parseInt(fp.child(0).text());
|
||||
catArray[i] = ParserUtils.trim(fp.child(2).text());
|
||||
}
|
||||
|
||||
Matcher m = LIMIT_PATTERN.matcher(body);
|
||||
if (m.find()) {
|
||||
current = ParserUtils.parseInt(m.group(1));
|
||||
limit = ParserUtils.parseInt(m.group(2));
|
||||
} else {
|
||||
current = -1;
|
||||
limit = -1;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ParseException("Parse favorites error", body);
|
||||
@@ -82,10 +70,8 @@ public class FavoritesParser {
|
||||
Result re = new Result();
|
||||
re.catArray = catArray;
|
||||
re.countArray = countArray;
|
||||
re.current = current;
|
||||
re.limit = limit;
|
||||
re.pages = result.pages;
|
||||
re.galleryInfoList = result.galleryInfos;
|
||||
re.galleryInfoList = result.galleryInfoList;
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -16,20 +16,33 @@
|
||||
|
||||
package com.hippo.ehviewer.client.parser;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.GalleryComment;
|
||||
import com.hippo.ehviewer.client.data.GalleryDetail;
|
||||
import com.hippo.ehviewer.client.data.GalleryTagGroup;
|
||||
import com.hippo.ehviewer.client.data.LargePreviewSet;
|
||||
import com.hippo.ehviewer.client.data.NormalPreviewSet;
|
||||
import com.hippo.ehviewer.client.data.PreviewSet;
|
||||
import com.hippo.ehviewer.client.exception.EhException;
|
||||
import com.hippo.ehviewer.client.exception.OffensiveException;
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
import com.hippo.ehviewer.client.exception.PiningException;
|
||||
import com.hippo.util.JsoupUtils;
|
||||
import com.hippo.yorozuya.NumberUtils;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@@ -40,52 +53,22 @@ import java.util.regex.Pattern;
|
||||
|
||||
public class GalleryDetailParser {
|
||||
|
||||
private static final Pattern PATTERN_ERROR = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
|
||||
private static final Pattern PATTERN_DETAIL = Pattern.compile("var gid = (\\d+);.+?var token = \"([a-f0-9]+)\";.+?var apiuid = ([\\-\\d]+);.+?var apikey = \"([a-f0-9]+)\";", Pattern.DOTALL);
|
||||
private static final Pattern PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>");
|
||||
private static final Pattern PATTERN_TAG_GROUP = Pattern.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
|
||||
private static final Pattern PATTERN_TAG = Pattern.compile("<div[^<>]+><a[^<>]+>([\\w\\s]+)</a></div>");
|
||||
private static final Pattern PATTERN_COMMENT = Pattern.compile("<div class=\"c3\">Posted on ([^<>]+) by: <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
|
||||
private static final Pattern PATTERN_PAGES = Pattern.compile("<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d,]+) pages</td></tr>");
|
||||
private static final Pattern PATTERN_PREVIEW_PAGES = Pattern.compile("<td[^>]+><a[^>]+>([\\d,]+)</a></td><td[^>]+>(?:<a[^>]+>)?>(?:</a>)?</td>");
|
||||
private static final Pattern PATTERN_NORMAL_PREVIEW = Pattern.compile("<div class=\"gdtm\"[^<>]*><div[^<>]*width:(\\d+)[^<>]*height:(\\d+)[^<>]*\\((.+?)\\)[^<>]*-(\\d+)px[^<>]*><a[^<>]*href=\"(.+?)\"[^<>]*><img alt=\"([\\d,]+)\"");
|
||||
private static final Pattern PATTERN_LARGE_PREVIEW = Pattern.compile("<div class=\"gdtl\".+?<a href=\"(.+?)\"><img alt=\"([\\d,]+)\".+?src=\"(.+?)\"");
|
||||
|
||||
private static final GalleryTagGroup[] EMPTY_GALLERY_TAG_GROUP_ARRAY = new GalleryTagGroup[0];
|
||||
private static final GalleryComment[] EMPTY_GALLERY_COMMENT_ARRAY = new GalleryComment[0];
|
||||
|
||||
private static final DateFormat WEB_COMMENT_DATE_FORMAT = new SimpleDateFormat("dd MMMMM yyyy, HH:mm z", Locale.US);
|
||||
|
||||
private static final Pattern ERROR_PATTERN = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
|
||||
private static final Pattern DETAIL_PATTERN = Pattern.compile(
|
||||
"var gid = (\\d+)" // 1 gid
|
||||
+ ".+?"
|
||||
+ "var token = \"([a-z0-9A]+)\"" // 2 token
|
||||
+ ".+?"
|
||||
+ "<div id=\"gd1\"><img src=\"([^\"]+)\"[^<>]+></div>" // 3 thumb
|
||||
+ "</div>"
|
||||
+ "<div id=\"gd2\">"
|
||||
+ "<h1 id=\"gn\">([^<>]+)</h1>" // 4 title
|
||||
+ "<h1 id=\"gj\">([^<>]*)</h1>" // 5 title_jpn might be empty string
|
||||
+ "</div>"
|
||||
+ ".+?"
|
||||
+ "<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>" // 6 torrentUrl, 7 torrentCount
|
||||
+ ".+?"
|
||||
+ "<div id=\"gdc\"><a[^<>]+><[^<>]*alt=\"([\\w\\-]+)\"[^<>]*></a></div>" // 8 category
|
||||
+ "<div id=\"gdn\"><a[^<>]+>([^<>]+)</a>" // 9 uploader
|
||||
+ ".+?"
|
||||
+ "<tr><td[^<>]*>Posted:</td><td[^<>]*>([\\w\\-\\s:]+)</td></tr>" // 10 posted
|
||||
+ "<tr><td[^<>]*>Parent:</td><td[^<>]*>(?:<a[^<>]*>)?([^<>]+)(?:</a>)?</td></tr>" // 11 parent
|
||||
+ "<tr><td[^<>]*>Visible:</td><td[^<>]*>([^<>]+)</td></tr>" // 12 visible
|
||||
+ "<tr><td[^<>]*>Language:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>[^<>]*</span>)?</td></tr>" // 13 language
|
||||
+ "<tr><td[^<>]*>File Size:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>([^<>]+)</span>)?</td></tr>" // 14 File size, 15 resize
|
||||
+ "<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d,]+) pages</td></tr>" // 16 pageCount
|
||||
+ "<tr><td[^<>]*>Favorited:</td><[^<>]*>([^<>]+)</td></tr>" // 17 Favorite times "([\d,]+) times" or "Once" or "Never"
|
||||
+ ".+?"
|
||||
+ "<td id=\"grt3\"><span id=\"rating_count\">([\\d,]+)</span></td>" // 18 ratedTimes
|
||||
+ "</tr>"
|
||||
+ "<tr><td[^<>]*>([^<>]+)</td>", // 19 rating "Average: x.xx" or "Not Yet Rated"
|
||||
Pattern.DOTALL);
|
||||
|
||||
private static final Pattern IS_FAVORED_PATTERN = Pattern.compile("<a id=\"favoritelink\"[^<>]*>(.+?)</a>"); // isFavored "Favorite Gallery" for favorite
|
||||
|
||||
private static final Pattern TAG_GROUP_PATTERN = Pattern.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
|
||||
private static final Pattern TAG_PATTERN = Pattern.compile("<div[^<>]+><a[^<>]+>([\\w\\s]+)</a></div>");
|
||||
|
||||
|
||||
private static final Pattern COMMENT_PATTERN = Pattern.compile("<div class=\"c3\">Posted on ([^<>]+) by: <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
|
||||
|
||||
public static final Pattern PAGES_PATTERN = Pattern.compile("<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d,]+) pages</td></tr>");
|
||||
public static final Pattern PREVIEW_PAGES_PATTERN = Pattern.compile("<td[^>]+><a[^>]+>([\\d,]+)</a></td><td[^>]+>(?:<a[^>]+>)?>(?:</a>)?</td>");
|
||||
private static final Pattern NORMAL_PREVIEW_PATTERN = Pattern.compile("<div class=\"gdtm\"[^<>]*><div[^<>]*width:(\\d+)[^<>]*height:(\\d+)[^<>]*\\((.+?)\\)[^<>]*-(\\d+)px[^<>]*><a[^<>]*href=\"(.+?)\"[^<>]*><img alt=\"([\\d,]+)\"");
|
||||
private static final Pattern LARGE_PREVIEW_PATTERN = Pattern.compile("<div class=\"gdtl\".+?<a href=\"(.+?)\"><img alt=\"([\\d,]+)\".+?src=\"(.+?)\"");
|
||||
|
||||
static {
|
||||
WEB_COMMENT_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
}
|
||||
@@ -105,83 +88,241 @@ public class GalleryDetailParser {
|
||||
}
|
||||
|
||||
// Error info
|
||||
Matcher m = ERROR_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_ERROR.matcher(body);
|
||||
if (m.find()) {
|
||||
throw new EhException(m.group(1));
|
||||
}
|
||||
|
||||
GalleryDetail galleryDetail = new GalleryDetail();
|
||||
parseDetail(body, galleryDetail);
|
||||
galleryDetail.tags = parseTagGroup(body);
|
||||
galleryDetail.comments = parseComment(body);
|
||||
galleryDetail.previewPages = parsePreviewPages(body);
|
||||
galleryDetail.previewSet = parseLargePreview(body);
|
||||
Document document = Jsoup.parse(body);
|
||||
parseDetail(galleryDetail, document, body);
|
||||
galleryDetail.tags = parseTagGroups(document);
|
||||
galleryDetail.comments = parseComments(document);
|
||||
galleryDetail.previewPages = parsePreviewPages(document, body);
|
||||
galleryDetail.previewSet = parsePreviewSet(document, body);
|
||||
return galleryDetail;
|
||||
}
|
||||
|
||||
public static void parseDetail(String body, GalleryDetail gd) throws EhException {
|
||||
Matcher m = DETAIL_PATTERN.matcher(body);
|
||||
if (!m.find()) {
|
||||
throw new ParseException("Parse gallery detail error", body);
|
||||
}
|
||||
|
||||
gd.gid = ParserUtils.parseLong(m.group(1));
|
||||
gd.token = ParserUtils.trim(m.group(2));
|
||||
gd.thumb = ParserUtils.trim(m.group(3));
|
||||
gd.title = ParserUtils.trim(m.group(4));
|
||||
gd.titleJpn = ParserUtils.trim(m.group(5));
|
||||
gd.torrentUrl = ParserUtils.trim(m.group(6));
|
||||
gd.torrentCount = ParserUtils.parseInt(m.group(7));
|
||||
gd.category = EhUtils.getCategory(ParserUtils.trim(m.group(8)));
|
||||
gd.uploader = ParserUtils.trim(m.group(9));
|
||||
gd.posted = ParserUtils.trim(m.group(10));
|
||||
gd.parent = ParserUtils.trim(m.group(11));
|
||||
gd.visible = ParserUtils.trim(m.group(12));
|
||||
gd.language = ParserUtils.trim(m.group(13));
|
||||
gd.size = ParserUtils.trim(m.group(14));
|
||||
gd.resize = ParserUtils.trim(m.group(15));
|
||||
gd.pages = ParserUtils.parseInt(m.group(16));
|
||||
String favTimeStr = ParserUtils.trim(m.group(17));
|
||||
|
||||
switch (favTimeStr) {
|
||||
case "Never":
|
||||
gd.favoredTimes = 0;
|
||||
break;
|
||||
case "Once":
|
||||
gd.favoredTimes = 1;
|
||||
break;
|
||||
default:
|
||||
int index = favTimeStr.indexOf(' ');
|
||||
if (index == -1) {
|
||||
gd.favoredTimes = 0;
|
||||
} else {
|
||||
gd.favoredTimes = ParserUtils.parseInt(favTimeStr.substring(0, index));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
gd.ratedTimes = ParserUtils.parseInt(m.group(18));
|
||||
|
||||
String ratingStr = ParserUtils.trim(m.group(19));
|
||||
if ("Not Yet Rated".equals(ratingStr)) {
|
||||
gd.rating = Float.NaN;
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
private static void parseDetail(GalleryDetail gd, Document d, String body) throws ParseException {
|
||||
Matcher matcher = PATTERN_DETAIL.matcher(body);
|
||||
if (matcher.find()) {
|
||||
gd.gid = Long.parseLong(matcher.group(1));
|
||||
gd.token = matcher.group(2);
|
||||
gd.apiUid = NumberUtils.parseLongSafely(matcher.group(3), -1L);
|
||||
gd.apiKey = matcher.group(4);
|
||||
} else {
|
||||
int index = ratingStr.indexOf(' ');
|
||||
if (index == -1 || index >= ratingStr.length()) {
|
||||
gd.rating = 0f;
|
||||
} else {
|
||||
gd.rating = NumberUtils.parseFloatSafely(ratingStr.substring(index + 1), 0f);
|
||||
}
|
||||
throw new ParseException("Can't parse gallery detail", body);
|
||||
}
|
||||
|
||||
m = IS_FAVORED_PATTERN.matcher(body);
|
||||
gd.isFavored = m.find() && "Favorite Gallery".equals(ParserUtils.trim(m.group(1)));
|
||||
matcher = PATTERN_TORRENT.matcher(body);
|
||||
if (matcher.find()) {
|
||||
gd.torrentUrl = StringUtils.unescapeXml(StringUtils.trim(matcher.group(1)));
|
||||
gd.torrentCount = NumberUtils.parseIntSafely(matcher.group(2), 0);
|
||||
} else {
|
||||
gd.torrentCount = 0;
|
||||
gd.torrentUrl = "";
|
||||
}
|
||||
|
||||
try {
|
||||
Element gm = JsoupUtils.getElementByClass(d, "gm");
|
||||
|
||||
// Thumb url
|
||||
Element gd1 = gm.getElementById("gd1");
|
||||
try {
|
||||
gd.thumb = EhUtils.handleThumbUrlResolution(StringUtils.trim(gd1.child(0).attr("src")));
|
||||
} catch (Exception e) {
|
||||
gd.thumb = "";
|
||||
}
|
||||
|
||||
// Title
|
||||
Element gn = gm.getElementById("gn");
|
||||
if (null != gn) {
|
||||
gd.title = StringUtils.trim(gn.text());
|
||||
} else {
|
||||
gd.title = "";
|
||||
}
|
||||
|
||||
// Jpn title
|
||||
Element gj = gm.getElementById("gj");
|
||||
if (null != gj) {
|
||||
gd.titleJpn = StringUtils.trim(gj.text());
|
||||
} else {
|
||||
gd.titleJpn = "";
|
||||
}
|
||||
|
||||
// Category
|
||||
Element gdc = gm.getElementById("gdc");
|
||||
try {
|
||||
gd.category = EhUtils.getCategory(gdc.child(0).child(0).attr("alt"));
|
||||
} catch (Exception e) {
|
||||
gd.category = EhUtils.UNKNOWN;
|
||||
}
|
||||
|
||||
// Uploader
|
||||
Element gdn = gm.getElementById("gdn");
|
||||
if (null != gdn) {
|
||||
gd.uploader = StringUtils.trim(gdn.text());
|
||||
} else {
|
||||
gd.uploader = "";
|
||||
}
|
||||
|
||||
Element gdd = gm.getElementById("gdd");
|
||||
gd.posted = "";
|
||||
gd.parent = "";
|
||||
gd.visible = "";
|
||||
gd.visible = "";
|
||||
gd.size = "";
|
||||
gd.pages = 0;
|
||||
gd.favoriteCount = 0;
|
||||
try {
|
||||
Elements es = gdd.child(0).child(0).children();
|
||||
for (int i = 0, n = es.size(); i < n; i++) {
|
||||
parseDetailInfo(gd, es.get(i), body);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
// Rating count
|
||||
Element rating_count = gm.getElementById("rating_count");
|
||||
if (null != rating_count) {
|
||||
gd.ratingCount = NumberUtils.parseIntSafely(
|
||||
StringUtils.trim(rating_count.text()), 0);
|
||||
} else {
|
||||
gd.ratingCount = 0;
|
||||
}
|
||||
|
||||
// Rating
|
||||
Element rating_label = gm.getElementById("rating_label");
|
||||
if (null != rating_label) {
|
||||
String ratingStr = StringUtils.trim(rating_label.text());
|
||||
if ("Not Yet Rated".equals(ratingStr)) {
|
||||
gd.rating = -1.0f;
|
||||
} else {
|
||||
int index = ratingStr.indexOf(' ');
|
||||
if (index == -1 || index >= ratingStr.length()) {
|
||||
gd.rating = 0f;
|
||||
} else {
|
||||
gd.rating = NumberUtils.parseFloatSafely(ratingStr.substring(index + 1), 0f);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
gd.rating = -1.0f;
|
||||
}
|
||||
|
||||
// isFavorited
|
||||
Element gdf = gm.getElementById("gdf");
|
||||
gd.isFavorited = null != gdf && !StringUtils.trim(gdf.text()).equals("Add to Favorites");
|
||||
} catch (Exception e) {
|
||||
throw new ParseException("Can't parse gallery detail", body);
|
||||
}
|
||||
}
|
||||
|
||||
public static GalleryTagGroup[] parseTagGroup(String body) throws EhException {
|
||||
private static void parseDetailInfo(GalleryDetail gd, Element e, String body) {
|
||||
Elements es = e.children();
|
||||
if (es.size() < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
String key = StringUtils.trim(es.get(0).text());
|
||||
String value = StringUtils.trim(es.get(1).ownText());
|
||||
if (key.startsWith("Posted")) {
|
||||
gd.posted = value;
|
||||
} else if (key.startsWith("Parent")) {
|
||||
gd.parent = value;
|
||||
} else if (key.startsWith("Visible")) {
|
||||
gd.visible = value;
|
||||
} else if (key.startsWith("Language")) {
|
||||
gd.language = value;
|
||||
} else if (key.startsWith("File Size")) {
|
||||
gd.size = value;
|
||||
} else if (key.startsWith("Length")) {
|
||||
int index = value.indexOf(' ');
|
||||
if (index >= 0) {
|
||||
gd.pages = NumberUtils.parseIntSafely(value.substring(0, index), 1);
|
||||
} else {
|
||||
gd.pages = 1;
|
||||
}
|
||||
} else if (key.startsWith("Favorited")) {
|
||||
switch (value) {
|
||||
case "Never":
|
||||
gd.favoriteCount = 0;
|
||||
break;
|
||||
case "Once":
|
||||
gd.favoriteCount = 1;
|
||||
break;
|
||||
default:
|
||||
int index = value.indexOf(' ');
|
||||
if (index == -1) {
|
||||
gd.favoriteCount = 0;
|
||||
} else {
|
||||
gd.favoriteCount = NumberUtils.parseIntSafely(value.substring(0, index), 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static GalleryTagGroup parseTagGroup(Element element) {
|
||||
try {
|
||||
GalleryTagGroup group = new GalleryTagGroup();
|
||||
|
||||
String nameSpace = element.child(0).text();
|
||||
// Remove last ':'
|
||||
nameSpace = nameSpace.substring(0, nameSpace.length() - 1);
|
||||
group.groupName = nameSpace;
|
||||
|
||||
Elements tags = element.child(1).children();
|
||||
for (int i = 0, n = tags.size(); i < n; i++) {
|
||||
String tag = tags.get(i).text();
|
||||
// Sometimes parody tag is followed with '|' and english translate, just remove them
|
||||
int index = tag.indexOf('|');
|
||||
if (index >= 0) {
|
||||
tag = tag.substring(0, index);
|
||||
}
|
||||
group.addTag(tag);
|
||||
}
|
||||
|
||||
return group.size() > 0 ? group : null;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse tag groups with html parser
|
||||
*/
|
||||
@NonNull
|
||||
public static GalleryTagGroup[] parseTagGroups(Document document) {
|
||||
try {
|
||||
Element taglist = document.getElementById("taglist");
|
||||
Elements tagGroups = taglist.child(0).child(0).children();
|
||||
|
||||
List<GalleryTagGroup> list = new ArrayList<>(tagGroups.size());
|
||||
for (int i = 0, n = tagGroups.size(); i < n; i++) {
|
||||
GalleryTagGroup group = parseTagGroup(tagGroups.get(i));
|
||||
if (null != group) {
|
||||
list.add(group);
|
||||
}
|
||||
}
|
||||
return list.toArray(new GalleryTagGroup[list.size()]);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return EMPTY_GALLERY_TAG_GROUP_ARRAY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse tag groups with regular expressions
|
||||
*/
|
||||
@NonNull
|
||||
private static GalleryTagGroup[] parseTagGroups(String body) throws EhException {
|
||||
List<GalleryTagGroup> list = new LinkedList<>();
|
||||
|
||||
Matcher m = TAG_GROUP_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_TAG_GROUP.matcher(body);
|
||||
while (m.find()) {
|
||||
GalleryTagGroup tagGroup = new GalleryTagGroup();
|
||||
tagGroup.groupName = ParserUtils.trim(m.group(1));
|
||||
@@ -193,16 +334,90 @@ public class GalleryDetailParser {
|
||||
}
|
||||
|
||||
private static void parseGroup(GalleryTagGroup tagGroup, String body) {
|
||||
Matcher m = TAG_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_TAG.matcher(body);
|
||||
while (m.find()) {
|
||||
tagGroup.addTag(ParserUtils.trim(m.group(1)));
|
||||
}
|
||||
}
|
||||
|
||||
public static GalleryComment[] parseComment(String body) {
|
||||
@Nullable
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
public static GalleryComment parseComment(Element element) {
|
||||
try {
|
||||
GalleryComment comment = new GalleryComment();
|
||||
// Id
|
||||
Element a = element.previousElementSibling();
|
||||
String name = a.attr("name");
|
||||
comment.id = Integer.parseInt(StringUtils.trim(name).substring(1));
|
||||
// Vote up and vote down
|
||||
Element c4 = JsoupUtils.getElementByClass(element, "c4");
|
||||
if (null != c4) {
|
||||
Elements es = c4.children();
|
||||
if (2 == es.size()) {
|
||||
comment.voteUp = !TextUtils.isEmpty(StringUtils.trim(es.get(0).attr("style")));
|
||||
comment.voteDown = !TextUtils.isEmpty(StringUtils.trim(es.get(1).attr("style")));
|
||||
}
|
||||
}
|
||||
// Vote state
|
||||
Element c7 = JsoupUtils.getElementByClass(element, "c7");
|
||||
if (null != c7) {
|
||||
comment.voteState = StringUtils.trim(c7.text());
|
||||
}
|
||||
// Score
|
||||
Element c5 = JsoupUtils.getElementByClass(element, "c5");
|
||||
if (null != c5) {
|
||||
Elements es = c5.children();
|
||||
if (!es.isEmpty()) {
|
||||
comment.score = NumberUtils.parseIntSafely(StringUtils.trim(es.get(0).text()), 0);
|
||||
}
|
||||
}
|
||||
// time
|
||||
Element c3 = JsoupUtils.getElementByClass(element, "c3");
|
||||
String temp = c3.ownText();
|
||||
temp = temp.substring("Posted on ".length(), temp.length() - " by: ".length());
|
||||
comment.time = WEB_COMMENT_DATE_FORMAT.parse(temp).getTime();
|
||||
// user
|
||||
comment.user = c3.child(0).text();
|
||||
// comment
|
||||
comment.comment = JsoupUtils.getElementByClass(element, "c6").html();
|
||||
return comment;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse comments with html parser
|
||||
*/
|
||||
@NonNull
|
||||
public static GalleryComment[] parseComments(Document document) {
|
||||
try {
|
||||
Element cdiv = document.getElementById("cdiv");
|
||||
Elements c1s = cdiv.getElementsByClass("c1");
|
||||
|
||||
List<GalleryComment> list = new ArrayList<>(c1s.size());
|
||||
for (int i = 0, n = c1s.size(); i < n; i++) {
|
||||
GalleryComment comment = parseComment(c1s.get(i));
|
||||
if (null != comment) {
|
||||
list.add(comment);
|
||||
}
|
||||
}
|
||||
return list.toArray(new GalleryComment[list.size()]);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return EMPTY_GALLERY_COMMENT_ARRAY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse comments with regular expressions
|
||||
*/
|
||||
@NonNull
|
||||
public static GalleryComment[] parseComments(String body) {
|
||||
List<GalleryComment> list = new LinkedList<>();
|
||||
|
||||
Matcher m = COMMENT_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_COMMENT.matcher(body);
|
||||
while (m.find()) {
|
||||
String webDateString = ParserUtils.trim(m.group(1));
|
||||
Date date;
|
||||
@@ -221,8 +436,24 @@ public class GalleryDetailParser {
|
||||
return list.toArray(new GalleryComment[list.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse preview pages with html parser
|
||||
*/
|
||||
public static int parsePreviewPages(Document document, String body) throws ParseException {
|
||||
try {
|
||||
Elements elements = document.getElementsByClass("ptt").first().child(0).child(0).children();
|
||||
return Integer.parseInt(elements.get(elements.size() - 2).text());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ParseException("Can't parse preview pages", body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse preview pages with regular expressions
|
||||
*/
|
||||
public static int parsePreviewPages(String body) throws ParseException {
|
||||
Matcher m = PREVIEW_PAGES_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_PREVIEW_PAGES.matcher(body);
|
||||
int previewPages = -1;
|
||||
if (m.find()) {
|
||||
previewPages = ParserUtils.parseInt(m.group(1));
|
||||
@@ -235,8 +466,11 @@ public class GalleryDetailParser {
|
||||
return previewPages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse pages with regular expressions
|
||||
*/
|
||||
public static int parsePages(String body) throws ParseException {
|
||||
Matcher m = PAGES_PATTERN.matcher(body);
|
||||
Matcher m = PATTERN_PAGES.matcher(body);
|
||||
if (m.find()) {
|
||||
return ParserUtils.parseInt(m.group(1));
|
||||
} else {
|
||||
@@ -244,8 +478,54 @@ public class GalleryDetailParser {
|
||||
}
|
||||
}
|
||||
|
||||
public static LargePreviewSet parseLargePreview(String body) throws ParseException {
|
||||
Matcher m = LARGE_PREVIEW_PATTERN.matcher(body);
|
||||
public static PreviewSet parsePreviewSet(Document d, String body) throws ParseException {
|
||||
try {
|
||||
return parseLargePreviewSet(d, body);
|
||||
} catch (ParseException e) {
|
||||
return parseNormalPreviewSet(body);
|
||||
}
|
||||
}
|
||||
|
||||
public static PreviewSet parsePreviewSet(String body) throws ParseException {
|
||||
try {
|
||||
return parseLargePreviewSet(body);
|
||||
} catch (ParseException e) {
|
||||
return parseNormalPreviewSet(body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse large previews with regular expressions
|
||||
*/
|
||||
private static LargePreviewSet parseLargePreviewSet(Document d, String body) throws ParseException {
|
||||
try {
|
||||
LargePreviewSet largePreviewSet = new LargePreviewSet();
|
||||
Element gdt = d.getElementById("gdt");
|
||||
Elements gdtls = gdt.getElementsByClass("gdtl");
|
||||
int n = gdtls.size();
|
||||
if (n <= 0) {
|
||||
throw new ParseException("Can't parse large preview", body);
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
Element element = gdtls.get(i).child(0);
|
||||
String pageUrl = element.attr("href");
|
||||
element = element.child(0);
|
||||
String imageUrl = element.attr("src");
|
||||
int index = Integer.parseInt(element.attr("alt")) - 1;
|
||||
largePreviewSet.addItem(index, imageUrl, pageUrl);
|
||||
}
|
||||
return largePreviewSet;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ParseException("Can't parse large preview", body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse large previews with regular expressions
|
||||
*/
|
||||
private static LargePreviewSet parseLargePreviewSet(String body) throws ParseException {
|
||||
Matcher m = PATTERN_LARGE_PREVIEW.matcher(body);
|
||||
LargePreviewSet largePreviewSet = new LargePreviewSet();
|
||||
|
||||
while (m.find()) {
|
||||
@@ -260,8 +540,11 @@ public class GalleryDetailParser {
|
||||
return largePreviewSet;
|
||||
}
|
||||
|
||||
public static NormalPreviewSet parseNormalPreviewSet(String body) throws ParseException {
|
||||
Matcher m = NORMAL_PREVIEW_PATTERN.matcher(body);
|
||||
/**
|
||||
* Parse normal previews with regular expressions
|
||||
*/
|
||||
private static NormalPreviewSet parseNormalPreviewSet(String body) throws ParseException {
|
||||
Matcher m = PATTERN_NORMAL_PREVIEW.matcher(body);
|
||||
NormalPreviewSet normalPreviewSet = new NormalPreviewSet();
|
||||
while (m.find()) {
|
||||
normalPreviewSet.addItem(ParserUtils.parseInt(m.group(6)) - 1,
|
||||
@@ -271,10 +554,9 @@ public class GalleryDetailParser {
|
||||
}
|
||||
|
||||
if (normalPreviewSet.size() == 0) {
|
||||
throw new ParseException("Can't parse large preview", body);
|
||||
throw new ParseException("Can't parse normal preview", body);
|
||||
}
|
||||
|
||||
return normalPreviewSet;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.hippo.ehviewer.client.parser;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
@@ -30,6 +32,7 @@ public final class GalleryDetailUrlParser {
|
||||
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
|
||||
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
|
||||
|
||||
@Nullable
|
||||
public static Result parse(String url) {
|
||||
if (url == null) {
|
||||
return null;
|
||||
|
||||
@@ -17,102 +17,50 @@
|
||||
package com.hippo.ehviewer.client.parser;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.exception.NotFoundException;
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
import com.hippo.util.JsoupUtils;
|
||||
import com.hippo.yorozuya.NumberUtils;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class GalleryListParser {
|
||||
|
||||
static final Pattern PAGES_PATTERN = Pattern.compile("<a[^<>]+>([\\d]+)</a></td><td[^<>]+>(?:<a[^<>]+>)?&");
|
||||
static final Pattern PATTERN = Pattern.compile(
|
||||
"<td class=\"itdc\">(?:<a.+?>)?<img.+?alt=\"(.+?)\".+?/>(?:</a>)?</td>" // category
|
||||
+ "<td.+?>(.+?)</td>" // posted
|
||||
+ "<td.+?><div.+?><div.+?height:(\\d+)px; width:(\\d+)px\">"
|
||||
+ "(?:<img.+?src=\"(.+?)\".+?alt=\"(.+?)\" style.+?/>"
|
||||
+ "|init~([^<>\"~]+~[^<>\"~]+)~([^<>]+))" // thumb and title
|
||||
+ "</div>"
|
||||
+ ".+?"
|
||||
+ "<div class=\"it5\"><a href=\"([^<>\"]+)\"[^<>]+>(.+?)</a></div>" // url and title
|
||||
+ ".+?"
|
||||
+ "<div class=\"ir it4r\" style=\"([^<>\"]+)\">" // rating
|
||||
+ ".+?"
|
||||
+ "<td class=\"itu\"><div><a.+?>(.+?)</a>"); // uploader
|
||||
static final Pattern RATING_PATTERN = Pattern.compile("\\d+px");
|
||||
private static final String TAG = GalleryListParser.class.getSimpleName();
|
||||
|
||||
private static final Pattern PATTERN_RATING = Pattern.compile("\\d+px");
|
||||
private static final Pattern PATTERN_THUMB_SIZE = Pattern.compile("height:(\\d+)px; width:(\\d+)px");
|
||||
|
||||
public static class Result {
|
||||
public int pages;
|
||||
public List<GalleryInfo> galleryInfos;
|
||||
public List<GalleryInfo> galleryInfoList;
|
||||
}
|
||||
|
||||
public static Result parse(@NonNull String body) throws Exception {
|
||||
Result result = new Result();
|
||||
Matcher m;
|
||||
|
||||
// pages
|
||||
m = PAGES_PATTERN.matcher(body);
|
||||
if (m.find()) {
|
||||
result.pages = ParserUtils.parseInt(m.group(1));
|
||||
} else if (body.contains("No hits found</p>")) {
|
||||
throw new NotFoundException();
|
||||
} else {
|
||||
// Can not get page number
|
||||
throw new ParseException("Can't parse gallery list", body);
|
||||
private static int parsePages(Document d, String body) throws ParseException {
|
||||
try {
|
||||
Elements es = d.getElementsByClass("ptt").first().child(0).child(0).children();
|
||||
return Integer.parseInt(es.get(es.size() - 2).text().trim());
|
||||
} catch (Exception e) {
|
||||
throw new ParseException("Can't parse gallery list pages", body);
|
||||
}
|
||||
|
||||
if (result.pages > 0) {
|
||||
List<GalleryInfo> list = new ArrayList<>(25);
|
||||
result.galleryInfos = list;
|
||||
|
||||
m = PATTERN.matcher(body);
|
||||
while (m.find()) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
|
||||
gi.category = EhUtils.getCategory(ParserUtils.trim(m.group(1)));
|
||||
gi.posted = ParserUtils.trim(m.group(2));
|
||||
//gi.thumbHeight = ParserUtils.parseInt(m.group(3));
|
||||
//gi.thumbWidth = ParserUtils.parseInt(m.group(4));
|
||||
|
||||
if (m.group(5) == null) {
|
||||
gi.thumb = ParserUtils.trim("http://" + m.group(7).replace('~', '/'));
|
||||
gi.title = ParserUtils.trim(m.group(8));
|
||||
} else {
|
||||
gi.thumb = ParserUtils.trim(m.group(5));
|
||||
gi.title = ParserUtils.trim(m.group(6));
|
||||
}
|
||||
|
||||
Matcher matcher = GalleryDetailUrlParser.URL_PATTERN.matcher(m.group(9));
|
||||
if (matcher.find()) {
|
||||
gi.gid = ParserUtils.parseLong(matcher.group(1));
|
||||
gi.token = ParserUtils.trim(matcher.group(2));
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
gi.rating = NumberUtils.parseFloatSafely(getRating(m.group(11)), Float.NaN);
|
||||
gi.uploader = ParserUtils.trim(m.group(12));
|
||||
gi.generateSLang();
|
||||
|
||||
list.add(gi);
|
||||
}
|
||||
|
||||
if (list.size() == 0) {
|
||||
throw new ParseException("Can't parse gallery list", body);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String getRating(String rawRate) {
|
||||
Matcher m = RATING_PATTERN.matcher(rawRate);
|
||||
private static String parseRating(String ratingStyle) {
|
||||
Matcher m = PATTERN_RATING.matcher(ratingStyle);
|
||||
int num1;
|
||||
int num2;
|
||||
int rate = 5;
|
||||
@@ -136,4 +84,135 @@ public class GalleryListParser {
|
||||
re = Integer.toString(rate);
|
||||
return re;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static GalleryInfo parseGalleryInfo(Element e) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
// Get category
|
||||
Element ic = JsoupUtils.getElementByClass(e, "ic");
|
||||
if (null != ic) {
|
||||
gi.category = EhUtils.getCategory(ic.attr("alt").trim());
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info category");
|
||||
gi.category = EhUtils.UNKNOWN;
|
||||
}
|
||||
// Posted
|
||||
Element itd = JsoupUtils.getElementByClass(e, "itd");
|
||||
if (null != itd) {
|
||||
gi.posted = itd.text().trim();
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info posted");
|
||||
gi.posted = "";
|
||||
}
|
||||
// Thumb
|
||||
Element it2 = JsoupUtils.getElementByClass(e, "it2");
|
||||
if (null != it2) {
|
||||
// Thumb size
|
||||
Matcher m = PATTERN_THUMB_SIZE.matcher(it2.attr("style"));
|
||||
if (m.find()) {
|
||||
gi.thumbWidth = NumberUtils.parseIntSafely(m.group(2), 0);
|
||||
gi.thumbHeight = NumberUtils.parseIntSafely(m.group(1), 0);
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info thumb size");
|
||||
gi.thumbWidth = 0;
|
||||
gi.thumbHeight = 0;
|
||||
}
|
||||
|
||||
// Thumb url
|
||||
Elements es = it2.children();
|
||||
if (null != es && es.size() >= 1) {
|
||||
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 = EhUtils.handleThumbUrlResolution(
|
||||
"http://" +StringUtils.replace(html.substring(index1 + 1, index2), "~", "/"));
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info thumb url");
|
||||
gi.thumb = "";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info thumb");
|
||||
gi.thumbWidth = 0;
|
||||
gi.thumbHeight = 0;
|
||||
gi.thumb = "";
|
||||
}
|
||||
// Title (required)
|
||||
Element it5 = JsoupUtils.getElementByClass(e, "it5");
|
||||
if (null == it5) {
|
||||
Log.e(TAG, "Can't parse gallery info title");
|
||||
return null;
|
||||
}
|
||||
Elements es = it5.children();
|
||||
if (null == es || es.size() <= 0) {
|
||||
Log.e(TAG, "Can't parse gallery info title");
|
||||
return null;
|
||||
}
|
||||
Element a = es.get(0);
|
||||
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
|
||||
if (null == result) {
|
||||
Log.e(TAG, "Can't parse gallery info title");
|
||||
return null;
|
||||
}
|
||||
gi.gid = result.gid;
|
||||
gi.token = result.token;
|
||||
gi.title = a.text().trim();
|
||||
// Rating
|
||||
Element it4r = JsoupUtils.getElementByClass(e, "it4r");
|
||||
if (null != it4r) {
|
||||
gi.rating = NumberUtils.parseFloatSafely(parseRating(it4r.attr("style")), -1.0f);
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info rating");
|
||||
gi.rating = -1.0f;
|
||||
}
|
||||
// Uploader
|
||||
Element itu = JsoupUtils.getElementByClass(e, "itu");
|
||||
if (null != itu) {
|
||||
gi.uploader = itu.text().trim();
|
||||
} else {
|
||||
Log.w(TAG, "Can't parse gallery info uploader");
|
||||
gi.uploader = "";
|
||||
}
|
||||
|
||||
gi.generateSLang();
|
||||
|
||||
return gi;
|
||||
}
|
||||
|
||||
public static Result parse(@NonNull String body) throws Exception {
|
||||
Result result = new Result();
|
||||
Document d = Jsoup.parse(body);
|
||||
|
||||
try {
|
||||
result.pages = parsePages(d, body);
|
||||
} catch (ParseException e) {
|
||||
if (body.contains("No hits found</p>")) {
|
||||
result.pages = 0;
|
||||
//noinspection unchecked
|
||||
result.galleryInfoList = Collections.EMPTY_LIST;
|
||||
return result;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Elements es = d.getElementsByClass("itg").first().child(0).children();
|
||||
List<GalleryInfo> list = new ArrayList<>(es.size() - 1);
|
||||
for (int i = 1; i < es.size(); i++) { // First one is table header, skip it
|
||||
GalleryInfo gi = parseGalleryInfo(es.get(i));
|
||||
if (null != gi) {
|
||||
list.add(gi);
|
||||
}
|
||||
}
|
||||
result.galleryInfoList = list;
|
||||
} catch (Exception e) {
|
||||
throw new ParseException("Can't parse gallery list", body);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -19,27 +19,34 @@ package com.hippo.ehviewer.client.parser;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class GalleryPageParser {
|
||||
|
||||
private static Pattern IMAGE_URL_PATTERN = Pattern.compile("<div id=\"i3\"><a[^>]+><img id=\"img\" src=\"([^\"]+)\"");
|
||||
private static Pattern SKIP_HATH_KEY_PATTERN = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
|
||||
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("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
|
||||
|
||||
public static Result parse(String body) throws ParseException {
|
||||
Matcher m;
|
||||
Result result = new Result();
|
||||
m = IMAGE_URL_PATTERN.matcher(body);
|
||||
m = PATTERN_IMAGE_URL.matcher(body);
|
||||
if (m.find()) {
|
||||
result.imageUrl = ParserUtils.trim(m.group(1));
|
||||
result.imageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
|
||||
}
|
||||
m = SKIP_HATH_KEY_PATTERN.matcher(body);
|
||||
m = PATTERN_SKIP_HATH_KEY.matcher(body);
|
||||
if (m.find()) {
|
||||
result.skipHathKey = ParserUtils.trim(m.group(1));
|
||||
result.skipHathKey = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
|
||||
}
|
||||
if (!TextUtils.isEmpty(result.imageUrl) && !TextUtils.isEmpty(result.skipHathKey)) {
|
||||
m = PATTERN_ORIGIN_IMAGE_URL.matcher(body);
|
||||
if (m.find()) {
|
||||
result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
|
||||
}
|
||||
|
||||
if (!TextUtils.isEmpty(result.imageUrl)) {
|
||||
return result;
|
||||
} else {
|
||||
throw new ParseException("Parse image url and skip hath key error", body);
|
||||
@@ -49,5 +56,6 @@ public class GalleryPageParser {
|
||||
public static class Result {
|
||||
public String imageUrl;
|
||||
public String skipHathKey;
|
||||
public String originImageUrl;
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class RateGalleryParser {
|
||||
|
||||
public static class Result {
|
||||
public float rating;
|
||||
public int ratedTimes;
|
||||
public int ratingCount;
|
||||
}
|
||||
|
||||
public static Result parse(String body) throws Exception {
|
||||
@@ -33,7 +33,7 @@ public class RateGalleryParser {
|
||||
JSONObject jsonObject = new JSONObject(body);
|
||||
Result result = new Result();
|
||||
result.rating = (float)jsonObject.getDouble("rating_avg");
|
||||
result.ratedTimes = jsonObject.getInt("rating_cnt");
|
||||
result.ratingCount = jsonObject.getInt("rating_cnt");
|
||||
return result;
|
||||
} catch (JSONException e) {
|
||||
Exception exception = new ParseException("Can't parse rate gallery", body);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* 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.client.parser;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class VoteCommentParser {
|
||||
|
||||
public static class Result {
|
||||
public long id;
|
||||
public int score;
|
||||
public int vote;
|
||||
public int expectVote;
|
||||
}
|
||||
|
||||
// {"comment_id":1253922,"comment_score":-19,"comment_vote":0}
|
||||
public static Result parse(String body, int vote) throws JSONException {
|
||||
Result result = new Result();
|
||||
JSONObject jo = new JSONObject(body);
|
||||
result.id = jo.getLong("comment_id");
|
||||
result.score = jo.getInt("comment_score");
|
||||
result.vote = jo.getInt("comment_vote");
|
||||
result.expectVote = vote;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.client.parser;
|
||||
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
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;
|
||||
@@ -35,7 +35,7 @@ public class WhatsHotParser {
|
||||
public static List<GalleryInfo> parse(String body) throws ParseException {
|
||||
try {
|
||||
List<GalleryInfo> galleryInfoList = new ArrayList<>(15);
|
||||
Document d = Jsoup.parse(body, EhUrl.HOST_G);
|
||||
Document d = Jsoup.parse(body);
|
||||
Element pp = d.getElementById("pp");
|
||||
Elements id1List = pp.getElementsByClass("id1");
|
||||
for (int i = 0, n = id1List.size(); i < n; i++) {
|
||||
@@ -48,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);
|
||||
|
||||
@@ -168,6 +168,11 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
|
||||
return mMap.get(label);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public DownloadInfo getDownloadInfo(long gid) {
|
||||
return mAllInfoMap.get(gid);
|
||||
}
|
||||
|
||||
public int getDownloadState(long gid) {
|
||||
DownloadInfo info = mAllInfoMap.get(gid);
|
||||
if (null != info) {
|
||||
@@ -348,6 +353,61 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
|
||||
}
|
||||
}
|
||||
|
||||
public void addDownload(List<DownloadInfo> downloadInfoList) {
|
||||
for (DownloadInfo info: downloadInfoList) {
|
||||
if (containDownloadInfo(info.gid)) {
|
||||
// Contain
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure download state
|
||||
if (DownloadInfo.STATE_WAIT == info.state ||
|
||||
DownloadInfo.STATE_DOWNLOAD == info.state) {
|
||||
info.state = DownloadInfo.STATE_NONE;
|
||||
}
|
||||
|
||||
// Add to label download list
|
||||
LinkedList<DownloadInfo> list = getInfoListForLabel(info.label);
|
||||
if (null == list) {
|
||||
// Can't find the label in label list
|
||||
list = new LinkedList<>();
|
||||
mMap.put(info.label, list);
|
||||
if (!containLabel(info.label)) {
|
||||
// Add label to DB and list
|
||||
mLabelList.add(EhDB.addDownloadLabel(info.label));
|
||||
}
|
||||
}
|
||||
list.add(info);
|
||||
// Sort
|
||||
Collections.sort(list, DATE_DESC_COMPARATOR);
|
||||
|
||||
// Add to all download list and map
|
||||
mAllInfoList.add(info);
|
||||
mAllInfoMap.put(info.gid, info);
|
||||
|
||||
// Save to
|
||||
EhDB.putDownloadInfo(info);
|
||||
}
|
||||
|
||||
// Sort all download list
|
||||
Collections.sort(mAllInfoList, DATE_DESC_COMPARATOR);
|
||||
|
||||
// Notify
|
||||
for (DownloadInfoListener l: mDownloadInfoListeners) {
|
||||
l.onReload();
|
||||
}
|
||||
}
|
||||
|
||||
public void addDownloadLabel(List<DownloadLabel> downloadLabelList) {
|
||||
for (DownloadLabel label: downloadLabelList) {
|
||||
String labelString = label.getLabel();
|
||||
if (!containLabel(labelString)) {
|
||||
mMap.put(labelString, new LinkedList<DownloadInfo>());
|
||||
mLabelList.add(EhDB.addDownloadLabel(label));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addDownload(GalleryInfo galleryInfo, @Nullable String label) {
|
||||
if (containDownloadInfo(galleryInfo.gid)) {
|
||||
// Contain
|
||||
@@ -615,7 +675,7 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
|
||||
srcList.remove(info);
|
||||
dstList.add(info);
|
||||
info.label = label;
|
||||
Collections.sort(dstList, sDateDescComparator);
|
||||
Collections.sort(dstList, DATE_DESC_COMPARATOR);
|
||||
|
||||
// Save to DB
|
||||
EhDB.putDownloadInfo(info);
|
||||
@@ -715,7 +775,7 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
|
||||
}
|
||||
|
||||
// Sort
|
||||
Collections.sort(mDefaultInfoList, sDateDescComparator);
|
||||
Collections.sort(mDefaultInfoList, DATE_DESC_COMPARATOR);
|
||||
|
||||
// Notify listener
|
||||
for (DownloadInfoListener l: mDownloadInfoListeners) {
|
||||
@@ -1074,7 +1134,7 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
|
||||
}
|
||||
}
|
||||
|
||||
private static final Comparator<DownloadInfo> sDateDescComparator = new Comparator<DownloadInfo>() {
|
||||
private static final Comparator<DownloadInfo> DATE_DESC_COMPARATOR = new Comparator<DownloadInfo>() {
|
||||
@Override
|
||||
public int compare(DownloadInfo lhs, DownloadInfo rhs) {
|
||||
return lhs.time - rhs.time > 0 ? -1 : 1;
|
||||
|
||||
@@ -48,7 +48,6 @@ import com.hippo.yorozuya.sparse.SparseJLArray;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
// TODO Stop and delete action should not pass through DownloadService
|
||||
public class DownloadService extends Service implements DownloadManager.DownloadListener {
|
||||
|
||||
public static final String ACTION_START = "start";
|
||||
@@ -209,15 +208,6 @@ public class DownloadService extends Service implements DownloadManager.Download
|
||||
stopAllIntent.setAction(ACTION_STOP_ALL);
|
||||
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString(DownloadsScene.KEY_ACTION, DownloadsScene.ACTION_CLEAR_DOWNLOAD_SERVICE);
|
||||
Intent activityIntent = new Intent(this, MainActivity.class);
|
||||
activityIntent.setAction(StageActivity.ACTION_START_SCENE);
|
||||
activityIntent.putExtra(StageActivity.KEY_SCENE_NAME, DownloadsScene.class.getName());
|
||||
activityIntent.putExtra(StageActivity.KEY_SCENE_ARGS, bundle);
|
||||
PendingIntent piActivity = PendingIntent.getActivity(DownloadService.this, 0,
|
||||
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
|
||||
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext())
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setOngoing(true)
|
||||
@@ -225,8 +215,7 @@ public class DownloadService extends Service implements DownloadManager.Download
|
||||
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
|
||||
.setColor(getResources().getColor(R.color.colorPrimary))
|
||||
.addAction(R.drawable.ic_pause_x24, getString(R.string.stat_download_action_stop_all), piStopAll)
|
||||
.setShowWhen(false)
|
||||
.setContentIntent(piActivity);
|
||||
.setShowWhen(false);
|
||||
|
||||
mDownloadingDelay = new NotificationDelay(this, mNotifyManager, mDownloadingBuilder, ID_DOWNLOADING);
|
||||
}
|
||||
@@ -297,10 +286,20 @@ public class DownloadService extends Service implements DownloadManager.Download
|
||||
|
||||
ensureDownloadingBuilder();
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putLong(DownloadsScene.KEY_GID, info.gid);
|
||||
Intent activityIntent = new Intent(this, MainActivity.class);
|
||||
activityIntent.setAction(StageActivity.ACTION_START_SCENE);
|
||||
activityIntent.putExtra(StageActivity.KEY_SCENE_NAME, DownloadsScene.class.getName());
|
||||
activityIntent.putExtra(StageActivity.KEY_SCENE_ARGS, bundle);
|
||||
PendingIntent piActivity = PendingIntent.getActivity(DownloadService.this, 0,
|
||||
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
|
||||
mDownloadingBuilder.setContentTitle(EhUtils.getSuitableTitle(info))
|
||||
.setContentText(null)
|
||||
.setContentInfo(null)
|
||||
.setProgress(0, 0, true);
|
||||
.setProgress(0, 0, true)
|
||||
.setContentIntent(piActivity);
|
||||
|
||||
mDownloadingDelay.startForeground();
|
||||
}
|
||||
@@ -346,7 +345,9 @@ public class DownloadService extends Service implements DownloadManager.Download
|
||||
return;
|
||||
}
|
||||
|
||||
mDownloadingDelay.cancel();
|
||||
if (null != mDownloadingDelay) {
|
||||
mDownloadingDelay.cancel();
|
||||
}
|
||||
|
||||
ensureDownloadedBuilder();
|
||||
|
||||
@@ -444,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -64,8 +64,8 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
|
||||
|
||||
private static final float[] LEFT_AREA = {0.0f, 0.0f, 1.0f / 3.0f, 1f};
|
||||
private static final float[] RIGHT_AREA = {2.0f / 3.0f, 0.0f, 1.0f, 1f};
|
||||
private static final float[] MENU_AREA = {1.0f / 3.0f, 0.0f, 2.0f / 3.0f, 3.0f / 4.0f};
|
||||
private static final float[] SLIDER_AREA = {1.0f / 3.0f, 3.0f / 4.0f, 2.0f / 3.0f, 1.0f};
|
||||
private static final float[] MENU_AREA = {1.0f / 3.0f, 0.0f, 2.0f / 3.0f, 1.0f / 2.0f};
|
||||
private static final float[] SLIDER_AREA = {1.0f / 3.0f, 1.0f / 2.0f, 2.0f / 3.0f, 1.0f};
|
||||
|
||||
private static final int METHOD_ON_SINGLE_TAP_UP = 0;
|
||||
private static final int METHOD_ON_SINGLE_TAP_CONFIRMED = 1;
|
||||
@@ -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();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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.v7.app.AlertDialog;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import com.hippo.ehviewer.EhDB;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.preference.MessagePreference;
|
||||
|
||||
public class ClearDownloadPathCachePreference extends MessagePreference {
|
||||
|
||||
public ClearDownloadPathCachePreference(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
|
||||
public ClearDownloadPathCachePreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
public ClearDownloadPathCachePreference(Context context,
|
||||
AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
public void init(Context context) {
|
||||
setDialogMessage(context.getString(R.string.settings_advanced_clear_download_path_cache_message));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||
super.onPrepareDialogBuilder(builder);
|
||||
builder.setTitle(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDialogClosed(boolean positiveResult) {
|
||||
super.onDialogClosed(positiveResult);
|
||||
|
||||
if (positiveResult) {
|
||||
EhDB.clearDownloadDirname();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
* 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.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.design.widget.TextInputLayout;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.SwitchCompat;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.network.InetValidator;
|
||||
import com.hippo.preference.DialogPreference;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
public class HatHProxyPreference extends DialogPreference implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
private SwitchCompat mEnable;
|
||||
@Nullable
|
||||
private TextInputLayout mIpInputLayout;
|
||||
@Nullable
|
||||
private EditText mIp;
|
||||
@Nullable
|
||||
private TextInputLayout mPortInputLayout;
|
||||
@Nullable
|
||||
private EditText mPort;
|
||||
@Nullable
|
||||
private TextInputLayout mPasskeyInputLayout;
|
||||
@Nullable
|
||||
private EditText mPasskey;
|
||||
|
||||
public HatHProxyPreference(Context context) {
|
||||
super(context);
|
||||
init();
|
||||
}
|
||||
|
||||
public HatHProxyPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
public HatHProxyPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
setDialogLayoutResource(R.layout.preference_dialog_hath_proxy);
|
||||
updateSummary(Settings.getHathProxy(), Settings.getHathIp(), Settings.getHathPort());
|
||||
}
|
||||
|
||||
private void updateSummary(boolean hathProxy, String hathIp, int hathPort) {
|
||||
if (InetValidator.isValidInet4Address(hathIp) && InetValidator.isValidInetPort(hathPort)) {
|
||||
Context context = getContext();
|
||||
setSummary(context.getString(R.string.settings_eh_hath_proxy_summary_1,
|
||||
context.getString(hathProxy ? R.string.enabled : R.string.disabled), hathIp, hathPort));
|
||||
} else {
|
||||
setSummary(R.string.settings_eh_hath_proxy_summary_2);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||
super.onPrepareDialogBuilder(builder);
|
||||
builder.setPositiveButton(android.R.string.ok, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("SetTextI18n")
|
||||
protected void onDialogCreated(AlertDialog dialog) {
|
||||
super.onDialogCreated(dialog);
|
||||
|
||||
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(this);
|
||||
|
||||
mEnable = (SwitchCompat) ViewUtils.$$(dialog, R.id.enable);
|
||||
mIpInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.ip_input_layout);
|
||||
mIp = (EditText) ViewUtils.$$(dialog, R.id.ip);
|
||||
mPortInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.port_input_layout);
|
||||
mPort = (EditText) ViewUtils.$$(dialog, R.id.port);
|
||||
mPasskeyInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.passkey_input_layout);
|
||||
mPasskey = (EditText) ViewUtils.$$(dialog, R.id.passkey);
|
||||
|
||||
mEnable.setChecked(Settings.getHathProxy());
|
||||
String ip = Settings.getHathIp();
|
||||
if (!InetValidator.isValidInet4Address(ip)) {
|
||||
ip = null;
|
||||
}
|
||||
String portString;
|
||||
int port = Settings.getHathPort();
|
||||
if (!InetValidator.isValidInetPort(port)) {
|
||||
portString = null;
|
||||
} else {
|
||||
portString = Integer.toString(Settings.getHathPort());
|
||||
}
|
||||
mIp.setText(ip);
|
||||
mPort.setText(portString);
|
||||
mPasskey.setText(Settings.getHathPasskey());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDialogClosed(boolean positiveResult) {
|
||||
super.onDialogClosed(positiveResult);
|
||||
mEnable = null;
|
||||
mIpInputLayout = null;
|
||||
mIp = null;
|
||||
mPortInputLayout = null;
|
||||
mPort = null;
|
||||
mPasskeyInputLayout = null;
|
||||
mPasskey = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Dialog dialog = getDialog();
|
||||
Context context = getContext();
|
||||
if (null == dialog || null == context || null == mEnable ||
|
||||
null == mIpInputLayout || null == mIp ||
|
||||
null == mPortInputLayout || null == mPort ||
|
||||
null == mPasskeyInputLayout || null == mPasskey) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean enable = mEnable.isChecked();
|
||||
|
||||
String ip = mIp.getText().toString().trim();
|
||||
if (ip.isEmpty()) {
|
||||
if (enable) {
|
||||
mIpInputLayout.setError(context.getString(R.string.text_is_empty));
|
||||
return;
|
||||
}
|
||||
} else if (!InetValidator.isValidInet4Address(ip)) {
|
||||
mIpInputLayout.setError(context.getString(R.string.domain_not_supported));
|
||||
return;
|
||||
} else {
|
||||
mIpInputLayout.setError(null);
|
||||
}
|
||||
|
||||
int port;
|
||||
String portString = mPort.getText().toString().trim();
|
||||
if (portString.isEmpty()) {
|
||||
if (enable) {
|
||||
mPortInputLayout.setError(context.getString(R.string.text_is_empty));
|
||||
return;
|
||||
} else {
|
||||
port = -1;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
port = Integer.parseInt(portString);
|
||||
} catch (NumberFormatException e) {
|
||||
port = -1;
|
||||
}
|
||||
if (!InetValidator.isValidInetPort(port)) {
|
||||
mPortInputLayout.setError(context.getString(R.string.invalid_port));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
String passkey = mPasskey.getText().toString();
|
||||
|
||||
Settings.putHathProxy(enable);
|
||||
Settings.putHathIp(ip);
|
||||
Settings.putHathPort(port);
|
||||
Settings.putHathPasskey(passkey);
|
||||
|
||||
updateSummary(enable, ip, port);
|
||||
|
||||
dialog.dismiss();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* 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.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.os.Parcel;
|
||||
import android.preference.Preference;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.EhDB;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.EhEngine;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.ehviewer.spider.SpiderQueen;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
public class RestoreDownloadPreference extends TaskPreference {
|
||||
|
||||
public RestoreDownloadPreference(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public RestoreDownloadPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public RestoreDownloadPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
protected Task onCreateTask() {
|
||||
return new RestoreTask(getContext());
|
||||
}
|
||||
|
||||
private static class RestoreTask extends Task {
|
||||
|
||||
private final EhApplication mApplication;
|
||||
private final DownloadManager mManager;
|
||||
private final OkHttpClient mHttpClient;
|
||||
|
||||
public RestoreTask(@NonNull Context context) {
|
||||
super(context);
|
||||
mApplication = (EhApplication) context.getApplicationContext();
|
||||
mManager = EhApplication.getDownloadManager(mApplication);
|
||||
mHttpClient = EhApplication.getOkHttpClient(mApplication);
|
||||
}
|
||||
|
||||
private RestoreItem getRestoreItem(UniFile file) {
|
||||
if (null == file || !file.isDirectory()) {
|
||||
return null;
|
||||
}
|
||||
UniFile siFile = file.findFile(SpiderQueen.SPIDER_INFO_FILENAME);
|
||||
if (null == siFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = siFile.openInputStream();
|
||||
// Skip start page
|
||||
IOUtils.readAsciiLine(is);
|
||||
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
|
||||
if (mManager.containDownloadInfo(gid)) {
|
||||
return null;
|
||||
}
|
||||
String token = IOUtils.readAsciiLine(is);
|
||||
RestoreItem restoreItem = new RestoreItem();
|
||||
restoreItem.gid = gid;
|
||||
restoreItem.token = token;
|
||||
restoreItem.dirname = file.getName();
|
||||
return restoreItem;
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
} finally {
|
||||
IOUtils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object doInBackground(Void... params) {
|
||||
UniFile dir = Settings.getDownloadLocation();
|
||||
if (null == dir) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<RestoreItem> restoreItemList = new ArrayList<>();
|
||||
|
||||
UniFile[] files = dir.listFiles();
|
||||
for (UniFile file: files) {
|
||||
RestoreItem restoreItem = getRestoreItem(file);
|
||||
if (null != restoreItem) {
|
||||
restoreItemList.add(restoreItem);
|
||||
}
|
||||
}
|
||||
|
||||
if (0 == restoreItemList.size()) {
|
||||
return Collections.EMPTY_LIST;
|
||||
}
|
||||
|
||||
try {
|
||||
return EhEngine.fillGalleryListByApi(null, mHttpClient, new ArrayList<GalleryInfo>(restoreItemList));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void onPostExecute(Object o) {
|
||||
if (!(o instanceof List)) {
|
||||
Toast.makeText(mApplication, R.string.settings_download_restore_failed, Toast.LENGTH_SHORT).show();
|
||||
} else {
|
||||
List<RestoreItem> list = (List<RestoreItem>) o;
|
||||
if (list.isEmpty()) {
|
||||
Toast.makeText(mApplication, R.string.settings_download_restore_not_found, Toast.LENGTH_SHORT).show();
|
||||
} else {
|
||||
int count = 0;
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
RestoreItem item = list.get(i);
|
||||
// Avoid failed gallery info
|
||||
if (null != item.title) {
|
||||
// Put to download
|
||||
mManager.addDownload(item, null);
|
||||
// Put download dir to DB
|
||||
EhDB.putDownloadDirname(item.gid, item.dirname);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
Toast.makeText(mApplication,
|
||||
mApplication.getString(R.string.settings_download_restore_successfully, count),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
|
||||
Preference preference = getPreference();
|
||||
if (null != preference) {
|
||||
Context context = preference.getContext();
|
||||
if (context instanceof Activity) {
|
||||
((Activity) context).setResult(Activity.RESULT_OK);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
super.onPostExecute(o);
|
||||
}
|
||||
}
|
||||
|
||||
private static class RestoreItem extends GalleryInfo {
|
||||
|
||||
public String dirname;
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeString(this.dirname);
|
||||
}
|
||||
|
||||
public RestoreItem() {
|
||||
}
|
||||
|
||||
protected RestoreItem(Parcel in) {
|
||||
super(in);
|
||||
this.dirname = in.readString();
|
||||
}
|
||||
|
||||
public static final Creator<RestoreItem> CREATOR = new Creator<RestoreItem>() {
|
||||
@Override
|
||||
public RestoreItem createFromParcel(Parcel source) {
|
||||
return new RestoreItem(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RestoreItem[] newArray(int size) {
|
||||
return new RestoreItem[size];
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* 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.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
import android.support.annotation.CallSuper;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.preference.DialogPreference;
|
||||
import com.hippo.yorozuya.IntIdGenerator;
|
||||
|
||||
public abstract class TaskPreference extends DialogPreference {
|
||||
|
||||
private Task mTask;
|
||||
private int mTaskId = IntIdGenerator.INVALID_ID;
|
||||
|
||||
public TaskPreference(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public TaskPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public TaskPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||
builder.setTitle(null);
|
||||
builder.setView(R.layout.preference_dialog_task);
|
||||
builder.setCancelable(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDialogCreated(AlertDialog dialog) {
|
||||
if (null == mTask) {
|
||||
mTask = onCreateTask();
|
||||
mTask.setPreference(this);
|
||||
mTaskId = ((EhApplication) getContext().getApplicationContext()).putGlobalStuff(mTask);
|
||||
mTask.execute();
|
||||
}
|
||||
}
|
||||
|
||||
protected void onTaskEnd() {
|
||||
// Dismiss dialog
|
||||
Dialog dialog = getDialog();
|
||||
if (null != dialog) {
|
||||
dialog.dismiss();
|
||||
}
|
||||
// Clear async
|
||||
mTask = null;
|
||||
mTaskId = IntIdGenerator.INVALID_ID;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
protected abstract Task onCreateTask();
|
||||
|
||||
@Override
|
||||
public void onActivityDestroy() {
|
||||
super.onActivityDestroy();
|
||||
|
||||
if (null != mTask) {
|
||||
mTask.setPreference(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Parcelable onSaveInstanceState() {
|
||||
final Parcelable superState = super.onSaveInstanceState();
|
||||
final SavedState myState = new SavedState(superState);
|
||||
myState.asyncTaskId = mTaskId;
|
||||
return myState;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onRestoreInstanceState(Parcelable state) {
|
||||
if (state == null || !state.getClass().equals(SavedState.class)) {
|
||||
// Didn't save state for us in onSaveInstanceState
|
||||
super.onRestoreInstanceState(state);
|
||||
return;
|
||||
}
|
||||
|
||||
SavedState myState = (SavedState) state;
|
||||
mTaskId = myState.asyncTaskId;
|
||||
if (IntIdGenerator.INVALID_ID != mTaskId) {
|
||||
Object o = ((EhApplication) getContext().getApplicationContext()).getGlobalStuff(mTaskId);
|
||||
if (o instanceof Task) {
|
||||
mTask = (Task) o;
|
||||
mTask.setPreference(this);
|
||||
}
|
||||
}
|
||||
if (null == mTask) {
|
||||
mTaskId = IntIdGenerator.INVALID_ID;
|
||||
}
|
||||
|
||||
// TODO if not task, show not reopen dialog
|
||||
|
||||
super.onRestoreInstanceState(myState.getSuperState());
|
||||
}
|
||||
|
||||
private static class SavedState extends BaseSavedState {
|
||||
int asyncTaskId;
|
||||
|
||||
public SavedState(Parcel source) {
|
||||
super(source);
|
||||
asyncTaskId = source.readInt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeInt(asyncTaskId);
|
||||
}
|
||||
|
||||
public SavedState(Parcelable superState) {
|
||||
super(superState);
|
||||
}
|
||||
|
||||
public static final Parcelable.Creator<SavedState> CREATOR =
|
||||
new Parcelable.Creator<SavedState>() {
|
||||
@Override
|
||||
public SavedState createFromParcel(Parcel in) {
|
||||
return new SavedState(in);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SavedState[] newArray(int size) {
|
||||
return new SavedState[size];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public abstract static class Task extends AsyncTask<Void, Void, Object> {
|
||||
|
||||
private final EhApplication mApplication;
|
||||
@Nullable
|
||||
private TaskPreference mPreference;
|
||||
|
||||
public Task(@NonNull Context context) {
|
||||
mApplication = (EhApplication) context.getApplicationContext();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public TaskPreference getPreference() {
|
||||
return mPreference;
|
||||
}
|
||||
|
||||
public void setPreference(@Nullable TaskPreference preference) {
|
||||
mPreference = preference;
|
||||
}
|
||||
|
||||
@CallSuper
|
||||
@Override
|
||||
protected void onPostExecute(Object o) {
|
||||
mApplication.removeGlobalStuff(this);
|
||||
if (null != mPreference) {
|
||||
mPreference.onTaskEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,9 +30,11 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.gallery.GalleryProvider;
|
||||
import com.hippo.io.UniFileInputStreamPipe;
|
||||
import com.hippo.io.UniFileOutputStreamPipe;
|
||||
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;
|
||||
@@ -53,7 +55,22 @@ 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 {
|
||||
|
||||
private final String mPrefix;
|
||||
|
||||
public StartWithFilenameFilter(String prefix) {
|
||||
mPrefix = prefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean accept(UniFile dir, String filename) {
|
||||
return filename.startsWith(mPrefix);
|
||||
}
|
||||
}
|
||||
|
||||
public static UniFile getGalleryDownloadDir(GalleryInfo galleryInfo) {
|
||||
@@ -61,11 +78,40 @@ public final class SpiderDen {
|
||||
if (dir != null) {
|
||||
// Read from DB
|
||||
String dirname = EhDB.getDownloadDirname(galleryInfo.gid);
|
||||
if (dirname == null) {
|
||||
dirname = FileUtils.sanitizeFilename(galleryInfo.gid + "-" + EhUtils.getSuitableTitle(galleryInfo));
|
||||
// Put into DB
|
||||
if (null != dirname) {
|
||||
// Some dirname may be invalid in some version
|
||||
dirname = FileUtils.sanitizeFilename(dirname);
|
||||
EhDB.putDownloadDirname(galleryInfo.gid, dirname);
|
||||
}
|
||||
|
||||
// Find it
|
||||
if (null == dirname) {
|
||||
UniFile[] files = dir.listFiles(new StartWithFilenameFilter(galleryInfo.gid + "-"));
|
||||
if (null != files) {
|
||||
// Get max-length-name dir
|
||||
int maxLength = -1;
|
||||
for (UniFile file : files) {
|
||||
if (file.isDirectory()) {
|
||||
String name = file.getName();
|
||||
int length = name.length();
|
||||
if (length > maxLength) {
|
||||
maxLength = length;
|
||||
dirname = name;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (null != dirname) {
|
||||
EhDB.putDownloadDirname(galleryInfo.gid, dirname);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create it
|
||||
if (null == dirname) {
|
||||
dirname = FileUtils.sanitizeFilename(galleryInfo.gid + "-" + EhUtils.getSuitableTitle(galleryInfo));
|
||||
EhDB.putDownloadDirname(galleryInfo.gid, dirname);
|
||||
}
|
||||
|
||||
return dir.subFile(dirname);
|
||||
} else {
|
||||
return null;
|
||||
@@ -89,6 +135,17 @@ public final class SpiderDen {
|
||||
return mDownloadDir != null && mDownloadDir.ensureDir();
|
||||
}
|
||||
|
||||
public boolean isReady() {
|
||||
switch (mMode) {
|
||||
case SpiderQueen.MODE_READ:
|
||||
return sCache != null;
|
||||
case SpiderQueen.MODE_DOWNLOAD:
|
||||
return mDownloadDir != null && mDownloadDir.isDirectory();
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public UniFile getDownloadDir() {
|
||||
return mDownloadDir != null && mDownloadDir.isDirectory() ? mDownloadDir : null;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -34,7 +35,6 @@ public class SpiderInfo {
|
||||
private static final String TAG = SpiderInfo.class.getSimpleName();
|
||||
|
||||
static final String TOKEN_FAILED = "failed";
|
||||
static final String TOKEN_WAIT = "wait";
|
||||
|
||||
int startPage = 0;
|
||||
long gid = -1;
|
||||
@@ -95,17 +95,18 @@ public class SpiderInfo {
|
||||
spiderInfo.gid = Long.parseLong(IOUtils.readAsciiLine(is));
|
||||
// Token
|
||||
spiderInfo.token = IOUtils.readAsciiLine(is);
|
||||
// Deprecated, mode, only ex is support now, MUST be 1
|
||||
if (1 != Integer.parseInt(IOUtils.readAsciiLine(is))) {
|
||||
Log.w(TAG, "Not ex mode");
|
||||
return null;
|
||||
}
|
||||
// Deprecated, mode, skip it
|
||||
IOUtils.readAsciiLine(is);
|
||||
// Preview pages
|
||||
spiderInfo.previewPages = Integer.parseInt(IOUtils.readAsciiLine(is));
|
||||
// Preview pre page
|
||||
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
|
||||
@@ -114,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);
|
||||
}
|
||||
@@ -151,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();
|
||||
|
||||
@@ -24,6 +24,7 @@ import android.support.annotation.IntDef;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.annotation.UiThread;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.util.SparseArray;
|
||||
import android.webkit.MimeTypeMap;
|
||||
@@ -34,10 +35,11 @@ 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;
|
||||
import com.hippo.ehviewer.client.data.NormalPreviewSet;
|
||||
import com.hippo.ehviewer.client.data.PreviewSet;
|
||||
import com.hippo.ehviewer.client.exception.Image509Exception;
|
||||
import com.hippo.ehviewer.client.exception.ParseException;
|
||||
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
|
||||
@@ -47,11 +49,14 @@ 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;
|
||||
import com.hippo.yorozuya.PriorityThread;
|
||||
import com.hippo.yorozuya.PriorityThreadFactory;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
import com.hippo.yorozuya.Utilities;
|
||||
import com.hippo.yorozuya.io.InputStreamPipe;
|
||||
import com.hippo.yorozuya.io.OutputStreamPipe;
|
||||
import com.hippo.yorozuya.sparse.SparseJLArray;
|
||||
@@ -61,18 +66,19 @@ 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.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.LinkedBlockingDeque;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
@@ -127,20 +133,19 @@ public class SpiderQueen implements Runnable {
|
||||
@Nullable
|
||||
private volatile Thread mQueenThread;
|
||||
private final Object mQueenLock = new Object();
|
||||
private final ThreadFactory mThreadFactory = new PriorityThreadFactory(
|
||||
SpiderWorker.class.getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND);
|
||||
|
||||
@Nullable
|
||||
private Thread mDecoderThread;
|
||||
private final Stack<Integer> mDecodeRequestStack = new Stack<>();
|
||||
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
|
||||
|
||||
private volatile Thread[] mWorkers;
|
||||
private final Object mWorkerLock = new Object();
|
||||
private ThreadPoolExecutor mWorkerPoolExecutor;
|
||||
private int mWorkerCount;
|
||||
|
||||
private final Object mPTokenLock = new Object();
|
||||
private volatile SpiderInfo mSpiderInfo;
|
||||
private final Queue<Integer> mRequestPTokenQueue = new LinkedList<>();
|
||||
private final Queue<Integer> mRequestPTokenQueue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
private final Object mPageStateLock = new Object();
|
||||
private volatile int[] mPageStateArray;
|
||||
@@ -154,8 +159,6 @@ public class SpiderQueen implements Runnable {
|
||||
// For download, when it go to mPageStateArray.size(), done
|
||||
private volatile int mDownloadPage = -1;
|
||||
|
||||
private final Set<Integer> mRequestPreviewPageSet = new HashSet<>();
|
||||
|
||||
private final AtomicInteger mDownloadedPages = new AtomicInteger(0);
|
||||
private final AtomicInteger mFinishedPages = new AtomicInteger(0);
|
||||
|
||||
@@ -166,7 +169,7 @@ public class SpiderQueen implements Runnable {
|
||||
|
||||
private final List<OnSpiderListener> mSpiderListeners = new ArrayList<>();
|
||||
|
||||
private final int mSpiderWorkerNumber;
|
||||
private final int mWorkerMaxCount;
|
||||
private final int mPreloadNumber;
|
||||
|
||||
private SpiderQueen(EhApplication application, @NonNull GalleryInfo galleryInfo) {
|
||||
@@ -175,8 +178,12 @@ public class SpiderQueen implements Runnable {
|
||||
mGalleryInfo = galleryInfo;
|
||||
mSpiderDen = new SpiderDen(mGalleryInfo);
|
||||
|
||||
mSpiderWorkerNumber = Settings.getMultiThreadDownload();
|
||||
mPreloadNumber = Settings.getPreloadImage();
|
||||
mWorkerMaxCount = MathUtils.clamp(Settings.getMultiThreadDownload(), 1, 10);
|
||||
mPreloadNumber = MathUtils.clamp(Settings.getPreloadImage(), 0, 100);
|
||||
|
||||
mWorkerPoolExecutor = new ThreadPoolExecutor(mWorkerMaxCount, mWorkerMaxCount,
|
||||
0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(),
|
||||
new PriorityThreadFactory(SpiderWorker.class.getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND));
|
||||
}
|
||||
|
||||
public void addOnSpiderListener(OnSpiderListener listener) {
|
||||
@@ -415,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) {
|
||||
@@ -465,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;
|
||||
}
|
||||
@@ -488,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;
|
||||
@@ -541,17 +548,13 @@ public class SpiderQueen implements Runnable {
|
||||
|
||||
private void ensureWorkers() {
|
||||
synchronized (mWorkerLock) {
|
||||
if (mWorkers == null) {
|
||||
mWorkers = new Thread[mSpiderWorkerNumber];
|
||||
if (null == mWorkerPoolExecutor) {
|
||||
Log.e(TAG, "Try to start worker after stopped");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0, n = mWorkers.length; i < n; i++) {
|
||||
if (mWorkers[i] == null) {
|
||||
SpiderWorker worker = new SpiderWorker(i);
|
||||
Thread thread = mThreadFactory.newThread(worker);
|
||||
mWorkers[i] = thread;
|
||||
thread.start();
|
||||
}
|
||||
for (; mWorkerCount < mWorkerMaxCount; mWorkerCount++) {
|
||||
mWorkerPoolExecutor.execute(new SpiderWorker());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,6 +684,19 @@ public class SpiderQueen implements Runnable {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void readPreviews(String body, SpiderInfo spiderInfo) throws ParseException {
|
||||
PreviewSet previewSet = GalleryDetailParser.parsePreviewSet(body);
|
||||
spiderInfo.previewPerPage = previewSet.size();
|
||||
for (int i = 0, n = previewSet.size(); i < n; i++) {
|
||||
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
|
||||
if (result != null) {
|
||||
synchronized (mPTokenLock) {
|
||||
spiderInfo.pTokenMap.put(result.page, result.pToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SpiderInfo readSpiderInfoFromInternet(EhConfig config) {
|
||||
try {
|
||||
SpiderInfo spiderInfo = new SpiderInfo();
|
||||
@@ -693,17 +709,9 @@ public class SpiderQueen implements Runnable {
|
||||
String body = response.body().string();
|
||||
|
||||
spiderInfo.pages = GalleryDetailParser.parsePages(body);
|
||||
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
|
||||
NormalPreviewSet previewSet = GalleryDetailParser.parseNormalPreviewSet(body);
|
||||
spiderInfo.previewPerPage = previewSet.size();
|
||||
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
|
||||
for (int i = 0, n = previewSet.size(); i < n; i++) {
|
||||
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
|
||||
if (result != null) {
|
||||
spiderInfo.pTokenMap.put(result.page, result.pToken);
|
||||
}
|
||||
}
|
||||
|
||||
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
|
||||
readPreviews(body, spiderInfo);
|
||||
return spiderInfo;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
@@ -713,12 +721,6 @@ public class SpiderQueen implements Runnable {
|
||||
private String getPTokenFromInternet(int index, EhConfig config) {
|
||||
// Check previewIndex
|
||||
int previewIndex = index / mSpiderInfo.previewPerPage;
|
||||
synchronized (mRequestPreviewPageSet) {
|
||||
if (mRequestPreviewPageSet.contains(previewIndex)) {
|
||||
return SpiderInfo.TOKEN_WAIT;
|
||||
}
|
||||
mRequestPreviewPageSet.add(previewIndex);
|
||||
}
|
||||
|
||||
try {
|
||||
String url = EhUrl.getGalleryDetailUrl(
|
||||
@@ -729,23 +731,19 @@ public class SpiderQueen implements Runnable {
|
||||
Request request = new EhRequestBuilder(url, config).build();
|
||||
Response response = mHttpClient.newCall(request).execute();
|
||||
String body = response.body().string();
|
||||
NormalPreviewSet previewSet = GalleryDetailParser.parseNormalPreviewSet(body);
|
||||
mSpiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
|
||||
readPreviews(body, mSpiderInfo);
|
||||
|
||||
// Save to local
|
||||
writeSpiderInfoToLocal(mSpiderInfo);
|
||||
|
||||
String pToken;
|
||||
synchronized (mPTokenLock) {
|
||||
for (int i = 0, n = previewSet.size(); i < n; i++) {
|
||||
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
|
||||
if (result != null) {
|
||||
mSpiderInfo.pTokenMap.put(result.page, result.pToken);
|
||||
}
|
||||
}
|
||||
writeSpiderInfoToLocal(mSpiderInfo);
|
||||
pToken = mSpiderInfo.pTokenMap.get(index);
|
||||
}
|
||||
return mSpiderInfo.pTokenMap.get(index);
|
||||
return pToken;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
} finally {
|
||||
synchronized (mRequestPreviewPageSet) {
|
||||
mRequestPreviewPageSet.remove(previewIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -831,10 +829,7 @@ public class SpiderQueen implements Runnable {
|
||||
|
||||
// handle pToken request
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
Integer index;
|
||||
synchronized (mPTokenLock) {
|
||||
index = mRequestPTokenQueue.poll();
|
||||
}
|
||||
Integer index = mRequestPTokenQueue.poll();
|
||||
|
||||
if (index == null) {
|
||||
// No request index, wait here
|
||||
@@ -863,8 +858,12 @@ public class SpiderQueen implements Runnable {
|
||||
|
||||
// Get pToken from internet
|
||||
pToken = getPTokenFromInternet(index, config);
|
||||
if (null == pToken) {
|
||||
// Preview size may changed, so try to get pToken twice
|
||||
pToken = getPTokenFromInternet(index, config);
|
||||
}
|
||||
|
||||
if (null == pToken || SpiderInfo.TOKEN_WAIT.equals(pToken)) {
|
||||
if (null == pToken) {
|
||||
// If failed, set the pToken "failed"
|
||||
synchronized (mPTokenLock) {
|
||||
mSpiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
|
||||
@@ -872,10 +871,8 @@ public class SpiderQueen implements Runnable {
|
||||
}
|
||||
|
||||
// Notify worker
|
||||
if (!SpiderInfo.TOKEN_WAIT.equals(pToken)) {
|
||||
synchronized (mWorkerLock) {
|
||||
mWorkerLock.notifyAll();
|
||||
}
|
||||
synchronized (mWorkerLock) {
|
||||
mWorkerLock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -899,18 +896,9 @@ public class SpiderQueen implements Runnable {
|
||||
|
||||
// Interrupt all workers
|
||||
synchronized (mWorkerLock) {
|
||||
if (mWorkers != null) {
|
||||
for (int i = 0, n = mWorkers.length; i < n; i++) {
|
||||
Thread thread = mWorkers[i];
|
||||
if (thread != null) {
|
||||
thread.interrupt();
|
||||
mWorkers[i] = null;
|
||||
}
|
||||
}
|
||||
mWorkers = null;
|
||||
}
|
||||
mWorkerPoolExecutor.shutdownNow();
|
||||
mWorkerPoolExecutor = null;
|
||||
}
|
||||
|
||||
notifyFinish();
|
||||
|
||||
if (DEBUG_LOG) {
|
||||
@@ -918,77 +906,71 @@ 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 int mWorkerIndex;
|
||||
private final long mGid;
|
||||
|
||||
public SpiderWorker(int workerIndex) {
|
||||
mWorkerIndex = workerIndex;
|
||||
public SpiderWorker() {
|
||||
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
|
||||
@@ -1008,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
|
||||
@@ -1030,7 +1013,11 @@ public class SpiderQueen implements Runnable {
|
||||
break;
|
||||
}
|
||||
|
||||
imageUrl = result.imageUrl;
|
||||
if (Settings.getDownloadOriginImage() && !TextUtils.isEmpty(result.originImageUrl)) {
|
||||
imageUrl = result.originImageUrl;
|
||||
} else {
|
||||
imageUrl = result.imageUrl;
|
||||
}
|
||||
skipHathKey = result.skipHathKey;
|
||||
|
||||
// If it is force request, skip first image
|
||||
@@ -1042,28 +1029,40 @@ public class SpiderQueen implements Runnable {
|
||||
Log.d(TAG, imageUrl);
|
||||
}
|
||||
|
||||
// Start download image
|
||||
OutputStreamPipe pipe = mSpiderDen.openOutputStreamPipe(
|
||||
index, MimeTypeMap.getFileExtensionFromUrl(imageUrl));
|
||||
if (pipe == null) {
|
||||
// Can't get pipe
|
||||
error = GetText.getString(R.string.error_write_failed);
|
||||
break;
|
||||
}
|
||||
|
||||
// Download image
|
||||
OutputStreamPipe pipe = null;
|
||||
InputStream is = null;
|
||||
try {
|
||||
if (DEBUG_LOG) {
|
||||
Log.d(TAG, "Start download image " + index);
|
||||
}
|
||||
|
||||
Response response = mHttpClient.newCall(new EhRequestBuilder(imageUrl).build()).execute();
|
||||
Call call = mHttpClient.newCall(new EhRequestBuilder(imageUrl).build());
|
||||
Response response = call.execute();
|
||||
if (response.code() >= 400) {
|
||||
// Maybe 404
|
||||
response.body().close();
|
||||
continue;
|
||||
}
|
||||
ResponseBody responseBody = response.body();
|
||||
|
||||
// Get extension
|
||||
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(
|
||||
responseBody.contentType().toString());
|
||||
// Ensure extension
|
||||
if (!Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
|
||||
extension = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
|
||||
}
|
||||
|
||||
// Get out put pipe
|
||||
pipe = mSpiderDen.openOutputStreamPipe(index, extension);
|
||||
if (null == pipe) {
|
||||
// Can't get pipe
|
||||
error = GetText.getString(R.string.error_write_failed);
|
||||
response.body().close();
|
||||
break;
|
||||
}
|
||||
|
||||
long contentLength = responseBody.contentLength();
|
||||
is = responseBody.byteStream();
|
||||
pipe.obtain();
|
||||
@@ -1075,6 +1074,7 @@ public class SpiderQueen implements Runnable {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
int bytesRead = is.read(data);
|
||||
if (bytesRead == -1) {
|
||||
response.body().close();
|
||||
break;
|
||||
}
|
||||
os.write(data, 0, bytesRead);
|
||||
@@ -1105,8 +1105,10 @@ public class SpiderQueen implements Runnable {
|
||||
error = GetText.getString(R.string.error_socket);
|
||||
} finally {
|
||||
IOUtils.closeQuietly(is);
|
||||
pipe.close();
|
||||
pipe.release();
|
||||
if (null != pipe) {
|
||||
pipe.close();
|
||||
pipe.release();
|
||||
}
|
||||
|
||||
if (DEBUG_LOG) {
|
||||
Log.d(TAG, "End download image " + index);
|
||||
@@ -1175,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1233,27 +1235,17 @@ public class SpiderQueen implements Runnable {
|
||||
Log.i(TAG, Thread.currentThread().getName() + ": start");
|
||||
}
|
||||
|
||||
while (!Thread.currentThread().isInterrupted() && runInternal());
|
||||
while (mSpiderDen.isReady() && !Thread.currentThread().isInterrupted() && runInternal());
|
||||
|
||||
|
||||
boolean finish = true;
|
||||
boolean finish;
|
||||
// Clear in spider worker array
|
||||
synchronized (mWorkerLock) {
|
||||
if (mWorkers != null && mWorkerIndex < mWorkers.length &&
|
||||
mWorkers[mWorkerIndex] == Thread.currentThread()) {
|
||||
mWorkers[mWorkerIndex] = null;
|
||||
}
|
||||
if (mWorkers != null) {
|
||||
for (Thread mWorker : mWorkers) {
|
||||
if (null != mWorker) {
|
||||
finish = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (finish) {
|
||||
mWorkers = null;
|
||||
mWorkerCount--;
|
||||
if (mWorkerCount < 0) {
|
||||
Log.e(TAG, "WTF, mWorkerCount < 0, not thread safe or something wrong");
|
||||
mWorkerCount = 0;
|
||||
}
|
||||
finish = mWorkerCount <= 0;
|
||||
}
|
||||
|
||||
if (finish) {
|
||||
@@ -1300,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -37,13 +37,17 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.dao.DownloadLabel;
|
||||
import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.ehviewer.download.DownloadService;
|
||||
import com.hippo.ehviewer.ui.scene.BaseScene;
|
||||
import com.hippo.text.Html;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.yorozuya.FileUtils;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
@@ -113,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();
|
||||
}
|
||||
@@ -216,7 +220,8 @@ public final class CommonOperations {
|
||||
client.execute(request);
|
||||
}
|
||||
|
||||
public static void startDownload(final Activity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
|
||||
// TODO Add context if activity and context are different style
|
||||
public static void startDownload(final MainActivity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
|
||||
final DownloadManager dm = EhApplication.getDownloadManager(activity);
|
||||
|
||||
boolean justStart = forceDefault || dm.containDownloadInfo(galleryInfo.gid);
|
||||
@@ -239,6 +244,8 @@ public final class CommonOperations {
|
||||
intent.putExtra(DownloadService.KEY_LABEL, label);
|
||||
intent.putExtra(DownloadService.KEY_GALLERY_INFO, galleryInfo);
|
||||
activity.startService(intent);
|
||||
// Notify
|
||||
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
|
||||
} else {
|
||||
// Let use chose label
|
||||
List<DownloadLabel> list = dm.getLabelList();
|
||||
@@ -274,10 +281,43 @@ public final class CommonOperations {
|
||||
} else {
|
||||
Settings.putHasDefaultDownloadLabel(false);
|
||||
}
|
||||
// Notify
|
||||
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
|
||||
}
|
||||
}, activity.getString(R.string.remember_download_label), false)
|
||||
.setTitle(R.string.download)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
public static void ensureNoMediaFile(UniFile file) {
|
||||
if (null == file) {
|
||||
return;
|
||||
}
|
||||
|
||||
UniFile noMedia = file.createFile(".nomedia");
|
||||
if (null == noMedia) {
|
||||
return;
|
||||
}
|
||||
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = noMedia.openInputStream();
|
||||
} catch (IOException e) {
|
||||
// Ignore
|
||||
} finally {
|
||||
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);
|
||||
|
||||
|
||||
+4
-14
@@ -14,18 +14,8 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import com.hippo.yorozuya.Messenger;
|
||||
|
||||
public final class Constants {
|
||||
|
||||
public static final int MESSAGE_ID_LIST_MODE;
|
||||
|
||||
static {
|
||||
Messenger messenger = Messenger.getInstance();
|
||||
MESSAGE_ID_LIST_MODE = messenger.newId();
|
||||
}
|
||||
|
||||
private Constants(){}
|
||||
}
|
||||
// It is a dump activity to make Chrome or maybe other browser to send implicit intent when open eh url.
|
||||
// Take a look at AndroidManifest to know how it works.
|
||||
public class DumpBrowsableActivity extends EhActivity {}
|
||||
+18
-1
@@ -16,15 +16,32 @@
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
|
||||
import com.google.analytics.tracking.android.EasyTracker;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
|
||||
public class TrackedActivity extends AppCompatActivity {
|
||||
public class EhActivity extends AppCompatActivity {
|
||||
|
||||
private boolean mTrackStarted;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
((EhApplication) getApplication()).registerActivity(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
((EhApplication) getApplication()).unregisterActivity(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
+19
-1
@@ -16,14 +16,32 @@
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import com.google.analytics.tracking.android.EasyTracker;
|
||||
import com.hippo.app.AppCompatPreferenceActivity;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
|
||||
public class TrackedPreferenceActivity extends AppCompatPreferenceActivity {
|
||||
public class EhPreferenceActivity extends AppCompatPreferenceActivity {
|
||||
|
||||
private boolean mTrackStarted;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
((EhApplication) getApplication()).registerActivity(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
((EhApplication) getApplication()).unregisterActivity(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* 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.content.DialogInterface;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.design.widget.TextInputLayout;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.text.TextUtils;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.easyrecyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.client.EhFilter;
|
||||
import com.hippo.ehviewer.dao.Filter;
|
||||
import com.hippo.util.DrawableManager;
|
||||
import com.hippo.view.ViewTransition;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class FilterActivity extends ToolbarActivity {
|
||||
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
@Nullable
|
||||
private FilterAdapter mAdapter;
|
||||
@Nullable
|
||||
private FilterList mFilterList;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_filter);
|
||||
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
|
||||
|
||||
mFilterList = new FilterList();
|
||||
|
||||
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(this, R.id.recycler_view);
|
||||
TextView tip = (TextView) ViewUtils.$$(this, R.id.tip);
|
||||
mViewTransition = new ViewTransition(mRecyclerView, tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(this, R.drawable.big_filter);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
|
||||
mAdapter = new FilterAdapter();
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
mRecyclerView.setClipChildren(false);
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
|
||||
mRecyclerView.hasFixedSize();
|
||||
|
||||
updateView(false);
|
||||
}
|
||||
|
||||
private void updateView(boolean animation) {
|
||||
if (null == mViewTransition) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (null == mFilterList || 0 == mFilterList.size()) {
|
||||
mViewTransition.showView(1, animation);
|
||||
} else {
|
||||
mViewTransition.showView(0, animation);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
mRecyclerView = null;
|
||||
mViewTransition = null;
|
||||
mAdapter = null;
|
||||
mFilterList = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
super.onCreateOptionsMenu(menu);
|
||||
getMenuInflater().inflate(R.menu.activity_filter, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
case R.id.action_add:
|
||||
showAddFilterDialog();
|
||||
return true;
|
||||
case R.id.action_tip:
|
||||
showTipDialog();
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
|
||||
private void showTipDialog() {
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.filter)
|
||||
.setMessage(R.string.filter_tip)
|
||||
.show();
|
||||
}
|
||||
|
||||
private void showAddFilterDialog() {
|
||||
AlertDialog dialog = new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.add_filter)
|
||||
.setView(R.layout.dialog_add_filter)
|
||||
.setPositiveButton(R.string.add, null)
|
||||
.show();
|
||||
AddFilterDialogHelper helper = new AddFilterDialogHelper();
|
||||
helper.setDialog(dialog);
|
||||
}
|
||||
|
||||
private void showDeleteFilterDialog(final Filter filter) {
|
||||
int messageId;
|
||||
switch (filter.mode) {
|
||||
case EhFilter.MODE_TITLE:
|
||||
messageId = R.string.delete_title_filter;
|
||||
break;
|
||||
case EhFilter.MODE_UPLOADER:
|
||||
messageId = R.string.delete_uploader_filter;
|
||||
break;
|
||||
case EhFilter.MODE_TAG:
|
||||
messageId = R.string.delete_tag_filter;
|
||||
break;
|
||||
default:
|
||||
messageId = R.string.delete_filter;
|
||||
}
|
||||
String message = getString(messageId, filter.text);
|
||||
|
||||
new AlertDialog.Builder(this)
|
||||
.setMessage(message)
|
||||
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
if (DialogInterface.BUTTON_POSITIVE != which || null == mFilterList) {
|
||||
return;
|
||||
}
|
||||
mFilterList.delete(filter);
|
||||
if (null != mAdapter) {
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
updateView(true);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private class AddFilterDialogHelper implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
private AlertDialog mDialog;
|
||||
@Nullable
|
||||
private Spinner mSpinner;
|
||||
@Nullable
|
||||
private TextInputLayout mInputLayout;
|
||||
@Nullable
|
||||
private EditText mEditText;
|
||||
|
||||
public void setDialog(AlertDialog dialog) {
|
||||
mDialog = dialog;
|
||||
mSpinner = (Spinner) ViewUtils.$$(dialog, R.id.spinner);
|
||||
mInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.text_input_layout);
|
||||
mEditText = mInputLayout.getEditText();
|
||||
View button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
|
||||
if (null != button) {
|
||||
button.setOnClickListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (null == mFilterList || null == mDialog || null == mSpinner ||
|
||||
null == mInputLayout || null == mEditText) {
|
||||
return;
|
||||
}
|
||||
|
||||
String text = mEditText.getText().toString().trim();
|
||||
if (TextUtils.isEmpty(text)) {
|
||||
mInputLayout.setError(getString(R.string.text_is_empty));
|
||||
return;
|
||||
} else {
|
||||
mInputLayout.setError(null);
|
||||
}
|
||||
int mode = mSpinner.getSelectedItemPosition();
|
||||
|
||||
Filter filter = new Filter();
|
||||
filter.mode = mode;
|
||||
filter.text = text;
|
||||
mFilterList.add(filter);
|
||||
|
||||
if (null != mAdapter) {
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
updateView(true);
|
||||
|
||||
mDialog.dismiss();
|
||||
mDialog = null;
|
||||
mSpinner = null;
|
||||
mInputLayout = null;
|
||||
mEditText = null;
|
||||
}
|
||||
}
|
||||
|
||||
private class FilterHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
|
||||
|
||||
private final TextView text;
|
||||
private final ImageView icon;
|
||||
|
||||
public FilterHolder(View itemView) {
|
||||
super(itemView);
|
||||
text = (TextView) ViewUtils.$$(itemView, R.id.text);
|
||||
icon = (ImageView) itemView.findViewById(R.id.icon);
|
||||
|
||||
if (null != icon) {
|
||||
icon.setOnClickListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
int position = getAdapterPosition();
|
||||
if (position < 0 || null == mFilterList) {
|
||||
return;
|
||||
}
|
||||
Filter filter = mFilterList.get(position);
|
||||
if (FilterList.MODE_HEADER != filter.mode) {
|
||||
showDeleteFilterDialog(filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class FilterAdapter extends RecyclerView.Adapter<FilterHolder> {
|
||||
|
||||
private static final int TYPE_ITEM = 0;
|
||||
private static final int TYPE_HEADER = 1;
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
if (null == mFilterList) {
|
||||
return TYPE_ITEM;
|
||||
}
|
||||
|
||||
if (mFilterList.get(position).mode == FilterList.MODE_HEADER) {
|
||||
return TYPE_HEADER;
|
||||
} else {
|
||||
return TYPE_ITEM;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
int layoutId;
|
||||
switch (viewType) {
|
||||
default:
|
||||
case TYPE_ITEM:
|
||||
layoutId = R.layout.item_filter;
|
||||
break;
|
||||
case TYPE_HEADER:
|
||||
layoutId = R.layout.item_filter_header;
|
||||
break;
|
||||
}
|
||||
|
||||
FilterHolder holder = new FilterHolder(getLayoutInflater().inflate(layoutId, parent, false));
|
||||
|
||||
if (R.layout.item_filter == layoutId) {
|
||||
holder.icon.setImageDrawable(
|
||||
DrawableManager.getDrawable(FilterActivity.this, R.drawable.v_delete_x24));
|
||||
}
|
||||
|
||||
return holder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(FilterHolder holder, int position) {
|
||||
if (null == mFilterList) {
|
||||
return;
|
||||
}
|
||||
|
||||
Filter filter = mFilterList.get(position);
|
||||
if (FilterList.MODE_HEADER == filter.mode) {
|
||||
holder.text.setText(filter.text);
|
||||
} else {
|
||||
holder.text.setText(filter.text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return null != mFilterList ? mFilterList.size(): 0;
|
||||
}
|
||||
}
|
||||
|
||||
private class FilterList {
|
||||
|
||||
public static final int MODE_HEADER = -1;
|
||||
|
||||
private final EhFilter mEhFilter;
|
||||
private final List<Filter> mTitleFilterList;
|
||||
private final List<Filter> mUploaderFilterList;
|
||||
private final List<Filter> mTagFilterList;
|
||||
private final List<Filter> mTagNamespaceFilterList;
|
||||
|
||||
private Filter mTitleHeader;
|
||||
private Filter mUploaderHeader;
|
||||
private Filter mTagHeader;
|
||||
private Filter mTagNamespaceHeader;
|
||||
|
||||
public FilterList() {
|
||||
mEhFilter = EhFilter.getInstance();
|
||||
mTitleFilterList = mEhFilter.getTitleFilterList();
|
||||
mUploaderFilterList = mEhFilter.getUploaderFilterList();
|
||||
mTagFilterList = mEhFilter.getTagFilterList();
|
||||
mTagNamespaceFilterList = mEhFilter.getTagNamespaceFilterList();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
int count = 0;
|
||||
int size = mTitleFilterList.size();
|
||||
count += 0 == size ? 0 : size + 1;
|
||||
size = mUploaderFilterList.size();
|
||||
count += 0 == size ? 0 : size + 1;
|
||||
size = mTagFilterList.size();
|
||||
count += 0 == size ? 0 : size + 1;
|
||||
size = mTagNamespaceFilterList.size();
|
||||
count += 0 == size ? 0 : size + 1;
|
||||
return count;
|
||||
}
|
||||
|
||||
private Filter getTitleHeader() {
|
||||
if (null == mTitleHeader) {
|
||||
mTitleHeader = new Filter();
|
||||
mTitleHeader.mode = MODE_HEADER;
|
||||
mTitleHeader.text = getString(R.string.filter_title);
|
||||
}
|
||||
return mTitleHeader;
|
||||
}
|
||||
|
||||
private Filter getUploaderHeader() {
|
||||
if (null == mUploaderHeader) {
|
||||
mUploaderHeader = new Filter();
|
||||
mUploaderHeader.mode = MODE_HEADER;
|
||||
mUploaderHeader.text = getString(R.string.filter_uploader);
|
||||
}
|
||||
return mUploaderHeader;
|
||||
}
|
||||
|
||||
private Filter getTagHeader() {
|
||||
if (null == mTagHeader) {
|
||||
mTagHeader = new Filter();
|
||||
mTagHeader.mode = MODE_HEADER;
|
||||
mTagHeader.text = getString(R.string.filter_tag);
|
||||
}
|
||||
return mTagHeader;
|
||||
}
|
||||
|
||||
private Filter getTagNamespaceHeader() {
|
||||
if (null == mTagNamespaceHeader) {
|
||||
mTagNamespaceHeader = new Filter();
|
||||
mTagNamespaceHeader.mode = MODE_HEADER;
|
||||
mTagNamespaceHeader.text = getString(R.string.filter_tag_namespace);
|
||||
}
|
||||
return mTagNamespaceHeader;
|
||||
}
|
||||
|
||||
public Filter get(int index) {
|
||||
int size = mTitleFilterList.size();
|
||||
if (0 != size) {
|
||||
if (index == 0) {
|
||||
return getTitleHeader();
|
||||
} else if (index <= size) {
|
||||
return mTitleFilterList.get(index - 1);
|
||||
} else {
|
||||
index -= size + 1;
|
||||
}
|
||||
}
|
||||
|
||||
size = mUploaderFilterList.size();
|
||||
if (0 != size) {
|
||||
if (index == 0) {
|
||||
return getUploaderHeader();
|
||||
} else if (index <= size) {
|
||||
return mUploaderFilterList.get(index - 1);
|
||||
} else {
|
||||
index -= size + 1;
|
||||
}
|
||||
}
|
||||
|
||||
size = mTagFilterList.size();
|
||||
if (0 != size) {
|
||||
if (index == 0) {
|
||||
return getTagHeader();
|
||||
} else if (index <= size) {
|
||||
return mTagFilterList.get(index - 1);
|
||||
} else {
|
||||
index -= size + 1;
|
||||
}
|
||||
}
|
||||
|
||||
size = mTagNamespaceFilterList.size();
|
||||
if (0 != size) {
|
||||
if (index == 0) {
|
||||
return getTagNamespaceHeader();
|
||||
} else if (index <= size) {
|
||||
return mTagNamespaceFilterList.get(index - 1);
|
||||
} else {
|
||||
index -= size + 1;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
|
||||
public void add(Filter filter) {
|
||||
mEhFilter.addFilter(filter);
|
||||
}
|
||||
|
||||
public void delete(Filter filter) {
|
||||
mEhFilter.deleteFilter(filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,13 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.res.Resources;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
@@ -30,9 +34,14 @@ import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.SwitchCompat;
|
||||
import android.text.TextUtils;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.webkit.MimeTypeMap;
|
||||
import android.widget.CompoundButton;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
@@ -49,21 +58,25 @@ import com.hippo.ehviewer.gallery.ZipGalleryProvider;
|
||||
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
|
||||
import com.hippo.ehviewer.gallery.gl.GalleryView;
|
||||
import com.hippo.ehviewer.gallery.gl.ImageView;
|
||||
import com.hippo.ehviewer.widget.GalleryGuideView;
|
||||
import com.hippo.ehviewer.widget.ReversibleSeekBar;
|
||||
import com.hippo.gl.glrenderer.ImageTexture;
|
||||
import com.hippo.gl.view.GLRootView;
|
||||
import com.hippo.image.Image;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.util.SystemUiHelper;
|
||||
import com.hippo.widget.Slider;
|
||||
import com.hippo.widget.ColorView;
|
||||
import com.hippo.yorozuya.AnimationUtils;
|
||||
import com.hippo.yorozuya.ConcurrentPool;
|
||||
import com.hippo.yorozuya.MathUtils;
|
||||
import com.hippo.yorozuya.SimpleAnimatorListener;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class GalleryActivity extends TrackedActivity
|
||||
implements GalleryProviderListener, Slider.OnSetProgressListener,
|
||||
public class GalleryActivity extends EhActivity
|
||||
implements GalleryProviderListener, SeekBar.OnSeekBarChangeListener,
|
||||
GalleryView.Listener {
|
||||
|
||||
public static final String ACTION_DIR = "dir";
|
||||
@@ -72,9 +85,9 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
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_SHOWING = "showing";
|
||||
public static final String KEY_CURRENT_INDEX = "current_index";
|
||||
|
||||
private static final long SLIDER_ANIMATION_DURING = 150;
|
||||
@@ -82,6 +95,7 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
private String mAction;
|
||||
private String mFilename;
|
||||
private Uri mUri;
|
||||
private GalleryInfo mGalleryInfo;
|
||||
private int mPage;
|
||||
|
||||
@@ -95,20 +109,26 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
@Nullable
|
||||
private SystemUiHelper mSystemUiHelper;
|
||||
private boolean mSystemUiShowing = false;
|
||||
private boolean mShowSystemUi;
|
||||
|
||||
@Nullable
|
||||
private ColorView mMaskView;
|
||||
@Nullable
|
||||
private View mClock;
|
||||
@Nullable
|
||||
private TextView mProgress;
|
||||
@Nullable
|
||||
private View mBattery;
|
||||
@Nullable
|
||||
private View mSliderPanel;
|
||||
private View mSeekBarPanel;
|
||||
@Nullable
|
||||
private TextView mLeftText;
|
||||
@Nullable
|
||||
private TextView mRightText;
|
||||
@Nullable
|
||||
private Slider mSlider;
|
||||
private ReversibleSeekBar mSeekBar;
|
||||
|
||||
private ObjectAnimator mSeekBarPanelAnimator;
|
||||
|
||||
private int mLayoutMode;
|
||||
private int mSize;
|
||||
@@ -116,20 +136,28 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
private final ConcurrentPool<NotifyTask> mNotifyTaskPool = new ConcurrentPool<>(3);
|
||||
|
||||
private final Runnable mRequestLayoutSliderTask = new Runnable() {
|
||||
private final ValueAnimator.AnimatorUpdateListener mUpdateSliderListener = new ValueAnimator.AnimatorUpdateListener() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mSliderPanel != null) {
|
||||
mSliderPanel.requestLayout();
|
||||
public void onAnimationUpdate(ValueAnimator animation) {
|
||||
if (null != mSeekBarPanel) {
|
||||
mSeekBarPanel.requestLayout();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final SimpleAnimatorListener mShowSliderListener = new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mSeekBarPanelAnimator = null;
|
||||
}
|
||||
};
|
||||
|
||||
private final SimpleAnimatorListener mHideSliderListener = new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
if (mSliderPanel != null) {
|
||||
mSliderPanel.setVisibility(View.INVISIBLE);
|
||||
mSeekBarPanelAnimator = null;
|
||||
if (mSeekBarPanel != null) {
|
||||
mSeekBarPanel.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -137,8 +165,8 @@ public class GalleryActivity extends TrackedActivity
|
||||
private final Runnable mHideSliderRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mSliderPanel != null) {
|
||||
hideSlider(mSliderPanel);
|
||||
if (mSeekBarPanel != null) {
|
||||
hideSlider(mSeekBarPanel);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -160,6 +188,11 @@ public class GalleryActivity extends TrackedActivity
|
||||
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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +204,7 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
mAction = intent.getAction();
|
||||
mFilename = intent.getStringExtra(KEY_FILENAME);
|
||||
mUri = intent.getData();
|
||||
mGalleryInfo = intent.getParcelableExtra(KEY_GALLERY_INFO);
|
||||
mPage = intent.getIntExtra(KEY_PAGE, -1);
|
||||
buildProvider();
|
||||
@@ -179,6 +213,7 @@ public class GalleryActivity extends TrackedActivity
|
||||
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);
|
||||
@@ -190,16 +225,24 @@ public class GalleryActivity extends TrackedActivity
|
||||
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);
|
||||
}
|
||||
outState.putBoolean(KEY_SHOWING, mSystemUiShowing);
|
||||
outState.putInt(KEY_PAGE, mPage);
|
||||
outState.putInt(KEY_CURRENT_INDEX, mCurrentIndex);
|
||||
}
|
||||
|
||||
@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) {
|
||||
@@ -216,7 +259,7 @@ public class GalleryActivity extends TrackedActivity
|
||||
mGalleryProvider.start();
|
||||
|
||||
setContentView(R.layout.activity_gallery);
|
||||
GLRootView glRootView = (GLRootView) findViewById(R.id.gl_root_view);
|
||||
GLRootView glRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
|
||||
mGalleryProvider.setGLRoot(glRootView);
|
||||
mUploader = new ImageTexture.Uploader(glRootView);
|
||||
|
||||
@@ -233,37 +276,32 @@ public class GalleryActivity extends TrackedActivity
|
||||
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_LOW_PROFILE;
|
||||
}
|
||||
mSystemUiHelper = new SystemUiHelper(this, systemUiLevel,
|
||||
SystemUiHelper.FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES | SystemUiHelper.FLAG_IMMERSIVE_STICKY);
|
||||
if (savedInstanceState == null || !savedInstanceState.getBoolean(KEY_SHOWING, false)) {
|
||||
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();
|
||||
mSystemUiShowing = false;
|
||||
} else {
|
||||
mSystemUiHelper.show();
|
||||
mSystemUiShowing = true;
|
||||
mShowSystemUi = false;
|
||||
}
|
||||
|
||||
mClock = findViewById(R.id.clock);
|
||||
mBattery = findViewById(R.id.battery);
|
||||
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);
|
||||
|
||||
if (mClock != null && !Settings.getShowClock()) {
|
||||
mClock.setVisibility(View.GONE);
|
||||
}
|
||||
if (mBattery != null && !Settings.getShowBattery()) {
|
||||
mBattery.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
mSliderPanel = findViewById(R.id.slider_panel);
|
||||
mLeftText = (TextView) mSliderPanel.findViewById(R.id.left);
|
||||
mRightText = (TextView) mSliderPanel.findViewById(R.id.right);
|
||||
mSlider = (Slider) mSliderPanel.findViewById(R.id.slider);
|
||||
mSlider.setOnSetProgressListener(this);
|
||||
mSeekBarPanel = ViewUtils.$$(this, R.id.seek_bar_panel);
|
||||
mLeftText = (TextView) ViewUtils.$$(mSeekBarPanel, R.id.left);
|
||||
mRightText = (TextView) ViewUtils.$$(mSeekBarPanel, R.id.right);
|
||||
mSeekBar = (ReversibleSeekBar) ViewUtils.$$(mSeekBarPanel, R.id.seek_bar);
|
||||
mSeekBar.setOnSeekBarChangeListener(this);
|
||||
|
||||
mSize = mGalleryProvider.size();
|
||||
mCurrentIndex = startPage;
|
||||
@@ -276,6 +314,30 @@ public class GalleryActivity extends TrackedActivity
|
||||
} else {
|
||||
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
|
||||
// Orientation
|
||||
int orientation;
|
||||
switch (Settings.getScreenRotation()) {
|
||||
default:
|
||||
case 0:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
|
||||
break;
|
||||
case 1:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
|
||||
break;
|
||||
case 2:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
|
||||
break;
|
||||
}
|
||||
setRequestedOrientation(orientation);
|
||||
|
||||
// Screen lightness
|
||||
setScreenLightness(Settings.getCustomScreenLightness(), Settings.getScreenLightness());
|
||||
|
||||
if (Settings.getGuideGallery()) {
|
||||
FrameLayout mainLayout = (FrameLayout) ViewUtils.$$(this, R.id.main);
|
||||
mainLayout.addView(new GalleryGuideView(this));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -292,28 +354,16 @@ public class GalleryActivity extends TrackedActivity
|
||||
mGalleryProvider = null;
|
||||
}
|
||||
|
||||
mSliderPanel = null;
|
||||
mMaskView = null;
|
||||
mClock = null;
|
||||
mProgress = null;
|
||||
mBattery = null;
|
||||
mSeekBarPanel = null;
|
||||
mLeftText = null;
|
||||
mRightText = null;
|
||||
mSlider = null;
|
||||
}
|
||||
mSeekBar = null;
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
|
||||
if (null != mGalleryView) {
|
||||
mGalleryView.pause();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
if (null != mGalleryView) {
|
||||
mGalleryView.resume();
|
||||
}
|
||||
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -321,7 +371,7 @@ public class GalleryActivity extends TrackedActivity
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
|
||||
if (hasFocus && mSystemUiHelper != null) {
|
||||
if (mSystemUiShowing) {
|
||||
if (mShowSystemUi) {
|
||||
mSystemUiHelper.show();
|
||||
} else {
|
||||
mSystemUiHelper.hide();
|
||||
@@ -422,9 +472,21 @@ public class GalleryActivity extends TrackedActivity
|
||||
}
|
||||
}
|
||||
|
||||
@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 (mSlider == null || mRightText == null || mLeftText == null || mSize <= 0 || mCurrentIndex < 0) {
|
||||
if (mSeekBar == null || mRightText == null || mLeftText == null || mSize <= 0 || mCurrentIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -433,16 +495,16 @@ public class GalleryActivity extends TrackedActivity
|
||||
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
|
||||
start = mRightText;
|
||||
end = mLeftText;
|
||||
mSlider.setReverse(true);
|
||||
mSeekBar.setReverse(true);
|
||||
} else {
|
||||
start = mLeftText;
|
||||
end = mRightText;
|
||||
mSlider.setReverse(false);
|
||||
mSeekBar.setReverse(false);
|
||||
}
|
||||
start.setText(Integer.toString(mCurrentIndex + 1));
|
||||
end.setText(Integer.toString(mSize));
|
||||
mSlider.setRange(1, mSize);
|
||||
mSlider.setProgress(mCurrentIndex + 1);
|
||||
mSeekBar.setMax(mSize - 1);
|
||||
mSeekBar.setProgress(mCurrentIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -525,21 +587,31 @@ public class GalleryActivity extends TrackedActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSetProgress(Slider slider, int newProgress, int oldProgress,
|
||||
boolean byUser, boolean confirm) {
|
||||
if (confirm && byUser && mGalleryView != null) {
|
||||
mGalleryView.setCurrentPage(newProgress - 1);
|
||||
@SuppressLint("SetTextI18n")
|
||||
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
|
||||
TextView start;
|
||||
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
|
||||
start = mRightText;
|
||||
} else {
|
||||
start = mLeftText;
|
||||
}
|
||||
if (fromUser && null != start) {
|
||||
start.setText(Integer.toString(progress + 1));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFingerDown() {
|
||||
public void onStartTrackingTouch(SeekBar seekBar) {
|
||||
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFingerUp() {
|
||||
public void onStopTrackingTouch(SeekBar seekBar) {
|
||||
SimpleHandler.getInstance().postDelayed(mHideSliderRunnable, HIDE_SLIDER_DELAY);
|
||||
int progress = seekBar.getProgress();
|
||||
if (progress != mCurrentIndex && null != mGalleryView) {
|
||||
mGalleryView.setCurrentPage(progress);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -587,50 +659,126 @@ public class GalleryActivity extends TrackedActivity
|
||||
}
|
||||
|
||||
private void showSlider(View sliderPanel) {
|
||||
if (null != mSeekBarPanelAnimator) {
|
||||
mSeekBarPanelAnimator.cancel();
|
||||
mSeekBarPanelAnimator = null;
|
||||
}
|
||||
|
||||
sliderPanel.setTranslationY(sliderPanel.getHeight());
|
||||
sliderPanel.setVisibility(View.VISIBLE);
|
||||
sliderPanel.animate().translationY(0.0f).setDuration(SLIDER_ANIMATION_DURING)
|
||||
.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR)
|
||||
.setListener(null).start();
|
||||
// Request layout ensure show it
|
||||
SimpleHandler.getInstance().post(mRequestLayoutSliderTask);
|
||||
|
||||
mSeekBarPanelAnimator = ObjectAnimator.ofFloat(sliderPanel, "translationY", 0.0f);
|
||||
mSeekBarPanelAnimator.setDuration(SLIDER_ANIMATION_DURING);
|
||||
mSeekBarPanelAnimator.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
|
||||
mSeekBarPanelAnimator.addUpdateListener(mUpdateSliderListener);
|
||||
mSeekBarPanelAnimator.addListener(mShowSliderListener);
|
||||
mSeekBarPanelAnimator.start();
|
||||
|
||||
if (null != mSystemUiHelper) {
|
||||
mSystemUiHelper.show();
|
||||
mShowSystemUi = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void hideSlider(View sliderPanel) {
|
||||
sliderPanel.animate().translationY(sliderPanel.getHeight()).setDuration(SLIDER_ANIMATION_DURING)
|
||||
.setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR)
|
||||
.setListener(mHideSliderListener).start();
|
||||
if (null != mSeekBarPanelAnimator) {
|
||||
mSeekBarPanelAnimator.cancel();
|
||||
mSeekBarPanelAnimator = null;
|
||||
}
|
||||
|
||||
mSeekBarPanelAnimator = ObjectAnimator.ofFloat(sliderPanel, "translationY", sliderPanel.getHeight());
|
||||
mSeekBarPanelAnimator.setDuration(SLIDER_ANIMATION_DURING);
|
||||
mSeekBarPanelAnimator.setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR);
|
||||
mSeekBarPanelAnimator.addUpdateListener(mUpdateSliderListener);
|
||||
mSeekBarPanelAnimator.addListener(mHideSliderListener);
|
||||
mSeekBarPanelAnimator.start();
|
||||
|
||||
if (null != mSystemUiHelper) {
|
||||
mSystemUiHelper.hide();
|
||||
mShowSystemUi = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param lightness 0 - 200
|
||||
*/
|
||||
private void setScreenLightness(boolean enable, int lightness) {
|
||||
if (null == mMaskView) {
|
||||
return;
|
||||
}
|
||||
|
||||
Window w = getWindow();
|
||||
WindowManager.LayoutParams lp = w.getAttributes();
|
||||
if (enable) {
|
||||
lightness = MathUtils.clamp(lightness, 0, 200);
|
||||
if (lightness > 100) {
|
||||
mMaskView.setColor(0);
|
||||
// Avoid BRIGHTNESS_OVERRIDE_OFF,
|
||||
// screen may be off when lp.screenBrightness is 0.0f
|
||||
lp.screenBrightness = Math.max((lightness - 100) / 100.0f, 0.01f);
|
||||
} else {
|
||||
mMaskView.setColor(MathUtils.lerp(0xde, 0x00, lightness / 100.0f) << 24);
|
||||
lp.screenBrightness = 0.01f;
|
||||
}
|
||||
} else {
|
||||
mMaskView.setColor(0);
|
||||
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
|
||||
}
|
||||
w.setAttributes(lp);
|
||||
}
|
||||
|
||||
private class GalleryMenuHelper implements DialogInterface.OnClickListener {
|
||||
|
||||
private final View mView;
|
||||
private final Spinner mScreenRotation;
|
||||
private final Spinner mReadingDirection;
|
||||
private final Spinner mScaleMode;
|
||||
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;
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
public GalleryMenuHelper() {
|
||||
mView = getLayoutInflater().inflate(R.layout.dialog_gallery_menu, null);
|
||||
public GalleryMenuHelper(Context context) {
|
||||
mView = LayoutInflater.from(context).inflate(R.layout.dialog_gallery_menu, null);
|
||||
mScreenRotation = (Spinner) mView.findViewById(R.id.screen_rotation);
|
||||
mReadingDirection = (Spinner) mView.findViewById(R.id.reading_direction);
|
||||
mScaleMode = (Spinner) mView.findViewById(R.id.page_scaling);
|
||||
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);
|
||||
|
||||
mScreenRotation.setSelection(Settings.getScreenRotation());
|
||||
mReadingDirection.setSelection(Settings.getReadingDirection());
|
||||
mScaleMode.setSelection(Settings.getPageScaling());
|
||||
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());
|
||||
|
||||
mCustomScreenLightness.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
|
||||
@Override
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
mScreenLightness.setEnabled(isChecked);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public View getView() {
|
||||
@@ -639,22 +787,48 @@ public class GalleryActivity extends TrackedActivity
|
||||
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
int screenRotation = mScreenRotation.getSelectedItemPosition();
|
||||
int layoutMode = GalleryView.sanitizeLayoutMode(mReadingDirection.getSelectedItemPosition());
|
||||
int scaleMode = ImageView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
|
||||
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);
|
||||
|
||||
int orientation;
|
||||
switch (screenRotation) {
|
||||
default:
|
||||
case 0:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
|
||||
break;
|
||||
case 1:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
|
||||
break;
|
||||
case 2:
|
||||
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
|
||||
break;
|
||||
}
|
||||
setRequestedOrientation(orientation);
|
||||
if (mGalleryView != null) {
|
||||
mGalleryView.setLayoutMode(layoutMode);
|
||||
mGalleryView.setScaleMode(scaleMode);
|
||||
@@ -668,13 +842,21 @@ public class GalleryActivity extends TrackedActivity
|
||||
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);
|
||||
}
|
||||
setScreenLightness(customScreenLightness, screenLightness);
|
||||
|
||||
// Update slider
|
||||
mLayoutMode = layoutMode;
|
||||
updateSlider();
|
||||
|
||||
if (oldReadingFullscreen != readingFullscreen) {
|
||||
recreate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -773,24 +955,24 @@ public class GalleryActivity extends TrackedActivity
|
||||
}
|
||||
|
||||
private void onTapMenuArea() {
|
||||
GalleryMenuHelper helper = new GalleryMenuHelper();
|
||||
new AlertDialog.Builder(GalleryActivity.this)
|
||||
.setTitle(R.string.gallery_menu_title)
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryActivity.this);
|
||||
GalleryMenuHelper helper = new GalleryMenuHelper(builder.getContext());
|
||||
builder.setTitle(R.string.gallery_menu_title)
|
||||
.setView(helper.getView())
|
||||
.setPositiveButton(android.R.string.ok, helper).show();
|
||||
}
|
||||
|
||||
private void onTapSliderArea() {
|
||||
if (mSliderPanel == null || mSize <= 0 || mCurrentIndex < 0) {
|
||||
if (mSeekBarPanel == null || mSize <= 0 || mCurrentIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
|
||||
|
||||
if (mSliderPanel.getVisibility() == View.VISIBLE) {
|
||||
hideSlider(mSliderPanel);
|
||||
if (mSeekBarPanel.getVisibility() == View.VISIBLE) {
|
||||
hideSlider(mSeekBarPanel);
|
||||
} else {
|
||||
showSlider(mSliderPanel);
|
||||
showSlider(mSeekBarPanel);
|
||||
SimpleHandler.getInstance().postDelayed(mHideSliderRunnable, HIDE_SLIDER_DELAY);
|
||||
}
|
||||
}
|
||||
@@ -809,10 +991,12 @@ public class GalleryActivity extends TrackedActivity
|
||||
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();
|
||||
|
||||
@@ -19,6 +19,8 @@ package com.hippo.ehviewer.ui;
|
||||
import android.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.PersistableBundle;
|
||||
@@ -28,7 +30,7 @@ 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;
|
||||
import android.view.Gravity;
|
||||
@@ -38,11 +40,14 @@ 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;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.EhUrlOpener;
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.ListUrlBuilder;
|
||||
import com.hippo.ehviewer.ui.scene.AnalyticsScene;
|
||||
import com.hippo.ehviewer.ui.scene.BaseScene;
|
||||
import com.hippo.ehviewer.ui.scene.CookieSignInScene;
|
||||
@@ -58,16 +63,29 @@ import com.hippo.ehviewer.ui.scene.GalleryPreviewsScene;
|
||||
import com.hippo.ehviewer.ui.scene.HistoryScene;
|
||||
import com.hippo.ehviewer.ui.scene.ProgressScene;
|
||||
import com.hippo.ehviewer.ui.scene.QuickSearchScene;
|
||||
import com.hippo.ehviewer.ui.scene.SecurityScene;
|
||||
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;
|
||||
import com.hippo.scene.StageActivity;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.util.BitmapUtils;
|
||||
import com.hippo.util.PermissionRequester;
|
||||
import com.hippo.widget.LoadImageView;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
import com.hippo.yorozuya.ResourcesUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public final class MainActivity extends StageActivity
|
||||
implements NavigationView.OnNavigationItemSelectedListener {
|
||||
|
||||
@@ -75,14 +93,16 @@ public final class MainActivity extends StageActivity
|
||||
|
||||
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
|
||||
|
||||
private static final int REQUEST_CODE_UPDATE_PROFILE = 0;
|
||||
private static final int REQUEST_CODE_SETTINGS = 0;
|
||||
|
||||
private static final String KEY_NAV_CHECKED_ITEM = "nav_checked_item";
|
||||
|
||||
public static final int CHECK_STEP_WARNING = 0;
|
||||
public static final int CHECK_STEP_ANALYTICS = 1;
|
||||
public static final int CHECK_STEP_CRASH = 2;
|
||||
public static final int CHECK_STEP_SIGN_IN = 3;
|
||||
public static final int CHECK_STEP_SECURITY = 0;
|
||||
public static final int CHECK_STEP_WARNING = 1;
|
||||
public static final int CHECK_STEP_ANALYTICS = 2;
|
||||
public static final int CHECK_STEP_CRASH = 3;
|
||||
public static final int CHECK_STEP_SIGN_IN = 4;
|
||||
public static final int CHECK_STEP_SELECT_SITE = 5;
|
||||
|
||||
public static final String KEY_TARGET_SCENE = "target_scene";
|
||||
public static final String KEY_TARGET_ARGS = "target_args";
|
||||
@@ -91,7 +111,7 @@ public final class MainActivity extends StageActivity
|
||||
Whole life cycle
|
||||
---------------*/
|
||||
@Nullable
|
||||
private DrawerLayout mDrawerLayout;
|
||||
private EhDrawerLayout mDrawerLayout;
|
||||
@Nullable
|
||||
private NavigationView mNavView;
|
||||
@Nullable
|
||||
@@ -104,12 +124,14 @@ public final class MainActivity extends StageActivity
|
||||
private int mNavCheckedItem = 0;
|
||||
|
||||
static {
|
||||
registerLaunchMode(SecurityScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(WarningScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(AnalyticsScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(CrashScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(SignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(WebViewSignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(CookieSignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(SelectSiteScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(GalleryListScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TOP);
|
||||
registerLaunchMode(QuickSearchScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
|
||||
registerLaunchMode(GalleryDetailScene.class, SceneFragment.LAUNCH_MODE_STANDARD);
|
||||
@@ -125,6 +147,11 @@ public final class MainActivity extends StageActivity
|
||||
|
||||
public void startSceneForCheckStep(int checkStep, Bundle args) {
|
||||
switch (checkStep) {
|
||||
case CHECK_STEP_SECURITY:
|
||||
if (Settings.getShowWarning()) {
|
||||
startScene(new Announcer(WarningScene.class).setArgs(args));
|
||||
break;
|
||||
}
|
||||
case CHECK_STEP_WARNING:
|
||||
if (Settings.getAskAnalytics()) {
|
||||
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
|
||||
@@ -136,11 +163,16 @@ public final class MainActivity extends StageActivity
|
||||
break;
|
||||
}
|
||||
case CHECK_STEP_CRASH:
|
||||
if (!EhUtils.hasSignedIn(this)) {
|
||||
if (EhUtils.needSignedIn(this)) {
|
||||
startScene(new Announcer(SignInScene.class).setArgs(args));
|
||||
break;
|
||||
}
|
||||
case CHECK_STEP_SIGN_IN:
|
||||
if (Settings.getSelectSite()) {
|
||||
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
|
||||
break;
|
||||
}
|
||||
case CHECK_STEP_SELECT_SITE:
|
||||
String targetScene = null;
|
||||
Bundle targetArgs = null;
|
||||
if (null != args) {
|
||||
@@ -176,14 +208,18 @@ public final class MainActivity extends StageActivity
|
||||
@Nullable
|
||||
@Override
|
||||
protected Announcer getLaunchAnnouncer() {
|
||||
if (Settings.getShowWarning()) {
|
||||
if (!TextUtils.isEmpty(Settings.getSecurity())) {
|
||||
return new Announcer(SecurityScene.class);
|
||||
} else if (Settings.getShowWarning()) {
|
||||
return new Announcer(WarningScene.class);
|
||||
} else if (Settings.getAskAnalytics()) {
|
||||
return new Announcer(AnalyticsScene.class);
|
||||
} else if (Crash.hasCrashFile()) {
|
||||
return new Announcer(CrashScene.class);
|
||||
} else if (!EhUtils.hasSignedIn(this)) {
|
||||
} else if (EhUtils.needSignedIn(this)) {
|
||||
return new Announcer(SignInScene.class);
|
||||
} else if (Settings.getSelectSite()) {
|
||||
return new Announcer(SelectSiteScene.class);
|
||||
} else {
|
||||
Bundle args = new Bundle();
|
||||
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
|
||||
@@ -194,7 +230,12 @@ public final class MainActivity extends StageActivity
|
||||
// Sometimes scene can't show directly
|
||||
private Announcer processAnnouncer(Announcer announcer) {
|
||||
if (0 == getSceneCount()) {
|
||||
if (Settings.getShowWarning()) {
|
||||
if (!TextUtils.isEmpty(Settings.getSecurity())) {
|
||||
Bundle newArgs = new Bundle();
|
||||
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
|
||||
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
|
||||
return new Announcer(SecurityScene.class).setArgs(newArgs);
|
||||
} else if (Settings.getShowWarning()) {
|
||||
Bundle newArgs = new Bundle();
|
||||
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
|
||||
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
|
||||
@@ -209,16 +250,53 @@ public final class MainActivity extends StageActivity
|
||||
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
|
||||
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
|
||||
return new Announcer(CrashScene.class).setArgs(newArgs);
|
||||
} else if (!EhUtils.hasSignedIn(this)) {
|
||||
} else if (EhUtils.needSignedIn(this)) {
|
||||
Bundle newArgs = new Bundle();
|
||||
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
|
||||
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
|
||||
return new Announcer(SignInScene.class).setArgs(newArgs);
|
||||
} else if (Settings.getSelectSite()) {
|
||||
Bundle newArgs = new Bundle();
|
||||
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
|
||||
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
|
||||
return new Announcer(SelectSiteScene.class).setArgs(newArgs);
|
||||
}
|
||||
}
|
||||
return announcer;
|
||||
}
|
||||
|
||||
private File saveImageToTempFile(UniFile file) {
|
||||
if (null == file) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Bitmap bitmap = null;
|
||||
try {
|
||||
bitmap = BitmapUtils.decodeStream(new UniFileInputStreamPipe(file), -1, -1, 500 * 500, false, false, null);
|
||||
} catch (OutOfMemoryError e) {
|
||||
// Ignore
|
||||
}
|
||||
if (null == bitmap) {
|
||||
return null;
|
||||
}
|
||||
|
||||
File temp = AppConfig.createTempFile();
|
||||
if (null == temp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
OutputStream os = null;
|
||||
try {
|
||||
os = new FileOutputStream(temp);
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
|
||||
return temp;
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
} finally {
|
||||
IOUtils.closeQuietly(os);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean handleIntent(Intent intent) {
|
||||
if (intent == null) {
|
||||
return false;
|
||||
@@ -231,6 +309,29 @@ public final class MainActivity extends StageActivity
|
||||
startScene(processAnnouncer(announcer));
|
||||
return true;
|
||||
}
|
||||
} else if (Intent.ACTION_SEND.equals(action)) {
|
||||
String type = intent.getType();
|
||||
if ("text/plain".equals(type)) {
|
||||
ListUrlBuilder builder = new ListUrlBuilder();
|
||||
builder.setKeyword(intent.getStringExtra(Intent.EXTRA_TEXT));
|
||||
startScene(processAnnouncer(GalleryListScene.getStartAnnouncer(builder)));
|
||||
return true;
|
||||
} else if (type.startsWith("image/")) {
|
||||
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
|
||||
if (null != uri) {
|
||||
UniFile file = UniFile.fromUri(this, uri);
|
||||
File temp = saveImageToTempFile(file);
|
||||
if (null != temp) {
|
||||
ListUrlBuilder builder = new ListUrlBuilder();
|
||||
builder.setMode(ListUrlBuilder.MODE_IMAGE_SEARCH);
|
||||
builder.setImagePath(temp.getPath());
|
||||
builder.setUseSimilarityScan(true);
|
||||
builder.setShowExpunged(true);
|
||||
startScene(processAnnouncer(GalleryListScene.getStartAnnouncer(builder)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -239,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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,13 +368,14 @@ public final class MainActivity extends StageActivity
|
||||
protected void onCreate2(@Nullable Bundle savedInstanceState) {
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
mDrawerLayout = (DrawerLayout) 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);
|
||||
mAvatar = (LoadImageView) ViewUtils.$$(headerLayout, R.id.avatar);
|
||||
mDisplayName = (TextView) ViewUtils.$$(headerLayout, R.id.display_name);
|
||||
|
||||
mDrawerLayout.setStatusBarColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimaryDark));
|
||||
// Pre-L need shadow drawable
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
|
||||
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow_left, Gravity.LEFT);
|
||||
@@ -280,11 +391,25 @@ public final class MainActivity extends StageActivity
|
||||
if (savedInstanceState == null) {
|
||||
onInit();
|
||||
CommonOperations.checkUpdate(this, false);
|
||||
checkDownloadLocation();
|
||||
} else {
|
||||
onRestore(savedInstanceState);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkDownloadLocation() {
|
||||
UniFile uniFile = Settings.getDownloadLocation();
|
||||
// null == uniFile for first start
|
||||
if (null == uniFile || uniFile.ensureDir()) {
|
||||
return;
|
||||
}
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.waring)
|
||||
.setMessage(R.string.invalid_download_location)
|
||||
.setPositiveButton(R.string.get_it, null)
|
||||
.show();
|
||||
}
|
||||
|
||||
private void onInit() {
|
||||
// Check permission
|
||||
PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
|
||||
@@ -339,7 +464,7 @@ public final class MainActivity extends StageActivity
|
||||
BaseScene baseScene = (BaseScene) scene;
|
||||
mRightDrawer.removeAllViews();
|
||||
View drawerView = baseScene.onCreateDrawerView(
|
||||
getLayoutInflater(), mRightDrawer, savedInstanceState);
|
||||
baseScene.getLayoutInflater2(), mRightDrawer, savedInstanceState);
|
||||
if (drawerView != null) {
|
||||
mRightDrawer.addView(drawerView);
|
||||
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
|
||||
@@ -378,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);
|
||||
@@ -479,7 +616,7 @@ public final class MainActivity extends StageActivity
|
||||
startScene(new Announcer(DownloadsScene.class));
|
||||
} else if (id == R.id.nav_settings) {
|
||||
Intent intent = new Intent(this, SettingsActivity.class);
|
||||
startActivity(intent);
|
||||
startActivityForResult(intent, REQUEST_CODE_SETTINGS);
|
||||
}
|
||||
|
||||
if (id != R.id.nav_stub && mDrawerLayout != null) {
|
||||
@@ -488,4 +625,18 @@ public final class MainActivity extends StageActivity
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
switch (requestCode) {
|
||||
case REQUEST_CODE_SETTINGS:
|
||||
if (RESULT_OK == resultCode) {
|
||||
refreshTopScene();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* 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.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.text.TextUtils;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.widget.lockpattern.LockPatternUtils;
|
||||
import com.hippo.widget.lockpattern.LockPatternView;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
public class SetSecurityActivity extends ToolbarActivity implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
private LockPatternView mPatternView;
|
||||
@Nullable
|
||||
private View mCancel;
|
||||
@Nullable
|
||||
private View mSet;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_set_security);
|
||||
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
|
||||
|
||||
mPatternView = (LockPatternView) ViewUtils.$$(this, R.id.pattern_view);
|
||||
mCancel = ViewUtils.$$(this, R.id.cancel);
|
||||
mSet = ViewUtils.$$(this, R.id.set);
|
||||
|
||||
String pattern = Settings.getSecurity();
|
||||
if (!TextUtils.isEmpty(pattern)) {
|
||||
mPatternView.setPattern(LockPatternView.DisplayMode.Correct,
|
||||
LockPatternUtils.stringToPattern(pattern));
|
||||
}
|
||||
|
||||
mCancel.setOnClickListener(this);
|
||||
mSet.setOnClickListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
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) {
|
||||
finish();
|
||||
} else if (v == mSet) {
|
||||
if (null != mPatternView) {
|
||||
String security;
|
||||
if (mPatternView.getCellSize() <= 1) {
|
||||
security = "";
|
||||
} else {
|
||||
security = mPatternView.getPatternString();
|
||||
}
|
||||
Settings.putSecurity(security);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ import com.hippo.util.DrawableManager;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
|
||||
public final class SettingsActivity extends TrackedPreferenceActivity {
|
||||
public final class SettingsActivity extends EhPreferenceActivity {
|
||||
|
||||
private static final int REQUEST_CODE_FRAGMENT = 0;
|
||||
|
||||
@@ -189,7 +189,7 @@ public final class SettingsActivity extends TrackedPreferenceActivity {
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
if (requestCode == REQUEST_CODE_FRAGMENT) {
|
||||
if (resultCode == RESULT_OK) {
|
||||
setResult(RESULT_OK, data);
|
||||
setResult(RESULT_OK);
|
||||
}
|
||||
} else {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
|
||||
@@ -26,7 +26,7 @@ import android.view.ViewGroup;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
|
||||
public class ToolbarActivity extends TrackedActivity {
|
||||
public class ToolbarActivity extends EhActivity {
|
||||
|
||||
@Override
|
||||
public void setContentView(@LayoutRes int layoutResID) {
|
||||
|
||||
@@ -25,20 +25,14 @@ import com.hippo.ehviewer.Analytics;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.UrlOpener;
|
||||
import com.hippo.ehviewer.ui.CommonOperations;
|
||||
import com.hippo.util.ActivityHelper;
|
||||
import com.hippo.util.AppHelper;
|
||||
|
||||
public class AboutFragment extends PreferenceFragment
|
||||
implements Preference.OnPreferenceChangeListener,
|
||||
Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_AUTHOR = "author";
|
||||
private static final String KEY_GOOGLE_PLUS = "google_plus";
|
||||
private static final String KEY_WEBSITE = "website";
|
||||
private static final String KEY_SOURCE = "source";
|
||||
private static final String KEY_CHANGELOG = "changelog";
|
||||
private static final String KEY_LICENSE = "license";
|
||||
private static final String KEY_DONATE = "donate";
|
||||
private static final String KEY_CHECK_FOR_UPDATES = "check_for_updates";
|
||||
|
||||
@@ -48,11 +42,7 @@ public class AboutFragment extends PreferenceFragment
|
||||
addPreferencesFromResource(R.xml.about_settings);
|
||||
|
||||
Preference author = findPreference(KEY_AUTHOR);
|
||||
Preference googlePlus = findPreference(KEY_GOOGLE_PLUS);
|
||||
Preference enableAnalytics = findPreference(Settings.KEY_ENABLE_ANALYTICS);
|
||||
Preference website = findPreference(KEY_WEBSITE);
|
||||
Preference source = findPreference(KEY_SOURCE);
|
||||
Preference changelog = findPreference(KEY_CHANGELOG);
|
||||
Preference donate = findPreference(KEY_DONATE);
|
||||
Preference checkForUpdate = findPreference(KEY_CHECK_FOR_UPDATES);
|
||||
|
||||
@@ -60,10 +50,6 @@ public class AboutFragment extends PreferenceFragment
|
||||
donate.setSummary(getString(R.string.settings_about_donate_summary).replace('$', '@'));
|
||||
|
||||
author.setOnPreferenceClickListener(this);
|
||||
googlePlus.setOnPreferenceClickListener(this);
|
||||
website.setOnPreferenceClickListener(this);
|
||||
source.setOnPreferenceClickListener(this);
|
||||
changelog.setOnPreferenceClickListener(this);
|
||||
donate.setOnPreferenceClickListener(this);
|
||||
checkForUpdate.setOnPreferenceClickListener(this);
|
||||
|
||||
@@ -86,20 +72,8 @@ 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_GOOGLE_PLUS.equals(key)) {
|
||||
UrlOpener.openUrl(getActivity(), "https://plus.google.com/communities/103823982034655188459",
|
||||
false, true);
|
||||
} else if (KEY_WEBSITE.equals(key)) {
|
||||
UrlOpener.openUrl(getActivity(), "http://www.ehviewer.com",
|
||||
false, true);
|
||||
} else if (KEY_SOURCE.equals(key)) {
|
||||
UrlOpener.openUrl(getActivity(), "https://github.com/seven332/EhViewer",
|
||||
false, true);
|
||||
} else if (KEY_CHANGELOG.equals(key)) {
|
||||
UrlOpener.openUrl(getActivity(), "http://www.ehviewer.com/changlog",
|
||||
false, true);
|
||||
} else if (KEY_DONATE.equals(key)) {
|
||||
new AlertDialog.Builder(getActivity())
|
||||
.setTitle(R.string.settings_about_donate)
|
||||
|
||||
@@ -16,22 +16,35 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.fragment;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Bundle;
|
||||
import android.preference.Preference;
|
||||
import android.preference.PreferenceFragment;
|
||||
import android.text.TextUtils;
|
||||
import android.widget.Toast;
|
||||
|
||||
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.util.LogCat;
|
||||
import com.hippo.util.ReadableTime;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AdvancedFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_DUMP_LOGCAT = "dump_logcat";
|
||||
private static final String KEY_CLEAR_MEMORY_CACHE = "clear_memory_cache";
|
||||
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
|
||||
private static final String KEY_EXPORT_DATA = "export_data";
|
||||
private static final String KEY_IMPORT_DATA = "import_data";
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
@@ -39,8 +52,24 @@ public class AdvancedFragment extends PreferenceFragment implements Preference.O
|
||||
addPreferencesFromResource(R.xml.advanced_settings);
|
||||
|
||||
Preference dumpLogcat = findPreference(KEY_DUMP_LOGCAT);
|
||||
Preference clearMemoryCache = findPreference(KEY_CLEAR_MEMORY_CACHE);
|
||||
Preference exportData = findPreference(KEY_EXPORT_DATA);
|
||||
Preference importData = findPreference(KEY_IMPORT_DATA);
|
||||
|
||||
dumpLogcat.setOnPreferenceClickListener(this);
|
||||
clearMemoryCache.setOnPreferenceClickListener(this);
|
||||
exportData.setOnPreferenceClickListener(this);
|
||||
importData.setOnPreferenceClickListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
|
||||
Preference patternProtection = findPreference(KEY_PATTERN_PROTECTION);
|
||||
patternProtection.setSummary(TextUtils.isEmpty(Settings.getSecurity()) ?
|
||||
R.string.settings_advanced_pattern_protection_not_set :
|
||||
R.string.settings_advanced_pattern_protection_set);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -58,10 +87,54 @@ public class AdvancedFragment extends PreferenceFragment implements Preference.O
|
||||
}
|
||||
Resources resources = getResources();
|
||||
Toast.makeText(getActivity(),
|
||||
ok ? resources.getString(R.string.settings_about_dump_logcat_to, file.getPath()) :
|
||||
resources.getString(R.string.settings_about_dump_logcat_failed), Toast.LENGTH_SHORT).show();
|
||||
ok ? resources.getString(R.string.settings_advanced_dump_logcat_to, file.getPath()) :
|
||||
resources.getString(R.string.settings_advanced_dump_logcat_failed), Toast.LENGTH_SHORT).show();
|
||||
return true;
|
||||
} else if (KEY_CLEAR_MEMORY_CACHE.equals(key)) {
|
||||
((EhApplication) getActivity().getApplication()).clearMemoryCache();
|
||||
Runtime.getRuntime().gc();
|
||||
} else if (KEY_EXPORT_DATA.equals(key)) {
|
||||
File dir = AppConfig.getExternalDataDir();
|
||||
if (dir != null) {
|
||||
File file = new File(dir, ReadableTime.getFilenamableTime(System.currentTimeMillis()) + ".db");
|
||||
if (EhDB.exportDB(getActivity(), file)) {
|
||||
Toast.makeText(getActivity(),
|
||||
getString(R.string.settings_advanced_export_data_to, file.getPath()), Toast.LENGTH_SHORT).show();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Toast.makeText(getActivity(),R.string.settings_advanced_export_data_failed, Toast.LENGTH_SHORT).show();
|
||||
return true;
|
||||
} else if (KEY_IMPORT_DATA.equals(key)) {
|
||||
importData(getActivity());
|
||||
getActivity().setResult(Activity.RESULT_OK);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void importData(final Context context) {
|
||||
final File dir = AppConfig.getExternalDataDir();
|
||||
if (null == dir) {
|
||||
Toast.makeText(context, R.string.cant_get_data_dir, Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
final String[] files = dir.list();
|
||||
if (null == files || files.length <= 0) {
|
||||
Toast.makeText(context, R.string.cant_find_any_data, Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
Arrays.sort(files);
|
||||
new AlertDialog.Builder(context).setItems(files, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
File file = new File(dir, files[which]);
|
||||
String error = EhDB.importDB(context, file);
|
||||
if (null == error) {
|
||||
error = context.getString(R.string.settings_advanced_import_data_successfully);
|
||||
}
|
||||
Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
}
|
||||
@@ -16,51 +16,33 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.fragment;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Parcel;
|
||||
import android.preference.Preference;
|
||||
import android.preference.PreferenceFragment;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.hippo.app.ProgressDialog;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.EhDB;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.EhClient;
|
||||
import com.hippo.ehviewer.client.EhRequest;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.ehviewer.spider.SpiderQueen;
|
||||
import com.hippo.ehviewer.ui.CommonOperations;
|
||||
import com.hippo.ehviewer.ui.DirPickerActivity;
|
||||
import com.hippo.unifile.UniFile;
|
||||
import com.hippo.yorozuya.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DownloadFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String TAG = DownloadFragment.class.getSimpleName();
|
||||
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;
|
||||
|
||||
public static final String KEY_DOWNLOAD_LOCATION = "download_location";
|
||||
public static final String KEY_RESTORE_DOWNLOAD_ITEMS = "restore_download_items";
|
||||
|
||||
@Nullable
|
||||
private Preference mDownloadLocation;
|
||||
@@ -70,15 +52,18 @@ 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);
|
||||
Preference restoreDownloadItems = findPreference(KEY_RESTORE_DOWNLOAD_ITEMS);
|
||||
|
||||
onUpdateDownloadLocation();
|
||||
|
||||
mediaScan.setOnPreferenceChangeListener(this);
|
||||
imageResolution.setOnPreferenceChangeListener(this);
|
||||
|
||||
if (mDownloadLocation != null) {
|
||||
mDownloadLocation.setOnPreferenceClickListener(this);
|
||||
}
|
||||
restoreDownloadItems.setOnPreferenceClickListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -111,18 +96,13 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
|
||||
showDirPickerDialogL();
|
||||
}
|
||||
return true;
|
||||
} else if (KEY_RESTORE_DOWNLOAD_ITEMS.equals(key)) {
|
||||
ProgressDialog dialog = ProgressDialog.show(getActivity(), null,
|
||||
getString(R.string.settings_download_restoring), true, false);
|
||||
new RestoreTask(dialog).execute();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void showDirPickerDialogKK() {
|
||||
new AlertDialog.Builder(getActivity()).setMessage(R.string.settings_download_pick_dir_kk)
|
||||
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
|
||||
.setPositiveButton(R.string.settings_download_continue, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
openDirPicker();
|
||||
@@ -146,7 +126,7 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
|
||||
};
|
||||
|
||||
new AlertDialog.Builder(getActivity()).setMessage(R.string.settings_download_pick_dir_l)
|
||||
.setPositiveButton(android.R.string.ok, listener)
|
||||
.setPositiveButton(R.string.settings_download_continue, listener)
|
||||
.setNeutralButton(R.string.settings_download_document, listener)
|
||||
.show();
|
||||
}
|
||||
@@ -160,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: {
|
||||
@@ -188,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);
|
||||
@@ -209,164 +189,25 @@ public class DownloadFragment extends PreferenceFragment implements Preference.O
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class RestoreTask extends AsyncTask<Void, Void, List<RestoreItem>> {
|
||||
|
||||
private final ProgressDialog mDialog;
|
||||
private final DownloadManager mManager;
|
||||
|
||||
public RestoreTask(ProgressDialog dialog) {
|
||||
mDialog = dialog;
|
||||
mManager = EhApplication.getDownloadManager(getActivity());
|
||||
}
|
||||
|
||||
private RestoreItem getRestoreItem(UniFile file) {
|
||||
if (null == file || !file.isDirectory()) {
|
||||
return null;
|
||||
}
|
||||
UniFile siFile = file.findFile(SpiderQueen.SPIDER_INFO_FILENAME);
|
||||
if (null == siFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = siFile.openInputStream();
|
||||
// Skip start page
|
||||
IOUtils.readAsciiLine(is);
|
||||
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
|
||||
if (mManager.containDownloadInfo(gid)) {
|
||||
return null;
|
||||
}
|
||||
String token = IOUtils.readAsciiLine(is);
|
||||
RestoreItem restoreItem = new RestoreItem();
|
||||
restoreItem.gid = gid;
|
||||
restoreItem.token = token;
|
||||
restoreItem.dirname = file.getName();
|
||||
return restoreItem;
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
} finally {
|
||||
IOUtils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<RestoreItem> doInBackground(Void... params) {
|
||||
UniFile dir = Settings.getDownloadLocation();
|
||||
if (null == dir) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<RestoreItem> restoreItemList = new ArrayList<>();
|
||||
|
||||
UniFile[] files = dir.listFiles();
|
||||
for (UniFile file: files) {
|
||||
RestoreItem restoreItem = getRestoreItem(file);
|
||||
if (null != restoreItem) {
|
||||
restoreItemList.add(restoreItem);
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
if (0 == restoreItemList.size()) {
|
||||
return null;
|
||||
} else {
|
||||
return restoreItemList;
|
||||
return true;
|
||||
} else if (Settings.KEY_IMAGE_RESOLUTION.equals(key)) {
|
||||
if (newValue instanceof String) {
|
||||
Settings.putImageResolution((String) newValue);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(List<RestoreItem> restoreItemList) {
|
||||
if (null == restoreItemList) {
|
||||
Toast.makeText(getActivity(), R.string.settings_download_restore_not_found,
|
||||
Toast.LENGTH_SHORT).show();
|
||||
mDialog.dismiss();
|
||||
return;
|
||||
}
|
||||
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_FILL_GALLERY_LIST_BY_API);
|
||||
request.setArgs(new ArrayList<GalleryInfo>(restoreItemList));
|
||||
request.setCallback(new EhClient.Callback<List<GalleryInfo>>() {
|
||||
@Override
|
||||
public void onSuccess(List<GalleryInfo> galleryInfoList) {
|
||||
DownloadManager downloadManager = EhApplication.getDownloadManager(getActivity());
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0, n = galleryInfoList.size(); i < n; i++) {
|
||||
GalleryInfo galleryInfo = galleryInfoList.get(i);
|
||||
// Avoid failed gallery info
|
||||
if (null != galleryInfo.title) {
|
||||
// Put to download
|
||||
downloadManager.addDownload(galleryInfo, null);
|
||||
// Put download dir to DB
|
||||
if (galleryInfo instanceof RestoreItem) {
|
||||
EhDB.putDownloadDirname(galleryInfo.gid, ((RestoreItem) galleryInfo).dirname);
|
||||
} else {
|
||||
Log.w(TAG, "The GalleryInfo is not RestoreItem");
|
||||
}
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
Toast.makeText(getActivity(),
|
||||
getString(R.string.settings_download_restore_successfully, count),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
|
||||
mDialog.dismiss();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Exception e) {
|
||||
Toast.makeText(getActivity(), R.string.settings_download_restore_failed,
|
||||
Toast.LENGTH_SHORT).show();
|
||||
mDialog.dismiss();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
mDialog.dismiss();
|
||||
}
|
||||
});
|
||||
|
||||
EhClient client = EhApplication.getEhClient(getActivity());
|
||||
client.execute(request);
|
||||
}
|
||||
}
|
||||
|
||||
private static class RestoreItem extends GalleryInfo {
|
||||
|
||||
public String dirname;
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeString(this.dirname);
|
||||
}
|
||||
|
||||
public RestoreItem() {
|
||||
}
|
||||
|
||||
protected RestoreItem(Parcel in) {
|
||||
super(in);
|
||||
this.dirname = in.readString();
|
||||
}
|
||||
|
||||
public static final Creator<RestoreItem> CREATOR = new Creator<RestoreItem>() {
|
||||
@Override
|
||||
public RestoreItem createFromParcel(Parcel source) {
|
||||
return new RestoreItem(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RestoreItem[] newArray(int size) {
|
||||
return new RestoreItem[size];
|
||||
}
|
||||
};
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,13 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.fragment;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.preference.Preference;
|
||||
import android.preference.PreferenceFragment;
|
||||
|
||||
import com.hippo.ehviewer.Constants;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.yorozuya.Messenger;
|
||||
|
||||
public class EhFragment extends PreferenceFragment
|
||||
implements Preference.OnPreferenceChangeListener {
|
||||
@@ -33,17 +32,26 @@ public class EhFragment extends PreferenceFragment
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.eh_settings);
|
||||
|
||||
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
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
String key = preference.getKey();
|
||||
if (Settings.KEY_LIST_MODE.equals(key)) {
|
||||
Messenger.getInstance().notify(Constants.MESSAGE_ID_LIST_MODE, null);
|
||||
if (Settings.KEY_GALLERY_SITE.equals(key)) {
|
||||
getActivity().setResult(Activity.RESULT_OK);
|
||||
return true;
|
||||
} 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;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.view.LayoutInflater;
|
||||
@@ -27,8 +28,6 @@ import com.hippo.ehviewer.Analytics;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
|
||||
import com.hippo.rippleold.RippleSalon;
|
||||
import com.hippo.text.Html;
|
||||
import com.hippo.text.LinkMovementMethod2;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
@@ -36,11 +35,9 @@ import com.hippo.yorozuya.ViewUtils;
|
||||
public class AnalyticsScene extends BaseScene implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
@ViewLifeCircle
|
||||
private View mCancel;
|
||||
private View mReject;
|
||||
@Nullable
|
||||
@ViewLifeCircle
|
||||
private View mOk;
|
||||
private View mAccept;
|
||||
|
||||
@Override
|
||||
public boolean needShowLeftDrawer() {
|
||||
@@ -49,22 +46,19 @@ public class AnalyticsScene extends BaseScene implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
|
||||
public View onCreateView2(LayoutInflater inflater, @Nullable ViewGroup container,
|
||||
@Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_analytics, container, false);
|
||||
|
||||
mCancel = ViewUtils.$$(view, R.id.cancel);
|
||||
mOk = ViewUtils.$$(view, R.id.ok);
|
||||
mReject = ViewUtils.$$(view, R.id.reject);
|
||||
mAccept = ViewUtils.$$(view, R.id.accept);
|
||||
TextView text = (TextView) ViewUtils.$$(view, R.id.text);
|
||||
|
||||
text.setText(Html.fromHtml(getString(R.string.analytics_explain)));
|
||||
text.setMovementMethod(new LinkMovementMethod2(getActivity()));
|
||||
text.setMovementMethod(LinkMovementMethod2.getInstance());
|
||||
|
||||
mCancel.setOnClickListener(this);
|
||||
mOk.setOnClickListener(this);
|
||||
|
||||
RippleSalon.addRipple(mCancel, true);
|
||||
RippleSalon.addRipple(mOk, true);
|
||||
mReject.setOnClickListener(this);
|
||||
mAccept.setOnClickListener(this);
|
||||
|
||||
return view;
|
||||
}
|
||||
@@ -73,24 +67,31 @@ public class AnalyticsScene extends BaseScene implements View.OnClickListener {
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
mCancel = null;
|
||||
mOk = null;
|
||||
mReject = null;
|
||||
mAccept = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mCancel == v) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mReject == v) {
|
||||
Settings.putEnableAnalytics(false);
|
||||
} else if (mOk == v) {
|
||||
} else if (mAccept == v) {
|
||||
Settings.putEnableAnalytics(true);
|
||||
// Start Analytics
|
||||
Analytics.start(getContext());
|
||||
Analytics.start(context);
|
||||
}
|
||||
Settings.putAskAnalytics(false);
|
||||
|
||||
// Start new scene and finish it self
|
||||
((MainActivity) getActivity()).startSceneForCheckStep(
|
||||
MainActivity.CHECK_STEP_ANALYTICS, getArguments());
|
||||
MainActivity activity = getActivity2();
|
||||
if (null != activity) {
|
||||
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_ANALYTICS, getArguments());
|
||||
}
|
||||
finish();
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,16 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.IdRes;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.annotation.StringRes;
|
||||
import android.support.annotation.StyleRes;
|
||||
import android.support.v4.app.FragmentActivity;
|
||||
import android.support.v4.widget.DrawerLayout;
|
||||
import android.view.ContextThemeWrapper;
|
||||
import android.view.Gravity;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -29,14 +33,14 @@ 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 {
|
||||
|
||||
public static final int LENGTH_SHORT = 0;
|
||||
public static final int LENGTH_LONG = 1;
|
||||
|
||||
private boolean mViewCreated;
|
||||
private Context mThemeContext;
|
||||
|
||||
public void updateAvatar() {
|
||||
FragmentActivity activity = getActivity();
|
||||
@@ -45,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) {
|
||||
@@ -122,10 +140,22 @@ public abstract class BaseScene extends SceneFragment {
|
||||
public void onDestroyDrawerView() {
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public final View onCreateView(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
return onCreateView2(LayoutInflater.from(getContext2()), container, savedInstanceState);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
mViewCreated = true;
|
||||
|
||||
// Update left drawer locked state
|
||||
if (needShowLeftDrawer()) {
|
||||
@@ -138,27 +168,58 @@ public abstract class BaseScene extends SceneFragment {
|
||||
setNavCheckedItem(getNavCheckedItem());
|
||||
|
||||
// Hide soft ime
|
||||
ActivityHelper.hideSoftInput(getActivity());
|
||||
AppHelper.hideSoftInput(getActivity());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
mViewCreated = false;
|
||||
super.onDestroyView();
|
||||
public void createThemeContext(@StyleRes int style) {
|
||||
mThemeContext = new ContextThemeWrapper(getContext(), style);
|
||||
}
|
||||
|
||||
public boolean isViewCreated() {
|
||||
return mViewCreated;
|
||||
public void destroyThemeContext() {
|
||||
mThemeContext = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityCreated(Bundle savedInstanceState) {
|
||||
super.onActivityCreated(savedInstanceState);
|
||||
if (savedInstanceState != null) {
|
||||
onRestoreInstanceState(savedInstanceState);
|
||||
@Nullable
|
||||
public Context getContext2() {
|
||||
return null != mThemeContext ? mThemeContext : super.getContext();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Resources getResources2() {
|
||||
Context context = getContext2();
|
||||
if (null != context) {
|
||||
return context.getResources();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected void onRestoreInstanceState(Bundle savedInstanceState) {
|
||||
@Nullable
|
||||
public MainActivity getActivity2() {
|
||||
FragmentActivity activity = getActivity();
|
||||
if (activity instanceof MainActivity) {
|
||||
return (MainActivity) activity;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public LayoutInflater getLayoutInflater2() {
|
||||
return LayoutInflater.from(getContext2());
|
||||
}
|
||||
|
||||
public void hideSoftInput() {
|
||||
FragmentActivity activity = getActivity();
|
||||
if (null != activity) {
|
||||
AppHelper.hideSoftInput(activity);
|
||||
}
|
||||
}
|
||||
|
||||
public void showSoftInput(@Nullable View view) {
|
||||
FragmentActivity activity = getActivity();
|
||||
if (null != activity && null != view) {
|
||||
AppHelper.showSoftInput(activity, view);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.design.widget.TextInputLayout;
|
||||
@@ -35,8 +36,6 @@ import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.client.EhCookieStore;
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.rippleold.RippleSalon;
|
||||
import com.hippo.util.ActivityHelper;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
@@ -66,7 +65,8 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_cookie_sign_in, container, false);
|
||||
mIpbMemberIdLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_member_id_layout);
|
||||
mIpbMemberId = mIpbMemberIdLayout.getEditText();
|
||||
@@ -80,7 +80,24 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
|
||||
mOk.setOnClickListener(this);
|
||||
|
||||
RippleSalon.addRipple(mOk, true);
|
||||
// Try to get old version cookie info
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
SharedPreferences sharedPreferences = context.getSharedPreferences("eh_info", 0);
|
||||
String ipbMemberId = sharedPreferences.getString("ipb_member_id", null);
|
||||
String ipbPassHash = sharedPreferences.getString("ipb_pass_hash", null);
|
||||
boolean getIt = false;
|
||||
if (!TextUtils.isEmpty(ipbMemberId)) {
|
||||
mIpbMemberId.setText(ipbMemberId);
|
||||
getIt = true;
|
||||
}
|
||||
if (!TextUtils.isEmpty(ipbPassHash)) {
|
||||
mIpbPassHash.setText(ipbPassHash);
|
||||
getIt = true;
|
||||
}
|
||||
if (getIt) {
|
||||
showTip(R.string.found_cookies, LENGTH_SHORT);
|
||||
}
|
||||
|
||||
return view;
|
||||
}
|
||||
@@ -90,7 +107,7 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
|
||||
ActivityHelper.showSoftInput(getActivity(), mIpbMemberId);
|
||||
showSoftInput(mIpbMemberId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -144,7 +161,8 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
}
|
||||
|
||||
public void enter() {
|
||||
if (null == mIpbMemberIdLayout || null == mIpbPassHashLayout ||
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mIpbMemberIdLayout || null == mIpbPassHashLayout ||
|
||||
null == mIpbMemberId || null == mIpbPassHash) {
|
||||
return;
|
||||
}
|
||||
@@ -165,10 +183,10 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
mIpbPassHashLayout.setError(null);
|
||||
}
|
||||
|
||||
ActivityHelper.hideSoftInput(getActivity());
|
||||
hideSoftInput();
|
||||
|
||||
if (!checkIpbMemberId(ipbMemberId) || !(checkIpbPassHash(ipbPassHash))) {
|
||||
new AlertDialog.Builder(getContext()).setTitle(R.string.waring)
|
||||
new AlertDialog.Builder(context).setTitle(R.string.waring)
|
||||
.setMessage(R.string.wrong_cookie_warning)
|
||||
.setNegativeButton(R.string.i_dont_think_so, null)
|
||||
.setPositiveButton(R.string.i_will_check_it, new DialogInterface.OnClickListener() {
|
||||
@@ -192,12 +210,12 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
|
||||
}
|
||||
|
||||
private void storeCookie(String id, String hash) {
|
||||
Context context = getContext();
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
|
||||
EhUtils.signOut(getContext());
|
||||
EhUtils.signOut(context);
|
||||
|
||||
EhCookieStore store = EhApplication.getEhCookieStore(context);
|
||||
store.add(newCookie(EhCookieStore.KEY_IPD_MEMBER_ID, id, EhUrl.DOMAIN_E));
|
||||
|
||||
@@ -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 {
|
||||
@@ -60,7 +60,7 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater,
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_crash, container, false);
|
||||
|
||||
@@ -70,23 +70,26 @@ 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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mSend == v && null != mCrash) {
|
||||
ActivityHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
|
||||
MainActivity activity = getActivity2();
|
||||
|
||||
if (mSend == v && null != mCrash && null != activity) {
|
||||
AppHelper.sendEmail(activity, EhApplication.getDeveloperEmail(),
|
||||
"I found a bug in EhViewer !", mCrash);
|
||||
}
|
||||
Crash.resetCrashFile();
|
||||
|
||||
// Start new scene and finish it self
|
||||
((MainActivity) getActivity()).startSceneForCheckStep(
|
||||
MainActivity.CHECK_STEP_CRASH, getArguments());
|
||||
if (null != activity) {
|
||||
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_CRASH, getArguments());
|
||||
}
|
||||
finish();
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.NinePatchDrawable;
|
||||
@@ -52,6 +53,7 @@ import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.dao.DownloadLabel;
|
||||
import com.hippo.util.DrawableManager;
|
||||
import com.hippo.view.ViewTransition;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.List;
|
||||
@@ -77,7 +79,7 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
mList = EhApplication.getDownloadManager(getContext()).getLabelList();
|
||||
mList = EhApplication.getDownloadManager(getContext2()).getLabelList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -89,7 +91,7 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
@SuppressWarnings("deprecation")
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_label_list, container, false);
|
||||
|
||||
@@ -97,7 +99,9 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
mViewTransition = new ViewTransition(mRecyclerView, tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_label);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_label);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
tip.setText(R.string.no_download_label);
|
||||
@@ -109,7 +113,7 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
// drag & drop manager
|
||||
RecyclerViewDragDropManager dragDropManager = new RecyclerViewDragDropManager();
|
||||
dragDropManager.setDraggingItemShadowDrawable(
|
||||
(NinePatchDrawable) getResources().getDrawable(R.drawable.shadow_8dp));
|
||||
(NinePatchDrawable) context.getResources().getDrawable(R.drawable.shadow_8dp));
|
||||
// swipe manager
|
||||
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
|
||||
RecyclerView.Adapter adapter = new LabelAdapter();
|
||||
@@ -120,7 +124,7 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
|
||||
animator.setSupportsChangeAnimations(false);
|
||||
mRecyclerView.hasFixedSize();
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
|
||||
mRecyclerView.setAdapter(adapter);
|
||||
mRecyclerView.setItemAnimator(animator);
|
||||
guardManager.attachRecyclerView(mRecyclerView);
|
||||
@@ -143,7 +147,11 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
mRecyclerView = null;
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
|
||||
mViewTransition = null;
|
||||
mAdapter = null;
|
||||
}
|
||||
@@ -160,10 +168,15 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemClick(MenuItem item) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int id = item.getItemId();
|
||||
switch (id) {
|
||||
case R.id.action_add: {
|
||||
EditTextDialogBuilder builder = new EditTextDialogBuilder(getContext(), null, getString(R.string.download_labels));
|
||||
EditTextDialogBuilder builder = new EditTextDialogBuilder(context, null, getString(R.string.download_labels));
|
||||
builder.setTitle(R.string.new_label_title);
|
||||
builder.setPositiveButton(android.R.string.ok, null);
|
||||
AlertDialog dialog = builder.show();
|
||||
@@ -199,17 +212,22 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
|
||||
String text = mBuilder.getText();
|
||||
if (TextUtils.isEmpty(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_is_empty));
|
||||
} else if (getString(R.string.default_download_label_name).equals(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_is_invalid));
|
||||
} else if (EhApplication.getDownloadManager(getContext()).containLabel(text)) {
|
||||
} else if (EhApplication.getDownloadManager(context).containLabel(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_exist));
|
||||
} else {
|
||||
mBuilder.setError(null);
|
||||
mDialog.dismiss();
|
||||
EhApplication.getDownloadManager(getContext()).addLabel(text);
|
||||
EhApplication.getDownloadManager(context).addLabel(text);
|
||||
if (mAdapter != null && mList != null) {
|
||||
mAdapter.notifyItemInserted(mList.size() - 1);
|
||||
}
|
||||
@@ -245,17 +263,22 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
|
||||
String text = mBuilder.getText();
|
||||
if (TextUtils.isEmpty(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_is_empty));
|
||||
} else if (getString(R.string.default_download_label_name).equals(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_is_invalid));
|
||||
} else if (EhApplication.getDownloadManager(getContext()).containLabel(text)) {
|
||||
} else if (EhApplication.getDownloadManager(context).containLabel(text)) {
|
||||
mBuilder.setError(getString(R.string.label_text_exist));
|
||||
} else {
|
||||
mBuilder.setError(null);
|
||||
mDialog.dismiss();
|
||||
EhApplication.getDownloadManager(getContext()).renameLabel(mOriginalLabel, text);
|
||||
EhApplication.getDownloadManager(context).renameLabel(mOriginalLabel, text);
|
||||
if (mAdapter != null) {
|
||||
mAdapter.notifyItemChanged(mPosition);
|
||||
}
|
||||
@@ -282,7 +305,8 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mList == null || mRecyclerView == null) {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mList || null == mRecyclerView) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -294,7 +318,7 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
if (label == v) {
|
||||
DownloadLabel raw = mList.get(index);
|
||||
EditTextDialogBuilder builder = new EditTextDialogBuilder(
|
||||
getContext(), raw.getLabel(), getString(R.string.download_labels));
|
||||
context, raw.getLabel(), getString(R.string.download_labels));
|
||||
builder.setTitle(R.string.rename_label_title);
|
||||
builder.setPositiveButton(android.R.string.ok, null);
|
||||
AlertDialog dialog = builder.show();
|
||||
@@ -312,10 +336,16 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
implements DraggableItemAdapter<LabelHolder>,
|
||||
SwipeableItemAdapter<LabelHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public LabelAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LabelHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new LabelHolder(getActivity().getLayoutInflater()
|
||||
.inflate(R.layout.item_label_list, parent, false));
|
||||
return new LabelHolder(mInflater.inflate(R.layout.item_label_list, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -348,11 +378,12 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
|
||||
@Override
|
||||
public void onMoveItem(int fromPosition, int toPosition) {
|
||||
if (fromPosition == toPosition) {
|
||||
Context context = getContext2();
|
||||
if (null == context || fromPosition == toPosition) {
|
||||
return;
|
||||
}
|
||||
|
||||
EhApplication.getDownloadManager(getContext()).moveLabel(fromPosition, toPosition);
|
||||
EhApplication.getDownloadManager(context).moveLabel(fromPosition, toPosition);
|
||||
if (mAdapter != null && mList != null) {
|
||||
notifyItemMoved(fromPosition, toPosition);
|
||||
}
|
||||
@@ -397,19 +428,20 @@ public class DownloadLabelsScene extends ToolbarScene {
|
||||
protected void onPerformAction() {
|
||||
super.onPerformAction();
|
||||
|
||||
final Context context = getContext2();
|
||||
final List<DownloadLabel> list = mList;
|
||||
if (list == null || mPosition < 0 || mPosition >= list.size()) {
|
||||
if (null == context || null == list || mPosition < 0 || mPosition >= list.size()) {
|
||||
return;
|
||||
}
|
||||
final DownloadLabel label = list.get(mPosition);
|
||||
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.delete_label_title)
|
||||
.setMessage(getString(R.string.delete_label_message, label.getLabel()))
|
||||
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
EhApplication.getDownloadManager(getContext()).deleteLabel(label.getLabel());
|
||||
EhApplication.getDownloadManager(context).deleteLabel(label.getLabel());
|
||||
}
|
||||
})
|
||||
.setOnDismissListener(new DialogInterface.OnDismissListener() {
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
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;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.AsyncTask;
|
||||
@@ -30,10 +32,11 @@ 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;
|
||||
import android.view.Display;
|
||||
import android.view.Gravity;
|
||||
@@ -41,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;
|
||||
@@ -55,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;
|
||||
@@ -68,8 +73,9 @@ import com.hippo.ehviewer.download.DownloadManager;
|
||||
import com.hippo.ehviewer.download.DownloadService;
|
||||
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;
|
||||
@@ -77,11 +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;
|
||||
@@ -94,6 +101,10 @@ public class DownloadsScene extends ToolbarScene
|
||||
EasyRecyclerView.OnItemLongClickListener,
|
||||
FabLayout.OnClickFabListener, FastScroller.OnDragHandlerListener {
|
||||
|
||||
private static final String TAG = DownloadsScene.class.getSimpleName();
|
||||
|
||||
public static final String KEY_GID = "gid";
|
||||
|
||||
public static final String KEY_ACTION = "action";
|
||||
private static final String KEY_LABEL = "label";
|
||||
|
||||
@@ -121,17 +132,47 @@ public class DownloadsScene extends ToolbarScene
|
||||
@Nullable
|
||||
private DownloadAdapter mAdapter;
|
||||
@Nullable
|
||||
private LinearLayoutManager mLayoutManager;
|
||||
private AutoStaggeredGridLayoutManager mLayoutManager;
|
||||
|
||||
private ShowcaseView mShowcaseView;
|
||||
|
||||
private int mInitPosition = -1;
|
||||
|
||||
@Override
|
||||
public int getNavCheckedItem() {
|
||||
return R.id.nav_downloads;
|
||||
}
|
||||
|
||||
private void handleArguments(Bundle args) {
|
||||
if (args != null && ACTION_CLEAR_DOWNLOAD_SERVICE.equals(args.getString(KEY_ACTION))) {
|
||||
private boolean handleArguments(Bundle args) {
|
||||
if (null == args) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ACTION_CLEAR_DOWNLOAD_SERVICE.equals(args.getString(KEY_ACTION))) {
|
||||
DownloadService.clear();
|
||||
}
|
||||
|
||||
long gid;
|
||||
if (null != mDownloadManager && -1L != (gid = args.getLong(KEY_GID, -1L))) {
|
||||
DownloadInfo info = mDownloadManager.getDownloadInfo(gid);
|
||||
if (null != info) {
|
||||
mLabel = info.getLabel();
|
||||
updateForLabel();
|
||||
updateView();
|
||||
|
||||
// Get position
|
||||
if (null != mList) {
|
||||
int position = mList.indexOf(info);
|
||||
if (position >= 0 && null != mRecyclerView) {
|
||||
mRecyclerView.scrollToPosition(position);
|
||||
} else {
|
||||
mInitPosition = position;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,9 +184,9 @@ public class DownloadsScene extends ToolbarScene
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
handleArguments(getArguments());
|
||||
|
||||
mDownloadManager = EhApplication.getDownloadManager(getContext());
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
mDownloadManager = EhApplication.getDownloadManager(context);
|
||||
mDownloadManager.addDownloadInfoListener(this);
|
||||
|
||||
if (savedInstanceState == null) {
|
||||
@@ -162,11 +203,19 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
DownloadManager manager = mDownloadManager;
|
||||
if (null == manager) {
|
||||
manager = EhApplication.getDownloadManager(getContext());
|
||||
Context context = getContext2();
|
||||
if (null != context) {
|
||||
manager = EhApplication.getDownloadManager(context);
|
||||
}
|
||||
} else {
|
||||
mDownloadManager = null;
|
||||
}
|
||||
manager.removeDownloadInfoListener(this);
|
||||
|
||||
if (null != manager) {
|
||||
manager.removeDownloadInfoListener(this);
|
||||
} else {
|
||||
Log.e(TAG, "Can't removeDownloadInfoListener");
|
||||
}
|
||||
}
|
||||
|
||||
private void updateForLabel() {
|
||||
@@ -198,8 +247,10 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void onInit() {
|
||||
mLabel = Settings.getRecentDownloadLabel();
|
||||
updateForLabel();
|
||||
if (!handleArguments(getArguments())) {
|
||||
mLabel = Settings.getRecentDownloadLabel();
|
||||
updateForLabel();
|
||||
}
|
||||
}
|
||||
|
||||
private void onRestore(@NonNull Bundle savedInstanceState) {
|
||||
@@ -215,7 +266,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_download, container, false);
|
||||
|
||||
@@ -226,16 +277,22 @@ public class DownloadsScene extends ToolbarScene
|
||||
TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
mViewTransition = new ViewTransition(content, tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_download);
|
||||
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());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
|
||||
mAdapter = new DownloadAdapter();
|
||||
mAdapter.setHasStableIds(true);
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
mLayoutManager = new LinearLayoutManager(getContext());
|
||||
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);
|
||||
@@ -248,13 +305,20 @@ public class DownloadsScene extends ToolbarScene
|
||||
if (itemAnimator instanceof SimpleItemAnimator) {
|
||||
((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
|
||||
}
|
||||
int paddingH = getResources().getDimensionPixelOffset(R.dimen.list_content_margin_h);
|
||||
int paddingV = 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;
|
||||
}
|
||||
|
||||
fastScroller.attachToRecyclerView(mRecyclerView);
|
||||
HandlerDrawable handlerDrawable = new HandlerDrawable();
|
||||
handlerDrawable.setColor(ResourcesUtils.getAttrColor(getContext(), R.attr.colorAccent));
|
||||
handlerDrawable.setColor(ResourcesUtils.getAttrColor(context, R.attr.colorAccent));
|
||||
fastScroller.setHandlerDrawable(handlerDrawable);
|
||||
fastScroller.setOnDragHandlerListener(this);
|
||||
|
||||
@@ -262,6 +326,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
mFabLayout.setHidePrimaryFab(true);
|
||||
mFabLayout.setAutoCancel(false);
|
||||
mFabLayout.setOnClickFabListener(this);
|
||||
addAboveSnackView(mFabLayout);
|
||||
|
||||
updateView();
|
||||
|
||||
@@ -271,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 {
|
||||
@@ -284,11 +354,12 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void guideDownloadThumb() {
|
||||
if (!Settings.getGuideDownloadThumb() || null == mLayoutManager || null == mRecyclerView) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || !Settings.getGuideDownloadThumb() || null == mLayoutManager || null == mRecyclerView) {
|
||||
guideDownloadLabels();
|
||||
return;
|
||||
}
|
||||
int position = mLayoutManager.findFirstCompletelyVisibleItemPosition();
|
||||
int position = mLayoutManager.findFirstCompletelyVisibleItemPositions(null)[0];
|
||||
if (position < 0) {
|
||||
guideDownloadLabels();
|
||||
return;
|
||||
@@ -299,7 +370,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
return;
|
||||
}
|
||||
|
||||
new ShowcaseView.Builder(getActivity())
|
||||
mShowcaseView = new ShowcaseView.Builder(activity)
|
||||
.withMaterialShowcase()
|
||||
.setStyle(R.style.Guide)
|
||||
.setTarget(new ViewTarget(((DownloadHolder) holder).thumb))
|
||||
@@ -310,6 +381,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
.setShowcaseEventListener(new SimpleShowcaseEventListener() {
|
||||
@Override
|
||||
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
|
||||
mShowcaseView = null;
|
||||
ViewUtils.removeFromParent(showcaseView);
|
||||
Settings.putGuideDownloadThumb(false);
|
||||
guideDownloadLabels();
|
||||
@@ -318,15 +390,16 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void guideDownloadLabels() {
|
||||
if (!Settings.getGuideDownloadLabels()) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || !Settings.getGuideDownloadLabels()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Display display = getActivity().getWindowManager().getDefaultDisplay();
|
||||
Display display = activity.getWindowManager().getDefaultDisplay();
|
||||
Point point = new Point();
|
||||
display.getSize(point);
|
||||
|
||||
new ShowcaseView.Builder(getActivity())
|
||||
mShowcaseView = new ShowcaseView.Builder(activity)
|
||||
.withMaterialShowcase()
|
||||
.setStyle(R.style.Guide)
|
||||
.setTarget(new PointTarget(point.x, point.y / 3))
|
||||
@@ -337,6 +410,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
.setShowcaseEventListener(new SimpleShowcaseEventListener() {
|
||||
@Override
|
||||
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
|
||||
mShowcaseView = null;
|
||||
ViewUtils.removeFromParent(showcaseView);
|
||||
Settings.puttGuideDownloadLabels(false);
|
||||
openDrawer(Gravity.RIGHT);
|
||||
@@ -355,8 +429,20 @@ public class DownloadsScene extends ToolbarScene
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mShowcaseView) {
|
||||
ViewUtils.removeFromParent(mShowcaseView);
|
||||
mShowcaseView = null;
|
||||
}
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
if (null != mFabLayout) {
|
||||
removeAboveSnackView(mFabLayout);
|
||||
mFabLayout = null;
|
||||
}
|
||||
|
||||
mRecyclerView = null;
|
||||
mFabLayout = null;
|
||||
mViewTransition = null;
|
||||
mAdapter = null;
|
||||
mLayoutManager = null;
|
||||
@@ -375,16 +461,17 @@ public class DownloadsScene extends ToolbarScene
|
||||
@Override
|
||||
public boolean onMenuItemClick(MenuItem item) {
|
||||
// Skip when in choice mode
|
||||
if (mRecyclerView == null || mRecyclerView.isInCustomChoice()) {
|
||||
Activity activity = getActivity2();
|
||||
if (null == activity || null == mRecyclerView || mRecyclerView.isInCustomChoice()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int id = item.getItemId();
|
||||
switch (id) {
|
||||
case R.id.action_start_all: {
|
||||
Intent intent = new Intent(getActivity(), DownloadService.class);
|
||||
Intent intent = new Intent(activity, DownloadService.class);
|
||||
intent.setAction(DownloadService.ACTION_START_ALL);
|
||||
getActivity().startService(intent);
|
||||
activity.startService(intent);
|
||||
return true;
|
||||
}
|
||||
case R.id.action_stop_all: {
|
||||
@@ -412,6 +499,9 @@ public class DownloadsScene extends ToolbarScene
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.drawer_list, container, false);
|
||||
|
||||
final Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
|
||||
toolbar.setTitle(R.string.download_labels);
|
||||
toolbar.inflateMenu(R.menu.drawer_download);
|
||||
@@ -436,7 +526,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
items[i + 2] = list.get(i).getLabel();
|
||||
}
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.default_download_label)
|
||||
.setItems(items, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
@@ -461,7 +551,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
});
|
||||
|
||||
List<DownloadLabel> list = EhApplication.getDownloadManager(getContext()).getLabelList();
|
||||
List<DownloadLabel> list = EhApplication.getDownloadManager(context).getLabelList();
|
||||
final List<String> labels = new ArrayList<>(list.size() + 1);
|
||||
// Add default label name
|
||||
labels.add(getString(R.string.default_download_label_name));
|
||||
@@ -471,7 +561,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
// TODO handle download label items update
|
||||
ListView listView = (ListView) view.findViewById(R.id.list_view);
|
||||
listView.setAdapter(new ArrayAdapter<>(getContext(), R.layout.item_simple_list, labels));
|
||||
listView.setAdapter(new ArrayAdapter<>(context, R.layout.item_simple_list, labels));
|
||||
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
|
||||
@@ -495,6 +585,10 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (null != mShowcaseView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
|
||||
mRecyclerView.outOfCustomChoiceMode();
|
||||
} else {
|
||||
@@ -518,8 +612,9 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
Activity activity = getActivity2();
|
||||
EasyRecyclerView recyclerView = mRecyclerView;
|
||||
if (recyclerView == null) {
|
||||
if (null == activity || null == recyclerView) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -535,7 +630,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
return false;
|
||||
}
|
||||
|
||||
Intent intent = new Intent(getActivity(), GalleryActivity.class);
|
||||
Intent intent = new Intent(activity, GalleryActivity.class);
|
||||
intent.setAction(GalleryActivity.ACTION_EH);
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, list.get(position));
|
||||
startActivity(intent);
|
||||
@@ -567,8 +662,10 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) {
|
||||
Context context = getContext2();
|
||||
Activity activity = getActivity2();
|
||||
EasyRecyclerView recyclerView = mRecyclerView;
|
||||
if (recyclerView == null) {
|
||||
if (null == context || null == activity || null == recyclerView) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -606,10 +703,10 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
switch (position) {
|
||||
case 1: { // Start
|
||||
Intent intent = new Intent(getActivity(), DownloadService.class);
|
||||
Intent intent = new Intent(activity, DownloadService.class);
|
||||
intent.setAction(DownloadService.ACTION_START_RANGE);
|
||||
intent.putExtra(DownloadService.KEY_GID_LIST, gidList);
|
||||
getActivity().startService(intent);
|
||||
activity.startService(intent);
|
||||
// Cancel check mode
|
||||
recyclerView.outOfCustomChoiceMode();
|
||||
break;
|
||||
@@ -623,7 +720,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
break;
|
||||
}
|
||||
case 3: { // Delete
|
||||
CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(getContext(),
|
||||
CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(context,
|
||||
getString(R.string.download_remove_dialog_message_2, gidList.size()),
|
||||
getString(R.string.download_remove_dialog_check_text),
|
||||
Settings.getRemoveImageFiles());
|
||||
@@ -635,7 +732,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
break;
|
||||
}
|
||||
case 4: {// Move
|
||||
List<DownloadLabel> labelRawList = EhApplication.getDownloadManager(getContext()).getLabelList();
|
||||
List<DownloadLabel> labelRawList = EhApplication.getDownloadManager(context).getLabelList();
|
||||
List<String> labelList = new ArrayList<>(labelRawList.size() + 1);
|
||||
labelList.add(getString(R.string.default_download_label_name));
|
||||
for (int i = 0, n = labelRawList.size(); i < n; i++) {
|
||||
@@ -645,7 +742,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
MoveDialogHelper helper = new MoveDialogHelper(labels, downloadInfoList);
|
||||
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.download_move_dialog_title)
|
||||
.setItems(labels, helper)
|
||||
.show();
|
||||
@@ -728,12 +825,17 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void bindForState(DownloadHolder holder, DownloadInfo info) {
|
||||
Resources resources = getResources2();
|
||||
if (null == resources) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (info.state) {
|
||||
case DownloadInfo.STATE_NONE:
|
||||
bindState(holder, info, getContext().getString(R.string.download_state_none));
|
||||
bindState(holder, info, resources.getString(R.string.download_state_none));
|
||||
break;
|
||||
case DownloadInfo.STATE_WAIT:
|
||||
bindState(holder, info, getContext().getString(R.string.download_state_wait));
|
||||
bindState(holder, info, resources.getString(R.string.download_state_wait));
|
||||
break;
|
||||
case DownloadInfo.STATE_DOWNLOAD:
|
||||
bindProgress(holder, info);
|
||||
@@ -741,14 +843,14 @@ public class DownloadsScene extends ToolbarScene
|
||||
case DownloadInfo.STATE_FAILED:
|
||||
String text;
|
||||
if (info.legacy <= 0) {
|
||||
text = getContext().getString(R.string.download_state_failed);
|
||||
text = resources.getString(R.string.download_state_failed);
|
||||
} else {
|
||||
text = getContext().getString(R.string.download_state_failed_2, info.legacy);
|
||||
text = resources.getString(R.string.download_state_failed_2, info.legacy);
|
||||
}
|
||||
bindState(holder, info, text);
|
||||
break;
|
||||
case DownloadInfo.STATE_FINISH:
|
||||
bindState(holder, info, getContext().getString(R.string.download_state_finish));
|
||||
bindState(holder, info, resources.getString(R.string.download_state_finish));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -912,7 +1014,11 @@ public class DownloadsScene extends ToolbarScene
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
// Cancel check mode
|
||||
if (mRecyclerView != null) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.outOfCustomChoiceMode();
|
||||
}
|
||||
|
||||
@@ -922,7 +1028,7 @@ public class DownloadsScene extends ToolbarScene
|
||||
} else {
|
||||
label = mLabels[which];
|
||||
}
|
||||
EhApplication.getDownloadManager(getContext()).changeLabel(mDownloadInfoList, label);
|
||||
EhApplication.getDownloadManager(context).changeLabel(mDownloadInfoList, label);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -935,7 +1041,6 @@ public class DownloadsScene extends ToolbarScene
|
||||
public final TextView category;
|
||||
public final View start;
|
||||
public final View stop;
|
||||
public final View delete;
|
||||
public final TextView state;
|
||||
public final ProgressBar progressBar;
|
||||
public final TextView percent;
|
||||
@@ -951,7 +1056,6 @@ public class DownloadsScene extends ToolbarScene
|
||||
category = (TextView) itemView.findViewById(R.id.category);
|
||||
start = itemView.findViewById(R.id.start);
|
||||
stop = itemView.findViewById(R.id.stop);
|
||||
delete = itemView.findViewById(R.id.delete);
|
||||
state = (TextView) itemView.findViewById(R.id.state);
|
||||
progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
|
||||
percent = (TextView) itemView.findViewById(R.id.percent);
|
||||
@@ -961,16 +1065,16 @@ public class DownloadsScene extends ToolbarScene
|
||||
thumb.setOnClickListener(this);
|
||||
start.setOnClickListener(this);
|
||||
stop.setOnClickListener(this);
|
||||
delete.setOnClickListener(this);
|
||||
RippleSalon.addRipple(start, false);
|
||||
RippleSalon.addRipple(stop, false);
|
||||
RippleSalon.addRipple(delete, false);
|
||||
Ripple.addRipple(start, false);
|
||||
Ripple.addRipple(stop, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Context context = getContext2();
|
||||
Activity activity = getActivity2();
|
||||
EasyRecyclerView recyclerView = mRecyclerView;
|
||||
if (recyclerView == null || recyclerView.isInCustomChoice()) {
|
||||
if (null == context || null == activity || null == recyclerView || recyclerView.isInCustomChoice()) {
|
||||
return;
|
||||
}
|
||||
List<DownloadInfo> list = mList;
|
||||
@@ -993,30 +1097,27 @@ public class DownloadsScene extends ToolbarScene
|
||||
}
|
||||
startScene(announcer);
|
||||
} else if (start == v) {
|
||||
Intent intent = new Intent(getActivity(), DownloadService.class);
|
||||
Intent intent = new Intent(activity, DownloadService.class);
|
||||
intent.setAction(DownloadService.ACTION_START);
|
||||
intent.putExtra(DownloadService.KEY_GALLERY_INFO, list.get(index));
|
||||
getActivity().startService(intent);
|
||||
activity.startService(intent);
|
||||
} else if (stop == v) {
|
||||
if (null != mDownloadManager) {
|
||||
mDownloadManager.stopDownload(list.get(index).gid);
|
||||
}
|
||||
} else if (delete == v) {
|
||||
GalleryInfo galleryInfo = list.get(index);
|
||||
CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(getContext(),
|
||||
getString(R.string.download_remove_dialog_message, EhUtils.getSuitableTitle(galleryInfo)),
|
||||
getString(R.string.download_remove_dialog_check_text),
|
||||
Settings.getRemoveImageFiles());
|
||||
DeleteDialogHelper helper = new DeleteDialogHelper(galleryInfo, builder);
|
||||
builder.setTitle(R.string.download_remove_dialog_title)
|
||||
.setPositiveButton(android.R.string.ok, helper)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DownloadAdapter extends RecyclerView.Adapter<DownloadHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public DownloadAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
if (mList == null || position < 0 || position >= mList.size()) {
|
||||
@@ -1027,17 +1128,16 @@ public class DownloadsScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public DownloadHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new DownloadHolder(getActivity().getLayoutInflater().inflate(R.layout.item_download, parent, false));
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
DownloadInfo info = mList.get(position);
|
||||
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb, true);
|
||||
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb);
|
||||
holder.title.setText(EhUtils.getSuitableTitle(info));
|
||||
holder.uploader.setText(info.uploader);
|
||||
holder.rating.setRating(info.rating);
|
||||
@@ -1050,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;
|
||||
}
|
||||
}
|
||||
@@ -16,17 +16,20 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
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.GridLayoutManager;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.text.Spannable;
|
||||
@@ -43,6 +46,7 @@ import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.github.amlcurran.showcaseview.ShowcaseView;
|
||||
import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener;
|
||||
@@ -51,6 +55,7 @@ import com.hippo.annotation.Implemented;
|
||||
import com.hippo.drawable.DrawerArrowDrawable;
|
||||
import com.hippo.easyrecyclerview.EasyRecyclerView;
|
||||
import com.hippo.easyrecyclerview.FastScroller;
|
||||
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.EhDB;
|
||||
import com.hippo.ehviewer.R;
|
||||
@@ -60,23 +65,25 @@ import com.hippo.ehviewer.client.EhRequest;
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.exception.NotFoundException;
|
||||
import com.hippo.ehviewer.client.parser.FavoritesParser;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
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.scene.StageActivity;
|
||||
import com.hippo.util.ApiHelper;
|
||||
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;
|
||||
import com.hippo.yorozuya.ResourcesUtils;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
@@ -84,7 +91,6 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
// TODO Bug for FavoritesScene and GalleryListScene, if list view of SearchBar expand first, RecyclerView padding top will be wrong
|
||||
// TODO Get favorite, modify favorite, add favorite, what a mess!
|
||||
public class FavoritesScene extends BaseScene implements
|
||||
EasyRecyclerView.OnItemClickListener, EasyRecyclerView.OnItemLongClickListener,
|
||||
@@ -97,8 +103,6 @@ public class FavoritesScene extends BaseScene implements
|
||||
private static final String KEY_SEARCH_MODE = "search_mode";
|
||||
private static final String KEY_HAS_FIRST_REFRESH = "has_first_refresh";
|
||||
private static final String KEY_FAV_COUNT_ARRAY = "fav_count_array";
|
||||
private static final String KEY_ALL_COUNT = "all_count";
|
||||
private static final String KEY_ALL_LIMIT = "all_limit";
|
||||
|
||||
@Nullable
|
||||
@ViewLifeCircle
|
||||
@@ -145,8 +149,6 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
@Nullable
|
||||
private int[] mFavCountArray;
|
||||
private int mAllCount = -1;
|
||||
private int mAllLimit = -1;
|
||||
|
||||
private boolean mHasFirstRefresh;
|
||||
private boolean mSearchMode;
|
||||
@@ -163,14 +165,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
// For modify action
|
||||
private boolean mModifyAdd;
|
||||
|
||||
private final Runnable mReturnSearchBarRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mSearchBarMover != null) {
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
}
|
||||
}
|
||||
};
|
||||
private ShowcaseView mShowcaseView;
|
||||
|
||||
@Override
|
||||
public int getNavCheckedItem() {
|
||||
@@ -181,7 +176,9 @@ public class FavoritesScene extends BaseScene implements
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mClient = EhApplication.getEhClient(getContext());
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
mClient = EhApplication.getEhClient(context);
|
||||
mFavCatArray = Settings.getFavCat();
|
||||
|
||||
if (savedInstanceState == null) {
|
||||
@@ -205,8 +202,6 @@ public class FavoritesScene extends BaseScene implements
|
||||
mSearchMode = savedInstanceState.getBoolean(KEY_SEARCH_MODE);
|
||||
mHasFirstRefresh = savedInstanceState.getBoolean(KEY_HAS_FIRST_REFRESH);
|
||||
mFavCountArray = savedInstanceState.getIntArray(KEY_FAV_COUNT_ARRAY);
|
||||
mAllCount = savedInstanceState.getInt(KEY_ALL_COUNT);
|
||||
mAllLimit = savedInstanceState.getInt(KEY_ALL_LIMIT);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -223,8 +218,6 @@ public class FavoritesScene extends BaseScene implements
|
||||
outState.putParcelable(KEY_URL_BUILDER, mUrlBuilder);
|
||||
outState.putBoolean(KEY_SEARCH_MODE, mSearchMode);
|
||||
outState.putIntArray(KEY_FAV_COUNT_ARRAY, mFavCountArray);
|
||||
outState.putInt(KEY_ALL_COUNT, mAllCount);
|
||||
outState.putInt(KEY_ALL_LIMIT, mAllLimit);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -238,7 +231,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater,
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_favorites, container, false);
|
||||
ContentLayout contentLayout = (ContentLayout) view.findViewById(R.id.content_layout);
|
||||
@@ -248,16 +241,18 @@ public class FavoritesScene extends BaseScene implements
|
||||
mSearchBar = (SearchBar) ViewUtils.$$(view, R.id.search_bar);
|
||||
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
|
||||
|
||||
Resources resources = getResources();
|
||||
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.list_padding_top_search_bar);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Resources resources = context.getResources();
|
||||
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
|
||||
|
||||
mHelper = new FavoritesHelper();
|
||||
mHelper.setEmptyString(resources.getString(R.string.gallery_list_empty_hit));
|
||||
contentLayout.setHelper(mHelper);
|
||||
contentLayout.getFastScroller().setOnDragHandlerListener(this);
|
||||
|
||||
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
|
||||
mRecyclerView.setLayoutManager(layoutManager);
|
||||
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
|
||||
mAdapter = new FavoritesAdapter(inflater, resources, mRecyclerView, Settings.getListMode());
|
||||
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
mRecyclerView.setDrawSelectorOnTop(true);
|
||||
mRecyclerView.hasFixedSize();
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
@@ -265,21 +260,15 @@ public class FavoritesScene extends BaseScene implements
|
||||
mRecyclerView.setOnItemLongClickListener(this);
|
||||
mRecyclerView.setChoiceMode(EasyRecyclerView.CHOICE_MODE_MULTIPLE_CUSTOM);
|
||||
mRecyclerView.setCustomCheckedListener(this);
|
||||
mAdapter = new FavoritesAdapter(LayoutInflater.from(getContext()),
|
||||
getContext(), mRecyclerView, layoutManager, Settings.getListMode());
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
mAdapter.register();
|
||||
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop() + paddingTopSB,
|
||||
mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom());
|
||||
|
||||
fastScroller.setPadding(fastScroller.getPaddingLeft(), fastScroller.getPaddingTop() + paddingTopSB,
|
||||
fastScroller.getPaddingRight(), fastScroller.getPaddingBottom());
|
||||
|
||||
refreshLayout.setHeaderTranslationY(paddingTopSB);
|
||||
|
||||
mLeftDrawable = new DrawerArrowDrawable(getContext());
|
||||
mLeftDrawable = new DrawerArrowDrawable(context);
|
||||
mSearchBar.setLeftDrawable(mLeftDrawable);
|
||||
mSearchBar.setRightDrawable(DrawableManager.getDrawable(getContext(), R.drawable.v_magnify_x24));
|
||||
mSearchBar.setRightDrawable(DrawableManager.getDrawable(context, R.drawable.v_magnify_x24));
|
||||
mSearchBar.setHelper(this);
|
||||
mSearchBar.setAllowEmptySearch(false);
|
||||
updateSearchBar();
|
||||
@@ -289,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) {
|
||||
@@ -308,15 +298,16 @@ public class FavoritesScene extends BaseScene implements
|
||||
}
|
||||
|
||||
private void guideCollections() {
|
||||
if (!Settings.getGuideCollections()) {
|
||||
Activity activity = getActivity2();
|
||||
if (null == activity || !Settings.getGuideCollections()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Display display = getActivity().getWindowManager().getDefaultDisplay();
|
||||
Display display = activity.getWindowManager().getDefaultDisplay();
|
||||
Point point = new Point();
|
||||
display.getSize(point);
|
||||
|
||||
new ShowcaseView.Builder(getActivity())
|
||||
mShowcaseView = new ShowcaseView.Builder(activity)
|
||||
.withMaterialShowcase()
|
||||
.setStyle(R.style.Guide)
|
||||
.setTarget(new PointTarget(point.x, point.y / 3))
|
||||
@@ -327,6 +318,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
.setShowcaseEventListener(new SimpleShowcaseEventListener() {
|
||||
@Override
|
||||
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
|
||||
mShowcaseView = null;
|
||||
ViewUtils.removeFromParent(showcaseView);
|
||||
Settings.putGuideCollections(false);
|
||||
openDrawer(Gravity.RIGHT);
|
||||
@@ -337,7 +329,8 @@ public class FavoritesScene extends BaseScene implements
|
||||
// keyword of mUrlBuilder, fav cat of mUrlBuilder, mFavCatArray.
|
||||
// They changed, call it
|
||||
private void updateSearchBar() {
|
||||
if (mUrlBuilder == null || mSearchBar == null || mFavCatArray == null) {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mUrlBuilder || null == mSearchBar || null == mFavCatArray) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -364,7 +357,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
// Update hint
|
||||
if (!ObjectUtils.equal(favCatName, mOldFavCat)) {
|
||||
Drawable searchImage = DrawableManager.getDrawable(getContext(), R.drawable.v_magnify_x24);
|
||||
Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
|
||||
SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
|
||||
ssb.append(getString(R.string.favorites_search_bar_hint, favCatName));
|
||||
int textSize = (int) (mSearchBar.getEditTextTextSize() * 1.25);
|
||||
@@ -386,20 +379,29 @@ public class FavoritesScene extends BaseScene implements
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mAdapter) {
|
||||
mAdapter.unregister();
|
||||
mAdapter = null;
|
||||
if (null != mShowcaseView) {
|
||||
ViewUtils.removeFromParent(mShowcaseView);
|
||||
mShowcaseView = null;
|
||||
}
|
||||
|
||||
if (null != mHelper) {
|
||||
if (1 == mHelper.getShownViewIndex()) {
|
||||
mHasFirstRefresh = false;
|
||||
}
|
||||
mHelper = null;
|
||||
}
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
if (null != mFabLayout) {
|
||||
removeAboveSnackView(mFabLayout);
|
||||
mFabLayout = null;
|
||||
}
|
||||
|
||||
mAdapter = null;
|
||||
|
||||
mRecyclerView = null;
|
||||
mSearchBar = null;
|
||||
mFabLayout = null;
|
||||
|
||||
mSearchBarMover = null;
|
||||
mLeftDrawable = null;
|
||||
@@ -408,21 +410,85 @@ public class FavoritesScene extends BaseScene implements
|
||||
mOldKeyword = null;
|
||||
}
|
||||
|
||||
private class InfoHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
private final TextView key;
|
||||
private final TextView value;
|
||||
|
||||
public InfoHolder(View itemView) {
|
||||
super(itemView);
|
||||
key = (TextView) ViewUtils.$$(itemView, R.id.key);
|
||||
value = (TextView) ViewUtils.$$(itemView, R.id.value);
|
||||
}
|
||||
}
|
||||
|
||||
private class InfoAdapter extends RecyclerView.Adapter<InfoHolder> {
|
||||
|
||||
private static final int TYPE_HEADER = 0;
|
||||
private static final int TYPE_DATA = 1;
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public InfoAdapter(LayoutInflater inflater) {
|
||||
mInflater = inflater;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
return 0 == position ? TYPE_HEADER : TYPE_DATA;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new InfoHolder(mInflater.inflate(TYPE_HEADER == viewType ?
|
||||
R.layout.item_favorite_info_header : R.layout.item_favorite_info_data, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("SetTextI18n")
|
||||
public void onBindViewHolder(InfoHolder holder, int position) {
|
||||
if (0 == position) {
|
||||
holder.key.setText(R.string.collections);
|
||||
holder.value.setText(R.string.count);
|
||||
holder.itemView.setEnabled(false);
|
||||
} else {
|
||||
if (null == mFavCatArray || null == mFavCountArray ||
|
||||
mFavCatArray.length < position || mFavCountArray.length < position) {
|
||||
return;
|
||||
}
|
||||
holder.key.setText(mFavCatArray[position - 1]);
|
||||
holder.value.setText(Integer.toString(mFavCountArray[position - 1]));
|
||||
holder.itemView.setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return 11;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
private void showFavoritesInfoDialog() {
|
||||
if (mFavCatArray == null || mFavCountArray == null) {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mFavCatArray || null == mFavCountArray) {
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(mAllCount).append("/").append(mAllLimit).append("\n");
|
||||
for (int i = 0, n = 10; i < n; i++) {
|
||||
sb.append(mFavCatArray[i]).append(": ").append(mFavCountArray[i]).append("\n");
|
||||
}
|
||||
|
||||
new AlertDialog.Builder(getContext())
|
||||
.setTitle(R.string.favorites_info)
|
||||
.setMessage(sb.toString())
|
||||
.show();
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(context);
|
||||
context = builder.getContext();
|
||||
final LayoutInflater inflater = LayoutInflater.from(context);
|
||||
EasyRecyclerView rv = (EasyRecyclerView) inflater.inflate(R.layout.dialog_recycler_view, null);
|
||||
rv.setAdapter(new InfoAdapter(inflater));
|
||||
rv.setLayoutManager(new LinearLayoutManager(context));
|
||||
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
|
||||
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(context, 1));
|
||||
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
|
||||
rv.addItemDecoration(decoration);
|
||||
rv.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
rv.setClipToPadding(false);
|
||||
builder.setView(rv).show();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -432,6 +498,9 @@ public class FavoritesScene extends BaseScene implements
|
||||
Toolbar toolbar = (Toolbar) ViewUtils.$$(view, R.id.toolbar);
|
||||
ListView listView = (ListView) view.findViewById(R.id.list_view);
|
||||
|
||||
final Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
toolbar.setTitle(R.string.collections);
|
||||
toolbar.inflateMenu(R.menu.drawer_favorites);
|
||||
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
|
||||
@@ -448,7 +517,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
items[1] = getString(R.string.local_favorites);
|
||||
String[] favCat = Settings.getFavCat();
|
||||
System.arraycopy(favCat, 0, items, 2, 10);
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.default_favorites_collection)
|
||||
.setItems(items, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
@@ -468,7 +537,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
if (mFavCatArray != null) {
|
||||
Collections.addAll(mDrawerList, mFavCatArray);
|
||||
}
|
||||
mDrawerAdapter = new ArrayAdapter<>(getContext(), R.layout.item_simple_list, mDrawerList);
|
||||
mDrawerAdapter = new ArrayAdapter<>(context, R.layout.item_simple_list, mDrawerList);
|
||||
listView.setAdapter(mDrawerAdapter);
|
||||
listView.setOnItemClickListener(this);
|
||||
|
||||
@@ -485,6 +554,10 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (null != mShowcaseView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
|
||||
mRecyclerView.outOfCustomChoiceMode();
|
||||
} else if (mSearchMode) {
|
||||
@@ -656,7 +729,8 @@ public class FavoritesScene extends BaseScene implements
|
||||
@Override
|
||||
@Implemented(FabLayout.OnClickFabListener.class)
|
||||
public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) {
|
||||
if (mRecyclerView == null || mHelper == null || !mRecyclerView.isInCustomChoice()) {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mRecyclerView || null == mHelper || !mRecyclerView.isInCustomChoice()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -671,7 +745,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
switch (position) {
|
||||
case 0: { // Delete
|
||||
DeleteDialogHelper helper = new DeleteDialogHelper();
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.delete_favorites_dialog_title)
|
||||
.setMessage(getString(R.string.delete_favorites_dialog_message, mModifyGiList.size()))
|
||||
.setPositiveButton(android.R.string.ok, helper)
|
||||
@@ -685,7 +759,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
String[] array = new String[11];
|
||||
array[0] = getString(R.string.local_favorites);
|
||||
System.arraycopy(Settings.getFavCat(), 0, array, 1, 10);
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.move_favorites_dialog_title)
|
||||
.setItems(array, helper)
|
||||
.setOnCancelListener(helper)
|
||||
@@ -802,17 +876,10 @@ public class FavoritesScene extends BaseScene implements
|
||||
}
|
||||
|
||||
mFavCountArray = result.countArray;
|
||||
if (result.current != -1) {
|
||||
mAllCount = result.current;
|
||||
}
|
||||
if (result.limit != -1) {
|
||||
mAllLimit = result.limit;
|
||||
}
|
||||
|
||||
updateSearchBar();
|
||||
mHelper.setPages(taskId, result.pages);
|
||||
mHelper.onGetPageData(taskId, result.galleryInfoList);
|
||||
SimpleHandler.getInstance().post(mReturnSearchBarRunnable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,6 +890,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void onGetFavoritesLocal(String keyword, int taskId) {
|
||||
if (mHelper != null && mHelper.isCurrentTask(taskId)) {
|
||||
List<GalleryInfo> list;
|
||||
@@ -832,12 +900,12 @@ public class FavoritesScene extends BaseScene implements
|
||||
list = EhDB.searchLocalFavorites(keyword);
|
||||
}
|
||||
if (list.size() == 0) {
|
||||
mHelper.onGetException(taskId, new NotFoundException());
|
||||
mHelper.setPages(taskId, 0);
|
||||
mHelper.onGetPageData(taskId, Collections.EMPTY_LIST);
|
||||
} else {
|
||||
mHelper.setPages(taskId, 1);
|
||||
mHelper.onGetPageData(taskId, list);
|
||||
}
|
||||
SimpleHandler.getInstance().post(mReturnSearchBarRunnable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,9 +998,9 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
private class FavoritesAdapter extends GalleryAdapter {
|
||||
|
||||
public FavoritesAdapter(LayoutInflater inflater, Context context,
|
||||
RecyclerView recyclerView, GridLayoutManager layoutManager, int type) {
|
||||
super(inflater, context, recyclerView, layoutManager, type);
|
||||
public FavoritesAdapter(@NonNull LayoutInflater inflater, @NonNull Resources resources,
|
||||
@NonNull RecyclerView recyclerView, int type) {
|
||||
super(inflater, resources, recyclerView, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -951,7 +1019,8 @@ public class FavoritesScene extends BaseScene implements
|
||||
|
||||
@Override
|
||||
protected void getPageData(final int taskId, int type, int page) {
|
||||
if (mUrlBuilder == null || mClient == null) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || null == mUrlBuilder || null == mClient ) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -973,7 +1042,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_ADD_FAVORITES_RANGE);
|
||||
request.setCallback(new AddFavoritesListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(),
|
||||
activity.getStageId(), getTag(),
|
||||
taskId, mUrlBuilder.getKeyword()));
|
||||
request.setArgs(gidArray, tokenArray, mModifyFavCat);
|
||||
mClient.execute(request);
|
||||
@@ -987,7 +1056,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
String url;
|
||||
if (local) {
|
||||
// Local fav is shown now, but operation need be done for cloud fav
|
||||
url = EhUrl.URL_FAVORITES;
|
||||
url = EhUrl.getFavoritesUrl();
|
||||
} else {
|
||||
url = mUrlBuilder.build();
|
||||
}
|
||||
@@ -996,7 +1065,7 @@ public class FavoritesScene extends BaseScene implements
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_MODIFY_FAVORITES);
|
||||
request.setCallback(new GetFavoritesListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(),
|
||||
activity.getStageId(), getTag(),
|
||||
taskId, local, mUrlBuilder.getKeyword()));
|
||||
request.setArgs(url, gidArray, mModifyFavCat, Settings.getShowJpnTitle());
|
||||
mClient.execute(request);
|
||||
@@ -1015,24 +1084,16 @@ public class FavoritesScene extends BaseScene implements
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_GET_FAVORITES);
|
||||
request.setCallback(new GetFavoritesListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(),
|
||||
activity.getStageId(), getTag(),
|
||||
taskId, false, mUrlBuilder.getKeyword()));
|
||||
request.setArgs(url, Settings.getShowJpnTitle());
|
||||
mClient.execute(request);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHideRecyclerView() {
|
||||
super.onHideRecyclerView();
|
||||
if (mSearchBarMover != null) {
|
||||
mSearchBarMover.showSearchBar();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Context getContext() {
|
||||
return FavoritesScene.this.getContext();
|
||||
return FavoritesScene.this.getContext2();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1060,6 +1121,22 @@ public class FavoritesScene extends BaseScene implements
|
||||
mAdapter.notifyItemRangeInserted(positionStart, itemCount);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShowView(View hiddenView, View shownView) {
|
||||
if (null != mSearchBarMover) {
|
||||
mSearchBarMover.showSearchBar();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onScrollToPosition(int postion) {
|
||||
if (0 == postion) {
|
||||
if (null != mSearchBarMover) {
|
||||
mSearchBarMover.showSearchBar();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class AddFavoritesListener extends EhCallback<FavoritesScene, Void> {
|
||||
|
||||
@@ -16,15 +16,14 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.support.annotation.IntDef;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.widget.GridLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.StaggeredGridLayoutManager;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
@@ -32,20 +31,18 @@ import android.widget.TextView;
|
||||
|
||||
import com.hippo.drawable.TriangleDrawable;
|
||||
import com.hippo.easyrecyclerview.MarginItemDecoration;
|
||||
import com.hippo.ehviewer.Constants;
|
||||
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.util.ApiHelper;
|
||||
import com.hippo.util.LayoutUtils2;
|
||||
import com.hippo.yorozuya.Messenger;
|
||||
import com.hippo.ehviewer.widget.TileThumb;
|
||||
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> implements Messenger.Receiver {
|
||||
abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
|
||||
|
||||
@IntDef({TYPE_LIST, TYPE_GRID})
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@@ -56,27 +53,34 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> implem
|
||||
public static final int TYPE_GRID = 1;
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
private final Context mContext;
|
||||
private final Resources mResources;
|
||||
private final RecyclerView mRecyclerView;
|
||||
private final GridLayoutManager mLayoutManager;
|
||||
private RecyclerView.ItemDecoration mGirdDecoration;
|
||||
private final AutoStaggeredGridLayoutManager mLayoutManager;
|
||||
private final int mPaddingTopSB;
|
||||
private MarginItemDecoration mListDecoration;
|
||||
private MarginItemDecoration mGirdDecoration;
|
||||
private int mType = TYPE_INVALID;
|
||||
|
||||
public GalleryAdapter(LayoutInflater inflater, Context context,
|
||||
RecyclerView recyclerView, GridLayoutManager layoutManager, int type) {
|
||||
public GalleryAdapter(@NonNull LayoutInflater inflater, @NonNull Resources resources,
|
||||
@NonNull RecyclerView recyclerView, int type) {
|
||||
mInflater = inflater;
|
||||
mContext = context;
|
||||
mResources = context.getResources();
|
||||
mResources = resources;
|
||||
mRecyclerView = recyclerView;
|
||||
mLayoutManager = layoutManager;
|
||||
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> implem
|
||||
}
|
||||
mType = type;
|
||||
|
||||
RecyclerView recyclerView = mRecyclerView;
|
||||
switch (type) {
|
||||
default:
|
||||
case GalleryAdapter.TYPE_LIST: {
|
||||
int minWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_list_min_width);
|
||||
int spanCount = LayoutUtils2.calculateSpanCount(mContext, minWidth);
|
||||
mLayoutManager.setSpanCount(spanCount);
|
||||
int columnWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_list_column_width);
|
||||
mLayoutManager.setColumnSize(columnWidth);
|
||||
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 minWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_grid_min_width);
|
||||
int spanCount = LayoutUtils2.calculateSpanCount(mContext, minWidth);
|
||||
mLayoutManager.setSpanCount(spanCount);
|
||||
if (null == mGirdDecoration) {
|
||||
mGirdDecoration = new MarginItemDecoration(
|
||||
mResources.getDimensionPixelOffset(R.dimen.list_content_interval));
|
||||
int columnWidth = mResources.getDimensionPixelOffset(Settings.getThumbSizeResId());
|
||||
mLayoutManager.setColumnSize(columnWidth);
|
||||
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> implem
|
||||
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) {
|
||||
@@ -163,13 +183,14 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> implem
|
||||
break;
|
||||
}
|
||||
case TYPE_GRID: {
|
||||
((TileThumb) holder.thumb).setThumbSize(gi.thumbWidth, gi.thumbHeight);
|
||||
holder.thumb.load(EhCacheKeyFactory.getThumbKey(gi.gid), gi.thumb);
|
||||
View category = holder.category;
|
||||
Drawable drawable = category.getBackground();
|
||||
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);
|
||||
}
|
||||
@@ -179,23 +200,9 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> implem
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
|
||||
public void register() {
|
||||
Messenger.getInstance().register(Constants.MESSAGE_ID_LIST_MODE, this);
|
||||
}
|
||||
|
||||
public void unregister() {
|
||||
Messenger.getInstance().unregister(Constants.MESSAGE_ID_LIST_MODE, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceive(int id, Object obj) {
|
||||
setType(Settings.getListMode());
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
}
|
||||
@@ -17,23 +17,36 @@
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.annotation.TargetApi;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Parcelable;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.design.widget.FloatingActionButton;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.DefaultItemAnimator;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.text.Spannable;
|
||||
import android.text.SpannableString;
|
||||
import android.text.SpannableStringBuilder;
|
||||
import android.text.TextUtils;
|
||||
import android.text.style.ClickableSpan;
|
||||
import android.text.style.ForegroundColorSpan;
|
||||
import android.text.style.RelativeSizeSpan;
|
||||
import android.text.style.StyleSpan;
|
||||
import android.text.style.URLSpan;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewAnimationUtils;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ImageView;
|
||||
@@ -48,40 +61,65 @@ import com.hippo.ehviewer.client.EhClient;
|
||||
import com.hippo.ehviewer.client.EhRequest;
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
import com.hippo.ehviewer.client.data.GalleryComment;
|
||||
import com.hippo.rippleold.RippleSalon;
|
||||
import com.hippo.ehviewer.client.parser.VoteCommentParser;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.reveal.ViewAnimationUtils;
|
||||
import com.hippo.ripple.Ripple;
|
||||
import com.hippo.scene.SceneFragment;
|
||||
import com.hippo.scene.StageActivity;
|
||||
import com.hippo.text.Html;
|
||||
import com.hippo.text.URLImageGetter;
|
||||
import com.hippo.util.ActivityHelper;
|
||||
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;
|
||||
import com.hippo.yorozuya.IntList;
|
||||
import com.hippo.yorozuya.LayoutUtils;
|
||||
import com.hippo.yorozuya.ResourcesUtils;
|
||||
import com.hippo.yorozuya.SimpleAnimatorListener;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class GalleryCommentsScene extends ToolbarScene
|
||||
implements EasyRecyclerView.OnItemClickListener,
|
||||
EasyRecyclerView.OnItemLongClickListener, View.OnClickListener {
|
||||
View.OnClickListener {
|
||||
|
||||
public static final String TAG = GalleryCommentsScene.class.getSimpleName();
|
||||
|
||||
public static final String KEY_API_UID = "api_uid";
|
||||
public static final String KEY_API_KEY = "api_key";
|
||||
public static final String KEY_GID = "gid";
|
||||
public static final String KEY_TOKEN = "token";
|
||||
public static final String KEY_COMMENTS = "comments";
|
||||
|
||||
private long mApiUid;
|
||||
private String mApiKey;
|
||||
private long mGid;
|
||||
private String mToken;
|
||||
@Nullable
|
||||
private GalleryComment[] mComments;
|
||||
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
@Nullable
|
||||
private FabLayout mFabLayout;
|
||||
@Nullable
|
||||
private FloatingActionButton mFab;
|
||||
@Nullable
|
||||
private View mEditPanel;
|
||||
@Nullable
|
||||
private ImageView mSendImage;
|
||||
@Nullable
|
||||
private EditText mEditText;
|
||||
|
||||
@Nullable
|
||||
private CommentAdapter mAdapter;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
|
||||
private boolean mInAnimation = false;
|
||||
@@ -102,7 +140,9 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
return;
|
||||
}
|
||||
|
||||
mGid = args.getLong(KEY_GID, -1);
|
||||
mApiUid = args.getLong(KEY_API_UID, -1L);
|
||||
mApiKey = args.getString(KEY_API_KEY);
|
||||
mGid = args.getLong(KEY_GID, -1L);
|
||||
mToken = args.getString(KEY_TOKEN, null);
|
||||
Parcelable[] parcelables = args.getParcelableArray(KEY_COMMENTS);
|
||||
if (parcelables instanceof GalleryComment[]) {
|
||||
@@ -115,7 +155,9 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void onRestore(@NonNull Bundle savedInstanceState) {
|
||||
mGid = savedInstanceState.getLong(KEY_GID, -1);
|
||||
mApiUid = savedInstanceState.getLong(KEY_API_UID, -1L);
|
||||
mApiKey = savedInstanceState.getString(KEY_API_KEY);
|
||||
mGid = savedInstanceState.getLong(KEY_GID, -1L);
|
||||
mToken = savedInstanceState.getString(KEY_TOKEN, null);
|
||||
Parcelable[] parcelables = savedInstanceState.getParcelableArray(KEY_COMMENTS);
|
||||
if (parcelables instanceof GalleryComment[]) {
|
||||
@@ -126,6 +168,8 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
@Override
|
||||
public void onSaveInstanceState(Bundle outState) {
|
||||
super.onSaveInstanceState(outState);
|
||||
outState.putLong(KEY_API_UID, mApiUid);
|
||||
outState.putString(KEY_API_KEY, mApiKey);
|
||||
outState.putLong(KEY_GID, mGid);
|
||||
outState.putString(KEY_TOKEN, mToken);
|
||||
outState.putParcelableArray(KEY_COMMENTS, mComments);
|
||||
@@ -133,48 +177,55 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_gallery_comments, container, false);
|
||||
EasyRecyclerView recyclerView = (EasyRecyclerView) view.findViewById(R.id.recycler_view);
|
||||
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
|
||||
TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
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);
|
||||
|
||||
int paddingBottomFab = getResources().getDimensionPixelOffset(R.dimen.list_padding_bottom_fab);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Resources resources = context.getResources();
|
||||
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_weird_face);
|
||||
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
|
||||
mAdapter = new CommentAdapter();
|
||||
recyclerView.setAdapter(mAdapter);
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(context,
|
||||
LinearLayoutManager.VERTICAL, false));
|
||||
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
|
||||
LinearDividerItemDecoration.VERTICAL, getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(getContext(), 1));
|
||||
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(context, 1));
|
||||
decoration.setShowLastDivider(true);
|
||||
recyclerView.addItemDecoration(decoration);
|
||||
recyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
|
||||
recyclerView.setHasFixedSize(true);
|
||||
recyclerView.setOnItemClickListener(this);
|
||||
recyclerView.setOnItemLongClickListener(this);
|
||||
recyclerView.setPadding(recyclerView.getPaddingLeft(), recyclerView.getPaddingTop(),
|
||||
recyclerView.getPaddingRight(), recyclerView.getPaddingBottom() + paddingBottomFab);
|
||||
mRecyclerView.addItemDecoration(decoration);
|
||||
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
mRecyclerView.setHasFixedSize(true);
|
||||
mRecyclerView.setOnItemClickListener(this);
|
||||
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop(),
|
||||
mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom() + paddingBottomFab);
|
||||
// Cancel change animator
|
||||
RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator();
|
||||
if (itemAnimator instanceof DefaultItemAnimator) {
|
||||
((DefaultItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
|
||||
}
|
||||
|
||||
mSendImage.setOnClickListener(this);
|
||||
mFab.setOnClickListener(this);
|
||||
|
||||
mViewTransition = new ViewTransition(recyclerView, tip);
|
||||
addAboveSnackView(mEditPanel);
|
||||
addAboveSnackView(mFabLayout);
|
||||
|
||||
if (mComments == null || mComments.length <= 0) {
|
||||
mViewTransition.showView(1);
|
||||
} else {
|
||||
mViewTransition.showView(0);
|
||||
}
|
||||
mViewTransition = new ViewTransition(mRecyclerView, tip);
|
||||
|
||||
updateView(false);
|
||||
|
||||
return view;
|
||||
}
|
||||
@@ -182,6 +233,23 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
if (null != mEditPanel) {
|
||||
removeAboveSnackView(mEditPanel);
|
||||
mEditPanel = null;
|
||||
}
|
||||
if (null != mFabLayout) {
|
||||
removeAboveSnackView(mFabLayout);
|
||||
mFabLayout = null;
|
||||
}
|
||||
|
||||
mFab = null;
|
||||
mSendImage = null;
|
||||
mEditText = null;
|
||||
mAdapter = null;
|
||||
mViewTransition = null;
|
||||
}
|
||||
@@ -198,8 +266,147 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
onBackPressed();
|
||||
}
|
||||
|
||||
private void voteComment(long id, int vote) {
|
||||
Context context = getContext2();
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == context || null == activity) {
|
||||
return;
|
||||
}
|
||||
|
||||
EhRequest request = new EhRequest()
|
||||
.setMethod(EhClient.METHOD_VOTE_COMMENT)
|
||||
.setArgs(mApiUid, mApiKey, mGid, mToken, id, vote)
|
||||
.setCallback(new VoteCommentListener(context,
|
||||
activity.getStageId(), getTag()));
|
||||
EhApplication.getEhClient(context).execute(request);
|
||||
}
|
||||
|
||||
private class InfoHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
private final TextView key;
|
||||
private final TextView value;
|
||||
|
||||
public InfoHolder(View itemView) {
|
||||
super(itemView);
|
||||
key = (TextView) ViewUtils.$$(itemView, R.id.key);
|
||||
value = (TextView) ViewUtils.$$(itemView, R.id.value);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
public void showVoteStatusDialog(Context context, String voteStatus) {
|
||||
String[] temp = StringUtils.split(voteStatus, ',');
|
||||
final int length = temp.length;
|
||||
final String[] userArray = new String[length];
|
||||
final String[] voteArray = new String[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
String str = StringUtils.trim(temp[i]);
|
||||
int index = str.lastIndexOf(' ');
|
||||
if (index < 0) {
|
||||
Log.d(TAG, "Something wrong happened about vote state");
|
||||
userArray[i] = str;
|
||||
voteArray[i] = "";
|
||||
} else {
|
||||
userArray[i] = StringUtils.trim(str.substring(0, index));
|
||||
voteArray[i] = StringUtils.trim(str.substring(index + 1));
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(context);
|
||||
context = builder.getContext();
|
||||
final LayoutInflater inflater = LayoutInflater.from(context);
|
||||
EasyRecyclerView rv = (EasyRecyclerView) inflater.inflate(R.layout.dialog_recycler_view, null);
|
||||
rv.setAdapter(new RecyclerView.Adapter<InfoHolder>() {
|
||||
@Override
|
||||
public InfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new InfoHolder(inflater.inflate(R.layout.item_favorite_info_data, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(InfoHolder holder, int position) {
|
||||
holder.key.setText(userArray[position]);
|
||||
holder.value.setText(voteArray[position]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return length;
|
||||
}
|
||||
});
|
||||
rv.setLayoutManager(new LinearLayoutManager(context));
|
||||
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
|
||||
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(context, 1));
|
||||
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
|
||||
rv.addItemDecoration(decoration);
|
||||
rv.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
rv.setClipToPadding(false);
|
||||
builder.setView(rv).show();
|
||||
}
|
||||
|
||||
private void showCommentDialog(int position) {
|
||||
final Context context = getContext2();
|
||||
if (null == context || null == mComments || position >= mComments.length || position < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
final GalleryComment comment = mComments[position];
|
||||
List<String> menu = new ArrayList<>();
|
||||
final IntList menuId = new IntList();
|
||||
Resources resources = context.getResources();
|
||||
if (0 == comment.id || mApiUid < 0) {
|
||||
// 0 id is uploader comment, can't vote
|
||||
// Not sign in, can't vote
|
||||
menu.add(resources.getString(R.string.copy_comment_text));
|
||||
menuId.add(R.id.copy);
|
||||
} else {
|
||||
menu.add(resources.getString(R.string.copy_comment_text));
|
||||
menuId.add(R.id.copy);
|
||||
menu.add(resources.getString(comment.voteUp ? R.string.cancel_vote_up : R.string.vote_up));
|
||||
menuId.add(R.id.vote_up);
|
||||
menu.add(resources.getString(comment.voteDown ? R.string.cancel_vote_down : R.string.vote_down));
|
||||
menuId.add(R.id.vote_down);
|
||||
}
|
||||
if (!TextUtils.isEmpty(comment.voteState)) {
|
||||
menu.add(resources.getString(R.string.check_vote_status));
|
||||
menuId.add(R.id.check_vote_status);
|
||||
}
|
||||
|
||||
new AlertDialog.Builder(context)
|
||||
.setItems(menu.toArray(new String[menu.size()]), new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
if (which < 0 || which >= menuId.size()) {
|
||||
return;
|
||||
}
|
||||
int id = menuId.get(which);
|
||||
switch (id) {
|
||||
case R.id.copy:
|
||||
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
cmb.setPrimaryClip(ClipData.newPlainText(null, comment.comment));
|
||||
showTip(R.string.copied_to_clipboard, LENGTH_SHORT);
|
||||
break;
|
||||
case R.id.vote_up:
|
||||
voteComment(comment.id, 1);
|
||||
break;
|
||||
case R.id.vote_down:
|
||||
voteComment(comment.id, -1);
|
||||
break;
|
||||
case R.id.check_vote_status:
|
||||
showVoteStatusDialog(context, comment.voteState);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
Activity activity = getActivity2();
|
||||
if (null == activity) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RecyclerView.ViewHolder holder = parent.getChildViewHolder(view);
|
||||
if (holder instanceof CommentHolder) {
|
||||
CommentHolder commentHolder = (CommentHolder) holder;
|
||||
@@ -207,20 +414,33 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
commentHolder.comment.clearCurrentSpan();
|
||||
|
||||
if (span instanceof URLSpan) {
|
||||
UrlOpener.openUrl(getActivity(), ((URLSpan) span).getURL(), true, true);
|
||||
UrlOpener.openUrl(activity, ((URLSpan) span).getURL(), true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
showCommentDialog(position);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
return false;
|
||||
private void updateView(boolean animation) {
|
||||
if (null == mViewTransition) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mComments == null || mComments.length <= 0) {
|
||||
mViewTransition.showView(1, animation);
|
||||
} else {
|
||||
mViewTransition.showView(0, animation);
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private void showEditPanelWithAnimationL() {
|
||||
private void showEditPanelWithAnimation() {
|
||||
if (null == mFab || null == mEditPanel) {
|
||||
return;
|
||||
}
|
||||
|
||||
mInAnimation = true;
|
||||
mFab.setTranslationX(0.0f);
|
||||
mFab.setTranslationY(0.0f);
|
||||
@@ -238,10 +458,10 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
int halfW = mEditPanel.getWidth() / 2;
|
||||
int halfH = mEditPanel.getHeight() / 2;
|
||||
Animator animator = ViewAnimationUtils.createCircularReveal(mEditPanel, halfW, halfH, 0,
|
||||
(float) Math.hypot(halfW, halfH)).setDuration(300);
|
||||
(float) Math.hypot(halfW, halfH)).setDuration(300L);
|
||||
animator.addListener(new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
public void onAnimationEnd(Animator a) {
|
||||
mInAnimation = false;
|
||||
}
|
||||
});
|
||||
@@ -252,21 +472,22 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
private void showEditPanel(boolean animation) {
|
||||
if (animation) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
showEditPanelWithAnimationL();
|
||||
} else {
|
||||
// TODO Add animation for pre-L
|
||||
mFab.setVisibility(View.INVISIBLE);
|
||||
mEditPanel.setVisibility(View.VISIBLE);
|
||||
}
|
||||
showEditPanelWithAnimation();
|
||||
} else {
|
||||
if (null == mFab || null == mEditPanel) {
|
||||
return;
|
||||
}
|
||||
|
||||
mFab.setVisibility(View.INVISIBLE);
|
||||
mEditPanel.setVisibility(View.VISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private void hideEditPanelWithAnimationL() {
|
||||
private void hideEditPanelWithAnimation() {
|
||||
if (null == mFab || null == mEditPanel) {
|
||||
return;
|
||||
}
|
||||
|
||||
mInAnimation = true;
|
||||
int halfW = mEditPanel.getWidth() / 2;
|
||||
int halfH = mEditPanel.getHeight() / 2;
|
||||
@@ -274,7 +495,7 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
(float) Math.hypot(halfW, halfH), 0.0f).setDuration(300L);
|
||||
animator.addListener(new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
public void onAnimationEnd(Animator a) {
|
||||
mEditPanel.setVisibility(View.GONE);
|
||||
mFab.setVisibility(View.VISIBLE);
|
||||
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
|
||||
@@ -283,7 +504,8 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
mFab.setY(fabStartY);
|
||||
mFab.setScaleX(0.0f);
|
||||
mFab.setScaleY(0.0f);
|
||||
mFab.animate().translationX(0.0f).translationY(0.0f).scaleX(1.0f).scaleY(1.0f)
|
||||
mFab.setRotation(-45.0f);
|
||||
mFab.animate().translationX(0.0f).translationY(0.0f).scaleX(1.0f).scaleY(1.0f).rotation(0.0f)
|
||||
.setInterpolator(AnimationUtils.SLOW_FAST_SLOW_INTERPOLATOR)
|
||||
.setDuration(300L).setListener(new SimpleAnimatorListener() {
|
||||
@Override
|
||||
@@ -298,14 +520,12 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
private void hideEditPanel(boolean animation) {
|
||||
if (animation) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
hideEditPanelWithAnimationL();
|
||||
} else {
|
||||
// TODO Add animation for pre-L
|
||||
mFab.setVisibility(View.VISIBLE);
|
||||
mEditPanel.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
hideEditPanelWithAnimation();
|
||||
} else {
|
||||
if (null == mFab || null == mEditPanel) {
|
||||
return;
|
||||
}
|
||||
|
||||
mFab.setVisibility(View.VISIBLE);
|
||||
mEditPanel.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
@@ -314,7 +534,7 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
@Nullable
|
||||
private String getGalleryDetailUrl() {
|
||||
if (mGid != -1 && mToken != null) {
|
||||
return EhUrl.getGalleryDetailUrl(mGid, mToken, 0, true);
|
||||
return EhUrl.getGalleryDetailUrl(mGid, mToken, 0, false);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -322,6 +542,12 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Context context = getContext2();
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == context || null == activity || null == mEditText) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mFab == v) {
|
||||
if (!mInAnimation) {
|
||||
showEditPanel(true);
|
||||
@@ -341,10 +567,10 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
EhRequest request = new EhRequest()
|
||||
.setMethod(EhClient.METHOD_GET_COMMENT_GALLERY)
|
||||
.setArgs(url, comment)
|
||||
.setCallback(new CommentGalleryListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag()));
|
||||
EhApplication.getEhClient(getContext()).execute(request);
|
||||
ActivityHelper.hideSoftInput(getActivity());
|
||||
.setCallback(new CommentGalleryListener(context,
|
||||
activity.getStageId(), getTag()));
|
||||
EhApplication.getEhClient(context).execute(request);
|
||||
hideSoftInput();
|
||||
hideEditPanel(true);
|
||||
}
|
||||
}
|
||||
@@ -355,7 +581,7 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
if (mInAnimation) {
|
||||
return;
|
||||
}
|
||||
if (mEditPanel.getVisibility() == View.VISIBLE) {
|
||||
if (null != mEditPanel && mEditPanel.getVisibility() == View.VISIBLE) {
|
||||
hideEditPanel(true);
|
||||
} else {
|
||||
finish();
|
||||
@@ -364,9 +590,9 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
private class CommentHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
public TextView user;
|
||||
public TextView time;
|
||||
public LinkifyTextView comment;
|
||||
public final TextView user;
|
||||
public final TextView time;
|
||||
public final LinkifyTextView comment;
|
||||
|
||||
public CommentHolder(View itemView) {
|
||||
super(itemView);
|
||||
@@ -378,19 +604,47 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
|
||||
private class CommentAdapter extends RecyclerView.Adapter<CommentHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public CommentAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new CommentHolder(getActivity().getLayoutInflater()
|
||||
.inflate(R.layout.item_gallery_comment, parent, false));
|
||||
return new CommentHolder(mInflater.inflate(R.layout.item_gallery_comment, parent, false));
|
||||
}
|
||||
|
||||
public CharSequence generateComment(Context context, TextView textView, GalleryComment comment) {
|
||||
SpannableStringBuilder ssb = Html.fromHtml(comment.comment, new URLImageGetter(textView,
|
||||
EhApplication.getConaco(context)), null);
|
||||
|
||||
if (0 != comment.id && 0 != comment.score) {
|
||||
int score = comment.score;
|
||||
String scoreString = score > 0 ? "+" + score : Integer.toString(score);
|
||||
SpannableString ss = new SpannableString(scoreString);
|
||||
ss.setSpan(new RelativeSizeSpan(0.8f), 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
ss.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.secondary_text_default_light))
|
||||
, 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
ssb.append(" ").append(ss);
|
||||
}
|
||||
|
||||
return TextUrl.handleTextUrl(ssb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(CommentHolder holder, int position) {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mComments) {
|
||||
return;
|
||||
}
|
||||
|
||||
GalleryComment comment = mComments[position];
|
||||
holder.user.setText(comment.user);
|
||||
holder.time.setText(ReadableTime.getTimeAgo(comment.time));
|
||||
holder.comment.setText(TextUrl.handleTextUrl(Html.fromHtml(comment.comment,
|
||||
new URLImageGetter(holder.comment, EhApplication.getConaco(getContext())), null)));
|
||||
holder.comment.setText(generateComment(context, holder.comment, comment));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -400,6 +654,10 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
}
|
||||
|
||||
private void onCommentGallerySuccess(GalleryComment[] result) {
|
||||
if (null == mAdapter) {
|
||||
return;
|
||||
}
|
||||
|
||||
mComments = result;
|
||||
mAdapter.notifyDataSetChanged();
|
||||
Bundle re = new Bundle();
|
||||
@@ -410,6 +668,45 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
if (mEditText != null) {
|
||||
mEditText.setText("");
|
||||
}
|
||||
|
||||
updateView(true);
|
||||
}
|
||||
|
||||
private void onVoteCommentSuccess(VoteCommentParser.Result result) {
|
||||
if (null == mAdapter || null == mComments) {
|
||||
return;
|
||||
}
|
||||
|
||||
int position = -1;
|
||||
for (int i = 0, n = mComments.length; i < n; i++) {
|
||||
GalleryComment comment = mComments[i];
|
||||
if (comment.id == result.id) {
|
||||
position = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (-1 == position) {
|
||||
Log.d(TAG, "Can't find comment with id " + result.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Update comment
|
||||
GalleryComment comment = mComments[position];
|
||||
comment.score = result.score;
|
||||
if (result.expectVote > 0) {
|
||||
comment.voteUp = 0 != result.vote;
|
||||
comment.voteDown = false;
|
||||
} else {
|
||||
comment.voteDown = 0 != result.vote;
|
||||
comment.voteUp = false;
|
||||
}
|
||||
|
||||
mAdapter.notifyItemChanged(position);
|
||||
|
||||
Bundle re = new Bundle();
|
||||
re.putParcelableArray(KEY_COMMENTS, mComments);
|
||||
setResult(SceneFragment.RESULT_OK, re);
|
||||
}
|
||||
|
||||
private static class CommentGalleryListener extends EhCallback<GalleryCommentsScene, GalleryComment[]> {
|
||||
@@ -442,4 +739,37 @@ public final class GalleryCommentsScene extends ToolbarScene
|
||||
return scene instanceof GalleryCommentsScene;
|
||||
}
|
||||
}
|
||||
|
||||
private static class VoteCommentListener extends EhCallback<GalleryCommentsScene, VoteCommentParser.Result> {
|
||||
|
||||
public VoteCommentListener(Context context, int stageId, String sceneTag) {
|
||||
super(context, stageId, sceneTag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(VoteCommentParser.Result result) {
|
||||
showTip(result.expectVote > 0 ?
|
||||
(0 != result.vote ? R.string.vote_up_successfully : R.string.cancel_vote_up_successfully) :
|
||||
(0 != result.vote ? R.string.vote_down_successfully : R.string.cancel_vote_down_successfully),
|
||||
LENGTH_SHORT);
|
||||
|
||||
GalleryCommentsScene scene = getScene();
|
||||
if (scene != null) {
|
||||
scene.onVoteCommentSuccess(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Exception e) {
|
||||
showTip(R.string.vote_failed, LENGTH_SHORT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {}
|
||||
|
||||
@Override
|
||||
public boolean isInstance(SceneFragment scene) {
|
||||
return scene instanceof GalleryCommentsScene;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -36,7 +36,8 @@ 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;
|
||||
|
||||
@@ -56,6 +57,9 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
@Nullable
|
||||
private ArrayList<String> mValues;
|
||||
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
@@ -79,7 +83,8 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
return;
|
||||
}
|
||||
|
||||
Resources resources = getResources();
|
||||
Resources resources = getResources2();
|
||||
AssertUtils.assertNotNull(resources);
|
||||
mKeys.add(resources.getString(R.string.header_key));
|
||||
mValues.add(resources.getString(R.string.header_value));
|
||||
mKeys.add(resources.getString(R.string.key_gid));
|
||||
@@ -110,14 +115,12 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
mValues.add(Integer.toString(gd.pages));
|
||||
mKeys.add(resources.getString(R.string.key_size));
|
||||
mValues.add(gd.size);
|
||||
mKeys.add(resources.getString(R.string.key_resize));
|
||||
mValues.add(gd.resize);
|
||||
mKeys.add(resources.getString(R.string.key_favorites));
|
||||
mValues.add(Integer.toString(gd.favoredTimes));
|
||||
mKeys.add(resources.getString(R.string.key_favorite_count));
|
||||
mValues.add(Integer.toString(gd.favoriteCount));
|
||||
mKeys.add(resources.getString(R.string.key_favorited));
|
||||
mValues.add(Boolean.toString(gd.isFavored));
|
||||
mKeys.add(resources.getString(R.string.key_rates));
|
||||
mValues.add(Integer.toString(gd.ratedTimes));
|
||||
mValues.add(Boolean.toString(gd.isFavorited));
|
||||
mKeys.add(resources.getString(R.string.key_rating_count));
|
||||
mValues.add(Integer.toString(gd.ratingCount));
|
||||
mKeys.add(resources.getString(R.string.key_rating));
|
||||
mValues.add(Float.toString(gd.rating));
|
||||
mKeys.add(resources.getString(R.string.key_torrents));
|
||||
@@ -147,23 +150,26 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
@SuppressWarnings("deprecation")
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_gallery_info, container, false);
|
||||
|
||||
EasyRecyclerView recyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
|
||||
InfoAdapter adapter = new InfoAdapter();
|
||||
recyclerView.setAdapter(adapter);
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
|
||||
mRecyclerView.setAdapter(adapter);
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
|
||||
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
|
||||
LinearDividerItemDecoration.VERTICAL, getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(getContext(), 1));
|
||||
decoration.setPadding(getResources().getDimensionPixelOffset(R.dimen.keyline_margin));
|
||||
recyclerView.addItemDecoration(decoration);
|
||||
recyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
|
||||
recyclerView.setClipToPadding(false);
|
||||
recyclerView.setHasFixedSize(true);
|
||||
recyclerView.setOnItemClickListener(this);
|
||||
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
|
||||
LayoutUtils.dp2pix(context, 1));
|
||||
decoration.setPadding(context.getResources().getDimensionPixelOffset(R.dimen.keyline_margin));
|
||||
mRecyclerView.addItemDecoration(decoration);
|
||||
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
mRecyclerView.setHasFixedSize(true);
|
||||
mRecyclerView.setOnItemClickListener(this);
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -174,10 +180,21 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
if (position != 0 && mValues != null) {
|
||||
ClipboardManager cmb = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
Context context = getContext2();
|
||||
if (null != context && 0 != position && null != mValues) {
|
||||
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
cmb.setPrimaryClip(ClipData.newPlainText(null, mValues.get(position)));
|
||||
showTip(R.string.copied_to_clipboard, LENGTH_SHORT);
|
||||
return true;
|
||||
@@ -209,6 +226,13 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
private static final int TYPE_HEADER = 0;
|
||||
private static final int TYPE_DATA = 1;
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public InfoAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
if (position == 0) {
|
||||
@@ -220,7 +244,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
|
||||
|
||||
@Override
|
||||
public InfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new InfoHolder(getActivity().getLayoutInflater().inflate(viewType == TYPE_HEADER ?
|
||||
return new InfoHolder(mInflater.inflate(viewType == TYPE_HEADER ?
|
||||
R.layout.item_gallery_info_header : R.layout.item_gallery_info_data, parent, false));
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,10 @@
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.drawable.Drawable;
|
||||
@@ -29,9 +31,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.GridLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.text.InputType;
|
||||
import android.text.Spannable;
|
||||
import android.text.SpannableStringBuilder;
|
||||
import android.text.TextUtils;
|
||||
@@ -41,6 +43,7 @@ import android.view.Gravity;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
@@ -50,6 +53,7 @@ import android.widget.TextView;
|
||||
import com.github.amlcurran.showcaseview.ShowcaseView;
|
||||
import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener;
|
||||
import com.github.amlcurran.showcaseview.targets.PointTarget;
|
||||
import com.hippo.app.CheckBoxDialogBuilder;
|
||||
import com.hippo.app.EditTextDialogBuilder;
|
||||
import com.hippo.drawable.AddDeleteDrawable;
|
||||
import com.hippo.drawable.DrawerArrowDrawable;
|
||||
@@ -61,30 +65,36 @@ 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;
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.data.ListUrlBuilder;
|
||||
import com.hippo.ehviewer.client.exception.EhException;
|
||||
import com.hippo.ehviewer.client.parser.GalleryListParser;
|
||||
import com.hippo.ehviewer.dao.QuickSearch;
|
||||
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.scene.StageActivity;
|
||||
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;
|
||||
import com.hippo.yorozuya.SimpleAnimatorListener;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
import com.hippo.yorozuya.StringUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.List;
|
||||
@@ -92,7 +102,8 @@ import java.util.List;
|
||||
public final class GalleryListScene extends BaseScene
|
||||
implements EasyRecyclerView.OnItemClickListener, EasyRecyclerView.OnItemLongClickListener,
|
||||
SearchBar.Helper, SearchBar.OnStateChangeListener, FastScroller.OnDragHandlerListener,
|
||||
SearchLayout.Helper, View.OnClickListener, SearchBarMover.Helper {
|
||||
SearchLayout.Helper, SearchBarMover.Helper, View.OnClickListener, FabLayout.OnClickFabListener,
|
||||
FabLayout.OnExpandListener {
|
||||
|
||||
@IntDef({STATE_NORMAL, STATE_SIMPLE_SEARCH, STATE_SEARCH, STATE_SEARCH_SHOW_LIST})
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@@ -100,6 +111,8 @@ public final class GalleryListScene extends BaseScene
|
||||
|
||||
private static final int BACK_PRESSED_INTERVAL = 2000;
|
||||
|
||||
public final static int REQUEST_CODE_SELECT_IMAGE = 0;
|
||||
|
||||
public final static String KEY_ACTION = "action";
|
||||
public final static String ACTION_HOMEPAGE = "action_homepage";
|
||||
public final static String ACTION_WHATS_HOT = "action_whats_hot";
|
||||
@@ -134,7 +147,9 @@ public final class GalleryListScene extends BaseScene
|
||||
@Nullable
|
||||
private SearchBar mSearchBar;
|
||||
@Nullable
|
||||
private FloatingActionButton mFab;
|
||||
private View mSearchFab;
|
||||
@Nullable
|
||||
private FabLayout mFabLayout;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
@Nullable
|
||||
@@ -148,7 +163,45 @@ public final class GalleryListScene extends BaseScene
|
||||
@Nullable
|
||||
private SearchBarMover mSearchBarMover;
|
||||
@Nullable
|
||||
private Animator.AnimatorListener mFabAnimatorListener;
|
||||
private AddDeleteDrawable mActionFabDrawable;
|
||||
|
||||
@Nullable
|
||||
private final Animator.AnimatorListener mActionFabAnimatorListener = new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
if (null != mFabLayout) {
|
||||
mFabLayout.getPrimaryFab().setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
private final Animator.AnimatorListener mSearchFabAnimatorListener = new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
if (null != mSearchFab) {
|
||||
mSearchFab.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private int mHideActionFabSlop;
|
||||
private boolean mShowActionFab = true;
|
||||
|
||||
@Nullable
|
||||
private final RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
|
||||
@Override
|
||||
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {}
|
||||
|
||||
@Override
|
||||
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
|
||||
if (dy >= mHideActionFabSlop) {
|
||||
hideActionFab();
|
||||
} else if (dy <= -mHideActionFabSlop / 2) {
|
||||
showActionFab();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@State
|
||||
private int mState = STATE_NORMAL;
|
||||
@@ -160,14 +213,7 @@ public final class GalleryListScene extends BaseScene
|
||||
|
||||
private int mNavCheckedId = 0;
|
||||
|
||||
private final Runnable mReturnSearchBarRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mSearchBarMover != null) {
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
}
|
||||
}
|
||||
};
|
||||
private ShowcaseView mShowcaseView;
|
||||
|
||||
@Override
|
||||
public int getNavCheckedItem() {
|
||||
@@ -209,7 +255,9 @@ public final class GalleryListScene extends BaseScene
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mClient = EhApplication.getEhClient(getContext());
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
mClient = EhApplication.getEhClient(context);
|
||||
|
||||
if (savedInstanceState == null) {
|
||||
onInit();
|
||||
@@ -257,7 +305,9 @@ public final class GalleryListScene extends BaseScene
|
||||
Resources resources = context.getResources();
|
||||
Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
|
||||
SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
|
||||
ssb.append(resources.getString(R.string.gallery_list_search_bar_hint));
|
||||
ssb.append(resources.getString(EhUrl.SITE_EX == Settings.getGallerySite() ?
|
||||
R.string.gallery_list_search_bar_hint_exhentai :
|
||||
R.string.gallery_list_search_bar_hint_e_hentai));
|
||||
int textSize = (int) (searchBar.getEditTextTextSize() * 1.25);
|
||||
if (searchImage != null) {
|
||||
searchImage.setBounds(0, 0, textSize, textSize);
|
||||
@@ -290,21 +340,22 @@ public final class GalleryListScene extends BaseScene
|
||||
// Update search bar title, drawer checked item
|
||||
private void onUpdateUrlBuilder() {
|
||||
ListUrlBuilder builder = mUrlBuilder;
|
||||
if (null == builder) {
|
||||
Resources resources = getResources2();
|
||||
if (null == resources || null == builder) {
|
||||
return;
|
||||
}
|
||||
|
||||
Resources resources = getResources();
|
||||
String keyword = builder.getKeyword();
|
||||
int category = builder.getCategory();
|
||||
|
||||
// Update search edit text
|
||||
if (!TextUtils.isEmpty(keyword) && null != mSearchBar) {
|
||||
mSearchBar.setText(keyword);
|
||||
mSearchBar.cursorToEnd();
|
||||
}
|
||||
|
||||
// Update title
|
||||
String title = getSuitableTitleForUrlBuilder(getResources(), builder, true);
|
||||
String title = getSuitableTitleForUrlBuilder(resources, builder, true);
|
||||
if (null == title) {
|
||||
title = resources.getString(R.string.search);
|
||||
}
|
||||
@@ -329,11 +380,16 @@ public final class GalleryListScene extends BaseScene
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
|
||||
public View onCreateView2(LayoutInflater inflater, @Nullable ViewGroup container,
|
||||
@Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_gallery_list, container, false);
|
||||
|
||||
Resources resources = getContext().getResources();
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Resources resources = context.getResources();
|
||||
|
||||
mHideActionFabSlop = ViewConfiguration.get(context).getScaledTouchSlop();
|
||||
mShowActionFab = true;
|
||||
|
||||
View mainLayout = ViewUtils.$$(view, R.id.main_layout);
|
||||
ContentLayout contentLayout = (ContentLayout) ViewUtils.$$(mainLayout, R.id.content_layout);
|
||||
@@ -342,10 +398,11 @@ public final class GalleryListScene extends BaseScene
|
||||
RefreshLayout refreshLayout = contentLayout.getRefreshLayout();
|
||||
mSearchLayout = (SearchLayout) ViewUtils.$$(mainLayout, R.id.search_layout);
|
||||
mSearchBar = (SearchBar) ViewUtils.$$(mainLayout, R.id.search_bar);
|
||||
mFab = (FloatingActionButton) ViewUtils.$$(mainLayout, R.id.fab);
|
||||
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);
|
||||
|
||||
@@ -354,39 +411,45 @@ public final class GalleryListScene extends BaseScene
|
||||
contentLayout.setHelper(mHelper);
|
||||
contentLayout.getFastScroller().setOnDragHandlerListener(this);
|
||||
|
||||
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
|
||||
mRecyclerView.setLayoutManager(layoutManager);
|
||||
mRecyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
|
||||
mAdapter = new GalleryListAdapter(inflater, resources,
|
||||
mRecyclerView, Settings.getListMode());
|
||||
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
|
||||
mRecyclerView.setDrawSelectorOnTop(true);
|
||||
mRecyclerView.hasFixedSize();
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
mRecyclerView.setOnItemClickListener(this);
|
||||
mRecyclerView.setOnItemLongClickListener(this);
|
||||
mAdapter = new GalleryListAdapter(LayoutInflater.from(getContext()),
|
||||
getContext(), mRecyclerView, layoutManager, Settings.getListMode());
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
mAdapter.register();
|
||||
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop() + paddingTopSB,
|
||||
mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom());
|
||||
mRecyclerView.addOnScrollListener(mOnScrollListener);
|
||||
|
||||
fastScroller.setPadding(fastScroller.getPaddingLeft(), fastScroller.getPaddingTop() + paddingTopSB,
|
||||
fastScroller.getPaddingRight(), fastScroller.getPaddingBottom());
|
||||
|
||||
refreshLayout.setHeaderTranslationY(paddingTopSB);
|
||||
|
||||
mLeftDrawable = new DrawerArrowDrawable(getContext());
|
||||
mRightDrawable = new AddDeleteDrawable(getContext());
|
||||
mLeftDrawable = new DrawerArrowDrawable(context);
|
||||
mRightDrawable = new AddDeleteDrawable(context);
|
||||
mSearchBar.setLeftDrawable(mLeftDrawable);
|
||||
mSearchBar.setRightDrawable(mRightDrawable);
|
||||
mSearchBar.setHelper(this);
|
||||
mSearchBar.setOnStateChangeListener(this);
|
||||
setSearchBarHint(getContext(), mSearchBar);
|
||||
setSearchBarHint(context, mSearchBar);
|
||||
|
||||
mSearchLayout.setHelper(this);
|
||||
mSearchLayout.setPadding(mSearchLayout.getPaddingLeft(), mSearchLayout.getPaddingTop() + paddingTopSB,
|
||||
mSearchLayout.getPaddingRight(), mSearchLayout.getPaddingBottom() + paddingBottomFab);
|
||||
|
||||
mFab.setOnClickListener(this);
|
||||
mFabLayout.setAutoCancel(true);
|
||||
mFabLayout.setExpanded(false);
|
||||
mFabLayout.setHidePrimaryFab(false);
|
||||
mFabLayout.setOnClickFabListener(this);
|
||||
mFabLayout.setOnExpandListener(this);
|
||||
addAboveSnackView(mFabLayout);
|
||||
|
||||
mActionFabDrawable = new AddDeleteDrawable(context);
|
||||
mActionFabDrawable.setColor(resources.getColor(R.color.primary_drawable_dark));
|
||||
mFabLayout.getPrimaryFab().setImageDrawable(mActionFabDrawable);
|
||||
|
||||
mSearchFab.setOnClickListener(this);
|
||||
|
||||
mSearchBarMover = new SearchBarMover(this, mSearchBar, mRecyclerView, mSearchLayout);
|
||||
|
||||
@@ -410,15 +473,16 @@ public final class GalleryListScene extends BaseScene
|
||||
}
|
||||
|
||||
private void guideQuickSearch() {
|
||||
if (!Settings.getGuideQuickSearch()) {
|
||||
Activity activity = getActivity2();
|
||||
if (null == activity || !Settings.getGuideQuickSearch()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Display display = getActivity().getWindowManager().getDefaultDisplay();
|
||||
Display display = activity.getWindowManager().getDefaultDisplay();
|
||||
Point point = new Point();
|
||||
display.getSize(point);
|
||||
|
||||
new ShowcaseView.Builder(getActivity())
|
||||
mShowcaseView = new ShowcaseView.Builder(activity)
|
||||
.withMaterialShowcase()
|
||||
.setStyle(R.style.Guide)
|
||||
.setTarget(new PointTarget(point.x, point.y / 3))
|
||||
@@ -429,6 +493,7 @@ public final class GalleryListScene extends BaseScene
|
||||
.setShowcaseEventListener(new SimpleShowcaseEventListener() {
|
||||
@Override
|
||||
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
|
||||
mShowcaseView = null;
|
||||
ViewUtils.removeFromParent(showcaseView);
|
||||
Settings.putGuideQuickSearch(false);
|
||||
openDrawer(Gravity.RIGHT);
|
||||
@@ -440,39 +505,83 @@ public final class GalleryListScene extends BaseScene
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mShowcaseView) {
|
||||
ViewUtils.removeFromParent(mShowcaseView);
|
||||
mShowcaseView = null;
|
||||
}
|
||||
if (null != mSearchBarMover) {
|
||||
mSearchBarMover.cancelAnimation();
|
||||
mSearchBarMover = null;
|
||||
}
|
||||
if (null != mAdapter) {
|
||||
mAdapter.unregister();
|
||||
mAdapter = null;
|
||||
}
|
||||
if (null != mHelper) {
|
||||
if (1 == mHelper.getShownViewIndex()) {
|
||||
mHasFirstRefresh = false;
|
||||
}
|
||||
mHelper = null;
|
||||
}
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
if (null != mFabLayout) {
|
||||
removeAboveSnackView(mFabLayout);
|
||||
mFabLayout = null;
|
||||
}
|
||||
|
||||
mRecyclerView = null;
|
||||
mAdapter = null;
|
||||
mSearchLayout = null;
|
||||
mSearchBar = null;
|
||||
mFab = null;
|
||||
mSearchFab = null;
|
||||
mViewTransition = null;
|
||||
mLeftDrawable = null;
|
||||
mRightDrawable = null;
|
||||
mFabAnimatorListener = null;
|
||||
mActionFabDrawable = null;
|
||||
}
|
||||
|
||||
private void showQuickSearchTipDialog(final List<QuickSearch> list,
|
||||
final ArrayAdapter<QuickSearch> adapter, final ListView listView, final TextView tip) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return;
|
||||
}
|
||||
final CheckBoxDialogBuilder builder = new CheckBoxDialogBuilder(
|
||||
context, getString(R.string.add_quick_search_tip), getString(R.string.get_it), false);
|
||||
builder.setTitle(R.string.readme);
|
||||
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
if (builder.isChecked()) {
|
||||
Settings.putQuickSearchTip(false);
|
||||
}
|
||||
showAddQuickSearchDialog(list, adapter, listView, tip);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void showAddQuickSearchDialog(final List<QuickSearch> list,
|
||||
final ArrayAdapter<QuickSearch> adapter, final ListView listView, final TextView tip) {
|
||||
if (null == mUrlBuilder) {
|
||||
Context context = getContext2();
|
||||
final ListUrlBuilder urlBuilder = mUrlBuilder;
|
||||
if (null == context || null == urlBuilder) {
|
||||
return;
|
||||
}
|
||||
|
||||
final EditTextDialogBuilder builder = new EditTextDialogBuilder(getContext(),
|
||||
getSuitableTitleForUrlBuilder(getResources(), mUrlBuilder, false), getString(R.string.quick_search));
|
||||
// Can't add image search as quick search
|
||||
if (ListUrlBuilder.MODE_IMAGE_SEARCH == urlBuilder.getMode()) {
|
||||
showTip(R.string.image_search_not_quick_search, LENGTH_SHORT);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check duplicate
|
||||
for (QuickSearch q: list) {
|
||||
if (urlBuilder.equalsQuickSearch(q)) {
|
||||
showTip(getString(R.string.duplicate_quick_search, q.name), LENGTH_SHORT);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final EditTextDialogBuilder builder = new EditTextDialogBuilder(context,
|
||||
getSuitableTitleForUrlBuilder(context.getResources(), urlBuilder, false), getString(R.string.quick_search));
|
||||
builder.setTitle(R.string.add_quick_search_dialog_title);
|
||||
builder.setPositiveButton(android.R.string.ok, null);
|
||||
final AlertDialog dialog = builder.show();
|
||||
@@ -480,25 +589,36 @@ public final class GalleryListScene extends BaseScene
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
String text = builder.getText().trim();
|
||||
|
||||
// Check name empty
|
||||
if (TextUtils.isEmpty(text)) {
|
||||
builder.setError(getString(R.string.name_is_empty));
|
||||
} else {
|
||||
builder.setError(null);
|
||||
dialog.dismiss();
|
||||
QuickSearch quickSearch = mUrlBuilder.toQuickSearch();
|
||||
quickSearch.name = text;
|
||||
EhDB.insertQuickSearch(quickSearch);
|
||||
list.add(quickSearch);
|
||||
adapter.notifyDataSetChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
if (0 == list.size()) {
|
||||
tip.setVisibility(View.VISIBLE);
|
||||
listView.setVisibility(View.GONE);
|
||||
} else {
|
||||
tip.setVisibility(View.GONE);
|
||||
listView.setVisibility(View.VISIBLE);
|
||||
// Check name duplicate
|
||||
for (QuickSearch q: list) {
|
||||
if (text.equals(q.name)) {
|
||||
builder.setError(getString(R.string.duplicate_name));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
builder.setError(null);
|
||||
dialog.dismiss();
|
||||
QuickSearch quickSearch = urlBuilder.toQuickSearch();
|
||||
quickSearch.name = text;
|
||||
EhDB.insertQuickSearch(quickSearch);
|
||||
list.add(quickSearch);
|
||||
adapter.notifyDataSetChanged();
|
||||
|
||||
if (0 == list.size()) {
|
||||
tip.setVisibility(View.VISIBLE);
|
||||
listView.setVisibility(View.GONE);
|
||||
} else {
|
||||
tip.setVisibility(View.GONE);
|
||||
listView.setVisibility(View.VISIBLE);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -511,8 +631,11 @@ public final class GalleryListScene extends BaseScene
|
||||
final TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
final ListView listView = (ListView) ViewUtils.$$(view, R.id.list_view);
|
||||
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
final List<QuickSearch> list = EhDB.getAllQuickSearch();
|
||||
final ArrayAdapter<QuickSearch> adapter = new ArrayAdapter<>(getContext(), R.layout.item_simple_list, list);
|
||||
final ArrayAdapter<QuickSearch> adapter = new ArrayAdapter<>(context, R.layout.item_simple_list, list);
|
||||
listView.setAdapter(adapter);
|
||||
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
@@ -539,7 +662,11 @@ public final class GalleryListScene extends BaseScene
|
||||
int id = item.getItemId();
|
||||
switch (id) {
|
||||
case R.id.action_add:
|
||||
showAddQuickSearchDialog(list, adapter, listView, tip);
|
||||
if (Settings.getQuickSearchTip()) {
|
||||
showQuickSearchTipDialog(list, adapter, listView, tip);
|
||||
} else {
|
||||
showAddQuickSearchDialog(list, adapter, listView, tip);
|
||||
}
|
||||
break;
|
||||
case R.id.action_settings:
|
||||
startScene(new Announcer(QuickSearchScene.class));
|
||||
@@ -560,15 +687,6 @@ public final class GalleryListScene extends BaseScene
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mFab == v) {
|
||||
if (mState != STATE_NORMAL && null != mSearchBar) {
|
||||
mSearchBar.applySearch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkDoubleClickExit() {
|
||||
if (getStackIndex() != 0) {
|
||||
return false;
|
||||
@@ -587,6 +705,15 @@ public final class GalleryListScene extends BaseScene
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (null != mShowcaseView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (null != mFabLayout && mFabLayout.isExpanded()) {
|
||||
mFabLayout.setExpanded(false);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean handle;
|
||||
switch (mState) {
|
||||
default:
|
||||
@@ -632,25 +759,120 @@ public final class GalleryListScene extends BaseScene
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
public void onClick(View v) {
|
||||
if (STATE_NORMAL != mState && null != mSearchBar) {
|
||||
mSearchBar.applySearch();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClickPrimaryFab(FabLayout view, FloatingActionButton fab) {
|
||||
if (STATE_NORMAL == mState) {
|
||||
view.toggle();
|
||||
}
|
||||
}
|
||||
|
||||
private void showGoToDialog() {
|
||||
Context context = getContext2();
|
||||
if (null == context || null == mHelper) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int page = mHelper.getPageForTop();
|
||||
final int pages = mHelper.getPages();
|
||||
String hint = getString(R.string.go_to_hint, page + 1, pages);
|
||||
final EditTextDialogBuilder builder = new EditTextDialogBuilder(context, null, hint);
|
||||
builder.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
|
||||
final AlertDialog dialog = builder.setTitle(R.string.go_to)
|
||||
.setPositiveButton(android.R.string.ok, null)
|
||||
.show();
|
||||
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (null == mHelper) {
|
||||
dialog.dismiss();
|
||||
return;
|
||||
}
|
||||
|
||||
String text = builder.getText().trim();
|
||||
int goTo;
|
||||
try {
|
||||
goTo = Integer.parseInt(text) - 1;
|
||||
} catch (NumberFormatException e){
|
||||
builder.setError(getString(R.string.error_invalid_number));
|
||||
return;
|
||||
}
|
||||
if (goTo < 0 || goTo >= pages) {
|
||||
builder.setError(getString(R.string.error_out_of_range));
|
||||
return;
|
||||
}
|
||||
builder.setError(null);
|
||||
mHelper.goTo(goTo);
|
||||
AppHelper.hideSoftInput(dialog);
|
||||
dialog.dismiss();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClickSecondaryFab(FabLayout view, FloatingActionButton fab, int position) {
|
||||
if (null == mHelper) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (position) {
|
||||
case 0: // Go to
|
||||
if (mHelper.canGoTo()) {
|
||||
showGoToDialog();
|
||||
}
|
||||
break;
|
||||
case 1: // Refresh
|
||||
mHelper.refresh();
|
||||
break;
|
||||
}
|
||||
|
||||
view.setExpanded(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onExpand(boolean expanded) {
|
||||
if (null == mActionFabDrawable) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (expanded) {
|
||||
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
|
||||
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
|
||||
mActionFabDrawable.setDelete(ANIMATE_TIME);
|
||||
} else {
|
||||
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
|
||||
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
|
||||
mActionFabDrawable.setAdd(ANIMATE_TIME);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
final Context context = getContext2();
|
||||
final MainActivity activity = getActivity2();
|
||||
if (null == context || null == activity || null == mHelper) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final GalleryInfo gi = mHelper.getDataAt(position);
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(EhUtils.getSuitableTitle(gi))
|
||||
.setItems(R.array.gallery_list_menu_entries, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
switch (which) {
|
||||
case 0: // Download
|
||||
CommonOperations.startDownload(getActivity(), gi, false);
|
||||
CommonOperations.startDownload(activity, gi, false);
|
||||
break;
|
||||
case 1: // Favorites
|
||||
CommonOperations.addToFavorites(getActivity(), gi,
|
||||
new addToFavoriteListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag()));
|
||||
CommonOperations.addToFavorites(activity, gi,
|
||||
new addToFavoriteListener(context,
|
||||
activity.getStageId(), getTag()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -658,35 +880,97 @@ public final class GalleryListScene extends BaseScene
|
||||
return true;
|
||||
}
|
||||
|
||||
private void showFab() {
|
||||
if (null == mFab) {
|
||||
return;
|
||||
private void showActionFab() {
|
||||
if (null != mFabLayout && STATE_NORMAL == mState && !mShowActionFab) {
|
||||
mShowActionFab = true;
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
fab.setVisibility(View.VISIBLE);
|
||||
fab.setRotation(-45.0f);
|
||||
fab.animate().scaleX(1.0f).scaleY(1.0f).rotation(0.0f).setListener(null)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(0L)
|
||||
.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR).start();
|
||||
}
|
||||
|
||||
mFab.setVisibility(View.VISIBLE);
|
||||
mFab.setScaleX(0.0f);
|
||||
mFab.setScaleY(0.0f);
|
||||
mFab.animate().scaleX(1.0f).scaleY(1.0f).setListener(null).setDuration(ANIMATE_TIME)
|
||||
.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR).start();
|
||||
}
|
||||
|
||||
private void hideFab() {
|
||||
if (null == mFab) {
|
||||
private void hideActionFab() {
|
||||
if (null != mFabLayout && STATE_NORMAL == mState && mShowActionFab) {
|
||||
mShowActionFab = false;
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
fab.animate().scaleX(0.0f).scaleY(0.0f).setListener(mActionFabAnimatorListener)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(0L)
|
||||
.setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR).start();
|
||||
}
|
||||
}
|
||||
|
||||
private void selectSearchFab(boolean animation) {
|
||||
if (null == mFabLayout || null == mSearchFab) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mFabAnimatorListener == null) {
|
||||
mFabAnimatorListener = new SimpleAnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
if (null != mFab) {
|
||||
mFab.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
};
|
||||
mShowActionFab = false;
|
||||
|
||||
if (animation) {
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
long delay;
|
||||
if (View.INVISIBLE == fab.getVisibility()) {
|
||||
delay = 0L;
|
||||
} else {
|
||||
delay = ANIMATE_TIME;
|
||||
fab.animate().scaleX(0.0f).scaleY(0.0f).setListener(mActionFabAnimatorListener)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(0L)
|
||||
.setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR).start();
|
||||
}
|
||||
mSearchFab.setVisibility(View.VISIBLE);
|
||||
mSearchFab.setRotation(-45.0f);
|
||||
mSearchFab.animate().scaleX(1.0f).scaleY(1.0f).rotation(0.0f).setListener(null)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(delay)
|
||||
.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR).start();
|
||||
} else {
|
||||
mFabLayout.setExpanded(false, false);
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
fab.setVisibility(View.INVISIBLE);
|
||||
fab.setScaleX(0.0f);
|
||||
fab.setScaleY(0.0f);
|
||||
mSearchFab.setVisibility(View.VISIBLE);
|
||||
mSearchFab.setScaleX(1.0f);
|
||||
mSearchFab.setScaleY(1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
private void selectActionFab(boolean animation) {
|
||||
if (null == mFabLayout || null == mSearchFab) {
|
||||
return;
|
||||
}
|
||||
|
||||
mShowActionFab = true;
|
||||
|
||||
if (animation) {
|
||||
long delay;
|
||||
if (View.INVISIBLE == mSearchFab.getVisibility()) {
|
||||
delay = 0L;
|
||||
} else {
|
||||
delay = ANIMATE_TIME;
|
||||
mSearchFab.animate().scaleX(0.0f).scaleY(0.0f).setListener(mSearchFabAnimatorListener)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(0L)
|
||||
.setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR).start();
|
||||
}
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
fab.setVisibility(View.VISIBLE);
|
||||
fab.setRotation(-45.0f);
|
||||
fab.animate().scaleX(1.0f).scaleY(1.0f).rotation(0.0f).setListener(null)
|
||||
.setDuration(ANIMATE_TIME).setStartDelay(delay)
|
||||
.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR).start();
|
||||
|
||||
} else {
|
||||
mFabLayout.setExpanded(false, false);
|
||||
View fab = mFabLayout.getPrimaryFab();
|
||||
fab.setVisibility(View.VISIBLE);
|
||||
fab.setScaleX(1.0f);
|
||||
fab.setScaleY(1.0f);
|
||||
mSearchFab.setVisibility(View.INVISIBLE);
|
||||
mSearchFab.setScaleX(0.0f);
|
||||
mSearchFab.setScaleY(0.0f);
|
||||
}
|
||||
mFab.animate().scaleX(0.0f).scaleY(0.0f).setListener(mFabAnimatorListener)
|
||||
.setDuration(ANIMATE_TIME).setInterpolator(AnimationUtils.SLOW_FAST_INTERPOLATOR).start();
|
||||
}
|
||||
|
||||
private void setState(@State int state) {
|
||||
@@ -708,26 +992,26 @@ public final class GalleryListScene extends BaseScene
|
||||
if (state == STATE_SIMPLE_SEARCH) {
|
||||
mSearchBar.setState(SearchBar.STATE_SEARCH_LIST, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
showFab();
|
||||
selectSearchFab(animation);
|
||||
} else if (state == STATE_SEARCH) {
|
||||
mViewTransition.showView(1, animation);
|
||||
mSearchLayout.scrollSearchContainerToTop();
|
||||
mSearchBar.setState(SearchBar.STATE_SEARCH, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
showFab();
|
||||
selectSearchFab(animation);
|
||||
} else if (state == STATE_SEARCH_SHOW_LIST) {
|
||||
mViewTransition.showView(1, animation);
|
||||
mSearchLayout.scrollSearchContainerToTop();
|
||||
mSearchBar.setState(SearchBar.STATE_SEARCH_LIST, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
showFab();
|
||||
selectSearchFab(animation);
|
||||
}
|
||||
break;
|
||||
case STATE_SIMPLE_SEARCH:
|
||||
if (state == STATE_NORMAL) {
|
||||
mSearchBar.setState(SearchBar.STATE_NORMAL, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
hideFab();
|
||||
selectActionFab(animation);
|
||||
} else if (state == STATE_SEARCH) {
|
||||
mViewTransition.showView(1, animation);
|
||||
mSearchLayout.scrollSearchContainerToTop();
|
||||
@@ -745,7 +1029,7 @@ public final class GalleryListScene extends BaseScene
|
||||
mViewTransition.showView(0, animation);
|
||||
mSearchBar.setState(SearchBar.STATE_NORMAL, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
hideFab();
|
||||
selectActionFab(animation);
|
||||
} else if (state == STATE_SIMPLE_SEARCH) {
|
||||
mViewTransition.showView(0, animation);
|
||||
mSearchBar.setState(SearchBar.STATE_SEARCH_LIST, animation);
|
||||
@@ -760,7 +1044,7 @@ public final class GalleryListScene extends BaseScene
|
||||
mViewTransition.showView(0, animation);
|
||||
mSearchBar.setState(SearchBar.STATE_NORMAL, animation);
|
||||
mSearchBarMover.returnSearchBarPosition();
|
||||
hideFab();
|
||||
selectActionFab(animation);
|
||||
} else if (state == STATE_SIMPLE_SEARCH) {
|
||||
mViewTransition.showView(0, animation);
|
||||
mSearchBar.setState(SearchBar.STATE_SEARCH_LIST, animation);
|
||||
@@ -846,7 +1130,12 @@ public final class GalleryListScene extends BaseScene
|
||||
startScene(new Announcer(GalleryDetailScene.class).setArgs(args));
|
||||
return;
|
||||
} else {
|
||||
mSearchLayout.formatListUrlBuilder(mUrlBuilder, query);
|
||||
try {
|
||||
mSearchLayout.formatListUrlBuilder(mUrlBuilder, query);
|
||||
} catch (EhException e) {
|
||||
showTip(e.getMessage(), LENGTH_LONG);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
mUrlBuilder.reset();
|
||||
@@ -912,6 +1201,15 @@ public final class GalleryListScene extends BaseScene
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelectImage() {
|
||||
Intent intent = new Intent();
|
||||
intent.setType("image/*");
|
||||
intent.setAction(Intent.ACTION_GET_CONTENT);
|
||||
startActivityForResult(Intent.createChooser(intent,
|
||||
getString(R.string.select_image)), REQUEST_CODE_SELECT_IMAGE);
|
||||
}
|
||||
|
||||
// SearchBarMover.Helper
|
||||
@Override
|
||||
public boolean isValidView(RecyclerView recyclerView) {
|
||||
@@ -936,17 +1234,32 @@ public final class GalleryListScene extends BaseScene
|
||||
}
|
||||
|
||||
public static void startScene(SceneFragment scene, ListUrlBuilder lub) {
|
||||
scene.startScene(getStartAnnouncer(lub));
|
||||
}
|
||||
|
||||
public static Announcer getStartAnnouncer(ListUrlBuilder lub) {
|
||||
Bundle args = new Bundle();
|
||||
args.putString(KEY_ACTION, ACTION_LIST_URL_BUILDER);
|
||||
args.putParcelable(KEY_LIST_URL_BUILDER, lub);
|
||||
scene.startScene(new Announcer(GalleryListScene.class).setArgs(args));
|
||||
return new Announcer(GalleryListScene.class).setArgs(args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
if (REQUEST_CODE_SELECT_IMAGE == requestCode) {
|
||||
if (Activity.RESULT_OK == resultCode && null != mSearchLayout && null != data) {
|
||||
mSearchLayout.setImageUri(data.getData());
|
||||
}
|
||||
} else {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
}
|
||||
}
|
||||
|
||||
private class GalleryListAdapter extends GalleryAdapter {
|
||||
|
||||
public GalleryListAdapter(LayoutInflater inflater, Context context,
|
||||
RecyclerView recyclerView, GridLayoutManager layoutManager, int type) {
|
||||
super(inflater, context, recyclerView, layoutManager, type);
|
||||
public GalleryListAdapter(@NonNull LayoutInflater inflater,
|
||||
@NonNull Resources resources, @NonNull RecyclerView recyclerView, int type) {
|
||||
super(inflater, resources, recyclerView, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -965,7 +1278,8 @@ public final class GalleryListScene extends BaseScene
|
||||
|
||||
@Override
|
||||
protected void getPageData(int taskId, int type, int page) {
|
||||
if (null == mClient || null == mUrlBuilder) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || null == mClient || null == mUrlBuilder) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -974,23 +1288,32 @@ public final class GalleryListScene extends BaseScene
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_GET_WHATS_HOT);
|
||||
request.setCallback(new GetWhatsHotListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(), taskId));
|
||||
activity.getStageId(), getTag(), taskId));
|
||||
request.setArgs();
|
||||
mClient.execute(request);
|
||||
} else if (ListUrlBuilder.MODE_IMAGE_SEARCH == mUrlBuilder.getMode()) {
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_IMAGE_SEARCH);
|
||||
request.setCallback(new GetGalleryListListener(getContext(),
|
||||
activity.getStageId(), getTag(), taskId));
|
||||
request.setArgs(new File(StringUtils.avoidNull(mUrlBuilder.getImagePath())),
|
||||
mUrlBuilder.isUseSimilarityScan(),
|
||||
mUrlBuilder.isOnlySearchCovers(), mUrlBuilder.isShowExpunged());
|
||||
mClient.execute(request);
|
||||
} else {
|
||||
String url = mUrlBuilder.build();
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_GET_GALLERY_LIST);
|
||||
request.setCallback(new GetGalleryListListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(), taskId));
|
||||
request.setArgs(url, Settings.getShowJpnTitle());
|
||||
activity.getStageId(), getTag(), taskId));
|
||||
request.setArgs(url);
|
||||
mClient.execute(request);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Context getContext() {
|
||||
return GalleryListScene.this.getContext();
|
||||
return GalleryListScene.this.getContext2();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1015,26 +1338,35 @@ public final class GalleryListScene extends BaseScene
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHideRecyclerView() {
|
||||
super.onHideRecyclerView();
|
||||
if (mSearchBarMover != null) {
|
||||
public void onShowView(View hiddenView, View shownView) {
|
||||
if (null != mSearchBarMover) {
|
||||
mSearchBarMover.showSearchBar();
|
||||
}
|
||||
showActionFab();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onScrollToPosition(int postion) {
|
||||
if (0 == postion) {
|
||||
if (null != mSearchBarMover) {
|
||||
mSearchBarMover.showSearchBar();
|
||||
}
|
||||
showActionFab();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onGetGalleryListSuccess(GalleryListParser.Result result, int taskId) {
|
||||
if (mHelper != null && mSearchBarMover != null &&
|
||||
mHelper.isCurrentTask(taskId) && isViewCreated()) {
|
||||
mHelper.isCurrentTask(taskId)) {
|
||||
mHelper.setPages(taskId, result.pages);
|
||||
mHelper.onGetPageData(taskId, result.galleryInfos);
|
||||
SimpleHandler.getInstance().post(mReturnSearchBarRunnable);
|
||||
mHelper.onGetPageData(taskId, result.galleryInfoList);
|
||||
}
|
||||
}
|
||||
|
||||
private void onGetGalleryListFailure(Exception e, int taskId) {
|
||||
if (mHelper != null && mSearchBarMover != null &&
|
||||
mHelper.isCurrentTask(taskId) && isViewCreated()) {
|
||||
mHelper.isCurrentTask(taskId)) {
|
||||
mHelper.onGetException(taskId, e);
|
||||
}
|
||||
}
|
||||
@@ -1044,13 +1376,12 @@ public final class GalleryListScene extends BaseScene
|
||||
mHelper.isCurrentTask(taskId)) {
|
||||
mHelper.setPages(taskId, 1);
|
||||
mHelper.onGetPageData(taskId, result);
|
||||
SimpleHandler.getInstance().post(mReturnSearchBarRunnable);
|
||||
}
|
||||
}
|
||||
|
||||
private void onGetWhatsHotFailure(Exception e, int taskId) {
|
||||
if (mHelper != null && mSearchBarMover != null &&
|
||||
mHelper.isCurrentTask(taskId) && isViewCreated()) {
|
||||
mHelper.isCurrentTask(taskId)) {
|
||||
mHelper.onGetException(taskId, e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.GridLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.util.Pair;
|
||||
import android.view.LayoutInflater;
|
||||
@@ -38,23 +38,24 @@ import com.hippo.easyrecyclerview.EasyRecyclerView;
|
||||
import com.hippo.easyrecyclerview.MarginItemDecoration;
|
||||
import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.client.EhCacheKeyFactory;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.client.EhClient;
|
||||
import com.hippo.ehviewer.client.EhRequest;
|
||||
import com.hippo.ehviewer.client.EhUrl;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.client.data.GalleryPreview;
|
||||
import com.hippo.ehviewer.client.data.LargePreviewSet;
|
||||
import com.hippo.ehviewer.client.data.PreviewSet;
|
||||
import com.hippo.ehviewer.client.exception.EhException;
|
||||
import com.hippo.ehviewer.ui.GalleryActivity;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.scene.SceneFragment;
|
||||
import com.hippo.scene.StageActivity;
|
||||
import com.hippo.util.LayoutUtils2;
|
||||
import com.hippo.widget.ContentLayout;
|
||||
import com.hippo.widget.LoadImageView;
|
||||
import com.hippo.widget.Slider;
|
||||
import com.hippo.widget.recyclerview.AutoGridLayoutManager;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.LayoutUtils;
|
||||
import com.hippo.yorozuya.SimpleHandler;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Locale;
|
||||
@@ -76,6 +77,8 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
View life cycle
|
||||
---------------*/
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
@Nullable
|
||||
private GalleryPreviewAdapter mAdapter;
|
||||
@Nullable
|
||||
private GalleryPreviewHelper mHelper;
|
||||
@@ -86,7 +89,9 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mClient = EhApplication.getEhClient(getContext());
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
mClient = EhApplication.getEhClient(context);
|
||||
if (savedInstanceState == null) {
|
||||
onInit();
|
||||
} else {
|
||||
@@ -124,23 +129,29 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
ContentLayout contentLayout = (ContentLayout) inflater.inflate(
|
||||
R.layout.scene_gallery_previews, container, false);
|
||||
contentLayout.hideFastScroll();
|
||||
EasyRecyclerView recyclerView = contentLayout.getRecyclerView();
|
||||
mRecyclerView = contentLayout.getRecyclerView();
|
||||
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Resources resources = context.getResources();
|
||||
|
||||
mAdapter = new GalleryPreviewAdapter();
|
||||
recyclerView.setAdapter(mAdapter);
|
||||
int minWidth = getResources().getDimensionPixelOffset(R.dimen.preview_grid_min_width);
|
||||
int spanCount = LayoutUtils2.calculateSpanCount(getContext(), minWidth);
|
||||
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount));
|
||||
int padding = LayoutUtils.dp2pix(getContext(), 4);
|
||||
recyclerView.setPadding(padding, padding, padding, padding);
|
||||
recyclerView.setClipToPadding(false);
|
||||
recyclerView.addItemDecoration(new MarginItemDecoration(padding));
|
||||
recyclerView.setOnItemClickListener(this);
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
int columnWidth = resources.getDimensionPixelOffset(Settings.getThumbSizeResId());
|
||||
AutoGridLayoutManager layoutManager = new AutoGridLayoutManager(context, columnWidth);
|
||||
layoutManager.setStrategy(AutoGridLayoutManager.STRATEGY_SUITABLE_SIZE);
|
||||
mRecyclerView.setLayoutManager(layoutManager);
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
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);
|
||||
@@ -164,6 +175,10 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
}
|
||||
mHelper = null;
|
||||
}
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
|
||||
mAdapter = null;
|
||||
}
|
||||
@@ -182,6 +197,11 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemClick(MenuItem item) {
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int id = item.getItemId();
|
||||
switch (id) {
|
||||
case R.id.action_go_to:
|
||||
@@ -191,12 +211,12 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
int pages = mHelper.getPages();
|
||||
if (pages > 0 && mHelper.canGoTo()) {
|
||||
GoToDialogHelper helper = new GoToDialogHelper(pages, mHelper.getPageForTop());
|
||||
AlertDialog dialog = new AlertDialog.Builder(getContext()).setTitle(R.string.go_to)
|
||||
.setView(helper.getView())
|
||||
AlertDialog dialog = new AlertDialog.Builder(context).setTitle(R.string.go_to)
|
||||
.setView(R.layout.dialog_go_to)
|
||||
.setPositiveButton(android.R.string.ok, null)
|
||||
.create();
|
||||
dialog.show();
|
||||
helper.setPositiveButtonClickListener(dialog);
|
||||
helper.setDialog(dialog);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -210,13 +230,13 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
Context context = getContext();
|
||||
Context context = getContext2();
|
||||
if (null != context && null != mHelper && null != mGalleryInfo) {
|
||||
GalleryPreview p = mHelper.getDataAt(position);
|
||||
Intent intent = new Intent(context, GalleryActivity.class);
|
||||
intent.setAction(GalleryActivity.ACTION_EH);
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mGalleryInfo);
|
||||
intent.putExtra(GalleryActivity.KEY_PAGE, p.index);
|
||||
intent.putExtra(GalleryActivity.KEY_PAGE, p.getPosition());
|
||||
startActivity(intent);
|
||||
}
|
||||
return true;
|
||||
@@ -237,17 +257,25 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
|
||||
private class GalleryPreviewAdapter extends RecyclerView.Adapter<GalleryPreviewHolder> {
|
||||
|
||||
@Override
|
||||
public GalleryPreviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new GalleryPreviewHolder(getActivity().getLayoutInflater().inflate(R.layout.item_gallery_preview, parent, false));
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public GalleryPreviewAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryPreviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new GalleryPreviewHolder(mInflater.inflate(R.layout.item_gallery_preview, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("SetTextI18n")
|
||||
public void onBindViewHolder(GalleryPreviewHolder holder, int position) {
|
||||
if (null != mHelper && null != mGalleryInfo) {
|
||||
if (null != mHelper) {
|
||||
GalleryPreview preview = mHelper.getDataAt(position);
|
||||
holder.image.load(EhCacheKeyFactory.getLargePreviewKey(mGalleryInfo.gid, preview.index), preview.imageUrl);
|
||||
holder.text.setText(String.format(Locale.US, "%d", preview.index + 1));
|
||||
preview.load(holder.image);
|
||||
holder.text.setText(Integer.toString(preview.getPosition() + 1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,36 +289,24 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
|
||||
@Override
|
||||
protected void getPageData(final int taskId, int type, int page) {
|
||||
if (null == mClient || null == mGalleryInfo) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || null == mClient || null == mGalleryInfo) {
|
||||
onGetException(taskId, new EhException(getString(R.string.error_cannot_find_gallery)));
|
||||
return;
|
||||
}
|
||||
|
||||
final LargePreviewSet previewSet = EhApplication.getLargePreviewSetCache(
|
||||
getContext()).get(EhCacheKeyFactory.getLargePreviewSetKey(mGalleryInfo.gid, page));
|
||||
final Integer pages = EhApplication.getPreviewPagesCache(getContext()).get(mGalleryInfo.gid);
|
||||
if (previewSet != null && pages != null) {
|
||||
SimpleHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
onGetLargePreviewSetSuccess(Pair.create(previewSet, pages), taskId);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
String url = EhUrl.getGalleryDetailUrl(mGalleryInfo.gid, mGalleryInfo.token, page, false);
|
||||
EhRequest request = new EhRequest();
|
||||
request.setMethod(EhClient.METHOD_GET_LARGE_PREVIEW_SET);
|
||||
request.setCallback(new GetLargePreviewSetListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag(), taskId, mGalleryInfo.gid, page));
|
||||
request.setMethod(EhClient.METHOD_GET_PREVIEW_SET);
|
||||
request.setCallback(new GetPreviewSetListener(getContext(),
|
||||
activity.getStageId(), getTag(), taskId));
|
||||
request.setArgs(url);
|
||||
mClient.execute(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Context getContext() {
|
||||
return GalleryPreviewsScene.this.getContext();
|
||||
return GalleryPreviewsScene.this.getContext2();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -315,17 +331,13 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
}
|
||||
}
|
||||
|
||||
private void onGetLargePreviewSetSuccess(Pair<LargePreviewSet, Integer> result, int taskId) {
|
||||
if (mHelper != null && mHelper.isCurrentTask(taskId) && isViewCreated()) {
|
||||
LargePreviewSet previewSet = result.first;
|
||||
private void onGetPreviewSetSuccess(Pair<PreviewSet, Integer> result, int taskId) {
|
||||
if (null != mHelper && mHelper.isCurrentTask(taskId) && null != mGalleryInfo) {
|
||||
PreviewSet previewSet = result.first;
|
||||
int size = previewSet.size();
|
||||
ArrayList<GalleryPreview> list = new ArrayList<>(size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
GalleryPreview preview = new GalleryPreview();
|
||||
preview.imageUrl = previewSet.getImageUrlAt(i);
|
||||
preview.pageUrl = previewSet.getPageUrlAt(i);
|
||||
preview.index = previewSet.getIndexAt(i);
|
||||
list.add(preview);
|
||||
list.add(previewSet.getGalleryPreview(mGalleryInfo.gid, i));
|
||||
}
|
||||
|
||||
mHelper.setPages(taskId, result.second);
|
||||
@@ -333,34 +345,26 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
}
|
||||
}
|
||||
|
||||
private void onGetLargePreviewSetFailure(Exception e, int taskId) {
|
||||
if (mHelper != null && mHelper.isCurrentTask(taskId) && isViewCreated()) {
|
||||
private void onGetPreviewSetFailure(Exception e, int taskId) {
|
||||
if (mHelper != null && mHelper.isCurrentTask(taskId)) {
|
||||
mHelper.onGetException(taskId, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class GetLargePreviewSetListener extends EhCallback<GalleryPreviewsScene, Pair<LargePreviewSet, Integer>> {
|
||||
private static class GetPreviewSetListener extends EhCallback<GalleryPreviewsScene, Pair<PreviewSet, Integer>> {
|
||||
|
||||
private final int mTaskId;
|
||||
private final long mGid;
|
||||
private final int mPage;
|
||||
|
||||
public GetLargePreviewSetListener(Context context, int stageId, String sceneTag, int taskId, long gid, int page) {
|
||||
public GetPreviewSetListener(Context context, int stageId, String sceneTag, int taskId) {
|
||||
super(context, stageId, sceneTag);
|
||||
mTaskId = taskId;
|
||||
mGid = gid;
|
||||
mPage = page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(Pair<LargePreviewSet, Integer> result) {
|
||||
EhApplication.getLargePreviewSetCache(getApplication()).put(
|
||||
EhCacheKeyFactory.getLargePreviewSetKey(mGid, mPage), result.first);
|
||||
EhApplication.getPreviewPagesCache(getApplication()).put(mGid, result.second);
|
||||
|
||||
public void onSuccess(Pair<PreviewSet, Integer> result) {
|
||||
GalleryPreviewsScene scene = getScene();
|
||||
if (scene != null) {
|
||||
scene.onGetLargePreviewSetSuccess(result, mTaskId);
|
||||
scene.onGetPreviewSetSuccess(result, mTaskId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,7 +372,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
public void onFailure(Exception e) {
|
||||
GalleryPreviewsScene scene = getScene();
|
||||
if (scene != null) {
|
||||
scene.onGetLargePreviewSetFailure(e, mTaskId);
|
||||
scene.onGetPreviewSetFailure(e, mTaskId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,35 +391,37 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
DialogInterface.OnDismissListener {
|
||||
|
||||
private final int mPages;
|
||||
private final int mCurrentPage;
|
||||
|
||||
private final View mView;
|
||||
private final Slider mSlider;
|
||||
|
||||
@Nullable
|
||||
private Slider mSlider;
|
||||
@Nullable
|
||||
private Dialog mDialog;
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
private GoToDialogHelper(int pages, int currentPage) {
|
||||
mPages = pages;
|
||||
mView = getActivity().getLayoutInflater().inflate(R.layout.dialog_go_to, null);
|
||||
((TextView) mView.findViewById(R.id.start)).setText("1");
|
||||
((TextView) mView.findViewById(R.id.end)).setText(String.format(Locale.US, "%d", pages));
|
||||
mSlider = (Slider) mView.findViewById(R.id.slider);
|
||||
mSlider.setRange(1, pages);
|
||||
mSlider.setProgress(currentPage + 1);
|
||||
mCurrentPage = currentPage;
|
||||
}
|
||||
|
||||
public View getView() {
|
||||
return mView;
|
||||
}
|
||||
|
||||
public void setPositiveButtonClickListener(AlertDialog dialog) {
|
||||
public void setDialog(@NonNull AlertDialog dialog) {
|
||||
mDialog = dialog;
|
||||
|
||||
((TextView) ViewUtils.$$(dialog, R.id.start)).setText(String.format(Locale.US, "%d", 1));
|
||||
((TextView) ViewUtils.$$(dialog, R.id.end)).setText(String.format(Locale.US, "%d", mPages));
|
||||
mSlider = (Slider) ViewUtils.$$(dialog, R.id.slider);
|
||||
mSlider.setRange(1, mPages);
|
||||
mSlider.setProgress(mCurrentPage + 1);
|
||||
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(this);
|
||||
dialog.setOnDismissListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (null == mSlider) {
|
||||
return;
|
||||
}
|
||||
|
||||
int page = mSlider.getProgress() - 1;
|
||||
if (page >= 0 && page < mPages && mHelper != null) {
|
||||
mHelper.goTo(page);
|
||||
@@ -431,6 +437,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
mDialog = null;
|
||||
mSlider = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,34 +18,52 @@ package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v7.app.AlertDialog;
|
||||
import android.support.v7.widget.GridLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.StaggeredGridLayoutManager;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemAdapter;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemConstants;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultAction;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionDefault;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionRemoveItem;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
|
||||
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractSwipeableItemViewHolder;
|
||||
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.Settings;
|
||||
import com.hippo.ehviewer.client.EhCacheKeyFactory;
|
||||
import com.hippo.ehviewer.client.EhUtils;
|
||||
import com.hippo.ehviewer.client.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.dao.HistoryInfo;
|
||||
import com.hippo.ehviewer.ui.CommonOperations;
|
||||
import com.hippo.rippleold.RippleSalon;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.ehviewer.widget.SimpleRatingView;
|
||||
import com.hippo.ripple.Ripple;
|
||||
import com.hippo.scene.Announcer;
|
||||
import com.hippo.scene.SceneFragment;
|
||||
import com.hippo.scene.StageActivity;
|
||||
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;
|
||||
|
||||
@@ -59,11 +77,13 @@ public class HistoryScene extends ToolbarScene
|
||||
View life cycle
|
||||
---------------*/
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
@Nullable
|
||||
private HistoryAdapter mAdapter;
|
||||
private RecyclerView.Adapter<?> mAdapter;
|
||||
@Nullable
|
||||
private LazyList<HistoryInfo> mList;
|
||||
private LazyList<HistoryInfo> mLazyList;
|
||||
|
||||
@Override
|
||||
public int getNavCheckedItem() {
|
||||
@@ -72,43 +92,61 @@ public class HistoryScene extends ToolbarScene
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_history, container, false);
|
||||
View content = ViewUtils.$$(view, R.id.content);
|
||||
EasyRecyclerView recyclerView = (EasyRecyclerView) ViewUtils.$$(content, R.id.recycler_view);
|
||||
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(content, R.id.recycler_view);
|
||||
FastScroller fastScroller = (FastScroller) ViewUtils.$$(content, R.id.fast_scroller);
|
||||
TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
mViewTransition = new ViewTransition(content, tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_history);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
Resources resources = context.getResources();
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_history);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
|
||||
mList = EhDB.getHistoryLazyList();
|
||||
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
|
||||
recyclerView.setLayoutManager(layoutManager);
|
||||
recyclerView.setSelector(RippleSalon.generateRippleDrawable(false));
|
||||
recyclerView.setDrawSelectorOnTop(true);
|
||||
recyclerView.hasFixedSize();
|
||||
recyclerView.setClipToPadding(false);
|
||||
recyclerView.setOnItemClickListener(this);
|
||||
recyclerView.setOnItemLongClickListener(this);
|
||||
mAdapter = new HistoryAdapter(LayoutInflater.from(getContext()),
|
||||
getContext(), recyclerView, layoutManager, Settings.getListMode());
|
||||
recyclerView.setAdapter(mAdapter);
|
||||
mAdapter.register();
|
||||
RecyclerViewTouchActionGuardManager guardManager = new RecyclerViewTouchActionGuardManager();
|
||||
guardManager.setInterceptVerticalScrollingWhileAnimationRunning(true);
|
||||
guardManager.setEnabled(true);
|
||||
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
|
||||
mAdapter = new HistoryAdapter();
|
||||
mAdapter.setHasStableIds(true);
|
||||
mAdapter = swipeManager.createWrappedAdapter(mAdapter);
|
||||
mRecyclerView.setAdapter(mAdapter);
|
||||
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
|
||||
animator.setSupportsChangeAnimations(false);
|
||||
mRecyclerView.setItemAnimator(animator);
|
||||
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(Ripple.generateRippleDrawable(context, false));
|
||||
mRecyclerView.setDrawSelectorOnTop(true);
|
||||
mRecyclerView.hasFixedSize();
|
||||
mRecyclerView.setClipToPadding(false);
|
||||
mRecyclerView.setOnItemClickListener(this);
|
||||
mRecyclerView.setOnItemLongClickListener(this);
|
||||
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);
|
||||
|
||||
fastScroller.attachToRecyclerView(recyclerView);
|
||||
fastScroller.attachToRecyclerView(mRecyclerView);
|
||||
HandlerDrawable handlerDrawable = new HandlerDrawable();
|
||||
handlerDrawable.setColor(ResourcesUtils.getAttrColor(getContext(), R.attr.colorAccent));
|
||||
handlerDrawable.setColor(ResourcesUtils.getAttrColor(context, R.attr.colorAccent));
|
||||
fastScroller.setHandlerDrawable(handlerDrawable);
|
||||
|
||||
if (null != mList && mList.size() > 0) {
|
||||
mViewTransition.showView(0);
|
||||
} else {
|
||||
mViewTransition.showView(1);
|
||||
}
|
||||
updateLazyList();
|
||||
updateView(false);
|
||||
|
||||
return view;
|
||||
}
|
||||
@@ -124,33 +162,95 @@ public class HistoryScene extends ToolbarScene
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mList) {
|
||||
mList.close();
|
||||
mList = null;
|
||||
if (null != mLazyList) {
|
||||
mLazyList.close();
|
||||
mLazyList = null;
|
||||
}
|
||||
if (null != mAdapter) {
|
||||
mAdapter.unregister();
|
||||
mAdapter = null;
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
|
||||
mViewTransition = null;
|
||||
mAdapter = null;
|
||||
}
|
||||
|
||||
// Remember to notify
|
||||
private void updateLazyList() {
|
||||
LazyList<HistoryInfo> lazyList = EhDB.getHistoryLazyList();
|
||||
if (mLazyList != null) {
|
||||
mLazyList.close();
|
||||
}
|
||||
mLazyList = lazyList;
|
||||
}
|
||||
|
||||
private void updateView(boolean animation) {
|
||||
if (null == mAdapter || null == mViewTransition) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mAdapter.getItemCount() == 0) {
|
||||
mViewTransition.showView(1, animation);
|
||||
} else {
|
||||
mViewTransition.showView(0, animation);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNavigationClick() {
|
||||
onBackPressed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMenuResId() {
|
||||
return R.menu.scene_history;
|
||||
}
|
||||
|
||||
private void showClearAllDialog() {
|
||||
new AlertDialog.Builder(getContext2())
|
||||
.setMessage(R.string.clear_all_history)
|
||||
.setPositiveButton(R.string.clear_all, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
if (DialogInterface.BUTTON_POSITIVE != which || null == mAdapter) {
|
||||
return;
|
||||
}
|
||||
|
||||
EhDB.clearHistoryInfo();
|
||||
updateLazyList();
|
||||
mAdapter.notifyDataSetChanged();
|
||||
updateView(true);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onMenuItemClick(MenuItem item) {
|
||||
// Skip when in choice mode
|
||||
Context context = getContext2();
|
||||
if (null == context) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int id = item.getItemId();
|
||||
switch (id) {
|
||||
case R.id.action_clear_all: {
|
||||
showClearAllDialog();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
if (null == mList) {
|
||||
if (null == mLazyList) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Bundle args = new Bundle();
|
||||
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GALLERY_INFO);
|
||||
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, mList.get(position));
|
||||
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, mLazyList.get(position));
|
||||
Announcer announcer = new Announcer(GalleryDetailScene.class).setArgs(args);
|
||||
View thumb;
|
||||
if (ApiHelper.SUPPORT_TRANSITION && null != (thumb = view.findViewById(R.id.thumb))) {
|
||||
@@ -162,24 +262,26 @@ public class HistoryScene extends ToolbarScene
|
||||
|
||||
@Override
|
||||
public boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id) {
|
||||
if (null == mList) {
|
||||
final Context context = getContext2();
|
||||
final MainActivity activity = getActivity2();
|
||||
if (null == context || null == activity || null == mLazyList) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final GalleryInfo gi = mList.get(position);
|
||||
new AlertDialog.Builder(getContext())
|
||||
final GalleryInfo gi = mLazyList.get(position);
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(EhUtils.getSuitableTitle(gi))
|
||||
.setItems(R.array.gallery_list_menu_entries, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
switch (which) {
|
||||
case 0: // Download
|
||||
CommonOperations.startDownload(getActivity(), gi, false);
|
||||
CommonOperations.startDownload(activity, gi, false);
|
||||
break;
|
||||
case 1: // Favorites
|
||||
CommonOperations.addToFavorites(getActivity(), gi,
|
||||
new addToFavoriteListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag()));
|
||||
CommonOperations.addToFavorites(activity, gi,
|
||||
new addToFavoriteListener(context,
|
||||
activity.getStageId(), getTag()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -187,22 +289,130 @@ public class HistoryScene extends ToolbarScene
|
||||
return true;
|
||||
}
|
||||
|
||||
private class HistoryAdapter extends GalleryAdapter {
|
||||
private class HistoryHolder extends AbstractSwipeableItemViewHolder {
|
||||
|
||||
public HistoryAdapter(LayoutInflater inflater, Context context,
|
||||
RecyclerView recyclerView, GridLayoutManager layoutManager, int type) {
|
||||
super(inflater, context, recyclerView, layoutManager, type);
|
||||
public final LoadImageView thumb;
|
||||
public final TextView title;
|
||||
public final TextView uploader;
|
||||
public final SimpleRatingView rating;
|
||||
public final TextView category;
|
||||
public final TextView posted;
|
||||
public final TextView simpleLanguage;
|
||||
|
||||
public HistoryHolder(View itemView) {
|
||||
super(itemView);
|
||||
|
||||
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
|
||||
title = (TextView) itemView.findViewById(R.id.title);
|
||||
uploader = (TextView) itemView.findViewById(R.id.uploader);
|
||||
rating = (SimpleRatingView) itemView.findViewById(R.id.rating);
|
||||
category = (TextView) itemView.findViewById(R.id.category);
|
||||
posted = (TextView) itemView.findViewById(R.id.posted);
|
||||
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public GalleryInfo getDataAt(int position) {
|
||||
return null != mList ? mList.get(position) : null;
|
||||
public View getSwipeableContainerView() {
|
||||
return itemView;
|
||||
}
|
||||
}
|
||||
|
||||
private class HistoryAdapter extends RecyclerView.Adapter<HistoryHolder>
|
||||
implements SwipeableItemAdapter<HistoryHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public HistoryAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
if (null == mLazyList) {
|
||||
return super.getItemId(position);
|
||||
} else {
|
||||
return mLazyList.get(position).gid;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public HistoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new HistoryHolder(mInflater.inflate(R.layout.item_gallery_list, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(HistoryHolder holder, int position) {
|
||||
if (null == mLazyList) {
|
||||
return;
|
||||
}
|
||||
|
||||
GalleryInfo gi = mLazyList.get(position);
|
||||
holder.thumb.load(EhCacheKeyFactory.getThumbKey(gi.gid), gi.thumb);
|
||||
holder.title.setText(EhUtils.getSuitableTitle(gi));
|
||||
holder.uploader.setText(gi.uploader);
|
||||
holder.rating.setRating(gi.rating);
|
||||
TextView category = holder.category;
|
||||
String newCategoryText = EhUtils.getCategory(gi.category);
|
||||
if (!newCategoryText.equals(category.getText())) {
|
||||
category.setText(newCategoryText);
|
||||
category.setBackgroundColor(EhUtils.getCategoryColor(gi.category));
|
||||
}
|
||||
holder.posted.setText(gi.posted);
|
||||
holder.simpleLanguage.setText(gi.simpleLanguage);
|
||||
|
||||
// Update transition name
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
long gid = gi.gid;
|
||||
holder.thumb.setTransitionName(TransitionNameFactory.getThumbTransitionName(gid));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return null != mList ? mList.size() : 0;
|
||||
return null != mLazyList ? mLazyList.size() : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onGetSwipeReactionType(HistoryHolder holder, int position, int x, int y) {
|
||||
return SwipeableItemConstants.REACTION_CAN_SWIPE_BOTH_H;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSetSwipeBackground(HistoryHolder holder, int position, int type) {}
|
||||
|
||||
@Override
|
||||
public SwipeResultAction onSwipeItem(HistoryHolder holder, int position, int result) {
|
||||
switch (result) {
|
||||
case SwipeableItemConstants.RESULT_SWIPED_LEFT:
|
||||
case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
|
||||
return new SwipeResultActionClear(position);
|
||||
case SwipeableItemConstants.RESULT_CANCELED:
|
||||
default:
|
||||
return new SwipeResultActionDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class SwipeResultActionClear extends SwipeResultActionRemoveItem {
|
||||
|
||||
private final int mPosition;
|
||||
|
||||
protected SwipeResultActionClear(int position) {
|
||||
mPosition = position;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPerformAction() {
|
||||
super.onPerformAction();
|
||||
if (null == mLazyList || null == mAdapter) {
|
||||
return;
|
||||
}
|
||||
|
||||
HistoryInfo info = mLazyList.get(mPosition);
|
||||
EhDB.deleteHistoryInfo(info);
|
||||
updateLazyList();
|
||||
mAdapter.notifyItemRemoved(mPosition);
|
||||
updateView(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,12 +30,14 @@ import com.hippo.ehviewer.EhApplication;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.client.EhClient;
|
||||
import com.hippo.ehviewer.client.EhRequest;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.scene.Announcer;
|
||||
import com.hippo.scene.SceneFragment;
|
||||
import com.hippo.scene.StageActivity;
|
||||
import com.hippo.util.DrawableManager;
|
||||
import com.hippo.util.ExceptionUtils;
|
||||
import com.hippo.view.ViewTransition;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
/**
|
||||
* Only show a progress with jobs in background
|
||||
@@ -61,7 +63,9 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
private String mPToken;
|
||||
private int mPage;
|
||||
|
||||
@Nullable
|
||||
private TextView mTip;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
|
||||
@Override
|
||||
@@ -81,6 +85,12 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
}
|
||||
|
||||
private boolean doJobs() {
|
||||
Context context = getContext2();
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == context || null == activity) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ACTION_GALLERY_TOKEN.equals(mAction)) {
|
||||
if (mGid == -1 || mPToken == null || mPage == -1) {
|
||||
return false;
|
||||
@@ -89,9 +99,9 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
EhRequest request = new EhRequest()
|
||||
.setMethod(EhClient.METHOD_GET_GALLERY_TOKEN)
|
||||
.setArgs(mGid, mPToken, mPage)
|
||||
.setCallback(new GetGalleryTokenListener(getContext(),
|
||||
((StageActivity) getActivity()).getStageId(), getTag()));
|
||||
EhApplication.getEhClient(getContext()).execute(request);
|
||||
.setCallback(new GetGalleryTokenListener(context,
|
||||
activity.getStageId(), getTag()));
|
||||
EhApplication.getEhClient(context).execute(request);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -152,13 +162,16 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater,
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_progress, container, false);
|
||||
View progress = view.findViewById(R.id.progress);
|
||||
mTip = (TextView) view.findViewById(R.id.tip);
|
||||
View progress = ViewUtils.$$(view, R.id.progress);
|
||||
mTip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_weird_face);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
mTip.setCompoundDrawables(null, drawable, null, null);
|
||||
mTip.setOnClickListener(this);
|
||||
@@ -175,13 +188,23 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
mTip = null;
|
||||
mViewTransition = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mTip == v) {
|
||||
if (doJobs()) {
|
||||
mValid = true;
|
||||
// Show progress
|
||||
mViewTransition.showView(0, true);
|
||||
if (null != mViewTransition) {
|
||||
mViewTransition.showView(0, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,10 +221,12 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
|
||||
|
||||
private void onGetGalleryTokenFailure(Exception e) {
|
||||
mValid = false;
|
||||
mError = ExceptionUtils.getReadableString(getContext(), e);
|
||||
|
||||
if (isViewCreated()) {
|
||||
Context context = getContext2();
|
||||
|
||||
if (null != context && null != mViewTransition && null != mTip) {
|
||||
// Show tip
|
||||
mError = ExceptionUtils.getReadableString(e);
|
||||
mViewTransition.showView(1);
|
||||
mTip.setText(mError);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.ui.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.NinePatchDrawable;
|
||||
@@ -48,6 +49,7 @@ import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.dao.QuickSearch;
|
||||
import com.hippo.util.DrawableManager;
|
||||
import com.hippo.view.ViewTransition;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.List;
|
||||
@@ -64,6 +66,8 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
View life cycle
|
||||
---------------*/
|
||||
@Nullable
|
||||
private EasyRecyclerView mRecyclerView;
|
||||
@Nullable
|
||||
private ViewTransition mViewTransition;
|
||||
@Nullable
|
||||
private RecyclerView.Adapter mAdapter;
|
||||
@@ -83,15 +87,18 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
@SuppressWarnings("deprecation")
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
public View onCreateView3(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_label_list, container, false);
|
||||
|
||||
EasyRecyclerView recyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
|
||||
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
|
||||
TextView tip = (TextView) ViewUtils.$$(view, R.id.tip);
|
||||
mViewTransition = new ViewTransition(recyclerView, tip);
|
||||
mViewTransition = new ViewTransition(mRecyclerView, tip);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.big_search);
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
|
||||
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_search);
|
||||
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
|
||||
tip.setCompoundDrawables(null, drawable, null, null);
|
||||
tip.setText(R.string.no_quick_search);
|
||||
@@ -103,7 +110,7 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
// drag & drop manager
|
||||
RecyclerViewDragDropManager dragDropManager = new RecyclerViewDragDropManager();
|
||||
dragDropManager.setDraggingItemShadowDrawable(
|
||||
(NinePatchDrawable) getResources().getDrawable(R.drawable.shadow_8dp));
|
||||
(NinePatchDrawable) context.getResources().getDrawable(R.drawable.shadow_8dp));
|
||||
// swipe manager
|
||||
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
|
||||
RecyclerView.Adapter adapter = new QuickSearchAdapter();
|
||||
@@ -113,13 +120,13 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
mAdapter = adapter;
|
||||
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
|
||||
animator.setSupportsChangeAnimations(false);
|
||||
recyclerView.hasFixedSize();
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
|
||||
recyclerView.setAdapter(adapter);
|
||||
recyclerView.setItemAnimator(animator);
|
||||
guardManager.attachRecyclerView(recyclerView);
|
||||
swipeManager.attachRecyclerView(recyclerView);
|
||||
dragDropManager.attachRecyclerView(recyclerView);
|
||||
mRecyclerView.hasFixedSize();
|
||||
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
|
||||
mRecyclerView.setAdapter(adapter);
|
||||
mRecyclerView.setItemAnimator(animator);
|
||||
guardManager.attachRecyclerView(mRecyclerView);
|
||||
swipeManager.attachRecyclerView(mRecyclerView);
|
||||
dragDropManager.attachRecyclerView(mRecyclerView);
|
||||
|
||||
updateView();
|
||||
|
||||
@@ -137,6 +144,11 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
if (null != mRecyclerView) {
|
||||
mRecyclerView.stopScroll();
|
||||
mRecyclerView = null;
|
||||
}
|
||||
|
||||
mViewTransition = null;
|
||||
mAdapter = null;
|
||||
}
|
||||
@@ -181,10 +193,16 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
implements DraggableItemAdapter<QuickSearchHolder>,
|
||||
SwipeableItemAdapter<QuickSearchHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
public QuickSearchAdapter() {
|
||||
mInflater = getLayoutInflater2();
|
||||
AssertUtils.assertNotNull(mInflater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public QuickSearchHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
return new QuickSearchHolder(getActivity().getLayoutInflater()
|
||||
.inflate(R.layout.item_label_list, parent, false));
|
||||
return new QuickSearchHolder(mInflater.inflate(R.layout.item_label_list, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -269,14 +287,15 @@ public final class QuickSearchScene extends ToolbarScene {
|
||||
protected void onPerformAction() {
|
||||
super.onPerformAction();
|
||||
|
||||
Context context = getContext2();
|
||||
final List<QuickSearch> quickSearchList = mQuickSearchList;
|
||||
if (quickSearchList == null || mPosition < 0 || mPosition >= quickSearchList.size()) {
|
||||
if (null == context || null == quickSearchList || mPosition < 0 || mPosition >= quickSearchList.size()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final QuickSearch quickSearch = quickSearchList.get(mPosition);
|
||||
|
||||
new AlertDialog.Builder(getContext())
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle(R.string.delete_quick_search_title)
|
||||
.setMessage(getString(R.string.delete_quick_search_message, quickSearch.name))
|
||||
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* 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.scene;
|
||||
|
||||
import android.content.Context;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorManager;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.Settings;
|
||||
import com.hippo.ehviewer.ui.MainActivity;
|
||||
import com.hippo.hardware.ShakeDetector;
|
||||
import com.hippo.widget.lockpattern.LockPatternUtils;
|
||||
import com.hippo.widget.lockpattern.LockPatternView;
|
||||
import com.hippo.yorozuya.AssertUtils;
|
||||
import com.hippo.yorozuya.ObjectUtils;
|
||||
import com.hippo.yorozuya.ViewUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class SecurityScene extends BaseScene implements
|
||||
LockPatternView.OnPatternListener, ShakeDetector.OnShakeListener {
|
||||
|
||||
private static final int MAX_RETRY_TIMES = 5;
|
||||
|
||||
private static final String KEY_RETRY_TIMES = "retry_times";
|
||||
|
||||
@Nullable
|
||||
private LockPatternView mPatternView;
|
||||
|
||||
private SensorManager mSensorManager;
|
||||
private Sensor mAccelerometer;
|
||||
private ShakeDetector mShakeDetector;
|
||||
|
||||
private int mRetryTimes;
|
||||
|
||||
@Override
|
||||
public boolean needShowLeftDrawer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
Context context = getContext2();
|
||||
AssertUtils.assertNotNull(context);
|
||||
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
|
||||
if (null != mSensorManager) {
|
||||
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
|
||||
if (null != mAccelerometer) {
|
||||
mShakeDetector = new ShakeDetector();
|
||||
mShakeDetector.setOnShakeListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
if (null == savedInstanceState) {
|
||||
mRetryTimes = MAX_RETRY_TIMES;
|
||||
} else {
|
||||
mRetryTimes = savedInstanceState.getInt(KEY_RETRY_TIMES);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
mSensorManager = null;
|
||||
mAccelerometer = null;
|
||||
mShakeDetector = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
|
||||
if (null != mShakeDetector) {
|
||||
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
|
||||
if (null != mShakeDetector) {
|
||||
mSensorManager.unregisterListener(mShakeDetector);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSaveInstanceState(Bundle outState) {
|
||||
super.onSaveInstanceState(outState);
|
||||
outState.putInt(KEY_RETRY_TIMES, mRetryTimes);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView2(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.scene_security, container, false);
|
||||
|
||||
mPatternView = (LockPatternView) ViewUtils.$$(view, R.id.pattern_view);
|
||||
mPatternView.setOnPatternListener(this);
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
|
||||
mPatternView = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternStart() {}
|
||||
|
||||
@Override
|
||||
public void onPatternCleared() {}
|
||||
|
||||
@Override
|
||||
public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {}
|
||||
|
||||
@Override
|
||||
public void onPatternDetected(List<LockPatternView.Cell> pattern) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity || null == mPatternView) {
|
||||
return;
|
||||
}
|
||||
|
||||
String enteredPatter = LockPatternUtils.patternToString(pattern);
|
||||
String targetPatter = Settings.getSecurity();
|
||||
|
||||
if (ObjectUtils.equal(enteredPatter, targetPatter)) {
|
||||
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
|
||||
finish();
|
||||
} else {
|
||||
mPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
|
||||
mRetryTimes--;
|
||||
if (mRetryTimes <= 0) {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShake(int count) {
|
||||
if (count == 10) {
|
||||
MainActivity activity = getActivity2();
|
||||
if (null == activity) {
|
||||
return;
|
||||
}
|
||||
Settings.putSecurity("");
|
||||
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user