mirror of
https://github.com/seven332/EhViewer
synced 2026-11-30 02:58:04 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
937fc619dd | ||
|
|
30c46bd0a2 | ||
|
|
ae90c1b2b1 | ||
|
|
e6e85dc8d4 | ||
|
|
1a1242cc47 | ||
|
|
9b34b561d8 | ||
|
|
ee5cc24a4d | ||
|
|
6ebc172783 | ||
|
|
a6237f0dc5 | ||
|
|
66e2727acb | ||
|
|
78bcb037ac | ||
|
|
9aecbf9e66 | ||
|
|
bcba2f556b | ||
|
|
148f03a175 | ||
|
|
f39cfc7875 | ||
|
|
5bc166d3da | ||
|
|
7e5a844246 | ||
|
|
8cecf200eb | ||
|
|
535a6297af | ||
|
|
5ea2fdb651 | ||
|
|
bfe9044fda | ||
|
|
d277066d34 | ||
|
|
cbbe1478ae | ||
|
|
8848e712cc | ||
|
|
ed693d1742 | ||
|
|
626def198c | ||
|
|
b9fc9b054b | ||
|
|
602f68e88b | ||
|
|
dfa00b7605 | ||
|
|
27cb0aa260 | ||
|
|
416d080eb4 | ||
|
|
386c98575d | ||
|
|
84f9aef856 | ||
|
|
13cbb7507e | ||
|
|
4a1594f982 | ||
|
|
761ce507f1 | ||
|
|
67884ed9d3 | ||
|
|
12412d67fb | ||
|
|
2c58f6c9ae | ||
|
|
65e908546b | ||
|
|
ea18b8c090 | ||
|
|
6c182f3bba | ||
|
|
807c49eea1 | ||
|
|
50dd19222e | ||
|
|
b5bbf19a65 | ||
|
|
9ed06be68b | ||
|
|
9da0c76da6 | ||
|
|
1b06d19059 | ||
|
|
e258617c23 | ||
|
|
839a7227ab | ||
|
|
f49b111e15 | ||
|
|
d5d6b6fb4c | ||
|
|
7cc794d614 | ||
|
|
f209f5f157 | ||
|
|
ca4be438c5 | ||
|
|
d9411b190c | ||
|
|
ec2cb356c1 | ||
|
|
15a2db978c | ||
|
|
a9506b1f53 | ||
|
|
1a8f6752c7 | ||
|
|
637579db5c | ||
|
|
534c5506e6 | ||
|
|
a2182e0f05 | ||
|
|
0d0153c6e8 | ||
|
|
ca6281bf72 | ||
|
|
a50df7308f | ||
|
|
d31a51ab9a | ||
|
|
91aa31503b | ||
|
|
a5e07a0ebe | ||
|
|
cfa51276bd | ||
|
|
148470e4be | ||
|
|
fd72fbf9bd | ||
|
|
b37087a69d | ||
|
|
ec1694347a | ||
|
|
a89b001370 | ||
|
|
867a0f4ef7 | ||
|
|
fee7d87a21 | ||
|
|
ffd0ca0cec | ||
|
|
7d819d4ac6 | ||
|
|
e08ee26991 | ||
|
|
599649200c | ||
|
|
4e4c670c97 | ||
|
|
1def607a80 | ||
|
|
5bee5d6663 | ||
|
|
834b9b7a2a | ||
|
|
4e7bb7aec3 | ||
|
|
f4c73e3b32 | ||
|
|
bb6f8ded7f | ||
|
|
e7753fddec | ||
|
|
29e77faec9 | ||
|
|
e0cc198d96 | ||
|
|
cc9d194ddd | ||
|
|
0735fa2425 | ||
|
|
d8fc3f0a51 | ||
|
|
c47f124854 | ||
|
|
7dba58b1aa | ||
|
|
5f34b5aeb0 | ||
|
|
7470a25cbe | ||
|
|
28b31d3439 | ||
|
|
97d855b546 | ||
|
|
711564a0ab | ||
|
|
f20bc2c954 | ||
|
|
ed0702068c | ||
|
|
b568082c2d | ||
|
|
f89ae0d1b1 | ||
|
|
d2c4cf598a | ||
|
|
f9ceddfabf | ||
|
|
cec40a8f89 | ||
|
|
4a4ec2312a | ||
|
|
5417918382 | ||
|
|
f8b2b46172 | ||
|
|
d0f07ae62b | ||
|
|
5d7b99e328 | ||
|
|
ae563a7950 | ||
|
|
1f6668cd8c | ||
|
|
24a384eed7 | ||
|
|
b5eeee9b73 | ||
|
|
1bd32d97de | ||
|
|
5e6d771dad | ||
|
|
9b80be453c | ||
|
|
7d0bfc1aa7 | ||
|
|
3d31c32d40 | ||
|
|
087a6ee305 | ||
|
|
9056d7ced0 | ||
|
|
4a8e01caec | ||
|
|
1088729269 | ||
|
|
21ac176f5f | ||
|
|
b3cc1dec4b | ||
|
|
3da180beb0 | ||
|
|
acec30ae5a | ||
|
|
8229007710 | ||
|
|
80e0432c73 | ||
|
|
c97dccaf04 | ||
|
|
f4bdbe1ed1 | ||
|
|
75a67ae54e | ||
|
|
61c3144a48 | ||
|
|
8158bae9d5 | ||
|
|
9615aa0b7c | ||
|
|
870153ef88 | ||
|
|
741203ab81 | ||
|
|
0b74bf3fc3 | ||
|
|
f5f7489093 | ||
|
|
05dae37a28 | ||
|
|
1384a05830 | ||
|
|
256b4896cb | ||
|
|
c44011402f | ||
|
|
eff24ca4b3 | ||
|
|
8f16044c6b | ||
|
|
7c46027bd6 | ||
|
|
5f7b677db7 | ||
|
|
b27e02fed1 | ||
|
|
abe2189acd | ||
|
|
721659d959 | ||
|
|
d2e083922e | ||
|
|
34181ce370 | ||
|
|
a939c505f9 | ||
|
|
5de9fc8134 | ||
|
|
0c45ddf04d | ||
|
|
74e37ea72d | ||
|
|
c6c060b5e2 | ||
|
|
def283de08 | ||
|
|
be3d3189ec | ||
|
|
0581b7cc53 | ||
|
|
79b75e5de1 | ||
|
|
f7be9dec18 | ||
|
|
566226958f | ||
|
|
e45db97a54 | ||
|
|
ea58ffed74 | ||
|
|
eb1e49e7c7 | ||
|
|
b69c71a54b | ||
|
|
3aff219639 | ||
|
|
e1edd00fb0 | ||
|
|
70e0aada25 | ||
|
|
1c11ac38ea | ||
|
|
7ac8878f83 | ||
|
|
a48a18ba84 | ||
|
|
8a2a2061a9 | ||
|
|
b1f772eb2f | ||
|
|
37043c1284 | ||
|
|
7f693f4e1d | ||
|
|
529ed71ebe | ||
|
|
644d3d6402 | ||
|
|
83395619e7 | ||
|
|
cde6904e3f | ||
|
|
74dcbae3dd | ||
|
|
70f6a2fa78 | ||
|
|
567b0a2c19 | ||
|
|
5e28481684 | ||
|
|
90ed3d40f3 | ||
|
|
366285f625 | ||
|
|
7945b0facd | ||
|
|
556429a4d6 | ||
|
|
601d426721 | ||
|
|
aa3d3ca57c | ||
|
|
471cf5df85 | ||
|
|
177920a1eb | ||
|
|
ab4b4ad598 | ||
|
|
626f7141e9 | ||
|
|
30c7ac5100 | ||
|
|
b30489785f | ||
|
|
22e042d11d | ||
|
|
6137e851cd | ||
|
|
57419fd8d1 | ||
|
|
471962e664 | ||
|
|
7254d9d7a7 | ||
|
|
ea2418b981 | ||
|
|
5c4009e435 | ||
|
|
89c7beda26 | ||
|
|
c6109bd0d4 | ||
|
|
15d6e4f87c | ||
|
|
7cfd910122 | ||
|
|
c67619d54c | ||
|
|
38ec446130 | ||
|
|
60a5fd2443 | ||
|
|
f8907c6e8f | ||
|
|
61e318fb6e | ||
|
|
1382a83648 |
No files matched your search
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
|
||||
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
|
||||
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="src" path="gen"/>
|
||||
<classpathentry kind="output" path="bin/classes"/>
|
||||
</classpath>
|
||||
@@ -1,8 +0,0 @@
|
||||
.gradle
|
||||
/local.properties
|
||||
.DS_Store
|
||||
/build
|
||||
/src
|
||||
*.iml
|
||||
.idea
|
||||
/captures
|
||||
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>EhViewer</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
||||
@@ -0,0 +1,4 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
|
||||
org.eclipse.jdt.core.compiler.compliance=1.6
|
||||
org.eclipse.jdt.core.compiler.source=1.6
|
||||
@@ -0,0 +1,133 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Copyright (C) 2014 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.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.hippo.ehviewer"
|
||||
android:versionCode="18"
|
||||
android:versionName="0.5.3" >
|
||||
|
||||
<uses-sdk
|
||||
android:minSdkVersion="14"
|
||||
android:targetSdkVersion="19" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
|
||||
<application
|
||||
android:name=".AppContext"
|
||||
android:allowBackup="true"
|
||||
android:largeHeap="false"
|
||||
android:hardwareAccelerated="true"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme.Normal" >
|
||||
|
||||
<activity
|
||||
android:name=".StartActivity"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent"
|
||||
android:screenOrientation="portrait" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.MangaListActivity"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:theme="@style/AppTheme.Main.ListActivity"
|
||||
android:launchMode="singleTask" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEARCH" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.app.searchable"
|
||||
android:resource="@xml/searchable" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.MangaDetailActivity"
|
||||
android:screenOrientation="portrait"
|
||||
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden"
|
||||
android:configChanges="orientation|screenSize" >
|
||||
<intent-filter>
|
||||
<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
|
||||
android:name="com.hippo.ehviewer.ui.MangaActivity"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.SettingsActivity"
|
||||
android:label="@string/preference_settings_title"
|
||||
android:icon="@drawable/ic_action_settings"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.FavouriteActivity"
|
||||
android:label="@string/favourite"
|
||||
android:icon="@drawable/ic_action_favorite"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.DownloadActivity"
|
||||
android:label="@string/download"
|
||||
android:icon="@drawable/ic_action_download"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:launchMode="singleTask"
|
||||
android:parentActivityName="com.hippo.ehviewer.ui.MangaListActivity"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="com.hippo.ehviewer.activity.MangaListActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.hippo.ehviewer.ui.MangaDownloadActivity"
|
||||
android:label="@string/download"
|
||||
android:icon="@drawable/ic_action_download"
|
||||
android:screenOrientation="portrait"
|
||||
android:configChanges="orientation|screenSize" >
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".service.DownloadService"
|
||||
android:label="DownloadService" />
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module external.linked.project.id="EhViewer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="java-gradle" name="Java-Gradle">
|
||||
<configuration>
|
||||
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
|
||||
<option name="BUILDABLE" value="false" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
@@ -1,70 +1,13 @@
|
||||
# EhViewer
|
||||
|
||||
这是一个 Android 平台上的 E-Hentai 阅读应用。访问 [EhViewer](http://www.ehviewer.com/) 网站以获取更多信息。<br>
|
||||
EhViewer is an E-Hentai Application for Android. Visit [EhViewer](http://www.ehviewer.com/)(Chinese Only) website for more information.
|
||||
|
||||
# Build
|
||||
|
||||
导入 Android Studio 即可。<br>
|
||||
Just import into Android Studio.
|
||||
|
||||
# Thanks
|
||||
|
||||
- [android-gif-drawable](https://github.com/koral--/android-gif-drawable)
|
||||
- 参考 gif 解码
|
||||
- [ActionBar-PullToRefresh](https://github.com/chrisbanes/ActionBar-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [ActionBarSherlocke](https://github.com/JakeWharton/ActionBarSherlock)
|
||||
- 曾用来对 4.0 一些系统兼容
|
||||
- [Android-PullToRefresh](https://github.com/chrisbanes/Android-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [AndroidStaggeredGrid](https://github.com/etsy/AndroidStaggeredGrid)
|
||||
- 列表控件
|
||||
- [Apollo-CM](https://github.com/adneal/Apollo-CM)
|
||||
- 缓存机制
|
||||
- [DiskLruCache](https://github.com/JakeWharton/DiskLruCache)
|
||||
- 缓存机制
|
||||
- [FloatingActionButton](https://github.com/FaizMalkani/FloatingActionButton)
|
||||
- 按钮控件
|
||||
- [GIFLIB](http://giflib.sourceforge.net)
|
||||
- gif 解码
|
||||
- [Gloria Hallelujah](https://www.google.com/fonts/specimen/Gloria+Hallelujah)
|
||||
- 启动界面字体
|
||||
- [ImageLoadingPattern](https://github.com/rnrneverdies/ImageLoadingPattern)
|
||||
- 图片过渡效果
|
||||
- [libjpeg-turbo](http://www.libjpeg-turbo.org)
|
||||
- jpge 解码
|
||||
- [libpng](http://www.libpng.org/pub/png/libpng.html)
|
||||
- png 解码
|
||||
- [material-menu](https://github.com/balysv/material-menu)
|
||||
- 抽屉指示器
|
||||
- [OpenCC](https://github.com/BYVoid/OpenCC)
|
||||
- 繁化工作
|
||||
- [Slabo](https://github.com/TiroTypeworks/Slabo)
|
||||
- 图标字体
|
||||
- [SlidingMenu](https://github.com/jfeinstein10/SlidingMenu)
|
||||
- 曾作为抽屉控件
|
||||
- [source-code-pro](https://github.com/adobe/source-code-pro)
|
||||
- 刷新控件字体
|
||||
- [svg-android](https://code.google.com/p/svg-android/)
|
||||
- svg 解析
|
||||
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
|
||||
- 状态栏背景设置
|
||||
- [twoway-view](https://github.com/lucasr/twoway-view)
|
||||
- RecyclerView 使用方法
|
||||
- [zlib](http://www.zlib.net)
|
||||
- 辅助 png 解码
|
||||
- [Android Open Source Project](http://source.android.com)
|
||||
- 很多很多
|
||||
- [commons-lang](http://commons.apache.org/proper/commons-lang)
|
||||
- 很多很多
|
||||
这是一个 Android 平台上的 E-Hentai 阅读应用。<br>
|
||||
E-Hentai Application for Android.
|
||||
|
||||
# License
|
||||
|
||||
本项目内容采用 [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) 授权,
|
||||
部分文件采用 [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) 授权([列表](rc/list1)),
|
||||
部分文件采用 [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) 授权([列表](rc/list2))。
|
||||
<br>
|
||||
部分文件可随意使用([列表](rc/list2))。<br>
|
||||
The content of this project itself is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0),
|
||||
some files are licensed under the [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) ([list](rc/list1)),
|
||||
some files are licensed under the [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) ([list](rc/list2)).
|
||||
some files are free to use ([list](rc/list2)).
|
||||
@@ -1,3 +0,0 @@
|
||||
/build
|
||||
/src/main/obj
|
||||
/src/main/libs
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EhViewer" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="android-gradle" name="Android-Gradle">
|
||||
<configuration>
|
||||
<option name="GRADLE_PROJECT_PATH" value=":app" />
|
||||
</configuration>
|
||||
</facet>
|
||||
<facet type="android" name="Android">
|
||||
<configuration>
|
||||
<option name="SELECTED_BUILD_VARIANT" value="debug" />
|
||||
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
|
||||
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
|
||||
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
|
||||
<afterSyncTasks>
|
||||
<task>generateDebugSources</task>
|
||||
</afterSyncTasks>
|
||||
<option name="ALLOW_USER_CONFIGURATION" value="false" />
|
||||
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
|
||||
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
|
||||
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
|
||||
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
|
||||
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
|
||||
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/recyclerview-v7/22.2.1/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/22.2.1/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-safeguard" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/instant-run-support" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-v4-22.2.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-22.2.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-annotations-22.2.1" level="project" />
|
||||
<orderEntry type="module" module-name="vector" exported="" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -1,72 +0,0 @@
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion '22.0.1'
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.hippo.ehviewer"
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 22
|
||||
versionCode 47
|
||||
versionName "0.6.16.3"
|
||||
}
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
release {
|
||||
minifyEnabled true
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
checkReleaseBuilds false
|
||||
// Or, if you prefer, you can continue to check for errors in release builds,
|
||||
// but continue the build even when errors are found:
|
||||
abortOnError false
|
||||
}
|
||||
|
||||
// Disable default NdkCompile task
|
||||
// Set new jni lib dir
|
||||
sourceSets.main {
|
||||
jni.srcDirs = []
|
||||
jniLibs.srcDir 'src/main/libs'
|
||||
}
|
||||
|
||||
// noinspection GroovyAssignabilityCheck
|
||||
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
|
||||
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
|
||||
def ndkBuilder
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
ndkBuilder = 'ndk-build.cmd'
|
||||
} else {
|
||||
ndkBuilder = 'ndk-build'
|
||||
}
|
||||
commandLine "$ndkDir\\$ndkBuilder",
|
||||
'-C', file('src/main').absolutePath,
|
||||
'NDK_DEBUG=0',
|
||||
'NDK_TOOLCHAIN_VERSION=clang',
|
||||
'-j4'
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile) {
|
||||
compileTask -> compileTask.dependsOn ndkBuild
|
||||
}
|
||||
}
|
||||
|
||||
clean {
|
||||
delete file('src/main/obj').absolutePath
|
||||
delete file('src/main/libs').absolutePath
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(dir: 'libs', include: ['*.jar'])
|
||||
compile project(':vector')
|
||||
compile 'com.android.support:support-v4:22.2.1'
|
||||
compile 'com.android.support:recyclerview-v7:22.2.1'
|
||||
}
|
||||
Binary file not shown.
Vendored
-55
@@ -1,55 +0,0 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# By default, the flags in this file are appended to flags specified
|
||||
# in E:\Android\android-sdk/tools/proguard/proguard-android.txt
|
||||
# You can edit the include path and order by changing the proguardFiles
|
||||
# directive in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# Add any project specific keep options here:
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
-keep class com.hippo.ehviewer.widget.SearchView {*;}
|
||||
|
||||
-keep class com.hippo.ehviewer.gallery.image.Image {*;}
|
||||
|
||||
-keep class com.hippo.ehviewer.gallery.image.GifImage {*;}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.drawable.MaterialProgressDrawable$Ring {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class * extends com.hippo.ehviewer.windowsanimate.Sprite {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class * extends android.graphics.drawable.Drawable {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.effect.ripple.Ripple {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.effect.ripple.RippleBackground {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
# For VectorResources
|
||||
-keep class android.content.res.VectorResources {*;}
|
||||
|
||||
# I want to track the error in them
|
||||
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.Application;
|
||||
import android.test.ApplicationTestCase;
|
||||
|
||||
/**
|
||||
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
|
||||
*/
|
||||
public class ApplicationTest extends ApplicationTestCase<Application> {
|
||||
public ApplicationTest() {
|
||||
super(Application.class);
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright (C) 2014 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.
|
||||
-->
|
||||
<manifest
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.hippo.ehviewer">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
|
||||
<application
|
||||
android:name=".AppContext"
|
||||
android:allowBackup="true"
|
||||
android:hardwareAccelerated="true"
|
||||
android:largeHeap="true"
|
||||
android:supportsRtl="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme.Normal">
|
||||
|
||||
<activity
|
||||
android:name=".StartActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent.Translucent" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryListActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:launchMode="singleTop"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.Main.ListActivity" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEARCH" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.app.searchable"
|
||||
android:resource="@xml/searchable" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.WebViewLoginActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/login"
|
||||
android:screenOrientation="behind"
|
||||
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
|
||||
android:theme="@style/AppTheme.NoActionBar">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryDetailActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden" >
|
||||
<intent-filter>
|
||||
<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:scheme="https" />
|
||||
<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
|
||||
android:name=".ui.GalleryActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.Dark.NoActionBar" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.SettingsActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/preference_settings_title"
|
||||
android:screenOrientation="behind" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.FavouriteActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/favourite"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.HistoryActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/history"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.DownloadActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/download"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value=".ui.GalleryListActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.SecretActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.PatternProtectionActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/AppTheme" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.EnterPatternActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/AppTheme" >
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".service.DownloadService"
|
||||
android:label="DownloadService" />
|
||||
|
||||
<provider
|
||||
android:name=".SimpleSuggestionProvider"
|
||||
android:authorities="com.hippo.ehviewer.SimpleSuggestionProvider"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver android:name=".receiver.RestPatternReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.provider.Telephony.SECRET_CODE"/>
|
||||
<data android:scheme="android_secret_code" android:host="110722"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,179 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.graphics.Typeface;
|
||||
import android.view.ContextThemeWrapper;
|
||||
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SlidingDrawerLayout;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.Thread.UncaughtExceptionHandler;
|
||||
|
||||
public class AppContext extends Application implements UncaughtExceptionHandler {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = AppContext.class.getSimpleName();
|
||||
|
||||
private Thread.UncaughtExceptionHandler mDefaultHandler;
|
||||
|
||||
private Typeface mFaceTypeface;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
// Do catch error prepare
|
||||
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
|
||||
Context mContextThemeWrapper = new ContextThemeWrapper(this, R.style.AppTheme);
|
||||
ViewUtils.initDialogViewInflater(this);
|
||||
|
||||
// Init everything
|
||||
Ui.init(mContextThemeWrapper);
|
||||
Config.init(mContextThemeWrapper);
|
||||
Log.init(mContextThemeWrapper);
|
||||
Crash.init(mContextThemeWrapper);
|
||||
EhClient.createInstance(mContextThemeWrapper);
|
||||
FavoriteHelper.init(mContextThemeWrapper);
|
||||
Data.createInstance(mContextThemeWrapper);
|
||||
ExDownloaderManager.createInstance(mContextThemeWrapper);
|
||||
MaterialToast.setContext(mContextThemeWrapper);
|
||||
|
||||
mFaceTypeface = Typeface.createFromAsset(getAssets(),"fonts/face.ttf");
|
||||
|
||||
// Set drawer margin
|
||||
SlidingDrawerLayout.setDefaultMinDrawerMargin(Ui.ACTION_BAR_HEIGHT * 2);
|
||||
|
||||
// Add .nomedia or delete it
|
||||
File nomedia = new File(Config.getDownloadPath(), ".nomedia");
|
||||
if (Config.getMediaScan()) {
|
||||
nomedia.delete();
|
||||
} else {
|
||||
try {
|
||||
new FileOutputStream(nomedia).close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
|
||||
// Update proxy urls
|
||||
HttpHelper.updateProxyUrls(mContextThemeWrapper);
|
||||
|
||||
String keyVersionCode = "version_code";
|
||||
int oldVersion = Config.getInt(keyVersionCode, Integer.MAX_VALUE);
|
||||
// Fix <=22 login error
|
||||
if (oldVersion <= 22)
|
||||
EhInfo.getInstance(mContextThemeWrapper).logout();
|
||||
|
||||
// Fix <=25 Update
|
||||
if (oldVersion <= 25) {
|
||||
File downloadDir = new File(Config.getDownloadPath());
|
||||
String cachePath = getExternalCacheDir() != null
|
||||
? getExternalCacheDir().getPath()
|
||||
: getCacheDir().getPath();
|
||||
File oldEdInfoDir = new File(cachePath, "ExDownloaderManager");
|
||||
String[] list = downloadDir.list();
|
||||
if (list != null && list.length != 0) {
|
||||
for (String str : list) {
|
||||
int index = str.indexOf('-');
|
||||
if (index == -1)
|
||||
continue;
|
||||
String gid = str.substring(0, index);
|
||||
File gDir = new File(downloadDir, str);
|
||||
// Move download info file
|
||||
File oldInfoFile = new File(oldEdInfoDir, gid);
|
||||
File newInfoFile = new File(gDir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
if (!oldInfoFile.exists())
|
||||
continue;
|
||||
try {
|
||||
FileOutputStream fos = new FileOutputStream(newInfoFile);
|
||||
// Add last page
|
||||
byte[] bs = {'0', '0', '0', '0', '0', '0', '0', '0', '\n'};
|
||||
fos.write(bs);
|
||||
Utils.copy(new FileInputStream(oldInfoFile), fos);
|
||||
} catch (Throwable e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Delete old exdownload info dir
|
||||
Utils.deleteDirInThread(oldEdInfoDir);
|
||||
}
|
||||
|
||||
// Update version code
|
||||
try {
|
||||
PackageInfo pi= getPackageManager().getPackageInfo(getPackageName(), 0);
|
||||
Config.setInt(keyVersionCode, pi.versionCode);
|
||||
} catch (NameNotFoundException e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void onLowMemory() {
|
||||
ImageCache.getImageCache(this).clearMemory();
|
||||
super.onLowMemory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uncaughtException(Thread thread, Throwable ex) {
|
||||
if (!handleException(ex) && mDefaultHandler != null) {
|
||||
mDefaultHandler.uncaughtException(thread, ex);
|
||||
}
|
||||
android.os.Process.killProcess(android.os.Process.myPid());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
private boolean handleException(Throwable ex) {
|
||||
if (ex == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Crash.saveCrashInfo2File(ex);
|
||||
return true;
|
||||
} catch (Throwable tr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Typeface getFaceTypeface() {
|
||||
return mFaceTypeface;
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.Constants;
|
||||
|
||||
public class AppHandler extends Handler {
|
||||
|
||||
public static final int HTTP_HELPER_TAG = 0x1;
|
||||
|
||||
private static Handler sInstance;
|
||||
|
||||
public AppHandler(Looper mainLooper) {
|
||||
super(mainLooper);
|
||||
}
|
||||
|
||||
public final static Handler getInstance() {
|
||||
if (sInstance == null)
|
||||
sInstance = new AppHandler(Looper.getMainLooper());
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
switch(msg.what) {
|
||||
|
||||
case HTTP_HELPER_TAG:
|
||||
HttpHelper.Package p = (HttpHelper.Package)msg.obj;
|
||||
HttpHelper.OnRespondListener listener = p.listener;
|
||||
Object obj = p.obj;
|
||||
if (msg.arg1 == Constants.TRUE) {
|
||||
listener.onSuccess(obj);
|
||||
} else {
|
||||
listener.onFailure((String)obj);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.cache.AnyCache;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class ImageLoader {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = ImageLoader.class.getSimpleName();
|
||||
|
||||
public static final int STATE_NONE = 0;
|
||||
public static final int STATE_FROM_MEMORY = 1;
|
||||
public static final int STATE_FROM_DISK = 2;
|
||||
public static final int STATE_FROM_NETWORK = 3;
|
||||
|
||||
private static ImageLoader sInstance;
|
||||
|
||||
class LoadTask {
|
||||
public String url;
|
||||
public String key;
|
||||
public OnGetImageListener listener;
|
||||
public Bitmap bitmap;
|
||||
public int state;
|
||||
|
||||
public LoadTask(String url, String key, OnGetImageListener listener) {
|
||||
this.url = url;
|
||||
this.key = key;
|
||||
this.listener = listener;
|
||||
}
|
||||
}
|
||||
|
||||
private final Context mContext;
|
||||
private final Stack<LoadTask> mLoadTasks;
|
||||
private final AnyCache<Bitmap> mImageCache;
|
||||
private final ImageDownloader mImageDownloader;
|
||||
|
||||
private ImageLoader(Context context) {
|
||||
mLoadTasks = new Stack<LoadTask>();
|
||||
mImageDownloader = new ImageDownloader();
|
||||
|
||||
mContext = context;
|
||||
mImageCache = ImageCache.getImageCache(mContext);
|
||||
|
||||
new BgThread(new LoadFromCacheTask()).start();
|
||||
}
|
||||
|
||||
public final static ImageLoader getInstance(final Context context) {
|
||||
if (sInstance == null) {
|
||||
sInstance = new ImageLoader(context.getApplicationContext());
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
public void add(String url, String key, OnGetImageListener listener) {
|
||||
synchronized (mLoadTasks) {
|
||||
mLoadTasks.push(new LoadTask(url, key, listener));
|
||||
mLoadTasks.notify();
|
||||
}
|
||||
}
|
||||
|
||||
private class LoadImageCallback implements Runnable {
|
||||
|
||||
private final LoadTask mLoadTask;
|
||||
|
||||
private LoadImageCallback(LoadTask task) {
|
||||
mLoadTask = task;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mLoadTask.listener.onGetImage(mLoadTask.key, mLoadTask.bitmap, mLoadTask.state);
|
||||
}
|
||||
}
|
||||
|
||||
private class LoadFromCacheTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
LoadTask loadTask;
|
||||
while (true) {
|
||||
synchronized (mLoadTasks) {
|
||||
if (mLoadTasks.isEmpty()) {
|
||||
try {
|
||||
mLoadTasks.wait();
|
||||
} catch (InterruptedException e) {}
|
||||
continue;
|
||||
}
|
||||
loadTask = mLoadTasks.pop();
|
||||
}
|
||||
|
||||
int[] state = new int[1];
|
||||
String key = loadTask.key;
|
||||
loadTask.bitmap = mImageCache.get(key);
|
||||
loadTask.state = state[0];
|
||||
|
||||
if (loadTask.bitmap != null)
|
||||
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
|
||||
else
|
||||
mImageDownloader.add(loadTask);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class ImageDownloader {
|
||||
private static final int MAX_DOWNLOAD_THREADS = 5;
|
||||
private final Stack<LoadTask> mDownloadTasks;
|
||||
private int mWorkingThreadNum = 0;
|
||||
|
||||
public ImageDownloader() {
|
||||
mDownloadTasks = new Stack<LoadTask>();
|
||||
}
|
||||
|
||||
public void add(LoadTask loadTask) {
|
||||
synchronized (mDownloadTasks) {
|
||||
mDownloadTasks.push(loadTask);
|
||||
if (mWorkingThreadNum < MAX_DOWNLOAD_THREADS) {
|
||||
new BgThread(new DownloadImageTask()).start();
|
||||
mWorkingThreadNum++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DownloadImageTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
LoadTask loadTask;
|
||||
HttpHelper httpHelper = new HttpHelper(mContext);
|
||||
while (true) {
|
||||
synchronized (mDownloadTasks) {
|
||||
if (mDownloadTasks.isEmpty()) {
|
||||
loadTask = null;
|
||||
mWorkingThreadNum--;
|
||||
break;
|
||||
}
|
||||
loadTask = mDownloadTasks.pop();
|
||||
}
|
||||
|
||||
// TODO use proxy to get image
|
||||
loadTask.bitmap = httpHelper.getImage(loadTask.url);
|
||||
if (loadTask.bitmap != null) {
|
||||
mImageCache.put(loadTask.key, loadTask.bitmap);
|
||||
loadTask.state = STATE_FROM_NETWORK;
|
||||
} else {
|
||||
loadTask.state = STATE_NONE;
|
||||
}
|
||||
|
||||
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface OnGetImageListener {
|
||||
/**
|
||||
* bmp is null for fail
|
||||
* @param key
|
||||
* @param bmp
|
||||
*/
|
||||
void onGetImage(String key, Bitmap bmp, int state);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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;
|
||||
|
||||
import android.content.SearchRecentSuggestionsProvider;
|
||||
|
||||
public class SimpleSuggestionProvider extends SearchRecentSuggestionsProvider {
|
||||
public final static String AUTHORITY = "com.hippo.ehviewer.SimpleSuggestionProvider";
|
||||
public final static int MODE = DATABASE_MODE_QUERIES;
|
||||
|
||||
public SimpleSuggestionProvider() {
|
||||
setupSuggestions(AUTHORITY, MODE);
|
||||
}
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Bundle;
|
||||
import android.text.util.Linkify;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
|
||||
import com.hippo.ehviewer.network.Network;
|
||||
import com.hippo.ehviewer.ui.AbsActivity;
|
||||
import com.hippo.ehviewer.ui.EnterPatternActivity;
|
||||
import com.hippo.ehviewer.ui.GalleryListActivity;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.SimpleImageView;
|
||||
import com.hippo.vector.VectorDrawable;
|
||||
|
||||
public class StartActivity extends AbsActivity {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = StartActivity.class.getSimpleName();
|
||||
|
||||
private static final int REQUEST_CODE_PATTERN = 0;
|
||||
|
||||
private static final int CHECK_WARING = 0;
|
||||
private static final int CHECK_ANALYTICS = 1;
|
||||
private static final int CHECK_NETWORK = 2;
|
||||
private static final int CHECK_CRASH = 3;
|
||||
|
||||
private static final String KEY_ALLOWED = "allowed";
|
||||
private static final String KEY_SET_ANALYTICS = "set_analyics";
|
||||
|
||||
private String lastCrash;
|
||||
private boolean isEnterPattern = false;
|
||||
private boolean isAnimationOver = false;
|
||||
private boolean isCheckOver = false;
|
||||
|
||||
private MaterialAlertDialog createWarningDialog() {
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dailog_waring_title)
|
||||
.setMessage(R.string.dailog_waring_plain)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
Config.setBoolean(KEY_ALLOWED, true);
|
||||
check(CHECK_ANALYTICS);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
finish();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createAllowAnalyicsDialog() {
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dailog_analyics_title)
|
||||
.setMessageAutoLink(Linkify.WEB_URLS)
|
||||
.setMessage(R.string.dailog_analyics_plain)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
Config.setAllowAnalyics(true);
|
||||
check(CHECK_NETWORK);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
Config.setAllowAnalyics(false);
|
||||
check(CHECK_NETWORK);
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createNetworkDialog(int state) {
|
||||
int mesgId;
|
||||
switch (state) {
|
||||
case Network.NETWORK_STATE_MOBILE:
|
||||
mesgId = R.string.dailog_network_mobile_title;
|
||||
break;
|
||||
case Network.NETWORK_STATE_NONE:
|
||||
default:
|
||||
mesgId = R.string.dailog_network_none_title;
|
||||
break;
|
||||
}
|
||||
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.warning).setMessage(mesgId)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
check(CHECK_CRASH);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
finish();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createSendCrashDialog() {
|
||||
View view = ViewUtils.inflateDialogView(R.layout.send_crash, false);
|
||||
final EditText et = (EditText) view.findViewById(R.id.description_of_user);
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dialog_send_crash_title)
|
||||
.setView(view, true)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
// A wait dialog
|
||||
new MaterialAlertDialog.Builder(StartActivity.this)
|
||||
.setCancelable(false)
|
||||
.setTitle(R.string.wait)
|
||||
.setMessage(R.string.dialog_wait_send_crash_msg)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setButtonListener(
|
||||
new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
checkOver();
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
ActivityHelper.sendEmail(StartActivity.this, "ehviewersu@gmail.com", "I found a bug in EhViewer !", lastCrash + "======== Description ========\n" + et.getText().toString());
|
||||
lastCrash = null;
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
lastCrash = null;
|
||||
checkOver();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
// Disable animate
|
||||
overridePendingTransition(0, 0);
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.start_activity);
|
||||
|
||||
TextView text = (TextView) findViewById(R.id.text);
|
||||
text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/GloriaHallelujah.ttf"));
|
||||
SimpleImageView image = (SimpleImageView) findViewById(R.id.image);
|
||||
image.setDrawable(VectorDrawable.create(this, R.drawable.sad_pandroid));
|
||||
|
||||
// Update secret image here
|
||||
int state = Network.getNetworkState(this);
|
||||
if (state == Network.NETWORK_STATE_WIFI) {
|
||||
Secret.updateSecretImage(this);
|
||||
}
|
||||
|
||||
AppHandler.getInstance().postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!StartActivity.this.isFinishing()) {
|
||||
if (isCheckOver && isEnterPattern)
|
||||
redirectTo();
|
||||
isAnimationOver = true;
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
check(CHECK_WARING);
|
||||
|
||||
// Enter Pattern
|
||||
String pattern = Config.getPatternProtection();
|
||||
if (LockPatternUtils.isPatternVaild(pattern)) {
|
||||
// Start activity to enter pattern
|
||||
Intent intent = new Intent(this, EnterPatternActivity.class);
|
||||
startActivityForResult(intent, REQUEST_CODE_PATTERN);
|
||||
} else {
|
||||
isEnterPattern = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
if (requestCode == REQUEST_CODE_PATTERN) {
|
||||
if (resultCode == RESULT_OK) {
|
||||
if (isAnimationOver && isCheckOver)
|
||||
redirectTo();
|
||||
isEnterPattern = true;
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Order is 1. check waring 2. check analyics 3. check network 4. check
|
||||
* crash 5. check external storage
|
||||
*
|
||||
* @param order
|
||||
*/
|
||||
private void check(int order) {
|
||||
switch (order) {
|
||||
case CHECK_WARING:
|
||||
if (!Config.getBoolean(KEY_ALLOWED, false)) {
|
||||
createWarningDialog().show();
|
||||
return;
|
||||
}
|
||||
case CHECK_ANALYTICS:
|
||||
if (!Config.getBoolean(KEY_SET_ANALYTICS, false)) {
|
||||
Config.setBoolean(KEY_SET_ANALYTICS, true);
|
||||
createAllowAnalyicsDialog().show();
|
||||
return;
|
||||
}
|
||||
case CHECK_NETWORK:
|
||||
int state = Network.getNetworkState(this);
|
||||
if (state != Network.NETWORK_STATE_WIFI) {
|
||||
createNetworkDialog(state).show();
|
||||
return;
|
||||
}
|
||||
case CHECK_CRASH:
|
||||
if ((lastCrash = Crash.getLastCrash()) != null) {
|
||||
createSendCrashDialog().show();
|
||||
return;
|
||||
}
|
||||
}
|
||||
checkOver();
|
||||
}
|
||||
|
||||
private void checkOver() {
|
||||
if (isAnimationOver && isEnterPattern)
|
||||
redirectTo();
|
||||
isCheckOver = true;
|
||||
}
|
||||
|
||||
private void redirectTo() {
|
||||
Intent intent = new Intent(this, GalleryListActivity.class);
|
||||
startActivity(intent);
|
||||
finish();
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.app;
|
||||
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.FileExplorerView;
|
||||
|
||||
public class DirSelectDialog extends MaterialAlertDialog {
|
||||
|
||||
private final FileExplorerView mFileExplorerView;
|
||||
|
||||
protected DirSelectDialog(Builder builder, FileExplorerView fileExplorerView) {
|
||||
super(builder);
|
||||
|
||||
mFileExplorerView = fileExplorerView;
|
||||
}
|
||||
|
||||
public static DirSelectDialog create(Builder builder, String path) {
|
||||
View view = ViewUtils.inflateDialogView(R.layout.dir_selection, builder.mDarkTheme);
|
||||
final FileExplorerView fileExplorerView = (FileExplorerView) view.findViewById(R.id.file_list);
|
||||
final TextView warningTextView = (TextView) view.findViewById(R.id.warning);
|
||||
final TextView pathTextView = (TextView) view.findViewById(R.id.path);
|
||||
|
||||
if (path != null)
|
||||
fileExplorerView.setPath(path);
|
||||
fileExplorerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
|
||||
fileExplorerView.onItemClick(parent, view, position, id);
|
||||
pathTextView.setText(fileExplorerView.getCurPath());
|
||||
if (fileExplorerView.canWrite())
|
||||
warningTextView.setVisibility(View.GONE);
|
||||
else
|
||||
warningTextView.setVisibility(View.VISIBLE);
|
||||
}
|
||||
});
|
||||
|
||||
pathTextView.setText(fileExplorerView.getCurPath());
|
||||
if (fileExplorerView.canWrite())
|
||||
warningTextView.setVisibility(View.GONE);
|
||||
else
|
||||
warningTextView.setVisibility(View.VISIBLE);
|
||||
|
||||
builder.setView(view, false,
|
||||
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Ui.dp2pix(360)));
|
||||
|
||||
return new DirSelectDialog(builder, fileExplorerView);
|
||||
}
|
||||
|
||||
public String getCurrentPath() {
|
||||
return mFileExplorerView.getCurPath();
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
mFileExplorerView.refresh();
|
||||
}
|
||||
|
||||
public boolean canWrite() {
|
||||
return mFileExplorerView.canWrite();
|
||||
}
|
||||
}
|
||||
@@ -1,504 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.app;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.view.ContextThemeWrapper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ListAdapter;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
|
||||
public class MaterialAlertDialog extends AlertDialog implements
|
||||
View.OnClickListener, AdapterView.OnItemClickListener {
|
||||
|
||||
public final static int ACTION = 0x1;
|
||||
public final static int POSITIVE = 0x2;
|
||||
public final static int NEGATIVE = 0x4;
|
||||
public final static int NEUTRAL = 0x8;
|
||||
|
||||
private final Context mContext;
|
||||
|
||||
private final Builder mBuilder;
|
||||
|
||||
private View mRootView;
|
||||
private TextView mTitle;
|
||||
private Button mActionButton;
|
||||
private Button mPositiveButton;
|
||||
private Button mNegativeButton;
|
||||
private Button mNeutralButton;
|
||||
|
||||
protected MaterialAlertDialog(Builder builder) {
|
||||
super(builder.mContext);
|
||||
mContext = builder.mContext;
|
||||
mBuilder = builder;
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
private void init() {
|
||||
LayoutInflater inflater = LayoutInflater.from(mContext);
|
||||
mRootView = inflater.inflate(R.layout.alert_dialog_material, null);
|
||||
|
||||
// Check in scroll view or not
|
||||
boolean inScrollView;
|
||||
if (mBuilder.mCustomView != null)
|
||||
inScrollView = mBuilder.mInScrollView;
|
||||
else if (mBuilder.mAdapter != null)
|
||||
inScrollView = false;
|
||||
else
|
||||
inScrollView = true;
|
||||
// Get widget
|
||||
LinearLayout topPanel;
|
||||
TextView message = null;
|
||||
ListView list = null;
|
||||
if (inScrollView) {
|
||||
mRootView.findViewById(R.id.top_panel_noscroll).setVisibility(
|
||||
View.GONE);
|
||||
mTitle = (TextView) mRootView.findViewById(R.id.title);
|
||||
topPanel = (LinearLayout) mRootView.findViewById(R.id.top_panel);
|
||||
message = (TextView) mRootView.findViewById(R.id.message);
|
||||
} else {
|
||||
mRootView.findViewById(R.id.scroll_view).setVisibility(View.GONE);
|
||||
mTitle = (TextView) mRootView.findViewById(R.id.title2);
|
||||
topPanel = (LinearLayout) mRootView
|
||||
.findViewById(R.id.top_panel_noscroll);
|
||||
list = (ListView) mRootView.findViewById(R.id.list);
|
||||
}
|
||||
// Title
|
||||
if (mBuilder.mTitle == null)
|
||||
mTitle.setVisibility(View.GONE);
|
||||
else
|
||||
mTitle.setText(mBuilder.mTitle);
|
||||
// Content
|
||||
if (mBuilder.mCustomView != null) {
|
||||
// CustomView
|
||||
if (message != null)
|
||||
message.setVisibility(View.GONE);
|
||||
if (list != null)
|
||||
list.setVisibility(View.GONE);
|
||||
LinearLayout.LayoutParams lp = mBuilder.mCustomLp;
|
||||
if (lp == null)
|
||||
lp = new LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT);
|
||||
mBuilder.mCustomView.setId(R.id.custom);
|
||||
topPanel.addView(mBuilder.mCustomView, lp);
|
||||
} else if (mBuilder.mAdapter != null) {
|
||||
// List
|
||||
if (message != null)
|
||||
message.setVisibility(View.GONE);
|
||||
list.setAdapter(mBuilder.mAdapter);
|
||||
list.setOnItemClickListener(this);
|
||||
if (mBuilder.mIsSingleChoice) {
|
||||
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
|
||||
if (mBuilder.mCheckedItem > -1) {
|
||||
list.setItemChecked(mBuilder.mCheckedItem, true);
|
||||
list.setSelection(mBuilder.mCheckedItem);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Message
|
||||
if (list != null)
|
||||
list.setVisibility(View.GONE);
|
||||
if (mBuilder.mAutoLinkMask != -1)
|
||||
message.setAutoLinkMask(mBuilder.mAutoLinkMask);
|
||||
message.setText(mBuilder.mMessage);
|
||||
}
|
||||
|
||||
// Buttons
|
||||
View buttonPanel = mRootView.findViewById(R.id.button_panel);
|
||||
View nonActionPanel = mRootView.findViewById(R.id.non_action_panel);
|
||||
mActionButton = (Button) mRootView.findViewById(R.id.button_action);
|
||||
mPositiveButton = (Button) mRootView.findViewById(R.id.button_positive);
|
||||
mNegativeButton = (Button) mRootView.findViewById(R.id.button_negative);
|
||||
mNeutralButton = (Button) mRootView.findViewById(R.id.button_neutral);
|
||||
boolean hasAction = mBuilder.mActionButtonText != null;
|
||||
boolean hasNonAction = mBuilder.mPositiveButtonText != null
|
||||
|| mBuilder.mNegativeButtonText != null
|
||||
|| mBuilder.mNeutralButtonText != null;
|
||||
boolean hasButton = hasAction || hasNonAction;
|
||||
if (hasButton) {
|
||||
if (hasAction) {
|
||||
mActionButton.setText(mBuilder.mActionButtonText);
|
||||
mActionButton.setOnClickListener(this);
|
||||
} else {
|
||||
mActionButton.setVisibility(View.GONE);
|
||||
}
|
||||
if (hasNonAction) {
|
||||
// Positive
|
||||
if (mBuilder.mPositiveButtonText != null) {
|
||||
mPositiveButton.setText(mBuilder.mPositiveButtonText);
|
||||
mPositiveButton.setOnClickListener(this);
|
||||
} else {
|
||||
mPositiveButton.setVisibility(View.GONE);
|
||||
}
|
||||
// Negative
|
||||
if (mBuilder.mNegativeButtonText != null) {
|
||||
mNegativeButton.setText(mBuilder.mNegativeButtonText);
|
||||
mNegativeButton.setOnClickListener(this);
|
||||
} else {
|
||||
mNegativeButton.setVisibility(View.GONE);
|
||||
}
|
||||
// Neutral
|
||||
if (mBuilder.mNeutralButtonText != null) {
|
||||
mNeutralButton.setText(mBuilder.mNeutralButtonText);
|
||||
mNeutralButton.setOnClickListener(this);
|
||||
} else {
|
||||
mNeutralButton.setVisibility(View.GONE);
|
||||
}
|
||||
} else {
|
||||
nonActionPanel.setVisibility(View.GONE);
|
||||
}
|
||||
} else {
|
||||
buttonPanel.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
setView(mRootView);
|
||||
|
||||
setCancelable(mBuilder.mCancelable);
|
||||
if (mBuilder.mOnCancelListener != null)
|
||||
setOnCancelListener(mBuilder.mOnCancelListener);
|
||||
if (mBuilder.mOnDismissListener != null)
|
||||
setOnDismissListener(mBuilder.mOnDismissListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTitle(CharSequence title) {
|
||||
mTitle.setText(title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTitle(int resId) {
|
||||
setTitle(getContext().getString(resId));
|
||||
}
|
||||
|
||||
public void setView(View view, boolean inScrollView) {
|
||||
setView(view, inScrollView, new LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT));
|
||||
}
|
||||
|
||||
public void setView(View view, boolean inScrollView,
|
||||
LinearLayout.LayoutParams lp) {
|
||||
mRootView.findViewById(inScrollView ? R.id.top_panel_noscroll : R.id.scroll_view).setVisibility(View.GONE);
|
||||
mRootView.findViewById(inScrollView ? R.id.scroll_view : R.id.top_panel_noscroll).setVisibility(View.VISIBLE);
|
||||
mRootView.findViewById(R.id.message).setVisibility(View.GONE);
|
||||
mRootView.findViewById(R.id.list).setVisibility(View.GONE);
|
||||
LinearLayout topPanel = (LinearLayout) mRootView.findViewById(inScrollView ? R.id.top_panel : R.id.top_panel_noscroll);
|
||||
topPanel.addView(view, lp);
|
||||
// Title
|
||||
TextView oldTitle = mTitle;
|
||||
mTitle = (TextView) mRootView.findViewById(inScrollView ? R.id.title : R.id.title2);
|
||||
if (mTitle != oldTitle && oldTitle != null)
|
||||
mTitle.setText(oldTitle.getText());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
boolean close = true;
|
||||
|
||||
if (mBuilder.mButtonListener != null) {
|
||||
if (v == mActionButton)
|
||||
close = mBuilder.mButtonListener.onClick(this, ACTION);
|
||||
else if (v == mPositiveButton)
|
||||
close = mBuilder.mButtonListener.onClick(this, POSITIVE);
|
||||
else if (v == mNegativeButton)
|
||||
close = mBuilder.mButtonListener.onClick(this, NEGATIVE);
|
||||
else if (v == mNeutralButton)
|
||||
close = mBuilder.mButtonListener.onClick(this, NEUTRAL);
|
||||
}
|
||||
|
||||
if (close)
|
||||
dismiss();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position,
|
||||
long id) {
|
||||
|
||||
boolean close = false;
|
||||
|
||||
if (mBuilder.mOnClickListener != null)
|
||||
close = mBuilder.mOnClickListener.onClick(this, position);
|
||||
|
||||
if (close)
|
||||
dismiss();
|
||||
}
|
||||
|
||||
public static interface OnClickListener {
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which);
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
|
||||
protected Context mContext;
|
||||
|
||||
protected boolean mDarkTheme = false;
|
||||
protected CharSequence mTitle;
|
||||
protected CharSequence mMessage;
|
||||
protected CharSequence mActionButtonText;
|
||||
protected CharSequence mPositiveButtonText;
|
||||
protected CharSequence mNegativeButtonText;
|
||||
protected CharSequence mNeutralButtonText;
|
||||
protected OnClickListener mButtonListener;
|
||||
protected View mCustomView;
|
||||
protected LinearLayout.LayoutParams mCustomLp;
|
||||
protected boolean mInScrollView = true;
|
||||
protected boolean mCancelable = true;
|
||||
protected int mAutoLinkMask = -1;
|
||||
|
||||
protected OnCancelListener mOnCancelListener;
|
||||
|
||||
protected ListAdapter mAdapter;
|
||||
protected OnClickListener mOnClickListener;
|
||||
protected int mCheckedItem;
|
||||
protected boolean mIsSingleChoice;
|
||||
|
||||
protected DialogInterface.OnDismissListener mOnDismissListener;
|
||||
|
||||
public Builder(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
public Builder setDrakTheme(boolean darkTheme) {
|
||||
mDarkTheme = darkTheme;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTitle(CharSequence title) {
|
||||
mTitle = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTitle(int resId) {
|
||||
return setTitle(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setMessage(CharSequence message) {
|
||||
mMessage = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setMessage(int resId) {
|
||||
return setMessage(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setActionButton(CharSequence text) {
|
||||
mActionButtonText = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setActionButton(int resId) {
|
||||
return setActionButton(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setPositiveButton(CharSequence text) {
|
||||
mPositiveButtonText = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setPositiveButton(int resId) {
|
||||
return setPositiveButton(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setNegativeButton(CharSequence text) {
|
||||
mNegativeButtonText = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setNegativeButton(int resId) {
|
||||
return setNegativeButton(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setNeutralButton(CharSequence text) {
|
||||
mNeutralButtonText = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setNeutralButton(int resId) {
|
||||
return setNeutralButton(mContext.getString(resId));
|
||||
}
|
||||
|
||||
public Builder setDefaultButton(int b) {
|
||||
if ((b & POSITIVE) == POSITIVE)
|
||||
mPositiveButtonText = mContext.getString(android.R.string.ok);
|
||||
if ((b & NEGATIVE) == NEGATIVE)
|
||||
mNegativeButtonText = mContext.getString(android.R.string.cancel);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setButtonListener(OnClickListener l) {
|
||||
mButtonListener = l;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom view id will be R.id.custom
|
||||
*
|
||||
* @param view
|
||||
* @param inScrollView
|
||||
* @return
|
||||
*/
|
||||
public Builder setView(View view, boolean inScrollView) {
|
||||
mCustomView = view;
|
||||
mInScrollView = inScrollView;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom view id will be R.id.custom
|
||||
*
|
||||
* @param view
|
||||
* @param inScrollView
|
||||
* @param lp
|
||||
* @return
|
||||
*/
|
||||
public Builder setView(View view, boolean inScrollView,
|
||||
LinearLayout.LayoutParams lp) {
|
||||
mCustomView = view;
|
||||
mInScrollView = inScrollView;
|
||||
mCustomLp = lp;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setView(int resId, boolean inScrollView, ViewHolder vh) {
|
||||
mCustomView = ViewUtils.inflateDialogView(resId, mDarkTheme);
|
||||
mInScrollView = inScrollView;
|
||||
if (vh != null)
|
||||
vh.setView(mCustomView);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setCancelable(boolean cancelable) {
|
||||
mCancelable = cancelable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
|
||||
mOnCancelListener = onCancelListener;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setMessageAutoLink(int mask) {
|
||||
mAutoLinkMask = mask;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setItems(int itemsId, final OnClickListener listener) {
|
||||
mAdapter = new ArrayAdapter<CharSequence>(
|
||||
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
|
||||
R.layout.select_dialog_item, android.R.id.text1, mContext
|
||||
.getResources().getTextArray(itemsId));
|
||||
mOnClickListener = listener;
|
||||
mIsSingleChoice = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setItems(CharSequence[] items,
|
||||
final OnClickListener listener) {
|
||||
mAdapter = new ArrayAdapter<CharSequence>(
|
||||
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
|
||||
R.layout.select_dialog_item, android.R.id.text1, items);
|
||||
mOnClickListener = listener;
|
||||
mIsSingleChoice = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setAdapter(final ListAdapter adapter,
|
||||
final OnClickListener listener) {
|
||||
mAdapter = adapter;
|
||||
mOnClickListener = listener;
|
||||
mIsSingleChoice = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
|
||||
final OnClickListener listener) {
|
||||
mAdapter = new ArrayAdapter<CharSequence>(
|
||||
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
|
||||
R.layout.select_dialog_singlechoice, android.R.id.text1,
|
||||
mContext.getResources().getTextArray(itemsId));
|
||||
mOnClickListener = listener;
|
||||
mCheckedItem = checkedItem;
|
||||
mIsSingleChoice = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setSingleChoiceItems(CharSequence[] items,
|
||||
int checkedItem, final OnClickListener listener) {
|
||||
mAdapter = new ArrayAdapter<CharSequence>(
|
||||
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
|
||||
R.layout.select_dialog_singlechoice, android.R.id.text1,
|
||||
items);
|
||||
mOnClickListener = listener;
|
||||
mCheckedItem = checkedItem;
|
||||
mIsSingleChoice = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setSingleChoiceItems(ListAdapter adapter,
|
||||
int checkedItem, final OnClickListener listener) {
|
||||
mAdapter = adapter;
|
||||
mOnClickListener = listener;
|
||||
mCheckedItem = checkedItem;
|
||||
mIsSingleChoice = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setOnDismissListener(DialogInterface.OnDismissListener l) {
|
||||
mOnDismissListener = l;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MaterialAlertDialog create() {
|
||||
mContext = new ContextThemeWrapper(mContext, mDarkTheme ?
|
||||
R.style.AppTheme_Dark_Dialog : R.style.AppTheme_Dialog);
|
||||
return new MaterialAlertDialog(this);
|
||||
}
|
||||
|
||||
public MaterialAlertDialog show() {
|
||||
MaterialAlertDialog dialog = create();
|
||||
dialog.show();
|
||||
return dialog;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ViewHolder {
|
||||
private View mView;
|
||||
|
||||
private void setView(View v) {
|
||||
mView = v;
|
||||
}
|
||||
|
||||
public View getView() {
|
||||
return mView;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,501 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.cache;
|
||||
|
||||
import android.os.Looper;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.util.LruCache;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public abstract class AnyCache<V> {
|
||||
|
||||
private static final String TAG = AnyCache.class.getSimpleName();
|
||||
|
||||
private LruCache<String, V> mMemoryCache;
|
||||
private @Nullable DiskCache<V> mDiskCache;
|
||||
|
||||
private final boolean mHasMemoryCache;
|
||||
private final boolean mHasDiskCache;
|
||||
|
||||
/**
|
||||
* Used to temporarily pause the disk cache while scrolling
|
||||
*/
|
||||
public boolean mPauseDiskAccess = false;
|
||||
private final Object mPauseLock = new Object();
|
||||
|
||||
private final Object mDiskCacheLock = new Object();
|
||||
|
||||
public AnyCache(AnyCacheParams params) {
|
||||
params.isValid();
|
||||
mHasMemoryCache = params.hasMemoryCache;
|
||||
mHasDiskCache = params.hasDiskCache;
|
||||
|
||||
if (mHasMemoryCache) {
|
||||
initMemoryCache(params.memoryCacheMaxSize);
|
||||
}
|
||||
|
||||
if (mHasDiskCache) {
|
||||
initDiskCache(params.diskCacheDir, params.diskCacheMaxSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void initMemoryCache(int maxSize) {
|
||||
mMemoryCache = new MemoryCahce<>(maxSize, this);
|
||||
}
|
||||
|
||||
private void initDiskCache(File cacheDir, int maxSize) {
|
||||
// Set up disk cache
|
||||
synchronized (mDiskCacheLock) {
|
||||
try {
|
||||
mDiskCache = new DiskCache<>(cacheDir, maxSize, this);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Can't create disk cache", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected abstract int sizeOf(String key, V value);
|
||||
|
||||
protected abstract V read(InputStream is);
|
||||
|
||||
protected abstract boolean write(OutputStream os, V value);
|
||||
|
||||
/**
|
||||
* Check if have memory cache
|
||||
*
|
||||
* @return true if have memory cache
|
||||
*/
|
||||
public boolean hasMemoryCache() {
|
||||
return mHasMemoryCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if have disk cache
|
||||
*
|
||||
* @return true if have disk cache
|
||||
*/
|
||||
public boolean hasDiskCache() {
|
||||
return mHasDiskCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get, null for miss or no memory cache
|
||||
*/
|
||||
public V getFromMemory(String key) {
|
||||
if (mHasMemoryCache) {
|
||||
return mMemoryCache.get(key);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get, null for miss or no memory cache or get error
|
||||
*/
|
||||
public V getFromDisk(String key) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
return mDiskCache.get(diskKey);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache and disk cache. If miss in memory cache and
|
||||
* get in disk cache, it will put value from disk cache to memory cache.
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get
|
||||
*/
|
||||
public V get(String key) {
|
||||
V value = getFromMemory(key);
|
||||
|
||||
if (value != null) {
|
||||
// Get it in memory cache
|
||||
return value;
|
||||
}
|
||||
|
||||
value = getFromDisk(key);
|
||||
|
||||
if (value != null) {
|
||||
// Get it in disk cache
|
||||
putToMemory(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to memory cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return false if no memory cache
|
||||
*/
|
||||
public boolean putToMemory(String key, V value) {
|
||||
if (mHasMemoryCache) {
|
||||
mMemoryCache.put(key, value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to disk cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return false if no disk cache or get error
|
||||
*/
|
||||
public boolean putToDisk(String key, V value) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
mDiskCache.put(diskKey, value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to memory cache and disk cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void put(String key, V value) {
|
||||
putToMemory(key, value);
|
||||
putToDisk(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to temporarily pause the disk cache while the user is scrolling to
|
||||
* improve scrolling.
|
||||
*
|
||||
* @param pause True to temporarily pause the disk cache, false otherwise.
|
||||
*/
|
||||
public void setPauseDiskCache(final boolean pause) {
|
||||
synchronized (mPauseLock) {
|
||||
if (mPauseDiskAccess != pause) {
|
||||
mPauseDiskAccess = pause;
|
||||
if (!pause) {
|
||||
mPauseLock.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void waitUntilUnpaused() {
|
||||
synchronized (mPauseLock) {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) {
|
||||
while (mPauseDiskAccess) {
|
||||
try {
|
||||
mPauseLock.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// ignored, we'll start waiting again
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts all of the items from the memory cache
|
||||
*/
|
||||
public void clearMemory() {
|
||||
if (mHasMemoryCache) {
|
||||
mMemoryCache.evictAll();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear disk cache
|
||||
*/
|
||||
public void clearDisk() {
|
||||
if (mHasDiskCache) {
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null && !mDiskCache.isClosed()) {
|
||||
try {
|
||||
mDiskCache.delete();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "AnyCache clearCache", e);
|
||||
}
|
||||
File cacheDir = mDiskCache.getCacheDir();
|
||||
int maxSize = mDiskCache.getMaxSize();
|
||||
mDiskCache = null;
|
||||
initDiskCache(cacheDir, maxSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
if (mHasDiskCache) {
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
try {
|
||||
mDiskCache.flush();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "AnyCache flush", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts all of the items from the memory cache and lets the system know
|
||||
* now would be a good time to garbage collect
|
||||
*/
|
||||
public void clear() {
|
||||
clearMemory();
|
||||
clearDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* A hashing method that changes a string (like a URL) into a hash suitable
|
||||
* for using as a disk filename.
|
||||
*
|
||||
* @param key The key used to store the file
|
||||
*/
|
||||
private static String hashKeyForDisk(final String key) {
|
||||
String cacheKey;
|
||||
try {
|
||||
final MessageDigest digest = MessageDigest.getInstance("MD5");
|
||||
digest.update(key.getBytes());
|
||||
cacheKey = bytesToHexString(digest.digest());
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
cacheKey = String.valueOf(key.hashCode());
|
||||
}
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* http://stackoverflow.com/questions/332079
|
||||
*
|
||||
* @param bytes The bytes to convert.
|
||||
* @return A {@link String} converted from the bytes of a hashable key used
|
||||
* to store a filename on the disk, to hex digits.
|
||||
*/
|
||||
private static String bytesToHexString(final byte[] bytes) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (final byte b : bytes) {
|
||||
final String hex = Integer.toHexString(0xFF & b);
|
||||
if (hex.length() == 1) {
|
||||
builder.append('0');
|
||||
}
|
||||
builder.append(hex);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A holder class that contains cache parameters.
|
||||
*/
|
||||
public static class AnyCacheParams {
|
||||
|
||||
public boolean hasMemoryCache = false;
|
||||
public int memoryCacheMaxSize = 0;
|
||||
public boolean hasDiskCache = false;
|
||||
public File diskCacheDir = null;
|
||||
public int diskCacheMaxSize = 0;
|
||||
|
||||
/**
|
||||
* Check AnyCacheParams is valid
|
||||
*
|
||||
* @throws IllegalStateException
|
||||
*/
|
||||
public void isValid() throws IllegalStateException {
|
||||
if (!hasMemoryCache && !hasDiskCache) {
|
||||
throw new IllegalStateException("No memory cache and no disk cache. What can I do for you?");
|
||||
}
|
||||
|
||||
if (hasMemoryCache && memoryCacheMaxSize <= 0) {
|
||||
throw new IllegalStateException("Memory cache max size must be bigger than 0.");
|
||||
}
|
||||
|
||||
if (hasDiskCache) {
|
||||
if (diskCacheDir == null) {
|
||||
throw new IllegalStateException("Disk cache dir can't be null.");
|
||||
}
|
||||
if (diskCacheMaxSize <= 0) {
|
||||
throw new IllegalStateException("Disk cache max size must be bigger than 0.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MemoryCahce<E> extends LruCache<String, E> {
|
||||
|
||||
public AnyCache<E> mParent;
|
||||
|
||||
public MemoryCahce(int maxSize, AnyCache<E> parent) {
|
||||
super(maxSize);
|
||||
mParent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int sizeOf(String key, E value) {
|
||||
return mParent.sizeOf(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DiskCache<E> {
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
private DiskLruCache mDiskLruCache;
|
||||
private AnyCache<E> mParent;
|
||||
|
||||
private File mCacheDir;
|
||||
private int mMaxSize;
|
||||
|
||||
public DiskCache(File cacheDir, int size, AnyCache<E> parent) throws IOException {
|
||||
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
|
||||
mParent = parent;
|
||||
|
||||
mCacheDir = cacheDir;
|
||||
mMaxSize = size;
|
||||
}
|
||||
|
||||
public File getCacheDir() {
|
||||
return mCacheDir;
|
||||
}
|
||||
|
||||
public int getMaxSize() {
|
||||
return mMaxSize;
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return mDiskLruCache.isClosed();
|
||||
}
|
||||
|
||||
public void delete() throws IOException {
|
||||
mDiskLruCache.delete();
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
mDiskLruCache.flush();
|
||||
}
|
||||
|
||||
public E get(String key) {
|
||||
DiskLruCache.Snapshot snapshot = null;
|
||||
try {
|
||||
snapshot = mDiskLruCache.get(key);
|
||||
if ( snapshot == null ) {
|
||||
// Miss
|
||||
return null;
|
||||
}
|
||||
|
||||
final InputStream in = snapshot.getInputStream(0);
|
||||
if (in != null) {
|
||||
final BufferedInputStream buffIn =
|
||||
new BufferedInputStream(in, IO_BUFFER_SIZE);
|
||||
return mParent.read(buffIn);
|
||||
} else {
|
||||
// Can't get InputStream
|
||||
return null;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
Util.closeQuietly(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean put(String key, E value) {
|
||||
DiskLruCache.Editor editor = null;
|
||||
OutputStream os = null;
|
||||
boolean completeEdit = false;
|
||||
try {
|
||||
editor = mDiskLruCache.edit(key);
|
||||
if (editor == null) {
|
||||
// The editor is in progress
|
||||
return false;
|
||||
}
|
||||
|
||||
os = editor.newOutputStream(0);
|
||||
if (os != null) {
|
||||
final BufferedOutputStream buffOut =
|
||||
new BufferedOutputStream(os, IO_BUFFER_SIZE);
|
||||
boolean result = mParent.write(buffOut, value);
|
||||
completeEdit = true;
|
||||
editor.commit();
|
||||
return result;
|
||||
} else {
|
||||
// Can't get OutputStream
|
||||
completeEdit = true;
|
||||
editor.abort();
|
||||
return false;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Util.closeQuietly(os);
|
||||
try {
|
||||
if (!completeEdit && editor != null) {
|
||||
editor.abort();
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,943 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2011 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.cache;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.Closeable;
|
||||
import java.io.EOFException;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A cache that uses a bounded amount of space on a filesystem. Each cache
|
||||
* entry has a string key and a fixed number of values. Each key must match
|
||||
* the regex <strong>[a-z0-9_-]{1,120}</strong>. Values are byte sequences,
|
||||
* accessible as streams or files. Each value must be between {@code 0} and
|
||||
* {@code Integer.MAX_VALUE} bytes in length.
|
||||
*
|
||||
* <p>The cache stores its data in a directory on the filesystem. This
|
||||
* directory must be exclusive to the cache; the cache may delete or overwrite
|
||||
* files from its directory. It is an error for multiple processes to use the
|
||||
* same cache directory at the same time.
|
||||
*
|
||||
* <p>This cache limits the number of bytes that it will store on the
|
||||
* filesystem. When the number of stored bytes exceeds the limit, the cache will
|
||||
* remove entries in the background until the limit is satisfied. The limit is
|
||||
* not strict: the cache may temporarily exceed it while waiting for files to be
|
||||
* deleted. The limit does not include filesystem overhead or the cache
|
||||
* journal so space-sensitive applications should set a conservative limit.
|
||||
*
|
||||
* <p>Clients call {@link #edit} to create or update the values of an entry. An
|
||||
* entry may have only one editor at one time; if a value is not available to be
|
||||
* edited then {@link #edit} will return null.
|
||||
* <ul>
|
||||
* <li>When an entry is being <strong>created</strong> it is necessary to
|
||||
* supply a full set of values; the empty value should be used as a
|
||||
* placeholder if necessary.
|
||||
* <li>When an entry is being <strong>edited</strong>, it is not necessary
|
||||
* to supply data for every value; values default to their previous
|
||||
* value.
|
||||
* </ul>
|
||||
* Every {@link #edit} call must be matched by a call to {@link Editor#commit}
|
||||
* or {@link Editor#abort}. Committing is atomic: a read observes the full set
|
||||
* of values as they were before or after the commit, but never a mix of values.
|
||||
*
|
||||
* <p>Clients call {@link #get} to read a snapshot of an entry. The read will
|
||||
* observe the value at the time that {@link #get} was called. Updates and
|
||||
* removals after the call do not impact ongoing reads.
|
||||
*
|
||||
* <p>This class is tolerant of some I/O errors. If files are missing from the
|
||||
* filesystem, the corresponding entries will be dropped from the cache. If
|
||||
* an error occurs while writing a cache value, the edit will fail silently.
|
||||
* Callers should handle other problems by catching {@code IOException} and
|
||||
* responding appropriately.
|
||||
*/
|
||||
public final class DiskLruCache implements Closeable {
|
||||
static final String JOURNAL_FILE = "journal";
|
||||
static final String JOURNAL_FILE_TEMP = "journal.tmp";
|
||||
static final String JOURNAL_FILE_BACKUP = "journal.bkp";
|
||||
static final String MAGIC = "libcore.io.DiskLruCache";
|
||||
static final String VERSION_1 = "1";
|
||||
static final long ANY_SEQUENCE_NUMBER = -1;
|
||||
static final String STRING_KEY_PATTERN = "[a-z0-9_-]{1,120}";
|
||||
static final Pattern LEGAL_KEY_PATTERN = Pattern.compile(STRING_KEY_PATTERN);
|
||||
private static final String CLEAN = "CLEAN";
|
||||
private static final String DIRTY = "DIRTY";
|
||||
private static final String REMOVE = "REMOVE";
|
||||
private static final String READ = "READ";
|
||||
|
||||
/*
|
||||
* This cache uses a journal file named "journal". A typical journal file
|
||||
* looks like this:
|
||||
* libcore.io.DiskLruCache
|
||||
* 1
|
||||
* 100
|
||||
* 2
|
||||
*
|
||||
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
|
||||
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
|
||||
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
|
||||
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
|
||||
* DIRTY 1ab96a171faeeee38496d8b330771a7a
|
||||
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
|
||||
* READ 335c4c6028171cfddfbaae1a9c313c52
|
||||
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
|
||||
*
|
||||
* The first five lines of the journal form its header. They are the
|
||||
* constant string "libcore.io.DiskLruCache", the disk cache's version,
|
||||
* the application's version, the value count, and a blank line.
|
||||
*
|
||||
* Each of the subsequent lines in the file is a record of the state of a
|
||||
* cache entry. Each line contains space-separated values: a state, a key,
|
||||
* and optional state-specific values.
|
||||
* o DIRTY lines track that an entry is actively being created or updated.
|
||||
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
|
||||
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
|
||||
* temporary files may need to be deleted.
|
||||
* o CLEAN lines track a cache entry that has been successfully published
|
||||
* and may be read. A publish line is followed by the lengths of each of
|
||||
* its values.
|
||||
* o READ lines track accesses for LRU.
|
||||
* o REMOVE lines track entries that have been deleted.
|
||||
*
|
||||
* The journal file is appended to as cache operations occur. The journal may
|
||||
* occasionally be compacted by dropping redundant lines. A temporary file named
|
||||
* "journal.tmp" will be used during compaction; that file should be deleted if
|
||||
* it exists when the cache is opened.
|
||||
*/
|
||||
|
||||
private final File directory;
|
||||
private final File journalFile;
|
||||
private final File journalFileTmp;
|
||||
private final File journalFileBackup;
|
||||
private final int appVersion;
|
||||
private long maxSize;
|
||||
private final int valueCount;
|
||||
private long size = 0;
|
||||
private Writer journalWriter;
|
||||
private final LinkedHashMap<String, Entry> lruEntries =
|
||||
new LinkedHashMap<String, Entry>(0, 0.75f, true);
|
||||
private int redundantOpCount;
|
||||
|
||||
/**
|
||||
* To differentiate between old and current snapshots, each entry is given
|
||||
* a sequence number each time an edit is committed. A snapshot is stale if
|
||||
* its sequence number is not equal to its entry's sequence number.
|
||||
*/
|
||||
private long nextSequenceNumber = 0;
|
||||
|
||||
/** This cache uses a single background thread to evict entries. */
|
||||
final ThreadPoolExecutor executorService =
|
||||
new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
|
||||
private final Callable<Void> cleanupCallable = new Callable<Void>() {
|
||||
public Void call() throws Exception {
|
||||
synchronized (DiskLruCache.this) {
|
||||
if (journalWriter == null) {
|
||||
return null; // Closed.
|
||||
}
|
||||
trimToSize();
|
||||
if (journalRebuildRequired()) {
|
||||
rebuildJournal();
|
||||
redundantOpCount = 0;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
|
||||
this.directory = directory;
|
||||
this.appVersion = appVersion;
|
||||
this.journalFile = new File(directory, JOURNAL_FILE);
|
||||
this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP);
|
||||
this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP);
|
||||
this.valueCount = valueCount;
|
||||
this.maxSize = maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the cache in {@code directory}, creating a cache if none exists
|
||||
* there.
|
||||
*
|
||||
* @param directory a writable directory
|
||||
* @param valueCount the number of values per cache entry. Must be positive.
|
||||
* @param maxSize the maximum number of bytes this cache should use to store
|
||||
* @throws IOException if reading or writing the cache directory fails
|
||||
*/
|
||||
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
|
||||
throws IOException {
|
||||
if (maxSize <= 0) {
|
||||
throw new IllegalArgumentException("maxSize <= 0");
|
||||
}
|
||||
if (valueCount <= 0) {
|
||||
throw new IllegalArgumentException("valueCount <= 0");
|
||||
}
|
||||
|
||||
// If a bkp file exists, use it instead.
|
||||
File backupFile = new File(directory, JOURNAL_FILE_BACKUP);
|
||||
if (backupFile.exists()) {
|
||||
File journalFile = new File(directory, JOURNAL_FILE);
|
||||
// If journal file also exists just delete backup file.
|
||||
if (journalFile.exists()) {
|
||||
backupFile.delete();
|
||||
} else {
|
||||
renameTo(backupFile, journalFile, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer to pick up where we left off.
|
||||
DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
|
||||
if (cache.journalFile.exists()) {
|
||||
try {
|
||||
cache.readJournal();
|
||||
cache.processJournal();
|
||||
return cache;
|
||||
} catch (IOException journalIsCorrupt) {
|
||||
System.out
|
||||
.println("DiskLruCache "
|
||||
+ directory
|
||||
+ " is corrupt: "
|
||||
+ journalIsCorrupt.getMessage()
|
||||
+ ", removing");
|
||||
cache.delete();
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new empty cache.
|
||||
directory.mkdirs();
|
||||
cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
|
||||
cache.rebuildJournal();
|
||||
return cache;
|
||||
}
|
||||
|
||||
private void readJournal() throws IOException {
|
||||
StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
|
||||
try {
|
||||
String magic = reader.readLine();
|
||||
String version = reader.readLine();
|
||||
String appVersionString = reader.readLine();
|
||||
String valueCountString = reader.readLine();
|
||||
String blank = reader.readLine();
|
||||
if (!MAGIC.equals(magic)
|
||||
|| !VERSION_1.equals(version)
|
||||
|| !Integer.toString(appVersion).equals(appVersionString)
|
||||
|| !Integer.toString(valueCount).equals(valueCountString)
|
||||
|| !"".equals(blank)) {
|
||||
throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
|
||||
+ valueCountString + ", " + blank + "]");
|
||||
}
|
||||
|
||||
int lineCount = 0;
|
||||
while (true) {
|
||||
try {
|
||||
readJournalLine(reader.readLine());
|
||||
lineCount++;
|
||||
} catch (EOFException endOfJournal) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
redundantOpCount = lineCount - lruEntries.size();
|
||||
|
||||
// If we ended on a truncated line, rebuild the journal before appending to it.
|
||||
if (reader.hasUnterminatedLine()) {
|
||||
rebuildJournal();
|
||||
} else {
|
||||
journalWriter = new BufferedWriter(new OutputStreamWriter(
|
||||
new FileOutputStream(journalFile, true), Util.US_ASCII));
|
||||
}
|
||||
} finally {
|
||||
Util.closeQuietly(reader);
|
||||
}
|
||||
}
|
||||
|
||||
private void readJournalLine(String line) throws IOException {
|
||||
int firstSpace = line.indexOf(' ');
|
||||
if (firstSpace == -1) {
|
||||
throw new IOException("unexpected journal line: " + line);
|
||||
}
|
||||
|
||||
int keyBegin = firstSpace + 1;
|
||||
int secondSpace = line.indexOf(' ', keyBegin);
|
||||
final String key;
|
||||
if (secondSpace == -1) {
|
||||
key = line.substring(keyBegin);
|
||||
if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) {
|
||||
lruEntries.remove(key);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
key = line.substring(keyBegin, secondSpace);
|
||||
}
|
||||
|
||||
Entry entry = lruEntries.get(key);
|
||||
if (entry == null) {
|
||||
entry = new Entry(key);
|
||||
lruEntries.put(key, entry);
|
||||
}
|
||||
|
||||
if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) {
|
||||
String[] parts = line.substring(secondSpace + 1).split(" ");
|
||||
entry.readable = true;
|
||||
entry.currentEditor = null;
|
||||
entry.setLengths(parts);
|
||||
} else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) {
|
||||
entry.currentEditor = new Editor(entry);
|
||||
} else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) {
|
||||
// This work was already done by calling lruEntries.get().
|
||||
} else {
|
||||
throw new IOException("unexpected journal line: " + line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the initial size and collects garbage as a part of opening the
|
||||
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
|
||||
*/
|
||||
private void processJournal() throws IOException {
|
||||
deleteIfExists(journalFileTmp);
|
||||
for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
|
||||
Entry entry = i.next();
|
||||
if (entry.currentEditor == null) {
|
||||
for (int t = 0; t < valueCount; t++) {
|
||||
size += entry.lengths[t];
|
||||
}
|
||||
} else {
|
||||
entry.currentEditor = null;
|
||||
for (int t = 0; t < valueCount; t++) {
|
||||
deleteIfExists(entry.getCleanFile(t));
|
||||
deleteIfExists(entry.getDirtyFile(t));
|
||||
}
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new journal that omits redundant information. This replaces the
|
||||
* current journal if it exists.
|
||||
*/
|
||||
private synchronized void rebuildJournal() throws IOException {
|
||||
if (journalWriter != null) {
|
||||
journalWriter.close();
|
||||
}
|
||||
|
||||
Writer writer = new BufferedWriter(
|
||||
new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
|
||||
try {
|
||||
writer.write(MAGIC);
|
||||
writer.write("\n");
|
||||
writer.write(VERSION_1);
|
||||
writer.write("\n");
|
||||
writer.write(Integer.toString(appVersion));
|
||||
writer.write("\n");
|
||||
writer.write(Integer.toString(valueCount));
|
||||
writer.write("\n");
|
||||
writer.write("\n");
|
||||
|
||||
for (Entry entry : lruEntries.values()) {
|
||||
if (entry.currentEditor != null) {
|
||||
writer.write(DIRTY + ' ' + entry.key + '\n');
|
||||
} else {
|
||||
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
writer.close();
|
||||
}
|
||||
|
||||
if (journalFile.exists()) {
|
||||
renameTo(journalFile, journalFileBackup, true);
|
||||
}
|
||||
renameTo(journalFileTmp, journalFile, false);
|
||||
journalFileBackup.delete();
|
||||
|
||||
journalWriter = new BufferedWriter(
|
||||
new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
|
||||
}
|
||||
|
||||
private static void deleteIfExists(File file) throws IOException {
|
||||
if (file.exists() && !file.delete()) {
|
||||
throw new IOException();
|
||||
}
|
||||
}
|
||||
|
||||
private static void renameTo(File from, File to, boolean deleteDestination) throws IOException {
|
||||
if (deleteDestination) {
|
||||
deleteIfExists(to);
|
||||
}
|
||||
if (!from.renameTo(to)) {
|
||||
throw new IOException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a snapshot of the entry named {@code key}, or null if it doesn't
|
||||
* exist is not currently readable. If a value is returned, it is moved to
|
||||
* the head of the LRU queue.
|
||||
*/
|
||||
public synchronized Snapshot get(String key) throws IOException {
|
||||
checkNotClosed();
|
||||
validateKey(key);
|
||||
Entry entry = lruEntries.get(key);
|
||||
if (entry == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!entry.readable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Open all streams eagerly to guarantee that we see a single published
|
||||
// snapshot. If we opened streams lazily then the streams could come
|
||||
// from different edits.
|
||||
InputStream[] ins = new InputStream[valueCount];
|
||||
try {
|
||||
for (int i = 0; i < valueCount; i++) {
|
||||
ins[i] = new FileInputStream(entry.getCleanFile(i));
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
// A file must have been deleted manually!
|
||||
for (int i = 0; i < valueCount; i++) {
|
||||
if (ins[i] != null) {
|
||||
Util.closeQuietly(ins[i]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
redundantOpCount++;
|
||||
journalWriter.append(READ + ' ' + key + '\n');
|
||||
if (journalRebuildRequired()) {
|
||||
executorService.submit(cleanupCallable);
|
||||
}
|
||||
|
||||
return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an editor for the entry named {@code key}, or null if another
|
||||
* edit is in progress.
|
||||
*/
|
||||
public Editor edit(String key) throws IOException {
|
||||
return edit(key, ANY_SEQUENCE_NUMBER);
|
||||
}
|
||||
|
||||
private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
|
||||
checkNotClosed();
|
||||
validateKey(key);
|
||||
Entry entry = lruEntries.get(key);
|
||||
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
|
||||
|| entry.sequenceNumber != expectedSequenceNumber)) {
|
||||
return null; // Snapshot is stale.
|
||||
}
|
||||
if (entry == null) {
|
||||
entry = new Entry(key);
|
||||
lruEntries.put(key, entry);
|
||||
} else if (entry.currentEditor != null) {
|
||||
return null; // Another edit is in progress.
|
||||
}
|
||||
|
||||
Editor editor = new Editor(entry);
|
||||
entry.currentEditor = editor;
|
||||
|
||||
// Flush the journal before creating files to prevent file leaks.
|
||||
journalWriter.write(DIRTY + ' ' + key + '\n');
|
||||
journalWriter.flush();
|
||||
return editor;
|
||||
}
|
||||
|
||||
/** Returns the directory where this cache stores its data. */
|
||||
public File getDirectory() {
|
||||
return directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum number of bytes that this cache should use to store
|
||||
* its data.
|
||||
*/
|
||||
public synchronized long getMaxSize() {
|
||||
return maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the maximum number of bytes the cache can store and queues a job
|
||||
* to trim the existing store, if necessary.
|
||||
*/
|
||||
public synchronized void setMaxSize(long maxSize) {
|
||||
this.maxSize = maxSize;
|
||||
executorService.submit(cleanupCallable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of bytes currently being used to store the values in
|
||||
* this cache. This may be greater than the max size if a background
|
||||
* deletion is pending.
|
||||
*/
|
||||
public synchronized long size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
|
||||
Entry entry = editor.entry;
|
||||
if (entry.currentEditor != editor) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
// If this edit is creating the entry for the first time, every index must have a value.
|
||||
if (success && !entry.readable) {
|
||||
for (int i = 0; i < valueCount; i++) {
|
||||
if (!editor.written[i]) {
|
||||
editor.abort();
|
||||
throw new IllegalStateException("Newly created entry didn't create value for index " + i);
|
||||
}
|
||||
if (!entry.getDirtyFile(i).exists()) {
|
||||
editor.abort();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < valueCount; i++) {
|
||||
File dirty = entry.getDirtyFile(i);
|
||||
if (success) {
|
||||
if (dirty.exists()) {
|
||||
File clean = entry.getCleanFile(i);
|
||||
dirty.renameTo(clean);
|
||||
long oldLength = entry.lengths[i];
|
||||
long newLength = clean.length();
|
||||
entry.lengths[i] = newLength;
|
||||
size = size - oldLength + newLength;
|
||||
}
|
||||
} else {
|
||||
deleteIfExists(dirty);
|
||||
}
|
||||
}
|
||||
|
||||
redundantOpCount++;
|
||||
entry.currentEditor = null;
|
||||
if (entry.readable | success) {
|
||||
entry.readable = true;
|
||||
journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
|
||||
if (success) {
|
||||
entry.sequenceNumber = nextSequenceNumber++;
|
||||
}
|
||||
} else {
|
||||
lruEntries.remove(entry.key);
|
||||
journalWriter.write(REMOVE + ' ' + entry.key + '\n');
|
||||
}
|
||||
journalWriter.flush();
|
||||
|
||||
if (size > maxSize || journalRebuildRequired()) {
|
||||
executorService.submit(cleanupCallable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* We only rebuild the journal when it will halve the size of the journal
|
||||
* and eliminate at least 2000 ops.
|
||||
*/
|
||||
private boolean journalRebuildRequired() {
|
||||
final int redundantOpCompactThreshold = 2000;
|
||||
return redundantOpCount >= redundantOpCompactThreshold //
|
||||
&& redundantOpCount >= lruEntries.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the entry for {@code key} if it exists and can be removed. Entries
|
||||
* actively being edited cannot be removed.
|
||||
*
|
||||
* @return true if an entry was removed.
|
||||
*/
|
||||
public synchronized boolean remove(String key) throws IOException {
|
||||
checkNotClosed();
|
||||
validateKey(key);
|
||||
Entry entry = lruEntries.get(key);
|
||||
if (entry == null || entry.currentEditor != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < valueCount; i++) {
|
||||
File file = entry.getCleanFile(i);
|
||||
if (file.exists() && !file.delete()) {
|
||||
throw new IOException("failed to delete " + file);
|
||||
}
|
||||
size -= entry.lengths[i];
|
||||
entry.lengths[i] = 0;
|
||||
}
|
||||
|
||||
redundantOpCount++;
|
||||
journalWriter.append(REMOVE + ' ' + key + '\n');
|
||||
lruEntries.remove(key);
|
||||
|
||||
if (journalRebuildRequired()) {
|
||||
executorService.submit(cleanupCallable);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Returns true if this cache has been closed. */
|
||||
public synchronized boolean isClosed() {
|
||||
return journalWriter == null;
|
||||
}
|
||||
|
||||
private void checkNotClosed() {
|
||||
if (journalWriter == null) {
|
||||
throw new IllegalStateException("cache is closed");
|
||||
}
|
||||
}
|
||||
|
||||
/** Force buffered operations to the filesystem. */
|
||||
public synchronized void flush() throws IOException {
|
||||
checkNotClosed();
|
||||
trimToSize();
|
||||
journalWriter.flush();
|
||||
}
|
||||
|
||||
/** Closes this cache. Stored values will remain on the filesystem. */
|
||||
public synchronized void close() throws IOException {
|
||||
if (journalWriter == null) {
|
||||
return; // Already closed.
|
||||
}
|
||||
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
|
||||
if (entry.currentEditor != null) {
|
||||
entry.currentEditor.abort();
|
||||
}
|
||||
}
|
||||
trimToSize();
|
||||
journalWriter.close();
|
||||
journalWriter = null;
|
||||
}
|
||||
|
||||
private void trimToSize() throws IOException {
|
||||
while (size > maxSize) {
|
||||
Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
|
||||
remove(toEvict.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the cache and deletes all of its stored values. This will delete
|
||||
* all files in the cache directory including files that weren't created by
|
||||
* the cache.
|
||||
*/
|
||||
public void delete() throws IOException {
|
||||
close();
|
||||
Util.deleteContents(directory);
|
||||
}
|
||||
|
||||
private void validateKey(String key) {
|
||||
Matcher matcher = LEGAL_KEY_PATTERN.matcher(key);
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalArgumentException("keys must match regex "
|
||||
+ STRING_KEY_PATTERN + ": \"" + key + "\"");
|
||||
}
|
||||
}
|
||||
|
||||
private static String inputStreamToString(InputStream in) throws IOException {
|
||||
return Util.readFully(new InputStreamReader(in, Util.UTF_8));
|
||||
}
|
||||
|
||||
/** A snapshot of the values for an entry. */
|
||||
public final class Snapshot implements Closeable {
|
||||
private final String key;
|
||||
private final long sequenceNumber;
|
||||
private final InputStream[] ins;
|
||||
private final long[] lengths;
|
||||
|
||||
private Snapshot(String key, long sequenceNumber, InputStream[] ins, long[] lengths) {
|
||||
this.key = key;
|
||||
this.sequenceNumber = sequenceNumber;
|
||||
this.ins = ins;
|
||||
this.lengths = lengths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an editor for this snapshot's entry, or null if either the
|
||||
* entry has changed since this snapshot was created or if another edit
|
||||
* is in progress.
|
||||
*/
|
||||
public Editor edit() throws IOException {
|
||||
return DiskLruCache.this.edit(key, sequenceNumber);
|
||||
}
|
||||
|
||||
/** Returns the unbuffered stream with the value for {@code index}. */
|
||||
public InputStream getInputStream(int index) {
|
||||
return ins[index];
|
||||
}
|
||||
|
||||
/** Returns the string value for {@code index}. */
|
||||
public String getString(int index) throws IOException {
|
||||
return inputStreamToString(getInputStream(index));
|
||||
}
|
||||
|
||||
/** Returns the byte length of the value for {@code index}. */
|
||||
public long getLength(int index) {
|
||||
return lengths[index];
|
||||
}
|
||||
|
||||
public void close() {
|
||||
for (InputStream in : ins) {
|
||||
Util.closeQuietly(in);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
// Eat all writes silently. Nom nom.
|
||||
}
|
||||
};
|
||||
|
||||
/** Edits the values for an entry. */
|
||||
public final class Editor {
|
||||
private final Entry entry;
|
||||
private final boolean[] written;
|
||||
private boolean hasErrors;
|
||||
private boolean committed;
|
||||
|
||||
private Editor(Entry entry) {
|
||||
this.entry = entry;
|
||||
this.written = (entry.readable) ? null : new boolean[valueCount];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unbuffered input stream to read the last committed value,
|
||||
* or null if no value has been committed.
|
||||
*/
|
||||
public InputStream newInputStream(int index) throws IOException {
|
||||
synchronized (DiskLruCache.this) {
|
||||
if (entry.currentEditor != this) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (!entry.readable) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new FileInputStream(entry.getCleanFile(index));
|
||||
} catch (FileNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last committed value as a string, or null if no value
|
||||
* has been committed.
|
||||
*/
|
||||
public String getString(int index) throws IOException {
|
||||
InputStream in = newInputStream(index);
|
||||
return in != null ? inputStreamToString(in) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new unbuffered output stream to write the value at
|
||||
* {@code index}. If the underlying output stream encounters errors
|
||||
* when writing to the filesystem, this edit will be aborted when
|
||||
* {@link #commit} is called. The returned output stream does not throw
|
||||
* IOExceptions.
|
||||
*/
|
||||
public OutputStream newOutputStream(int index) throws IOException {
|
||||
if (index < 0 || index >= valueCount) {
|
||||
throw new IllegalArgumentException("Expected index " + index + " to "
|
||||
+ "be greater than 0 and less than the maximum value count "
|
||||
+ "of " + valueCount);
|
||||
}
|
||||
synchronized (DiskLruCache.this) {
|
||||
if (entry.currentEditor != this) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (!entry.readable) {
|
||||
written[index] = true;
|
||||
}
|
||||
File dirtyFile = entry.getDirtyFile(index);
|
||||
FileOutputStream outputStream;
|
||||
try {
|
||||
outputStream = new FileOutputStream(dirtyFile);
|
||||
} catch (FileNotFoundException e) {
|
||||
// Attempt to recreate the cache directory.
|
||||
directory.mkdirs();
|
||||
try {
|
||||
outputStream = new FileOutputStream(dirtyFile);
|
||||
} catch (FileNotFoundException e2) {
|
||||
// We are unable to recover. Silently eat the writes.
|
||||
return NULL_OUTPUT_STREAM;
|
||||
}
|
||||
}
|
||||
return new FaultHidingOutputStream(outputStream);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the value at {@code index} to {@code value}. */
|
||||
public void set(int index, String value) throws IOException {
|
||||
Writer writer = null;
|
||||
try {
|
||||
writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
|
||||
writer.write(value);
|
||||
} finally {
|
||||
Util.closeQuietly(writer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits this edit so it is visible to readers. This releases the
|
||||
* edit lock so another edit may be started on the same key.
|
||||
*/
|
||||
public void commit() throws IOException {
|
||||
if (hasErrors) {
|
||||
completeEdit(this, false);
|
||||
remove(entry.key); // The previous entry is stale.
|
||||
} else {
|
||||
completeEdit(this, true);
|
||||
}
|
||||
committed = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts this edit. This releases the edit lock so another edit may be
|
||||
* started on the same key.
|
||||
*/
|
||||
public void abort() throws IOException {
|
||||
completeEdit(this, false);
|
||||
}
|
||||
|
||||
public void abortUnlessCommitted() {
|
||||
if (!committed) {
|
||||
try {
|
||||
abort();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class FaultHidingOutputStream extends FilterOutputStream {
|
||||
private FaultHidingOutputStream(OutputStream out) {
|
||||
super(out);
|
||||
}
|
||||
|
||||
@Override public void write(int oneByte) {
|
||||
try {
|
||||
out.write(oneByte);
|
||||
} catch (IOException e) {
|
||||
hasErrors = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void write(byte[] buffer, int offset, int length) {
|
||||
try {
|
||||
out.write(buffer, offset, length);
|
||||
} catch (IOException e) {
|
||||
hasErrors = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
try {
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
hasErrors = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void flush() {
|
||||
try {
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
hasErrors = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class Entry {
|
||||
private final String key;
|
||||
|
||||
/** Lengths of this entry's files. */
|
||||
private final long[] lengths;
|
||||
|
||||
/** True if this entry has ever been published. */
|
||||
private boolean readable;
|
||||
|
||||
/** The ongoing edit or null if this entry is not being edited. */
|
||||
private Editor currentEditor;
|
||||
|
||||
/** The sequence number of the most recently committed edit to this entry. */
|
||||
private long sequenceNumber;
|
||||
|
||||
private Entry(String key) {
|
||||
this.key = key;
|
||||
this.lengths = new long[valueCount];
|
||||
}
|
||||
|
||||
public String getLengths() throws IOException {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (long size : lengths) {
|
||||
result.append(' ').append(size);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/** Set lengths using decimal numbers like "10123". */
|
||||
private void setLengths(String[] strings) throws IOException {
|
||||
if (strings.length != valueCount) {
|
||||
throw invalidLengths(strings);
|
||||
}
|
||||
|
||||
try {
|
||||
for (int i = 0; i < strings.length; i++) {
|
||||
lengths[i] = Long.parseLong(strings[i]);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalidLengths(strings);
|
||||
}
|
||||
}
|
||||
|
||||
private IOException invalidLengths(String[] strings) throws IOException {
|
||||
throw new IOException("unexpected journal line: " + java.util.Arrays.toString(strings));
|
||||
}
|
||||
|
||||
public File getCleanFile(int i) {
|
||||
return new File(directory, key + "." + i);
|
||||
}
|
||||
|
||||
public File getDirtyFile(int i) {
|
||||
return new File(directory, key + "." + i + ".tmp");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.cache;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class ImageCache extends AnyCache<Bitmap>{
|
||||
|
||||
private static final String TAG = "ImageCache";
|
||||
|
||||
/**
|
||||
* Default memory cache size as a percent of device memory class
|
||||
*/
|
||||
private static final float MEM_CACHE_DIVIDER = 0.25f;
|
||||
|
||||
/**
|
||||
* Compression settings when writing images to disk cache
|
||||
*/
|
||||
private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
|
||||
|
||||
/**
|
||||
* Image compression quality
|
||||
*/
|
||||
private static final int COMPRESS_QUALITY = 98;
|
||||
|
||||
private static ImageCache sImageCache;
|
||||
|
||||
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
|
||||
if (sImageCache == null) {
|
||||
final ActivityManager activityManager = (ActivityManager)context
|
||||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
|
||||
* 1024 * 1024);
|
||||
|
||||
AnyCacheParams params = new AnyCacheParams();
|
||||
params.hasMemoryCache = true;
|
||||
params.memoryCacheMaxSize = memoryCacheMax;
|
||||
params.hasDiskCache = true;
|
||||
params.diskCacheDir = getDiskCacheDir(context, TAG);
|
||||
params.diskCacheMaxSize = 20 * 1024 * 1024;
|
||||
|
||||
sImageCache = new ImageCache(params);
|
||||
}
|
||||
return sImageCache;
|
||||
}
|
||||
|
||||
public ImageCache(AnyCacheParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int sizeOf(String key, Bitmap value) {
|
||||
return value.getByteCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Bitmap read(InputStream is) {
|
||||
return BitmapFactory.decodeStream(is);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean write(OutputStream os, Bitmap value) {
|
||||
return value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the external app cache directory
|
||||
*
|
||||
* @param context The {@link Context} to use
|
||||
* @return The external cache directory
|
||||
*/
|
||||
private static File getExternalCacheDir(final Context context) {
|
||||
return context.getExternalCacheDir();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a usable cache directory (external if available, internal otherwise)
|
||||
*
|
||||
* @param context The {@link Context} to use
|
||||
* @param uniqueName A unique directory name to append to the cache
|
||||
* directory
|
||||
* @return The cache directory
|
||||
*/
|
||||
private static File getDiskCacheDir(final Context context, final String uniqueName) {
|
||||
// getExternalCacheDir(context) returns null if external storage is not ready
|
||||
final String cachePath = getExternalCacheDir(context) != null
|
||||
? getExternalCacheDir(context).getPath()
|
||||
: context.getCacheDir().getPath();
|
||||
return new File(cachePath, uniqueName);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.cardview;
|
||||
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* @author Hippo
|
||||
*
|
||||
* A salon to make views look like card
|
||||
*/
|
||||
public final class CardViewSalon {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reform(View view, int bgColor, int boundColor) {
|
||||
view.setBackgroundDrawable(new RoundRectDrawable(
|
||||
bgColor, boundColor));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reform(View view, int[][] stateSets, int[] bgColors,
|
||||
int[] boundColors) {
|
||||
view.setBackgroundDrawable(new RoundRectDrawable(
|
||||
stateSets, bgColors, boundColors));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reformWithShadow(View view, int bgColor, int boundColor,
|
||||
boolean keepPadding) {
|
||||
view.setBackgroundDrawable(new RoundRectDrawableWithShadow(
|
||||
bgColor, boundColor, keepPadding));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reformWithShadow(View view, int[][] stateSets, int[] bgColors,
|
||||
int[] boundColors, boolean keepPadding) {
|
||||
view.setBackgroundDrawable(new RoundRectDrawableWithShadow(
|
||||
stateSets, bgColors, boundColors, keepPadding));
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.cardview;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.util.StateSet;
|
||||
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
// Get most code from android.support.v7.widget.CardViewEclairMr1
|
||||
public class RoundRectDrawable extends Drawable {
|
||||
|
||||
protected final float mCornerRadius;
|
||||
private final int[][] mStateSets;
|
||||
private final int[] mBgColors;
|
||||
private final int[] mBoundColors;
|
||||
|
||||
private final Paint mBgPaint;
|
||||
private final Paint mBoundPaint;
|
||||
|
||||
private int mLastIndex = -1;
|
||||
protected final RectF mTempRectF = new RectF();
|
||||
|
||||
public RoundRectDrawable(int bgColor, int boundColor) {
|
||||
mCornerRadius = Ui.dp2pix(2);
|
||||
mStateSets = null;
|
||||
mBgColors = null;
|
||||
mBoundColors = null;
|
||||
|
||||
mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mBgPaint.setColor(bgColor);
|
||||
if (boundColor == 0) {
|
||||
mBoundPaint = null;
|
||||
} else {
|
||||
mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mBoundPaint.setColor(boundColor);
|
||||
}
|
||||
}
|
||||
|
||||
public RoundRectDrawable(int[][] stateSets, int[] bgColors, int[] boundColors) {
|
||||
mCornerRadius = Ui.dp2pix(2);
|
||||
mStateSets = stateSets;
|
||||
mBgColors = bgColors;
|
||||
mBoundColors = boundColors;
|
||||
|
||||
mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
if (mBoundColors == null) {
|
||||
mBoundPaint = null;
|
||||
} else {
|
||||
mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStateful() {
|
||||
return mStateSets != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onStateChange(int[] stateSet) {
|
||||
final int N = mStateSets.length;
|
||||
for (int i = 0; i < N; i++) {
|
||||
if (StateSet.stateSetMatches(mStateSets[i], stateSet)) {
|
||||
if (mLastIndex == i)
|
||||
return false;
|
||||
mLastIndex = i;
|
||||
|
||||
mBgPaint.setColor(mBgColors[i]);
|
||||
if (mBoundColors != null)
|
||||
mBoundPaint.setColor(mBoundColors[i]);
|
||||
invalidateSelf();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
drawBody(canvas, new RectF(getBounds()));
|
||||
}
|
||||
|
||||
protected void drawBody(Canvas canvas, RectF bounds) {
|
||||
if (mBoundPaint == null && Build.VERSION.SDK_INT >= 17) {
|
||||
canvas.drawRoundRect(bounds, mCornerRadius, mCornerRadius, mBgPaint);
|
||||
|
||||
} else {
|
||||
final float twoRadius = mCornerRadius * 2;
|
||||
final float innerWidth = bounds.width() - twoRadius;
|
||||
final float innerHeight = bounds.height() - twoRadius;
|
||||
Paint drawBoundsPaint = mBoundPaint == null ? mBgPaint : mBoundPaint;
|
||||
|
||||
// Draw four corner
|
||||
mTempRectF.set(bounds.left, bounds.top,
|
||||
bounds.left + mCornerRadius * 2, bounds.top + mCornerRadius * 2);
|
||||
canvas.drawArc(mTempRectF, 180, 90, true, drawBoundsPaint);
|
||||
mTempRectF.offset(innerWidth, 0);
|
||||
canvas.drawArc(mTempRectF, 270, 90, true, drawBoundsPaint);
|
||||
mTempRectF.offset(0, innerHeight);
|
||||
canvas.drawArc(mTempRectF, 0, 90, true, drawBoundsPaint);
|
||||
mTempRectF.offset(-innerWidth, 0);
|
||||
canvas.drawArc(mTempRectF, 90, 90, true, drawBoundsPaint);
|
||||
|
||||
//draw top and bottom pieces
|
||||
canvas.drawRect(bounds.left + mCornerRadius, bounds.top,
|
||||
bounds.right - mCornerRadius, bounds.top + mCornerRadius,
|
||||
drawBoundsPaint);
|
||||
canvas.drawRect(bounds.left + mCornerRadius,
|
||||
bounds.bottom - mCornerRadius, bounds.right - mCornerRadius,
|
||||
bounds.bottom, drawBoundsPaint);
|
||||
|
||||
if (mBoundPaint == null) {
|
||||
// No bounds color, just draw center and left and right at same time
|
||||
canvas.drawRect(bounds.left, bounds.top + mCornerRadius,
|
||||
bounds.right, bounds.bottom - mCornerRadius, mBgPaint);
|
||||
} else {
|
||||
// Draw left and right pieces
|
||||
canvas.drawRect(bounds.left, bounds.top + mCornerRadius,
|
||||
bounds.left + mCornerRadius, bounds.bottom - mCornerRadius,
|
||||
drawBoundsPaint);
|
||||
canvas.drawRect(bounds.right - mCornerRadius, bounds.top + mCornerRadius,
|
||||
bounds.right, bounds.bottom - mCornerRadius, drawBoundsPaint);
|
||||
// Draw center
|
||||
canvas.drawRect(bounds.left + mCornerRadius, bounds.top + mCornerRadius,
|
||||
bounds.right - mCornerRadius, bounds.bottom - mCornerRadius, mBgPaint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
// not supported
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
// not supported
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return PixelFormat.OPAQUE;
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.cardview;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.LinearGradient;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.RadialGradient;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Shader;
|
||||
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
// Get most code from android.support.v7.widget.RoundRectDrawableWithShadow
|
||||
public class RoundRectDrawableWithShadow extends RoundRectDrawable {
|
||||
private final static float SHADOW_MULTIPLIER = 1.5f;
|
||||
|
||||
private int mShadowStartColor;
|
||||
private int mShadowEndColor;
|
||||
private float mShadowSize;
|
||||
|
||||
private Paint mCornerShadowPaint;
|
||||
private Paint mEdgeShadowPaint;
|
||||
|
||||
private final RectF mPreShadowBounds = new RectF();
|
||||
private final Path mCornerShadowPath = new Path();
|
||||
|
||||
private boolean mDirty = true;
|
||||
private final boolean mKeepPadding;
|
||||
|
||||
public RoundRectDrawableWithShadow(int bgColor, int boundColor,
|
||||
boolean keepPadding) {
|
||||
super(bgColor, boundColor);
|
||||
mKeepPadding = keepPadding;
|
||||
init();
|
||||
}
|
||||
|
||||
public RoundRectDrawableWithShadow(int[][] stateSets,
|
||||
int[] bgColors, int[] boundColors, boolean keepPadding) {
|
||||
super(stateSets, bgColors, boundColors);
|
||||
mKeepPadding = keepPadding;
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
mShadowStartColor = 0x37000000;
|
||||
mShadowEndColor = 0x03000000;
|
||||
mShadowSize = Ui.dp2pix(2) * SHADOW_MULTIPLIER;
|
||||
|
||||
mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mCornerShadowPaint.setStyle(Paint.Style.FILL);
|
||||
mCornerShadowPaint.setDither(true);
|
||||
mEdgeShadowPaint = new Paint(mCornerShadowPaint);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
super.onBoundsChange(bounds);
|
||||
mDirty = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getPadding(Rect padding) {
|
||||
if (mKeepPadding) {
|
||||
return false;
|
||||
} else {
|
||||
padding.set(getSuggestionPadding());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public Rect getSuggestionPadding() {
|
||||
Rect padding = new Rect();
|
||||
final int topShadow = (int) Math.ceil(mShadowSize * (1 / (SHADOW_MULTIPLIER * 2)));
|
||||
final int sideShadow = (int) Math.ceil(mShadowSize - topShadow);
|
||||
padding.set(sideShadow, topShadow, sideShadow, (int) Math.ceil(mShadowSize));
|
||||
return padding;
|
||||
}
|
||||
|
||||
private void buildShadowCorners() {
|
||||
RectF innerBounds = new RectF(-mCornerRadius, -mCornerRadius, mCornerRadius, mCornerRadius);
|
||||
RectF outerBounds = new RectF(innerBounds);
|
||||
outerBounds.inset(-mShadowSize, -mShadowSize);
|
||||
|
||||
mCornerShadowPath.reset();
|
||||
mCornerShadowPath.setFillType(Path.FillType.EVEN_ODD);
|
||||
mCornerShadowPath.moveTo(-mCornerRadius, 0);
|
||||
mCornerShadowPath.rLineTo(-mShadowSize, 0);
|
||||
// outer arc
|
||||
mCornerShadowPath.arcTo(outerBounds, 180f, 90f, false);
|
||||
// inner arc
|
||||
mCornerShadowPath.arcTo(innerBounds, 270f, -90f, false);
|
||||
mCornerShadowPath.close();
|
||||
|
||||
float startRatio = mCornerRadius / (mCornerRadius + mShadowSize);
|
||||
mCornerShadowPaint.setShader(new RadialGradient(0, 0, mCornerRadius + mShadowSize,
|
||||
new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
|
||||
new float[]{0f, startRatio, 1f}
|
||||
, Shader.TileMode.CLAMP));
|
||||
|
||||
// we offset the content shadowSize/2 pixels up to make it more realistic.
|
||||
// this is why edge shadow shader has some extra space
|
||||
// When drawing bottom edge shadow, we use that extra space.
|
||||
mEdgeShadowPaint.setShader(new LinearGradient(0, -mCornerRadius + mShadowSize, 0,
|
||||
-mCornerRadius - mShadowSize,
|
||||
new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
|
||||
new float[]{0f, .5f, 1f}, Shader.TileMode.CLAMP));
|
||||
}
|
||||
|
||||
private void buildComponents(Rect bounds) {
|
||||
mPreShadowBounds.set(bounds.left + mShadowSize, bounds.top + mShadowSize,
|
||||
bounds.right - mShadowSize, bounds.bottom - mShadowSize);
|
||||
buildShadowCorners();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
if (mDirty) {
|
||||
buildComponents(getBounds());
|
||||
mDirty = false;
|
||||
}
|
||||
drawShadow(canvas);
|
||||
final float offset = mShadowSize * (1 - 1 / (SHADOW_MULTIPLIER * 2));
|
||||
final float horizontalOffset = mShadowSize - offset;
|
||||
canvas.translate(0, -offset);
|
||||
mPreShadowBounds.bottom += offset;
|
||||
mPreShadowBounds.left -= horizontalOffset;
|
||||
mPreShadowBounds.right += horizontalOffset;
|
||||
drawBody(canvas, mPreShadowBounds);
|
||||
mPreShadowBounds.bottom -= offset;
|
||||
mPreShadowBounds.left += horizontalOffset;
|
||||
mPreShadowBounds.right -= horizontalOffset;
|
||||
canvas.translate(0, offset);
|
||||
}
|
||||
|
||||
private void drawShadow(Canvas canvas) {
|
||||
int saved = canvas.save();
|
||||
|
||||
float cornerPathSize = 2 * (mCornerRadius + mShadowSize);
|
||||
float edgeShadowTop = -mCornerRadius - mShadowSize;
|
||||
final Rect bounds = getBounds();
|
||||
|
||||
// LT
|
||||
canvas.translate(mPreShadowBounds.left + mCornerRadius,
|
||||
mPreShadowBounds.top + mCornerRadius);
|
||||
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
|
||||
canvas.drawRect(0, edgeShadowTop,
|
||||
bounds.right - cornerPathSize, -mCornerRadius,
|
||||
mEdgeShadowPaint);
|
||||
// RB
|
||||
canvas.rotate(180f);
|
||||
canvas.translate(-bounds.width() + cornerPathSize, -bounds.height() + cornerPathSize);
|
||||
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
|
||||
canvas.drawRect(0, edgeShadowTop,
|
||||
bounds.right - cornerPathSize, -mCornerRadius + mShadowSize,
|
||||
mEdgeShadowPaint);
|
||||
|
||||
// LB
|
||||
canvas.rotate(90f);
|
||||
canvas.translate(0, -bounds.width() + cornerPathSize);
|
||||
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
|
||||
canvas.drawRect(0, edgeShadowTop,
|
||||
bounds.bottom - cornerPathSize, -mCornerRadius,
|
||||
mEdgeShadowPaint);
|
||||
|
||||
// RT
|
||||
canvas.rotate(180f);
|
||||
canvas.translate(-bounds.height() + cornerPathSize, -bounds.width() + cornerPathSize);
|
||||
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
|
||||
canvas.drawRect(0, edgeShadowTop,
|
||||
bounds.bottom - cornerPathSize, -mCornerRadius,
|
||||
mEdgeShadowPaint);
|
||||
|
||||
canvas.restoreToCount(saved);
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ApiGalleryDetail extends ApiGalleryInfo
|
||||
implements LofiDetailImpl {
|
||||
public int previewPageNum;
|
||||
public int previewPerPage;
|
||||
private final List<PreviewList> previewLists = new ArrayList<PreviewList>();
|
||||
|
||||
public ApiGalleryDetail() {}
|
||||
|
||||
public ApiGalleryDetail(ApiGalleryInfo apiGalleryInfo) {
|
||||
gid = apiGalleryInfo.gid;
|
||||
token = apiGalleryInfo.token;
|
||||
title = apiGalleryInfo.title;
|
||||
posted = apiGalleryInfo.posted;
|
||||
category = apiGalleryInfo.category;
|
||||
thumb = apiGalleryInfo.thumb;
|
||||
uploader = apiGalleryInfo.uploader;
|
||||
rating = apiGalleryInfo.rating;
|
||||
simpleLanguage = apiGalleryInfo.simpleLanguage;
|
||||
archiver_key = apiGalleryInfo.archiver_key;
|
||||
title_jpn = apiGalleryInfo.title_jpn;
|
||||
filecount = apiGalleryInfo.filecount;
|
||||
filesize = apiGalleryInfo.filesize;
|
||||
expunged = apiGalleryInfo.expunged;
|
||||
torrentcount = apiGalleryInfo.torrentcount;
|
||||
apiTags = apiGalleryInfo.apiTags;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getGid() {
|
||||
return gid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPreviewPageNum() {
|
||||
return previewPageNum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPreviewPageNum(int pageNum) {
|
||||
previewPageNum = pageNum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPreviewPerPage() {
|
||||
return previewPerPage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreviewList getPreview(int page) {
|
||||
if (page >= 0 && page < previewLists.size())
|
||||
return previewLists.get(page);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPreview(int page, PreviewList previewList) {
|
||||
if (page >= 0 && page < previewLists.size())
|
||||
previewLists.set(page, previewList);
|
||||
else if (page == previewLists.size())
|
||||
previewLists.add(previewList);
|
||||
else
|
||||
; // Do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getTags() {
|
||||
return apiTags;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo toGalleryInfo() {
|
||||
return new GalleryInfo(this);
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
|
||||
public class ApiGalleryInfo extends GalleryInfo{
|
||||
public String archiver_key;
|
||||
public String title_jpn;
|
||||
public String filecount;
|
||||
public long filesize;
|
||||
public boolean expunged;
|
||||
public String torrentcount;
|
||||
public String[] apiTags;
|
||||
|
||||
public static final Parcelable.Creator<ApiGalleryInfo> CREATOR =
|
||||
new Parcelable.Creator<ApiGalleryInfo>() {
|
||||
@Override
|
||||
public ApiGalleryInfo createFromParcel(Parcel source) {
|
||||
ApiGalleryInfo p = new ApiGalleryInfo();
|
||||
p.gid = source.readInt();
|
||||
p.token = source.readString();
|
||||
p.title = source.readString();
|
||||
p.posted = source.readString();
|
||||
p.category = source.readInt();
|
||||
p.thumb = source.readString();
|
||||
p.uploader = source.readString();
|
||||
p.rating = source.readFloat();
|
||||
p.simpleLanguage = source.readString();
|
||||
p.archiver_key = source.readString();
|
||||
p.title_jpn = source.readString();
|
||||
p.filecount = source.readString();
|
||||
p.filesize = source.readLong();
|
||||
p.expunged = Utils.int2boolean(source.readInt());
|
||||
p.torrentcount = source.readString();
|
||||
int apiTagsLength = source.readInt();
|
||||
p.apiTags = new String[apiTagsLength];
|
||||
for (int i = 0; i < apiTagsLength; i++)
|
||||
p.apiTags[i] = source.readString();
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiGalleryInfo[] newArray(int size) {
|
||||
return new ApiGalleryInfo[size];
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeString(archiver_key);
|
||||
dest.writeString(title_jpn);
|
||||
dest.writeString(filecount);
|
||||
dest.writeLong(filesize);
|
||||
dest.writeInt(Utils.boolean2int(expunged));
|
||||
dest.writeString(torrentcount);
|
||||
dest.writeInt(apiTags.length);
|
||||
for (String str : apiTags)
|
||||
dest.writeString(str);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import com.hippo.ehviewer.widget.ExpandableListItem;
|
||||
|
||||
|
||||
public class DownloadInfo implements ExpandableListItem {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = DownloadInfo.class.getSimpleName();
|
||||
|
||||
public static final int STATE_NONE = 0x0;
|
||||
public static final int STATE_WAIT = 0x1;
|
||||
public static final int STATE_DOWNLOAD = 0x2;
|
||||
public static final int STATE_FINISH = 0x3;
|
||||
|
||||
public final GalleryInfo galleryInfo;
|
||||
public final int mode;
|
||||
public volatile int state = STATE_NONE;
|
||||
/** byte/second **/
|
||||
public volatile int speed;
|
||||
public volatile int download = -1;
|
||||
public volatile int total = -1;
|
||||
public volatile int legacy;
|
||||
|
||||
private boolean mExpanded = false;
|
||||
|
||||
public DownloadInfo(GalleryInfo gi, int mode) {
|
||||
this.galleryInfo = gi;
|
||||
this.mode = mode;
|
||||
}
|
||||
|
||||
public DownloadInfo(GalleryInfo gi, int mode, int state, int legacy) {
|
||||
this.galleryInfo = gi;
|
||||
this.mode = mode;
|
||||
this.state = state;
|
||||
this.legacy = legacy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExpanded(boolean expanded) {
|
||||
mExpanded = expanded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getExpanded() {
|
||||
return mExpanded;
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
public class GalleryInfo implements Parcelable {
|
||||
|
||||
/**
|
||||
* ISO 639-1
|
||||
*/
|
||||
public static final String S_LANG_JA = "JA";
|
||||
public static final String S_LANG_EN = "EN";
|
||||
public static final String S_LANG_ZH = "ZH";
|
||||
public static final String S_LANG_NL = "NL";
|
||||
public static final String S_LANG_FR = "FR";
|
||||
public static final String S_LANG_DE = "DE";
|
||||
public static final String S_LANG_HU = "HU";
|
||||
public static final String S_LANG_IT = "IT";
|
||||
public static final String S_LANG_KO = "KO";
|
||||
public static final String S_LANG_PL = "PL";
|
||||
public static final String S_LANG_PT = "PT";
|
||||
public static final String S_LANG_RU = "RU";
|
||||
public static final String S_LANG_ES = "ES";
|
||||
public static final String S_LANG_TH = "TH";
|
||||
public static final String S_LANG_VI = "VI";
|
||||
|
||||
public static final String[] S_LANGS = {
|
||||
S_LANG_EN,
|
||||
S_LANG_ZH,
|
||||
S_LANG_ES,
|
||||
S_LANG_KO,
|
||||
S_LANG_RU,
|
||||
S_LANG_FR,
|
||||
S_LANG_PT,
|
||||
S_LANG_TH,
|
||||
S_LANG_DE,
|
||||
S_LANG_IT,
|
||||
S_LANG_VI,
|
||||
S_LANG_PL,
|
||||
S_LANG_HU,
|
||||
S_LANG_NL,
|
||||
};
|
||||
|
||||
public static final String[] S_LANG_PATTERNS = {
|
||||
"[(\\[]eng(?:lish)?[)\\]]",
|
||||
"[((\\[]chinese[))\\]]|[汉漢]化|中[国國][语語]|中文|[(\\[]CN[)\\]]",
|
||||
"[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]",
|
||||
"[(\\[]korean?[)\\]]",
|
||||
"[(\\[]rus(?:sian)?[)\\]]",
|
||||
"[(\\[]fr(?:ench)?[)\\]]",
|
||||
"[(\\[]portuguese",
|
||||
"[(\\[]thai(?: ภาษาไทย)?[)\\]]",
|
||||
"[(\\[]german[)\\]]",
|
||||
"[(\\[]italiano?[)\\]]",
|
||||
"[(\\[]vietnamese(?: Tiếng Việt)?[)\\]]",
|
||||
"[(\\[]polish[)\\]]",
|
||||
"[(\\[]hun(?:garian)?[)\\]]",
|
||||
"[(\\[]dutch[)\\]]",
|
||||
};
|
||||
|
||||
public int gid;
|
||||
public String token;
|
||||
public String title;
|
||||
public String posted;
|
||||
public int category;
|
||||
public String thumb;
|
||||
public String uploader;
|
||||
public float rating;
|
||||
/**
|
||||
* Will not be recond
|
||||
*/
|
||||
public int thumbWidth;
|
||||
/**
|
||||
* Will not be recond
|
||||
*/
|
||||
public int thumbHeight;
|
||||
/**
|
||||
* language get from title
|
||||
*/
|
||||
public String simpleLanguage;
|
||||
|
||||
public static final Parcelable.Creator<GalleryInfo> CREATOR =
|
||||
new Parcelable.Creator<GalleryInfo>() {
|
||||
@Override
|
||||
public GalleryInfo createFromParcel(Parcel source) {
|
||||
GalleryInfo p = new GalleryInfo();
|
||||
p.gid = source.readInt();
|
||||
p.token = source.readString();
|
||||
p.title = source.readString();
|
||||
p.posted = source.readString();
|
||||
p.category = source.readInt();
|
||||
p.thumb = source.readString();
|
||||
p.uploader = source.readString();
|
||||
p.rating = source.readFloat();
|
||||
p.simpleLanguage = source.readString();
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo[] newArray(int size) {
|
||||
return new GalleryInfo[size];
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeInt(gid);
|
||||
dest.writeString(token);
|
||||
dest.writeString(title);
|
||||
dest.writeString(posted);
|
||||
dest.writeInt(category);
|
||||
dest.writeString(thumb);
|
||||
dest.writeString(uploader);
|
||||
dest.writeFloat(rating);
|
||||
dest.writeString(simpleLanguage);
|
||||
}
|
||||
|
||||
public GalleryInfo() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public GalleryInfo(GalleryInfo gi) {
|
||||
gid = gi.gid;
|
||||
token = gi.token;
|
||||
title = gi.title;
|
||||
posted = gi.posted;
|
||||
category = gi.category;
|
||||
thumb = gi.thumb;
|
||||
uploader = gi.uploader;
|
||||
rating = gi.rating;
|
||||
simpleLanguage = gi.simpleLanguage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof GalleryInfo && ((GalleryInfo) o).gid == gid)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public final void generateSLang() {
|
||||
for (int i = 0; i < S_LANGS.length; i++) {
|
||||
if (Pattern.compile(S_LANG_PATTERNS[i], Pattern.CASE_INSENSITIVE).matcher(title).find()) {
|
||||
simpleLanguage = S_LANGS[i];
|
||||
return;
|
||||
}
|
||||
}
|
||||
simpleLanguage = null;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
public class GalleryPopular extends GalleryInfo {
|
||||
public long count;
|
||||
|
||||
public static final Parcelable.Creator<GalleryPopular> CREATOR =
|
||||
new Parcelable.Creator<GalleryPopular>() {
|
||||
@Override
|
||||
public GalleryPopular createFromParcel(Parcel source) {
|
||||
GalleryPopular p = new GalleryPopular();
|
||||
p.gid = source.readInt();
|
||||
p.token = source.readString();
|
||||
p.title = source.readString();
|
||||
p.posted = source.readString();
|
||||
p.category = source.readInt();
|
||||
p.thumb = source.readString();
|
||||
p.uploader = source.readString();
|
||||
p.rating = source.readFloat();
|
||||
p.simpleLanguage = source.readString();
|
||||
p.count = source.readLong();
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryPopular[] newArray(int size) {
|
||||
return new GalleryPopular[size];
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeLong(count);
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.ImageLoader;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.ui.GalleryActivity;
|
||||
import com.hippo.ehviewer.widget.SimpleGridLayout;
|
||||
|
||||
public class LargePreviewList extends PreviewList {
|
||||
|
||||
private class Item {
|
||||
public String mImageUrl;
|
||||
public String mPageUrl;
|
||||
|
||||
public Item(String imageUrl, String pageUrl) {
|
||||
mImageUrl = imageUrl;
|
||||
mPageUrl = pageUrl;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Item> mItemList = new ArrayList<Item>();
|
||||
|
||||
public void addItem(String imageUrl, String pageUrl) {
|
||||
mItemList.add(new Item(imageUrl, pageUrl));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPageUrl(int index) {
|
||||
if (index >= 0 && index < mItemList.size())
|
||||
return mItemList.get(index).mPageUrl;
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return mItemList.size();
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
@Override
|
||||
public void addPreview(SimpleGridLayout viewGroup) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
viewGroup.removeAllViews();
|
||||
LayoutInflater inflater = LayoutInflater.from(mActivity);
|
||||
int startIndex = mTargetPage * mPi.getPreviewPerPage();
|
||||
int index = startIndex;
|
||||
for (Item item : mItemList) {
|
||||
|
||||
View view = inflater.inflate(R.layout.preview_item, null);
|
||||
((TextView)view.findViewById(R.id.text)).setText(String.valueOf(index + 1));
|
||||
final int _index = index;
|
||||
view.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
// Add to read in Data
|
||||
Intent intent = new Intent(mActivity,
|
||||
GalleryActivity.class);
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mPi.toGalleryInfo());
|
||||
intent.putExtra(GalleryActivity.KEY_START_INDEX, _index);
|
||||
mActivity.startActivity(intent);
|
||||
}
|
||||
});
|
||||
viewGroup.addView(view);
|
||||
// TODO I need a better key
|
||||
ImageLoader.getInstance(mActivity).add(item.mImageUrl, mPi.getGid() +
|
||||
"-preview-" + index,
|
||||
new PreviewImageGetListener(viewGroup, index - startIndex));
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
private class PreviewImageGetListener implements ImageLoader.OnGetImageListener {
|
||||
private final SimpleGridLayout mViewGroup;
|
||||
private final int mIndex;
|
||||
|
||||
/**
|
||||
* index is view index in viewgroup
|
||||
* @param viewGroup
|
||||
* @param index
|
||||
*/
|
||||
public PreviewImageGetListener(SimpleGridLayout viewGroup, int index) {
|
||||
mViewGroup = viewGroup;
|
||||
mIndex = index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGetImage(String key, Bitmap bmp, int state) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
if (bmp == null)
|
||||
mHolder.onGetPreviewImageFailure();
|
||||
else
|
||||
((ImageView)mViewGroup.getChildAt(mIndex).findViewById(R.id.image)).setImageBitmap(bmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,334 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.network.UrlBuilder;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class ListUrls {
|
||||
|
||||
public static final boolean NUM_CATEGORY = false;
|
||||
|
||||
// Mode
|
||||
public static final int MODE_NORMAL = 0x0;
|
||||
public static final int MODE_UPLOADER = 0x1;
|
||||
public static final int MODE_TAG = 0x2;
|
||||
public static final int MODE_POPULAR = 0x3;
|
||||
public static final int MODE_IMAGE_SEARCH = 0x4;
|
||||
|
||||
// Category
|
||||
public static final int NONE = -1; // Use it for homepage
|
||||
public static final int MISC = 0x1;
|
||||
public static final int DOUJINSHI = 0x2;
|
||||
public static final int MANGA = 0x4;
|
||||
public static final int ARTIST_CG = 0x8;
|
||||
public static final int GAME_CG = 0x10;
|
||||
public static final int IMAGE_SET = 0x20;
|
||||
public static final int COSPLAY = 0x40;
|
||||
public static final int ASIAN_PORN = 0x80;
|
||||
public static final int NON_H = 0x100;
|
||||
public static final int WESTERN = 0x200;
|
||||
public static final int UNKNOWN = 0x400;
|
||||
|
||||
public static final int ALL_CATEGORT = UNKNOWN - 1;
|
||||
//DOUJINSHI|MANGA|ARTIST_CG|GAME_CG|WESTERN|NON_H|IMAGE_SET|COSPLAY|ASIAN_PORN|MISC;
|
||||
|
||||
// advance search
|
||||
public static final int SNAME = 0x1;
|
||||
public static final int STAGS = 0x2;
|
||||
public static final int SDESC = 0x4;
|
||||
public static final int STORR = 0x8;
|
||||
public static final int STO = 0x10;
|
||||
public static final int STD1 = 0x20;
|
||||
public static final int STD2 = 0x40;
|
||||
public static final int SH = 0x80;
|
||||
|
||||
public static final int DEFAULT_ADVANCE = SNAME | STAGS;
|
||||
public static final int DEFAULT_MIN_RATING = 2;
|
||||
|
||||
private int mMode = MODE_NORMAL;
|
||||
|
||||
private int page = 0;
|
||||
private int category = NONE;
|
||||
|
||||
private int advsearchType = -1;
|
||||
private int minRating = -1;
|
||||
|
||||
private String search = null;
|
||||
private String mTag = null;
|
||||
|
||||
private int mImageSearchMode;
|
||||
private String mImageKey;
|
||||
private String mImageUrl;
|
||||
private File mSearchFile;
|
||||
private String mResultUrl = null;
|
||||
|
||||
public ListUrls() {}
|
||||
|
||||
public ListUrls(int category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public ListUrls(int category, int page) {
|
||||
this.category = category;
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public ListUrls(int category, String search) {
|
||||
this.category = category;
|
||||
this.search = search;
|
||||
}
|
||||
|
||||
public ListUrls(int category, String search, int page) {
|
||||
this.category = category;
|
||||
this.search = search;
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public void setCategory(int category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public int getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public String getSearch() {
|
||||
return search;
|
||||
}
|
||||
|
||||
public void setAdvance(boolean enabled) {
|
||||
if (enabled && advsearchType == -1)
|
||||
advsearchType = DEFAULT_ADVANCE;
|
||||
else if (!enabled)
|
||||
advsearchType = -1;
|
||||
}
|
||||
|
||||
public void setAdvance(int advanceType) {
|
||||
advsearchType = advanceType;
|
||||
}
|
||||
|
||||
public void setAdvance(int advanceType, int minRating) {
|
||||
advsearchType = advanceType;
|
||||
this.minRating = minRating;
|
||||
}
|
||||
|
||||
public boolean isAdvance() {
|
||||
return advsearchType != -1;
|
||||
}
|
||||
|
||||
public int getAdvanceType() {
|
||||
return advsearchType;
|
||||
}
|
||||
|
||||
public boolean isMinRating() {
|
||||
return minRating != -1;
|
||||
}
|
||||
|
||||
public int getMinRating() {
|
||||
return minRating;
|
||||
}
|
||||
|
||||
public void setPage(int p) {
|
||||
page = p;
|
||||
}
|
||||
|
||||
public int getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
public int getMode() {
|
||||
return mMode;
|
||||
}
|
||||
|
||||
public void setMode(int mode) {
|
||||
mMode = mode;
|
||||
}
|
||||
|
||||
// For tag mode
|
||||
public void setTag(String tag) {
|
||||
mMode = MODE_TAG;
|
||||
mTag = tag;
|
||||
}
|
||||
|
||||
public String getTag() {
|
||||
return mTag;
|
||||
}
|
||||
|
||||
// For image search mode
|
||||
public void setSearchImage(String key, String url, int imageSearchMode) {
|
||||
mMode = MODE_IMAGE_SEARCH;
|
||||
mImageKey = key;
|
||||
mImageUrl = url;
|
||||
mImageSearchMode = imageSearchMode;
|
||||
}
|
||||
|
||||
public void setSearchFile(File searchFile, int imageSearchMode) {
|
||||
mMode = MODE_IMAGE_SEARCH;
|
||||
mSearchFile = searchFile;
|
||||
mImageSearchMode = imageSearchMode;
|
||||
}
|
||||
|
||||
public void setSearchResult(String resultUrl) {
|
||||
mResultUrl = resultUrl;
|
||||
}
|
||||
|
||||
public File getSearchFile() {
|
||||
return mSearchFile;
|
||||
}
|
||||
|
||||
public String getSearchImageKey() {
|
||||
return mImageKey;
|
||||
}
|
||||
|
||||
public String getSearchImageUrl() {
|
||||
return mImageUrl;
|
||||
}
|
||||
|
||||
public int getImageSearchMode() {
|
||||
return mImageSearchMode;
|
||||
}
|
||||
|
||||
|
||||
public String getUrl() {
|
||||
return getUrl(Config.getMode());
|
||||
}
|
||||
|
||||
public String getUrl(int mode) {
|
||||
|
||||
switch (mMode) {
|
||||
case MODE_POPULAR:
|
||||
return null;
|
||||
|
||||
case MODE_IMAGE_SEARCH:
|
||||
if (mResultUrl == null)
|
||||
return null;
|
||||
else
|
||||
return mResultUrl + "&page=" + page;
|
||||
|
||||
case MODE_TAG:
|
||||
// Add tag
|
||||
StringBuilder sb = new StringBuilder(EhClient.getUrlHeader(mode));
|
||||
sb.append("tag/");
|
||||
if (mTag != null) {
|
||||
String[] tag = mTag.split("\\s+");
|
||||
try {
|
||||
for (int i = 0; i < tag.length; i++)
|
||||
tag[i] = URLEncoder.encode(tag[i], "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {}
|
||||
sb.append(Utils.join(tag, '+'));
|
||||
|
||||
// Add page
|
||||
sb.append("/").append(page);
|
||||
} else {
|
||||
sb.append(page);
|
||||
}
|
||||
return sb.toString();
|
||||
|
||||
case MODE_NORMAL:
|
||||
case MODE_UPLOADER:
|
||||
default:
|
||||
String header = EhClient.getUrlHeader(mode);
|
||||
boolean isNeedFooter = false;
|
||||
UrlBuilder ub;
|
||||
// Add category
|
||||
if (category != NONE) {
|
||||
isNeedFooter = true;
|
||||
if (NUM_CATEGORY) {
|
||||
ub = new UrlBuilder(header + category);
|
||||
} else {
|
||||
ub = new UrlBuilder(header);
|
||||
ub.addQuery("f_doujinshi", ((category & DOUJINSHI) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_manga", ((category & MANGA) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_artistcg", ((category & ARTIST_CG) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_gamecg", ((category & GAME_CG) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_western", ((category & WESTERN) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_non-h", ((category & NON_H) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_imageset", ((category & IMAGE_SET) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_cosplay", ((category & COSPLAY) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_asianporn", ((category & ASIAN_PORN) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_misc", ((category & MISC) == 0) ? "0" : "1");
|
||||
}
|
||||
} else {
|
||||
ub = new UrlBuilder(header);
|
||||
}
|
||||
|
||||
// Add search item
|
||||
if (search != null) {
|
||||
isNeedFooter = true;
|
||||
|
||||
String[] tag = search.split("\\s+");
|
||||
try {
|
||||
for (int i = 0; i < tag.length; i++)
|
||||
tag[i] = URLEncoder.encode(tag[i], "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {}
|
||||
|
||||
ub.addQuery("f_search", Utils.join(tag, '+'));
|
||||
}
|
||||
|
||||
// Add page
|
||||
if (page != 0) {
|
||||
ub.addQuery("page", page);
|
||||
}
|
||||
|
||||
// Add foot
|
||||
if (isNeedFooter) ub.addQuery("f_apply", "Apply+Filter");
|
||||
|
||||
// Add advance search
|
||||
if (isAdvance()) {
|
||||
ub.addQuery("advsearch", "1");
|
||||
if((advsearchType & SNAME) != 0) ub.addQuery("f_sname", "on");
|
||||
if((advsearchType & STAGS) != 0) ub.addQuery("f_stags", "on");
|
||||
if((advsearchType & SDESC) != 0) ub.addQuery("f_sdesc", "on");
|
||||
if((advsearchType & STORR) != 0) ub.addQuery("f_storr", "on");
|
||||
if((advsearchType & STO) != 0) ub.addQuery("f_sto", "on");
|
||||
if((advsearchType & STD1) != 0) ub.addQuery("f_sdt1", "on");
|
||||
if((advsearchType & STD2) != 0) ub.addQuery("f_sdt2", "on");
|
||||
if((advsearchType & SH) != 0) ub.addQuery("f_sh", "on");
|
||||
|
||||
// Set min star
|
||||
if (isMinRating()) {
|
||||
ub.addQuery("f_sr", "on");
|
||||
ub.addQuery("f_srdd", minRating);
|
||||
}
|
||||
}
|
||||
return ub.build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
switch (mMode) {
|
||||
case MODE_NORMAL:
|
||||
case MODE_UPLOADER:
|
||||
return search;
|
||||
case MODE_TAG:
|
||||
return mTag;
|
||||
case MODE_POPULAR:
|
||||
case MODE_IMAGE_SEARCH:
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class LofiGalleryDetail extends LofiGalleryInfo
|
||||
implements LofiDetailImpl {
|
||||
public int previewPageNum;
|
||||
public int previewPerPage;
|
||||
private final List<PreviewList> previewLists = new ArrayList<PreviewList>();
|
||||
|
||||
public LofiGalleryDetail(GalleryInfo galleryInfo) {
|
||||
this(new LofiGalleryInfo(galleryInfo));
|
||||
}
|
||||
|
||||
public LofiGalleryDetail(LofiGalleryInfo lofiGalleryInfo) {
|
||||
gid = lofiGalleryInfo.gid;
|
||||
token = lofiGalleryInfo.token;
|
||||
title = lofiGalleryInfo.title;
|
||||
posted = lofiGalleryInfo.posted;
|
||||
category = lofiGalleryInfo.category;
|
||||
thumb = lofiGalleryInfo.thumb;
|
||||
uploader = lofiGalleryInfo.uploader;
|
||||
rating = lofiGalleryInfo.rating;
|
||||
simpleLanguage = lofiGalleryInfo.simpleLanguage;
|
||||
lofiTags = lofiGalleryInfo.lofiTags;
|
||||
|
||||
previewPageNum = Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getGid() {
|
||||
return gid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPreviewPageNum() {
|
||||
return previewPageNum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPreviewPageNum(int pageNum) {
|
||||
previewPageNum = pageNum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPreviewPerPage() {
|
||||
return previewPerPage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreviewList getPreview(int page) {
|
||||
if (page >= 0 && page < previewLists.size())
|
||||
return previewLists.get(page);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPreview(int page, PreviewList previewList) {
|
||||
if (page >= 0 && page < previewLists.size())
|
||||
previewLists.set(page, previewList);
|
||||
else if (page == previewLists.size())
|
||||
previewLists.add(previewList);
|
||||
else
|
||||
; // Do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getTags() {
|
||||
return lofiTags;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo toGalleryInfo() {
|
||||
return new GalleryInfo(this);
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
public class LofiGalleryInfo extends GalleryInfo {
|
||||
|
||||
/**
|
||||
* It could be null, please check before use.
|
||||
*/
|
||||
public String[] lofiTags;
|
||||
|
||||
public static final Parcelable.Creator<LofiGalleryInfo> CREATOR =
|
||||
new Parcelable.Creator<LofiGalleryInfo>() {
|
||||
@Override
|
||||
public LofiGalleryInfo createFromParcel(Parcel source) {
|
||||
int length;
|
||||
|
||||
LofiGalleryInfo p = new LofiGalleryInfo();
|
||||
p.gid = source.readInt();
|
||||
p.token = source.readString();
|
||||
p.title = source.readString();
|
||||
p.posted = source.readString();
|
||||
p.category = source.readInt();
|
||||
p.thumb = source.readString();
|
||||
p.uploader = source.readString();
|
||||
p.rating = source.readFloat();
|
||||
p.simpleLanguage = source.readString();
|
||||
|
||||
length = source.readInt();
|
||||
if (length > 0) {
|
||||
p.lofiTags = new String[length];
|
||||
for (int i = 0; i < length; i++)
|
||||
p.lofiTags[i] = source.readString();
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LofiGalleryInfo[] newArray(int size) {
|
||||
return new LofiGalleryInfo[size];
|
||||
}
|
||||
};
|
||||
|
||||
public LofiGalleryInfo() {}
|
||||
|
||||
public LofiGalleryInfo(GalleryInfo galleryInfo) {
|
||||
gid = galleryInfo.gid;
|
||||
token = galleryInfo.token;
|
||||
title = galleryInfo.title;
|
||||
posted = galleryInfo.posted;
|
||||
category = galleryInfo.category;
|
||||
thumb = galleryInfo.thumb;
|
||||
uploader = galleryInfo.uploader;
|
||||
rating = galleryInfo.rating;
|
||||
simpleLanguage = galleryInfo.simpleLanguage;
|
||||
lofiTags = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
|
||||
int length = lofiTags == null ? 0 : lofiTags.length;
|
||||
dest.writeInt(length);
|
||||
for (int i = 0; i < length; i++)
|
||||
dest.writeString(lofiTags[i]);
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.ImageLoader;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.ui.GalleryActivity;
|
||||
import com.hippo.ehviewer.widget.SimpleGridLayout;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class NormalPreviewList extends PreviewList{
|
||||
|
||||
public class Item {
|
||||
public int xOffset;
|
||||
public int yOffset;
|
||||
public int width;
|
||||
public int height;
|
||||
public String url;
|
||||
|
||||
public Item(int xOffset, int yOffset, int width, int height, String url) {
|
||||
this.xOffset = xOffset;
|
||||
this.yOffset = yOffset;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.url = url;
|
||||
}
|
||||
}
|
||||
|
||||
public class Row {
|
||||
public String imageUrl;
|
||||
public ArrayList<Item> itemArray = new ArrayList<Item>();
|
||||
public int startIndex;
|
||||
public Row(String imageUrl) {
|
||||
this.imageUrl = imageUrl;
|
||||
}
|
||||
|
||||
public void addItem(int xOffset, int yOffset, int width, int height,
|
||||
String url) {
|
||||
itemArray.add(new Item(xOffset, yOffset, width, height, url));
|
||||
}
|
||||
}
|
||||
|
||||
private Row curRow;
|
||||
public ArrayList<Row> rowArray = new ArrayList<Row>();
|
||||
|
||||
public void addItem(String imageUrl, String xOffset, String yOffset, String width, String height,
|
||||
String url) {
|
||||
if (curRow == null) {
|
||||
curRow = new Row(imageUrl);
|
||||
curRow.startIndex = 0;
|
||||
rowArray.add(curRow);
|
||||
} else if (!curRow.imageUrl.equals(imageUrl)) {
|
||||
Row lastRow = curRow;
|
||||
curRow = new Row(imageUrl);
|
||||
curRow.startIndex = lastRow.startIndex + lastRow.itemArray.size();
|
||||
rowArray.add(curRow);
|
||||
}
|
||||
|
||||
curRow.addItem(Integer.parseInt(xOffset),
|
||||
Integer.parseInt(yOffset), Integer.parseInt(width),
|
||||
Integer.parseInt(height), url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
int sum = 0;
|
||||
for (Row row : rowArray)
|
||||
sum += row.itemArray.size();
|
||||
return sum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPageUrl(int index) {
|
||||
for (Row row : rowArray) {
|
||||
if (index < row.startIndex + row.itemArray.size() && index >= row.startIndex)
|
||||
return row.itemArray.get(index - row.startIndex).url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO reuse the TextView in AutoWrapLayout
|
||||
@SuppressLint("InflateParams")
|
||||
@Override
|
||||
public void addPreview(SimpleGridLayout viewGroup) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
viewGroup.removeAllViews();
|
||||
LayoutInflater inflater = LayoutInflater.from(mActivity);
|
||||
int index = mTargetPage * mPi.getPreviewPerPage(); // it is display index
|
||||
int rowIndex = 0;
|
||||
for (NormalPreviewList.Row row : rowArray) {
|
||||
for (int i = 0; i < row.itemArray.size(); i++) {
|
||||
View view = inflater.inflate(R.layout.preview_item, null);
|
||||
|
||||
((TextView)view.findViewById(R.id.text)).setText(String.valueOf(index + 1));
|
||||
|
||||
final int _index = index;
|
||||
view.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
// Add to read in Data
|
||||
Intent intent = new Intent(mActivity,
|
||||
GalleryActivity.class);
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mPi.toGalleryInfo());
|
||||
intent.putExtra(GalleryActivity.KEY_START_INDEX, _index);
|
||||
mActivity.startActivity(intent);
|
||||
}
|
||||
});
|
||||
|
||||
viewGroup.addView(view);
|
||||
index++;
|
||||
}
|
||||
// TODO I need a better key
|
||||
ImageLoader.getInstance(mActivity).add(row.imageUrl, mPi.getGid() +
|
||||
"-preview-" + mTargetPage + "-" + rowIndex,
|
||||
new PreviewImageGetListener(viewGroup, rowIndex));
|
||||
rowIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
private class PreviewImageGetListener implements ImageLoader.OnGetImageListener {
|
||||
private final SimpleGridLayout mViewGroup;
|
||||
private final int mRowIndex;
|
||||
|
||||
public PreviewImageGetListener(SimpleGridLayout viewGroup, int rowIndex) {
|
||||
mViewGroup = viewGroup;
|
||||
mRowIndex = rowIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGetImage(String key, Bitmap bmp, int state) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
if (bmp == null) {
|
||||
mHolder.onGetPreviewImageFailure();
|
||||
} else {
|
||||
int maxWidth = bmp.getWidth();
|
||||
int maxHeight = bmp.getHeight();
|
||||
|
||||
NormalPreviewList.Row row = rowArray.get(mRowIndex);
|
||||
int i = row.startIndex;
|
||||
for(Item item : row.itemArray) {
|
||||
|
||||
if (item.xOffset + item.width > maxWidth) {
|
||||
item.width = maxWidth - item.xOffset;
|
||||
if (item.width <= 0) {
|
||||
// Bad area
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (item.yOffset + item.height > maxHeight) {
|
||||
item.height = maxHeight - item.yOffset;
|
||||
if (item.height <= 0) {
|
||||
// Bad area
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Bitmap bitmap = Bitmap.createBitmap(bmp, item.xOffset, item.yOffset, item.width, item.height);
|
||||
|
||||
((ImageView)mViewGroup.getChildAt(i).findViewById(R.id.image)).setImageBitmap(bitmap);
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
public interface PreviewImpl {
|
||||
|
||||
public int getGid();
|
||||
|
||||
public String getToken();
|
||||
|
||||
public String getTitle();
|
||||
|
||||
/**
|
||||
* If it is unkonwn, return Integer.MAX_VALUE
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int getPreviewPageNum();
|
||||
|
||||
public int getPreviewPerPage();
|
||||
|
||||
/**
|
||||
* If page is error, return null
|
||||
*
|
||||
* @param page
|
||||
* @return
|
||||
*/
|
||||
public PreviewList getPreview(int page);
|
||||
|
||||
/**
|
||||
*
|
||||
* @param previewList
|
||||
*/
|
||||
public void setPreview(int page, PreviewList previewList);
|
||||
|
||||
public GalleryInfo toGalleryInfo();
|
||||
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.data;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.widget.SimpleGridLayout;
|
||||
|
||||
/**
|
||||
* This interface describe the previews in one page
|
||||
*
|
||||
* @author Hippo
|
||||
*
|
||||
*/
|
||||
public abstract class PreviewList {
|
||||
|
||||
protected PreviewHolder mHolder;
|
||||
protected Activity mActivity;
|
||||
protected PreviewImpl mPi;
|
||||
protected int mTargetPage;
|
||||
|
||||
/**
|
||||
* Add preview to view group
|
||||
* @param viewGroup
|
||||
* @return
|
||||
*/
|
||||
public abstract void addPreview(SimpleGridLayout viewGroup);
|
||||
|
||||
public abstract int size();
|
||||
|
||||
public void setData(PreviewHolder holder, Activity activity, PreviewImpl pi, int targetPage) {
|
||||
mHolder = holder;
|
||||
mActivity = activity;
|
||||
mPi = pi;
|
||||
mTargetPage = targetPage;
|
||||
}
|
||||
|
||||
public void setTargetPage(int targetPage) {
|
||||
mTargetPage = targetPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return page url at target index, null for invalid index
|
||||
* @param index
|
||||
* @return
|
||||
*/
|
||||
public abstract String getPageUrl(int index);
|
||||
|
||||
protected class TextViewWithUrl extends TextView {
|
||||
public String url;
|
||||
|
||||
public TextViewWithUrl(Context context) {
|
||||
super(context);
|
||||
}
|
||||
}
|
||||
|
||||
public interface PreviewHolder {
|
||||
public int getCurPreviewPage();
|
||||
public void onGetPreviewImageFailure();
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.drawable;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
|
||||
public class BatteryDrawable extends Drawable {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = BatteryDrawable.class.getSimpleName();
|
||||
|
||||
public static final int WARN_LIMIT = 15;
|
||||
|
||||
private int mColor = Color.WHITE;
|
||||
private int mWarnColor = Color.RED;
|
||||
private int mElect = -1;
|
||||
private final Paint mPaint;
|
||||
|
||||
private final Rect mTopRect;
|
||||
private final Rect mBottomRect;
|
||||
private final Rect mRightRect;
|
||||
private final Rect mHeadRect;
|
||||
private final Rect mElectRect;
|
||||
private int mStart;
|
||||
private int mStop;
|
||||
|
||||
public BatteryDrawable() {
|
||||
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mPaint.setStyle(Paint.Style.FILL);
|
||||
|
||||
mTopRect = new Rect();
|
||||
mBottomRect = new Rect();
|
||||
mRightRect = new Rect();
|
||||
mHeadRect = new Rect();
|
||||
mElectRect = new Rect();
|
||||
updatePaint();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
int width = bounds.width();
|
||||
int height = bounds.height();
|
||||
int strokeWidth = (int) (Math.sqrt(width * width + height * height) * 0.06f);
|
||||
int turn1 = width * 6 / 7;
|
||||
int turn2 = height / 3;
|
||||
int secBottom = height - strokeWidth;
|
||||
mStart = strokeWidth;
|
||||
mStop = turn1 - strokeWidth;
|
||||
|
||||
mTopRect.set(0, 0, turn1, strokeWidth);
|
||||
mBottomRect.set(0, secBottom, turn1, height);
|
||||
mRightRect.set(turn1 - strokeWidth, strokeWidth, turn1, secBottom);
|
||||
mHeadRect.set(turn1, turn2, width, height - turn2);
|
||||
mElectRect.set(0, strokeWidth, mStop, secBottom);
|
||||
}
|
||||
|
||||
/**
|
||||
* How to draw:<br>
|
||||
* |------------------------------|<br>
|
||||
* |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|<br>
|
||||
* |------------------------------|---|<br>
|
||||
* |/////////////////| |//|\\\|<br>
|
||||
* |/////////////////| |//|\\\|<br>
|
||||
* |------------------------------|---|<br>
|
||||
* |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|<br>
|
||||
* |------------------------------|
|
||||
*/
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
if (mElect == -1)
|
||||
return;
|
||||
|
||||
mElectRect.right = MathUtils.lerp(mStart, mStop, mElect / 100.0f);
|
||||
|
||||
canvas.drawRect(mTopRect, mPaint);
|
||||
canvas.drawRect(mBottomRect, mPaint);
|
||||
canvas.drawRect(mRightRect, mPaint);
|
||||
canvas.drawRect(mHeadRect, mPaint);
|
||||
canvas.drawRect(mElectRect, mPaint);
|
||||
}
|
||||
|
||||
private boolean isWarn() {
|
||||
return mElect <= WARN_LIMIT;
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
if (mColor == color)
|
||||
return;
|
||||
|
||||
mColor = color;
|
||||
if (!isWarn()) {
|
||||
mPaint.setColor(mColor);
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
public void setWarnColor(int color) {
|
||||
if (mWarnColor == color)
|
||||
return;
|
||||
|
||||
mWarnColor = color;
|
||||
if (isWarn()) {
|
||||
mPaint.setColor(mWarnColor);
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
public void setElect(int elect) {
|
||||
if (mElect == elect)
|
||||
return;
|
||||
|
||||
mElect = elect;
|
||||
updatePaint();
|
||||
}
|
||||
|
||||
public void setElect(int elect, boolean warn) {
|
||||
if (mElect == elect)
|
||||
return;
|
||||
|
||||
mElect = elect;
|
||||
updatePaint(warn);
|
||||
}
|
||||
|
||||
private void updatePaint() {
|
||||
updatePaint(isWarn());
|
||||
}
|
||||
|
||||
private void updatePaint(boolean warn) {
|
||||
if (warn)
|
||||
mPaint.setColor(mWarnColor);
|
||||
else
|
||||
mPaint.setColor(mColor);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return PixelFormat.TRANSLUCENT;
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.drawable;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
public class FreeMaterialDrawable extends Drawable {
|
||||
|
||||
private static final String TAG = FreeMaterialDrawable.class.getSimpleName();
|
||||
|
||||
private static final int MAX_SPRITE_NUM = 6;
|
||||
|
||||
private static final int SPRITE_SHAPE_RECTANGLE = 0;
|
||||
private static final int SPRITE_SHAPE_ROUND = 1;
|
||||
private static final int SPRITE_SHAPE_MAX = 2;
|
||||
|
||||
private boolean mKeepTop;
|
||||
private int mBgIndex;
|
||||
private int mBgColor;
|
||||
private final Paint mPaint;
|
||||
private int mSpriteNum;
|
||||
private final Sprite[] mSpriteArray = new Sprite[MAX_SPRITE_NUM];
|
||||
|
||||
private static final int[] sColorArray = new int[] {
|
||||
0xff9c27b0, 0xff673ab7,
|
||||
0xff3f51b5, 0xff2196f3, 0xff03a9f4, 0xff00bcd4,
|
||||
0xff4caf50
|
||||
};
|
||||
|
||||
public FreeMaterialDrawable () {
|
||||
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
mPaint.setStyle(Paint.Style.FILL);
|
||||
mPaint.setShadowLayer(Ui.dp2pix(3), 0, 0, 0x8a000000);
|
||||
}
|
||||
|
||||
public FreeMaterialDrawable setBgIndex(int bgIndex) {
|
||||
mBgIndex = bgIndex;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FreeMaterialDrawable setKeepTop(boolean keepTop) {
|
||||
mKeepTop = keepTop;
|
||||
return this;
|
||||
}
|
||||
|
||||
private int getColor(int[] copyOfColorArray) {
|
||||
int index = MathUtils.random(0, copyOfColorArray.length);
|
||||
int color = copyOfColorArray[index];
|
||||
while (color == -1)
|
||||
color = copyOfColorArray[++index < copyOfColorArray.length ? index : (index = 0)];
|
||||
copyOfColorArray[index] = -1;
|
||||
return color;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
int w = bounds.width();
|
||||
int h = bounds.height();
|
||||
Sprite s;
|
||||
int[] copyOfColorArray = Arrays.copyOf(sColorArray, sColorArray.length);
|
||||
if (mBgIndex >= 0) {
|
||||
mBgColor = copyOfColorArray[mBgIndex];
|
||||
copyOfColorArray[mBgIndex] = -1;
|
||||
} else {
|
||||
mBgColor = getColor(copyOfColorArray);
|
||||
}
|
||||
mSpriteNum = MathUtils.random(4, MAX_SPRITE_NUM + 1);
|
||||
for (int i = 0; i < mSpriteNum; i++) {
|
||||
switch (SPRITE_SHAPE_ROUND) {//MathUtils.random(0, SPRITE_SHAPE_MAX)) {
|
||||
case SPRITE_SHAPE_RECTANGLE:
|
||||
s = new Rectangle(w, h, getColor(copyOfColorArray));
|
||||
break;
|
||||
default:
|
||||
case SPRITE_SHAPE_ROUND:
|
||||
s = new Round(w, h, getColor(copyOfColorArray));
|
||||
break;
|
||||
}
|
||||
mSpriteArray[i] = s;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
canvas.drawColor(mBgColor);
|
||||
|
||||
for (int i = 0; i < mSpriteNum; i++)
|
||||
mSpriteArray[i].draw(canvas, mPaint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return PixelFormat.OPAQUE;
|
||||
}
|
||||
|
||||
private abstract class Sprite {
|
||||
|
||||
private final int mColor;
|
||||
|
||||
public Sprite(int w, int h, int color) {
|
||||
mColor = color;
|
||||
}
|
||||
|
||||
public void draw(Canvas canvas, Paint paint) {
|
||||
paint.setColor(mColor);
|
||||
doDraw(canvas, paint);
|
||||
}
|
||||
|
||||
public abstract void doDraw(Canvas canvas, Paint paint);
|
||||
}
|
||||
|
||||
private class Rectangle extends Sprite {
|
||||
|
||||
private final int left;
|
||||
private final int top;
|
||||
private final int right;
|
||||
private final int bottom;
|
||||
|
||||
public Rectangle(int w, int h, int color) {
|
||||
super(w, h, color);
|
||||
|
||||
int width = MathUtils.random(w / 4, w / 2);
|
||||
int height = MathUtils.random(h / 4, h / 2);
|
||||
left = MathUtils.random(w - width / 2);
|
||||
top = MathUtils.random(h - height / 2);
|
||||
right = left + width;
|
||||
bottom = top + height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doDraw(Canvas canvas, Paint paint) {
|
||||
canvas.drawRect(left, top, right, bottom, paint);
|
||||
}
|
||||
}
|
||||
|
||||
private class Round extends Sprite {
|
||||
|
||||
int mX, mY, mRadius;
|
||||
|
||||
public Round(int w, int h, int color) {
|
||||
super(w, h, color);
|
||||
|
||||
int t = (w + h) / 2;
|
||||
mRadius = MathUtils.random(t / 8, t / 4);
|
||||
mX = MathUtils.random(w);
|
||||
mY = MathUtils.random(mKeepTop ? mRadius + 10 : 0, h);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doDraw(Canvas canvas, Paint paint) {
|
||||
canvas.drawCircle(mX, mY, mRadius, paint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,695 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Balys Valentukevicius
|
||||
*
|
||||
* 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.drawable;
|
||||
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Paint.Style;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.drawable.Animatable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Bundle;
|
||||
import android.util.Property;
|
||||
import android.util.TypedValue;
|
||||
import android.view.animation.DecelerateInterpolator;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
|
||||
public class MaterialIndicatorDrawable extends Drawable implements Animatable {
|
||||
|
||||
private static final String STATE_KEY = "material_menu_icon_state";
|
||||
|
||||
public enum IconState {
|
||||
BURGER, ARROW
|
||||
}
|
||||
|
||||
public enum AnimationState {
|
||||
BURGER_ARROW;
|
||||
|
||||
public IconState getFirstState() {
|
||||
switch (this) {
|
||||
case BURGER_ARROW:
|
||||
return IconState.BURGER;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public IconState getSecondState() {
|
||||
switch (this) {
|
||||
case BURGER_ARROW:
|
||||
return IconState.ARROW;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum Stroke {
|
||||
/**
|
||||
* 3 dip
|
||||
*/
|
||||
REGULAR(3),
|
||||
/**
|
||||
* 2 dip
|
||||
*/
|
||||
THIN(2),
|
||||
/**
|
||||
* 1 dip
|
||||
*/
|
||||
EXTRA_THIN(1);
|
||||
|
||||
private final int strokeWidth;
|
||||
|
||||
Stroke(int strokeWidth) {
|
||||
this.strokeWidth = strokeWidth;
|
||||
}
|
||||
|
||||
protected static Stroke valueOf(int strokeWidth) {
|
||||
switch (strokeWidth) {
|
||||
case 3:
|
||||
return REGULAR;
|
||||
case 2:
|
||||
return THIN;
|
||||
case 1:
|
||||
return EXTRA_THIN;
|
||||
default:
|
||||
return THIN;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final int DEFAULT_COLOR = Color.WHITE;
|
||||
public static final int DEFAULT_SCALE = 1;
|
||||
public static final int DEFAULT_TRANSFORM_DURATION = 800;
|
||||
public static final int DEFAULT_PRESSED_DURATION = 400;
|
||||
|
||||
private static final int BASE_DRAWABLE_WIDTH = 40;
|
||||
private static final int BASE_DRAWABLE_HEIGHT = 40;
|
||||
private static final int BASE_ICON_WIDTH = 20;
|
||||
private static final int BASE_CIRCLE_RADIUS = 18;
|
||||
|
||||
private static final float ARROW_MID_LINE_ANGLE = 180;
|
||||
private static final float ARROW_TOP_LINE_ANGLE = 135;
|
||||
private static final float ARROW_BOT_LINE_ANGLE = 225;
|
||||
|
||||
private static final float TRANSFORMATION_START = 0;
|
||||
private static final float TRANSFORMATION_MID = 1.0f;
|
||||
private static final float TRANSFORMATION_END = 2.0f;
|
||||
|
||||
private static final int DEFAULT_CIRCLE_ALPHA = 200;
|
||||
|
||||
private final float diph;
|
||||
private final float dip1;
|
||||
private final float dip2;
|
||||
private final float dip3;
|
||||
private final float dip4;
|
||||
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final float strokeWidth;
|
||||
private final float iconWidth;
|
||||
private final float topPadding;
|
||||
private final float sidePadding;
|
||||
private final float circleRadius;
|
||||
|
||||
private final Stroke stroke;
|
||||
|
||||
private final Object lock = new Object();
|
||||
|
||||
private final Paint gridPaint = new Paint();
|
||||
private final Paint iconPaint = new Paint();
|
||||
private final Paint circlePaint = new Paint();
|
||||
|
||||
private float transformationValue = 0f;
|
||||
private float pressedProgressValue = 0f;
|
||||
private boolean transformationRunning = false;
|
||||
|
||||
private IconState currentIconState = IconState.BURGER;
|
||||
private AnimationState animationState = AnimationState.BURGER_ARROW;
|
||||
|
||||
private IconState animatingIconState;
|
||||
private boolean drawTouchCircle;
|
||||
private boolean neverDrawTouch;
|
||||
private boolean rtlEnabled;
|
||||
|
||||
private ObjectAnimator transformation;
|
||||
private ObjectAnimator pressedCircle;
|
||||
|
||||
private MaterialMenuState materialMenuState;
|
||||
|
||||
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke) {
|
||||
this(context, color, stroke, DEFAULT_SCALE, DEFAULT_TRANSFORM_DURATION, DEFAULT_PRESSED_DURATION);
|
||||
}
|
||||
|
||||
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke, int transformDuration, int pressedDuration) {
|
||||
this(context, color, stroke, DEFAULT_SCALE, transformDuration, pressedDuration);
|
||||
}
|
||||
|
||||
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke, int scale, int transformDuration, int pressedDuration) {
|
||||
Resources resources = context.getResources();
|
||||
// convert each separately due to various densities
|
||||
this.dip1 = dpToPx(resources, 1) * scale;
|
||||
this.dip2 = dpToPx(resources, 2) * scale;
|
||||
this.dip3 = dpToPx(resources, 3) * scale;
|
||||
this.dip4 = dpToPx(resources, 4) * scale;
|
||||
this.diph = dip1 / 2;
|
||||
|
||||
this.stroke = stroke;
|
||||
this.width = (int) (dpToPx(resources, BASE_DRAWABLE_WIDTH) * scale);
|
||||
this.height = (int) (dpToPx(resources, BASE_DRAWABLE_HEIGHT) * scale);
|
||||
this.iconWidth = dpToPx(resources, BASE_ICON_WIDTH) * scale;
|
||||
this.circleRadius = dpToPx(resources, BASE_CIRCLE_RADIUS) * scale;
|
||||
this.strokeWidth = dpToPx(resources, stroke.strokeWidth) * scale;
|
||||
|
||||
this.sidePadding = (width - iconWidth) / 2;
|
||||
this.topPadding = (height - 5 * dip3) / 2;
|
||||
|
||||
initPaint(color);
|
||||
initAnimations(transformDuration, pressedDuration);
|
||||
|
||||
materialMenuState = new MaterialMenuState();
|
||||
}
|
||||
|
||||
private MaterialIndicatorDrawable(int color, Stroke stroke, long transformDuration, long pressedDuration,
|
||||
int width, int height, float iconWidth, float circleRadius, float strokeWidth, float dip1
|
||||
) {
|
||||
this.dip1 = dip1;
|
||||
this.dip2 = dip1 * 2;
|
||||
this.dip3 = dip1 * 3;
|
||||
this.dip4 = dip1 * 4;
|
||||
this.diph = dip1 / 2;
|
||||
this.stroke = stroke;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.iconWidth = iconWidth;
|
||||
this.circleRadius = circleRadius;
|
||||
this.strokeWidth = strokeWidth;
|
||||
this.sidePadding = (width - iconWidth) / 2;
|
||||
this.topPadding = (height - 5 * dip3) / 2;
|
||||
|
||||
initPaint(color);
|
||||
initAnimations((int) transformDuration, (int) pressedDuration);
|
||||
|
||||
materialMenuState = new MaterialMenuState();
|
||||
}
|
||||
|
||||
private void initPaint(int color) {
|
||||
gridPaint.setAntiAlias(false);
|
||||
gridPaint.setColor(Color.GREEN);
|
||||
gridPaint.setStrokeWidth(1);
|
||||
|
||||
iconPaint.setAntiAlias(true);
|
||||
iconPaint.setStyle(Style.STROKE);
|
||||
iconPaint.setStrokeWidth(strokeWidth);
|
||||
iconPaint.setColor(color);
|
||||
|
||||
circlePaint.setAntiAlias(true);
|
||||
circlePaint.setStyle(Style.FILL);
|
||||
circlePaint.setColor(color);
|
||||
circlePaint.setAlpha(DEFAULT_CIRCLE_ALPHA);
|
||||
|
||||
setBounds(0, 0, width, height);
|
||||
}
|
||||
|
||||
/*
|
||||
* Drawing
|
||||
*/
|
||||
|
||||
@Override public void draw(Canvas canvas) {
|
||||
final float ratio = transformationValue <= 1 ? transformationValue : 2 - transformationValue;
|
||||
|
||||
if (rtlEnabled) {
|
||||
canvas.save();
|
||||
canvas.scale(-1, 1, 0, 0);
|
||||
canvas.translate(-getIntrinsicWidth(), 0);
|
||||
}
|
||||
|
||||
drawTopLine(canvas, ratio);
|
||||
drawMiddleLine(canvas, ratio);
|
||||
drawBottomLine(canvas, ratio);
|
||||
|
||||
if (rtlEnabled) {
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
if (drawTouchCircle) drawTouchCircle(canvas);
|
||||
}
|
||||
|
||||
private void drawTouchCircle(Canvas canvas) {
|
||||
canvas.restore();
|
||||
canvas.drawCircle(width / 2, height / 2, pressedProgressValue, circlePaint);
|
||||
}
|
||||
|
||||
private void drawMiddleLine(Canvas canvas, float ratio) {
|
||||
canvas.restore();
|
||||
canvas.save();
|
||||
|
||||
float rotation = 0;
|
||||
float pivotX = width / 2;
|
||||
float pivotY = width / 2;
|
||||
float startX = sidePadding;
|
||||
float startY = topPadding + dip3 / 2 * 5;
|
||||
float stopX = width - sidePadding;
|
||||
float stopY = topPadding + dip3 / 2 * 5;
|
||||
int alpha = 255;
|
||||
|
||||
switch (animationState) {
|
||||
case BURGER_ARROW:
|
||||
// rotate by 180
|
||||
if (isMorphingForward()) {
|
||||
rotation = ratio * ARROW_MID_LINE_ANGLE;
|
||||
} else {
|
||||
rotation = ARROW_MID_LINE_ANGLE + (1 - ratio) * ARROW_MID_LINE_ANGLE;
|
||||
}
|
||||
// shorten one end
|
||||
stopX -= ratio * resolveStrokeModifier(ratio) / 2;
|
||||
break;
|
||||
}
|
||||
|
||||
iconPaint.setAlpha(alpha);
|
||||
canvas.rotate(rotation, pivotX, pivotY);
|
||||
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
|
||||
iconPaint.setAlpha(255);
|
||||
}
|
||||
|
||||
private void drawTopLine(Canvas canvas, float ratio) {
|
||||
canvas.save();
|
||||
|
||||
float rotation = 0, pivotX = 0, pivotY = 0;
|
||||
float rotation2 = 0;
|
||||
// pivot at center of line
|
||||
float pivotX2 = width / 2 + dip3 / 2;
|
||||
float pivotY2 = topPadding + dip2;
|
||||
|
||||
float startX = sidePadding;
|
||||
float startY = topPadding + dip2;
|
||||
float stopX = width - sidePadding;
|
||||
float stopY = topPadding + dip2;
|
||||
int alpha = 255;
|
||||
|
||||
switch (animationState) {
|
||||
case BURGER_ARROW:
|
||||
if (isMorphingForward()) {
|
||||
// rotate until required angle
|
||||
rotation = ratio * ARROW_BOT_LINE_ANGLE;
|
||||
} else {
|
||||
// rotate back to start doing a 360
|
||||
rotation = ARROW_BOT_LINE_ANGLE + (1 - ratio) * ARROW_TOP_LINE_ANGLE;
|
||||
}
|
||||
// rotate by middle
|
||||
pivotX = width / 2;
|
||||
pivotY = height / 2;
|
||||
|
||||
// shorten both ends
|
||||
stopX -= resolveStrokeModifier(ratio);
|
||||
startX += dip3 * ratio;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
iconPaint.setAlpha(alpha);
|
||||
canvas.rotate(rotation, pivotX, pivotY);
|
||||
canvas.rotate(rotation2, pivotX2, pivotY2);
|
||||
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
|
||||
iconPaint.setAlpha(255);
|
||||
}
|
||||
|
||||
private void drawBottomLine(Canvas canvas, float ratio) {
|
||||
canvas.restore();
|
||||
canvas.save();
|
||||
|
||||
float rotation = 0, pivotX = 0, pivotY = 0;
|
||||
float rotation2 = 0;
|
||||
// pivot at center of line
|
||||
float pivotX2 = width / 2 + dip3 / 2;
|
||||
float pivotY2 = height - topPadding - dip2;
|
||||
|
||||
float startX = sidePadding;
|
||||
float startY = height - topPadding - dip2;
|
||||
float stopX = width - sidePadding;
|
||||
float stopY = height - topPadding - dip2;
|
||||
|
||||
switch (animationState) {
|
||||
case BURGER_ARROW:
|
||||
if (isMorphingForward()) {
|
||||
// rotate to required angle
|
||||
rotation = ARROW_TOP_LINE_ANGLE * ratio;
|
||||
} else {
|
||||
// rotate back to start doing a 360
|
||||
rotation = ARROW_TOP_LINE_ANGLE + (1 - ratio) * ARROW_BOT_LINE_ANGLE;
|
||||
}
|
||||
// pivot center of canvas
|
||||
pivotX = width / 2;
|
||||
pivotY = height / 2;
|
||||
|
||||
// shorten both ends
|
||||
stopX = width - sidePadding - resolveStrokeModifier(ratio);
|
||||
startX = sidePadding + dip3 * ratio;
|
||||
break;
|
||||
}
|
||||
|
||||
canvas.rotate(rotation, pivotX, pivotY);
|
||||
canvas.rotate(rotation2, pivotX2, pivotY2);
|
||||
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
|
||||
}
|
||||
|
||||
private boolean isMorphingForward() {
|
||||
return transformationValue <= TRANSFORMATION_MID;
|
||||
}
|
||||
|
||||
private float resolveStrokeModifier(float ratio) {
|
||||
switch (stroke) {
|
||||
case REGULAR:
|
||||
return ratio * dip3;
|
||||
case THIN:
|
||||
return ratio * (dip3 + diph);
|
||||
case EXTRA_THIN:
|
||||
return ratio * dip4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override public void setAlpha(int alpha) {
|
||||
iconPaint.setAlpha(alpha);
|
||||
}
|
||||
|
||||
@Override public void setColorFilter(ColorFilter cf) {
|
||||
iconPaint.setColorFilter(cf);
|
||||
}
|
||||
|
||||
@Override public int getOpacity() {
|
||||
return PixelFormat.TRANSPARENT;
|
||||
}
|
||||
|
||||
/*
|
||||
* Accessor methods
|
||||
*/
|
||||
|
||||
public void setColor(int color) {
|
||||
iconPaint.setColor(color);
|
||||
circlePaint.setColor(color);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public void setTransformationDuration(int duration) {
|
||||
transformation.setDuration(duration);
|
||||
}
|
||||
|
||||
public void setPressedDuration(int duration) {
|
||||
pressedCircle.setDuration(duration);
|
||||
}
|
||||
|
||||
public void setInterpolator(Interpolator interpolator) {
|
||||
transformation.setInterpolator(interpolator);
|
||||
}
|
||||
|
||||
public void setNeverDrawTouch(boolean neverDrawTouch) {
|
||||
this.neverDrawTouch = neverDrawTouch;
|
||||
}
|
||||
|
||||
public void setIconState(IconState iconState) {
|
||||
synchronized (lock) {
|
||||
if (transformationRunning) {
|
||||
transformation.cancel();
|
||||
transformationRunning = false;
|
||||
}
|
||||
|
||||
if (currentIconState == iconState) return;
|
||||
|
||||
switch (iconState) {
|
||||
case BURGER:
|
||||
animationState = AnimationState.BURGER_ARROW;
|
||||
transformationValue = TRANSFORMATION_START;
|
||||
break;
|
||||
case ARROW:
|
||||
animationState = AnimationState.BURGER_ARROW;
|
||||
transformationValue = TRANSFORMATION_MID;
|
||||
break;
|
||||
}
|
||||
currentIconState = iconState;
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
public void animateIconState(IconState state, boolean drawTouch) {
|
||||
synchronized (lock) {
|
||||
if (transformationRunning) {
|
||||
transformation.end();
|
||||
pressedCircle.end();
|
||||
}
|
||||
drawTouchCircle = drawTouch;
|
||||
animatingIconState = state;
|
||||
start();
|
||||
}
|
||||
}
|
||||
|
||||
public IconState setTransformationOffset(AnimationState animationState, float offset) {
|
||||
if (offset < TRANSFORMATION_START || offset > TRANSFORMATION_END) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Value must be between %s and %s", TRANSFORMATION_START, TRANSFORMATION_END)
|
||||
);
|
||||
}
|
||||
|
||||
this.animationState = animationState;
|
||||
|
||||
final boolean isFirstIcon = offset < TRANSFORMATION_MID || offset == TRANSFORMATION_END;
|
||||
|
||||
currentIconState = isFirstIcon ? animationState.getFirstState() : animationState.getSecondState();
|
||||
animatingIconState = isFirstIcon ? animationState.getSecondState() : animationState.getFirstState();
|
||||
|
||||
setTransformationValue(offset);
|
||||
|
||||
return currentIconState;
|
||||
}
|
||||
|
||||
public void setRTLEnabled(boolean rtlEnabled) {
|
||||
this.rtlEnabled = rtlEnabled;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public IconState getIconState() {
|
||||
return currentIconState;
|
||||
}
|
||||
|
||||
/*
|
||||
* Animations
|
||||
*/
|
||||
private final Property<MaterialIndicatorDrawable, Float> transformationProperty
|
||||
= new Property<MaterialIndicatorDrawable, Float>(Float.class, "transformation") {
|
||||
@Override
|
||||
public Float get(MaterialIndicatorDrawable object) {
|
||||
return object.getTransformationValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(MaterialIndicatorDrawable object, Float value) {
|
||||
object.setTransformationValue(value);
|
||||
}
|
||||
};
|
||||
|
||||
private final Property<MaterialIndicatorDrawable, Float> pressedProgressProperty
|
||||
= new Property<MaterialIndicatorDrawable, Float>(Float.class, "pressedProgress") {
|
||||
@Override
|
||||
public Float get(MaterialIndicatorDrawable object) {
|
||||
return object.getPressedProgress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(MaterialIndicatorDrawable object, Float value) {
|
||||
object.setPressedProgress(value);
|
||||
}
|
||||
};
|
||||
|
||||
public Float getTransformationValue() {
|
||||
return transformationValue;
|
||||
}
|
||||
|
||||
public void setTransformationValue(Float value) {
|
||||
this.transformationValue = value;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public Float getPressedProgress() {
|
||||
return pressedProgressValue;
|
||||
}
|
||||
|
||||
public void setPressedProgress(Float value) {
|
||||
this.pressedProgressValue = value;
|
||||
circlePaint.setAlpha((int) (DEFAULT_CIRCLE_ALPHA * (1 - value / (circleRadius * 1.22f))));
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
private void initAnimations(int transformDuration, int pressedDuration) {
|
||||
transformation = ObjectAnimator.ofFloat(this, transformationProperty, 0);
|
||||
transformation.setInterpolator(new DecelerateInterpolator(3));
|
||||
transformation.setDuration(transformDuration);
|
||||
transformation.addListener(new AnimatorListenerAdapter() {
|
||||
@Override public void onAnimationEnd(Animator animation) {
|
||||
transformationRunning = false;
|
||||
setIconState(animatingIconState);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
pressedCircle = ObjectAnimator.ofFloat(this, pressedProgressProperty, 0, 0);
|
||||
pressedCircle.setDuration(pressedDuration);
|
||||
pressedCircle.setInterpolator(new DecelerateInterpolator());
|
||||
pressedCircle.addListener(new AnimatorListenerAdapter() {
|
||||
@Override public void onAnimationEnd(Animator animation) {
|
||||
pressedProgressValue = 0;
|
||||
}
|
||||
|
||||
@Override public void onAnimationCancel(Animator animation) {
|
||||
pressedProgressValue = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean resolveTransformation() {
|
||||
boolean isCurrentBurger = currentIconState == IconState.BURGER;
|
||||
boolean isCurrentArrow = currentIconState == IconState.ARROW;
|
||||
boolean isAnimatingBurger = animatingIconState == IconState.BURGER;
|
||||
boolean isAnimatingArrow = animatingIconState == IconState.ARROW;
|
||||
|
||||
if ((isCurrentBurger && isAnimatingArrow) || (isCurrentArrow && isAnimatingBurger)) {
|
||||
animationState = AnimationState.BURGER_ARROW;
|
||||
return isCurrentBurger;
|
||||
}
|
||||
|
||||
throw new IllegalStateException(
|
||||
String.format("Animating from %s to %s is not supported", currentIconState, animatingIconState)
|
||||
);
|
||||
}
|
||||
|
||||
@Override public void start() {
|
||||
if (transformationRunning || animatingIconState == null || animatingIconState == currentIconState) return;
|
||||
transformationRunning = true;
|
||||
|
||||
final boolean direction = resolveTransformation();
|
||||
transformation.setFloatValues(
|
||||
direction ? TRANSFORMATION_START : TRANSFORMATION_MID,
|
||||
direction ? TRANSFORMATION_MID : TRANSFORMATION_END
|
||||
);
|
||||
transformation.start();
|
||||
|
||||
if (pressedCircle.isRunning()) {
|
||||
pressedCircle.cancel();
|
||||
}
|
||||
if (drawTouchCircle && !neverDrawTouch) {
|
||||
pressedCircle.setFloatValues(0, circleRadius * 1.22f);
|
||||
pressedCircle.start();
|
||||
}
|
||||
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override public void stop() {
|
||||
if (isRunning() && transformation.isRunning()) {
|
||||
transformation.end();
|
||||
} else {
|
||||
transformationRunning = false;
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
@Override public boolean isRunning() {
|
||||
return transformationRunning;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ConstantState getConstantState() {
|
||||
materialMenuState.changingConfigurations = getChangingConfigurations();
|
||||
return materialMenuState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable mutate() {
|
||||
materialMenuState = new MaterialMenuState();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call from {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)} to store current icon state
|
||||
*
|
||||
* @param outState outState
|
||||
*/
|
||||
public void onSaveInstanceState(Bundle outState) {
|
||||
outState.putString(STATE_KEY, currentIconState.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Call from {@link android.app.Activity#onPostCreate(android.os.Bundle)} to restore icon state
|
||||
*
|
||||
* @param state state
|
||||
*/
|
||||
public void syncState(Bundle state) {
|
||||
if (state != null) {
|
||||
String iconStateName = state.getString(STATE_KEY);
|
||||
if (iconStateName == null) {
|
||||
iconStateName = MaterialIndicatorDrawable.IconState.BURGER.name();
|
||||
}
|
||||
setIconState(MaterialIndicatorDrawable.IconState.valueOf(iconStateName));
|
||||
}
|
||||
}
|
||||
|
||||
private final class MaterialMenuState extends ConstantState {
|
||||
private int changingConfigurations;
|
||||
|
||||
private MaterialMenuState() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable newDrawable() {
|
||||
MaterialIndicatorDrawable drawable = new MaterialIndicatorDrawable(
|
||||
circlePaint.getColor(), stroke, transformation.getDuration(),
|
||||
pressedCircle.getDuration(), width, height, iconWidth, circleRadius, strokeWidth, dip1
|
||||
);
|
||||
drawable.setIconState(animatingIconState != null ? animatingIconState : currentIconState);
|
||||
drawable.setRTLEnabled(rtlEnabled);
|
||||
return drawable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getChangingConfigurations() {
|
||||
return changingConfigurations;
|
||||
}
|
||||
}
|
||||
|
||||
static float dpToPx(Resources resources, float dp) {
|
||||
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics());
|
||||
}
|
||||
}
|
||||
@@ -1,446 +0,0 @@
|
||||
package com.hippo.ehviewer.drawable;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Animatable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
// Get from android.graphics.drawable.MaterialProgressDrawable
|
||||
public class MaterialProgressDrawable extends Drawable implements Animatable {
|
||||
private static final TimeInterpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
|
||||
private static final TimeInterpolator END_CURVE_INTERPOLATOR = new EndCurveInterpolator();
|
||||
private static final TimeInterpolator START_CURVE_INTERPOLATOR = new StartCurveInterpolator();
|
||||
|
||||
private static final long ANIMATION_DURATION = 1333;
|
||||
|
||||
private static final int NUM_POINTS = 5;
|
||||
|
||||
private final ArrayList<Animator> mAnimators = new ArrayList<Animator>();
|
||||
|
||||
private final Ring mRing;
|
||||
|
||||
private MaterialProgressState mState;
|
||||
|
||||
private float mRotation;
|
||||
|
||||
private boolean mMutated;
|
||||
|
||||
public MaterialProgressDrawable() {
|
||||
this(new MaterialProgressState(null));
|
||||
}
|
||||
|
||||
public MaterialProgressDrawable(int width, int height, int color, float strokeWidth, float innerRadius) {
|
||||
this(new MaterialProgressState(width, height, color, strokeWidth, innerRadius));
|
||||
}
|
||||
|
||||
private MaterialProgressDrawable(MaterialProgressState state) {
|
||||
mState = state;
|
||||
mRing = new Ring(mCallback);
|
||||
mMutated = false;
|
||||
|
||||
initializeFromState();
|
||||
setupAnimators();
|
||||
}
|
||||
|
||||
private void initializeFromState() {
|
||||
MaterialProgressState state = mState;
|
||||
|
||||
Ring ring = mRing;
|
||||
ring.setStrokeWidth(state.mStrokeWidth);
|
||||
|
||||
int color = state.mColor.getColorForState(getState(), 0);
|
||||
ring.setColor(color);
|
||||
|
||||
float minEdge = Math.min(state.mWidth, state.mHeight);
|
||||
if ((state.mInnerRadius <= 0.0F) || (minEdge < 0.0F)) {
|
||||
ring.setInsets((int) Math.ceil(state.mStrokeWidth / 2.0F));
|
||||
} else {
|
||||
float insets = minEdge / 2.0F - state.mInnerRadius;
|
||||
ring.setInsets(insets);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable mutate() {
|
||||
if ((!mMutated) && (super.mutate() == this)) {
|
||||
mState = new MaterialProgressState(mState);
|
||||
mMutated = true;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onStateChange(int[] state) {
|
||||
boolean changed = super.onStateChange(state);
|
||||
|
||||
int color = mState.mColor.getColorForState(state, 0);
|
||||
if (color != mRing.getColor()) {
|
||||
mRing.setColor(color);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStateful() {
|
||||
return (super.isStateful()) || (mState.mColor.isStateful());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicHeight() {
|
||||
return mState.mHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicWidth() {
|
||||
return mState.mWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas c) {
|
||||
Rect bounds = getBounds();
|
||||
int saveCount = c.save();
|
||||
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
|
||||
mRing.draw(c, bounds);
|
||||
c.restoreToCount(saveCount);
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
mState.mColor = ColorStateList.valueOf(color);
|
||||
mRing.setColor(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
mRing.setAlpha(alpha);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAlpha() {
|
||||
return mRing.getAlpha();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter colorFilter) {
|
||||
mRing.setColorFilter(colorFilter);
|
||||
}
|
||||
|
||||
private void setRotation(float rotation) {
|
||||
mRotation = rotation;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
private float getRotation() {
|
||||
return mRotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return -3;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setVisible(boolean visible, boolean restart) {
|
||||
boolean changed = super.setVisible(visible, restart);
|
||||
if (visible) {
|
||||
if ((changed) || (restart)) {
|
||||
start();
|
||||
}
|
||||
} else {
|
||||
stop();
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
ArrayList<Animator> animators = mAnimators;
|
||||
int N = animators.size();
|
||||
for (int i = 0; i < N; i++) {
|
||||
Animator animator = animators.get(i);
|
||||
if (animator.isRunning()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.KITKAT)
|
||||
public void start() {
|
||||
ArrayList<Animator> animators = mAnimators;
|
||||
int N = animators.size();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
for (int i = 0; i < N; i++) {
|
||||
Animator animator = animators.get(i);
|
||||
if (animator.isPaused())
|
||||
animator.resume();
|
||||
else if (!animator.isRunning())
|
||||
animator.start();
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < N; i++) {
|
||||
Animator animator = animators.get(i);
|
||||
if (!animator.isRunning())
|
||||
animator.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.KITKAT)
|
||||
public void stop() {
|
||||
ArrayList<Animator> animators = mAnimators;
|
||||
int N = animators.size();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
for (int i = 0; i < N; i++) {
|
||||
animators.get(i).pause();
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < N; i++) {
|
||||
animators.get(i).cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setupAnimators() {
|
||||
Ring ring = mRing;
|
||||
|
||||
ObjectAnimator endTrim = ObjectAnimator.ofFloat(ring, "endTrim",
|
||||
new float[] { 0.0F, 0.75F });
|
||||
endTrim.setDuration(ANIMATION_DURATION);
|
||||
endTrim.setInterpolator(START_CURVE_INTERPOLATOR);
|
||||
endTrim.setRepeatCount(-1);
|
||||
endTrim.setRepeatMode(1);
|
||||
|
||||
ObjectAnimator startTrim = ObjectAnimator.ofFloat(ring, "startTrim",
|
||||
new float[] { 0.0F, 0.75F });
|
||||
startTrim.setDuration(ANIMATION_DURATION);
|
||||
startTrim.setInterpolator(END_CURVE_INTERPOLATOR);
|
||||
startTrim.setRepeatCount(-1);
|
||||
startTrim.setRepeatMode(1);
|
||||
|
||||
ObjectAnimator rotation = ObjectAnimator.ofFloat(ring, "rotation",
|
||||
new float[] { 0.0F, 0.25F });
|
||||
rotation.setDuration(ANIMATION_DURATION);
|
||||
rotation.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
rotation.setRepeatCount(-1);
|
||||
rotation.setRepeatMode(1);
|
||||
|
||||
ObjectAnimator groupRotation = ObjectAnimator.ofFloat(this, "rotation",
|
||||
new float[] { 0.0F, 360.0F });
|
||||
groupRotation.setDuration(6665L);
|
||||
groupRotation.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
groupRotation.setRepeatCount(-1);
|
||||
groupRotation.setRepeatMode(1);
|
||||
|
||||
mAnimators.add(endTrim);
|
||||
mAnimators.add(startTrim);
|
||||
mAnimators.add(rotation);
|
||||
mAnimators.add(groupRotation);
|
||||
}
|
||||
|
||||
private final Drawable.Callback mCallback = new Drawable.Callback() {
|
||||
@Override
|
||||
public void invalidateDrawable(Drawable d) {
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scheduleDrawable(Drawable d, Runnable what, long when) {
|
||||
scheduleSelf(what, when);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unscheduleDrawable(Drawable d, Runnable what) {
|
||||
unscheduleSelf(what);
|
||||
}
|
||||
};
|
||||
|
||||
private static class MaterialProgressState extends Drawable.ConstantState {
|
||||
private float mStrokeWidth = 5.0F;
|
||||
private float mInnerRadius = -1.0F;
|
||||
private int mWidth = -1;
|
||||
private int mHeight = -1;
|
||||
private ColorStateList mColor = ColorStateList.valueOf(0);
|
||||
|
||||
public MaterialProgressState(int width, int height, int color, float strokeWidth, float innerRadius) {
|
||||
mWidth = width;
|
||||
mHeight = height;
|
||||
mColor = ColorStateList.valueOf(color);
|
||||
mStrokeWidth = strokeWidth;
|
||||
mInnerRadius = innerRadius;
|
||||
}
|
||||
|
||||
public MaterialProgressState(MaterialProgressState orig) {
|
||||
if (orig != null) {
|
||||
mStrokeWidth = orig.mStrokeWidth;
|
||||
mInnerRadius = orig.mInnerRadius;
|
||||
mWidth = orig.mWidth;
|
||||
mHeight = orig.mHeight;
|
||||
mColor = orig.mColor;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getChangingConfigurations() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable newDrawable() {
|
||||
return new MaterialProgressDrawable(this);
|
||||
}
|
||||
}
|
||||
|
||||
private static class Ring {
|
||||
private final RectF mTempBounds = new RectF();
|
||||
private final Paint mPaint = new Paint();
|
||||
|
||||
private final Drawable.Callback mCallback;
|
||||
|
||||
private float mStartTrim = 0.0F;
|
||||
private float mEndTrim = 0.0F;
|
||||
private float mRotation = 0.0F;
|
||||
private float mStrokeWidth = 5.0F;
|
||||
private float mStrokeInset = 2.5F;
|
||||
|
||||
private int mAlpha = 255;
|
||||
private int mColor = -16777216;
|
||||
|
||||
public Ring(Drawable.Callback callback) {
|
||||
mCallback = callback;
|
||||
|
||||
mPaint.setStrokeCap(Paint.Cap.ROUND);
|
||||
mPaint.setAntiAlias(true);
|
||||
mPaint.setStyle(Paint.Style.STROKE);
|
||||
}
|
||||
|
||||
public void draw(Canvas c, Rect bounds) {
|
||||
RectF arcBounds = mTempBounds;
|
||||
arcBounds.set(bounds);
|
||||
arcBounds.inset(mStrokeInset, mStrokeInset);
|
||||
|
||||
float startAngle = (mStartTrim + mRotation) * 360.0F;
|
||||
float endAngle = (mEndTrim + mRotation) * 360.0F;
|
||||
float sweepAngle = endAngle - startAngle;
|
||||
|
||||
float diameter = Math.min(arcBounds.width(), arcBounds.height());
|
||||
float minAngle = (float) (360.0D / (diameter * 3.141592653589793D));
|
||||
if ((sweepAngle < minAngle) && (sweepAngle > -minAngle)) {
|
||||
sweepAngle = Math.signum(sweepAngle) * minAngle;
|
||||
}
|
||||
|
||||
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
|
||||
}
|
||||
|
||||
public void setColorFilter(ColorFilter filter) {
|
||||
mPaint.setColorFilter(filter);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public ColorFilter getColorFilter() {
|
||||
return mPaint.getColorFilter();
|
||||
}
|
||||
|
||||
public void setAlpha(int alpha) {
|
||||
mAlpha = alpha;
|
||||
mPaint.setColor(mColor & 0xFFFFFF | alpha << 24);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public int getAlpha() {
|
||||
return mAlpha;
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
mColor = color;
|
||||
mPaint.setColor(color & 0xFFFFFF | mAlpha << 24);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public int getColor() {
|
||||
return mColor;
|
||||
}
|
||||
|
||||
public void setStrokeWidth(float strokeWidth) {
|
||||
mStrokeWidth = strokeWidth;
|
||||
mPaint.setStrokeWidth(strokeWidth);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getStrokeWidth() {
|
||||
return mStrokeWidth;
|
||||
}
|
||||
|
||||
public void setStartTrim(float startTrim) {
|
||||
mStartTrim = startTrim;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getStartTrim() {
|
||||
return mStartTrim;
|
||||
}
|
||||
|
||||
public void setEndTrim(float endTrim) {
|
||||
mEndTrim = endTrim;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getEndTrim() {
|
||||
return mEndTrim;
|
||||
}
|
||||
|
||||
public void setRotation(float rotation) {
|
||||
mRotation = rotation;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getRotation() {
|
||||
return mRotation;
|
||||
}
|
||||
|
||||
public void setInsets(float insets) {
|
||||
mStrokeInset = insets;
|
||||
}
|
||||
|
||||
public float getInsets() {
|
||||
return mStrokeInset;
|
||||
}
|
||||
|
||||
private void invalidateSelf() {
|
||||
mCallback.invalidateDrawable(null);
|
||||
}
|
||||
}
|
||||
|
||||
private static class EndCurveInterpolator extends
|
||||
AccelerateDecelerateInterpolator {
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
return super
|
||||
.getInterpolation(Math.max(0.0F, (input - 0.5F) * 2.0F));
|
||||
}
|
||||
}
|
||||
|
||||
private static class StartCurveInterpolator extends
|
||||
AccelerateDecelerateInterpolator {
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
return super.getInterpolation(Math.min(1.0F, input * 2.0F));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.drawable;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
public class OvalDrawable extends Drawable {
|
||||
|
||||
private final Paint mPaint;
|
||||
private final RectF mRectF;
|
||||
|
||||
public OvalDrawable(int color) {
|
||||
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mPaint.setColor(color);
|
||||
mRectF = new RectF();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
mRectF.set(bounds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
canvas.drawOval(mRectF, mPaint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
mPaint.setColor(mPaint.getColor() & 0x00ffffff | (alpha << 24));
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
// Not support
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return PixelFormat.OPAQUE;
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
mPaint.setColor(color);
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.effect;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.graphics.ColorMatrix;
|
||||
import android.graphics.ColorMatrixColorFilter;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
public class DrawableTransition {
|
||||
|
||||
public static void transit(final Drawable drawable, boolean fromDark, long duration) {
|
||||
final AlphaSatColorMatrixEvaluator evaluator = new AlphaSatColorMatrixEvaluator(fromDark);
|
||||
evaluator.setFraction(0.0f);
|
||||
drawable.setColorFilter(new ColorMatrixColorFilter(evaluator.getColorMatrix()));
|
||||
|
||||
ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
|
||||
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation) {
|
||||
float f = (Float) animation.getAnimatedValue();
|
||||
evaluator.setFraction(f);
|
||||
drawable.setColorFilter(new ColorMatrixColorFilter(evaluator.getColorMatrix()));
|
||||
}
|
||||
});
|
||||
animator.setDuration(duration);
|
||||
animator.start();
|
||||
}
|
||||
|
||||
// From rnr.tests.imageloadingpattern.AlphaSatColorMatrixEvaluator
|
||||
// with modification
|
||||
private static class AlphaSatColorMatrixEvaluator {
|
||||
private final ColorMatrix colorMatrix;
|
||||
private final float[] elements = new float[20];
|
||||
private final boolean mFromDark;
|
||||
|
||||
public AlphaSatColorMatrixEvaluator(boolean fromDark) {
|
||||
colorMatrix = new ColorMatrix ();
|
||||
mFromDark = fromDark;
|
||||
}
|
||||
|
||||
public ColorMatrix getColorMatrix() {
|
||||
return colorMatrix;
|
||||
}
|
||||
|
||||
public void setFraction(float fraction) {
|
||||
// There are 4 phases so we multiply fraction by that amount
|
||||
float phase = fraction * 4;
|
||||
|
||||
// Compute the alpha change over period [0, 2]
|
||||
float alpha = Math.min(phase, 2.0f) / 2.0f;
|
||||
elements [19] = Math.round(alpha * 255);
|
||||
|
||||
// We substract to make the picture look darker, it will automatically clamp
|
||||
// This is spread over period [0, 3]
|
||||
final int MaxBlacker = 50;
|
||||
float blackening = Math.round((1 - Math.min(phase, 3.0f) / 3.0f) * MaxBlacker);
|
||||
elements [4] = elements [9] = elements [14] = mFromDark ? -blackening : blackening;
|
||||
|
||||
// Finally we desaturate over [0, 4], taken from ColorMatrix.SetSaturation
|
||||
float invSat = 1 - Math.max(0.2f, fraction);
|
||||
float R = 0.213f * invSat;
|
||||
float G = 0.715f * invSat;
|
||||
float B = 0.072f * invSat;
|
||||
|
||||
elements[0] = R + fraction; elements[1] = G; elements[2] = B;
|
||||
elements[5] = R; elements[6] = G + fraction; elements[7] = B;
|
||||
elements[10] = R; elements[11] = G; elements[12] = B + fraction;
|
||||
|
||||
colorMatrix.set(elements);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,423 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2013 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.effect.ripple;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Paint.Style;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Build;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
|
||||
/**
|
||||
* Draws a Material ripple.
|
||||
*/
|
||||
class Ripple {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = Ripple.class.getSimpleName();
|
||||
|
||||
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
|
||||
private static final Interpolator DECEL_INTERPOLATOR = new LogInterpolator();
|
||||
|
||||
private static final float GLOBAL_SPEED = 1.0f;
|
||||
private static final float WAVE_TOUCH_DOWN_ACCELERATION = 1024.0f * GLOBAL_SPEED;
|
||||
private static final float WAVE_TOUCH_UP_ACCELERATION = 3400.0f * GLOBAL_SPEED;
|
||||
private static final float WAVE_OPACITY_DECAY_VELOCITY = 3.0f / GLOBAL_SPEED;
|
||||
|
||||
private static final long RIPPLE_ENTER_DELAY = 80;
|
||||
|
||||
private final RippleOwner mOwner;
|
||||
|
||||
/** Bounds used for computing max radius. */
|
||||
private final Rect mBounds;
|
||||
|
||||
/** Full-opacity color for drawing this ripple. */
|
||||
private int mColorOpaque;
|
||||
|
||||
/** Maximum ripple radius. */
|
||||
private float mOuterRadius;
|
||||
|
||||
/** Screen density used to adjust pixel-based velocities. */
|
||||
private float mDensity;
|
||||
|
||||
private float mStartingX;
|
||||
private float mStartingY;
|
||||
private float mClampedStartingX;
|
||||
private float mClampedStartingY;
|
||||
|
||||
// Software animators.
|
||||
private ObjectAnimator mAnimRadius;
|
||||
private ObjectAnimator mAnimOpacity;
|
||||
private ObjectAnimator mAnimX;
|
||||
private ObjectAnimator mAnimY;
|
||||
|
||||
// Software rendering properties.
|
||||
private float mOpacity = 1;
|
||||
private float mOuterX;
|
||||
private float mOuterY;
|
||||
|
||||
// Values used to tween between the start and end positions.
|
||||
private float mTweenRadius = 0;
|
||||
private float mTweenX = 0;
|
||||
private float mTweenY = 0;
|
||||
|
||||
/** Whether we have an explicit maximum radius. */
|
||||
private boolean mHasMaxRadius;
|
||||
|
||||
/** Whether we were canceled externally and should avoid self-removal. */
|
||||
private boolean mCanceled;
|
||||
|
||||
/**
|
||||
* Creates a new ripple.
|
||||
*/
|
||||
public Ripple(RippleOwner owner, Rect bounds, float startingX, float startingY) {
|
||||
mOwner = owner;
|
||||
mBounds = bounds;
|
||||
|
||||
mStartingX = startingX;
|
||||
mStartingY = startingY;
|
||||
}
|
||||
|
||||
public void setup(int maxRadius, int color, float density) {
|
||||
mColorOpaque = color | 0xFF000000;
|
||||
mOpacity = Color.alpha(color) / 2 / 255.0f;
|
||||
|
||||
if (maxRadius != RippleOwner.RADIUS_AUTO) {
|
||||
mHasMaxRadius = true;
|
||||
mOuterRadius = maxRadius;
|
||||
} else {
|
||||
final float halfWidth = mBounds.width() / 2.0f;
|
||||
final float halfHeight = mBounds.height() / 2.0f;
|
||||
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
|
||||
}
|
||||
|
||||
mOuterX = 0;
|
||||
mOuterY = 0;
|
||||
mDensity = density;
|
||||
|
||||
clampStartingPosition();
|
||||
}
|
||||
|
||||
private void clampStartingPosition() {
|
||||
final float cX = mBounds.exactCenterX();
|
||||
final float cY = mBounds.exactCenterY();
|
||||
final float dX = mStartingX - cX;
|
||||
final float dY = mStartingY - cY;
|
||||
final float r = mOuterRadius;
|
||||
if (dX * dX + dY * dY > r * r) {
|
||||
// Point is outside the circle, clamp to the circumference.
|
||||
final double angle = Math.atan2(dY, dX);
|
||||
mClampedStartingX = cX + (float) (Math.cos(angle) * r);
|
||||
mClampedStartingY = cY + (float) (Math.sin(angle) * r);
|
||||
} else {
|
||||
mClampedStartingX = mStartingX;
|
||||
mClampedStartingY = mStartingY;
|
||||
}
|
||||
}
|
||||
|
||||
public void onHotspotBoundsChanged() {
|
||||
if (!mHasMaxRadius) {
|
||||
final float halfWidth = mBounds.width() / 2.0f;
|
||||
final float halfHeight = mBounds.height() / 2.0f;
|
||||
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
|
||||
|
||||
clampStartingPosition();
|
||||
}
|
||||
}
|
||||
|
||||
public void setOpacity(float a) {
|
||||
mOpacity = a;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getOpacity() {
|
||||
return mOpacity;
|
||||
}
|
||||
|
||||
public void setRadiusGravity(float r) {
|
||||
mTweenRadius = r;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getRadiusGravity() {
|
||||
return mTweenRadius;
|
||||
}
|
||||
|
||||
public void setXGravity(float x) {
|
||||
mTweenX = x;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getXGravity() {
|
||||
return mTweenX;
|
||||
}
|
||||
|
||||
public void setYGravity(float y) {
|
||||
mTweenY = y;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getYGravity() {
|
||||
return mTweenY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the ripple centered at (0,0) using the specified paint.
|
||||
*/
|
||||
public boolean draw(Canvas c, Paint p) {
|
||||
return drawSoftware(c, p);
|
||||
}
|
||||
|
||||
private boolean drawSoftware(Canvas c, Paint p) {
|
||||
boolean hasContent = false;
|
||||
|
||||
p.setColor(mColorOpaque);
|
||||
final int alpha = MathUtils.clamp((int) (255 * mOpacity + 0.5f), 0, 255);
|
||||
final float radius = MathUtils.lerp(0, mOuterRadius, mTweenRadius);
|
||||
if (alpha > 0 && radius > 0) {
|
||||
final float x = MathUtils.lerp(
|
||||
mClampedStartingX - mBounds.exactCenterX(), mOuterX, mTweenX);
|
||||
final float y = MathUtils.lerp(
|
||||
mClampedStartingY - mBounds.exactCenterY(), mOuterY, mTweenY);
|
||||
p.setAlpha(alpha);
|
||||
p.setStyle(Style.FILL);
|
||||
c.drawCircle(x, y, radius, p);
|
||||
hasContent = true;
|
||||
}
|
||||
|
||||
return hasContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum bounds of the ripple relative to the ripple center.
|
||||
*/
|
||||
public void getBounds(Rect bounds) {
|
||||
final int outerX = (int) mOuterX;
|
||||
final int outerY = (int) mOuterY;
|
||||
final int r = (int) mOuterRadius + 1;
|
||||
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the starting position relative to the drawable bounds. No-op if
|
||||
* the ripple has already entered.
|
||||
*/
|
||||
public void move(float x, float y) {
|
||||
mStartingX = x;
|
||||
mStartingY = y;
|
||||
|
||||
clampStartingPosition();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the enter animation.
|
||||
*/
|
||||
public void enter() {
|
||||
cancel();
|
||||
|
||||
final int radiusDuration = (int)
|
||||
(1000 * Math.sqrt(mOuterRadius / WAVE_TOUCH_DOWN_ACCELERATION * mDensity) + 0.5);
|
||||
|
||||
final ObjectAnimator radius = ObjectAnimator.ofFloat(this, "radiusGravity", 1);
|
||||
radius.setDuration(radiusDuration);
|
||||
radius.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
radius.setStartDelay(RIPPLE_ENTER_DELAY);
|
||||
|
||||
final ObjectAnimator cX = ObjectAnimator.ofFloat(this, "xGravity", 1);
|
||||
cX.setDuration(radiusDuration);
|
||||
cX.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
cX.setStartDelay(RIPPLE_ENTER_DELAY);
|
||||
|
||||
final ObjectAnimator cY = ObjectAnimator.ofFloat(this, "yGravity", 1);
|
||||
cY.setDuration(radiusDuration);
|
||||
cY.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
cY.setStartDelay(RIPPLE_ENTER_DELAY);
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
radius.setAutoCancel(true);
|
||||
cX.setAutoCancel(true);
|
||||
cY.setAutoCancel(true);
|
||||
}
|
||||
|
||||
mAnimRadius = radius;
|
||||
mAnimX = cX;
|
||||
mAnimY = cY;
|
||||
|
||||
// Enter animations always run on the UI thread, since it's unlikely
|
||||
// that anything interesting is happening until the user lifts their
|
||||
// finger.
|
||||
radius.start();
|
||||
cX.start();
|
||||
cY.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the exit animation.
|
||||
*/
|
||||
public void exit() {
|
||||
cancel();
|
||||
|
||||
final float radius = MathUtils.lerp(0, mOuterRadius, mTweenRadius);
|
||||
final float remaining;
|
||||
if (mAnimRadius != null && mAnimRadius.isRunning()) {
|
||||
remaining = mOuterRadius - radius;
|
||||
} else {
|
||||
remaining = mOuterRadius;
|
||||
}
|
||||
|
||||
final int radiusDuration = (int) (1000 * Math.sqrt(remaining / (WAVE_TOUCH_UP_ACCELERATION
|
||||
+ WAVE_TOUCH_DOWN_ACCELERATION) * mDensity) + 0.5);
|
||||
final int opacityDuration = (int) (1000 * 1 / WAVE_OPACITY_DECAY_VELOCITY + 0.5f);
|
||||
|
||||
exitSoftware(radiusDuration, opacityDuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Jump all animations to their end state. The caller is responsible for
|
||||
* removing the ripple from the list of animating ripples.
|
||||
*/
|
||||
public void jump() {
|
||||
mCanceled = true;
|
||||
endSoftwareAnimations();
|
||||
mCanceled = false;
|
||||
}
|
||||
|
||||
private void endSoftwareAnimations() {
|
||||
if (mAnimRadius != null) {
|
||||
mAnimRadius.end();
|
||||
mAnimRadius = null;
|
||||
}
|
||||
|
||||
if (mAnimOpacity != null) {
|
||||
mAnimOpacity.end();
|
||||
mAnimOpacity = null;
|
||||
}
|
||||
|
||||
if (mAnimX != null) {
|
||||
mAnimX.end();
|
||||
mAnimX = null;
|
||||
}
|
||||
|
||||
if (mAnimY != null) {
|
||||
mAnimY.end();
|
||||
mAnimY = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void exitSoftware(int radiusDuration, int opacityDuration) {
|
||||
final ObjectAnimator radiusAnim = ObjectAnimator.ofFloat(this, "radiusGravity", 1);
|
||||
radiusAnim.setDuration(radiusDuration);
|
||||
radiusAnim.setInterpolator(DECEL_INTERPOLATOR);
|
||||
|
||||
final ObjectAnimator xAnim = ObjectAnimator.ofFloat(this, "xGravity", 1);
|
||||
xAnim.setDuration(radiusDuration);
|
||||
xAnim.setInterpolator(DECEL_INTERPOLATOR);
|
||||
|
||||
final ObjectAnimator yAnim = ObjectAnimator.ofFloat(this, "yGravity", 1);
|
||||
yAnim.setDuration(radiusDuration);
|
||||
yAnim.setInterpolator(DECEL_INTERPOLATOR);
|
||||
|
||||
final ObjectAnimator opacityAnim = ObjectAnimator.ofFloat(this, "opacity", 0);
|
||||
opacityAnim.setDuration(opacityDuration);
|
||||
opacityAnim.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
opacityAnim.addListener(mAnimationListener);
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
radiusAnim.setAutoCancel(true);
|
||||
xAnim.setAutoCancel(true);
|
||||
yAnim.setAutoCancel(true);
|
||||
opacityAnim.setAutoCancel(true);
|
||||
}
|
||||
|
||||
mAnimRadius = radiusAnim;
|
||||
mAnimOpacity = opacityAnim;
|
||||
mAnimX = xAnim;
|
||||
mAnimY = yAnim;
|
||||
|
||||
radiusAnim.start();
|
||||
opacityAnim.start();
|
||||
xAnim.start();
|
||||
yAnim.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels all animations. The caller is responsible for removing
|
||||
* the ripple from the list of animating ripples.
|
||||
*/
|
||||
public void cancel() {
|
||||
mCanceled = true;
|
||||
cancelSoftwareAnimations();
|
||||
mCanceled = false;
|
||||
}
|
||||
|
||||
private void cancelSoftwareAnimations() {
|
||||
if (mAnimRadius != null) {
|
||||
mAnimRadius.cancel();
|
||||
mAnimRadius = null;
|
||||
}
|
||||
|
||||
if (mAnimOpacity != null) {
|
||||
mAnimOpacity.cancel();
|
||||
mAnimOpacity = null;
|
||||
}
|
||||
|
||||
if (mAnimX != null) {
|
||||
mAnimX.cancel();
|
||||
mAnimX = null;
|
||||
}
|
||||
|
||||
if (mAnimY != null) {
|
||||
mAnimY.cancel();
|
||||
mAnimY = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void removeSelf() {
|
||||
// The owner will invalidate itself.
|
||||
if (!mCanceled) {
|
||||
mOwner.removeRipple(this);
|
||||
}
|
||||
}
|
||||
|
||||
private void invalidateSelf() {
|
||||
mOwner.invalidateSelf();
|
||||
}
|
||||
|
||||
private final AnimatorListenerAdapter mAnimationListener = new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
removeSelf();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Interpolator with a smooth log deceleration
|
||||
*/
|
||||
private static final class LogInterpolator implements Interpolator {
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
return 1 - (float) Math.pow(400, -input * 1.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* 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.effect.ripple;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Paint.Style;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Build;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
|
||||
/**
|
||||
* Draws a Material ripple.
|
||||
*/
|
||||
class RippleBackground {
|
||||
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
|
||||
|
||||
private static final float GLOBAL_SPEED = 1.0f;
|
||||
private static final float WAVE_OPACITY_DECAY_VELOCITY = 3.0f / GLOBAL_SPEED;
|
||||
private static final float WAVE_OUTER_OPACITY_EXIT_VELOCITY_MAX = 4.5f * GLOBAL_SPEED;
|
||||
private static final float WAVE_OUTER_OPACITY_EXIT_VELOCITY_MIN = 1.5f * GLOBAL_SPEED;
|
||||
private static final float WAVE_OUTER_OPACITY_ENTER_VELOCITY = 10.0f * GLOBAL_SPEED;
|
||||
private static final float WAVE_OUTER_SIZE_INFLUENCE_MAX = 200f;
|
||||
private static final float WAVE_OUTER_SIZE_INFLUENCE_MIN = 40f;
|
||||
|
||||
private final RippleOwner mOwner;
|
||||
|
||||
/** Bounds used for computing max radius. */
|
||||
private final Rect mBounds;
|
||||
|
||||
/** Full-opacity color for drawing this ripple. */
|
||||
private int mColorOpaque;
|
||||
|
||||
/** Maximum alpha value for drawing this ripple. */
|
||||
private int mColorAlpha;
|
||||
|
||||
/** Maximum ripple radius. */
|
||||
private float mOuterRadius;
|
||||
|
||||
/** Screen density used to adjust pixel-based velocities. */
|
||||
private float mDensity;
|
||||
|
||||
// Software animators.
|
||||
private ObjectAnimator mAnimOuterOpacity;
|
||||
|
||||
// Software rendering properties.
|
||||
private float mOuterOpacity = 0;
|
||||
private float mOuterX;
|
||||
private float mOuterY;
|
||||
|
||||
/** Whether we have an explicit maximum radius. */
|
||||
private boolean mHasMaxRadius;
|
||||
|
||||
/**
|
||||
* Creates a new ripple.
|
||||
*/
|
||||
public RippleBackground(RippleOwner owner, Rect bounds) {
|
||||
mOwner = owner;
|
||||
mBounds = bounds;
|
||||
}
|
||||
|
||||
public void setup(int maxRadius, int color, float density) {
|
||||
mColorOpaque = color | 0xFF000000;
|
||||
mColorAlpha = Color.alpha(color) / 2;
|
||||
|
||||
if (maxRadius != RippleOwner.RADIUS_AUTO) {
|
||||
mHasMaxRadius = true;
|
||||
mOuterRadius = maxRadius;
|
||||
} else {
|
||||
final float halfWidth = mBounds.width() / 2.0f;
|
||||
final float halfHeight = mBounds.height() / 2.0f;
|
||||
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
|
||||
}
|
||||
|
||||
mOuterX = 0;
|
||||
mOuterY = 0;
|
||||
mDensity = density;
|
||||
}
|
||||
|
||||
public void onHotspotBoundsChanged() {
|
||||
if (!mHasMaxRadius) {
|
||||
final float halfWidth = mBounds.width() / 2.0f;
|
||||
final float halfHeight = mBounds.height() / 2.0f;
|
||||
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
|
||||
}
|
||||
}
|
||||
|
||||
public void setOuterOpacity(float a) {
|
||||
mOuterOpacity = a;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
public float getOuterOpacity() {
|
||||
return mOuterOpacity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the ripple centered at (0,0) using the specified paint.
|
||||
*/
|
||||
public boolean draw(Canvas c, Paint p) {
|
||||
return drawSoftware(c, p);
|
||||
}
|
||||
|
||||
public boolean shouldDraw() {
|
||||
final int outerAlpha = (int) (mColorAlpha * mOuterOpacity + 0.5f);
|
||||
return outerAlpha > 0 && mOuterRadius > 0;
|
||||
}
|
||||
|
||||
private boolean drawSoftware(Canvas c, Paint p) {
|
||||
boolean hasContent = false;
|
||||
|
||||
p.setColor(mColorOpaque);
|
||||
final int outerAlpha = (int) (mColorAlpha * mOuterOpacity + 0.5f);
|
||||
if (outerAlpha > 0 && mOuterRadius > 0) {
|
||||
p.setAlpha(outerAlpha);
|
||||
p.setStyle(Style.FILL);
|
||||
c.drawCircle(mOuterX, mOuterY, mOuterRadius, p);
|
||||
hasContent = true;
|
||||
}
|
||||
|
||||
return hasContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum bounds of the ripple relative to the ripple center.
|
||||
*/
|
||||
public void getBounds(Rect bounds) {
|
||||
final int outerX = (int) mOuterX;
|
||||
final int outerY = (int) mOuterY;
|
||||
final int r = (int) mOuterRadius + 1;
|
||||
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the enter animation.
|
||||
*/
|
||||
public void enter() {
|
||||
cancel();
|
||||
|
||||
final int outerDuration = (int) (1000 * 1.0f / WAVE_OUTER_OPACITY_ENTER_VELOCITY);
|
||||
final ObjectAnimator outer = ObjectAnimator.ofFloat(this, "outerOpacity", 0, 1);
|
||||
outer.setDuration(outerDuration);
|
||||
outer.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
outer.setAutoCancel(true);
|
||||
}
|
||||
|
||||
mAnimOuterOpacity = outer;
|
||||
|
||||
// Enter animations always run on the UI thread, since it's unlikely
|
||||
// that anything interesting is happening until the user lifts their
|
||||
// finger.
|
||||
outer.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the exit animation.
|
||||
*/
|
||||
public void exit() {
|
||||
cancel();
|
||||
|
||||
// Scale the outer max opacity and opacity velocity based
|
||||
// on the size of the outer radius.
|
||||
final int opacityDuration = (int) (1000 / WAVE_OPACITY_DECAY_VELOCITY + 0.5f);
|
||||
final float outerSizeInfluence = MathUtils.clamp(
|
||||
(mOuterRadius - WAVE_OUTER_SIZE_INFLUENCE_MIN * mDensity)
|
||||
/ (WAVE_OUTER_SIZE_INFLUENCE_MAX * mDensity), 0, 1);
|
||||
final float outerOpacityVelocity = MathUtils.lerp(WAVE_OUTER_OPACITY_EXIT_VELOCITY_MIN,
|
||||
WAVE_OUTER_OPACITY_EXIT_VELOCITY_MAX, outerSizeInfluence);
|
||||
|
||||
// Determine at what time the inner and outer opacity intersect.
|
||||
// inner(t) = mOpacity - t * WAVE_OPACITY_DECAY_VELOCITY / 1000
|
||||
// outer(t) = mOuterOpacity + t * WAVE_OUTER_OPACITY_VELOCITY / 1000
|
||||
final int inflectionDuration = Math.max(0, (int) (1000 * (1 - mOuterOpacity)
|
||||
/ (WAVE_OPACITY_DECAY_VELOCITY + outerOpacityVelocity) + 0.5f));
|
||||
final int inflectionOpacity = (int) (mColorAlpha * (mOuterOpacity
|
||||
+ inflectionDuration * outerOpacityVelocity * outerSizeInfluence / 1000) + 0.5f);
|
||||
|
||||
exitSoftware(opacityDuration, inflectionDuration, inflectionOpacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Jump all animations to their end state. The caller is responsible for
|
||||
* removing the ripple from the list of animating ripples.
|
||||
*/
|
||||
public void jump() {
|
||||
endSoftwareAnimations();
|
||||
}
|
||||
|
||||
private void endSoftwareAnimations() {
|
||||
if (mAnimOuterOpacity != null) {
|
||||
mAnimOuterOpacity.end();
|
||||
mAnimOuterOpacity = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void exitSoftware(int opacityDuration, int inflectionDuration, int inflectionOpacity) {
|
||||
final ObjectAnimator outerOpacityAnim;
|
||||
if (inflectionDuration > 0) {
|
||||
// Outer opacity continues to increase for a bit.
|
||||
outerOpacityAnim = ObjectAnimator.ofFloat(this,
|
||||
"outerOpacity", inflectionOpacity / 255.0f);
|
||||
outerOpacityAnim.setDuration(inflectionDuration);
|
||||
outerOpacityAnim.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
outerOpacityAnim.setAutoCancel(true);
|
||||
}
|
||||
|
||||
// Chain the outer opacity exit animation.
|
||||
final int outerDuration = opacityDuration - inflectionDuration;
|
||||
if (outerDuration > 0) {
|
||||
outerOpacityAnim.addListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
final ObjectAnimator outerFadeOutAnim = ObjectAnimator.ofFloat(
|
||||
RippleBackground.this, "outerOpacity", 0);
|
||||
outerFadeOutAnim.setDuration(outerDuration);
|
||||
outerFadeOutAnim.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
outerFadeOutAnim.setAutoCancel(true);
|
||||
}
|
||||
|
||||
mAnimOuterOpacity = outerFadeOutAnim;
|
||||
|
||||
outerFadeOutAnim.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationCancel(Animator animation) {
|
||||
animation.removeListener(this);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
outerOpacityAnim = ObjectAnimator.ofFloat(this, "outerOpacity", 0);
|
||||
outerOpacityAnim.setDuration(opacityDuration);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
outerOpacityAnim.setAutoCancel(true);
|
||||
}
|
||||
}
|
||||
|
||||
mAnimOuterOpacity = outerOpacityAnim;
|
||||
|
||||
outerOpacityAnim.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all animations. The caller is responsible for removing
|
||||
* the ripple from the list of animating ripples.
|
||||
*/
|
||||
public void cancel() {
|
||||
cancelSoftwareAnimations();
|
||||
}
|
||||
|
||||
private void cancelSoftwareAnimations() {
|
||||
if (mAnimOuterOpacity != null) {
|
||||
mAnimOuterOpacity.cancel();
|
||||
mAnimOuterOpacity = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void invalidateSelf() {
|
||||
mOwner.invalidateSelf();
|
||||
}
|
||||
}
|
||||
@@ -1,579 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* 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.effect.ripple;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.hippo.ehviewer.widget.Hotspotable;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Drawable that shows a ripple effect in response to state changes. The
|
||||
* anchoring position of the ripple for a given state may be specified by
|
||||
* calling {@link #setHotspot(float, float)} with the corresponding state
|
||||
* attribute identifier.
|
||||
* <p>
|
||||
* A touch feedback drawable may contain multiple child layers, including a
|
||||
* special mask layer that is not drawn to the screen. A single layer may be set
|
||||
* as the mask by specifying its android:id value as {@link android.R.id#mask}.
|
||||
* <pre>
|
||||
* <code><!-- A red ripple masked against an opaque rectangle. --/>
|
||||
* <ripple android:color="#ffff0000">
|
||||
* <item android:id="@android:id/mask"
|
||||
* android:drawable="@android:color/white" />
|
||||
* <ripple /></code>
|
||||
* </pre>
|
||||
* <p>
|
||||
* If a mask layer is set, the ripple effect will be masked against that layer
|
||||
* before it is drawn over the composite of the remaining child layers.
|
||||
* <p>
|
||||
* If no mask layer is set, the ripple effect is masked against the composite
|
||||
* of the child layers.
|
||||
* <pre>
|
||||
* <code><!-- A blue ripple drawn atop a black rectangle. --/>
|
||||
* <ripple android:color="#ff00ff00">
|
||||
* <item android:drawable="@android:color/black" />
|
||||
* <ripple />
|
||||
*
|
||||
* <!-- A red ripple drawn atop a drawable resource. --/>
|
||||
* <ripple android:color="#ff00ff00">
|
||||
* <item android:drawable="@drawable/my_drawable" />
|
||||
* <ripple /></code>
|
||||
* </pre>
|
||||
* <p>
|
||||
* If no child layers or mask is specified and the ripple is set as a View
|
||||
* background, the ripple will be drawn atop the first available parent
|
||||
* background within the View's hierarchy. In this case, the drawing region
|
||||
* may extend outside of the Drawable bounds.
|
||||
* <pre>
|
||||
* <code><!-- An unbounded green ripple. --/>
|
||||
* <ripple android:color="#ff0000ff" /></code>
|
||||
* </pre>
|
||||
*
|
||||
* @attr ref android.R.styleable#RippleDrawable_color
|
||||
*/
|
||||
public class RippleDrawable extends Drawable implements RippleOwner, Hotspotable {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = RippleDrawable.class.getSimpleName();
|
||||
|
||||
/** The maximum number of ripples supported. */
|
||||
private static final int MAX_RIPPLES = 10;
|
||||
|
||||
/** Current ripple effect bounds, used to constrain ripple effects. */
|
||||
private final Rect mHotspotBounds = new Rect();
|
||||
|
||||
/** The current background. May be actively animating or pending entry. */
|
||||
private RippleBackground mBackground;
|
||||
|
||||
/** Whether we expect to draw a background when visible. */
|
||||
private boolean mBackgroundActive;
|
||||
|
||||
/** The current ripple. May be actively animating or pending entry. */
|
||||
private Ripple mRipple;
|
||||
|
||||
/** Whether we expect to draw a ripple when visible. */
|
||||
private boolean mRippleActive;
|
||||
|
||||
// Hotspot coordinates that are awaiting activation.
|
||||
private float mPendingX;
|
||||
private float mPendingY;
|
||||
private boolean mHasPending;
|
||||
|
||||
/**
|
||||
* Lazily-created array of actively animating ripples. Inactive ripples are
|
||||
* pruned during draw(). The locations of these will not change.
|
||||
*/
|
||||
private Ripple[] mExitingRipples;
|
||||
private int mExitingRipplesCount = 0;
|
||||
|
||||
/** Paint used to control appearance of ripples. */
|
||||
private Paint mRipplePaint;
|
||||
|
||||
/** Target density of the display into which ripples are drawn. */
|
||||
private final float mDensity = 1.0f;
|
||||
|
||||
/** Whether bounds are being overridden. */
|
||||
private boolean mOverrideBounds;
|
||||
|
||||
/**
|
||||
* Whether the next draw MUST draw something to canvas. Used to work around
|
||||
* a bug in hardware invalidation following a render thread-accelerated
|
||||
* animation.
|
||||
*/
|
||||
private boolean mNeedsDraw;
|
||||
|
||||
private ColorStateList mColor = ColorStateList.valueOf(Color.MAGENTA);
|
||||
|
||||
private int mMaxRadius = RADIUS_AUTO;
|
||||
|
||||
private final Drawable mContent;
|
||||
|
||||
RippleDrawable(ColorStateList color, Drawable content) {
|
||||
setColor(color);
|
||||
|
||||
mContent = content;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
|
||||
public void jumpToCurrentState() {
|
||||
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
|
||||
super.jumpToCurrentState();
|
||||
}
|
||||
|
||||
boolean needsDraw = false;
|
||||
|
||||
if (mRipple != null) {
|
||||
mRipple.jump();
|
||||
}
|
||||
|
||||
if (mBackground != null) {
|
||||
mBackground.jump();
|
||||
}
|
||||
|
||||
needsDraw |= cancelExitingRipples();
|
||||
|
||||
mNeedsDraw = needsDraw;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
private boolean cancelExitingRipples() {
|
||||
final int count = mExitingRipplesCount;
|
||||
final Ripple[] ripples = mExitingRipples;
|
||||
for (int i = 0; i < count; i++) {
|
||||
ripples[i].cancel();
|
||||
}
|
||||
|
||||
if (ripples != null) {
|
||||
Arrays.fill(ripples, 0, count, null);
|
||||
}
|
||||
mExitingRipplesCount = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
mColor.withAlpha(alpha);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAlpha() {
|
||||
return Color.alpha(mColor.getDefaultColor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
//TODO Paint.setColorFilter(filter) ?
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
// Worst-case scenario.
|
||||
return PixelFormat.TRANSLUCENT;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onStateChange(int[] stateSet) {
|
||||
boolean changed = false;
|
||||
if (mContent != null)
|
||||
changed |= mContent.setState(stateSet);
|
||||
|
||||
boolean enabled = false;
|
||||
boolean pressed = false;
|
||||
boolean focused = false;
|
||||
|
||||
for (int state : stateSet) {
|
||||
if (state == android.R.attr.state_enabled) {
|
||||
enabled = true;
|
||||
}
|
||||
if (state == android.R.attr.state_focused) {
|
||||
focused = true;
|
||||
}
|
||||
if (state == android.R.attr.state_pressed) {
|
||||
pressed = true;
|
||||
}
|
||||
}
|
||||
|
||||
setRippleActive(enabled && pressed);
|
||||
setBackgroundActive(focused || (enabled && pressed));
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
private void setRippleActive(boolean active) {
|
||||
if (mRippleActive != active) {
|
||||
mRippleActive = active;
|
||||
if (active) {
|
||||
tryRippleEnter();
|
||||
} else {
|
||||
tryRippleExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setBackgroundActive(boolean active) {
|
||||
if (mBackgroundActive != active) {
|
||||
mBackgroundActive = active;
|
||||
if (active) {
|
||||
tryBackgroundEnter();
|
||||
} else {
|
||||
tryBackgroundExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
super.onBoundsChange(bounds);
|
||||
|
||||
if (!mOverrideBounds) {
|
||||
mHotspotBounds.set(bounds);
|
||||
onHotspotBoundsChanged();
|
||||
}
|
||||
|
||||
if (mContent != null)
|
||||
mContent.setBounds(bounds);
|
||||
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setVisible(boolean visible, boolean restart) {
|
||||
final boolean changed = super.setVisible(visible, restart);
|
||||
|
||||
if (!visible) {
|
||||
clearHotspots();
|
||||
} else if (changed) {
|
||||
// If we just became visible, ensure the background and ripple
|
||||
// visibilities are consistent with their internal states.
|
||||
if (mRippleActive) {
|
||||
tryRippleEnter();
|
||||
}
|
||||
|
||||
if (mBackgroundActive) {
|
||||
tryBackgroundEnter();
|
||||
}
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStateful() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setColor(ColorStateList color) {
|
||||
int alpha = Color.alpha(color.getDefaultColor());
|
||||
mColor = color.withAlpha((int) (alpha * (1 - 0.001f * alpha)));
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHotspot(float x, float y) {
|
||||
if (mRipple == null || mBackground == null) {
|
||||
mPendingX = x;
|
||||
mPendingY = y;
|
||||
mHasPending = true;
|
||||
}
|
||||
|
||||
if (mRipple != null) {
|
||||
mRipple.move(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an active hotspot at the specified location.
|
||||
*/
|
||||
private void tryBackgroundEnter() {
|
||||
if (mBackground == null) {
|
||||
mBackground = new RippleBackground(this, mHotspotBounds);
|
||||
}
|
||||
|
||||
final int color = mColor.getColorForState(getState(), Color.TRANSPARENT);
|
||||
mBackground.setup(mMaxRadius, color, mDensity);
|
||||
mBackground.enter();
|
||||
}
|
||||
|
||||
private void tryBackgroundExit() {
|
||||
if (mBackground != null) {
|
||||
// Don't null out the background, we need it to draw!
|
||||
mBackground.exit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to start an enter animation for the active hotspot. Fails if
|
||||
* there are too many animating ripples.
|
||||
*/
|
||||
private void tryRippleEnter() {
|
||||
if (mExitingRipplesCount >= MAX_RIPPLES) {
|
||||
// This should never happen unless the user is tapping like a maniac
|
||||
// or there is a bug that's preventing ripples from being removed.
|
||||
return;
|
||||
}
|
||||
|
||||
if (mRipple == null) {
|
||||
final float x;
|
||||
final float y;
|
||||
if (mHasPending) {
|
||||
mHasPending = false;
|
||||
x = mPendingX;
|
||||
y = mPendingY;
|
||||
} else {
|
||||
x = mHotspotBounds.exactCenterX();
|
||||
y = mHotspotBounds.exactCenterY();
|
||||
}
|
||||
mRipple = new Ripple(this, mHotspotBounds, x, y);
|
||||
}
|
||||
|
||||
final int color = mColor.getColorForState(getState(), Color.TRANSPARENT);
|
||||
mRipple.setup(mMaxRadius, color, mDensity);
|
||||
mRipple.enter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to start an exit animation for the active hotspot. Fails if
|
||||
* there is no active hotspot.
|
||||
*/
|
||||
private void tryRippleExit() {
|
||||
if (mRipple != null) {
|
||||
if (mExitingRipples == null) {
|
||||
mExitingRipples = new Ripple[MAX_RIPPLES];
|
||||
}
|
||||
mExitingRipples[mExitingRipplesCount++] = mRipple;
|
||||
mRipple.exit();
|
||||
mRipple = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels and removes the active ripple, all exiting ripples, and the
|
||||
* background. Nothing will be drawn after this method is called.
|
||||
*/
|
||||
private void clearHotspots() {
|
||||
boolean needsDraw = false;
|
||||
|
||||
if (mRipple != null) {
|
||||
mRipple.cancel();
|
||||
mRipple = null;
|
||||
}
|
||||
|
||||
if (mBackground != null) {
|
||||
mBackground.cancel();
|
||||
mBackground = null;
|
||||
}
|
||||
|
||||
needsDraw |= cancelExitingRipples();
|
||||
|
||||
mNeedsDraw = needsDraw;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setHotspotBounds(int left, int top, int right, int bottom) {
|
||||
mOverrideBounds = true;
|
||||
mHotspotBounds.set(left, top, right, bottom);
|
||||
|
||||
onHotspotBoundsChanged();
|
||||
}
|
||||
|
||||
/** @hide */
|
||||
public void getHotspotBounds(Rect outRect) {
|
||||
outRect.set(mHotspotBounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies all the animating ripples that the hotspot bounds have changed.
|
||||
*/
|
||||
private void onHotspotBoundsChanged() {
|
||||
final int count = mExitingRipplesCount;
|
||||
final Ripple[] ripples = mExitingRipples;
|
||||
for (int i = 0; i < count; i++) {
|
||||
ripples[i].onHotspotBoundsChanged();
|
||||
}
|
||||
|
||||
if (mRipple != null) {
|
||||
mRipple.onHotspotBoundsChanged();
|
||||
}
|
||||
|
||||
if (mBackground != null) {
|
||||
mBackground.onHotspotBoundsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(@NonNull Canvas canvas) {
|
||||
final boolean drawNonMaskContent = mContent != null;
|
||||
final Rect bounds = getDirtyBounds();
|
||||
final int saveCount = canvas.save(Canvas.CLIP_SAVE_FLAG);
|
||||
canvas.clipRect(bounds);
|
||||
|
||||
// If we have content, draw it into a layer first.
|
||||
if (drawNonMaskContent) {
|
||||
drawContentLayer(canvas, bounds);
|
||||
}
|
||||
|
||||
// If we have a background and a non-opaque mask, draw the masking layer.
|
||||
drawBackgroundLayer(canvas, bounds);
|
||||
|
||||
// If we have ripples and a non-opaque mask, draw the masking layer.
|
||||
drawRippleLayer(canvas, bounds);
|
||||
|
||||
// If we failed to draw anything and we just canceled animations, at
|
||||
// least draw a color so that hardware invalidation works correctly.
|
||||
if (mNeedsDraw) {
|
||||
canvas.drawColor(Color.TRANSPARENT);
|
||||
|
||||
// Request another draw so we can avoid adding a transparent layer
|
||||
// during the next display list refresh.
|
||||
invalidateSelf();
|
||||
}
|
||||
mNeedsDraw = false;
|
||||
|
||||
canvas.restoreToCount(saveCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a ripple from the exiting ripple list.
|
||||
*
|
||||
* @param ripple the ripple to remove
|
||||
*/
|
||||
@Override
|
||||
public void removeRipple(Ripple ripple) {
|
||||
// Ripple ripple ripple ripple. Ripple ripple.
|
||||
final Ripple[] ripples = mExitingRipples;
|
||||
final int count = mExitingRipplesCount;
|
||||
final int index = getRippleIndex(ripple);
|
||||
if (index >= 0) {
|
||||
System.arraycopy(ripples, index + 1, ripples, index, count - (index + 1));
|
||||
ripples[count - 1] = null;
|
||||
mExitingRipplesCount--;
|
||||
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
private int getRippleIndex(Ripple ripple) {
|
||||
final Ripple[] ripples = mExitingRipples;
|
||||
final int count = mExitingRipplesCount;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (ripples[i] == ripple) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void drawContentLayer(Canvas canvas, Rect bounds) {
|
||||
mContent.draw(canvas);
|
||||
}
|
||||
|
||||
private void drawBackgroundLayer(
|
||||
Canvas canvas, Rect bounds) {
|
||||
if (mBackground != null && mBackground.shouldDraw()) {
|
||||
final float x = mHotspotBounds.exactCenterX();
|
||||
final float y = mHotspotBounds.exactCenterY();
|
||||
canvas.translate(x, y);
|
||||
mBackground.draw(canvas, getRipplePaint());
|
||||
canvas.translate(-x, -y);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawRippleLayer(Canvas canvas, Rect bounds) {
|
||||
int restoreTranslate = -1;
|
||||
|
||||
// Translate the canvas to the current hotspot bounds.
|
||||
restoreTranslate = canvas.save();
|
||||
canvas.translate(mHotspotBounds.exactCenterX(), mHotspotBounds.exactCenterY());
|
||||
|
||||
// Draw ripples and update the animating ripples array.
|
||||
final int count = mExitingRipplesCount;
|
||||
final Ripple[] ripples = mExitingRipples;
|
||||
for (int i = 0; i <= count; i++) {
|
||||
final Ripple ripple;
|
||||
if (i < count) {
|
||||
ripple = ripples[i];
|
||||
} else if (mRipple != null) {
|
||||
ripple = mRipple;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
ripple.draw(canvas, getRipplePaint());
|
||||
}
|
||||
|
||||
// Always restore the translation.
|
||||
if (restoreTranslate >= 0) {
|
||||
canvas.restoreToCount(restoreTranslate);
|
||||
}
|
||||
}
|
||||
|
||||
private Paint getRipplePaint() {
|
||||
if (mRipplePaint == null) {
|
||||
mRipplePaint = new Paint();
|
||||
mRipplePaint.setAntiAlias(true);
|
||||
}
|
||||
return mRipplePaint;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Rect getDirtyBounds() {
|
||||
return getBounds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum ripple radius in pixels. The default value of
|
||||
* {@link #RADIUS_AUTO} defines the radius as the distance from the center
|
||||
* of the drawable bounds (or hotspot bounds, if specified) to a corner.
|
||||
*
|
||||
* @param maxRadius the maximum ripple radius in pixels or
|
||||
* {@link #RADIUS_AUTO} to automatically determine the maximum
|
||||
* radius based on the bounds
|
||||
* @see #getMaxRadius()
|
||||
* @see #setHotspotBounds(int, int, int, int)
|
||||
* @hide
|
||||
*/
|
||||
public void setMaxRadius(int maxRadius) {
|
||||
if (maxRadius != RADIUS_AUTO && maxRadius < 0) {
|
||||
throw new IllegalArgumentException("maxRadius must be RADIUS_AUTO or >= 0");
|
||||
}
|
||||
|
||||
mMaxRadius = maxRadius;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the maximum ripple radius in pixels, or {@link #RADIUS_AUTO} if
|
||||
* the radius is determined automatically
|
||||
* @see #setMaxRadius(int)
|
||||
* @hide
|
||||
*/
|
||||
public int getMaxRadius() {
|
||||
return mMaxRadius;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* 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.effect.ripple;
|
||||
|
||||
|
||||
public interface RippleOwner {
|
||||
/**
|
||||
* Constant for automatically determining the maximum ripple radius.
|
||||
*/
|
||||
public static final int RADIUS_AUTO = -1;
|
||||
|
||||
public void removeRipple(Ripple ripple);
|
||||
|
||||
public void invalidateSelf();
|
||||
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.effect.ripple;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.view.View;
|
||||
|
||||
import com.hippo.ehviewer.widget.HotspotTouchHelper;
|
||||
|
||||
|
||||
public final class RippleSalon {
|
||||
|
||||
private static final boolean USE_OLD_RIPPLE =
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP;
|
||||
|
||||
private static final Drawable MASK = new ColorDrawable(Color.BLACK);
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public static void addRipple(View v, ColorStateList color) {
|
||||
addRipple(v, color, v.getBackground());
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public static void addRipple(View v, ColorStateList color, Drawable content) {
|
||||
if (USE_OLD_RIPPLE) {
|
||||
RippleDrawable rippleDrawable = new RippleDrawable(color, content);
|
||||
v.setOnTouchListener(new HotspotTouchHelper(rippleDrawable));
|
||||
v.setBackgroundDrawable(rippleDrawable);
|
||||
} else {
|
||||
android.graphics.drawable.RippleDrawable rippleDrawable = new android.graphics.drawable.RippleDrawable(color, content, MASK);
|
||||
v.setBackgroundDrawable(rippleDrawable);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class EdDetailParser {
|
||||
|
||||
int previewPageNum;
|
||||
int previewStartIndex;
|
||||
int imageNum;
|
||||
boolean isLastPage;
|
||||
List<String> pageTokenArray;
|
||||
String emsg;
|
||||
|
||||
public boolean parser(String body, int mode, boolean needPreviewInfo) {
|
||||
Pattern p;
|
||||
Matcher m;
|
||||
|
||||
if (body == null)
|
||||
return false;
|
||||
|
||||
if (!body.contains("<"))
|
||||
emsg = body;
|
||||
|
||||
if (mode == EhClient.MODE_LOFI) {
|
||||
// Check is last page
|
||||
p = Pattern.compile("<a[^>]+>Next Page ></a>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
isLastPage = false;
|
||||
else
|
||||
isLastPage = true;
|
||||
|
||||
// Parser preview
|
||||
p = Pattern.compile("<div class=\"gi\"[^>]*><a href=\"https?://lofi.e-hentai.org/s/(\\w+)/\\d+-(\\d+)\"[^>]*>");
|
||||
m = p.matcher(body);
|
||||
boolean first = true;
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
if (first)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
|
||||
} else {
|
||||
// Parser preview info
|
||||
if (needPreviewInfo) {
|
||||
p = Pattern.compile("<td[^>]+><a[^>]+>([\\d,]+)</a></td><td[^>]+>(?:<a[^>]+>)?>(?:</a>)?</td>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
previewPageNum = Integer.valueOf(m.group(1).replace(",", ""));
|
||||
else {
|
||||
Log.e("TAG", "get needPreviewInfo failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
p = Pattern.compile("<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d|,]+) pages</td></tr>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
imageNum = Integer.valueOf(m.group(1).replace(",", ""));
|
||||
else {
|
||||
Log.e("TAG", "get needPreviewInfo failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Parser preview
|
||||
|
||||
boolean first = true;
|
||||
if (body.contains("<div class=\"gdtl\"")) {
|
||||
p = Pattern.compile("<div class=\"gdtl\"[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
|
||||
} else {
|
||||
p = Pattern.compile("<div class=\"gdtm\"[^>]*><div[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (first) {
|
||||
Log.e("TAG", "get gdtm");
|
||||
return false;
|
||||
} else
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,328 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.vector.VectorDrawable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Hippo
|
||||
*
|
||||
*/
|
||||
public class EhInfo {
|
||||
|
||||
private static final String TAG = EhInfo.class.getSimpleName();
|
||||
private static final String PREF_NAME = "eh_info";
|
||||
private static final String DIR_NAME = "file";
|
||||
private static final String AVATAR_NAME = "avatar.png";
|
||||
private static final Bitmap.CompressFormat AVATAR_FORMAT = Bitmap.CompressFormat.PNG;
|
||||
private static Drawable DEFAULT_AVATAR;
|
||||
|
||||
public static final String EX_HOST = "exhentai.org";
|
||||
public static final String[] COOKIABLE_SITE_ARRAY = {
|
||||
"exhentai.org",
|
||||
"e-hentai.org"};
|
||||
|
||||
private static final String KEY_LOGIN = "login";
|
||||
private static final boolean DEFAULT_LOGIN = false;
|
||||
private static final String KEY_USERNAME = "username";
|
||||
private static final String KEY_DISPLAYNAME = "displayname";
|
||||
private static final String DEFAULT_NAME = "Hippo";
|
||||
private static final String KEY_MEMBER_ID = "ipb_member_id";
|
||||
private static final String DEFAULT_MEMBER_ID = null;
|
||||
private static final String KEY_PASS_HASH = "ipb_pass_hash";
|
||||
private static final String DEFAULT_PASS_HASH = null;
|
||||
|
||||
private final Context mContext;
|
||||
private final SharedPreferences mInfoPref;
|
||||
private String mUconfig;
|
||||
private boolean mIsLogin;
|
||||
private String mUsername;
|
||||
private String mDisplayname;
|
||||
private BitmapDrawable mAvatar;
|
||||
private int mDefaultCat;
|
||||
private String mPreviewMode;
|
||||
private int mExculdeTagGroup;
|
||||
private String mExculdeLanguage;
|
||||
|
||||
private boolean mHAHProxy;
|
||||
private String mHAHIp;
|
||||
private String mHAHPort;
|
||||
private String mHAHPasskey;
|
||||
|
||||
private static EhInfo sInstance;
|
||||
|
||||
private BitmapDrawable getAvatarFromFile() {
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
File avatarFile = new File(dir, AVATAR_NAME);
|
||||
if (!avatarFile.exists())
|
||||
return null;
|
||||
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = new FileInputStream(avatarFile);
|
||||
return (BitmapDrawable) BitmapDrawable.createFromStream(is, null);
|
||||
} catch (FileNotFoundException e) {
|
||||
return null;
|
||||
} finally {
|
||||
Utils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
private EhInfo(final Context context){
|
||||
mContext = context;
|
||||
mInfoPref = mContext.getSharedPreferences(PREF_NAME, 0);
|
||||
if (DEFAULT_AVATAR == null)
|
||||
DEFAULT_AVATAR = VectorDrawable.create(context, R.drawable.default_avatar);
|
||||
|
||||
mIsLogin = mInfoPref.getBoolean(KEY_LOGIN, DEFAULT_LOGIN);
|
||||
mUsername = mInfoPref.getString(KEY_USERNAME, DEFAULT_NAME);
|
||||
mDisplayname = mInfoPref.getString(KEY_DISPLAYNAME, DEFAULT_NAME);
|
||||
mAvatar = getAvatarFromFile();
|
||||
|
||||
mDefaultCat = Config.getDefaultCat();
|
||||
mPreviewMode = Config.getPreviewMode();
|
||||
mExculdeTagGroup = Config.getExculdeTagGroup();
|
||||
mExculdeLanguage = Config.getExculdeLanguage();
|
||||
mHAHProxy = Config.getHAHProxy();
|
||||
mHAHIp = Config.getHAHIp();
|
||||
mHAHPort = Config.getHAHPort();
|
||||
mHAHPasskey = Config.getHAHPasskey();
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
private String getUconfigString(String previewMode) {
|
||||
String proxy;
|
||||
if (!mHAHProxy || TextUtils.isEmpty(mHAHIp) || TextUtils.isEmpty(mHAHPort)) {
|
||||
proxy = "";
|
||||
} else {
|
||||
proxy = mHAHIp + "%3A" + mHAHPort;
|
||||
}
|
||||
|
||||
return "cats_" + mDefaultCat
|
||||
+ "-ts_" + (previewMode == null ? mPreviewMode : previewMode)
|
||||
+ "-xns_" + mExculdeTagGroup
|
||||
+ "-xl_" + mExculdeLanguage
|
||||
+ "-hp_" + proxy
|
||||
+ "-hk_" + mHAHPasskey
|
||||
+ "-prn_" + (TextUtils.isEmpty(proxy) ? "n" : "y")
|
||||
+ "-tl_m-uh_y-tr_2-dm_l-ar_0-rc_0-rx_0-ry_0-sa_y-oi_n-qb_n-tf_n-ms_n-mt_n";
|
||||
}
|
||||
|
||||
private void updateUconfig() {
|
||||
mUconfig = getUconfigString(null);
|
||||
}
|
||||
|
||||
public static EhInfo getInstance(final Context context) {
|
||||
if (sInstance == null)
|
||||
sInstance = new EhInfo(context.getApplicationContext());
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
public static boolean isEhSite(URL url) {
|
||||
String host = url.getHost();
|
||||
int length = host.length();
|
||||
int dotCount = 0;
|
||||
int i = length;
|
||||
while(i-- != 0) {
|
||||
char ch = host.charAt(i);
|
||||
if (ch == '.') {
|
||||
dotCount++;
|
||||
}
|
||||
if (dotCount == 2) {
|
||||
// Get it
|
||||
break;
|
||||
}
|
||||
}
|
||||
String site = host.substring(MathUtils.clamp(i+1, 0, length));
|
||||
|
||||
for (String h : EhInfo.COOKIABLE_SITE_ARRAY) {
|
||||
if (h.equals(site))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String getCookie(String cookieStr, String key) {
|
||||
String value = null;
|
||||
int index1 = -1;
|
||||
int index2 = -1;
|
||||
|
||||
if ((index1 = cookieStr.indexOf(key + "=")) != -1) {
|
||||
index1 += key.length() + 1; // size of key + "="
|
||||
if ((index2 = cookieStr.indexOf(";", index1)) != -1)
|
||||
value = cookieStr.substring(index1, index2);
|
||||
else
|
||||
value = cookieStr.substring(index1);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public void storeCookie(HttpURLConnection conn) {
|
||||
List<String> cookieList = conn.getHeaderFields().get("Set-Cookie");
|
||||
if (cookieList == null)
|
||||
return;
|
||||
|
||||
for (String str : cookieList) {
|
||||
setCookie(str);
|
||||
}
|
||||
}
|
||||
|
||||
public void setCookie(String cookie) {
|
||||
SharedPreferences.Editor editor = mInfoPref.edit();
|
||||
String ipb_member_id = getCookie(cookie, KEY_MEMBER_ID);
|
||||
String ipb_pass_hash = getCookie(cookie, KEY_PASS_HASH);
|
||||
|
||||
if (ipb_member_id != null)
|
||||
editor.putString(KEY_MEMBER_ID, ipb_member_id);
|
||||
if (ipb_pass_hash != null)
|
||||
editor.putString(KEY_PASS_HASH, ipb_pass_hash);
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
public void setCookie(HttpURLConnection conn) {
|
||||
setCookie(conn, null);
|
||||
}
|
||||
|
||||
public void setCookie(HttpURLConnection conn, String previewMode) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String id = mInfoPref.getString(KEY_MEMBER_ID, DEFAULT_MEMBER_ID);
|
||||
String hash = mInfoPref.getString(KEY_PASS_HASH, DEFAULT_PASS_HASH);
|
||||
sb.append("uconfig=").append(previewMode == null ? mUconfig : getUconfigString(previewMode))
|
||||
.append("; xres=").append(Config.getLofiResolution());
|
||||
if (id != null)
|
||||
sb.append("; ipb_member_id=").append(id);
|
||||
if (hash != null)
|
||||
sb.append("; ipb_pass_hash=").append(hash);
|
||||
// Fake
|
||||
sb.append("; igneous=");
|
||||
sb.append("; lv=");
|
||||
|
||||
conn.setRequestProperty("Cookie", sb.toString());
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
return mIsLogin;
|
||||
}
|
||||
|
||||
public void login(String username, String displayname) {
|
||||
mIsLogin = true;
|
||||
mUsername = username;
|
||||
mDisplayname = displayname;
|
||||
|
||||
mInfoPref.edit().putBoolean(KEY_LOGIN, true)
|
||||
.putString(KEY_USERNAME, username)
|
||||
.putString(KEY_DISPLAYNAME, displayname).apply();
|
||||
}
|
||||
|
||||
public void logout() {
|
||||
mIsLogin = false;
|
||||
// Remove avatar
|
||||
if (mAvatar != null) {
|
||||
mAvatar.getBitmap().recycle();
|
||||
mAvatar = null;
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
File avatarFile = new File(dir, AVATAR_NAME);
|
||||
avatarFile.delete();
|
||||
}
|
||||
|
||||
mInfoPref.edit().putBoolean(KEY_LOGIN, false)
|
||||
.putString(KEY_MEMBER_ID, DEFAULT_MEMBER_ID)
|
||||
.putString(KEY_PASS_HASH, DEFAULT_PASS_HASH).apply();
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return mUsername;
|
||||
}
|
||||
|
||||
public String getDisplayname() {
|
||||
return mDisplayname;
|
||||
}
|
||||
|
||||
public Drawable getAvatar() {
|
||||
return isLogin() && mAvatar != null ? mAvatar : DEFAULT_AVATAR;
|
||||
}
|
||||
|
||||
public void setAvatar(BitmapDrawable avatar) {
|
||||
mAvatar = avatar;
|
||||
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
File avatarFile = new File(dir, AVATAR_NAME);
|
||||
OutputStream os = null;
|
||||
try {
|
||||
os = new FileOutputStream(avatarFile);
|
||||
avatar.getBitmap().compress(AVATAR_FORMAT, 100, os);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
Utils.closeQuietly(os);
|
||||
}
|
||||
}
|
||||
|
||||
public void setDefaultCat(int defaultCat) {
|
||||
mDefaultCat = defaultCat;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setPreviewMode(String previewMode) {
|
||||
mPreviewMode = previewMode;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setExculdeTagGroup(int exculdeTagGroup) {
|
||||
mExculdeTagGroup = exculdeTagGroup;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setExculdeLanguage(String exculdeLanguage) {
|
||||
mExculdeLanguage = exculdeLanguage;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setHAHProxy(boolean hahProxy) {
|
||||
mHAHProxy = hahProxy;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setHAHProxy(String ip, String port, String passkey) {
|
||||
mHAHIp = ip;
|
||||
mHAHPort = port;
|
||||
mHAHPasskey = passkey;
|
||||
updateUconfig();
|
||||
}
|
||||
}
|
||||
@@ -1,931 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.AutoExpandArray;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
// TODO what a mess
|
||||
public final class ExDownloader implements Runnable {
|
||||
|
||||
private static final String TAG = ExDownloader.class.getSimpleName();
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
private static final String[] URL_509_SUFFIX_ARRAY = {
|
||||
"/509.gif",
|
||||
"/509s.gif"
|
||||
};
|
||||
|
||||
private final Context mContext;
|
||||
private final ExDownloaderManager mManager;
|
||||
|
||||
private final int mGid;
|
||||
private final String mToken;
|
||||
private final String mTitle;
|
||||
private final int mMode;
|
||||
private volatile int mPreviewPageNum = -1;
|
||||
private volatile int mPreviewPerPage = -1;
|
||||
private volatile int mImageNum = -1;
|
||||
private final AutoExpandArray<String> mPageTokeArray = new AutoExpandArray<String>();
|
||||
private final AutoExpandArray<String> mImageFilenameArray = new AutoExpandArray<String>();
|
||||
|
||||
private volatile int mOwnerNum = 0;
|
||||
private Thread mMainThread = null;
|
||||
/** Only work for EhClient.MODE_LOFI when do not know image number **/
|
||||
private int mCurMaxPreviewPage = -1;
|
||||
|
||||
private volatile int mStartIndex = 0;
|
||||
private final Queue<Integer> mRequestIndexArray = new ConcurrentLinkedQueue<Integer>();
|
||||
private final Queue<Integer> mNoTokenIndexArray = new ConcurrentLinkedQueue<Integer>();
|
||||
private final Queue<Integer> mRequestPageIndexArray = new ConcurrentLinkedQueue<Integer>();
|
||||
|
||||
/** The set contains the requsting index **/
|
||||
private final Set<Integer> mRequstingIndexSet = new HashSet<Integer>();
|
||||
|
||||
private volatile int mCurRequestPageIndex = -1;
|
||||
|
||||
private final int mWorkerNum;
|
||||
private final Worker[] mWorkerArray;
|
||||
private final HttpHelper.DownloadControlor[] mControlorArray;
|
||||
|
||||
private final Object mPageTokenLock = new Object();
|
||||
private final Object mWorkerLock = new Object();
|
||||
private final Object mWorkerGetIndexLock = new Object();
|
||||
|
||||
private volatile boolean mDownloadMode = false;
|
||||
private volatile boolean mPauseWork = false;
|
||||
private volatile boolean mStopWork = false;
|
||||
|
||||
private final File mDir;
|
||||
private ListenerForImageSet mLfis;
|
||||
private ListenerForDownload mLfd;
|
||||
|
||||
private static final long UPDATE_SPEED_INTERVAL = 500;
|
||||
private volatile long mLastUpdateSpeedTime = 0;
|
||||
private volatile long mAccumulateSize;
|
||||
private volatile HashSet<Integer> mDownloadIndexSet;
|
||||
private final Object mDownloadLock = new Object();
|
||||
|
||||
private int mCurReadIndex = 0;
|
||||
|
||||
/**
|
||||
* Do no work in UI thread
|
||||
* @author Hippo
|
||||
*/
|
||||
public interface ListenerForImageSet {
|
||||
public void onDownloadStart(int index);
|
||||
public void onDownloading(int index, float percent);
|
||||
public void onDownloadComplete(int index);
|
||||
public void onDownloadFail(int index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Do no work in UI thread
|
||||
* @author Hippo
|
||||
*/
|
||||
public interface ListenerForDownload {
|
||||
public void onStart(int gid);
|
||||
public void onGetSum(int gid, int sum);
|
||||
public void onDownload(int gid, int downloadSize, int totalSize);
|
||||
public void onUpdateSpeed(int gid, int speed);
|
||||
public void onDownloadOver(int gid, int legacy);
|
||||
}
|
||||
|
||||
ExDownloader(Context context, int gid, String token, String title, int mode) {
|
||||
mContext = context;
|
||||
mManager = ExDownloaderManager.getInstance();
|
||||
mGid = gid;
|
||||
mToken = token;
|
||||
mTitle = title;
|
||||
mMode = mode;
|
||||
|
||||
mWorkerNum = Config.getDownloadThread();
|
||||
mWorkerArray = new Worker[mWorkerNum];
|
||||
mControlorArray = new HttpHelper.DownloadControlor[mWorkerNum];
|
||||
|
||||
// Make sure dir
|
||||
mDir = EhUtils.getGalleryDir(mGid, mTitle);
|
||||
Utils.ensureDir(mDir, true);
|
||||
}
|
||||
|
||||
public void setListenerForImageSet(ListenerForImageSet l) {
|
||||
mLfis = l;
|
||||
}
|
||||
|
||||
public void setListenerDownload(ListenerForDownload l) {
|
||||
mLfd = l;
|
||||
}
|
||||
|
||||
void occupy() {
|
||||
mOwnerNum++;
|
||||
}
|
||||
|
||||
void free() {
|
||||
mOwnerNum--;
|
||||
}
|
||||
|
||||
boolean isOrphans() {
|
||||
return mOwnerNum == 0;
|
||||
}
|
||||
|
||||
void stop() {
|
||||
// TODO stop all thread, release all resources
|
||||
mStopWork = true;
|
||||
// Stop download
|
||||
for (HttpHelper.DownloadControlor c : mControlorArray) {
|
||||
if (c != null)
|
||||
c.stop();
|
||||
}
|
||||
// Wake all thread
|
||||
synchronized(mPageTokenLock) {mPageTokenLock.notifyAll();}
|
||||
synchronized(mWorkerGetIndexLock) {mWorkerGetIndexLock.notifyAll();}
|
||||
synchronized(mWorkerLock) {mWorkerLock.notifyAll();}
|
||||
}
|
||||
|
||||
boolean pause(boolean pause) {
|
||||
if (mOwnerNum > 1)
|
||||
return false;
|
||||
|
||||
mPauseWork = pause;
|
||||
if (mPauseWork) {
|
||||
// Stop download
|
||||
for (HttpHelper.DownloadControlor c : mControlorArray)
|
||||
if (c != null) c.stop();
|
||||
// Wake all thread
|
||||
synchronized(mPageTokenLock) {mPageTokenLock.notifyAll();}
|
||||
synchronized(mWorkerGetIndexLock) {mWorkerGetIndexLock.notifyAll();}
|
||||
synchronized(mWorkerLock) {mWorkerLock.notifyAll();}
|
||||
} else {
|
||||
// Reset download
|
||||
for (HttpHelper.DownloadControlor c : mControlorArray)
|
||||
if (c != null) c.reset();
|
||||
ensureStart();
|
||||
ensureWorkers();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getGid() {
|
||||
return mGid;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return mToken;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return mTitle;
|
||||
}
|
||||
|
||||
public void setDownloadMode(boolean downloadMode) {
|
||||
synchronized (mDownloadLock) {
|
||||
if (downloadMode) {
|
||||
setStartIndex(0);
|
||||
if (mDownloadIndexSet == null)
|
||||
mDownloadIndexSet = new HashSet<Integer>();
|
||||
if (mDownloadMode && mLfd != null)
|
||||
mLfd.onStart(mGid);
|
||||
} else {
|
||||
mDownloadIndexSet = null;
|
||||
}
|
||||
mDownloadMode = downloadMode;
|
||||
}
|
||||
}
|
||||
|
||||
public void setStartIndex(int startIndex) {
|
||||
if (mDownloadMode) {
|
||||
addTargetIndex(startIndex);
|
||||
} else {
|
||||
if (mImageNum != -1 && startIndex >= mImageNum)
|
||||
mStartIndex = 0;
|
||||
else
|
||||
mStartIndex = startIndex;
|
||||
|
||||
ensureStart();
|
||||
ensureWorkers();
|
||||
}
|
||||
}
|
||||
|
||||
public void addTargetIndex(int index) {
|
||||
if (mImageNum != -1 && index >= mImageNum)
|
||||
return;
|
||||
|
||||
mRequestIndexArray.offer(index);
|
||||
ensureStart();
|
||||
ensureWorkers();
|
||||
}
|
||||
|
||||
public void setCurReadIndex(final int index) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
writeCurReadIndex(index);
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public int getMaxEnsureIndex() {
|
||||
if (mImageNum != -1) {
|
||||
return mImageNum - 1;
|
||||
} else {
|
||||
return Math.max(Math.max(Math.max(mStartIndex,
|
||||
Math.max(mCurMaxPreviewPage, mPreviewPageNum - 1) * mPreviewPerPage),
|
||||
mPageTokeArray.maxValidIndex()), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If do not know image num, return -1.
|
||||
* You should call getMaxEnsureIndex().
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int getImageNum() {
|
||||
return mImageNum;
|
||||
}
|
||||
|
||||
public AutoExpandArray<String> getImageFilenameArray() {
|
||||
return mImageFilenameArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* If targer index image is downloading, return true
|
||||
*
|
||||
* @param index
|
||||
* @return
|
||||
*/
|
||||
public boolean isDownloading(int index) {
|
||||
return mRequstingIndexSet.contains(index);
|
||||
}
|
||||
|
||||
private synchronized void ensureStart() {
|
||||
if (mMainThread != null)
|
||||
return;
|
||||
|
||||
mMainThread = new BgThread(this);
|
||||
mMainThread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
||||
mMainThread.start();
|
||||
}
|
||||
|
||||
private File getExDownloadInfoFile() {
|
||||
return new File(mDir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
}
|
||||
|
||||
private boolean checkMode(int samlpe, int target) {
|
||||
return samlpe <= EhClient.MODE_EX && target <= EhClient.MODE_EX
|
||||
|| samlpe == EhClient.MODE_LOFI && target == EhClient.MODE_LOFI;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function parser the download info file.<br>
|
||||
* The file look like this:<br>
|
||||
* <code>
|
||||
* 00000000<br>
|
||||
* 728874<br>
|
||||
* 306429c222<br>
|
||||
* 1<br>
|
||||
* 4<br>
|
||||
* 40<br>
|
||||
* 128<br>
|
||||
* 1 43a64e6e79<br>
|
||||
* </code><br>
|
||||
* Fist line is gid, a integer.
|
||||
* Second line is token, a ten-character string.
|
||||
* Third line is mode.
|
||||
* Fourth line is preview page num.
|
||||
* Fifth line is preview per page.
|
||||
*
|
||||
* @param ediFile
|
||||
* @return
|
||||
*/
|
||||
private synchronized boolean parserEdiFile(File ediFile) {
|
||||
if (!ediFile.exists() || !ediFile.isFile() || !ediFile.canRead()
|
||||
|| !ediFile.canWrite())
|
||||
return false;
|
||||
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = new BufferedInputStream(new FileInputStream(ediFile),
|
||||
IO_BUFFER_SIZE);
|
||||
// skip read index
|
||||
Utils.readAsciiLine(is);
|
||||
if (mGid != Integer.valueOf(Utils.readAsciiLine(is)) ||
|
||||
!mToken.equals(Utils.readAsciiLine(is)))
|
||||
return false;
|
||||
|
||||
if (!checkMode(Integer.valueOf(Utils.readAsciiLine(is)), mMode)) {
|
||||
// If preview info is not same
|
||||
// skip preview page num and preview per page
|
||||
Utils.readAsciiLine(is);
|
||||
Utils.readAsciiLine(is);
|
||||
} else {
|
||||
mPreviewPageNum = Integer.valueOf(Utils.readAsciiLine(is));
|
||||
mPreviewPerPage = Integer.valueOf(Utils.readAsciiLine(is));
|
||||
}
|
||||
|
||||
mImageNum = Integer.parseInt(Utils.readAsciiLine(is));
|
||||
if (mImageNum != -1) {
|
||||
mPageTokeArray.setCapacity(mImageNum);
|
||||
mImageFilenameArray.setCapacity(mImageNum);
|
||||
}
|
||||
else if (mPreviewPageNum != -1 && mPreviewPerPage != -1) {
|
||||
mPageTokeArray.setCapacity(mPreviewPageNum * mPreviewPerPage);
|
||||
mImageFilenameArray.setCapacity(mPreviewPageNum * mPreviewPerPage);
|
||||
}
|
||||
|
||||
// read page token info
|
||||
try {
|
||||
while(true) {
|
||||
String line = Utils.readAsciiLine(is);
|
||||
int pos = line.indexOf(" ");
|
||||
if (pos == -1 && line.length() - pos != 11)
|
||||
continue;
|
||||
try {
|
||||
int index = Integer.parseInt(line.substring(0, pos));
|
||||
String token = line.substring(pos + 1);
|
||||
mPageTokeArray.set(index, token);
|
||||
} catch (NumberFormatException e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch (EOFException e) {
|
||||
// Empty
|
||||
}
|
||||
return true;
|
||||
} catch (Throwable e) {
|
||||
// If read error
|
||||
return false;
|
||||
} finally {
|
||||
Utils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void writeEdiFile(File ediFile) {
|
||||
try {
|
||||
FileWriter writer = new FileWriter(ediFile);
|
||||
writer.write(String.format("%08x", mCurReadIndex));
|
||||
writer.write("\n");
|
||||
writer.write(String.valueOf(mGid));
|
||||
writer.write("\n");
|
||||
writer.write(mToken);
|
||||
writer.write("\n");
|
||||
writer.write(mMode + '0');
|
||||
writer.write("\n");
|
||||
writer.write(String.valueOf(mPreviewPageNum));
|
||||
writer.write("\n");
|
||||
writer.write(String.valueOf(mPreviewPerPage));
|
||||
writer.write("\n");
|
||||
writer.write(String.valueOf(mImageNum));
|
||||
writer.write("\n");
|
||||
for (int i = 0; i < mPageTokeArray.length(); i++) {
|
||||
String pageToken = mPageTokeArray.get(i);
|
||||
if (pageToken != null) {
|
||||
writer.write(String.valueOf(i));
|
||||
writer.write(" ");
|
||||
writer.write(pageToken);
|
||||
writer.write("\n");
|
||||
}
|
||||
}
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
|
||||
private synchronized void writeCurReadIndex(int index) {
|
||||
mCurReadIndex = index;
|
||||
try {
|
||||
RandomAccessFile raf = new RandomAccessFile(getExDownloadInfoFile(), "rw");
|
||||
raf.write(String.format("%08x", mCurReadIndex).getBytes());
|
||||
raf.close();
|
||||
} catch (Throwable e) {}
|
||||
}
|
||||
|
||||
public static int readCurReadIndex(int gid, String title) {
|
||||
try {
|
||||
RandomAccessFile raf = new RandomAccessFile(new File(EhUtils.getGalleryDir(gid, title),
|
||||
EhUtils.EH_DOWNLOAD_FILENAME), "r");
|
||||
int index = Integer.parseInt(raf.readLine(), 16);
|
||||
raf.close();
|
||||
return index;
|
||||
} catch (Throwable e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void getDetailInfo(int pageIndex, File ediFile, boolean needPreviewInfo) throws Exception {
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
EdDetailParser edp = new EdDetailParser();
|
||||
String url = EhClient.getDetailUrl(mGid, mToken, pageIndex, mMode);
|
||||
hh.setPreviewMode("m");
|
||||
String body = hh.get(url);
|
||||
if (body == null)
|
||||
throw new Exception(hh.getEMsg() != null ? hh.getEMsg() : "Http error, body == null");
|
||||
if (!edp.parser(body, mMode, needPreviewInfo))
|
||||
throw new Exception(edp.emsg != null ? edp.emsg : "Parser error, body is \n" + body);
|
||||
if (edp.previewStartIndex != pageIndex * mPreviewPerPage)
|
||||
throw new Exception("预测与实际不匹配, 预测: " + edp.previewStartIndex +
|
||||
", 实际: " + pageIndex * mPreviewPerPage + ", body is \n" + body);
|
||||
|
||||
List<String> pageTokenArray = edp.pageTokenArray;
|
||||
if (needPreviewInfo)
|
||||
mPreviewPerPage = pageTokenArray.size();
|
||||
if (mMode == EhClient.MODE_LOFI) {
|
||||
// update mCurMaxPreviewPage
|
||||
if (edp.isLastPage) {
|
||||
mPreviewPageNum = pageIndex + 1;
|
||||
mImageNum = pageIndex * mPreviewPerPage + pageTokenArray.size();
|
||||
} else if (mPreviewPageNum == -1) {
|
||||
mCurMaxPreviewPage = Math.max(mCurMaxPreviewPage, pageIndex + 1);
|
||||
}
|
||||
} else {
|
||||
if (needPreviewInfo) {
|
||||
mPreviewPageNum = edp.previewPageNum;
|
||||
mImageNum = edp.imageNum;
|
||||
mPageTokeArray.setCapacity(mPreviewPageNum * mPreviewPerPage);
|
||||
mImageFilenameArray.setCapacity(mPreviewPageNum * mPreviewPerPage);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < pageTokenArray.size(); i++)
|
||||
mPageTokeArray.set(i + edp.previewStartIndex, pageTokenArray.get(i));
|
||||
|
||||
writeEdiFile(ediFile);
|
||||
}
|
||||
|
||||
private void ensureWorkers() {
|
||||
if (mPreviewPerPage == -1)
|
||||
return;
|
||||
|
||||
synchronized(mWorkerArray) {
|
||||
for (int i = 0; i < mWorkerArray.length; i++) {
|
||||
if (mWorkerArray[i] == null) {
|
||||
Worker worker = new Worker(i);
|
||||
worker.start();
|
||||
mWorkerArray[i] = worker;
|
||||
mControlorArray[i] = new HttpHelper.DownloadControlor();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateDownload(int index) {
|
||||
synchronized (mDownloadLock) {
|
||||
if (mDownloadIndexSet != null && !mDownloadIndexSet.contains(index)) {
|
||||
mDownloadIndexSet.add(index);
|
||||
if (mDownloadMode && mLfd != null)
|
||||
mLfd.onDownload(mGid, mDownloadIndexSet.size(), getMaxEnsureIndex() + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final int BE_NOTIFY_ID = -3;
|
||||
|
||||
private static final void show509Notification(Context context) {
|
||||
NotificationManager notifyManager = (NotificationManager) context
|
||||
.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
|
||||
mBuilder.setSmallIcon(R.drawable.ic_stat_eh).setContentTitle(context.getString(R.string.notification_be_title))
|
||||
.setContentText(context.getString(R.string.notification_be_mesg))
|
||||
.setOngoing(false).setAutoCancel(true);
|
||||
notifyManager.notify(BE_NOTIFY_ID, mBuilder.build());
|
||||
}
|
||||
|
||||
// TODO for download , when to claim download completed
|
||||
@Override
|
||||
public void run() {
|
||||
// Try to get info from file
|
||||
try {
|
||||
File ediFile = getExDownloadInfoFile();
|
||||
if (!parserEdiFile(ediFile) || mPreviewPerPage == -1 ||
|
||||
((mMode == EhClient.MODE_EX || mMode == EhClient.MODE_G) && mImageNum == -1)) {
|
||||
getDetailInfo(0, ediFile, true);
|
||||
}
|
||||
|
||||
if (mLfd != null)
|
||||
mLfd.onGetSum(mGid, mImageNum);
|
||||
|
||||
ensureWorkers();
|
||||
|
||||
// A loop to get page token
|
||||
while (true) {
|
||||
// Check stop
|
||||
if (mStopWork)
|
||||
break;
|
||||
|
||||
int noTokenIndex = -1;
|
||||
int pageIndex = -1;
|
||||
synchronized(mPageTokenLock) {
|
||||
if (mNoTokenIndexArray.isEmpty()) {
|
||||
if (mRequestPageIndexArray.isEmpty()) {
|
||||
try {
|
||||
mPageTokenLock.wait();
|
||||
} catch (InterruptedException e) {}
|
||||
continue;
|
||||
} else {
|
||||
pageIndex = mRequestPageIndexArray.poll();
|
||||
mCurRequestPageIndex = pageIndex;
|
||||
}
|
||||
} else {
|
||||
noTokenIndex = mNoTokenIndexArray.poll();
|
||||
}
|
||||
}
|
||||
|
||||
if (noTokenIndex != -1) {
|
||||
if (mPageTokeArray.get(noTokenIndex) == null) {
|
||||
getDetailInfo(noTokenIndex / mPreviewPerPage, ediFile, false);
|
||||
} else {
|
||||
// The token is already got, no need to re
|
||||
}
|
||||
} else if (noTokenIndex == -1){
|
||||
getDetailInfo(pageIndex, ediFile, false);
|
||||
mCurRequestPageIndex = -1;
|
||||
}
|
||||
|
||||
ensureWorkers();
|
||||
|
||||
synchronized(mWorkerGetIndexLock) {mWorkerGetIndexLock.notifyAll();}
|
||||
synchronized(mWorkerLock) {mWorkerLock.notifyAll();}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
Log.f(e);
|
||||
|
||||
synchronized (mDownloadLock) {
|
||||
if (mDownloadMode && mLfd != null && mDownloadIndexSet != null) {
|
||||
mLfd.onDownloadOver(mGid,
|
||||
getMaxEnsureIndex() + 1 - mDownloadIndexSet.size());
|
||||
}
|
||||
}
|
||||
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
mMainThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "ExDownloader over");
|
||||
}
|
||||
|
||||
private class Worker extends BgThread {
|
||||
|
||||
private final int mIndex;
|
||||
|
||||
public Worker(int index) {
|
||||
super();
|
||||
mIndex = index;
|
||||
setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
||||
}
|
||||
|
||||
private void addNoTokenIndex(int index) {
|
||||
synchronized(mPageTokenLock) {
|
||||
mNoTokenIndexArray.offer(index);
|
||||
mPageTokenLock.notify();
|
||||
}
|
||||
}
|
||||
|
||||
private void addRequstPageIndex(int pageIndex) {
|
||||
synchronized(mPageTokenLock) {
|
||||
if (mCurRequestPageIndex != pageIndex &&
|
||||
!mRequestPageIndexArray.contains(pageIndex)) {
|
||||
mRequestPageIndexArray.offer(pageIndex);
|
||||
mPageTokenLock.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int getTargetIndex() {
|
||||
synchronized(mWorkerGetIndexLock) {
|
||||
while (true) {
|
||||
|
||||
// Check stop
|
||||
if (mStopWork || mPauseWork)
|
||||
return -1;
|
||||
|
||||
if (!mRequestIndexArray.isEmpty()) {
|
||||
return mRequestIndexArray.poll();
|
||||
} else if (mImageNum != -1 && mStartIndex == mImageNum) {
|
||||
return -1;
|
||||
} else if (mImageNum == -1 && mStartIndex > getMaxEnsureIndex()) {
|
||||
// If do not sure the index is valid
|
||||
|
||||
Log.d(TAG, "mPreviewPerPage = " + mPreviewPerPage);
|
||||
|
||||
addRequstPageIndex(getMaxEnsureIndex() / mPreviewPerPage);
|
||||
try {
|
||||
mWorkerGetIndexLock.wait();
|
||||
} catch (InterruptedException e) {}
|
||||
} else {
|
||||
return mStartIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO what if download failed ? what to do ?
|
||||
@Override
|
||||
public void run() {
|
||||
HttpDownloadListener listener = new HttpDownloadListener();
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
ImagePageParser ipp = new ImagePageParser();
|
||||
HttpHelper.DownloadOption option = new HttpHelper.DownloadOption();
|
||||
|
||||
option.setAllowFixingExtension(true);
|
||||
|
||||
while (true) {
|
||||
// Check stop
|
||||
if (mStopWork || mPauseWork)
|
||||
break;
|
||||
|
||||
int targetIndex = getTargetIndex();
|
||||
if (targetIndex == -1)
|
||||
break;
|
||||
|
||||
// Check is the index is requsted
|
||||
if (mRequstingIndexSet.contains(targetIndex))
|
||||
continue;
|
||||
|
||||
// Check is this already downloaded
|
||||
boolean isAlreadyDownloaded = false;
|
||||
// First check mImageFilenameArray
|
||||
String imageFilename = mImageFilenameArray.get(targetIndex);
|
||||
if (imageFilename != null) {
|
||||
File file = new File(mDir, imageFilename);
|
||||
if (file.exists())
|
||||
isAlreadyDownloaded = true;
|
||||
} else {
|
||||
// Can not find image file name, just guess
|
||||
for (String possibleFilename : EhUtils.getPossibleImageFilenames(targetIndex)) {
|
||||
File file = new File(mDir, possibleFilename);
|
||||
if (file.exists()) {
|
||||
isAlreadyDownloaded = true;
|
||||
mImageFilenameArray.set(targetIndex, possibleFilename);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isAlreadyDownloaded) {
|
||||
Log.d(TAG, "isAlreadyDownloaded");
|
||||
updateDownload(targetIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
mRequstingIndexSet.add(targetIndex);
|
||||
|
||||
listener.index = targetIndex;
|
||||
|
||||
String pageToken = null;
|
||||
while (true) {
|
||||
// Check stop
|
||||
if (mStopWork || mPauseWork)
|
||||
break;
|
||||
|
||||
pageToken = mPageTokeArray.get(targetIndex);
|
||||
if (pageToken == null) {
|
||||
addNoTokenIndex(targetIndex);
|
||||
synchronized(mWorkerLock) {
|
||||
try {mWorkerLock.wait();}
|
||||
catch (InterruptedException e) {}
|
||||
}
|
||||
} else {
|
||||
// Get valid page token, jump out of loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Parser image page
|
||||
for (int i = 0; i < 2 && !mStopWork && !mPauseWork; i++) {
|
||||
hh.reset();
|
||||
ipp.reset();
|
||||
String body = hh.get(EhClient.getPageUrl(mGid, pageToken, targetIndex + 1, mMode)
|
||||
+ ((i == 1) ? "?nl=48" : ""));
|
||||
if (ipp.parser(body, mMode)) {
|
||||
// Download image
|
||||
HttpHelper.DownloadControlor c = mControlorArray[mIndex];
|
||||
|
||||
if (Config.getDownloadOriginImage() && ipp.originalImageUrl != null) {
|
||||
|
||||
Log.d(TAG, "Download origin image");
|
||||
|
||||
// Download orgin image
|
||||
String imageUrl = ipp.originalImageUrl;
|
||||
// Guess filename
|
||||
String filename = EhUtils.getImageFilename(targetIndex, "jpg");
|
||||
// Download
|
||||
hh.reset();
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadOriginEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (hh.getException() instanceof HttpHelper.BandwidthExceededException) {
|
||||
// Get 509
|
||||
show509Notification(mContext);
|
||||
break;
|
||||
} else {
|
||||
String newImageUrl = hh.getLastUrl();
|
||||
if (newImageUrl != null) {
|
||||
// Try download from proxy
|
||||
hh.reset();
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(newImageUrl, mDir, filename, option, c, listener) == null) {
|
||||
// Download failed
|
||||
Log.d(TAG, "Download failed");
|
||||
} else {
|
||||
// Download successful
|
||||
Log.d(TAG, "Download successful");
|
||||
}
|
||||
} else {
|
||||
// Download failed
|
||||
Log.d(TAG, "Download failed");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Download successful
|
||||
Log.d(TAG, "Download successful");
|
||||
}
|
||||
|
||||
// No need to refresh image url
|
||||
break;
|
||||
} else {
|
||||
// Download scale image
|
||||
String imageUrl = ipp.imageUrl;
|
||||
|
||||
//Check 509 gif
|
||||
boolean get509 = false;
|
||||
for (String suffix : URL_509_SUFFIX_ARRAY) {
|
||||
if (imageUrl.endsWith(suffix)) {
|
||||
// Get 509 gif here
|
||||
get509 = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (get509) {
|
||||
show509Notification(mContext);
|
||||
break;
|
||||
}
|
||||
|
||||
// Guess filename
|
||||
String filename = EhUtils.getImageFilename(targetIndex, Utils.getExtension(imageUrl, "jpg"));
|
||||
// Don't put into mImageFilenameArray, because extension maybe be wrong
|
||||
// mImageFilenameArray.set(targetIndex, filename);
|
||||
hh.reset();
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
hh.reset();
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (i == 1) {
|
||||
// TODO download error
|
||||
Log.d(TAG, "download error");
|
||||
}
|
||||
} else {
|
||||
// download ok
|
||||
Log.d(TAG, "download ok proxy");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// download ok
|
||||
Log.d(TAG, "download ok");
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// TODO parser error, Do somthing
|
||||
Log.d(TAG, "parser error");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from requsting set
|
||||
mRequstingIndexSet.remove(targetIndex);
|
||||
}
|
||||
|
||||
// Worker over
|
||||
synchronized(mWorkerArray) {
|
||||
// Remove from mWorkerArray
|
||||
mWorkerArray[mIndex] = null;
|
||||
mControlorArray[mIndex] = null;
|
||||
|
||||
boolean allNull = true;
|
||||
for (Worker w : mWorkerArray)
|
||||
if (w != null) {allNull = false; break;}
|
||||
|
||||
synchronized (mDownloadLock) {
|
||||
if (allNull && mDownloadMode && mLfd != null && mDownloadIndexSet != null) {
|
||||
mLfd.onDownloadOver(mGid,
|
||||
getMaxEnsureIndex() + 1 - mDownloadIndexSet.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "ExDownloader Worker over");
|
||||
}
|
||||
}
|
||||
|
||||
public class HttpDownloadListener implements HttpHelper.OnDownloadListener {
|
||||
|
||||
public int index;
|
||||
private float lastPercent;
|
||||
private int lastDownloadSize;
|
||||
|
||||
@Override
|
||||
public void onDownloadStartConnect() {
|
||||
lastPercent = 0.0f;
|
||||
lastDownloadSize = 0;
|
||||
|
||||
if (mLfis != null)
|
||||
mLfis.onDownloadStart(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStartDownload(int totalSize) {
|
||||
lastPercent = 0.0f;
|
||||
lastDownloadSize = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStatusUpdate(int downloadSize, int totalSize) {
|
||||
if (totalSize == -1)
|
||||
return;
|
||||
|
||||
float percent = (float)downloadSize / totalSize;
|
||||
if (percent - lastPercent >= 0.05f) {
|
||||
lastPercent = percent;
|
||||
|
||||
if (mLfis != null)
|
||||
mLfis.onDownloading(index, percent);
|
||||
}
|
||||
|
||||
// Update download size
|
||||
int accumulateSize = downloadSize - lastDownloadSize;
|
||||
lastDownloadSize = downloadSize;
|
||||
mAccumulateSize += accumulateSize;
|
||||
long curTime = System.currentTimeMillis();
|
||||
long interval = curTime - mLastUpdateSpeedTime;
|
||||
if (interval > UPDATE_SPEED_INTERVAL) {
|
||||
if (mDownloadMode && mLfd != null)
|
||||
mLfd.onUpdateSpeed(mGid, (int)(mAccumulateSize * 1000 / interval));
|
||||
mLastUpdateSpeedTime = curTime;
|
||||
mAccumulateSize = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadOver(int status, String eMsg) {
|
||||
if (status == HttpHelper.DOWNLOAD_OK_CODE) {
|
||||
mRequstingIndexSet.remove(index);
|
||||
|
||||
updateDownload(index);
|
||||
}
|
||||
|
||||
if (mLfis != null && status == HttpHelper.DOWNLOAD_OK_CODE)
|
||||
mLfis.onDownloadComplete(index);
|
||||
else if (mLfis != null && status == HttpHelper.DOWNLOAD_FAIL_CODE)
|
||||
mLfis.onDownloadFail(index);
|
||||
|
||||
lastPercent = 0.0f;
|
||||
lastDownloadSize = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.SparseArray;
|
||||
|
||||
public class ExDownloaderManager {
|
||||
|
||||
private static final String TAG = ExDownloaderManager.class.getSimpleName();
|
||||
|
||||
private final Context mContext;
|
||||
private final SparseArray<ExDownloader> mExDownloadList;
|
||||
|
||||
private static ExDownloaderManager sInstance;
|
||||
|
||||
public static void createInstance(Context context) {
|
||||
sInstance = new ExDownloaderManager(context.getApplicationContext());
|
||||
}
|
||||
|
||||
public static ExDownloaderManager getInstance() {
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
private ExDownloaderManager(Context context) {
|
||||
mContext = context;
|
||||
mExDownloadList = new SparseArray<ExDownloader>();
|
||||
}
|
||||
|
||||
public synchronized ExDownloader getExDownloader(int gid, String token, String title, int mode) {
|
||||
ExDownloader exDownloader = mExDownloadList.get(gid);
|
||||
if (exDownloader == null) {
|
||||
exDownloader = new ExDownloader(mContext, gid, token, title, mode);
|
||||
mExDownloadList.append(gid, exDownloader);
|
||||
}
|
||||
exDownloader.occupy();
|
||||
return exDownloader;
|
||||
}
|
||||
|
||||
public synchronized void freeExDownloader(ExDownloader exDownloader) {
|
||||
exDownloader.free();
|
||||
if (exDownloader.isOrphans()) {
|
||||
exDownloader.stop();
|
||||
mExDownloadList.remove(exDownloader.getGid());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ImagePageParser {
|
||||
|
||||
public String imageUrl;
|
||||
public String originalImageUrl;
|
||||
public int gid;
|
||||
public String token;
|
||||
|
||||
public void reset() {
|
||||
imageUrl = null;
|
||||
originalImageUrl = null;
|
||||
gid = 0;
|
||||
token = null;
|
||||
}
|
||||
|
||||
public boolean parser(String body, int mode) {
|
||||
Pattern p;
|
||||
Matcher m;
|
||||
|
||||
if (body == null)
|
||||
return false;
|
||||
|
||||
if (mode ==EhClient.MODE_LOFI) {
|
||||
p = Pattern.compile("<img id=\"sm\" src=\"([^\"]+)\"[^>]+>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
imageUrl = Utils.unescapeXml(m.group(1));
|
||||
else
|
||||
return false;
|
||||
|
||||
p = Pattern.compile("<a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)/?\">Back</a>");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
gid = Integer.parseInt(m.group(1));
|
||||
token = m.group(2);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
} else {
|
||||
p = Pattern.compile(
|
||||
"<(?:/iframe|div id=\"i3\")[^>]*><a[^>]*><img[^>]*src=\"(.+?)\"" +
|
||||
".+?" +
|
||||
"<div class=\"sb\"><a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
imageUrl = Utils.unescapeXml(m.group(1));
|
||||
gid = Integer.parseInt(m.group(2));
|
||||
token = m.group(3);
|
||||
|
||||
p = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
originalImageUrl = Utils.unescapeXml(
|
||||
new StringBuilder(m.group(1)).append("fullimg.php").append(m.group(2)).toString());
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.data.LofiGalleryInfo;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class ListParser {
|
||||
|
||||
public static final int TARGET_PAGE_IS_LAST = -1;
|
||||
|
||||
public static final int ALL = 0x1;
|
||||
public static final int NOT_FOUND = 0x2;
|
||||
public static final int PARSER_ERROR = -1;
|
||||
public static final int INDEX_ERROR = -2;
|
||||
|
||||
public int pageNum;
|
||||
|
||||
public ArrayList<GalleryInfo> giList;
|
||||
|
||||
/**
|
||||
* If NOT_FOUND maxPage is 0,
|
||||
* if can not get maxPage, set it Integer.MAX_VALUE
|
||||
*
|
||||
* @param pageContext
|
||||
* @param mode
|
||||
* @return
|
||||
*/
|
||||
public int parser(String body, int mode) {
|
||||
|
||||
Pattern p;
|
||||
Matcher m;
|
||||
|
||||
if (body == null)
|
||||
return 0;
|
||||
|
||||
giList = new ArrayList<GalleryInfo>(25);
|
||||
|
||||
switch (mode) {
|
||||
case EhClient.MODE_LOFI:
|
||||
p = Pattern.compile("<td class=\"ii\"><a href=\"(.+?)\">" // detail url
|
||||
+ "<img src=\"(.+?)\".+?/>" // thumb url
|
||||
+ ".+?<a class=\"b\" href=\".+?\">(.+?)</a>" // title
|
||||
+ ".+?<td class=\"ik ip\">Posted:</td><td class=\"ip\">(.+?)</td>" // Posted and uploader
|
||||
+ "</tr><tr><td class=\"ik\">Category:</td><td>(.+?)</td>" // Category
|
||||
+ "</tr><tr><td class=\"ik\">Tags:</td><td>(.+?)</td>" // Tags
|
||||
+ "</tr><tr><td class=\"ik\">Rating:</td><td class=\"ir\">(.+?)</td>"); // rating
|
||||
m = p.matcher(body);
|
||||
DetailUrlParser dup = new DetailUrlParser();
|
||||
while (m.find()) {
|
||||
LofiGalleryInfo lgi = new LofiGalleryInfo();
|
||||
String[] pau = new String[2];
|
||||
|
||||
if (dup.parser(m.group(1))) {
|
||||
lgi.gid = dup.gid;
|
||||
lgi.token = dup.token;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
lgi.thumb = Utils.unescapeXml(m.group(2));
|
||||
lgi.title = Utils.unescapeXml(m.group(3));
|
||||
if (getPostedAndUploader(m.group(4), pau)) {
|
||||
lgi.posted = pau[0];
|
||||
lgi.uploader = pau[1];
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
lgi.category = EhUtils.getCategory(m.group(5));
|
||||
String tags = m.group(6);
|
||||
if (tags.equals("-"))
|
||||
lgi.lofiTags = null;
|
||||
else
|
||||
lgi.lofiTags = tags.split(", ");
|
||||
String rating = m.group(7);
|
||||
if (rating.equals("-"))
|
||||
lgi.rating = Float.NaN;
|
||||
else
|
||||
lgi.rating = getStartNum(rating);
|
||||
lgi.generateSLang();
|
||||
|
||||
giList.add(lgi);
|
||||
}
|
||||
|
||||
if (giList.size() == 0) {
|
||||
if (body.contains("No hits found</div>")) {
|
||||
pageNum = 0;
|
||||
return NOT_FOUND;
|
||||
} else if (body.contains("No more hits found</div>")) {
|
||||
return INDEX_ERROR;
|
||||
} else {
|
||||
return PARSER_ERROR;
|
||||
}
|
||||
} else {
|
||||
if (!body.contains("Next Page ></a>"))
|
||||
pageNum = TARGET_PAGE_IS_LAST;
|
||||
else
|
||||
pageNum = Integer.MAX_VALUE;
|
||||
return ALL;
|
||||
}
|
||||
|
||||
case EhClient.MODE_EX:
|
||||
p = Pattern.compile("<a[^<>]+>([\\d]+)</a></td><td[^<>]+>(?:<a[^<>]+>)?&");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
pageNum = Integer.parseInt(m.group(1));
|
||||
} else if (body.contains("No hits found</p>")) {
|
||||
pageNum = 0;
|
||||
return NOT_FOUND;
|
||||
} else {
|
||||
return PARSER_ERROR;
|
||||
}
|
||||
|
||||
p = 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.+?/>"
|
||||
+ "|inits~([^<>\"~]+~[^<>\"~]+)~([^<>]+))" // 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
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
|
||||
gi.category = EhUtils.getCategory(m.group(1));
|
||||
gi.posted = m.group(2);
|
||||
gi.thumbHeight = Integer.parseInt(m.group(3));
|
||||
gi.thumbWidth = Integer.parseInt(m.group(4));
|
||||
|
||||
if (m.group(5) == null) {
|
||||
gi.thumb = Utils.unescapeXml("http://"
|
||||
+ m.group(7).replace('~', '/'));
|
||||
gi.title = Utils.unescapeXml(m.group(8));
|
||||
} else {
|
||||
gi.thumb = Utils.unescapeXml(m.group(5));
|
||||
gi.title = Utils.unescapeXml(m.group(6));
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern
|
||||
.compile("/(\\d+)/(\\w+)");
|
||||
Matcher matcher = pattern.matcher(m.group(9));
|
||||
if (matcher.find()) {
|
||||
gi.gid = Integer.parseInt(matcher.group(1));
|
||||
gi.token = matcher.group(2);
|
||||
} else
|
||||
continue;
|
||||
|
||||
gi.rating = Float.parseFloat(getRate(m.group(11)));
|
||||
gi.uploader = m.group(12);
|
||||
gi.generateSLang();
|
||||
|
||||
giList.add(gi);
|
||||
}
|
||||
return ALL;
|
||||
case EhClient.MODE_G:
|
||||
default:
|
||||
p = Pattern.compile("<a[^<>]+>([\\d]+)</a></td><td[^<>]+>(?:<a[^<>]+>)?&");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
pageNum = Integer.parseInt(m.group(1));
|
||||
} else if (body.contains("No hits found</p>")) {
|
||||
pageNum = 0;
|
||||
return NOT_FOUND;
|
||||
} else {
|
||||
return PARSER_ERROR;
|
||||
}
|
||||
|
||||
p = 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
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
|
||||
gi.category = EhUtils.getCategory(m.group(1));
|
||||
gi.posted = m.group(2);
|
||||
gi.thumbHeight = Integer.parseInt(m.group(3));
|
||||
gi.thumbWidth = Integer.parseInt(m.group(4));
|
||||
|
||||
if (m.group(5) == null) {
|
||||
gi.thumb = Utils.unescapeXml("http://"
|
||||
+ m.group(7).replace('~', '/'));
|
||||
gi.title = Utils.unescapeXml(m.group(8));
|
||||
} else {
|
||||
gi.thumb = Utils.unescapeXml(m.group(5));
|
||||
gi.title = Utils.unescapeXml(m.group(6));
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern
|
||||
.compile("/(\\d+)/(\\w+)");
|
||||
Matcher matcher = pattern.matcher(m.group(9));
|
||||
if (matcher.find()) {
|
||||
gi.gid = Integer.parseInt(matcher.group(1));
|
||||
gi.token = matcher.group(2);
|
||||
} else
|
||||
continue;
|
||||
|
||||
gi.rating = Float.parseFloat(getRate(m.group(11)));
|
||||
gi.uploader = m.group(12);
|
||||
gi.generateSLang();
|
||||
|
||||
giList.add(gi);
|
||||
}
|
||||
return ALL;
|
||||
}
|
||||
}
|
||||
|
||||
private String getRate(String rawRate) {
|
||||
Pattern p = Pattern.compile("\\d+px");
|
||||
Matcher m = p.matcher(rawRate);
|
||||
int num1;
|
||||
int num2;
|
||||
int rate = 5;
|
||||
String re;
|
||||
if (m.find())
|
||||
num1 = Integer.parseInt(m.group().replace("px", ""));
|
||||
else
|
||||
return null;
|
||||
if (m.find())
|
||||
num2 = Integer.parseInt(m.group().replace("px", ""));
|
||||
else
|
||||
return null;
|
||||
rate = rate - num1 / 16;
|
||||
if (num2 == 21) {
|
||||
rate--;
|
||||
re = Integer.toString(rate);
|
||||
re = re + ".5";
|
||||
} else
|
||||
re = Integer.toString(rate);
|
||||
return re;
|
||||
}
|
||||
|
||||
private static final String PAU_SPACER = " by ";
|
||||
|
||||
private boolean getPostedAndUploader(String raw, String[] pau) {
|
||||
int index = raw.indexOf(PAU_SPACER);
|
||||
if (index == -1) {
|
||||
return false;
|
||||
} else {
|
||||
pau[0] = raw.substring(0, index);
|
||||
pau[1] = raw.substring(index + PAU_SPACER.length());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private int getStartNum(String str) {
|
||||
int startNum = 0;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
if (str.charAt(i) == '*')
|
||||
startNum++;
|
||||
}
|
||||
return startNum;
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.hippo.ehviewer.data.LargePreviewList;
|
||||
|
||||
|
||||
public class LofiDetailParser {
|
||||
|
||||
public boolean isLastPage;
|
||||
public LargePreviewList preview;
|
||||
public String emesg;
|
||||
|
||||
public boolean parser(String body) {
|
||||
Pattern p;
|
||||
Matcher m;
|
||||
|
||||
if (body == null)
|
||||
return false;
|
||||
|
||||
// Get preview
|
||||
p = Pattern.compile("<div class=\"gi\"[^>]+><a[^>]+href=\"([^>\"]+)\"[^>]+><img[^>]+src=\"([^>\"]+)\"[^>]+>");
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
if (preview == null)
|
||||
preview = new LargePreviewList();
|
||||
preview.addItem(m.group(2), m.group(1));
|
||||
}
|
||||
// Check is last page
|
||||
p = Pattern.compile("<a[^>]+>Next Page ></a>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
isLastPage = false;
|
||||
else
|
||||
isLastPage = true;
|
||||
|
||||
return preview != null;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.ehclient;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class LoginParser {
|
||||
public String displayname;
|
||||
public String eMesg;
|
||||
|
||||
public boolean parser(String body) {
|
||||
Pattern p;
|
||||
Matcher m;
|
||||
|
||||
if (body == null)
|
||||
return false;
|
||||
|
||||
p = Pattern.compile("<p>You are now logged in as: (.+?)<br />");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
displayname = m.group(1);
|
||||
return true;
|
||||
} else {
|
||||
p = Pattern.compile("(?:<h4>The error returned was:</h4>\\s*<p>(.+?)</p>)"
|
||||
+ "|(?:<span class=\"postcolor\">(.+?)</span>)");
|
||||
m = p.matcher(body);
|
||||
|
||||
if (m.find())
|
||||
eMesg = m.group(1) == null ? m.group(2) : m.group(1);
|
||||
else
|
||||
eMesg = "Unknown error";
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Pair;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class TorrentParser {
|
||||
|
||||
/**
|
||||
*
|
||||
* @return the param or new instance if size changed
|
||||
*/
|
||||
public static Pair<String, String>[] parse(String body, @Nullable Pair<String, String>[] torrents) {
|
||||
List<Pair<String, String>> torrentList;
|
||||
int arrayLength;
|
||||
int size = 0;
|
||||
|
||||
if (torrents == null) {
|
||||
arrayLength = 0;
|
||||
torrentList = new LinkedList<>();
|
||||
} else {
|
||||
arrayLength = torrents.length;
|
||||
torrentList = null;
|
||||
}
|
||||
|
||||
Pattern p = Pattern.compile("<td colspan=\"5\"> <a href=\"([^\"]+)\">([^<>]*)</a></td>");
|
||||
Matcher m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
size++;
|
||||
|
||||
if (size > arrayLength && torrentList == null) {
|
||||
torrentList = new LinkedList<>();
|
||||
// Copy data
|
||||
int copySize = size - 1;
|
||||
for (int i = 0; i < copySize; i++) {
|
||||
torrentList.add(torrents[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove ?p= to make torrent redistributable
|
||||
String url = m.group(1);
|
||||
if (url == null) {
|
||||
size--;
|
||||
continue;
|
||||
}
|
||||
int index = url.indexOf("?p=");
|
||||
if (index != -1) {
|
||||
url = url.substring(0, index);
|
||||
}
|
||||
|
||||
Pair<String, String> newItem = new Pair<>(url, Utils.unescapeXml(m.group(2)));
|
||||
if (torrentList != null) {
|
||||
torrentList.add(newItem);
|
||||
} else {
|
||||
torrents[size - 1] = newItem;
|
||||
}
|
||||
}
|
||||
|
||||
if (torrentList != null) {
|
||||
//noinspection unchecked,SuspiciousToArrayCall
|
||||
return (Pair<String, String>[]) torrentList.toArray(new Pair[torrentList.size()]);
|
||||
} else if (size == arrayLength){
|
||||
return torrents;
|
||||
} else {
|
||||
//noinspection unchecked
|
||||
Pair<String, String>[] result = new Pair[size];
|
||||
System.arraycopy(torrents, 0, result, 0, size);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,176 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2012 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.anim;
|
||||
|
||||
import android.view.animation.DecelerateInterpolator;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
|
||||
import com.hippo.ehviewer.gallery.glrenderer.RawTexture;
|
||||
import com.hippo.ehviewer.gallery.ui.GLView;
|
||||
|
||||
public class StateTransitionAnimation extends Animation {
|
||||
|
||||
public static class Spec {
|
||||
public static final Spec OUTGOING;
|
||||
public static final Spec INCOMING;
|
||||
public static final Spec PHOTO_INCOMING;
|
||||
|
||||
private static final Interpolator DEFAULT_INTERPOLATOR =
|
||||
new DecelerateInterpolator();
|
||||
|
||||
public int duration = 330;
|
||||
public float backgroundAlphaFrom = 0;
|
||||
public float backgroundAlphaTo = 0;
|
||||
public float backgroundScaleFrom = 0;
|
||||
public float backgroundScaleTo = 0;
|
||||
public float contentAlphaFrom = 1;
|
||||
public float contentAlphaTo = 1;
|
||||
public float contentScaleFrom = 1;
|
||||
public float contentScaleTo = 1;
|
||||
public float overlayAlphaFrom = 0;
|
||||
public float overlayAlphaTo = 0;
|
||||
public float overlayScaleFrom = 0;
|
||||
public float overlayScaleTo = 0;
|
||||
public Interpolator interpolator = DEFAULT_INTERPOLATOR;
|
||||
|
||||
static {
|
||||
OUTGOING = new Spec();
|
||||
OUTGOING.backgroundAlphaFrom = 0.5f;
|
||||
OUTGOING.backgroundAlphaTo = 0f;
|
||||
OUTGOING.backgroundScaleFrom = 1f;
|
||||
OUTGOING.backgroundScaleTo = 0f;
|
||||
OUTGOING.contentAlphaFrom = 0.5f;
|
||||
OUTGOING.contentAlphaTo = 1f;
|
||||
OUTGOING.contentScaleFrom = 3f;
|
||||
OUTGOING.contentScaleTo = 1f;
|
||||
|
||||
INCOMING = new Spec();
|
||||
INCOMING.overlayAlphaFrom = 1f;
|
||||
INCOMING.overlayAlphaTo = 0f;
|
||||
INCOMING.overlayScaleFrom = 1f;
|
||||
INCOMING.overlayScaleTo = 3f;
|
||||
INCOMING.contentAlphaFrom = 0f;
|
||||
INCOMING.contentAlphaTo = 1f;
|
||||
INCOMING.contentScaleFrom = 0.25f;
|
||||
INCOMING.contentScaleTo = 1f;
|
||||
|
||||
PHOTO_INCOMING = INCOMING;
|
||||
}
|
||||
|
||||
private static Spec specForTransition(Transition t) {
|
||||
switch (t) {
|
||||
case Outgoing:
|
||||
return Spec.OUTGOING;
|
||||
case Incoming:
|
||||
return Spec.INCOMING;
|
||||
case PhotoIncoming:
|
||||
return Spec.PHOTO_INCOMING;
|
||||
case None:
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static enum Transition { None, Outgoing, Incoming, PhotoIncoming }
|
||||
|
||||
private final Spec mTransitionSpec;
|
||||
private float mCurrentContentScale;
|
||||
private float mCurrentContentAlpha;
|
||||
private float mCurrentBackgroundScale;
|
||||
private float mCurrentBackgroundAlpha;
|
||||
private float mCurrentOverlayScale;
|
||||
private float mCurrentOverlayAlpha;
|
||||
private RawTexture mOldScreenTexture;
|
||||
|
||||
public StateTransitionAnimation(Transition t, RawTexture oldScreen) {
|
||||
this(Spec.specForTransition(t), oldScreen);
|
||||
}
|
||||
|
||||
public StateTransitionAnimation(Spec spec, RawTexture oldScreen) {
|
||||
mTransitionSpec = spec != null ? spec : Spec.OUTGOING;
|
||||
setDuration(mTransitionSpec.duration);
|
||||
setInterpolator(mTransitionSpec.interpolator);
|
||||
mOldScreenTexture = oldScreen;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean calculate(long currentTimeMillis) {
|
||||
boolean retval = super.calculate(currentTimeMillis);
|
||||
if (!isActive()) {
|
||||
if (mOldScreenTexture != null) {
|
||||
mOldScreenTexture.recycle();
|
||||
mOldScreenTexture = null;
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCalculate(float progress) {
|
||||
mCurrentContentScale = mTransitionSpec.contentScaleFrom
|
||||
+ (mTransitionSpec.contentScaleTo - mTransitionSpec.contentScaleFrom) * progress;
|
||||
mCurrentContentAlpha = mTransitionSpec.contentAlphaFrom
|
||||
+ (mTransitionSpec.contentAlphaTo - mTransitionSpec.contentAlphaFrom) * progress;
|
||||
mCurrentBackgroundAlpha = mTransitionSpec.backgroundAlphaFrom
|
||||
+ (mTransitionSpec.backgroundAlphaTo - mTransitionSpec.backgroundAlphaFrom)
|
||||
* progress;
|
||||
mCurrentBackgroundScale = mTransitionSpec.backgroundScaleFrom
|
||||
+ (mTransitionSpec.backgroundScaleTo - mTransitionSpec.backgroundScaleFrom)
|
||||
* progress;
|
||||
mCurrentOverlayScale = mTransitionSpec.overlayScaleFrom
|
||||
+ (mTransitionSpec.overlayScaleTo - mTransitionSpec.overlayScaleFrom) * progress;
|
||||
mCurrentOverlayAlpha = mTransitionSpec.overlayAlphaFrom
|
||||
+ (mTransitionSpec.overlayAlphaTo - mTransitionSpec.overlayAlphaFrom) * progress;
|
||||
}
|
||||
|
||||
private void applyOldTexture(GLView view, GLCanvas canvas, float alpha, float scale, boolean clear) {
|
||||
if (mOldScreenTexture == null)
|
||||
return;
|
||||
if (clear) canvas.clearBuffer(view.getBackgroundColor());
|
||||
canvas.save();
|
||||
canvas.setAlpha(alpha);
|
||||
int xOffset = view.getWidth() / 2;
|
||||
int yOffset = view.getHeight() / 2;
|
||||
canvas.translate(xOffset, yOffset);
|
||||
canvas.scale(scale, scale, 1);
|
||||
mOldScreenTexture.draw(canvas, -xOffset, -yOffset);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
public void applyBackground(GLView view, GLCanvas canvas) {
|
||||
if (mCurrentBackgroundAlpha > 0f) {
|
||||
applyOldTexture(view, canvas, mCurrentBackgroundAlpha, mCurrentBackgroundScale, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void applyContentTransform(GLView view, GLCanvas canvas) {
|
||||
int xOffset = view.getWidth() / 2;
|
||||
int yOffset = view.getHeight() / 2;
|
||||
canvas.translate(xOffset, yOffset);
|
||||
canvas.scale(mCurrentContentScale, mCurrentContentScale, 1);
|
||||
canvas.translate(-xOffset, -yOffset);
|
||||
canvas.setAlpha(mCurrentContentAlpha);
|
||||
}
|
||||
|
||||
public void applyOverlay(GLView view, GLCanvas canvas) {
|
||||
if (mCurrentOverlayAlpha > 0f) {
|
||||
applyOldTexture(view, canvas, mCurrentOverlayAlpha, mCurrentOverlayScale, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,297 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.data;
|
||||
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Movie;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloader;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.gallery.image.Image;
|
||||
import com.hippo.ehviewer.util.AutoExpandArray;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
|
||||
private static final String TAG = ImageSet.class.getSimpleName();
|
||||
|
||||
/**
|
||||
* These are code reture by getImage()
|
||||
*/
|
||||
public static final int RESULT_NONE = 0x0;
|
||||
public static final int RESULT_DOWNLOADING = 0x1;
|
||||
public static final int RESULT_DECODE = 0x2;
|
||||
|
||||
private final ExDownloaderManager mEdManager;
|
||||
private final ExDownloader mExDownloader;
|
||||
|
||||
private final File mDir;
|
||||
private final AutoExpandArray<String> mImageFilenameArray;
|
||||
private ImageListener mListener;
|
||||
private final Queue<DecodeInfo> mDecodeQueue = new ConcurrentLinkedQueue<>();
|
||||
private final Map<Integer, Float> mPercentMap = new ConcurrentHashMap<>(5);
|
||||
private final DecodeWorker mDecodeWorker;
|
||||
/** If true, then wake Worker, worker will stop **/
|
||||
private volatile boolean mStopWork = false;
|
||||
|
||||
public class DecodeInfo {
|
||||
public int index;
|
||||
public String filename;
|
||||
|
||||
public DecodeInfo(int index, String filename) {
|
||||
this.index = index;
|
||||
this.filename = filename;
|
||||
}
|
||||
}
|
||||
|
||||
public interface ImageListener {
|
||||
/**
|
||||
* It will be invoke when ExDownloader download successful
|
||||
*
|
||||
* @param index
|
||||
*/
|
||||
void onGetImage(int index);
|
||||
|
||||
void onDownloading(int index, float percent);
|
||||
|
||||
/**
|
||||
* It will be invoke when decode image over
|
||||
*
|
||||
* @param index
|
||||
* @param res
|
||||
*/
|
||||
void onDecodeOver(int index, Object res);
|
||||
}
|
||||
|
||||
public ImageSet(int gid, String token, String title, int startIndex) {
|
||||
|
||||
mDir = EhUtils.getGalleryDir(gid, title);
|
||||
Utils.ensureDir(mDir, true);
|
||||
|
||||
// Init ExDownloader
|
||||
mEdManager = ExDownloaderManager.getInstance();
|
||||
mExDownloader = mEdManager.getExDownloader(gid, token, title, Config.getMode());
|
||||
mExDownloader.setListenerForImageSet(this);
|
||||
mExDownloader.setStartIndex(startIndex);
|
||||
|
||||
mImageFilenameArray = mExDownloader.getImageFilenameArray();
|
||||
|
||||
// Start decode worker
|
||||
mDecodeWorker = new DecodeWorker();
|
||||
mDecodeWorker.start();
|
||||
}
|
||||
|
||||
public boolean isStop() {
|
||||
return mStopWork;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return mExDownloader.getImageNum();
|
||||
}
|
||||
|
||||
public int getEnsureSize() {
|
||||
return mExDownloader.getMaxEnsureIndex() + 1;
|
||||
}
|
||||
|
||||
public void setImageListener(ImageListener l) {
|
||||
mListener = l;
|
||||
}
|
||||
|
||||
public void addTargetIndex(int index) {
|
||||
mExDownloader.addTargetIndex(index);
|
||||
}
|
||||
|
||||
public void setStartIndex(int startIndex) {
|
||||
mExDownloader.setStartIndex(startIndex);
|
||||
}
|
||||
|
||||
public void setCurReadIndex(int index) {
|
||||
mExDownloader.setCurReadIndex(index);
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return mExDownloader.getTitle();
|
||||
}
|
||||
|
||||
public File getImageFile(int index) {
|
||||
File file = null;
|
||||
String name = getImageFilename(index);
|
||||
if (name != null)
|
||||
file = new File(mDir, name);
|
||||
return file;
|
||||
}
|
||||
|
||||
private String getImageFilename(int index) {
|
||||
String filename = mImageFilenameArray.get(index);
|
||||
if (filename == null) {
|
||||
// Just guess filename
|
||||
for (String possibleFilename : EhUtils.getPossibleImageFilenames(index)) {
|
||||
if (new File(mDir, possibleFilename).exists()) {
|
||||
// Get filename
|
||||
filename = possibleFilename;
|
||||
mImageFilenameArray.set(index, filename);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
public void redownload(int index) {
|
||||
String filename = getImageFilename(index);
|
||||
if (filename != null) {
|
||||
// Delete file
|
||||
new File(mDir, filename).delete();
|
||||
}
|
||||
mExDownloader.addTargetIndex(index);
|
||||
mListener.onGetImage(index);
|
||||
}
|
||||
|
||||
public Object getImage(int index) {
|
||||
String filename = getImageFilename(index);
|
||||
Float percent;
|
||||
|
||||
if ((percent = mPercentMap.get(index)) != null) {
|
||||
return percent;
|
||||
} else if (mExDownloader.isDownloading(index)) {
|
||||
// downloading
|
||||
return RESULT_DOWNLOADING;
|
||||
} else if (filename == null || !new File(mDir, filename).exists()) {
|
||||
// Target index has not being downloading
|
||||
return RESULT_NONE;
|
||||
} else {
|
||||
mDecodeQueue.offer(new DecodeInfo(index, filename));
|
||||
// wake decode worker
|
||||
synchronized(mDecodeQueue) {mDecodeQueue.notify();}
|
||||
return RESULT_DECODE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* You must call it when you do not need it any more
|
||||
*/
|
||||
public void free() {
|
||||
mStopWork = true;
|
||||
// wake decode worker to wash wash sleep
|
||||
synchronized(mDecodeQueue) {mDecodeQueue.notify();}
|
||||
|
||||
// Remove listener for ImageSet
|
||||
mExDownloader.setListenerForImageSet(null);
|
||||
// Free ExDownloader
|
||||
mEdManager.freeExDownloader(mExDownloader);
|
||||
}
|
||||
|
||||
private class DecodeWorker extends BgThread {
|
||||
@Override
|
||||
public void run() {
|
||||
DecodeInfo decodeInfo;
|
||||
while (true) {
|
||||
// Check stop work or not
|
||||
if (mStopWork)
|
||||
break;
|
||||
|
||||
// Get decode task
|
||||
synchronized (mDecodeQueue) {
|
||||
if (mDecodeQueue.isEmpty()) {
|
||||
try {
|
||||
mDecodeQueue.wait();
|
||||
} catch (InterruptedException e) {}
|
||||
continue;
|
||||
}
|
||||
decodeInfo = mDecodeQueue.poll();
|
||||
}
|
||||
|
||||
// do decode
|
||||
final int index = decodeInfo.index;
|
||||
String pathName = Utils.getPathName(mDir.getPath(), decodeInfo.filename);
|
||||
Object res = null;
|
||||
|
||||
if (Utils.SUPPORT_IMAGE && Config.getCustomCodec()) {
|
||||
res = Image.decodeFile(pathName, Config.getDecodeFormat());
|
||||
} else {
|
||||
if (Utils.getExtension(pathName, "jpg").equals("gif"))
|
||||
res = Movie.decodeFile(pathName);
|
||||
else
|
||||
res = BitmapFactory.decodeFile(pathName);
|
||||
}
|
||||
|
||||
final Object _res = res;
|
||||
// Post to UI thread
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mListener != null)
|
||||
mListener.onDecodeOver(index, _res);
|
||||
}
|
||||
});
|
||||
}
|
||||
Log.d(TAG, "DecodeWorker stop working");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStart(final int index) {
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mListener != null)
|
||||
mListener.onDownloading(index, 0.0f);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloading(final int index, final float percent) {
|
||||
mPercentMap.put(index, percent);
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mListener != null)
|
||||
mListener.onDownloading(index, percent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadComplete(final int index) {
|
||||
mPercentMap.remove(index);
|
||||
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mListener != null)
|
||||
mListener.onGetImage(index);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadFail(int index) {
|
||||
mPercentMap.remove(index);
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.glrenderer;
|
||||
|
||||
import javax.microedition.khronos.opengles.GL11;
|
||||
|
||||
import android.opengl.GLES20;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.gallery.image.Image;
|
||||
|
||||
public class ImageTexture extends BasicTexture implements Uploaded {
|
||||
|
||||
private static final String TAG = ImageTexture.class.getSimpleName();
|
||||
|
||||
private Image mImage;
|
||||
private boolean mContentValid = true;
|
||||
private boolean mOpaque = true;
|
||||
|
||||
public ImageTexture(Image image) {
|
||||
mImage = image;
|
||||
setSize(image.getWidth(), image.getHeight());
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (mImage != null)
|
||||
mImage.start();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (mImage != null)
|
||||
mImage.stop();
|
||||
}
|
||||
|
||||
public boolean isAnimated() {
|
||||
if (mImage == null || mImage.isRecycled())
|
||||
return false;
|
||||
else
|
||||
return mImage.isAnimated();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpaque() {
|
||||
return mOpaque;
|
||||
}
|
||||
|
||||
public void setOpaque(boolean opaque) {
|
||||
mOpaque = opaque;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the content on GPU is valid.
|
||||
*/
|
||||
@Override
|
||||
public boolean isContentValid() {
|
||||
return isLoaded() && mContentValid;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getTarget() {
|
||||
return GL11.GL_TEXTURE_2D;
|
||||
}
|
||||
|
||||
public int getFormat() {
|
||||
return mImage.getFormat();
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return mImage.getType();
|
||||
}
|
||||
|
||||
public static void checkError() {
|
||||
int error = GLES20.glGetError();
|
||||
if (error != 0) {
|
||||
Throwable t = new Throwable();
|
||||
Log.e(TAG, "GL error: " + error, t);
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadToCanvas(GLCanvas canvas) {
|
||||
mId = canvas.getGLId().generateTexture();
|
||||
int format = getFormat();
|
||||
int type = getType();
|
||||
|
||||
canvas.setTextureParameters(this);
|
||||
canvas.initializeTextureSize(this, format, type);
|
||||
|
||||
GLES20.glBindTexture(getTarget(), mId);
|
||||
checkError();
|
||||
mImage.render();
|
||||
|
||||
setAssociatedCanvas(canvas);
|
||||
mState = STATE_LOADED;
|
||||
mContentValid = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateContent(GLCanvas canvas) {
|
||||
if (!isLoaded()) {
|
||||
uploadToCanvas(canvas);
|
||||
} else if (isAnimated()) {
|
||||
GLES20.glBindTexture(getTarget(), mId);
|
||||
checkError();
|
||||
mImage.render();
|
||||
|
||||
mContentValid = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onBind(GLCanvas canvas) {
|
||||
if (mImage == null || mImage.isRecycled()) {
|
||||
return false;
|
||||
} else {
|
||||
updateContent(canvas);
|
||||
return isContentValid();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recycle() {
|
||||
super.recycle();
|
||||
if (mImage != null) {
|
||||
mImage.recycle();
|
||||
mImage = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.image;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
public class GifImage extends Image {
|
||||
|
||||
private static final String TAG = Image.class.getSimpleName();
|
||||
|
||||
private final int mImageCount;
|
||||
private final int[] mDelayArray;
|
||||
private long mDelaySum;
|
||||
private volatile long mStartTime;
|
||||
private volatile long mStopTime = -1;
|
||||
private volatile boolean mRunning = true;
|
||||
|
||||
private int mLastIndex = -1;
|
||||
|
||||
protected GifImage(long nativeImage, int fileFormat, int width, int height,
|
||||
int format, int type, int[] delayArray) {
|
||||
super(nativeImage, fileFormat, width, height, format, type);
|
||||
mImageCount = delayArray.length;
|
||||
mDelayArray = delayArray;
|
||||
|
||||
mDelaySum = 0;
|
||||
for (int delay : delayArray)
|
||||
mDelaySum += delay;
|
||||
}
|
||||
|
||||
private int getCurIndex() {
|
||||
int index = 0;
|
||||
if (mRunning) {
|
||||
if (mLastIndex == -1) {
|
||||
index = 0;
|
||||
mStartTime = System.currentTimeMillis();
|
||||
} else {
|
||||
long curTime = System.currentTimeMillis();
|
||||
long time = (curTime - mStartTime) % mDelaySum;
|
||||
int end = mImageCount - 1;
|
||||
for (; index < end && (time -= mDelayArray[index]) > 0; index++)
|
||||
;
|
||||
}
|
||||
return index;
|
||||
} else {
|
||||
return mLastIndex == -1 ? index : mLastIndex;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
if (!mRunning) {
|
||||
mRunning = true;
|
||||
long curTime = System.currentTimeMillis();
|
||||
mStartTime = curTime - (mStopTime == -1 ? curTime : mStopTime)
|
||||
+ mStartTime;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (mRunning) {
|
||||
mRunning = false;
|
||||
mStopTime = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnimated() {
|
||||
return mImageCount > 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
render(getCurIndex());
|
||||
}
|
||||
|
||||
public void render(int index) {
|
||||
if (mNativeImage != 0) {
|
||||
if (index >= mImageCount || index < 0) {
|
||||
Log.d(TAG, "GifImage try render index " + index + ", but image count is " + mImageCount);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mLastIndex != index) {
|
||||
nativeRender(mFormat, mType, mNativeImage, FILE_FORMAT_GIF,
|
||||
index);
|
||||
mLastIndex = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
System.loadLibrary("image");
|
||||
}
|
||||
|
||||
private static native void nativeRender(int format, int type,
|
||||
long nativeImage, int fileFormat, int index);
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.image;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.microedition.khronos.opengles.GL11;
|
||||
|
||||
public class Image {
|
||||
|
||||
private static final String TAG = Image.class.getSimpleName();
|
||||
|
||||
public static final int FILE_FORMAT_JPEG = 0x0;
|
||||
public static final int FILE_FORMAT_PNG = 0x1;
|
||||
public static final int FILE_FORMAT_BMP = 0x2;
|
||||
public static final int FILE_FORMAT_GIF = 0x3;
|
||||
|
||||
public static final int FORMAT_AUTO = 0x0;
|
||||
public static final int FORMAT_GRAY = GL11.GL_LUMINANCE;
|
||||
public static final int FORMAT_GRAY_ALPHA = GL11.GL_LUMINANCE_ALPHA;
|
||||
public static final int FORMAT_RGB = GL11.GL_RGB;
|
||||
public static final int FORMAT_RGBA = GL11.GL_RGBA;
|
||||
|
||||
protected long mNativeImage;
|
||||
protected final int mFileFormat;
|
||||
protected final int mWidth;
|
||||
protected final int mHeight;
|
||||
|
||||
protected final int mFormat;
|
||||
protected final int mType;
|
||||
|
||||
protected Image(long nativeImage, int fileFormat, int width, int height,
|
||||
int format, int type) {
|
||||
mNativeImage = nativeImage;
|
||||
mFileFormat = fileFormat;
|
||||
mWidth = width;
|
||||
mHeight = height;
|
||||
mFormat = format;
|
||||
mType = type;
|
||||
}
|
||||
|
||||
public int getFileFormat() {
|
||||
return mFileFormat;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return mWidth;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return mHeight;
|
||||
}
|
||||
|
||||
public int getFormat() {
|
||||
return mFormat;
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return mType;
|
||||
}
|
||||
|
||||
public boolean isAnimated() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public void render() {
|
||||
if (mNativeImage != 0) {
|
||||
nativeRender(mFormat, mType, mNativeImage, mFileFormat);
|
||||
}
|
||||
}
|
||||
|
||||
public void recycle() {
|
||||
if (mNativeImage != 0) {
|
||||
nativeFree(mNativeImage, mFileFormat);
|
||||
mNativeImage = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRecycled() {
|
||||
return mNativeImage == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* format can be GL11.GL_RGB, GL11.GL_RGBA, GL11.GL_LUMINANCE,
|
||||
* GL11.GL_LUMINANCE_ALPHA
|
||||
*
|
||||
* @param is
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static final Image decodeStream(InputStream is, int format) {
|
||||
return nativeDecodeStream(is, format);
|
||||
}
|
||||
|
||||
public static final Image decodeFile(String pathName, int format) {
|
||||
return nativeDecodeFile(pathName, format);
|
||||
}
|
||||
|
||||
static {
|
||||
System.loadLibrary("image");
|
||||
}
|
||||
|
||||
private static native Image nativeDecodeStream(InputStream is, int format);
|
||||
|
||||
private static native Image nativeDecodeFile(String pathName, int format);
|
||||
|
||||
private static native void nativeFree(long nativeImage, int format);
|
||||
|
||||
private static native void nativeRender(int format, int type,
|
||||
long nativeImage, int fileFormat);
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.ui;
|
||||
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.os.Handler;
|
||||
|
||||
public abstract class TimeRunner {
|
||||
private static final int INTERVAL = 5;
|
||||
|
||||
private static final int RUNNING = 0x0;
|
||||
private static final int START = 0x1;
|
||||
private static final int END = 0x2;
|
||||
private static final int CANCEL = 0x3;
|
||||
|
||||
private boolean mDoInThread = false;
|
||||
private int mDuration = 0;
|
||||
private int mDelay = 0;
|
||||
private TimeInterpolator mInterpolator;
|
||||
private Handler mHandler;
|
||||
private volatile boolean mCancel = false;
|
||||
|
||||
private class Respond implements Runnable {
|
||||
private final int state;
|
||||
private float interpolatedTime;
|
||||
private int runningTime;
|
||||
|
||||
public Respond(int state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public Respond(float interpolatedTime, int runningTime) {
|
||||
this.state = RUNNING;
|
||||
this.interpolatedTime = interpolatedTime;
|
||||
this.runningTime = runningTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
switch (state) {
|
||||
case RUNNING:
|
||||
TimeRunner.this.onRun(interpolatedTime, runningTime);
|
||||
break;
|
||||
case START:
|
||||
TimeRunner.this.onStart();
|
||||
break;
|
||||
case END:
|
||||
TimeRunner.this.onEnd();
|
||||
break;
|
||||
case CANCEL:
|
||||
TimeRunner.this.onCancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setDuration(int duration) {
|
||||
mDuration = duration;
|
||||
}
|
||||
|
||||
public void setDoInThread(boolean doInThread) {
|
||||
mDoInThread = doInThread;
|
||||
}
|
||||
|
||||
public void setHandler(Handler handler) {
|
||||
mHandler = handler;
|
||||
mDoInThread = false;
|
||||
}
|
||||
|
||||
public void setInterpolator(TimeInterpolator interpolator) {
|
||||
mInterpolator = interpolator;
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
mCancel = true;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
start(0);
|
||||
}
|
||||
|
||||
public void start(int delay) {
|
||||
mCancel = false;
|
||||
mDelay = delay;
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(mDelay);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (mDoInThread || mHandler == null)
|
||||
onStart();
|
||||
else
|
||||
mHandler.post(new Respond(START));
|
||||
|
||||
// Check cancel
|
||||
if (mCancel) {
|
||||
if (mDoInThread || mHandler == null)
|
||||
onStart();
|
||||
else
|
||||
mHandler.post(new Respond(CANCEL));
|
||||
return;
|
||||
}
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
for (int runningTime = 0; runningTime < mDuration; runningTime = (int)(System.currentTimeMillis() - startTime)) {
|
||||
// Check cancel
|
||||
if (mCancel) {
|
||||
if (mDoInThread || mHandler == null)
|
||||
onStart();
|
||||
else
|
||||
mHandler.post(new Respond(CANCEL));
|
||||
return;
|
||||
}
|
||||
|
||||
float percent = runningTime / (float)mDuration;
|
||||
if (mInterpolator != null)
|
||||
percent = mInterpolator.getInterpolation(percent);
|
||||
|
||||
if (mDoInThread || mHandler == null)
|
||||
TimeRunner.this.onRun(percent, runningTime);
|
||||
else
|
||||
mHandler.post(new Respond(percent, runningTime));
|
||||
try {
|
||||
Thread.sleep(INTERVAL);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if (mDoInThread || mHandler == null)
|
||||
onEnd();
|
||||
else
|
||||
mHandler.post(new Respond(END));
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
protected abstract void onStart();
|
||||
protected abstract void onRun(float percent, int runningTime);
|
||||
protected abstract void onEnd();
|
||||
protected abstract void onCancel();
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2010 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.gallery.util;
|
||||
|
||||
import android.graphics.Color;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
public class GalleryUtils {
|
||||
private static final String TAG = GalleryUtils.class.getSimpleName();
|
||||
|
||||
public static float[] intColorToFloatARGBArray(int from) {
|
||||
return new float[] {
|
||||
Color.alpha(from) / 255f,
|
||||
Color.red(from) / 255f,
|
||||
Color.green(from) / 255f,
|
||||
Color.blue(from) / 255f
|
||||
};
|
||||
}
|
||||
|
||||
// Below are used the detect using database in the render thread. It only
|
||||
// works most of the time, but that's ok because it's for debugging only.
|
||||
|
||||
private static volatile Thread sCurrentThread;
|
||||
private static volatile boolean sWarned;
|
||||
|
||||
public static void setRenderThread() {
|
||||
sCurrentThread = Thread.currentThread();
|
||||
}
|
||||
|
||||
public static void assertNotInRenderThread() {
|
||||
if (!sWarned) {
|
||||
if (Thread.currentThread() == sCurrentThread) {
|
||||
sWarned = true;
|
||||
Log.w(TAG, new Throwable("Should not do this in render thread"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public final class ActivityHelper {
|
||||
|
||||
public static boolean sendEmail(@NonNull Activity from, @NonNull String address,
|
||||
@Nullable String subject, @Nullable String text) {
|
||||
Intent i = new Intent(Intent.ACTION_SENDTO);
|
||||
i.setData(Uri.parse("mailto:" + address));
|
||||
if (subject != null) {
|
||||
i.putExtra(Intent.EXTRA_SUBJECT, subject);
|
||||
}
|
||||
if (text != null) {
|
||||
i.putExtra(Intent.EXTRA_TEXT, text);
|
||||
}
|
||||
|
||||
try {
|
||||
from.startActivity(i);
|
||||
return true;
|
||||
} catch (ActivityNotFoundException e) {
|
||||
MaterialToast.showToast(R.string.em_cant_find_activity);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean share(@NonNull Activity from, String text) {
|
||||
Intent sendIntent = new Intent();
|
||||
sendIntent.setAction(Intent.ACTION_SEND);
|
||||
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
|
||||
sendIntent.setType("text/plain");
|
||||
|
||||
try {
|
||||
from.startActivity(sendIntent);
|
||||
return true;
|
||||
} catch (ActivityNotFoundException e) {
|
||||
MaterialToast.showToast(R.string.em_cant_find_activity);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class Downloader implements Runnable, HttpHelper.OnDownloadListener {
|
||||
|
||||
private Context mContext;
|
||||
private String mUrl;
|
||||
private File mDir;
|
||||
private String mFilename;
|
||||
|
||||
private boolean mIsRunning = false;
|
||||
|
||||
public Downloader(Context context, String url, File dir, String filename) {
|
||||
mContext = context.getApplicationContext();
|
||||
mUrl = url;
|
||||
mDir = dir;
|
||||
mFilename = filename;
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return mIsRunning;
|
||||
}
|
||||
|
||||
public void startDownload() {
|
||||
if (mIsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
mIsRunning = true;
|
||||
new BgThread(this).start();
|
||||
MaterialToast.showToast(R.string.start_saving_torrent);
|
||||
}
|
||||
|
||||
public void post(Runnable runnable) {
|
||||
AppHandler.getInstance().post(runnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
HttpHelper.DownloadOption dOpt = new HttpHelper.DownloadOption();
|
||||
dOpt.setUseProxy(false);
|
||||
dOpt.setAllowFixingExtension(true);
|
||||
dOpt.setAllowFixingName(true);
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
final boolean ok = HttpHelper.DOWNLOAD_OK_STR.equals(
|
||||
hh.download(mUrl, mDir, mFilename, null, null, this));
|
||||
post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
MaterialToast.showToast(ok ?
|
||||
String.format(mContext.getString(R.string.save_torrent_successful),
|
||||
mDir.getAbsolutePath() + File.separatorChar + mFilename) :
|
||||
mContext.getString(R.string.save_torrent_failed));
|
||||
}
|
||||
});
|
||||
mIsRunning = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStartConnect() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStartDownload(int totalSize) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStatusUpdate(int downloadSize, int totalSize) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadOver(int status, String eMsg) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
mFilename = newFilename;
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.miscellaneous;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.ListView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class FavoriteHelper {
|
||||
|
||||
private static Context mContext;
|
||||
private static Resources mResources;
|
||||
|
||||
private static AlertDialog lastAddToFavoriteDialog;
|
||||
|
||||
public static String[] FAVORITE_TITLES;
|
||||
|
||||
public static void init(Context context) {
|
||||
mContext = context;
|
||||
mResources = mContext.getResources();
|
||||
|
||||
FAVORITE_TITLES = new String[EhClient.FAVORITE_SLOT_NUM + 1];
|
||||
FAVORITE_TITLES[0] = mResources.getString(R.string.local_favorite);
|
||||
for (int i = 1; i < EhClient.FAVORITE_SLOT_NUM + 1; i++) {
|
||||
FAVORITE_TITLES[i] = mResources.getString(R.string.favourite) + " "+ (i - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addToFavorite(final Context context, final GalleryInfo gi,
|
||||
final OnAddToFavoriteListener listener) {
|
||||
final int defaultFavorite = Config.getDefaultFavorite();
|
||||
switch (defaultFavorite) {
|
||||
case -2:
|
||||
FavoriteHelper.getAddToFavoriteDialog(context, gi, listener).show();
|
||||
break;
|
||||
case -1:
|
||||
Data.getInstance().addLocalFavourite(gi);
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, -1);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
EhClient.getInstance().addToFavorite(gi.gid,
|
||||
gi.token, defaultFavorite, null, new EhClient.OnAddToFavoriteListener() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, defaultFavorite);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
MaterialToast.showToast(R.string.failed_to_add);
|
||||
if (listener != null) {
|
||||
listener.onFailure(eMsg, gi, defaultFavorite);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
public static AlertDialog getAddToFavoriteDialog(final Context context, final GalleryInfo gi,
|
||||
final OnAddToFavoriteListener listener) {
|
||||
|
||||
View view = ViewUtils.inflateDialogView(R.layout.add_to_favorite, false);
|
||||
final CheckBox cb = (CheckBox) view.findViewById(R.id.set_default);
|
||||
ListView lv = (ListView) view.findViewById(R.id.list);
|
||||
lv.setAdapter(new ArrayAdapter<String>(mContext,
|
||||
R.layout.select_dialog_item, FAVORITE_TITLES));
|
||||
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view,
|
||||
int position, long id) {
|
||||
lastAddToFavoriteDialog.dismiss();
|
||||
lastAddToFavoriteDialog = null;
|
||||
|
||||
if (cb.isChecked())
|
||||
Config.setDefaultFavorite(position - 1);
|
||||
final int favoriteSlot = position - 1;
|
||||
|
||||
switch (position) {
|
||||
case 0:
|
||||
Data.getInstance().addLocalFavourite(gi);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, favoriteSlot);
|
||||
}
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
break;
|
||||
default:
|
||||
EhClient.getInstance().addToFavorite(gi.gid,
|
||||
gi.token, position - 1, null, new EhClient.OnAddToFavoriteListener() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, favoriteSlot);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
MaterialToast.showToast(R.string.failed_to_add);
|
||||
if (listener != null) {
|
||||
listener.onFailure(eMsg, gi, favoriteSlot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return lastAddToFavoriteDialog = new MaterialAlertDialog.Builder(context)
|
||||
.setTitle(R.string.where_to_add)
|
||||
.setView(view, false).setNegativeButton(android.R.string.cancel)
|
||||
.setPositiveButton(android.R.string.ok).create();
|
||||
}
|
||||
|
||||
public interface OnAddToFavoriteListener {
|
||||
void onSuccess(GalleryInfo gi, int slot);
|
||||
void onFailure(String eMsg, GalleryInfo gi, int slot);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
/**
|
||||
* com.hippo.ehviewer.miscellaneous is a group of stuff combine more than one scopes
|
||||
*/
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.network;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
|
||||
public final class Network {
|
||||
|
||||
public static final int NETWORK_STATE_NONE = 0x0;
|
||||
public static final int NETWORK_STATE_MOBILE = 0x1;
|
||||
public static final int NETWORK_STATE_WIFI = 0x2;
|
||||
|
||||
public static int getNetworkState(Context context) {
|
||||
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
|
||||
NetworkInfo mMobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
|
||||
|
||||
if (mWifi != null && mWifi.isConnected())
|
||||
return NETWORK_STATE_WIFI;
|
||||
else if (mMobile != null && mMobile.isConnected())
|
||||
return NETWORK_STATE_MOBILE;
|
||||
else
|
||||
return NETWORK_STATE_NONE;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.network;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class UrlBuilder {
|
||||
|
||||
public String mRootUrl;
|
||||
public Map<String, Object> mQueryMap = new HashMap<String, Object>();
|
||||
|
||||
public UrlBuilder(String rootUrl) {
|
||||
mRootUrl = rootUrl;
|
||||
}
|
||||
|
||||
public void addQuery(String key, Object value) {
|
||||
mQueryMap.put(key, value);
|
||||
}
|
||||
|
||||
public String build() {
|
||||
if (mQueryMap.size() == 0) {
|
||||
return mRootUrl;
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder(mRootUrl);
|
||||
sb.append("?");
|
||||
|
||||
Iterator<String> iter = mQueryMap.keySet().iterator();
|
||||
if (iter.hasNext()) {
|
||||
String key = iter.next();
|
||||
Object value = mQueryMap.get(key);
|
||||
sb.append(key).append("=").append(value);
|
||||
}
|
||||
while (iter.hasNext()) {
|
||||
String key = iter.next();
|
||||
Object value = mQueryMap.get(key);
|
||||
sb.append("&").append(key).append("=").append(value);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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 java.util.Locale;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.text.Editable;
|
||||
import android.text.TextWatcher;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.ColorPickerView;
|
||||
|
||||
public class ColorPreference extends DialogPreference implements ColorPickerView.OnColorChangedListener, View.OnClickListener {
|
||||
|
||||
private View mColorBrick;
|
||||
|
||||
public ColorPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public ColorPreference(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
if (mColorBrick != null)
|
||||
mColorBrick.setBackgroundColor(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindView(View view) {
|
||||
super.onBindView(view);
|
||||
|
||||
View ll = view.findViewById(android.R.id.widget_frame);
|
||||
if (ll != null && ll instanceof LinearLayout) {
|
||||
LinearLayout widgetFrame = (LinearLayout)ll;
|
||||
widgetFrame.setVisibility(View.VISIBLE);
|
||||
|
||||
mColorBrick = new View(getContext());
|
||||
if (isEnabled())
|
||||
setColor(Config.getThemeColor());
|
||||
else
|
||||
setColor(getContext().getResources().getColor(R.color.disabled_mask));
|
||||
widgetFrame.addView(mColorBrick, new LinearLayout.LayoutParams(Ui.dp2pix(24), Ui.dp2pix(24)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean inScrollView() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("InflateParams")
|
||||
protected View onCreateDialogView() {
|
||||
return ViewUtils.inflateDialogView(R.layout.color_scheme_dialog, false);
|
||||
}
|
||||
|
||||
private void setUpPresets(View view, final int which) {
|
||||
final Button preset = (Button) view.findViewById(which);
|
||||
if (preset != null)
|
||||
preset.setOnClickListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindDialogView(View view) {
|
||||
int curColor = Config.getThemeColor();
|
||||
final ColorPickerView colorPicker = (ColorPickerView) view.findViewById(R.id.color_picker_view);
|
||||
ViewUtils.removeHardwareAccelerationSupport(colorPicker);
|
||||
Button oldColor = (Button) view.findViewById(R.id.color_scheme_dialog_old_color);
|
||||
oldColor.setOnClickListener(this);
|
||||
final Button newColor = (Button) view.findViewById(R.id.color_scheme_dialog_new_color);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_one);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_two);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_three);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_four);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_five);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_six);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_seven);
|
||||
setUpPresets(view, R.id.color_scheme_dialog_preset_eight);
|
||||
final EditText hexValue = (EditText) view.findViewById(R.id.color_scheme_dialog_hex_value);
|
||||
hexValue.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void onTextChanged(final CharSequence s, final int start, final int before,
|
||||
final int count) {
|
||||
try {
|
||||
int color = Color.parseColor("#"
|
||||
+ hexValue.getText().toString().toUpperCase(Locale.getDefault()));
|
||||
colorPicker.setColor(color);
|
||||
newColor.setBackgroundColor(color);
|
||||
} catch (final Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(final CharSequence s, final int start, final int count,
|
||||
final int after) {
|
||||
/* Nothing to do */
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTextChanged(final Editable s) {
|
||||
/* Nothing to do */
|
||||
}
|
||||
});
|
||||
|
||||
colorPicker.setOnColorChangedListener(this);
|
||||
oldColor.setBackgroundColor(curColor);
|
||||
colorPicker.setColor(curColor, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
super.onClick(dialog, which);
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
ColorPickerView colorPicker = (ColorPickerView) dialog.findViewById(R.id.color_picker_view);
|
||||
if (colorPicker == null)
|
||||
return true;
|
||||
int color = colorPicker.getColor() | 0xff000000;
|
||||
if (callChangeListener(color)) {
|
||||
Config.setThemeColor(color);
|
||||
setColor(color);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private String padLeft(final String string, final char padChar, final int size) {
|
||||
if (string.length() >= size) {
|
||||
return string;
|
||||
}
|
||||
final StringBuilder result = new StringBuilder();
|
||||
for (int i = string.length(); i < size; i++) {
|
||||
result.append(padChar);
|
||||
}
|
||||
result.append(string);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onColorChanged(View view, int color) {
|
||||
try {
|
||||
View p = (View) view.getParent();
|
||||
EditText hexValue = (EditText) p.findViewById(R.id.color_scheme_dialog_hex_value);
|
||||
Button newColor = (Button) view.findViewById(R.id.color_scheme_dialog_new_color);
|
||||
|
||||
if (hexValue != null)
|
||||
hexValue.setText(padLeft(Integer.toHexString(color).toUpperCase(Locale.getDefault()),
|
||||
'0', 8));
|
||||
if (newColor != null)
|
||||
newColor.setBackgroundColor(color);
|
||||
} catch (Throwable e) {
|
||||
}
|
||||
}
|
||||
|
||||
private int getColor(final int color) {
|
||||
return getContext().getResources().getColor(color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
|
||||
View view = ViewUtils.getAncestor(v, R.id.main);
|
||||
if (view == null)
|
||||
return;
|
||||
ColorPickerView colorPicker = (ColorPickerView) view.findViewById(R.id.color_picker_view);
|
||||
if (colorPicker == null)
|
||||
return;
|
||||
|
||||
switch (v.getId()) {
|
||||
case R.id.color_scheme_dialog_preset_one:
|
||||
colorPicker.setColor(getColor(R.color.theme_red));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_two:
|
||||
colorPicker.setColor(getColor(R.color.theme_orange));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_three:
|
||||
colorPicker.setColor(getColor(R.color.theme_lime));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_four:
|
||||
colorPicker.setColor(getColor(R.color.theme_green));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_five:
|
||||
colorPicker.setColor(getColor(R.color.theme_teal));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_six:
|
||||
colorPicker.setColor(getColor(R.color.theme_blue));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_seven:
|
||||
colorPicker.setColor(getColor(R.color.theme_purple));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_preset_eight:
|
||||
colorPicker.setColor(getColor(R.color.theme_brown));
|
||||
break;
|
||||
case R.id.color_scheme_dialog_old_color:
|
||||
colorPicker.setColor(Config.getThemeColor());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
onColorChanged(colorPicker, colorPicker.getColor());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDialogCreate(Dialog dialog) {
|
||||
dialog.getWindow().setFormat(PixelFormat.RGBA_8888);
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.content.DialogInterface;
|
||||
import android.os.Bundle;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
|
||||
public abstract class DialogPreference extends android.preference.DialogPreference implements MaterialAlertDialog.OnClickListener {
|
||||
|
||||
private MaterialAlertDialog.Builder mBuilder;
|
||||
|
||||
/** The dialog, if it is showing. */
|
||||
private Dialog mDialog;
|
||||
/** Which button was clicked. */
|
||||
private int mWhichButtonClicked;
|
||||
|
||||
public DialogPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public DialogPreference(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onClick() {
|
||||
if (mDialog != null && mDialog.isShowing()) return;
|
||||
|
||||
showDialog(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
mWhichButtonClicked = which;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected abstract void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder);
|
||||
|
||||
protected abstract boolean inScrollView();
|
||||
|
||||
@Override
|
||||
protected void showDialog(Bundle state) {
|
||||
Context context = getContext();
|
||||
|
||||
mWhichButtonClicked = MaterialAlertDialog.POSITIVE;
|
||||
|
||||
mBuilder = new MaterialAlertDialog.Builder(context)
|
||||
.setTitle(getDialogTitle())
|
||||
//.setIcon(mDialogIcon) // TODO Not support now
|
||||
.setPositiveButton(getPositiveButtonText())
|
||||
.setNegativeButton(getNegativeButtonText())
|
||||
.setButtonListener(this);
|
||||
|
||||
|
||||
View contentView = onCreateDialogView();
|
||||
if (contentView != null) {
|
||||
onBindDialogView(contentView);
|
||||
mBuilder.setView(contentView, inScrollView());
|
||||
} else {
|
||||
mBuilder.setMessage(getDialogMessage());
|
||||
}
|
||||
|
||||
onPrepareDialogBuilder(mBuilder);
|
||||
|
||||
// Create the dialog
|
||||
final Dialog dialog = mDialog = mBuilder.create();
|
||||
onDialogCreate(dialog);
|
||||
if (state != null) {
|
||||
dialog.onRestoreInstanceState(state);
|
||||
}
|
||||
dialog.setOnDismissListener(this);
|
||||
dialog.show();
|
||||
}
|
||||
|
||||
protected void onDialogCreate(Dialog dialog) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected abstract void onBindDialogView(View view);
|
||||
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
mDialog = null;
|
||||
onDialogClosed(mWhichButtonClicked == MaterialAlertDialog.POSITIVE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Dialog getDialog() {
|
||||
return mDialog;
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.content.res.TypedArray;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewParent;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class EditTextPreference extends DialogPreference {
|
||||
|
||||
private EditText mEditText;
|
||||
|
||||
private int mMax;
|
||||
private int mMin;
|
||||
|
||||
public EditTextPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs, 0);
|
||||
}
|
||||
|
||||
public EditTextPreference(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
init(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs, int defStyle) {
|
||||
mEditText = new EditText(context, attrs);
|
||||
|
||||
TypedArray a = context.obtainStyledAttributes(attrs,
|
||||
R.styleable.EditTextPreference, defStyle, 0);
|
||||
mMax = a.getInt(R.styleable.EditTextPreference_etpMax, Integer.MAX_VALUE);
|
||||
mMin = a.getInt(R.styleable.EditTextPreference_etpMin, Integer.MIN_VALUE);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean inScrollView() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected View onCreateDialogView() {
|
||||
// Make sure mEditText is an orphan
|
||||
ViewParent oldParent = mEditText.getParent();
|
||||
if (oldParent != null)
|
||||
((ViewGroup) oldParent).removeView(mEditText);
|
||||
|
||||
mEditText.setTextColor(getContext().getResources().getColor(
|
||||
R.color.secondary_text_dark));
|
||||
return mEditText;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindDialogView(View view) {
|
||||
mEditText.setText(getPersistedString(null));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object onGetDefaultValue(TypedArray a, int index) {
|
||||
return a.getString(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSetInitialValue(boolean restorePersistedValue,
|
||||
Object defaultValue) {
|
||||
setSummary(restorePersistedValue ? getPersistedString((String) defaultValue)
|
||||
: (String) defaultValue);
|
||||
if (!restorePersistedValue)
|
||||
persistString((String) defaultValue);
|
||||
}
|
||||
|
||||
// Return true for close and save
|
||||
private boolean checkBorder(String value) {
|
||||
boolean re;
|
||||
if (mMax == Integer.MAX_VALUE && mMin == Integer.MIN_VALUE) {
|
||||
return true;
|
||||
} else {
|
||||
try {
|
||||
int intValue = Integer.parseInt(value);
|
||||
if (intValue > mMax || intValue < mMin)
|
||||
re = false;
|
||||
else
|
||||
re = true;
|
||||
} catch (Throwable e) {
|
||||
re = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Show Toast
|
||||
if (!re)
|
||||
MaterialToast.showToast(R.string.invalid_input);
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
super.onClick(dialog, which);
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
String value = mEditText.getText().toString();
|
||||
if (checkBorder(value) && callChangeListener(value)) {
|
||||
persistString(value);
|
||||
setSummary(value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.content.res.TypedArray;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
import android.text.TextUtils;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog.Builder;
|
||||
|
||||
public class ListPreference extends DialogPreference {
|
||||
|
||||
private CharSequence[] mEntries;
|
||||
private CharSequence[] mEntryValues;
|
||||
private String mValue;
|
||||
private String mSummary;
|
||||
private int mClickedDialogEntryIndex;
|
||||
private boolean mValueSet;
|
||||
|
||||
public ListPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs, 0);
|
||||
}
|
||||
|
||||
public ListPreference(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
init(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs, int defStyle) {
|
||||
TypedArray a = context.obtainStyledAttributes(attrs,
|
||||
new int[]{ 16842930, 16843256 }, 0, 0);
|
||||
mEntries = a.getTextArray(0);
|
||||
mEntryValues = a.getTextArray(1);
|
||||
a.recycle();
|
||||
|
||||
a = context.obtainStyledAttributes(attrs,
|
||||
new int[]{ 16842754, 16842765, 16842766,
|
||||
16842994, 16843233, 16843238, 16843240,
|
||||
16843241, 16843242, 16843243, 16843244,
|
||||
16843245, 16843246, 16843491 }, 0, 0);
|
||||
mSummary = a.getString(7);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
public void setEntries(CharSequence[] entries) {
|
||||
mEntries = entries;
|
||||
}
|
||||
|
||||
public void setEntries(int entriesResId) {
|
||||
setEntries(getContext().getResources().getTextArray(entriesResId));
|
||||
}
|
||||
|
||||
public CharSequence[] getEntries() {
|
||||
return mEntries;
|
||||
}
|
||||
|
||||
public void setEntryValues(CharSequence[] entryValues) {
|
||||
mEntryValues = entryValues;
|
||||
}
|
||||
|
||||
public void setEntryValues(int entryValuesResId) {
|
||||
setEntryValues(getContext().getResources().getTextArray(entryValuesResId));
|
||||
}
|
||||
|
||||
public CharSequence[] getEntryValues() {
|
||||
return mEntryValues;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
// Always persist/notify the first time.
|
||||
final boolean changed = !TextUtils.equals(mValue, value);
|
||||
if (changed || !mValueSet) {
|
||||
mValue = value;
|
||||
mValueSet = true;
|
||||
persistString(value);
|
||||
if (changed) {
|
||||
notifyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getSummary() {
|
||||
final CharSequence entry = getEntry();
|
||||
if (entry == null) {
|
||||
return super.getSummary();
|
||||
} else if (mSummary == null) {
|
||||
return entry;
|
||||
} else {
|
||||
return String.format(mSummary, entry);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSummary(CharSequence summary) {
|
||||
super.setSummary(summary);
|
||||
if (summary == null && mSummary != null) {
|
||||
mSummary = null;
|
||||
} else if (summary != null && !summary.equals(mSummary)) {
|
||||
mSummary = summary.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public void setValueIndex(int index) {
|
||||
if (mEntryValues != null) {
|
||||
setValue(mEntryValues[index].toString());
|
||||
}
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return mValue;
|
||||
}
|
||||
|
||||
public CharSequence getEntry() {
|
||||
int index = getValueIndex();
|
||||
return index >= 0 && mEntries != null ? mEntries[index] : null;
|
||||
}
|
||||
|
||||
public int findIndexOfValue(String value) {
|
||||
if (value != null && mEntryValues != null) {
|
||||
for (int i = mEntryValues.length - 1; i >= 0; i--) {
|
||||
if (mEntryValues[i].equals(value)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private int getValueIndex() {
|
||||
return findIndexOfValue(mValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean inScrollView() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindDialogView(View view) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(Builder builder) {
|
||||
|
||||
mClickedDialogEntryIndex = getValueIndex();
|
||||
|
||||
builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
|
||||
new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
mClickedDialogEntryIndex = which;
|
||||
ListPreference.this.onClick(dialog, MaterialAlertDialog.POSITIVE);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onDialogClosed(boolean positiveResult) {
|
||||
super.onDialogClosed(positiveResult);
|
||||
|
||||
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
|
||||
String value = mEntryValues[mClickedDialogEntryIndex].toString();
|
||||
if (callChangeListener(value)) {
|
||||
setValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object onGetDefaultValue(TypedArray a, int index) {
|
||||
return a.getString(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
|
||||
setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Parcelable onSaveInstanceState() {
|
||||
final Parcelable superState = super.onSaveInstanceState();
|
||||
if (isPersistent()) {
|
||||
// No need to save instance state since it's persistent
|
||||
return superState;
|
||||
}
|
||||
|
||||
final SavedState myState = new SavedState(superState);
|
||||
myState.value = getValue();
|
||||
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;
|
||||
super.onRestoreInstanceState(myState.getSuperState());
|
||||
setValue(myState.value);
|
||||
}
|
||||
|
||||
private static class SavedState extends BaseSavedState {
|
||||
String value;
|
||||
|
||||
public SavedState(Parcel source) {
|
||||
super(source);
|
||||
value = source.readString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeString(value);
|
||||
}
|
||||
|
||||
public SavedState(Parcelable superState) {
|
||||
super(superState);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
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];
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog.Builder;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class NumberOfColumnsPreference extends DialogPreference {
|
||||
|
||||
private Context mContext;
|
||||
private String keyPortrait;
|
||||
private String keyLandscape;
|
||||
private int defValuePortrait;
|
||||
private int defValueLandscape;
|
||||
|
||||
public NumberOfColumnsPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs, 0);
|
||||
}
|
||||
|
||||
public NumberOfColumnsPreference(Context context, AttributeSet attrs,
|
||||
int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
init(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
private void updateSummary(int portrait, int landscape) {
|
||||
setSummary(String.format("%s: %d, %s: %d", mContext.getString(R.string.portrait),
|
||||
portrait, mContext.getString(R.string.landscape), landscape));
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs,
|
||||
int defStyle) {
|
||||
mContext = context;
|
||||
TypedArray a = mContext.obtainStyledAttributes(attrs,
|
||||
R.styleable.NumberOfColumnsPreference, defStyle, 0);
|
||||
|
||||
keyPortrait = a.getString(R.styleable.NumberOfColumnsPreference_keyPortrait);
|
||||
keyLandscape = a.getString(R.styleable.NumberOfColumnsPreference_keyLandscape);
|
||||
defValuePortrait = a.getInt(R.styleable.NumberOfColumnsPreference_defValuePortrait, 0);
|
||||
defValueLandscape = a.getInt(R.styleable.NumberOfColumnsPreference_defValueLandscape, 0);
|
||||
|
||||
if (defValuePortrait <= 0 || defValuePortrait >= 100)
|
||||
defValuePortrait = 1;
|
||||
if (defValueLandscape <= 0 || defValueLandscape >= 100)
|
||||
defValueLandscape = 1;
|
||||
|
||||
a.recycle();
|
||||
|
||||
updateSummary(Config.getInt(keyPortrait, defValuePortrait),
|
||||
Config.getInt(keyLandscape, defValueLandscape));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean inScrollView() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("InflateParams")
|
||||
protected View onCreateDialogView() {
|
||||
return ViewUtils.inflateDialogView(R.layout.set_column_number, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindDialogView(View view) {
|
||||
final EditText editTextPortrait = (EditText) view.findViewById(R.id.portrait);
|
||||
editTextPortrait.setText(String.valueOf(Config.getInt(keyPortrait, defValuePortrait)));
|
||||
final EditText editTextLandscape = (EditText) view.findViewById(R.id.landscape);
|
||||
editTextLandscape.setText(String.valueOf(Config.getInt(keyLandscape, defValueLandscape)));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(Builder builder) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
super.onClick(dialog, which);
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
try {
|
||||
EditText editTextPortrait = (EditText) dialog.findViewById(R.id.portrait);
|
||||
EditText editTextLandscape = (EditText) dialog.findViewById(R.id.landscape);
|
||||
int newPortrait = Integer.valueOf(editTextPortrait.getText().toString());
|
||||
int newLandscape = Integer.valueOf(editTextLandscape.getText().toString());
|
||||
if (newPortrait > 0 && newPortrait < 25 &&
|
||||
newLandscape > 0 && newLandscape < 25) { // TODO Need a better range
|
||||
Config.setInt(keyPortrait, newPortrait);
|
||||
Config.setInt(keyLandscape, newLandscape);
|
||||
updateSummary(newPortrait, newLandscape);
|
||||
return true;
|
||||
} else {
|
||||
throw new Exception();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
MaterialToast.showToast(R.string.invalid_input);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.content.res.TypedArray;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewParent;
|
||||
import android.widget.SeekBar;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog.Builder;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class SeekBarDialogPreference extends DialogPreference {
|
||||
|
||||
private SeekBar mSeekBar;
|
||||
|
||||
public SeekBarDialogPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs, 0);
|
||||
}
|
||||
|
||||
public SeekBarDialogPreference(Context context, AttributeSet attrs,
|
||||
int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
init(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs, int defStyle) {
|
||||
mSeekBar = new SeekBar(context, attrs);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean inScrollView() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected View onCreateDialogView() {
|
||||
// Make sure mEditText is an orphan
|
||||
ViewParent oldParent = mSeekBar.getParent();
|
||||
if (oldParent != null)
|
||||
((ViewGroup) oldParent).removeView(mSeekBar);
|
||||
|
||||
return mSeekBar;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBindDialogView(View view) {
|
||||
mSeekBar.setProgress(Utils.parseIntSafely(getPersistedString(null), 120));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(Builder builder) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object onGetDefaultValue(TypedArray a, int index) {
|
||||
return a.getString(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSetInitialValue(boolean restorePersistedValue,
|
||||
Object defaultValue) {
|
||||
setSummary(restorePersistedValue ? getPersistedString((String) defaultValue)
|
||||
: (String) defaultValue);
|
||||
if (!restorePersistedValue)
|
||||
persistString((String) defaultValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
super.onClick(dialog, which);
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
String value = Integer.toString(mSeekBar.getProgress());
|
||||
if (callChangeListener(value)) {
|
||||
persistString(value);
|
||||
setSummary(value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.hippo.ehviewer.receiver;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class RestPatternReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
Config.setPatternProtection("");
|
||||
MaterialToast.showToast(R.string.reset_pattern_protection);
|
||||
}
|
||||
}
|
||||
@@ -1,489 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.service;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.IBinder;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.DownloadInfo;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloader;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.ui.DownloadActivity;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DownloadService extends Service
|
||||
implements ExDownloader.ListenerForDownload {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = DownloadService.class.getSimpleName();
|
||||
|
||||
private static final int DOWNLOADING_NOTIFY_ID = -1;
|
||||
private static final int DOWNLOAD_NOTIFY_ID = -2;
|
||||
|
||||
public static final String ACTION_UPDATE = "com.hippo.ehviewer.service.DownloadService.UPDATE";
|
||||
|
||||
public static final String ACTION_ADD = "com.hippo.ehviewer.service.DownloadService.ADD";
|
||||
public static final String ACTION_START = "com.hippo.ehviewer.service.DownloadService.START";
|
||||
public static final String ACTION_START_ALL = "com.hippo.ehviewer.service.DownloadService.START_ALL";
|
||||
public static final String ACTION_STOP = "com.hippo.ehviewer.service.DownloadService.STOP";
|
||||
public static final String ACTION_STOP_CURRENT = "com.hippo.ehviewer.service.DownloadService.STOP_CURRENT";
|
||||
public static final String ACTION_STOP_ALL = "com.hippo.ehviewer.service.DownloadService.STOP_ALL";
|
||||
public static final String ACTION_DELETE = "com.hippo.ehviewer.service.DownloadService.DELETE";
|
||||
public static final String ACTION_CLEAR = "com.hippo.ehviewer.service.DownloadService.ACTION_CLEAR";
|
||||
|
||||
public static final String KEY_GID = "gid";
|
||||
public static final String KEY_GALLERY_INFO = "gallery_info";
|
||||
|
||||
private Context mContext;
|
||||
private Data mData;
|
||||
private ExDownloaderManager mEdManager;
|
||||
private volatile DownloadInfo mCurDownloadInfo = null;
|
||||
private volatile ExDownloader mCurExDownloader = null;
|
||||
private Binder mBinder = null;
|
||||
private NotificationManager mNotifyManager;
|
||||
private NotificationCompat.Builder mBuilder;
|
||||
private String mSpeedStr = null;
|
||||
|
||||
private final List<Integer> mDownloadOk = new ArrayList<Integer>();
|
||||
private final List<Integer> mDownloadFailed = new ArrayList<Integer>();
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
mContext = getApplication();
|
||||
mData = Data.getInstance();
|
||||
mEdManager = ExDownloaderManager.getInstance();
|
||||
|
||||
mBinder = new Binder();
|
||||
mNotifyManager = (NotificationManager)
|
||||
getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
}
|
||||
|
||||
private synchronized void handleIntent(Intent intent) {
|
||||
boolean startDownload = false;
|
||||
|
||||
if (intent == null) {
|
||||
if (!Config.getKeepDownloadService()) {
|
||||
stopForeground(true);
|
||||
stopSelf();
|
||||
return;
|
||||
} else {
|
||||
startDownload = true;
|
||||
}
|
||||
} else {
|
||||
String action = intent.getAction();
|
||||
if (ACTION_ADD.equals(action)) {
|
||||
GalleryInfo gi = intent.getParcelableExtra(KEY_GALLERY_INFO);
|
||||
if (gi != null)
|
||||
add(gi);
|
||||
else
|
||||
startDownload = true;
|
||||
|
||||
} else if (ACTION_START.equals(action)) {
|
||||
int gid = intent.getIntExtra(KEY_GID, -1);
|
||||
if (gid != -1)
|
||||
start(gid);
|
||||
else
|
||||
startDownload = true;
|
||||
|
||||
} else if (ACTION_START_ALL.equals(action)) {
|
||||
startAll();
|
||||
|
||||
} else if (ACTION_STOP.equals(action)) {
|
||||
int gid = intent.getIntExtra(KEY_GID, -1);
|
||||
if (gid != -1)
|
||||
stop(gid);
|
||||
else
|
||||
startDownload = true;
|
||||
|
||||
} else if (ACTION_STOP_CURRENT.equals(action)) {
|
||||
stopCurrentTask();
|
||||
|
||||
} else if (ACTION_STOP_ALL.equals(action)) {
|
||||
stopAll();
|
||||
|
||||
} else if (ACTION_DELETE.equals(action)) {
|
||||
int gid = intent.getIntExtra(KEY_GID, -1);
|
||||
if (gid != -1)
|
||||
delete(gid);
|
||||
else
|
||||
startDownload = true;
|
||||
|
||||
} else if (ACTION_CLEAR.equals(action)) {
|
||||
mDownloadOk.clear();
|
||||
mDownloadFailed.clear();
|
||||
startDownload = true;
|
||||
|
||||
} else {
|
||||
startDownload = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (startDownload)
|
||||
tryToStartDownload();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
handleIntent(intent);
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return mBinder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
stopForeground(true);
|
||||
|
||||
mBinder = null;
|
||||
mNotifyManager = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to start download, if there is no item to start, stop itself
|
||||
*/
|
||||
private synchronized void tryToStartDownload() {
|
||||
if (mCurDownloadInfo != null || mCurExDownloader != null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo = mData.getFirstWaitDownloadInfo();
|
||||
if (mCurDownloadInfo == null) {
|
||||
stopSelf();
|
||||
return;
|
||||
}
|
||||
|
||||
mCurDownloadInfo.state = DownloadInfo.STATE_DOWNLOAD;
|
||||
mCurDownloadInfo.download = -1;
|
||||
mCurDownloadInfo.total = -1;
|
||||
// To update download state
|
||||
mData.addDownload(mCurDownloadInfo);
|
||||
|
||||
GalleryInfo gi = mCurDownloadInfo.galleryInfo;
|
||||
mCurExDownloader = mEdManager.getExDownloader(gi.gid,
|
||||
gi.token, gi.title, mCurDownloadInfo.mode);
|
||||
mCurExDownloader.setListenerDownload(this);
|
||||
// setDownloadMode will start download thread
|
||||
mCurExDownloader.setDownloadMode(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* notify download info has changed
|
||||
*/
|
||||
private void notifyUpdate() {
|
||||
Intent it = new Intent(ACTION_UPDATE);
|
||||
sendBroadcast(it);
|
||||
}
|
||||
|
||||
/**
|
||||
* If task is in list, reture false
|
||||
* @param galleryInfo
|
||||
* @return
|
||||
*/
|
||||
private boolean add(GalleryInfo galleryInfo) {
|
||||
int gid = galleryInfo.gid;
|
||||
DownloadInfo di;
|
||||
if ((di = mData.getDownload(gid)) != null) {
|
||||
if (di.state != DownloadInfo.STATE_DOWNLOAD) {
|
||||
mData.setDownloadState(gid, DownloadInfo.STATE_WAIT);
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
di = new DownloadInfo(galleryInfo, Config.getMode());
|
||||
di.state = DownloadInfo.STATE_WAIT;
|
||||
mData.addDownload(di);
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void start(int gid) {
|
||||
DownloadInfo di = mData.getDownload(gid);
|
||||
if (di != null)
|
||||
start(di);
|
||||
}
|
||||
|
||||
private synchronized void start(DownloadInfo di) {
|
||||
if (mCurDownloadInfo != di && di.state != DownloadInfo.STATE_WAIT) {
|
||||
mData.setDownloadState(di, DownloadInfo.STATE_WAIT);
|
||||
notifyUpdate();
|
||||
}
|
||||
tryToStartDownload();
|
||||
}
|
||||
|
||||
public void startAll() {
|
||||
mData.startAllDownload();
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
private synchronized void stop(int gid) {
|
||||
DownloadInfo di = mData.getDownload(gid);
|
||||
if (di != null)
|
||||
stop(di);
|
||||
}
|
||||
|
||||
private synchronized void stop(DownloadInfo di) {
|
||||
if (mCurDownloadInfo == di) {
|
||||
// Cancel download notification
|
||||
stopForeground(true);
|
||||
|
||||
// Target downloadinfo is downloading
|
||||
mData.setDownloadState(mCurDownloadInfo, DownloadInfo.STATE_NONE);
|
||||
mCurDownloadInfo = null;
|
||||
|
||||
mCurExDownloader.setListenerDownload(null);
|
||||
mCurExDownloader.setDownloadMode(false);
|
||||
mEdManager.freeExDownloader(mCurExDownloader);
|
||||
mCurExDownloader = null;
|
||||
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
} else {
|
||||
di.state = DownloadInfo.STATE_NONE;
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
public void stopCurrentTask() {
|
||||
if (mCurDownloadInfo != null)
|
||||
stop(mCurDownloadInfo);
|
||||
else
|
||||
tryToStartDownload();
|
||||
}
|
||||
|
||||
public synchronized void stopAll() {
|
||||
mData.stopAllDownload();
|
||||
stopCurrentTask();
|
||||
}
|
||||
|
||||
private synchronized void delete(int gid) {
|
||||
DownloadInfo di = mData.getDownload(gid);
|
||||
if (di != null)
|
||||
delete(di);
|
||||
}
|
||||
|
||||
public void delete(DownloadInfo di) {
|
||||
stop(di);
|
||||
mData.deleteDownload(di.galleryInfo.gid);
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
private void ensureNotification() {
|
||||
if (mBuilder != null)
|
||||
return;
|
||||
|
||||
mBuilder = new NotificationCompat.Builder(mContext);
|
||||
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
|
||||
mBuilder.setOngoing(true).setAutoCancel(false);
|
||||
|
||||
// Add action
|
||||
Intent stopIntent = new Intent(this, DownloadService.class);
|
||||
stopIntent.setAction(ACTION_STOP_CURRENT);
|
||||
PendingIntent piStop = PendingIntent.getService(this, 0, stopIntent, 0);
|
||||
mBuilder.addAction(R.drawable.ic_action_stop, getString(R.string.stop), piStop);
|
||||
|
||||
Intent stopAllIntent = new Intent(this, DownloadService.class);
|
||||
stopAllIntent.setAction(ACTION_STOP_ALL);
|
||||
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
|
||||
mBuilder.addAction(R.drawable.ic_action_close, getString(R.string.stop_all), piStopAll);
|
||||
}
|
||||
|
||||
private void setPendingIntent() {
|
||||
Intent intent = new Intent(DownloadService.this, DownloadActivity.class);
|
||||
intent.setAction(DownloadActivity.ACTION_SPECIFIC_GALLERY);
|
||||
intent.putExtra(DownloadActivity.KEY_SPECIFIC_GALLERY_GID, mCurDownloadInfo.galleryInfo.gid);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0,
|
||||
intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
mBuilder.setContentIntent(pendingIntent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart(int gid) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.download = -1;
|
||||
mCurDownloadInfo.total = -1;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.start_download) + " " + gid)
|
||||
.setContentText(null)
|
||||
.setProgress(0, 0, true);
|
||||
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
|
||||
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGetSum(int gid, int sum) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.download = 0;
|
||||
mCurDownloadInfo.total = sum;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(null)
|
||||
.setProgress(mCurDownloadInfo.total, mCurDownloadInfo.download, false);
|
||||
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
|
||||
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
private long mLastStartForegroundTime = 0;
|
||||
|
||||
@Override
|
||||
public void onDownload(int gid, int downloadSize, int totalSize) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.download = downloadSize;
|
||||
mCurDownloadInfo.total = totalSize;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(mSpeedStr)
|
||||
.setProgress(totalSize, downloadSize, false);
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - mLastStartForegroundTime > 500) {
|
||||
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
|
||||
mLastStartForegroundTime = now;
|
||||
}
|
||||
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateSpeed(int gid, int speed) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.speed = speed;
|
||||
mSpeedStr = Utils.sizeToString(speed) + "/S";
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(mSpeedStr)
|
||||
.setProgress(mCurDownloadInfo.total, mCurDownloadInfo.download, false);
|
||||
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
|
||||
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
private synchronized String getDownloadNotificationText() {
|
||||
|
||||
int ok = mDownloadOk.size();
|
||||
int failed = mDownloadFailed.size();
|
||||
|
||||
if (ok == 0 && failed == 0) {
|
||||
return "null";
|
||||
} else if (ok == 1 && failed == 0) {
|
||||
return String.format(getString(R.string.download_1), mDownloadOk.get(0));
|
||||
} else if (failed == 0) {
|
||||
return String.format(getString(R.string.download_2), mDownloadOk.size());
|
||||
} else if (ok == 0 && failed == 1) {
|
||||
return String.format(getString(R.string.download_3), mDownloadFailed.get(0));
|
||||
} else if (ok == 0) {
|
||||
return String.format(getString(R.string.download_4), mDownloadFailed.size());
|
||||
} else if (ok == 1 && failed == 1){
|
||||
return String.format(getString(R.string.download_5), mDownloadOk.get(0), mDownloadFailed.get(0));
|
||||
} else {
|
||||
return String.format(getString(R.string.download_6), mDownloadOk.size(), mDownloadFailed.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onDownloadOver(int gid, int legacy) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.legacy = legacy;
|
||||
if (mCurDownloadInfo.legacy == 0) {
|
||||
// Download ok
|
||||
if (!mDownloadOk.contains(gid))
|
||||
mDownloadOk.add(gid);
|
||||
mDownloadFailed.remove((Integer) gid);
|
||||
} else {
|
||||
// Download failed
|
||||
if (!mDownloadFailed.contains(gid))
|
||||
mDownloadFailed.add(gid);
|
||||
mDownloadOk.remove((Integer) gid);
|
||||
}
|
||||
|
||||
Intent clearIntent = new Intent(this, DownloadService.class);
|
||||
clearIntent.setAction(ACTION_CLEAR);
|
||||
PendingIntent piClear = PendingIntent.getService(this, 0, clearIntent, 0);
|
||||
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
|
||||
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
|
||||
Intent intent = new Intent(DownloadService.this,DownloadActivity.class);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
builder.setContentIntent(pendingIntent);
|
||||
builder.setContentTitle(getString(R.string.download_over))
|
||||
.setContentText(getDownloadNotificationText())
|
||||
.setDeleteIntent(piClear)
|
||||
.setOngoing(false).setAutoCancel(true);
|
||||
mNotifyManager.notify(DOWNLOAD_NOTIFY_ID, builder.build());
|
||||
stopForeground(true);
|
||||
|
||||
mCurDownloadInfo.legacy = legacy;
|
||||
mCurDownloadInfo.state = DownloadInfo.STATE_FINISH;
|
||||
mData.addDownload(mCurDownloadInfo);
|
||||
mCurDownloadInfo = null;
|
||||
|
||||
mCurExDownloader.setListenerDownload(null);
|
||||
mCurExDownloader.setDownloadMode(false);
|
||||
mEdManager.freeExDownloader(mCurExDownloader);
|
||||
mCurExDownloader = null;
|
||||
|
||||
tryToStartDownload();
|
||||
notifyUpdate();
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.tile;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.StateSet;
|
||||
|
||||
public class RectDrawable extends Drawable {
|
||||
|
||||
private final int[][] mStateSets;
|
||||
private final int[] mColors;
|
||||
private int mColor;
|
||||
private int mLastIndex = -1;
|
||||
|
||||
public RectDrawable(int color) {
|
||||
mStateSets = null;
|
||||
mColors = null;
|
||||
mColor = color;
|
||||
}
|
||||
|
||||
public RectDrawable(int[][] stateSets, int[] colors) {
|
||||
mStateSets = stateSets;
|
||||
mColors = colors;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStateful() {
|
||||
return mStateSets != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onStateChange(int[] stateSet) {
|
||||
final int N = mStateSets.length;
|
||||
for (int i = 0; i < N; i++) {
|
||||
if (StateSet.stateSetMatches(mStateSets[i], stateSet)) {
|
||||
if (mLastIndex == i)
|
||||
return false;
|
||||
mLastIndex = i;
|
||||
|
||||
mColor = mColors[i];
|
||||
invalidateSelf();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
canvas.drawColor(mColor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter cf) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
// Empty
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.tile;
|
||||
|
||||
import android.view.View;
|
||||
|
||||
public class TileSalon {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reform(View view, int bgColor) {
|
||||
view.setBackgroundDrawable(new RectDrawable(bgColor));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void reform(View view, int[][] stateSets, int[] bgColors) {
|
||||
view.setBackgroundDrawable(new RectDrawable(stateSets, bgColors));
|
||||
}
|
||||
}
|
||||
@@ -1,415 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.annotation.SuppressLint;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
import com.hippo.ehviewer.ImageLoader;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.cardview.CardViewSalon;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.DownloadInfo;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
|
||||
import com.hippo.ehviewer.service.DownloadService;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.ExpandingListView;
|
||||
import com.hippo.ehviewer.widget.FitWindowView;
|
||||
import com.hippo.ehviewer.widget.LoadImageView;
|
||||
import com.hippo.ehviewer.windowsanimate.WindowsAnimate;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class DownloadActivity extends AbsTranslucentActivity implements FitWindowView.OnFitSystemWindowsListener {
|
||||
|
||||
public static final String ACTION_SPECIFIC_GALLERY = "com.hippo.ehviewer.ui.DownloadActivity.SPECIFIC_GALLERY";
|
||||
|
||||
public static final String KEY_SPECIFIC_GALLERY_GID = "specific_gallery_gid";
|
||||
|
||||
private AppContext mAppContext;
|
||||
private WindowsAnimate mWindowsAnimate;
|
||||
private int mThemeColor;
|
||||
private List<DownloadInfo> mDownloads;
|
||||
|
||||
private FitWindowView mStandard;
|
||||
private ExpandingListView mList;
|
||||
private ListAdapter mAdapter;
|
||||
|
||||
private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if(intent.getAction().equals(DownloadService.ACTION_UPDATE))
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void onFitSystemWindows(int l, int t, int r, int b) {
|
||||
mList.setPadding(mList.getPaddingLeft(), t, mList.getPaddingRight(), b);
|
||||
|
||||
Ui.colorStatusBarKK(this, mThemeColor, t - Ui.ACTION_BAR_HEIGHT);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.download);
|
||||
|
||||
mAppContext = (AppContext) getApplication();
|
||||
|
||||
// Init windows animate
|
||||
mWindowsAnimate = new WindowsAnimate();
|
||||
mWindowsAnimate.init(this);
|
||||
|
||||
// Receiver
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(DownloadService.ACTION_UPDATE);
|
||||
registerReceiver(mReceiver, filter);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
mDownloads = Data.getInstance().getAllDownloads();
|
||||
for (DownloadInfo di : mDownloads)
|
||||
di.setExpanded(false);
|
||||
|
||||
mStandard = (FitWindowView) findViewById(R.id.standard);
|
||||
mList = (ExpandingListView)findViewById(R.id.download);
|
||||
|
||||
mStandard.addOnFitSystemWindowsListener(this);
|
||||
mAdapter = new ListAdapter();
|
||||
mList.setAdapter(mAdapter);
|
||||
mList.setSelector(new ColorDrawable(Color.TRANSPARENT));
|
||||
mList.setExpandingId(R.id.buttons);
|
||||
|
||||
mThemeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(mThemeColor));
|
||||
Ui.colorStatusBarL(this, mThemeColor);
|
||||
|
||||
// Go to specific gid
|
||||
Intent intent = getIntent();
|
||||
if (intent != null && ACTION_SPECIFIC_GALLERY.equals(intent.getAction())) {
|
||||
int specificGid = intent.getIntExtra(KEY_SPECIFIC_GALLERY_GID, -1);
|
||||
if (specificGid != -1) {
|
||||
int size = mDownloads.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (mDownloads.get(i).galleryInfo.gid == specificGid) {
|
||||
mList.setSelection(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
unregisterReceiver(mReceiver);
|
||||
mWindowsAnimate.free();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
getMenuInflater().inflate(R.menu.download, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
// Handle item selection
|
||||
Intent it;
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
|
||||
case R.id.action_start:
|
||||
it = new Intent(DownloadActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_START_ALL);
|
||||
startService(it);
|
||||
return true;
|
||||
|
||||
case R.id.action_stop:
|
||||
it = new Intent(DownloadActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_STOP_ALL);
|
||||
startService(it);
|
||||
return true;
|
||||
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
|
||||
public class ListAdapter extends BaseAdapter {
|
||||
@Override
|
||||
public int getCount() {
|
||||
return mDownloads.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getItem(int position) {
|
||||
return mDownloads.get(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
final DownloadInfo di = mDownloads.get(position);
|
||||
final GalleryInfo gi = di.galleryInfo;
|
||||
|
||||
if (convertView == null) {
|
||||
convertView = LayoutInflater.from(DownloadActivity.this)
|
||||
.inflate(R.layout.download_list_item, parent, false);
|
||||
CardViewSalon.reformWithShadow(((ViewGroup)convertView).getChildAt(0),
|
||||
0xFFFAFAFA, 0, false); // TODO
|
||||
((TextView)convertView.findViewById(R.id.action)).setTextColor(mThemeColor);
|
||||
}
|
||||
LoadImageView thumb = (LoadImageView)convertView.findViewById(R.id.thumb);
|
||||
if (!String.valueOf(gi.gid).equals(thumb.getKey())) {
|
||||
// Set margin top 8dp if position is 0, otherwise 4dp
|
||||
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
|
||||
convertView.findViewById(R.id.card_view).getLayoutParams();
|
||||
if (position == 0)
|
||||
lp.topMargin = Ui.dp2pix(8);
|
||||
else
|
||||
lp.topMargin = Ui.dp2pix(4);
|
||||
|
||||
// Set new thumb
|
||||
thumb.setImageDrawable(null);
|
||||
thumb.setLoadInfo(gi.thumb, String.valueOf(gi.gid));
|
||||
ImageLoader.getInstance(DownloadActivity.this).add(gi.thumb, String.valueOf(gi.gid),
|
||||
new LoadImageView.SimpleImageGetListener(thumb).setFixScaleType(true));
|
||||
}
|
||||
TextView title = (TextView)convertView.findViewById(R.id.title);
|
||||
title.setText(gi.title);
|
||||
View Buttons = convertView.findViewById(R.id.buttons);
|
||||
if (di.getExpanded())
|
||||
Buttons.setVisibility(View.VISIBLE);
|
||||
else
|
||||
Buttons.setVisibility(View.GONE);
|
||||
|
||||
ProgressBar pb = (ProgressBar)convertView.findViewById(R.id.progress_bar);
|
||||
TextView leftText = (TextView)convertView.findViewById(R.id.text_left);
|
||||
TextView rightText = (TextView)convertView.findViewById(R.id.text_right);
|
||||
|
||||
View read = convertView.findViewById(R.id.read);
|
||||
TextView action = (TextView)convertView.findViewById(R.id.action);
|
||||
View detail = convertView.findViewById(R.id.detail);
|
||||
View delete = convertView.findViewById(R.id.delete);
|
||||
|
||||
read.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Intent intent = new Intent(DownloadActivity.this,
|
||||
GalleryActivity.class);
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, gi);
|
||||
intent.putExtra(GalleryActivity.KEY_START_INDEX, -1);
|
||||
startActivity(intent);
|
||||
}
|
||||
});
|
||||
delete.setOnClickListener(new DeleteAction(di));
|
||||
detail.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Intent intent = new Intent(DownloadActivity.this,
|
||||
GalleryDetailActivity.class);
|
||||
intent.putExtra(GalleryDetailActivity.KEY_G_INFO, gi);
|
||||
startActivity(intent);
|
||||
}
|
||||
});
|
||||
|
||||
switch (di.state) {
|
||||
case DownloadInfo.STATE_NONE:
|
||||
pb.setVisibility(View.INVISIBLE);
|
||||
leftText.setText(R.string.not_started);
|
||||
rightText.setVisibility(View.GONE);
|
||||
|
||||
action.setText(getString(R.string.start));
|
||||
action.setOnClickListener(new StartAction(di));
|
||||
break;
|
||||
|
||||
case DownloadInfo.STATE_WAIT:
|
||||
pb.setVisibility(View.INVISIBLE);
|
||||
leftText.setText(R.string.waiting);
|
||||
rightText.setVisibility(View.GONE);
|
||||
|
||||
action.setText(getString(R.string.stop));
|
||||
action.setOnClickListener(new StopAction(di));
|
||||
break;
|
||||
|
||||
case DownloadInfo.STATE_DOWNLOAD:
|
||||
leftText.setText(Utils.sizeToString(di.speed) + "/S");
|
||||
if (di.total == -1) {
|
||||
pb.setVisibility(View.VISIBLE);
|
||||
pb.setIndeterminate(true);
|
||||
rightText.setVisibility(View.GONE);
|
||||
} else {
|
||||
pb.setVisibility(View.VISIBLE);
|
||||
pb.setIndeterminate(false);
|
||||
pb.setMax(di.total);
|
||||
pb.setProgress(di.download);
|
||||
rightText.setVisibility(View.VISIBLE);
|
||||
rightText.setText(di.download + "/" + di.total);
|
||||
}
|
||||
|
||||
action.setText(getString(R.string.stop));
|
||||
action.setOnClickListener(new StopAction(di));
|
||||
break;
|
||||
|
||||
case DownloadInfo.STATE_FINISH:
|
||||
pb.setVisibility(View.INVISIBLE);
|
||||
if (di.legacy == 0)
|
||||
leftText.setText(R.string.done);
|
||||
else
|
||||
leftText.setText(String.format(getApplication().getString(R.string.legacy_pages), di.legacy));
|
||||
rightText.setVisibility(View.GONE);
|
||||
|
||||
action.setText(getString(R.string.start));
|
||||
action.setOnClickListener(new StartAction(di));
|
||||
break;
|
||||
}
|
||||
return convertView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void notifyDataSetChanged() {
|
||||
if (!mList.isAnimating())
|
||||
super.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void notifyDataSetInvalidated() {
|
||||
if (!mList.isAnimating())
|
||||
super.notifyDataSetInvalidated();
|
||||
}
|
||||
}
|
||||
|
||||
private class DeleteAction implements View.OnClickListener {
|
||||
|
||||
private static final String KEY_INCLUDE_PIC = "include_pic";
|
||||
|
||||
public DownloadInfo mDownloadInfo;
|
||||
|
||||
public DeleteAction(DownloadInfo di) {
|
||||
mDownloadInfo = di;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("InflateParams")
|
||||
public void onClick(View v) {
|
||||
final View view = ViewUtils.inflateDialogView(R.layout.dialog_message_checkbox, false);
|
||||
final TextView message = (TextView) view.findViewById(R.id.message);
|
||||
final CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
|
||||
message.setText(R.string.delete_item);
|
||||
cb.setText(R.string.pic_included);
|
||||
cb.setChecked(Config.getBoolean(KEY_INCLUDE_PIC, false));
|
||||
|
||||
new MaterialAlertDialog.Builder(DownloadActivity.this).setTitle(R.string.attention)
|
||||
.setView(view, true)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_DELETE);
|
||||
it.putExtra(DownloadService.KEY_GID, mDownloadInfo.galleryInfo.gid);
|
||||
startService(it);
|
||||
// Delete dir
|
||||
if (cb.isChecked()) {
|
||||
GalleryInfo gi = mDownloadInfo.galleryInfo;
|
||||
Utils.deleteDirInThread(EhUtils.getGalleryDir(gi.gid, gi.title));
|
||||
}
|
||||
// Remember delete choice
|
||||
Config.setBoolean(KEY_INCLUDE_PIC, cb.isChecked());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
}
|
||||
|
||||
private class StartAction implements View.OnClickListener {
|
||||
public DownloadInfo mDownloadInfo;
|
||||
|
||||
public StartAction(DownloadInfo di) {
|
||||
mDownloadInfo = di;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mDownloadInfo.state == DownloadInfo.STATE_NONE ||
|
||||
mDownloadInfo.state == DownloadInfo.STATE_FINISH) {
|
||||
|
||||
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_START);
|
||||
it.putExtra(DownloadService.KEY_GID, mDownloadInfo.galleryInfo.gid);
|
||||
startService(it);
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class StopAction implements View.OnClickListener {
|
||||
|
||||
public DownloadInfo mDownloadInfo;
|
||||
|
||||
public StopAction(DownloadInfo di) {
|
||||
mDownloadInfo = di;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_STOP);
|
||||
it.putExtra(DownloadService.KEY_GID, mDownloadInfo.galleryInfo.gid);
|
||||
startService(it);
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternView;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class EnterPatternActivity extends AbsActivity {
|
||||
|
||||
private static final String KEY_LAST_BAD_PATTERN_RETRY = "last_bad_pattern_retry";
|
||||
|
||||
private static final int MAX_RETRY_TIMES = 5;
|
||||
|
||||
private int mRetryTimes = 0;
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_enter_pattern);
|
||||
|
||||
// Set random color
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
// Can't try if bad retry happened in 10 mins
|
||||
long lastBadRetry = Config.getLong(KEY_LAST_BAD_PATTERN_RETRY, 0);
|
||||
if (System.currentTimeMillis() - lastBadRetry < 1000 * 60 * 10) {
|
||||
mRetryTimes = 10;
|
||||
}
|
||||
|
||||
final TextView textView = (TextView) findViewById(R.id.text);
|
||||
LockPatternView patternView = (LockPatternView) findViewById(R.id.pattern_view);
|
||||
patternView.setOnPatternListener(new LockPatternView.OnPatternListener() {
|
||||
@Override
|
||||
public void onPatternStart() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternCleared() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternDetected(List<LockPatternView.Cell> pattern) {
|
||||
if (mRetryTimes > MAX_RETRY_TIMES) {
|
||||
textView.setText(R.string.no_more_retries);
|
||||
Config.setLong(KEY_LAST_BAD_PATTERN_RETRY, System.currentTimeMillis());
|
||||
} else {
|
||||
String enterPatter = LockPatternUtils.patternToString(pattern);
|
||||
if (enterPatter.equals(Config.getPatternProtection())) {
|
||||
setResult(RESULT_OK);
|
||||
finish();
|
||||
} else {
|
||||
textView.setText(R.string.error_pattern);
|
||||
}
|
||||
}
|
||||
mRetryTimes++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
@@ -1,596 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.annotation.TargetApi;
|
||||
import android.app.Dialog;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Configuration;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.CompoundButton;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.DirSelectDialog;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloader;
|
||||
import com.hippo.ehviewer.gallery.GalleryView;
|
||||
import com.hippo.ehviewer.gallery.data.ImageSet;
|
||||
import com.hippo.ehviewer.gallery.ui.GLRootView;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.FullScreenHelper;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Messenger;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.widget.ColorView;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SlidingLayout;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class GalleryActivity extends StatsActivity
|
||||
implements GalleryView.GalleryViewListener, SeekBar.OnSeekBarChangeListener,
|
||||
FullScreenHelper.OnFullScreenBrokenListener, CompoundButton.OnCheckedChangeListener,
|
||||
SlidingLayout.OnChildHideListener, AdapterView.OnItemSelectedListener,
|
||||
View.OnClickListener, Utils.OnCopyOverListener, Messenger.Receiver {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private final static String TAG = GalleryActivity.class.getSimpleName();
|
||||
|
||||
public final static String KEY_GALLERY_INFO = "gallery_info";
|
||||
public final static String KEY_START_INDEX = "start_index";
|
||||
|
||||
public final static String KEY_LIGHTNESS = "lightness";
|
||||
public final static float DEFAULT_LIGHTNESS = 0.5f;
|
||||
|
||||
public final static String KEY_FIRST_READ_CONFIG_V1 = "first_read_config_v1";
|
||||
public final static boolean DEFAULT_FIRST_READ_CONFIG_V1 = true;
|
||||
|
||||
public final static String KEY_LAST_SAVE_IMAGE_FILE_PATH = "last_save_image_file_path";
|
||||
public final static String DEFAULT_LAST_SAVE_IMAGE_FILE_PATH = null;
|
||||
|
||||
private View mClock;
|
||||
private View mBattery;
|
||||
|
||||
private SlidingLayout mConfigSliding;
|
||||
/** It store index, start from 0, so max is samller than size **/
|
||||
private TextView mCurrentPage;
|
||||
private TextView mPageSum;
|
||||
private SeekBar mPageSeeker;
|
||||
private TextView mRefresh;
|
||||
private TextView mSend;
|
||||
private TextView mMoreSettings;
|
||||
private Spinner mReadingDirection;
|
||||
private Spinner mPageScaling;
|
||||
private Spinner mStartPosition;
|
||||
private CheckBox mKeepScreenOn;
|
||||
private CheckBox mShowClock;
|
||||
private CheckBox mShowBattery;
|
||||
private CheckBox mCustomLightness;
|
||||
private SeekBar mCustomLightnessValue;
|
||||
private CheckBox mCustomCodec;
|
||||
private Spinner mDecodeFormat;
|
||||
|
||||
private ImageSet mImageSet;
|
||||
|
||||
private GalleryView mGalleryView;
|
||||
|
||||
private ColorView mMaskView;
|
||||
|
||||
private GalleryInfo mGi;
|
||||
|
||||
private FullScreenHelper mFullScreenHelper;
|
||||
|
||||
private File mCurImageFile;
|
||||
|
||||
private Dialog mSendDialog;
|
||||
|
||||
private boolean mVolumePage;
|
||||
|
||||
private final Runnable mFullScreenTask = new Runnable() {
|
||||
@Override public void run() {
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
}
|
||||
};
|
||||
|
||||
private void startFullScreenTask() {
|
||||
AppHandler.getInstance().postDelayed(mFullScreenTask, 2000);
|
||||
}
|
||||
|
||||
private void cancelFullScreenTask() {
|
||||
AppHandler.getInstance().removeCallbacks(mFullScreenTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCopyOver(boolean success, File src, File dst) {
|
||||
MaterialToast.showToast(success ? String.format(getString(R.string.save_successful), dst.getPath()) : getString(R.string.save_failed));
|
||||
if (success)
|
||||
Config.setString(KEY_LAST_SAVE_IMAGE_FILE_PATH, dst.getParent());
|
||||
}
|
||||
|
||||
private Dialog createSaveImageDialog() {
|
||||
return DirSelectDialog.create(
|
||||
new MaterialAlertDialog.Builder(GalleryActivity.this)
|
||||
.setDrakTheme(true).setTitle(R.string.select_save_dir)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
String targetPath = ((DirSelectDialog) dialog).getCurrentPath();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(mImageSet.getTitle()).append("-").append(mGalleryView.getCurIndex() + 1)
|
||||
.append(".").append(Utils.getExtension(mCurImageFile.getName(), "jpg"));
|
||||
Utils.copyInNewThread(mCurImageFile, new File(targetPath, Utils.standardizeFilename(sb.toString())),
|
||||
GalleryActivity.this);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}),
|
||||
Config.getString(KEY_LAST_SAVE_IMAGE_FILE_PATH, null));
|
||||
}
|
||||
|
||||
private Dialog createSendDialog() {
|
||||
return new MaterialAlertDialog.Builder(this).setDrakTheme(true).setTitle(R.string.send)
|
||||
.setItems(R.array.send_entries, new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
// Check current image file again
|
||||
if (mCurImageFile == null || !mCurImageFile.exists()) {
|
||||
MaterialToast.showToast(R.string.current_image_not_downloaded);
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (which) {
|
||||
case 0:
|
||||
createSaveImageDialog().show();
|
||||
break;
|
||||
case 1:
|
||||
Uri uri = Uri.fromFile(mCurImageFile);
|
||||
Intent shareIntent = new Intent();
|
||||
shareIntent.setAction(Intent.ACTION_SEND);
|
||||
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
|
||||
shareIntent.setType(Utils.getMimeType(uri.toString()));
|
||||
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_image)));
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).setNegativeButton(android.R.string.cancel).create();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onFullScreenBroken(boolean fullScreen) {
|
||||
// TODO For some MIUI system, onSystemUiVisibilityChange() do not work fine
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
updateState();
|
||||
mFullScreenHelper.setFullScreen(!mConfigSliding.isShowing());
|
||||
}
|
||||
|
||||
private void setScreenLightness(boolean enable, int lightness) {
|
||||
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.05f);
|
||||
} else {
|
||||
mMaskView.setColor(MathUtils.lerp(0xde, 0x00, lightness / 100.0f) << 24);
|
||||
lp.screenBrightness = 0.05f;
|
||||
}
|
||||
} else {
|
||||
mMaskView.setColor(0);
|
||||
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
|
||||
}
|
||||
w.setAttributes(lp);
|
||||
}
|
||||
|
||||
private void updateState() {
|
||||
mReadingDirection.setSelection(Config.getReadingDirection());
|
||||
mPageScaling.setSelection(Config.getPageScaling());
|
||||
mStartPosition.setSelection(Config.getStartPosition());
|
||||
mGalleryView.setReadingDirection(Config.getReadingDirection());
|
||||
mGalleryView.setPageScaling(Config.getPageScaling());
|
||||
mGalleryView.setStartPosition(Config.getStartPosition());
|
||||
|
||||
mKeepScreenOn.setChecked(Config.getKeepSreenOn());
|
||||
if (Config.getKeepSreenOn())
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
else
|
||||
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
|
||||
mShowClock.setChecked(Config.getShowClock());
|
||||
mShowBattery.setChecked(Config.getShowBattery());
|
||||
mClock.setVisibility(Config.getShowClock() ? View.VISIBLE : View.GONE);
|
||||
mBattery.setVisibility(Config.getShowBattery() ? View.VISIBLE : View.GONE);
|
||||
|
||||
mCustomLightness.setChecked(Config.getCustomLightness());
|
||||
if (mCustomLightness.isChecked())
|
||||
mCustomLightnessValue.setEnabled(true);
|
||||
else
|
||||
mCustomLightnessValue.setEnabled(false);
|
||||
mCustomLightnessValue.setProgress(Config.getCustomLightnessValue());
|
||||
setScreenLightness(mCustomLightness.isChecked(), mCustomLightnessValue.getProgress());
|
||||
|
||||
if (Utils.SUPPORT_IMAGE)
|
||||
mCustomCodec.setEnabled(true);
|
||||
else
|
||||
mCustomCodec.setEnabled(false);
|
||||
mCustomCodec.setChecked(Config.getCustomCodec());
|
||||
if (Utils.SUPPORT_IMAGE && mCustomCodec.isChecked())
|
||||
mDecodeFormat.setEnabled(true);
|
||||
else
|
||||
mDecodeFormat.setEnabled(false);
|
||||
mDecodeFormat.setSelection(Config.getDecodeFormatIndex());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.gl_root_group);
|
||||
|
||||
mVolumePage = Config.getVolumePage();
|
||||
Messenger.getInstance().register(Config.MESSENGER_ID_VOLUME_PAGE, this);
|
||||
|
||||
mFullScreenHelper = new FullScreenHelper(this);
|
||||
mFullScreenHelper.setOnFullScreenBrokenListener(this);
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
|
||||
mMaskView = (ColorView)findViewById(R.id.mask);
|
||||
mClock = findViewById(R.id.clock);
|
||||
mBattery = findViewById(R.id.battery);
|
||||
|
||||
mConfigSliding = (SlidingLayout) findViewById(R.id.config_sliding);
|
||||
mCurrentPage = (TextView) mConfigSliding.findViewById(R.id.current_page);
|
||||
mPageSum = (TextView) mConfigSliding.findViewById(R.id.page_sum);
|
||||
mPageSeeker = (SeekBar) mConfigSliding.findViewById(R.id.page_seeker);
|
||||
mRefresh = (TextView) mConfigSliding.findViewById(R.id.refresh);
|
||||
mSend = (TextView) mConfigSliding.findViewById(R.id.send);
|
||||
mMoreSettings = (TextView) mConfigSliding.findViewById(R.id.more_settings);
|
||||
mReadingDirection = (Spinner) mConfigSliding.findViewById(R.id.reading_direction);
|
||||
mPageScaling = (Spinner) mConfigSliding.findViewById(R.id.page_scaling);
|
||||
mStartPosition = (Spinner) mConfigSliding.findViewById(R.id.start_position);
|
||||
mKeepScreenOn = (CheckBox) mConfigSliding.findViewById(R.id.keep_screen_on);
|
||||
mShowClock = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_clock);
|
||||
mShowBattery = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_battery);
|
||||
mCustomLightness = (CheckBox) mConfigSliding.findViewById(R.id.custom_lightness);
|
||||
mCustomLightnessValue = (SeekBar) mConfigSliding.findViewById(R.id.custom_lightness_value);
|
||||
mCustomCodec = (CheckBox) mConfigSliding.findViewById(R.id.custom_codec);
|
||||
mDecodeFormat = (Spinner) mConfigSliding.findViewById(R.id.decode_format);
|
||||
|
||||
mConfigSliding.hide();
|
||||
|
||||
mSendDialog = createSendDialog();
|
||||
|
||||
Intent intent = getIntent();
|
||||
mGi = intent.getParcelableExtra(KEY_GALLERY_INFO);
|
||||
|
||||
if (mGi == null) {
|
||||
// Get error force finish
|
||||
new MaterialAlertDialog.Builder(this).setTitle(R.string.error)
|
||||
.setMessage(R.string.ga_data_error)
|
||||
.setPositiveButton(R.string.close)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
} else {
|
||||
|
||||
Data.getInstance().addHistory(mGi, Data.READ);
|
||||
|
||||
int startIndex = intent.getIntExtra(KEY_START_INDEX, 0);
|
||||
if (startIndex == -1)
|
||||
startIndex = ExDownloader.readCurReadIndex(mGi.gid, mGi.title);
|
||||
|
||||
mImageSet = new ImageSet(mGi.gid, mGi.token, mGi.title, startIndex);
|
||||
mGalleryView = new GalleryView(getApplicationContext(), mImageSet, startIndex);
|
||||
|
||||
GLRootView glrv= (GLRootView)findViewById(R.id.gl_root_view);
|
||||
glrv.setContentPane(mGalleryView);
|
||||
|
||||
// Set listener
|
||||
mConfigSliding.setOnChildHideListener(this);
|
||||
mGalleryView.setGalleryViewListener(this);
|
||||
mPageSeeker.setOnSeekBarChangeListener(this);
|
||||
mRefresh.setOnClickListener(this);
|
||||
mSend.setOnClickListener(this);
|
||||
mMoreSettings.setOnClickListener(this);
|
||||
mReadingDirection.setOnItemSelectedListener(this);
|
||||
mPageScaling.setOnItemSelectedListener(this);
|
||||
mStartPosition.setOnItemSelectedListener(this);
|
||||
mDecodeFormat.setOnItemSelectedListener(this);
|
||||
mKeepScreenOn.setOnCheckedChangeListener(this);
|
||||
mShowClock.setOnCheckedChangeListener(this);
|
||||
mShowBattery.setOnCheckedChangeListener(this);
|
||||
mCustomLightness.setOnCheckedChangeListener(this);
|
||||
mCustomLightnessValue.setOnSeekBarChangeListener(this);
|
||||
mCustomCodec.setOnCheckedChangeListener(this);
|
||||
|
||||
mKeepScreenOn = (CheckBox) mConfigSliding.findViewById(R.id.keep_screen_on);
|
||||
mShowClock = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_clock);
|
||||
mShowBattery = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_battery);
|
||||
mCustomCodec = (CheckBox) mConfigSliding.findViewById(R.id.custom_codec);
|
||||
|
||||
mPageSeeker.setMax(mGalleryView.getSize() - 1);
|
||||
mPageSeeker.setProgress(startIndex);
|
||||
|
||||
mCurrentPage.setText(Integer.toString(startIndex + 1));
|
||||
mPageSum.setText(Integer.toString(mGalleryView.getSize()));
|
||||
|
||||
onRightToLeftChanged(mGalleryView.isRightToLeft());
|
||||
|
||||
// Show first tip
|
||||
String keyGalleryFirst = "gallery_first";
|
||||
if (Config.getBoolean(keyGalleryFirst, true)) {
|
||||
Config.setBoolean(keyGalleryFirst, false);
|
||||
new MaterialAlertDialog.Builder(this).setDrakTheme(true).setTitle(R.string.tip)
|
||||
.setMessage(R.string.gallery_tip)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
// Update state
|
||||
updateState();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
Messenger.getInstance().unregister(Config.MESSENGER_ID_VOLUME_PAGE, this);
|
||||
|
||||
if (mImageSet != null)
|
||||
mImageSet.free();
|
||||
if (mGalleryView != null)
|
||||
mGalleryView.free();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (mConfigSliding.isInHideAnimate())
|
||||
return;
|
||||
|
||||
if (mConfigSliding.isShowing())
|
||||
mConfigSliding.toBaseLevel();
|
||||
else
|
||||
finish();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (v == mRefresh) {
|
||||
mImageSet.redownload(mGalleryView.getCurIndex());
|
||||
} else if (v == mSend) {
|
||||
mCurImageFile = mImageSet.getImageFile(mGalleryView.getCurIndex());
|
||||
if (mCurImageFile == null || !mCurImageFile.exists())
|
||||
MaterialToast.showToast(R.string.current_image_not_downloaded);
|
||||
else
|
||||
mSendDialog.show();
|
||||
|
||||
} else if (v == mMoreSettings) {
|
||||
Intent intent = new Intent(GalleryActivity.this, SettingsActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKeyDown (int keyCode, @NonNull KeyEvent event) {
|
||||
switch (keyCode) {
|
||||
case KeyEvent.KEYCODE_VOLUME_DOWN:
|
||||
if (mVolumePage) {
|
||||
mGalleryView.showNextPage();
|
||||
return true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
case KeyEvent.KEYCODE_VOLUME_UP:
|
||||
if (mVolumePage) {
|
||||
mGalleryView.showPreviousPage();
|
||||
return true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT:
|
||||
case KeyEvent.KEYCODE_PAGE_UP:
|
||||
mGalleryView.showPreviousPage();
|
||||
return true;
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT:
|
||||
case KeyEvent.KEYCODE_PAGE_DOWN:
|
||||
mGalleryView.showNextPage();
|
||||
return true;
|
||||
}
|
||||
return super.onKeyDown(keyCode, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceive(int id, Object obj) {
|
||||
if (obj instanceof Boolean) {
|
||||
mVolumePage = (Boolean) obj;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTapCenter() {
|
||||
if (!mConfigSliding.isShowing()) {
|
||||
if (mFullScreenHelper.willHideNavBar())
|
||||
cancelFullScreenTask();
|
||||
mFullScreenHelper.setFullScreen(false);
|
||||
|
||||
boolean firstTime = Config.getBoolean(KEY_FIRST_READ_CONFIG_V1, DEFAULT_FIRST_READ_CONFIG_V1);
|
||||
mConfigSliding.toReservedLevel(firstTime);
|
||||
if (firstTime)
|
||||
Config.setBoolean(KEY_FIRST_READ_CONFIG_V1, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageChanged(int index) {
|
||||
mPageSeeker.setProgress(index);
|
||||
mCurrentPage.setText(Integer.toString(index + 1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSizeUpdate(int size) {
|
||||
mPageSeeker.setMax(size - 1);
|
||||
mPageSeeker.setProgress(mGalleryView.getCurIndex() + 1);
|
||||
mCurrentPage.setText(Integer.toString(mGalleryView.getCurIndex() + 1));
|
||||
mPageSum.setText(Integer.toString(size));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSlideBottom(float dx) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSlideBottomOver() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
|
||||
public void onRightToLeftChanged(boolean value) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
|
||||
int nevLd = value ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR;
|
||||
if (mPageSeeker.getLayoutDirection() != nevLd) {
|
||||
mPageSeeker.setLayoutDirection(nevLd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProgressChanged(SeekBar seekBar, int progress,
|
||||
boolean fromUser) {
|
||||
if (seekBar == mPageSeeker) {
|
||||
mCurrentPage.setText(Integer.toString(progress + 1));
|
||||
} else if (seekBar == mCustomLightnessValue) {
|
||||
setScreenLightness(mCustomLightness.isChecked(), progress);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStartTrackingTouch(SeekBar seekBar) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStopTrackingTouch(SeekBar seekBar) {
|
||||
if (seekBar == mPageSeeker) {
|
||||
mGalleryView.goToPage(seekBar.getProgress());
|
||||
} else if (seekBar == mCustomLightnessValue) {
|
||||
Config.setCustomLightnessValue(seekBar.getProgress());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onChildHide() {
|
||||
if (mFullScreenHelper.willHideNavBar())
|
||||
startFullScreenTask();
|
||||
else
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int position,
|
||||
long id) {
|
||||
if (parent == mReadingDirection) {
|
||||
Config.setReadingDirection(mReadingDirection.getSelectedItemPosition());
|
||||
mGalleryView.setReadingDirection(position);
|
||||
} else if (parent == mPageScaling) {
|
||||
Config.setPageScaling(mPageScaling.getSelectedItemPosition());
|
||||
mGalleryView.setPageScaling(position);
|
||||
} else if (parent == mStartPosition) {
|
||||
Config.setStartPosition(mStartPosition.getSelectedItemPosition());
|
||||
mGalleryView.setStartPosition(position);
|
||||
} else if (parent == mDecodeFormat) {
|
||||
Config.setDecodeFormatFromIndex(mDecodeFormat.getSelectedItemPosition());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
if (buttonView == mShowClock) {
|
||||
Config.setShowClock(isChecked);
|
||||
mClock.setVisibility(isChecked ? View.VISIBLE : View.GONE);
|
||||
} else if (buttonView == mShowBattery) {
|
||||
Config.setShowBattery(isChecked);
|
||||
mBattery.setVisibility(isChecked ? View.VISIBLE : View.GONE);
|
||||
} else if (buttonView == mKeepScreenOn) {
|
||||
Config.setKeepSreenOn(isChecked);
|
||||
if (isChecked)
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
else
|
||||
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
} else if (buttonView == mCustomLightness) {
|
||||
Config.setCustomLightness(isChecked);
|
||||
if (isChecked)
|
||||
mCustomLightnessValue.setEnabled(true);
|
||||
else
|
||||
mCustomLightnessValue.setEnabled(false);
|
||||
setScreenLightness(isChecked, mCustomLightnessValue.getProgress());
|
||||
} else if (buttonView == mCustomCodec) {
|
||||
Config.setCustomCodec(isChecked);
|
||||
if (Utils.SUPPORT_IMAGE && mCustomCodec.isChecked())
|
||||
mDecodeFormat.setEnabled(true);
|
||||
else
|
||||
mDecodeFormat.setEnabled(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,271 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.CheckBox;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.FitWindowView;
|
||||
import com.hippo.ehviewer.widget.GalleryListView;
|
||||
import com.hippo.ehviewer.widget.GalleryListView.OnGetListListener;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.widget.recyclerview.SwipeToDismissTouchListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HistoryActivity extends AbsTranslucentActivity
|
||||
implements EasyRecyclerView.OnItemClickListener, MaterialAlertDialog.OnClickListener,
|
||||
GalleryListView.GalleryListViewHelper, FitWindowView.OnFitSystemWindowsListener {
|
||||
|
||||
private static final String TAG = HistoryActivity.class.getSimpleName();
|
||||
|
||||
public static final int LIST_MODE_DETAIL = 0;
|
||||
public static final int LIST_MODE_THUMB = 1;
|
||||
|
||||
private Data mData;
|
||||
private int mThemeColor;
|
||||
|
||||
private FitWindowView mStandard;
|
||||
private GalleryListView mGalleryListView;
|
||||
|
||||
private int mFilterMode;
|
||||
|
||||
private Dialog mFilterDialog;
|
||||
private CheckBox mJustBrowse;
|
||||
private CheckBox mHaveRead;
|
||||
|
||||
private Dialog mClearDialog;
|
||||
|
||||
private static final String HISTORY_URL = "ehviewer://history";
|
||||
private static final String KEY_HISTORY_FILTER = "history_filter";
|
||||
|
||||
private void setFilterDialogMode(int filterMode) {
|
||||
if ((filterMode & Data.BROWSE) == 0)
|
||||
mJustBrowse.setChecked(false);
|
||||
else
|
||||
mJustBrowse.setChecked(true);
|
||||
if ((filterMode & Data.READ) == 0)
|
||||
mHaveRead.setChecked(false);
|
||||
else
|
||||
mHaveRead.setChecked(true);
|
||||
}
|
||||
|
||||
private int getFilterDialogMode() {
|
||||
int filterMode = 0;
|
||||
filterMode |= mJustBrowse.isChecked() ? Data.BROWSE : 0;
|
||||
filterMode |= mHaveRead.isChecked() ? Data.READ : 0;
|
||||
return filterMode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (dialog == mFilterDialog) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
int newFilterMode = getFilterDialogMode();
|
||||
if (newFilterMode != mFilterMode) {
|
||||
mFilterMode = newFilterMode;
|
||||
Config.setInt(KEY_HISTORY_FILTER, mFilterMode);
|
||||
mGalleryListView.refresh();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
} else if (dialog == mClearDialog) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
Data.getInstance().clearHistory();
|
||||
mGalleryListView.refresh();
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
private void createFilterDialog() {
|
||||
View view = ViewUtils.inflateDialogView(R.layout.history_filter, false);
|
||||
mJustBrowse = (CheckBox) view.findViewById(R.id.just_browse);
|
||||
mHaveRead = (CheckBox) view.findViewById(R.id.have_read);
|
||||
|
||||
mFilterDialog = new MaterialAlertDialog.Builder(this).setTitle(R.string.filter)
|
||||
.setView(view, true)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(this).create();
|
||||
}
|
||||
|
||||
private void createClearDialog() {
|
||||
mClearDialog = new MaterialAlertDialog.Builder(this).setTitle(R.string.attention)
|
||||
.setMessage(R.string.clear_history_message)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(this).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFitSystemWindows(int l, int t, int r, int b) {
|
||||
mGalleryListView.setPaddingTopAndBottom(t, b);
|
||||
Ui.colorStatusBarKK(this, mThemeColor, t - Ui.ACTION_BAR_HEIGHT);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
mGalleryListView.refresh();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.history);
|
||||
|
||||
mData = Data.getInstance();
|
||||
mFilterMode = Config.getInt(KEY_HISTORY_FILTER, Data.BROWSE | Data.READ);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
// Theme
|
||||
mThemeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(mThemeColor));
|
||||
Ui.colorStatusBarL(this, mThemeColor);
|
||||
|
||||
mStandard = (FitWindowView) findViewById(R.id.standard);
|
||||
mGalleryListView = (GalleryListView) findViewById(R.id.gallery_list);
|
||||
|
||||
mGalleryListView.setGalleryListViewHelper(this);
|
||||
mStandard.addOnFitSystemWindowsListener(this);
|
||||
|
||||
// Do not need header an footer
|
||||
mGalleryListView.setEnabledHeader(false);
|
||||
mGalleryListView.setEnabledFooter(false);
|
||||
mGalleryListView.setOnItemClickListener(this);
|
||||
|
||||
SwipeToDismissTouchListener.DismissCallbacks callbacks = new SwipeToDismissTouchListener.DismissCallbacks() {
|
||||
@Override
|
||||
public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) {
|
||||
return SwipeToDismissTouchListener.SwipeDirection.BOTH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) {
|
||||
for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) {
|
||||
// TODO After delete all show NONE tip
|
||||
int position = data.position;
|
||||
mData.deleteHistory(mGalleryListView.getGalleryInfo(position).gid);
|
||||
mGalleryListView.removeGalleryInfo(position);
|
||||
mGalleryListView.getGalleryAdapter().notifyItemRemoved(data.position);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResetMotion() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTouchDown() {
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
mGalleryListView.addOnItemTouchListener(
|
||||
new SwipeToDismissTouchListener(mGalleryListView.getEasyRecyclerView(), callbacks));
|
||||
|
||||
createFilterDialog();
|
||||
createClearDialog();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
getMenuInflater().inflate(R.menu.history, menu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
|
||||
case R.id.action_filter:
|
||||
if (!mFilterDialog.isShowing()) {
|
||||
setFilterDialogMode(mFilterMode);
|
||||
mFilterDialog.show();
|
||||
}
|
||||
return true;
|
||||
|
||||
case R.id.action_clear:
|
||||
if (!mClearDialog.isShowing())
|
||||
mClearDialog.show();
|
||||
return true;
|
||||
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTargetUrl(int targetPage) {
|
||||
return HISTORY_URL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doGetGallerys(String url, long taskStamp,
|
||||
OnGetListListener listener) {
|
||||
if (url.equals(HISTORY_URL)) {
|
||||
List<GalleryInfo> giList = new ArrayList<GalleryInfo>(mData.getHistory(mFilterMode, true));
|
||||
if (giList.size() == 0)
|
||||
listener.onSuccess(taskStamp, giList, 0);
|
||||
else
|
||||
listener.onSuccess(taskStamp, giList, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onItemClick(EasyRecyclerView parent, View view,
|
||||
int position, long id) {
|
||||
Intent intent = new Intent(this, GalleryDetailActivity.class);
|
||||
GalleryInfo gi = mGalleryListView.getGalleryInfo(position);
|
||||
intent.putExtra(GalleryDetailActivity.KEY_G_INFO, gi);
|
||||
startActivity(intent);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternView;
|
||||
|
||||
public class PatternProtectionActivity extends AbsActivity implements View.OnClickListener{
|
||||
|
||||
private TextView mTextView;
|
||||
private LockPatternView mPatternView;
|
||||
private View mCancel;
|
||||
private View mOK;
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_pattern_protection);
|
||||
|
||||
// Set random color
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
mTextView = (TextView) findViewById(R.id.text);
|
||||
mPatternView = (LockPatternView) findViewById(R.id.pattern_view);
|
||||
mCancel = findViewById(R.id.cancel);
|
||||
mOK = findViewById(R.id.ok);
|
||||
|
||||
mOK.setOnClickListener(this);
|
||||
mCancel.setOnClickListener(this);
|
||||
|
||||
String pattern = Config.getPatternProtection();
|
||||
boolean setPattern = LockPatternUtils.isPatternVaild(pattern);
|
||||
Resources resources = getResources();
|
||||
int patternProtectionStateId = setPattern ?
|
||||
R.string.pattern_protection_set : R.string.pattern_protection_not_set;
|
||||
mTextView.setText(resources.getString(patternProtectionStateId) + "\n\n" +
|
||||
getString(R.string.pattern_protection_warning));
|
||||
|
||||
if (setPattern) {
|
||||
mPatternView.setPattern(LockPatternView.DisplayMode.Correct, LockPatternUtils.stringToPattern(pattern));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (v == mOK) {
|
||||
Config.setPatternProtection(mPatternView.getPatternString());
|
||||
finish();
|
||||
} else if (v == mCancel) {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.SystemClock;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.effect.DrawableTransition;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SecretActivity extends AbsActivity implements View.OnClickListener {
|
||||
|
||||
private final long[] mHits = new long[3];
|
||||
private Bitmap mBmp;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mBmp = Secret.getSecretImage(this);
|
||||
if (mBmp == null) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
ImageView iv = new ImageView(this);
|
||||
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
|
||||
iv.setImageBitmap(mBmp);
|
||||
iv.setOnClickListener(this);
|
||||
iv.setSoundEffectsEnabled(false);
|
||||
setContentView(iv);
|
||||
DrawableTransition.transit(iv.getDrawable(), false, 3000);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
if (mBmp != null) {
|
||||
mBmp.recycle();
|
||||
mBmp = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
System.arraycopy(mHits, 1, mHits, 0, mHits.length-1);
|
||||
mHits[mHits.length-1] = SystemClock.uptimeMillis();
|
||||
if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
|
||||
Arrays.fill(mHits, 0);
|
||||
MaterialToast.showToast(R.string.photo_footnotes);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,159 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* 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.annotation.SuppressLint;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Bundle;
|
||||
import android.os.Debug;
|
||||
import android.os.Handler;
|
||||
import android.view.Gravity;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Constants;
|
||||
import com.hippo.ehviewer.util.Messenger;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public abstract class StatsActivity extends AbsActivity {
|
||||
|
||||
private static final int DEFAULT_MESSAGE_SIZE = 128;
|
||||
private static final long STATS_CLOCK_INTERVAL_MS = 1000;
|
||||
private static final int BYTES_IN_MEGABYTE = 1024 * 1024;
|
||||
|
||||
private TextView mStatsTextView;
|
||||
private boolean mShowStats;
|
||||
private Runnable mStatsClockTickRunnable;
|
||||
private Handler mHandler;
|
||||
|
||||
private Messenger.Receiver mReceiver = new Messenger.Receiver() {
|
||||
@Override
|
||||
public void onReceive(int id, Object obj) {
|
||||
if (obj instanceof Boolean) {
|
||||
boolean showStats = (Boolean) obj;
|
||||
if (mShowStats != showStats) {
|
||||
mShowStats = showStats;
|
||||
ViewGroup vg = (ViewGroup) getWindow().getDecorView();
|
||||
if (showStats) {
|
||||
vg.addView(mStatsTextView, generateLayoutParams());
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
} else {
|
||||
vg.removeView(mStatsTextView);
|
||||
cancelNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@SuppressLint("RtlHardcoded")
|
||||
private ViewGroup.LayoutParams generateLayoutParams() {
|
||||
Resources resources = getResources();
|
||||
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.gravity = Gravity.TOP | Gravity.RIGHT;
|
||||
lp.topMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_top);
|
||||
lp.rightMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_right);
|
||||
return lp;
|
||||
}
|
||||
|
||||
private boolean isShowStats() {
|
||||
return Config.getShowApplicationStats();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mStatsTextView = new TextView(this);
|
||||
mHandler = AppHandler.getInstance();
|
||||
mStatsClockTickRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
}
|
||||
};
|
||||
Messenger.getInstance().register(
|
||||
Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
|
||||
|
||||
if (isShowStats()) {
|
||||
mShowStats = true;
|
||||
((ViewGroup) getWindow().getDecorView()).addView(mStatsTextView,
|
||||
generateLayoutParams());
|
||||
} else {
|
||||
mShowStats = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
Messenger.getInstance().unregister(Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
if (mShowStats) {
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
|
||||
if (mShowStats) {
|
||||
cancelNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
|
||||
private void scheduleNextStatsClockTick() {
|
||||
mHandler.postDelayed(mStatsClockTickRunnable, STATS_CLOCK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private void cancelNextStatsClockTick() {
|
||||
mHandler.removeCallbacks(mStatsClockTickRunnable);
|
||||
}
|
||||
|
||||
private void updateStats() {
|
||||
final Runtime runtime = Runtime.getRuntime();
|
||||
final long heapMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
final StringBuilder sb = new StringBuilder(DEFAULT_MESSAGE_SIZE);
|
||||
appendSize(sb, "Java heap size: ", heapMemory, "\n");
|
||||
appendSize(sb, "Native heap size: ", Debug.getNativeHeapAllocatedSize(), "\n");
|
||||
mStatsTextView.setText(sb.toString());
|
||||
}
|
||||
|
||||
private static void appendSize(StringBuilder sb, String prefix, long bytes, String suffix) {
|
||||
String value = String.format(Locale.getDefault(), "%.2f", (float) bytes / BYTES_IN_MEGABYTE);
|
||||
appendValue(sb, prefix, value + " MB", suffix);
|
||||
}
|
||||
|
||||
private static void appendValue(StringBuilder sb, String prefix, String value, String suffix) {
|
||||
sb.append(prefix).append(value).append(suffix);
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.Bundle;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
|
||||
public class WebViewLoginActivity extends AbsActivity {
|
||||
|
||||
private static final String TITLE_LOGIN_SUCCESS = "Please stand by...";
|
||||
|
||||
public static final String KEY_ERROR = "error";
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
WebView wv = new WebView(this);
|
||||
CookieManager.getInstance().removeAllCookie();
|
||||
wv.getSettings().setJavaScriptEnabled(true);
|
||||
wv.setWebViewClient(new LoginWebViewClient());
|
||||
wv.loadUrl(EhClient.LOGIN_URL);
|
||||
setContentView(wv);
|
||||
}
|
||||
|
||||
private class LoginWebViewClient extends WebViewClient {
|
||||
@Override
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
if (TITLE_LOGIN_SUCCESS.equals(view.getTitle())) {
|
||||
// Login OK
|
||||
String cookies = CookieManager.getInstance().getCookie(url);
|
||||
if (cookies != null) {
|
||||
// Store cookie
|
||||
EhInfo ehInfo = EhInfo.getInstance(WebViewLoginActivity.this);
|
||||
ehInfo.setCookie(cookies);
|
||||
ehInfo.login("User", "User");
|
||||
setResult(RESULT_OK);
|
||||
} else {
|
||||
setResult(RESULT_CANCELED);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* 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.util;
|
||||
|
||||
import android.os.Environment;
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Something about this app
|
||||
*/
|
||||
public final class AppConfig {
|
||||
|
||||
private static final String APP_DIRNAME = "EhViewer";
|
||||
private static final String CRASH_DIRNAME = "crash";
|
||||
private static final String DOWNLOAD_DIRNAME = "download";
|
||||
private static final String TORRENT_DIRNAME = "torrent";
|
||||
|
||||
public static @Nullable File getAppDir() {
|
||||
if (Environment.getExternalStorageState()
|
||||
.equals(Environment.MEDIA_MOUNTED)) {
|
||||
return new File(Environment.getExternalStorageDirectory(), APP_DIRNAME);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable File getFileInAppDir(String filename) {
|
||||
File appFolder = getAppDir();
|
||||
if (appFolder != null) {
|
||||
return new File(appFolder, filename);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable File getCrashDir() {
|
||||
return getFileInAppDir(CRASH_DIRNAME);
|
||||
}
|
||||
|
||||
public static @Nullable File getDownloadDir() {
|
||||
return getFileInAppDir(DOWNLOAD_DIRNAME);
|
||||
}
|
||||
|
||||
public static @Nullable File getTorrentDir() {
|
||||
return getFileInAppDir(TORRENT_DIRNAME);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user