mirror of
https://github.com/seven332/EhViewer
synced 2026-12-05 21:39:01 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b6f458c60 | ||
|
|
1998af3d0b | ||
|
|
e3b5ed840e | ||
|
|
e96d91184f | ||
|
|
5822e58984 | ||
|
|
da90150233 | ||
|
|
62d6609b15 | ||
|
|
e451db6032 | ||
|
|
a2bbe855e8 | ||
|
|
374ed3a515 | ||
|
|
6f0af8b6ec | ||
|
|
a98cd0bc79 | ||
|
|
0e125738e2 | ||
|
|
055fd5e8ae | ||
|
|
10ba81f5cc | ||
|
|
08d79aa204 | ||
|
|
d0e1b4cfee | ||
|
|
90d95c6552 | ||
|
|
53a7cc84a2 | ||
|
|
129b70e15c | ||
|
|
80282ffd04 | ||
|
|
e3209cd2c0 | ||
|
|
3681bd1dd4 | ||
|
|
a6fea77b15 | ||
|
|
e08a9bfdfa | ||
|
|
ee229b11da | ||
|
|
dfa5998483 | ||
|
|
b743bdb581 | ||
|
|
fa5d8380c9 | ||
|
|
79ffce2f3e | ||
|
|
d89db7754f | ||
|
|
ef154867a6 | ||
|
|
8abe21c536 | ||
|
|
333c783a0d | ||
|
|
eae2375560 | ||
|
|
0a3adfb06b | ||
|
|
5fda8b792c | ||
|
|
0ea49f593b | ||
|
|
6331c3c86d | ||
|
|
99df5be760 | ||
|
|
53f8f6defc | ||
|
|
c1d39de57c | ||
|
|
f0c8c14918 | ||
|
|
5b0b1b1614 | ||
|
|
8ffa54dc25 | ||
|
|
ae4714aa48 | ||
|
|
802c11bed1 | ||
|
|
ff2ed3205d | ||
|
|
ba7f1a5aed | ||
|
|
43903adcc4 | ||
|
|
703fc5f44d | ||
|
|
485f4ba9f2 | ||
|
|
1d6e6277d8 | ||
|
|
2ed2c08183 | ||
|
|
eaae310f05 | ||
|
|
ab9b7e59d9 | ||
|
|
07614fecef | ||
|
|
fae86c1782 | ||
|
|
b0fc8f4c58 | ||
|
|
5cdc004829 | ||
|
|
7efed23ddf | ||
|
|
251ed9b687 | ||
|
|
1b017250a5 | ||
|
|
5e9097b1bf | ||
|
|
62858aa5d2 | ||
|
|
8ceb7ca912 | ||
|
|
4ce0a60397 | ||
|
|
75731d5600 | ||
|
|
7ddeef682a | ||
|
|
da076be7fb | ||
|
|
7235e3abd5 | ||
|
|
05cfabae10 | ||
|
|
32e345f9f0 | ||
|
|
6b7f314e9f | ||
|
|
db3fe7e446 | ||
|
|
d7e42a760c | ||
|
|
f90588e79e | ||
|
|
deefd9b9e3 | ||
|
|
e01ef1abff | ||
|
|
facb17eac2 | ||
|
|
151c16ad83 | ||
|
|
07d1cc6bf6 | ||
|
|
e9bb78ebfc | ||
|
|
c154f9b73a | ||
|
|
51266d4c3b | ||
|
|
f02998b917 | ||
|
|
b6f89741ee | ||
|
|
2498be6850 | ||
|
|
ce2907610a | ||
|
|
4e266c160c | ||
|
|
3e76680aeb | ||
|
|
8ad331af60 | ||
|
|
90a41a1d6b | ||
|
|
ce786f4e41 | ||
|
|
3f099969d1 | ||
|
|
e0acfa55eb | ||
|
|
f4472005b5 | ||
|
|
1c2263c001 | ||
|
|
6f93bb5b88 | ||
|
|
1d2978952b | ||
|
|
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,6 +0,0 @@
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
Generated
-1
@@ -1 +0,0 @@
|
||||
EhViewer
|
||||
Generated
-23
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<option name="DEFAULT_COMPILER" value="Javac" />
|
||||
<resourceExtensions />
|
||||
<wildcardResourcePatterns>
|
||||
<entry name="!?*.java" />
|
||||
<entry name="!?*.form" />
|
||||
<entry name="!?*.class" />
|
||||
<entry name="!?*.groovy" />
|
||||
<entry name="!?*.scala" />
|
||||
<entry name="!?*.flex" />
|
||||
<entry name="!?*.kt" />
|
||||
<entry name="!?*.clj" />
|
||||
</wildcardResourcePatterns>
|
||||
<annotationProcessing>
|
||||
<profile default="true" name="Default" enabled="false">
|
||||
<processorPath useClasspath="true" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
||||
|
||||
Generated
-3
@@ -1,3 +0,0 @@
|
||||
<component name="CopyrightManager">
|
||||
<settings default="" />
|
||||
</component>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" defaultCharsetForPropertiesFiles="UTF-8">
|
||||
<file url="PROJECT" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-18
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleJvm" value="1.7" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0" is_locked="false">
|
||||
<option name="myName" value="Project Default" />
|
||||
<option name="myLocal" value="false" />
|
||||
<inspection_tool class="LoggerInitializedWithForeignClass" enabled="false" level="WARNING" enabled_by_default="false">
|
||||
<option name="loggerClassName" value="org.apache.log4j.Logger,org.slf4j.LoggerFactory,org.apache.commons.logging.LogFactory,java.util.logging.Logger" />
|
||||
<option name="loggerFactoryMethodName" value="getLogger,getLogger,getLog,getLogger" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
|
||||
<option name="processCode" value="true" />
|
||||
<option name="processLiterals" value="true" />
|
||||
<option name="processComments" value="true" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="PROJECT_PROFILE" value="Project Default" />
|
||||
<option name="USE_PROJECT_PROFILE" value="true" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
Generated
-10
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EntryPointsManager">
|
||||
<entry_points version="2.0" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
</project>
|
||||
|
||||
Generated
-10
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/EhViewer.iml" filepath="$PROJECT_DIR$/EhViewer.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
||||
Generated
-5
@@ -1,5 +0,0 @@
|
||||
<component name="DependencyValidationManager">
|
||||
<state>
|
||||
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
|
||||
</state>
|
||||
</component>
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
|
||||
@@ -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
|
||||
@@ -14,9 +14,14 @@
|
||||
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">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.hippo.ehviewer"
|
||||
android:versionCode="21"
|
||||
android:versionName="0.6.0" >
|
||||
|
||||
<uses-sdk
|
||||
android:minSdkVersion="14"
|
||||
android:targetSdkVersion="19" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
@@ -28,17 +33,15 @@
|
||||
android:allowBackup="true"
|
||||
android:hardwareAccelerated="true"
|
||||
android:largeHeap="true"
|
||||
android:supportsRtl="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme.Normal">
|
||||
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" >
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
@@ -47,7 +50,7 @@
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryListActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:label="@string/app_name"
|
||||
android:launchMode="singleTop"
|
||||
android:screenOrientation="behind"
|
||||
@@ -60,18 +63,9 @@
|
||||
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:configChanges="orientation|screenSize"
|
||||
android:screenOrientation="behind"
|
||||
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden" >
|
||||
<intent-filter>
|
||||
@@ -88,37 +82,32 @@
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.Dark.NoActionBar" >
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.SettingsActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_settings"
|
||||
android:label="@string/preference_settings_title"
|
||||
android:screenOrientation="behind" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.FavouriteActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_favorite"
|
||||
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:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_download"
|
||||
android:label="@string/download"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="behind"
|
||||
@@ -128,22 +117,9 @@
|
||||
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>
|
||||
|
||||
<service
|
||||
android:name=".service.DownloadService"
|
||||
android:label="DownloadService" />
|
||||
|
||||
<provider
|
||||
android:name=".SimpleSuggestionProvider"
|
||||
android:authorities="com.hippo.ehviewer.SimpleSuggestionProvider"
|
||||
android:exported="false" />
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
</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" 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.
|
||||
@@ -0,0 +1,13 @@
|
||||
# EhViewer
|
||||
|
||||
这是一个 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)),
|
||||
部分文件可随意使用([列表](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 free to use ([list](rc/list2)).
|
||||
@@ -1 +0,0 @@
|
||||
/build
|
||||
-95
@@ -1,95 +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" />
|
||||
<option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
|
||||
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
|
||||
<option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
|
||||
<option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
|
||||
<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" inherit-compiler-output="false">
|
||||
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
|
||||
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/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/generated/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/generated/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/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/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" 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" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
|
||||
<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="support-v4-22.0.0" level="project" />
|
||||
<orderEntry type="library" exported="" name="svg-android-2.0.6" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-annotations-22.0.0" level="project" />
|
||||
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-22.0.0" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -1,31 +0,0 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion "22"
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.hippo.ehviewer"
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 22
|
||||
versionCode 36
|
||||
versionName "0.6.12"
|
||||
}
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
release {
|
||||
minifyEnabled true
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(dir: 'libs', include: ['*.jar'])
|
||||
compile 'com.android.support:support-v4:22.0.0'
|
||||
compile 'com.android.support:recyclerview-v7:22.0.0'
|
||||
compile 'com.github.japgolly.android:svg-android:2.0.6'
|
||||
}
|
||||
Binary file not shown.
Vendored
-52
@@ -1,52 +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*();
|
||||
}
|
||||
|
||||
# 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);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -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;
|
||||
|
||||
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.data.Data;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
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);
|
||||
Favorite.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).evictAll();
|
||||
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;
|
||||
Crash.saveCrashInfo2File(ex);
|
||||
return true;
|
||||
}
|
||||
|
||||
public Typeface getFaceTypeface() {
|
||||
return mFaceTypeface;
|
||||
}
|
||||
}
|
||||
@@ -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,256 +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.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.text.util.Linkify;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.network.Network;
|
||||
import com.hippo.ehviewer.ui.AbsActivity;
|
||||
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.larvalabs.svgandroid.SVGBuilder;
|
||||
|
||||
public class StartActivity extends AbsActivity {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = StartActivity.class.getSimpleName();
|
||||
|
||||
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 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();
|
||||
Intent i = new Intent(Intent.ACTION_SENDTO);
|
||||
i.setData(Uri.parse("mailto:ehviewersu@gmail.com"));
|
||||
i.putExtra(Intent.EXTRA_SUBJECT, "I found a bug in EhViewer !");
|
||||
i.putExtra(Intent.EXTRA_TEXT, lastCrash + "======== Description ========\n" + et.getText().toString());
|
||||
startActivity(i);
|
||||
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"));
|
||||
ImageView image = (ImageView) findViewById(R.id.image);
|
||||
image.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
|
||||
image.setImageDrawable(new SVGBuilder().readFromResource(getResources(), R.raw.sad_pandroid).build().getDrawable());
|
||||
|
||||
// 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 (isCheckOver)
|
||||
redirectTo();
|
||||
isAnimationOver = true;
|
||||
}
|
||||
}, 3000);
|
||||
check(CHECK_WARING);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
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,405 +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.v4.util.LruCache;
|
||||
|
||||
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 class AnyCache<V> {
|
||||
|
||||
private LruCache<String, V> mMemoryCache;
|
||||
private DiskCache<V> mDiskCache;
|
||||
|
||||
/**
|
||||
* Used to temporarily pause the disk cache while scrolling
|
||||
*/
|
||||
public boolean mPauseDiskAccess = false;
|
||||
private final Object mPauseLock = new Object();
|
||||
|
||||
private AnyCache(Builder builder) {
|
||||
if (builder.mMemoryCacheMaxSize > 0 && builder.mMemoryCacheHelper != null) {
|
||||
mMemoryCache = new MemoryCahce<V>(
|
||||
builder.mMemoryCacheMaxSize, builder.mMemoryCacheHelper);
|
||||
}
|
||||
if (builder.mDiskCacheDir != null && builder.mDiskCacheMaxSize > 0 &&
|
||||
builder.mDiskCacheHelper != null) {
|
||||
try {
|
||||
mDiskCache = new DiskCache<V>(
|
||||
builder.mDiskCacheDir, builder.mDiskCacheMaxSize, builder.mDiskCacheHelper);
|
||||
} catch (IOException e) {
|
||||
// Can't create disk cache
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if have memory cache
|
||||
*
|
||||
* @return true if have memory cache
|
||||
*/
|
||||
public boolean hasMemoryCache() {
|
||||
return mMemoryCache != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if have disk cache
|
||||
*
|
||||
* @return true if have disk cache
|
||||
*/
|
||||
public boolean hasDiskCache() {
|
||||
return mDiskCache != 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
|
||||
*/
|
||||
public V getFromMemory(String key) {
|
||||
if (mMemoryCache != null) {
|
||||
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 (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
return mDiskCache.get(diskKey);
|
||||
} 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;
|
||||
if (mMemoryCache != null) {
|
||||
value = mMemoryCache.get(key);
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
if (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
value = mDiskCache.get(diskKey);
|
||||
// Put value to memory cach
|
||||
if (value != null && mMemoryCache != null) {
|
||||
mMemoryCache.put(key, value);
|
||||
}
|
||||
return value;
|
||||
} else {
|
||||
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 (mMemoryCache != null) {
|
||||
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 (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
return mDiskCache.put(diskKey, value);
|
||||
} 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) {
|
||||
if (mMemoryCache != null) {
|
||||
mMemoryCache.put(key, value);
|
||||
}
|
||||
|
||||
if (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
mDiskCache.put(diskKey, 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 and lets the system know
|
||||
* now would be a good time to garbage collect
|
||||
*/
|
||||
public void evictAll() {
|
||||
if (mMemoryCache != null) {
|
||||
mMemoryCache.evictAll();
|
||||
}
|
||||
System.gc();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
|
||||
private int mMemoryCacheMaxSize;
|
||||
private MemoryCacheHelper mMemoryCacheHelper;
|
||||
|
||||
private File mDiskCacheDir;
|
||||
private int mDiskCacheMaxSize;
|
||||
private DiskCacheHelper mDiskCacheHelper;
|
||||
|
||||
public Builder setMemoryCache(int maxSize, MemoryCacheHelper helper) {
|
||||
mMemoryCacheMaxSize = maxSize;
|
||||
mMemoryCacheHelper = helper;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this dir to store disk cache.
|
||||
*
|
||||
* @param cacheDir this dir to store disk cache, null for no disk cache
|
||||
* @return the Builder
|
||||
*/
|
||||
public Builder setDiskCache(File cacheDir, int maxSize, DiskCacheHelper helper) {
|
||||
mDiskCacheDir = cacheDir;
|
||||
mDiskCacheMaxSize = maxSize;
|
||||
mDiskCacheHelper = helper;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AnyCache build() {
|
||||
return new AnyCache(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class MemoryCahce<E> extends LruCache<String, E> {
|
||||
|
||||
private MemoryCacheHelper<E> mHelper;
|
||||
|
||||
public MemoryCahce(int maxSize, MemoryCacheHelper<E> helper) {
|
||||
super(maxSize);
|
||||
mHelper = helper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int sizeOf(String key, E value) {
|
||||
return mHelper.sizeOf(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class MemoryCacheHelper<E> {
|
||||
public abstract int sizeOf(String key, E value);
|
||||
}
|
||||
|
||||
public static class DiskCache<E> {
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
public DiskLruCache mDiskLruCache;
|
||||
public DiskCacheHelper<E> mHelper;
|
||||
|
||||
public DiskCache(File cacheDir, int size, DiskCacheHelper<E> helper) throws IOException {
|
||||
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
|
||||
mHelper = helper;
|
||||
}
|
||||
|
||||
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 mHelper.get(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;
|
||||
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 = mHelper.put(buffOut, value);
|
||||
mDiskLruCache.flush();
|
||||
editor.commit();
|
||||
return result;
|
||||
} else {
|
||||
// Can't get OutputStream
|
||||
editor.abort();
|
||||
return false;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Util.closeQuietly(os);
|
||||
try {
|
||||
if (editor != null) {
|
||||
editor.abort();
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public abstract static class DiskCacheHelper<E> {
|
||||
public abstract E get(InputStream is);
|
||||
|
||||
public abstract boolean put(OutputStream os, E value);
|
||||
}
|
||||
}
|
||||
@@ -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,122 +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.os.Build;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class ImageCache {
|
||||
|
||||
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 AnyCache<Bitmap> sImageCache;
|
||||
|
||||
public static AnyCache<Bitmap> getImageCache(Context context) {
|
||||
if (sImageCache == null) {
|
||||
AnyCache.Builder builder = new AnyCache.Builder();
|
||||
|
||||
final ActivityManager activityManager = (ActivityManager)context
|
||||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
|
||||
* 1024 * 1024);
|
||||
builder.setMemoryCache(memoryCacheMax, new BitmapMemoryCacheHelper());
|
||||
|
||||
File diskCacheDir = getDiskCacheDir(context, TAG);
|
||||
if (diskCacheDir != null) {
|
||||
if (!diskCacheDir.exists()) {
|
||||
diskCacheDir.mkdirs();
|
||||
}
|
||||
builder.setDiskCache(diskCacheDir, 20 * 1024 * 1024, new BitmapDiskCacheHelper());
|
||||
}
|
||||
|
||||
sImageCache = builder.build();
|
||||
}
|
||||
return sImageCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the external app cache directory
|
||||
*
|
||||
* @param context The {@link Context} to use
|
||||
* @return The external cache directory
|
||||
*/
|
||||
public 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
|
||||
*/
|
||||
public 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);
|
||||
}
|
||||
|
||||
private static class BitmapMemoryCacheHelper extends AnyCache.MemoryCacheHelper<Bitmap> {
|
||||
@Override
|
||||
public int sizeOf(String key, android.graphics.Bitmap bitmap) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
return bitmap.getAllocationByteCount();
|
||||
} else {
|
||||
return bitmap.getByteCount();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class BitmapDiskCacheHelper extends AnyCache.DiskCacheHelper<Bitmap> {
|
||||
@Override
|
||||
public Bitmap get(InputStream is) {
|
||||
return BitmapFactory.decodeStream(is);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean put(OutputStream os, Bitmap value) {
|
||||
value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,196 +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.cache;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Buffers input from an {@link InputStream} for reading lines.
|
||||
*
|
||||
* <p>This class is used for buffered reading of lines. For purposes of this class, a line ends
|
||||
* with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated
|
||||
* line at end of input is invalid and will be ignored, the caller may use {@code
|
||||
* hasUnterminatedLine()} to detect it after catching the {@code EOFException}.
|
||||
*
|
||||
* <p>This class is intended for reading input that strictly consists of lines, such as line-based
|
||||
* cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
|
||||
* with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
|
||||
* end-of-input reporting and a more restrictive definition of a line.
|
||||
*
|
||||
* <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
|
||||
* and 10, respectively, and the representation of no other character contains these values.
|
||||
* We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
|
||||
* The default charset is US_ASCII.
|
||||
*/
|
||||
class StrictLineReader implements Closeable {
|
||||
private static final byte CR = (byte) '\r';
|
||||
private static final byte LF = (byte) '\n';
|
||||
|
||||
private final InputStream in;
|
||||
private final Charset charset;
|
||||
|
||||
/*
|
||||
* Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
|
||||
* and the data in the range [pos, end) is buffered for reading. At end of input, if there is
|
||||
* an unterminated line, we set end == -1, otherwise end == pos. If the underlying
|
||||
* {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
|
||||
*/
|
||||
private byte[] buf;
|
||||
private int pos;
|
||||
private int end;
|
||||
|
||||
/**
|
||||
* Constructs a new {@code LineReader} with the specified charset and the default capacity.
|
||||
*
|
||||
* @param in the {@code InputStream} to read data from.
|
||||
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
|
||||
* supported.
|
||||
* @throws NullPointerException if {@code in} or {@code charset} is null.
|
||||
* @throws IllegalArgumentException if the specified charset is not supported.
|
||||
*/
|
||||
public StrictLineReader(InputStream in, Charset charset) {
|
||||
this(in, 8192, charset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new {@code LineReader} with the specified capacity and charset.
|
||||
*
|
||||
* @param in the {@code InputStream} to read data from.
|
||||
* @param capacity the capacity of the buffer.
|
||||
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
|
||||
* supported.
|
||||
* @throws NullPointerException if {@code in} or {@code charset} is null.
|
||||
* @throws IllegalArgumentException if {@code capacity} is negative or zero
|
||||
* or the specified charset is not supported.
|
||||
*/
|
||||
public StrictLineReader(InputStream in, int capacity, Charset charset) {
|
||||
if (in == null || charset == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
if (capacity < 0) {
|
||||
throw new IllegalArgumentException("capacity <= 0");
|
||||
}
|
||||
if (!(charset.equals(Util.US_ASCII))) {
|
||||
throw new IllegalArgumentException("Unsupported encoding");
|
||||
}
|
||||
|
||||
this.in = in;
|
||||
this.charset = charset;
|
||||
buf = new byte[capacity];
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the reader by closing the underlying {@code InputStream} and
|
||||
* marking this reader as closed.
|
||||
*
|
||||
* @throws IOException for errors when closing the underlying {@code InputStream}.
|
||||
*/
|
||||
public void close() throws IOException {
|
||||
synchronized (in) {
|
||||
if (buf != null) {
|
||||
buf = null;
|
||||
in.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
|
||||
* this end of line marker is not included in the result.
|
||||
*
|
||||
* @return the next line from the input.
|
||||
* @throws IOException for underlying {@code InputStream} errors.
|
||||
* @throws EOFException for the end of source stream.
|
||||
*/
|
||||
public String readLine() throws IOException {
|
||||
synchronized (in) {
|
||||
if (buf == null) {
|
||||
throw new IOException("LineReader is closed");
|
||||
}
|
||||
|
||||
// Read more data if we are at the end of the buffered data.
|
||||
// Though it's an error to read after an exception, we will let {@code fillBuf()}
|
||||
// throw again if that happens; thus we need to handle end == -1 as well as end == pos.
|
||||
if (pos >= end) {
|
||||
fillBuf();
|
||||
}
|
||||
// Try to find LF in the buffered data and return the line if successful.
|
||||
for (int i = pos; i != end; ++i) {
|
||||
if (buf[i] == LF) {
|
||||
int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
|
||||
String res = new String(buf, pos, lineEnd - pos, charset.name());
|
||||
pos = i + 1;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// Let's anticipate up to 80 characters on top of those already read.
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
|
||||
@Override
|
||||
public String toString() {
|
||||
int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
|
||||
try {
|
||||
return new String(buf, 0, length, charset.name());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new AssertionError(e); // Since we control the charset this will never happen.
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
while (true) {
|
||||
out.write(buf, pos, end - pos);
|
||||
// Mark unterminated line in case fillBuf throws EOFException or IOException.
|
||||
end = -1;
|
||||
fillBuf();
|
||||
// Try to find LF in the buffered data and return the line if successful.
|
||||
for (int i = pos; i != end; ++i) {
|
||||
if (buf[i] == LF) {
|
||||
if (i != pos) {
|
||||
out.write(buf, pos, i - pos);
|
||||
}
|
||||
pos = i + 1;
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasUnterminatedLine() {
|
||||
return end == -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads new input data into the buffer. Call only with pos == end or end == -1,
|
||||
* depending on the desired outcome if the function throws.
|
||||
*/
|
||||
private void fillBuf() throws IOException {
|
||||
int result = in.read(buf, 0, buf.length);
|
||||
if (result == -1) {
|
||||
throw new EOFException();
|
||||
}
|
||||
pos = 0;
|
||||
end = result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,77 +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.cache;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** Junk drawer of utility methods. */
|
||||
final class Util {
|
||||
static final Charset US_ASCII = Charset.forName("US-ASCII");
|
||||
static final Charset UTF_8 = Charset.forName("UTF-8");
|
||||
|
||||
private Util() {
|
||||
}
|
||||
|
||||
static String readFully(Reader reader) throws IOException {
|
||||
try {
|
||||
StringWriter writer = new StringWriter();
|
||||
char[] buffer = new char[1024];
|
||||
int count;
|
||||
while ((count = reader.read(buffer)) != -1) {
|
||||
writer.write(buffer, 0, count);
|
||||
}
|
||||
return writer.toString();
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the contents of {@code dir}. Throws an IOException if any file
|
||||
* could not be deleted, or if {@code dir} is not a readable directory.
|
||||
*/
|
||||
static void deleteContents(File dir) throws IOException {
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) {
|
||||
throw new IOException("not a readable directory: " + dir);
|
||||
}
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
deleteContents(file);
|
||||
}
|
||||
if (!file.delete()) {
|
||||
throw new IOException("failed to delete file: " + file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void closeQuietly(/*Auto*/Closeable closeable) {
|
||||
if (closeable != null) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (RuntimeException rethrown) {
|
||||
throw rethrown;
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,73 +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 HistoryItem extends GalleryInfo {
|
||||
public int mode;
|
||||
public long date;
|
||||
|
||||
public static final Parcelable.Creator<HistoryItem> CREATOR =
|
||||
new Parcelable.Creator<HistoryItem>() {
|
||||
@Override
|
||||
public HistoryItem createFromParcel(Parcel source) {
|
||||
HistoryItem p = new HistoryItem();
|
||||
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.mode = source.readInt();
|
||||
p.date = source.readLong();
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HistoryItem[] newArray(int size) {
|
||||
return new HistoryItem[size];
|
||||
}
|
||||
};
|
||||
|
||||
public HistoryItem() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public HistoryItem(GalleryInfo gi, int m, long d) {
|
||||
super(gi);
|
||||
mode = m;
|
||||
date = d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
dest.writeInt(mode);
|
||||
dest.writeLong(date);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,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,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,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,41 +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.ui;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class SynchronizedHandler extends Handler {
|
||||
|
||||
private final GLRoot mRoot;
|
||||
|
||||
public SynchronizedHandler(GLRoot root) {
|
||||
mRoot = Utils.checkNotNull(root);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispatchMessage(Message message) {
|
||||
mRoot.lockRenderThread();
|
||||
try {
|
||||
super.dispatchMessage(message);
|
||||
} finally {
|
||||
mRoot.unlockRenderThread();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,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,479 +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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
|
||||
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);
|
||||
Intent intent = new Intent(DownloadService.this,DownloadActivity.class);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
mBuilder.setContentIntent(pendingIntent);
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart(int gid) {
|
||||
if (mCurDownloadInfo == null)
|
||||
return;
|
||||
|
||||
mCurDownloadInfo.download = -1;
|
||||
mCurDownloadInfo.total = -1;
|
||||
|
||||
ensureNotification();
|
||||
|
||||
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();
|
||||
|
||||
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();
|
||||
|
||||
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();
|
||||
|
||||
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,49 +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.app.Activity;
|
||||
|
||||
import com.google.analytics.tracking.android.EasyTracker;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
public abstract class AbsActivity extends Activity {
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
Ui.adjustOrientation(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
|
||||
if (Config.getAllowAnalyics())
|
||||
EasyTracker.getInstance(this).activityStart(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
|
||||
if (Config.getAllowAnalyics())
|
||||
EasyTracker.getInstance(this).activityStop(this);
|
||||
}
|
||||
}
|
||||
@@ -1,551 +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 java.io.File;
|
||||
|
||||
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.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.Utils;
|
||||
import com.hippo.ehviewer.widget.ColorView;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SlidingLayout;
|
||||
|
||||
public class GalleryActivity extends AbsActivity
|
||||
implements GalleryView.GalleryViewListener, SeekBar.OnSeekBarChangeListener,
|
||||
FullScreenHelper.OnFullScreenBrokenListener, CompoundButton.OnCheckedChangeListener,
|
||||
SlidingLayout.OnChildHideListener, AdapterView.OnItemSelectedListener,
|
||||
View.OnClickListener, Utils.OnCopyOverListener {
|
||||
|
||||
@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 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);
|
||||
|
||||
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 = (GalleryInfo) 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();
|
||||
|
||||
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 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
@@ -1,238 +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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.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;
|
||||
|
||||
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);
|
||||
|
||||
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 == null || 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,81 +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 java.util.Arrays;
|
||||
|
||||
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.Config;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,921 +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 java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.SystemClock;
|
||||
import android.preference.CheckBoxPreference;
|
||||
import android.preference.Preference;
|
||||
import android.preference.PreferenceFragment;
|
||||
import android.provider.SearchRecentSuggestions;
|
||||
import android.text.util.Linkify;
|
||||
import android.view.MenuItem;
|
||||
import android.webkit.WebView;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TableLayout;
|
||||
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.SimpleSuggestionProvider;
|
||||
import com.hippo.ehviewer.UpdateHelper;
|
||||
import com.hippo.ehviewer.app.DirSelectDialog;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.app.MaterialProgressDialog;
|
||||
import com.hippo.ehviewer.data.ApiGalleryInfo;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.DownloadInfo;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.preference.ListPreference;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.DialogUtils;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.CategoryTable;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SuggestionHelper;
|
||||
|
||||
public class SettingsActivity extends AbsPreferenceActivity {
|
||||
@SuppressWarnings("unused")
|
||||
private static String TAG = SettingsActivity.class.getSimpleName();
|
||||
|
||||
private int mThemeColor;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
// Set random color
|
||||
mThemeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(mThemeColor));
|
||||
Ui.colorStatusBarL(this, mThemeColor);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBuildHeaders(List<Header> target) {
|
||||
loadHeadersFromResource(R.xml.settings_headers, target);
|
||||
}
|
||||
|
||||
private static final String[] ENTRY_FRAGMENTS = { DisplayFragment.class.getName(), EhFragment.class.getName(),
|
||||
ReadFragment.class.getName(), DownloadFragment.class.getName(), AdvancedFragment.class.getName(),
|
||||
AboutFragment.class.getName() };
|
||||
|
||||
private static final int[] FRAGMENT_ICONS = { R.drawable.ic_setting_display, R.drawable.ic_setting_panda_light,
|
||||
R.drawable.ic_setting_read, R.drawable.ic_setting_download, R.drawable.ic_setting_advanced,
|
||||
R.drawable.ic_setting_about };
|
||||
|
||||
@Override
|
||||
protected boolean isValidFragment(String fragmentName) {
|
||||
for (int i = 0; i < ENTRY_FRAGMENTS.length; i++) {
|
||||
if (ENTRY_FRAGMENTS[i].equals(fragmentName))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static class DisplayFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceChangeListener {
|
||||
|
||||
private static final String KEY_SCREEN_ORIENTATION = "screen_orientation";
|
||||
|
||||
private ListPreference mScreenOrientation;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.display_settings);
|
||||
|
||||
mScreenOrientation = (ListPreference) findPreference(KEY_SCREEN_ORIENTATION);
|
||||
mScreenOrientation.setOnPreferenceChangeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_SCREEN_ORIENTATION.equals(key)) {
|
||||
getActivity().setRequestedOrientation(Config.screenOriPre2Value(Integer.parseInt((String) newValue)));
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class EhFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final int[] EXCULDE_TAG_GROUP_RESID = { R.id.tag_group_reclass, R.id.tag_group_language,
|
||||
R.id.tag_group_parody, R.id.tag_group_character, R.id.tag_group_group, R.id.tag_group_artist,
|
||||
R.id.tag_group_male, R.id.tag_group_female };
|
||||
|
||||
private static final int[] EXCULDE_TAG_GROUP_ID = { 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80 };
|
||||
|
||||
private static final int[] EXCULDE_LANGUAGE_RESID = { R.id.el_japanese_translated, R.id.el_japanese_rewrite,
|
||||
R.id.el_english_original, R.id.el_english_translated, R.id.el_english_rewrite,
|
||||
R.id.el_chinese_original, R.id.el_chinese_translated, R.id.el_chinese_rewrite, R.id.el_dutch_original,
|
||||
R.id.el_dutch_translated, R.id.el_dutch_rewrite, R.id.el_french_original, R.id.el_french_translated,
|
||||
R.id.el_french_rewrite, R.id.el_german_original, R.id.el_german_translated, R.id.el_german_rewrite,
|
||||
R.id.el_hungarian_original, R.id.el_hungarian_translated, R.id.el_hungarian_rewrite,
|
||||
R.id.el_italian_original, R.id.el_italian_translated, R.id.el_italian_rewrite, R.id.el_korean_original,
|
||||
R.id.el_korean_translated, R.id.el_korean_rewrite, R.id.el_polish_original, R.id.el_polish_translated,
|
||||
R.id.el_polish_rewrite, R.id.el_portuguese_original, R.id.el_portuguese_translated,
|
||||
R.id.el_portuguese_rewrite, R.id.el_russian_original, R.id.el_russian_translated,
|
||||
R.id.el_russian_rewrite, R.id.el_spanish_original, R.id.el_spanish_translated, R.id.el_spanish_rewrite,
|
||||
R.id.el_thai_original, R.id.el_thai_translated, R.id.el_thai_rewrite, R.id.el_vietnamese_original,
|
||||
R.id.el_vietnamese_translated, R.id.el_vietnamese_rewrite, R.id.el_other_original,
|
||||
R.id.el_other_translated, R.id.el_other_rewrite, };
|
||||
|
||||
private static final String[] EXCULDE_LANGUAGE_ID = { "1024", "2048", "1", "1025", "2049", "10", "1034",
|
||||
"2058", "20", "1044", "2068", "30", "1054", "2078", "40", "1064", "2088", "50", "1074", "2098", "60",
|
||||
"1084", "2108", "70", "1094", "2118", "80", "1104", "2128", "90", "1114", "2138", "100", "1124",
|
||||
"2148", "110", "1134", "2158", "120", "1144", "2168", "130", "1154", "2178", "255", "1279", "2303" };
|
||||
|
||||
private static final String KEY_LIST_DEFAULT_CATEGORY = "list_default_category";
|
||||
private static final String KEY_EXCULDE_TAG_GROUP = "exculde_tag_group";
|
||||
private static final String KEY_EXCULDE_LANGUAGE = "exculde_language";
|
||||
private static final String KEY_CLEAR_SUGGESTIONS = "clear_suggestions";
|
||||
private static final String KEY_PREVIEW_MODE = "preview_mode";
|
||||
private static final String KEY_DEFAULT_FAVORITE = "default_favorite";
|
||||
|
||||
private Preference mListDefaultCategory;
|
||||
private Preference mExculdeTagGroup;
|
||||
private Preference mExculdeLanguage;
|
||||
private Preference mClearSuggestions;
|
||||
private ListPreference mPreviewMode;
|
||||
private ListPreference mDefaultFavorite;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.eh_settings);
|
||||
|
||||
mListDefaultCategory = findPreference(KEY_LIST_DEFAULT_CATEGORY);
|
||||
mListDefaultCategory.setOnPreferenceClickListener(this);
|
||||
mExculdeTagGroup = findPreference(KEY_EXCULDE_TAG_GROUP);
|
||||
mExculdeTagGroup.setOnPreferenceClickListener(this);
|
||||
mExculdeLanguage = findPreference(KEY_EXCULDE_LANGUAGE);
|
||||
mExculdeLanguage.setOnPreferenceClickListener(this);
|
||||
mClearSuggestions = findPreference(KEY_CLEAR_SUGGESTIONS);
|
||||
mClearSuggestions.setOnPreferenceClickListener(this);
|
||||
mPreviewMode = (ListPreference) findPreference(KEY_PREVIEW_MODE);
|
||||
mPreviewMode.setOnPreferenceChangeListener(this);
|
||||
mDefaultFavorite = (ListPreference) findPreference(KEY_DEFAULT_FAVORITE);
|
||||
|
||||
int i = 0;
|
||||
String[] entrise = new String[Favorite.FAVORITE_TITLES.length + 1];
|
||||
entrise[i++] = getString(R.string.none);
|
||||
for (String str : Favorite.FAVORITE_TITLES)
|
||||
entrise[i++] = str;
|
||||
mDefaultFavorite.setEntries(entrise);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_PREVIEW_MODE.equals(key)) {
|
||||
String newPreviewMode = (String) newValue;
|
||||
EhInfo.getInstance(getActivity()).setPreviewMode(newPreviewMode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_LIST_DEFAULT_CATEGORY.equals(key)) {
|
||||
int defaultCat = Config.getDefaultCat();
|
||||
final CategoryTable ct = new CategoryTable(getActivity());
|
||||
ct.setCategory(defaultCat);
|
||||
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.list_default_category_title)
|
||||
.setView(ct, true).setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
int defaultCat = ct.getCategory();
|
||||
Config.setDefaultCat(defaultCat);
|
||||
EhInfo.getInstance(getActivity()).setDefaultCat(defaultCat);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
|
||||
} else if (KEY_EXCULDE_TAG_GROUP.equals(key)) {
|
||||
final TableLayout tl = (TableLayout) ViewUtils.inflateDialogView(R.layout.exculde_tag_group, false);
|
||||
setExculdeTagGroup(tl, Config.getExculdeTagGroup());
|
||||
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.exculde_tag_group_title).setView(tl, true)
|
||||
.setPositiveButton(android.R.string.ok).setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
int newValue = getExculdeTagGroup(tl);
|
||||
Config.setExculdeTagGroup(newValue);
|
||||
EhInfo.getInstance(getActivity()).setExculdeTagGroup(newValue);
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
|
||||
} else if (KEY_EXCULDE_LANGUAGE.equals(key)) {
|
||||
final TableLayout tl = (TableLayout) ViewUtils.inflateDialogView(R.layout.exculde_language, false);
|
||||
setExculdeLanguage(tl, Config.getExculdeLanguage());
|
||||
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.exculde_language_title).setView(tl, true)
|
||||
.setPositiveButton(android.R.string.ok).setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
String newValue = getExculdeLanguage(tl);
|
||||
Config.setExculdeLanguage(newValue);
|
||||
EhInfo.getInstance(getActivity()).setExculdeLanguage(newValue);
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
|
||||
} else if (KEY_CLEAR_SUGGESTIONS.equals(key)) {
|
||||
SearchRecentSuggestions suggestions = SuggestionHelper.getInstance(getActivity(),
|
||||
SimpleSuggestionProvider.AUTHORITY, SimpleSuggestionProvider.MODE);
|
||||
suggestions.clearHistory();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void setExculdeTagGroup(TableLayout tl, int value) {
|
||||
for (int i = 0; i < EXCULDE_TAG_GROUP_RESID.length; i++) {
|
||||
CheckBox cb = (CheckBox) tl.findViewById(EXCULDE_TAG_GROUP_RESID[i]);
|
||||
cb.setChecked(Utils.int2boolean(value & EXCULDE_TAG_GROUP_ID[i]));
|
||||
}
|
||||
}
|
||||
|
||||
private static int getExculdeTagGroup(TableLayout tl) {
|
||||
int newValue = 0;
|
||||
for (int i = 0; i < EXCULDE_TAG_GROUP_RESID.length; i++) {
|
||||
CheckBox cb = (CheckBox) tl.findViewById(EXCULDE_TAG_GROUP_RESID[i]);
|
||||
if (cb.isChecked())
|
||||
newValue |= EXCULDE_TAG_GROUP_ID[i];
|
||||
}
|
||||
return newValue;
|
||||
}
|
||||
|
||||
private static int getLanguage(String id) {
|
||||
for (int i = 0; i < EXCULDE_LANGUAGE_ID.length; i++) {
|
||||
if (EXCULDE_LANGUAGE_ID[i].equals(id))
|
||||
return EXCULDE_LANGUAGE_RESID[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void setExculdeLanguage(TableLayout tl, String value) {
|
||||
String[] items = value.split("x");
|
||||
for (String item : items) {
|
||||
int resId = getLanguage(item);
|
||||
if (resId != 0)
|
||||
((CheckBox) tl.findViewById(resId)).setChecked(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getExculdeLanguage(TableLayout tl) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean isFirst = true;
|
||||
for (int i = 0; i < EXCULDE_LANGUAGE_RESID.length; i++) {
|
||||
if (((CheckBox) tl.findViewById(EXCULDE_LANGUAGE_RESID[i])).isChecked()) {
|
||||
if (isFirst)
|
||||
isFirst = false;
|
||||
else
|
||||
sb.append('x');
|
||||
sb.append(EXCULDE_LANGUAGE_ID[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static class ReadFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_CUSTOM_CODEC = "custom_codec";
|
||||
private static final String KEY_CLEAN_REDUNDANCY = "clean_redundancy";
|
||||
|
||||
private CheckBoxPreference mCustomCodec;
|
||||
private Preference mCleanRedundancy;
|
||||
|
||||
private MaterialProgressDialog mMaterialProgressDialog;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.read_settings);
|
||||
|
||||
mCustomCodec = (CheckBoxPreference) findPreference(KEY_CUSTOM_CODEC);
|
||||
mCleanRedundancy = findPreference(KEY_CLEAN_REDUNDANCY);
|
||||
mCleanRedundancy.setOnPreferenceClickListener(this);
|
||||
|
||||
if (!Utils.SUPPORT_IMAGE) {
|
||||
mCustomCodec.setEnabled(false);
|
||||
mCustomCodec.setChecked(Config.getCustomCodec());
|
||||
mCustomCodec.setSummary(R.string.custom_codec_summary_not);
|
||||
} else {
|
||||
mCustomCodec.setChecked(Config.getCustomCodec());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isInDownloadList(List<DownloadInfo> diList, String filename) {
|
||||
for (DownloadInfo di : diList)
|
||||
if (filename.startsWith(String.valueOf(di.galleryInfo.gid)))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private class CleanResponder implements Runnable {
|
||||
|
||||
public static final int STATE_NONE = 0x0;
|
||||
public static final int STATE_START = 0x1;
|
||||
public static final int STATE_DOING = 0x2;
|
||||
public static final int STATE_DONE = 0x3;
|
||||
|
||||
private final int mState;
|
||||
private final int mMax;
|
||||
private final int mProgress;
|
||||
|
||||
public CleanResponder(int state, int max, int progress) {
|
||||
mState = state;
|
||||
mMax = max;
|
||||
mProgress = progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
switch (mState) {
|
||||
case STATE_NONE:
|
||||
MaterialToast.showToast(R.string.no_redundancy);
|
||||
break;
|
||||
case STATE_START:
|
||||
if (!getActivity().isFinishing()) {
|
||||
mMaterialProgressDialog = MaterialProgressDialog.create(getActivity(), getActivity().getString(R.string.clean_redundancy_title), false);
|
||||
mMaterialProgressDialog.show();
|
||||
}
|
||||
break;
|
||||
case STATE_DOING:
|
||||
if (mMaterialProgressDialog != null) {
|
||||
mMaterialProgressDialog.setMax(mMax);
|
||||
mMaterialProgressDialog.setProgress(mProgress);
|
||||
}
|
||||
break;
|
||||
case STATE_DONE:
|
||||
if (mMaterialProgressDialog != null) {
|
||||
mMaterialProgressDialog.dismiss();
|
||||
MaterialToast.showToast(String.format(getString(R.string.clean_redundancy), mMax));
|
||||
}
|
||||
mMaterialProgressDialog = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_CLEAN_REDUNDANCY.equals(key)) {
|
||||
|
||||
// Create a thread to do clean task
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
Data data = Data.getInstance();
|
||||
List<DownloadInfo> diList = data.getAllDownloads();
|
||||
File downloadDir = new File(Config.getDownloadPath());
|
||||
String[] files = downloadDir.list();
|
||||
Handler handler = AppHandler.getInstance();
|
||||
List<File> targetDirList = new ArrayList<File>();
|
||||
|
||||
if (files == null) {
|
||||
// Check files null
|
||||
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
|
||||
return;
|
||||
}
|
||||
|
||||
for (String filename : files) {
|
||||
// If in download list, just continue
|
||||
if (isInDownloadList(diList, filename))
|
||||
continue;
|
||||
File dir = new File(downloadDir, filename);
|
||||
// If there is no tag file, just continue
|
||||
if (!new File(dir, EhUtils.EH_DOWNLOAD_FILENAME).exists())
|
||||
continue;
|
||||
// Add to list
|
||||
targetDirList.add(dir);
|
||||
}
|
||||
|
||||
if (targetDirList.isEmpty()) {
|
||||
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
|
||||
return;
|
||||
} else {
|
||||
handler.post(new CleanResponder(CleanResponder.STATE_START, 0, 0));
|
||||
}
|
||||
// Do delete
|
||||
for (int i = 0; i < targetDirList.size(); i++) {
|
||||
File dir = targetDirList.get(i);
|
||||
Utils.deleteFile(dir);
|
||||
handler.post(new CleanResponder(CleanResponder.STATE_DOING, targetDirList.size(), i + 1));
|
||||
}
|
||||
// Close windows
|
||||
handler.post(new CleanResponder(CleanResponder.STATE_DONE, targetDirList.size(), targetDirList
|
||||
.size()));
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class DownloadFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_DOWNLOAD_PATH = "download_path";
|
||||
private static final String KEY_MEDIA_SCAN = "media_scan";
|
||||
|
||||
private DirSelectDialog mDirSelectDialog;
|
||||
|
||||
private Preference mDownloadPath;
|
||||
private CheckBoxPreference mMediaScan;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.download_settings);
|
||||
|
||||
mDownloadPath = findPreference(KEY_DOWNLOAD_PATH);
|
||||
mDownloadPath.setOnPreferenceClickListener(this);
|
||||
mMediaScan = (CheckBoxPreference) findPreference(KEY_MEDIA_SCAN);
|
||||
mMediaScan.setOnPreferenceChangeListener(this);
|
||||
|
||||
mDownloadPath.setSummary(Config.getDownloadPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_MEDIA_SCAN.equals(key)) {
|
||||
boolean value = (Boolean) newValue;
|
||||
File nomedia = new File(Config.getDownloadPath(), ".nomedia");
|
||||
if (value) {
|
||||
nomedia.delete();
|
||||
} else {
|
||||
try {
|
||||
nomedia.createNewFile();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("InflateParams")
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_DOWNLOAD_PATH.equals(key)) {
|
||||
mDirSelectDialog = DirSelectDialog.create(new MaterialAlertDialog.Builder(getActivity())
|
||||
.setTitle(R.string.download_path_title)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setActionButton(R.string._new)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog,
|
||||
int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.ACTION:
|
||||
final EditText et = new EditText(getActivity());
|
||||
et.setText(R.string.new_folder);
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT);
|
||||
int x = Ui.dp2pix(8);
|
||||
lp.leftMargin = x;
|
||||
lp.rightMargin = x;
|
||||
lp.topMargin = x;
|
||||
lp.bottomMargin = x;
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.new_folder)
|
||||
.setView(et, true, lp).setPositiveButton(R.string._new)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
File dir = new File(mDirSelectDialog.getCurrentPath(), et.getText()
|
||||
.toString());
|
||||
dir.mkdirs();
|
||||
mDirSelectDialog.refresh();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
return false;
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
if (!mDirSelectDialog.canWrite()) {
|
||||
MaterialToast.showToast(R.string.cur_dir_not_writable);
|
||||
return false;
|
||||
}
|
||||
String downloadPath = mDirSelectDialog.getCurrentPath();
|
||||
// Update .nomedia file
|
||||
// TODO Should I delete .nomedia in old
|
||||
// download dir ?
|
||||
if (!Config.getMediaScan()) {
|
||||
try {
|
||||
new File(Config.getDownloadPath(), ".nomedia").createNewFile();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
Config.setDownloadPath(downloadPath);
|
||||
mDownloadPath.setSummary(downloadPath);
|
||||
return true;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}) , Config.getDownloadPath());
|
||||
mDirSelectDialog.show();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class AdvancedFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_FIX_DIRNAME = "fix_dirname";
|
||||
|
||||
private Preference mFixDirname;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.advanced_settings);
|
||||
|
||||
mFixDirname = findPreference(KEY_FIX_DIRNAME);
|
||||
mFixDirname.setOnPreferenceClickListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_FIX_DIRNAME.equals(key)) {
|
||||
mFixDirname.setEnabled(false);
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
File downloadDir = new File(Config.getDownloadPath());
|
||||
List<File> targetDirList = new ArrayList<File>();
|
||||
|
||||
String[] list = downloadDir.list();
|
||||
if (list != null) {
|
||||
for (String str : list) {
|
||||
if (str.contains("-"))
|
||||
continue;
|
||||
File dir = new File(downloadDir, str);
|
||||
if (new File(dir, EhUtils.EH_DOWNLOAD_FILENAME).exists())
|
||||
targetDirList.add(dir);
|
||||
}
|
||||
}
|
||||
|
||||
if (targetDirList.size() == 0) {
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mFixDirname.setEnabled(true);
|
||||
MaterialToast.showToast(R.string.no_need_fixing);
|
||||
}
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
MaterialToast.showToast(R.string.start_fixing);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
int handleNum = 0;
|
||||
List<File> dirs = new ArrayList<File>();
|
||||
List<Integer> gids = new ArrayList<Integer>();
|
||||
List<String> tokens = new ArrayList<String>();
|
||||
// Do get title from api
|
||||
for (int i = 0; i < targetDirList.size(); i++) {
|
||||
File dir = targetDirList.get(i);
|
||||
File info = new File(dir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
InputStream is = null;
|
||||
int gid;
|
||||
String token;
|
||||
try {
|
||||
is = new BufferedInputStream(new FileInputStream(info), 128);
|
||||
// skip read index
|
||||
Utils.readAsciiLine(is);
|
||||
gid = Integer.parseInt(Utils.readAsciiLine(is));
|
||||
token = Utils.readAsciiLine(is);
|
||||
Utils.closeQuietly(is);
|
||||
dirs.add(dir);
|
||||
gids.add(gid);
|
||||
tokens.add(token);
|
||||
// Post api when to 25 or the end
|
||||
if (gids.size() == 25 || i == targetDirList.size() - 1) {
|
||||
ApiGalleryInfo[] agiArray = EhClient.getInstance().getApiGalleryInfo(
|
||||
Utils.toIntArray(gids), tokens.toArray(new String[tokens.size()]));
|
||||
// Change dirname
|
||||
if (agiArray != null) {
|
||||
for (int j = 0; j < agiArray.length; j++) {
|
||||
ApiGalleryInfo agi = agiArray[j];
|
||||
if (agi != null) {
|
||||
handleNum++;
|
||||
dirs.get(j).renameTo(EhUtils.generateGalleryDir(agi.gid, agi.title));
|
||||
}
|
||||
}
|
||||
}
|
||||
dirs.clear();
|
||||
gids.clear();
|
||||
tokens.clear();
|
||||
// Wait for CD, if not last
|
||||
if (i != targetDirList.size() - 1)
|
||||
Thread.sleep(3000);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
final int _handleNum = handleNum;
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mFixDirname.setEnabled(true);
|
||||
MaterialToast.showToast(String.format(getString(R.string.fixing_over), _handleNum));
|
||||
}
|
||||
});
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class AboutFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceClickListener {
|
||||
|
||||
private static final String KEY_AUTHOR = "author";
|
||||
private static final String KEY_TWITTER = "twitter";
|
||||
private static final String KEY_GOOGLE_PLUS = "google_plus";
|
||||
private static final String KEY_CHANGELOG = "changelog";
|
||||
private static final String KEY_THANKS = "thanks";
|
||||
private static final String KEY_WEBSITE = "website";
|
||||
private static final String KEY_SOURCE = "source";
|
||||
private static final String KEY_VERSION = "version";
|
||||
private static final String KEY_CHECK_UPDATE = "check_for_update";
|
||||
private static final String KEY_CLOUD_DRIVE = "cloud_drive";
|
||||
private static final String KEY_ABOUT_ANALYICS = "about_analyics";
|
||||
|
||||
private Preference mAuthor;
|
||||
private Preference mTwitter;
|
||||
private Preference mGooglePlus;
|
||||
private Preference mChangelog;
|
||||
private Preference mThanks;
|
||||
private Preference mWebsite;
|
||||
private Preference mSource;
|
||||
private Preference mVersion;
|
||||
private Preference mCheckUpdate;
|
||||
private Preference mCloudDrive;
|
||||
private Preference mAboutAnalyics;
|
||||
|
||||
private final long[] mHits = new long[3];
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.about_settings);
|
||||
|
||||
mAuthor = findPreference(KEY_AUTHOR);
|
||||
mAuthor.setOnPreferenceClickListener(this);
|
||||
mTwitter = findPreference(KEY_TWITTER);
|
||||
mTwitter.setOnPreferenceClickListener(this);
|
||||
mGooglePlus = findPreference(KEY_GOOGLE_PLUS);
|
||||
mGooglePlus.setOnPreferenceClickListener(this);
|
||||
mChangelog = findPreference(KEY_CHANGELOG);
|
||||
mChangelog.setOnPreferenceClickListener(this);
|
||||
mThanks = findPreference(KEY_THANKS);
|
||||
mThanks.setOnPreferenceClickListener(this);
|
||||
mWebsite = findPreference(KEY_WEBSITE);
|
||||
mWebsite.setOnPreferenceClickListener(this);
|
||||
mSource = findPreference(KEY_SOURCE);
|
||||
mSource.setOnPreferenceClickListener(this);
|
||||
mVersion = findPreference(KEY_VERSION);
|
||||
mVersion.setOnPreferenceClickListener(this);
|
||||
mCheckUpdate = findPreference(KEY_CHECK_UPDATE);
|
||||
mCheckUpdate.setOnPreferenceClickListener(this);
|
||||
mCloudDrive = findPreference(KEY_CLOUD_DRIVE);
|
||||
mCloudDrive.setOnPreferenceClickListener(this);
|
||||
mAboutAnalyics = findPreference(KEY_ABOUT_ANALYICS);
|
||||
mAboutAnalyics.setOnPreferenceClickListener(this);
|
||||
|
||||
try {
|
||||
Context c = getActivity().getApplicationContext();
|
||||
PackageInfo pi= c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
|
||||
mVersion.setSummary(pi.versionName);
|
||||
} catch (NameNotFoundException e) {}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_VERSION.equals(key)) {
|
||||
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);
|
||||
Activity a = getActivity();
|
||||
if (Secret.hasSecretImage(a)) {
|
||||
Intent intent = new Intent(a, SecretActivity.class);
|
||||
a.startActivity(intent);
|
||||
getActivity().overridePendingTransition(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
} else if (KEY_AUTHOR.equals(key)) {
|
||||
Intent i = new Intent(Intent.ACTION_SENDTO);
|
||||
i.setData(Uri.parse("mailto:ehviewersu@gmail.com"));
|
||||
i.putExtra(Intent.EXTRA_SUBJECT, "About EhViewer");
|
||||
startActivity(i);
|
||||
|
||||
} else if (KEY_TWITTER.equals(key)) {
|
||||
new MaterialAlertDialog.Builder(getActivity())
|
||||
.setTitle(R.string.twitter_title)
|
||||
.setItems(new CharSequence[] { "@EhViewer", "@jkjvinn" },
|
||||
new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
Uri uri = null;
|
||||
switch (which) {
|
||||
case 0:
|
||||
uri = Uri.parse("https://twitter.com/EhViewer");
|
||||
break;
|
||||
case 1:
|
||||
uri = Uri.parse("https://twitter.com/jkjvinn");
|
||||
break;
|
||||
}
|
||||
if (uri != null) {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).setNegativeButton(android.R.string.cancel).show();
|
||||
|
||||
} else if (KEY_GOOGLE_PLUS.equals(key)) {
|
||||
Uri uri = Uri.parse("https://plus.google.com/communities/103823982034655188459");
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
|
||||
} else if (KEY_CHANGELOG.equals(key)) {
|
||||
InputStream is = getActivity().getResources().openRawResource(R.raw.change_log);
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.changelog)
|
||||
.setMessage(Utils.InputStream2String(is, "utf-8")).setNegativeButton(android.R.string.cancel)
|
||||
.show();
|
||||
|
||||
} else if (KEY_THANKS.equals(key)) {
|
||||
InputStream is = getActivity().getResources().openRawResource(R.raw.thanks);
|
||||
final WebView webView = new WebView(getActivity());
|
||||
webView.loadData(Utils.InputStream2String(is, "utf-8"), "text/html; charset=UTF-8", null);
|
||||
new MaterialAlertDialog.Builder(getActivity())// .setTitle(R.string.thanks)
|
||||
.setView(webView, true).setNegativeButton(android.R.string.cancel).show();
|
||||
|
||||
} else if (KEY_WEBSITE.equals(key)) {
|
||||
Uri uri = Uri.parse("http://www.ehviewer.com");
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
|
||||
} else if (KEY_SOURCE.equals(key)) {
|
||||
Uri uri = Uri.parse("https://github.com/seven332/EhViewer");
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
|
||||
} else if (KEY_CHECK_UPDATE.equals(key)) {
|
||||
mCheckUpdate.setSummary(R.string.checking_update);
|
||||
mCheckUpdate.setEnabled(false);
|
||||
new UpdateHelper((AppContext) getActivity().getApplication()).SetOnCheckUpdateListener(
|
||||
new UpdateHelper.OnCheckUpdateListener() {
|
||||
@Override
|
||||
public void onSuccess(String version, long size, final String url, final String fileName,
|
||||
String info) {
|
||||
mCheckUpdate.setSummary(R.string.found_update);
|
||||
String sizeStr = Utils.sizeToString(size);
|
||||
AlertDialog dialog = DialogUtils.createUpdateDialog(getActivity(), version, sizeStr, info,
|
||||
new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
HttpHelper hh = new HttpHelper(getActivity());
|
||||
hh.downloadInThread(url, new File(Config.getDownloadPath()),
|
||||
fileName, false, null, new UpdateHelper.UpdateListener(
|
||||
getActivity(), fileName));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
if (!getActivity().isFinishing())
|
||||
dialog.show();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNoUpdate() {
|
||||
mCheckUpdate.setSummary(R.string.up_to_date);
|
||||
mCheckUpdate.setEnabled(true);
|
||||
UpdateHelper.setEnabled(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
mCheckUpdate.setSummary(eMsg);
|
||||
mCheckUpdate.setEnabled(true);
|
||||
UpdateHelper.setEnabled(true);
|
||||
}
|
||||
}).checkUpdate();
|
||||
|
||||
} else if (KEY_CLOUD_DRIVE.equals(key)) {
|
||||
Uri uri = Uri.parse("https://mega.co.nz/#F!xkMChYrI!Q85i3d7kNkhVkwvDePbahw");
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
|
||||
} else if (KEY_ABOUT_ANALYICS.equals(key)) {
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.about_analyics_title)
|
||||
.setMessageAutoLink(Linkify.WEB_URLS).setMessage(R.string.about_analyics_comment)
|
||||
.setNegativeButton(android.R.string.cancel).show();
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
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";
|
||||
|
||||
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
CookieManager.getInstance().removeAllCookie();
|
||||
WebView wv = new WebView(this);
|
||||
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,643 +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.util;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.os.Environment;
|
||||
import android.preference.PreferenceManager;
|
||||
|
||||
import com.hippo.ehviewer.data.ListUrls;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public final class Config {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = Config.class.getSimpleName();
|
||||
|
||||
public static final String EXTERANL_DIR_NAME = "EhViewer";
|
||||
public static File sExternalDir;
|
||||
|
||||
private static final String KEY_UPDATE_DATE = "update_date";
|
||||
|
||||
private static boolean mInit = false;
|
||||
|
||||
private static Context mContext;
|
||||
private static SharedPreferences mConfigPre;
|
||||
|
||||
/**
|
||||
* Init Config
|
||||
*
|
||||
* @param context Application context
|
||||
*/
|
||||
public static void init(Context context) {
|
||||
if (mInit)
|
||||
return;
|
||||
mInit = true;
|
||||
|
||||
mContext = context;
|
||||
mConfigPre = PreferenceManager.getDefaultSharedPreferences(mContext);
|
||||
|
||||
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
||||
sExternalDir = new File(Environment.getExternalStorageDirectory(), EXTERANL_DIR_NAME);
|
||||
Utils.ensureDir(sExternalDir, true);
|
||||
} else {
|
||||
sExternalDir = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is init
|
||||
* @return True if init
|
||||
*/
|
||||
public static boolean isInit() {
|
||||
return mInit;
|
||||
}
|
||||
|
||||
public static boolean getBoolean(String key, boolean defValue) {
|
||||
return mConfigPre.getBoolean(key, defValue);
|
||||
}
|
||||
|
||||
public static void setBoolean(String key, boolean value) {
|
||||
mConfigPre.edit().putBoolean(key, value).apply();
|
||||
}
|
||||
|
||||
public static int getInt(String key, int defValue) {
|
||||
return mConfigPre.getInt(key, defValue);
|
||||
}
|
||||
|
||||
public static void setInt(String key, int value) {
|
||||
mConfigPre.edit().putInt(key, value).apply();
|
||||
}
|
||||
|
||||
public static String getString(String key, String defValue) {
|
||||
return mConfigPre.getString(key, defValue);
|
||||
}
|
||||
|
||||
public static void setString(String key, String value) {
|
||||
mConfigPre.edit().putString(key, value).apply();
|
||||
}
|
||||
|
||||
public static int getIntFromStr(String key, int defValue) {
|
||||
return Utils.parseIntSafely(mConfigPre.getString(key, Integer.toString(defValue)), defValue);
|
||||
}
|
||||
|
||||
public static void setIntToStr(String key, int value) {
|
||||
mConfigPre.edit().putString(key, Integer.toString(value)).apply();
|
||||
}
|
||||
|
||||
public static float getFloat(String key, float defValue) {
|
||||
return mConfigPre.getFloat(key, defValue);
|
||||
}
|
||||
|
||||
public static void setFloat(String key, float value) {
|
||||
mConfigPre.edit().putFloat(key, value).apply();
|
||||
}
|
||||
|
||||
|
||||
/****** Display ******/
|
||||
|
||||
private static final String KEY_CUSTOM_THEME_COLOR = "custom_theme_color";
|
||||
private static final boolean DEFAULT_CUSTOM_THEME_COLOR = false;
|
||||
|
||||
private static final String KEY_THEME_COLOR = "theme_color";
|
||||
private static final int DEFAULT_THEME_COLOR = Ui.THEME_COLOR;
|
||||
|
||||
private static final String KEY_SCREEN_ORIENTATION = "screen_orientation";
|
||||
private static final int DEFAULT_SCREEN_ORIENTATION = 0;
|
||||
|
||||
private static final String KEY_LIST_MODE = "list_mode";
|
||||
private static final int DEFAULT_LIST_MODE = 0;
|
||||
|
||||
private static final String KEY_LIST_THUMB_COLUMNS_PORTRAIT = "list_thumb_columns_portrait";
|
||||
private static final int DEFAULT_LIST_THUMB_COLUMNS_PORTRAIT = 3;
|
||||
|
||||
private static final String KEY_LIST_THUMB_COLUMNS_LANDSCAPE = "list_thumb_columns_landscape";
|
||||
private static final int DEFAULT_LIST_THUMB_COLUMNS_LANDSCAPE = 5;
|
||||
|
||||
private static final String KEY_PREVIEW_COLUMNS_PORTRAIT = "preview_columns_portrait";
|
||||
private static final int DEFAULT_PREVIEW_COLUMNS_PORTRAIT = 3;
|
||||
|
||||
private static final String KEY_PREVIEW_COLUMNS_LANDSCAPE = "preview_columns_landscape";
|
||||
private static final int DEFAULT_PREVIEW_COLUMNS_LANDSCAPE = 5;
|
||||
|
||||
private static final String KEY_SHOW_POPULAR_UPDATE_TIME = "show_popular_update_time";
|
||||
private static final boolean DEFAULT_SHOW_POPULAR_UPDATE_TIME = false;
|
||||
|
||||
public static boolean getCustomThemeColor() {
|
||||
return getBoolean(KEY_CUSTOM_THEME_COLOR, DEFAULT_CUSTOM_THEME_COLOR);
|
||||
}
|
||||
|
||||
public static int getThemeColor() {
|
||||
return getInt(KEY_THEME_COLOR, DEFAULT_THEME_COLOR);
|
||||
}
|
||||
|
||||
public static void setThemeColor(int color) {
|
||||
setInt(KEY_THEME_COLOR, color);
|
||||
}
|
||||
|
||||
public static int getScreenOriMode() {
|
||||
return screenOriPre2Value(getIntFromStr(KEY_SCREEN_ORIENTATION, DEFAULT_SCREEN_ORIENTATION));
|
||||
}
|
||||
|
||||
public static int screenOriPre2Value(int screenOriModePre) {
|
||||
switch (screenOriModePre) {
|
||||
case 0:
|
||||
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
|
||||
case 1:
|
||||
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
|
||||
case 2:
|
||||
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
|
||||
default:
|
||||
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
|
||||
}
|
||||
}
|
||||
|
||||
public static int getListMode() {
|
||||
return getIntFromStr(KEY_LIST_MODE, DEFAULT_LIST_MODE);
|
||||
}
|
||||
|
||||
public static void setListMode(int listMode) {
|
||||
setIntToStr(KEY_LIST_MODE, listMode);
|
||||
}
|
||||
|
||||
public static int getListThumbColumnsPortrait() {
|
||||
return getInt(KEY_LIST_THUMB_COLUMNS_PORTRAIT, DEFAULT_LIST_THUMB_COLUMNS_PORTRAIT);
|
||||
}
|
||||
|
||||
public static int getListThumbColumnsLandscape() {
|
||||
return getInt(KEY_LIST_THUMB_COLUMNS_LANDSCAPE, DEFAULT_LIST_THUMB_COLUMNS_LANDSCAPE);
|
||||
}
|
||||
|
||||
public static int getPreviewColumnsPortrait() {
|
||||
return getInt(KEY_PREVIEW_COLUMNS_PORTRAIT, DEFAULT_PREVIEW_COLUMNS_PORTRAIT);
|
||||
}
|
||||
|
||||
public static int getPreviewColumnsLandscape() {
|
||||
return getInt(KEY_PREVIEW_COLUMNS_LANDSCAPE, DEFAULT_PREVIEW_COLUMNS_LANDSCAPE);
|
||||
}
|
||||
|
||||
public static boolean getShowPopularUpdateTime() {
|
||||
return getBoolean(KEY_SHOW_POPULAR_UPDATE_TIME, DEFAULT_SHOW_POPULAR_UPDATE_TIME);
|
||||
}
|
||||
|
||||
|
||||
/****** Eh Config ******/
|
||||
|
||||
private static final String KEY_DEFAULT_CAT = "default_cat";
|
||||
private static final int DEFAULT_DEFAULT_CAT = ListUrls.ALL_CATEGORT;
|
||||
|
||||
// m for normal, l for large
|
||||
public static final String KEY_PREVIEW_MODE = "preview_mode";
|
||||
public static final String PREVIEW_MODE_NORMAL = "m";
|
||||
public static final String PREVIEW_MODE_LARGE = "l";
|
||||
private static final String DEFAULT_PREVIEW_MODE = PREVIEW_MODE_LARGE;
|
||||
|
||||
/**
|
||||
* reclass 0x1
|
||||
* language 0x2
|
||||
* parody 0x4
|
||||
* character 0x8
|
||||
* group 0x10
|
||||
* artist 0x20
|
||||
* male 0x40
|
||||
* female 0x80
|
||||
*/
|
||||
private static final String KEY_EXCLUDE_TAG_GROUP = "exculde_tag_group";
|
||||
private static final int DEFAULT_EXCLUDE_TAG_GROUP = 0;
|
||||
|
||||
/**
|
||||
* Original Translated Rewrite All
|
||||
* Japanese 1024 2048
|
||||
* English 1 1025 2049
|
||||
* Chinese 10 1034 2058
|
||||
* Dutch 20 1044 2068
|
||||
* French 30 1054 2078
|
||||
* German 40 1064 2088
|
||||
* Hungarian 50 1074 2098
|
||||
* Italian 60 1084 2108
|
||||
* Korean 70 1094 2118
|
||||
* Polish 80 1104 2128
|
||||
* Portuguese 90 1114 2138
|
||||
* Russian 100 1124 2148
|
||||
* Spanish 110 1134 2158
|
||||
* Thai 120 1144 2168
|
||||
* Vietnamese 130 1154 2178
|
||||
* Other 255 1279 2303
|
||||
*/
|
||||
private static final String KEY_EXCLUDE_LANGUAGE = "exculde_language";
|
||||
private static final String DEFAULT_EXCLUDE_LANGUAGE = "";
|
||||
|
||||
private static final String KEY_DEFAULT_FAVORITE = "default_favorite";
|
||||
private static final int DEFAULT_DEFAULT_FAVORITE = -2;
|
||||
|
||||
private static final String KEY_MAX_HISTORY_COUNT = "max_history_count";
|
||||
private static final int DEFAULT_MAX_HISTORY_COUNT = 100;
|
||||
|
||||
public static int getDefaultCat() {
|
||||
return getInt(KEY_DEFAULT_CAT, DEFAULT_DEFAULT_CAT);
|
||||
}
|
||||
|
||||
public static void setDefaultCat(int defaultCat) {
|
||||
setInt(KEY_DEFAULT_CAT, defaultCat);
|
||||
}
|
||||
|
||||
public static String getPreviewMode() {
|
||||
return getString(KEY_PREVIEW_MODE, DEFAULT_PREVIEW_MODE);
|
||||
}
|
||||
|
||||
public static int getExculdeTagGroup() {
|
||||
return getInt(KEY_EXCLUDE_TAG_GROUP, DEFAULT_EXCLUDE_TAG_GROUP);
|
||||
}
|
||||
|
||||
public static void setExculdeTagGroup(int exculdeTagGroup) {
|
||||
setInt(KEY_EXCLUDE_TAG_GROUP, exculdeTagGroup);
|
||||
}
|
||||
|
||||
public static String getExculdeLanguage() {
|
||||
return getString(KEY_EXCLUDE_LANGUAGE, DEFAULT_EXCLUDE_LANGUAGE);
|
||||
}
|
||||
|
||||
public static void setExculdeLanguage(String exculdeLanguage) {
|
||||
setString(KEY_EXCLUDE_LANGUAGE, exculdeLanguage);
|
||||
}
|
||||
|
||||
public static int getDefaultFavorite() {
|
||||
return getIntFromStr(KEY_DEFAULT_FAVORITE, DEFAULT_DEFAULT_FAVORITE);
|
||||
}
|
||||
|
||||
public static void setDefaultFavorite(int defaultFavorite) {
|
||||
setIntToStr(KEY_DEFAULT_FAVORITE, defaultFavorite);
|
||||
}
|
||||
|
||||
public static int getMaxHistoryCount() {
|
||||
return getIntFromStr(KEY_MAX_HISTORY_COUNT, DEFAULT_MAX_HISTORY_COUNT);
|
||||
}
|
||||
|
||||
|
||||
/****** Read ******/
|
||||
|
||||
private static final String KEY_READING_DIRECTION = "reading_direction";
|
||||
private static final int DEFAULT_READING_DIRECTION = 0;
|
||||
|
||||
private static final String KEY_PAGE_SCALING = "page_scaling";
|
||||
private static final int DEFAULT_PAGE_SCALING = 3;
|
||||
|
||||
private static final String KEY_START_POSITION = "start_position";
|
||||
private static final int DEFAULT_START_POSITION = 1;
|
||||
|
||||
private static final String KEY_GALLERY_SHOW_CLOCK = "gallery_show_clock";
|
||||
private static final boolean DEFAULT_GALLERY_SHOW_CLOCK = true;
|
||||
|
||||
private static final String KEY_KEEP_SCREEN_ON = "keep_screen_on";
|
||||
private static final boolean DEFAULT_KEEP_SCREEN_ON = false;
|
||||
|
||||
private static final String KEY_GALLERY_SHOW_BATTERY = "gallery_show_battery";
|
||||
private static final boolean DEFAULT_GALLERY_SHOW_BATTERY = true;
|
||||
|
||||
private static final String KEY_CUSTOM_LIGHTNESS = "custom_lightness";
|
||||
private static final boolean DEFAULT_CUSTOM_LIGHTNESS = false;
|
||||
|
||||
private static final String KEY_CUSTOM_LIGHTNESS_VALUE = "custom_lightness_value";
|
||||
private static final int DEFAULT_CUSTOM_LIGHTNESS_VALUE = 120;
|
||||
|
||||
private static final String KEY_CUSTOM_CODEC = "custom_codec";
|
||||
|
||||
private static final String KEY_DECODE_FORMAT = "decode_format";
|
||||
private static final int DEFAULT_DECODE_FORMAT = 0;
|
||||
|
||||
public static int getReadingDirection() {
|
||||
return getIntFromStr(KEY_READING_DIRECTION, DEFAULT_READING_DIRECTION);
|
||||
}
|
||||
|
||||
public static void setReadingDirection(int value) {
|
||||
setIntToStr(KEY_READING_DIRECTION, value);
|
||||
}
|
||||
|
||||
public static int getPageScaling() {
|
||||
return getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING);
|
||||
}
|
||||
|
||||
public static void setPageScaling(int value) {
|
||||
setIntToStr(KEY_PAGE_SCALING, value);
|
||||
}
|
||||
|
||||
public static int getStartPosition() {
|
||||
return getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION);
|
||||
}
|
||||
|
||||
public static void setStartPosition(int value) {
|
||||
setIntToStr(KEY_START_POSITION, value);
|
||||
}
|
||||
|
||||
public static boolean getKeepSreenOn() {
|
||||
return getBoolean(KEY_KEEP_SCREEN_ON, DEFAULT_KEEP_SCREEN_ON);
|
||||
}
|
||||
|
||||
public static void setKeepSreenOn(boolean value) {
|
||||
setBoolean(KEY_KEEP_SCREEN_ON, value);
|
||||
}
|
||||
|
||||
public static boolean getShowClock() {
|
||||
return getBoolean(KEY_GALLERY_SHOW_CLOCK, DEFAULT_GALLERY_SHOW_CLOCK);
|
||||
}
|
||||
|
||||
public static void setShowClock(boolean value) {
|
||||
setBoolean(KEY_GALLERY_SHOW_CLOCK, value);
|
||||
}
|
||||
|
||||
public static boolean getShowBattery() {
|
||||
return getBoolean(KEY_GALLERY_SHOW_BATTERY, DEFAULT_GALLERY_SHOW_BATTERY);
|
||||
}
|
||||
|
||||
public static void setShowBattery(boolean value) {
|
||||
setBoolean(KEY_GALLERY_SHOW_BATTERY, value);
|
||||
}
|
||||
|
||||
public static boolean getCustomLightness() {
|
||||
return getBoolean(KEY_CUSTOM_LIGHTNESS, DEFAULT_CUSTOM_LIGHTNESS);
|
||||
}
|
||||
|
||||
public static void setCustomLightness(boolean value) {
|
||||
setBoolean(KEY_CUSTOM_LIGHTNESS, value);
|
||||
}
|
||||
|
||||
public static int getCustomLightnessValue() {
|
||||
return getIntFromStr(KEY_CUSTOM_LIGHTNESS_VALUE, DEFAULT_CUSTOM_LIGHTNESS_VALUE);
|
||||
}
|
||||
|
||||
public static void setCustomLightnessValue(int value) {
|
||||
setIntToStr(KEY_CUSTOM_LIGHTNESS_VALUE, value);
|
||||
}
|
||||
|
||||
public static boolean getCustomCodec() {
|
||||
return getBoolean(KEY_CUSTOM_CODEC, Utils.SUPPORT_IMAGE);
|
||||
}
|
||||
|
||||
public static void setCustomCodec(boolean value) {
|
||||
setBoolean(KEY_CUSTOM_CODEC, value);
|
||||
}
|
||||
|
||||
public static int getDecodeFormat() {
|
||||
return getIntFromStr(KEY_DECODE_FORMAT, DEFAULT_DECODE_FORMAT);
|
||||
}
|
||||
|
||||
public static int getDecodeFormatIndex() {
|
||||
int index = getIntFromStr(KEY_DECODE_FORMAT, DEFAULT_DECODE_FORMAT);
|
||||
switch (index) {
|
||||
case 6409:
|
||||
index = 1;
|
||||
break;
|
||||
case 6410:
|
||||
index = 2;
|
||||
break;
|
||||
case 6407:
|
||||
index = 3;
|
||||
break;
|
||||
case 6408:
|
||||
index = 4;
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
index = 0;
|
||||
break;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public static void setDecodeFormatFromIndex(int index) {
|
||||
switch (index) {
|
||||
case 1:
|
||||
index = 6409;
|
||||
break;
|
||||
case 2:
|
||||
index = 6410;
|
||||
break;
|
||||
case 3:
|
||||
index = 6407;
|
||||
break;
|
||||
case 4:
|
||||
index = 6408;
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
index = 0;
|
||||
break;
|
||||
}
|
||||
setIntToStr(KEY_DECODE_FORMAT, index);
|
||||
}
|
||||
|
||||
|
||||
/****** Download ******/
|
||||
|
||||
private static final String KEY_DOWNLOAD_PATH = "download_path";
|
||||
private static final String DEFAULT_DOWNLOAD_PATH =
|
||||
Environment.getExternalStorageDirectory() + "/EhViewer/download/";
|
||||
|
||||
private static final String KEY_MEDIA_SCAN = "media_scan";
|
||||
private static final boolean DEFAULT_MEDIA_SCAN = false;
|
||||
|
||||
private static final String KEY_DOWNLOAD_THREAD = "download_thread";
|
||||
private static final int DEFAULT_DOWNLOAD_THREAD = 3;
|
||||
|
||||
private static final String KEY_DOWNLOAD_ORIGIN_IMAGE = "download_origin_image";
|
||||
private static final boolean DEFAULT_DOWNLOAD_ORIGIN_IMAGE = false;
|
||||
|
||||
private static final String KEY_KEEP_DOWNLOAD_SERVICE = "keep_download_service";
|
||||
private static final boolean DEFAULT_KEEP_DOWNLOAD_SERVICE = true;
|
||||
|
||||
public static String getDownloadPath() {
|
||||
return getString(KEY_DOWNLOAD_PATH, DEFAULT_DOWNLOAD_PATH);
|
||||
}
|
||||
|
||||
public static void setDownloadPath(String path) {
|
||||
setString(KEY_DOWNLOAD_PATH, path);
|
||||
}
|
||||
|
||||
public static boolean getMediaScan() {
|
||||
return getBoolean(KEY_MEDIA_SCAN, DEFAULT_MEDIA_SCAN);
|
||||
}
|
||||
|
||||
public static int getDownloadThread() {
|
||||
return getIntFromStr(KEY_DOWNLOAD_THREAD, DEFAULT_DOWNLOAD_THREAD);
|
||||
}
|
||||
|
||||
public static boolean getDownloadOriginImage() {
|
||||
return getBoolean(KEY_DOWNLOAD_ORIGIN_IMAGE, DEFAULT_DOWNLOAD_ORIGIN_IMAGE);
|
||||
}
|
||||
|
||||
public static boolean getKeepDownloadService() {
|
||||
return getBoolean(KEY_KEEP_DOWNLOAD_SERVICE, DEFAULT_KEEP_DOWNLOAD_SERVICE);
|
||||
}
|
||||
|
||||
|
||||
/****** Advanced ******/
|
||||
|
||||
private static final String KEY_HTTP_RETRY = "http_retry";
|
||||
private static final int DEFAULT_HTTP_RETRY = 3;
|
||||
|
||||
private static final String KEY_HTTP_CONNECT_TIMEOUT = "http_connect_timeout";
|
||||
private static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 5000;
|
||||
|
||||
private static final String KEY_HTTP_READ_TIMEOUT = "http_read_timeout";
|
||||
private static final int DEFAULT_HTTP_READ_TIMEOUT = 5000;
|
||||
|
||||
private static final String KEY_EH_MIN_INTERVAL = "eh_min_interval";
|
||||
private static final int DEFAULT_EH_MIN_INTERVAL = 0;
|
||||
|
||||
public static int getHttpRetry() {
|
||||
return getIntFromStr(KEY_HTTP_RETRY, DEFAULT_HTTP_RETRY);
|
||||
}
|
||||
|
||||
public static int getHttpConnectTimeout() {
|
||||
return getIntFromStr(KEY_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_CONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
public static int getHttpReadTimeout() {
|
||||
return getIntFromStr(KEY_HTTP_READ_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT);
|
||||
}
|
||||
|
||||
public static int getEhMinInterval() {
|
||||
return getIntFromStr(KEY_EH_MIN_INTERVAL, DEFAULT_EH_MIN_INTERVAL);
|
||||
}
|
||||
|
||||
|
||||
/****** About ******/
|
||||
|
||||
private static final String KEY_AUTO_CHECK_FOR_UPDATE = "auto_check_for_update";
|
||||
private static final boolean DEFAULT_AUTO_CHECK_FOR_UPDATE = true;
|
||||
|
||||
private static final String KEY_UPDATE_SERVER = "update_server";
|
||||
private static final int DEFAULT_UPDATE_SERVER = 1;
|
||||
|
||||
private static final String KEY_ALLOW_ANALYTICS = "allow_analyics";
|
||||
private static final boolean DEFAULT_ALLOW_ANALYTICS = false;
|
||||
|
||||
public static boolean isAutoCheckForUpdate() {
|
||||
return getBoolean(KEY_AUTO_CHECK_FOR_UPDATE, DEFAULT_AUTO_CHECK_FOR_UPDATE);
|
||||
}
|
||||
|
||||
public static void setAutoCheckForUpdate(boolean autoCheckForUpdate) {
|
||||
setBoolean(KEY_AUTO_CHECK_FOR_UPDATE, autoCheckForUpdate);
|
||||
}
|
||||
|
||||
public static int getUpdateDate() {
|
||||
return getInt(KEY_UPDATE_DATE, 0);
|
||||
}
|
||||
|
||||
public static void setUpdateDate() {
|
||||
setUpdateDate(Utils.getDate());
|
||||
}
|
||||
|
||||
public static void setUpdateDate(int date) {
|
||||
setInt(KEY_UPDATE_DATE, date);
|
||||
}
|
||||
|
||||
public static String getUpdateServer() {
|
||||
int value = getIntFromStr(KEY_UPDATE_SERVER, DEFAULT_UPDATE_SERVER);
|
||||
switch (value) {
|
||||
case 1:
|
||||
return "qiniu";
|
||||
case 0:
|
||||
default:
|
||||
return "google";
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean getAllowAnalyics() {
|
||||
return getBoolean(KEY_ALLOW_ANALYTICS, DEFAULT_ALLOW_ANALYTICS);
|
||||
}
|
||||
|
||||
public static void setAllowAnalyics(boolean setAnalyics) {
|
||||
setBoolean(KEY_ALLOW_ANALYTICS, setAnalyics);
|
||||
}
|
||||
|
||||
|
||||
/****** Mode an API Mode ******/
|
||||
|
||||
private static final String KEY_MODE = "mode";
|
||||
private static final int DEFAULT_MODE = EhClient.MODE_G;
|
||||
|
||||
private static final String KEY_API_MODE = "api_mode";
|
||||
private static final int DEFAULT_API_MODE = EhClient.MODE_G;
|
||||
|
||||
private static final String KEY_LOFI_RESOLUTION = "lofi_resolution";
|
||||
private static final int DEFAULT_LOFI_RESOLUTION = 1;
|
||||
|
||||
public static int getMode() {
|
||||
return getInt(KEY_MODE, DEFAULT_MODE);
|
||||
}
|
||||
|
||||
public static void setMode(int mode) {
|
||||
setInt(KEY_MODE, mode);
|
||||
}
|
||||
|
||||
public static int getApiMode() {
|
||||
return getInt(KEY_API_MODE, DEFAULT_API_MODE);
|
||||
}
|
||||
|
||||
public static void setApiMode(int apiMode) {
|
||||
setInt(KEY_API_MODE, apiMode);
|
||||
}
|
||||
|
||||
public static int getLofiResolution() {
|
||||
return getInt(KEY_LOFI_RESOLUTION, DEFAULT_LOFI_RESOLUTION);
|
||||
}
|
||||
|
||||
public static void setLofiResolution(int lofiResolution) {
|
||||
setInt(KEY_LOFI_RESOLUTION, lofiResolution);
|
||||
}
|
||||
|
||||
|
||||
// Proxy urls
|
||||
private static final String PROXY_URLS_KEY = "proxy_urls";
|
||||
public static final String[] DEFAULT_PROXY_URLS = {
|
||||
"http://proxyy0000.appsp0t.com/proxy",
|
||||
"http://proxyy0001.appsp0t.com/proxy",
|
||||
"http://proxyy0002.appsp0t.com/proxy",
|
||||
"http://proxyy0003.appsp0t.com/proxy",
|
||||
"http://proxyy0004.appsp0t.com/proxy",
|
||||
"http://proxyy0005.appsp0t.com/proxy",
|
||||
"http://proxyy0006.appsp0t.com/proxy",
|
||||
"http://proxyy0007.appsp0t.com/proxy",
|
||||
"http://proxyy0008.appsp0t.com/proxy",
|
||||
"http://proxyy0009.appsp0t.com/proxy",
|
||||
"http://proxyy000a.appsp0t.com/proxy",
|
||||
"http://proxyy000b.appsp0t.com/proxy",
|
||||
"http://proxyy000c.appsp0t.com/proxy",
|
||||
"http://proxyy000d.appsp0t.com/proxy",
|
||||
"http://proxyy000e.appsp0t.com/proxy",
|
||||
"http://proxyy000f.appsp0t.com/proxy"
|
||||
};
|
||||
|
||||
public static String[] getProxyUrls() {
|
||||
Set<String> re = mConfigPre.getStringSet(PROXY_URLS_KEY, null);
|
||||
if (re != null && re.size() > 0)
|
||||
return re.toArray(new String[re.size()]);
|
||||
else
|
||||
return DEFAULT_PROXY_URLS;
|
||||
}
|
||||
|
||||
public static void setProxyUrls(String[] urls) {
|
||||
mConfigPre.edit().putStringSet(PROXY_URLS_KEY, new HashSet<String>(Arrays.asList(urls))).apply();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +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.util;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
|
||||
public class DialogUtils {
|
||||
|
||||
public static MaterialAlertDialog.Builder createUpdateDialog(Context context, String version, String size,
|
||||
String info, MaterialAlertDialog.OnClickListener l) {
|
||||
|
||||
return new MaterialAlertDialog.Builder(context).setTitle(R.string.update).setCancelable(false)
|
||||
.setMessage(String.format(context.getString(R.string.update_message), version, size, info))
|
||||
.setPositiveButton(android.R.string.ok).setNegativeButton(android.R.string.cancel).setButtonListener(l);
|
||||
}
|
||||
}
|
||||
@@ -1,124 +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.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import com.hippo.ehviewer.data.ListUrls;
|
||||
|
||||
public final class EhUtils {
|
||||
|
||||
public static final String EH_DOWNLOAD_FILENAME = ".ehviewer";
|
||||
|
||||
private static final int[] CATEGORY_VALUES = { ListUrls.MISC, ListUrls.DOUJINSHI, ListUrls.MANGA,
|
||||
ListUrls.ARTIST_CG, ListUrls.GAME_CG, ListUrls.IMAGE_SET, ListUrls.COSPLAY, ListUrls.ASIAN_PORN,
|
||||
ListUrls.NON_H, ListUrls.WESTERN, ListUrls.UNKNOWN };
|
||||
|
||||
// TODO How about "Private"
|
||||
private static final String[][] CATEGORY_STRINGS = { new String[] { "misc" }, new String[] { "doujinshi" },
|
||||
new String[] { "manga" }, new String[] { "artistcg", "Artist CG Sets" },
|
||||
new String[] { "gamecg", "Game CG Sets" }, new String[] { "imageset", "Image Sets" },
|
||||
new String[] { "cosplay" }, new String[] { "asianporn", "Asian Porn" }, new String[] { "non-h" },
|
||||
new String[] { "western" }, new String[] { "unknown" } };
|
||||
|
||||
public static int getCategory(String type) {
|
||||
int i;
|
||||
for (i = 0; i < CATEGORY_STRINGS.length - 1; i++) {
|
||||
for (String str : CATEGORY_STRINGS[i])
|
||||
if (str.equalsIgnoreCase(type))
|
||||
return CATEGORY_VALUES[i];
|
||||
}
|
||||
|
||||
return CATEGORY_VALUES[i];
|
||||
}
|
||||
|
||||
public static String getCategory(int type) {
|
||||
int i;
|
||||
for (i = 0; i < CATEGORY_VALUES.length - 1; i++) {
|
||||
if (CATEGORY_VALUES[i] == type)
|
||||
break;
|
||||
}
|
||||
return CATEGORY_STRINGS[i][0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get gallery for read and download Gid is constant, but title may be
|
||||
* changed
|
||||
*
|
||||
* @param gid
|
||||
* @param title
|
||||
* @return
|
||||
*/
|
||||
public static File getGalleryDir(int gid, String title) {
|
||||
|
||||
File downloadDir = new File(Config.getDownloadPath());
|
||||
File gDir = new File(downloadDir, Utils.standardizeFilename(Integer.toString(gid)));
|
||||
File defaultDir = generateGalleryDir(gid, title);
|
||||
|
||||
if (gDir.exists()) {
|
||||
if (gDir.renameTo(defaultDir))
|
||||
return defaultDir;
|
||||
else
|
||||
return gDir;
|
||||
} else {
|
||||
// TODO I need a better way or only call it in non-UI thread
|
||||
String[] fileList = downloadDir.list();
|
||||
if (fileList != null) {
|
||||
for (String str : fileList) {
|
||||
// For title changed
|
||||
if (str.startsWith(gid + "-") && (gDir = new File(downloadDir, str)) != null && gDir.isDirectory())
|
||||
return gDir;
|
||||
}
|
||||
}
|
||||
|
||||
return defaultDir;
|
||||
}
|
||||
}
|
||||
|
||||
public static File generateGalleryDir(int gid, String title) {
|
||||
return new File(Config.getDownloadPath(), Utils.standardizeFilename(gid + "-" + title));
|
||||
}
|
||||
|
||||
/**
|
||||
* Index start from 0
|
||||
*
|
||||
* @param index
|
||||
* @param extension
|
||||
* @return
|
||||
*/
|
||||
public static String getImageFilename(int index, String extension) {
|
||||
return String.format("%08d.%s", index + 1, extension);
|
||||
}
|
||||
|
||||
public static String[] POSSIBLE_IMAGE_EXTENSION_ARRAY = new String[] {
|
||||
"jpg", "jpeg", "png", "gif"
|
||||
};
|
||||
|
||||
public static String DEFAULT_IMAGE_EXTENSION = POSSIBLE_IMAGE_EXTENSION_ARRAY[0];
|
||||
|
||||
public static String[] getPossibleImageFilenames(int index) {
|
||||
String prefix = String.format("%08d.", index + 1);
|
||||
|
||||
int length = POSSIBLE_IMAGE_EXTENSION_ARRAY.length;
|
||||
String[] strs = new String[length];
|
||||
for (int i = 0; i < length; i++)
|
||||
strs[i] = prefix + POSSIBLE_IMAGE_EXTENSION_ARRAY[i];
|
||||
|
||||
return strs;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,156 +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.util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.os.Build;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
|
||||
@SuppressLint("InlinedApi")
|
||||
public final class FullScreenHelper implements View.OnSystemUiVisibilityChangeListener {
|
||||
|
||||
private static final String TAG = FullScreenHelper.class.getSimpleName();
|
||||
|
||||
private final int NOT_FULL_SCREEN_JELLY_BEAN =
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
|
||||
|
||||
private final int FULL_SCREEN_JELLY_BEAN =
|
||||
NOT_FULL_SCREEN_JELLY_BEAN |
|
||||
View.SYSTEM_UI_FLAG_LOW_PROFILE |
|
||||
View.SYSTEM_UI_FLAG_FULLSCREEN;
|
||||
|
||||
private final int FULL_SCREEN_FLAG_JELLY_BEAN =
|
||||
View.SYSTEM_UI_FLAG_LOW_PROFILE |
|
||||
View.SYSTEM_UI_FLAG_FULLSCREEN;
|
||||
|
||||
private final int NOT_FULL_SCREEN_KITKAT =
|
||||
NOT_FULL_SCREEN_JELLY_BEAN |
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
|
||||
|
||||
private final int FULL_SCREEN_KITKAT =
|
||||
NOT_FULL_SCREEN_KITKAT |
|
||||
View.SYSTEM_UI_FLAG_LOW_PROFILE |
|
||||
View.SYSTEM_UI_FLAG_FULLSCREEN |
|
||||
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
|
||||
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
|
||||
|
||||
private boolean mFullScreen;
|
||||
private final Activity mActivity;
|
||||
private final Window mWindow;
|
||||
private final View mDecorView;
|
||||
|
||||
private boolean mHasNavBar;
|
||||
|
||||
private OnFullScreenBrokenListener mListener;
|
||||
|
||||
private final int TEST_SDK = Build.VERSION.SDK_INT;
|
||||
|
||||
public interface OnFullScreenBrokenListener {
|
||||
/**
|
||||
* FullScreen state should be fullScreen or not,
|
||||
* but user or system broke it
|
||||
*
|
||||
* @param fullScreen support to be
|
||||
*/
|
||||
public void onFullScreenBroken(boolean fullScreen);
|
||||
}
|
||||
|
||||
public FullScreenHelper(Activity activity) {
|
||||
mFullScreen = false;
|
||||
mActivity = activity;
|
||||
mWindow = mActivity.getWindow();
|
||||
mDecorView = mWindow.getDecorView();
|
||||
mDecorView.setOnSystemUiVisibilityChangeListener(this);
|
||||
|
||||
String mainKey = Utils.getSystemProperties("qemu.hw.mainkeys");
|
||||
int resourceId = activity.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
|
||||
if (resourceId != 0) {
|
||||
mHasNavBar = activity.getResources().getBoolean(resourceId);
|
||||
// check override flag (see static block)
|
||||
if ("1".equals(mainKey)) {
|
||||
mHasNavBar = false;
|
||||
} else if ("0".equals(mainKey)) {
|
||||
mHasNavBar = true;
|
||||
}
|
||||
} else {
|
||||
mHasNavBar = !ViewConfiguration.get(activity).hasPermanentMenuKey();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean willHideNavBar() {
|
||||
if (TEST_SDK >= Build.VERSION_CODES.KITKAT && mHasNavBar)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSystemUiVisibilityChange(int visibility) {
|
||||
if (TEST_SDK >= Build.VERSION_CODES.JELLY_BEAN &&
|
||||
TEST_SDK < Build.VERSION_CODES.KITKAT) {
|
||||
if ((mFullScreen && visibility != FULL_SCREEN_FLAG_JELLY_BEAN) ||
|
||||
(!mFullScreen && visibility != 0)) {
|
||||
// User or system change visibility
|
||||
if (mListener != null)
|
||||
mListener.onFullScreenBroken(mFullScreen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setOnFullScreenBrokenListener(OnFullScreenBrokenListener l) {
|
||||
mListener = l;
|
||||
}
|
||||
|
||||
public boolean getFullScreen() {
|
||||
return mFullScreen;
|
||||
}
|
||||
|
||||
public void setFullScreen(boolean fullScreen) {
|
||||
mFullScreen = fullScreen;
|
||||
if (fullScreen) {
|
||||
if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
|
||||
// Empty
|
||||
} else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) {
|
||||
mWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
|
||||
WindowManager.LayoutParams.FLAG_FULLSCREEN);
|
||||
|
||||
} else if (TEST_SDK < Build.VERSION_CODES.KITKAT) {
|
||||
mDecorView.setSystemUiVisibility(FULL_SCREEN_JELLY_BEAN);
|
||||
|
||||
} else {
|
||||
mDecorView.setSystemUiVisibility(FULL_SCREEN_KITKAT);
|
||||
}
|
||||
} else {
|
||||
if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
|
||||
// Empty
|
||||
} else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) {
|
||||
mWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
|
||||
|
||||
} else if (TEST_SDK < Build.VERSION_CODES.KITKAT) {
|
||||
mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_JELLY_BEAN);
|
||||
|
||||
} else {
|
||||
mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_KITKAT);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,149 +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.util;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.hippo.ehviewer.BuildConfig;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
public final class Log {
|
||||
private static final String NULL = "null";
|
||||
private static final String LOG_FILENAME = "log.log";
|
||||
|
||||
private static final Object sLock = new Object();
|
||||
|
||||
private static File sLogFile;
|
||||
|
||||
public static void init(Context context) {
|
||||
if (Config.sExternalDir != null)
|
||||
sLogFile = new File(Config.sExternalDir, LOG_FILENAME);
|
||||
else
|
||||
sLogFile = new File(context.getFilesDir(), LOG_FILENAME);
|
||||
}
|
||||
|
||||
public static void f(final String msg) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized(sLock) {
|
||||
try {
|
||||
FileWriter fw = new FileWriter(sLogFile, true);
|
||||
fw.append(Utils.sDate.format(System.currentTimeMillis()))
|
||||
.append(": ").append(msg).append("\n");
|
||||
fw.flush();
|
||||
fw.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public static void f(final Throwable tr) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized(sLock) {
|
||||
try {
|
||||
FileWriter fw = new FileWriter(sLogFile, true);
|
||||
fw.append(Utils.sDate.format(System.currentTimeMillis()))
|
||||
.append(": ").append(Crash.getThrowableInfo(tr)).append("\n");
|
||||
fw.flush();
|
||||
fw.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public static int v(String tag, String msg) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.v(tag, msg == null ? NULL : msg);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int v(String tag, String msg, Throwable tr) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.v(tag, msg == null ? NULL : msg, tr);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int d(String tag, String msg) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.d(tag, msg == null ? NULL : msg);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int d(String tag, String msg, Throwable tr) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.d(tag, msg == null ? NULL : msg, tr);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int i(String tag, String msg) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.i(tag, msg == null ? NULL : msg);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int i(String tag, String msg, Throwable tr) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.i(tag, msg == null ? NULL : msg, tr);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int w(String tag, String msg) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.w(tag, msg == null ? NULL : msg);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int w(String tag, String msg, Throwable tr) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.w(tag, msg == null ? NULL : msg, tr);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int w(String tag, Throwable tr) {
|
||||
return android.util.Log.w(tag, tr);
|
||||
}
|
||||
|
||||
public static int e(String tag, String msg) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.e(tag, msg == null ? NULL : msg);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int e(String tag, String msg, Throwable tr) {
|
||||
if (BuildConfig.DEBUG)
|
||||
return android.util.Log.e(tag, msg == null ? NULL : msg, tr);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,89 +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.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
|
||||
public final class Secret {
|
||||
|
||||
private static final String DIR_NAME = "images";
|
||||
private static final String IMAGE_NAME = "sercet.jpg";
|
||||
private static final String SERCET_IMAGE_URL = "http://www.ehviewer.com/static/images/pandas.jpg";
|
||||
|
||||
private static volatile boolean sIsGetSecretImage = false;
|
||||
|
||||
public static void updateSecretImage(Context context) {
|
||||
if (sIsGetSecretImage)
|
||||
return;
|
||||
sIsGetSecretImage = true;
|
||||
|
||||
new UpdateSercetImageThread(context).start();
|
||||
}
|
||||
|
||||
public static boolean hasSecretImage(Context context) {
|
||||
if (sIsGetSecretImage)
|
||||
return false;
|
||||
|
||||
File dir = context.getExternalFilesDir(DIR_NAME);
|
||||
File image = new File(dir, IMAGE_NAME);
|
||||
BitmapFactory.Options opts = new BitmapFactory.Options();
|
||||
opts.inJustDecodeBounds = true;
|
||||
BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
|
||||
return opts.outWidth > 0 && opts.outHeight > 0;
|
||||
}
|
||||
|
||||
public static Bitmap getSecretImage(Context context) {
|
||||
if (sIsGetSecretImage)
|
||||
return null;
|
||||
|
||||
File dir = context.getExternalFilesDir(DIR_NAME);
|
||||
File image = new File(dir, IMAGE_NAME);
|
||||
return BitmapFactory.decodeFile(image.getAbsolutePath(), null);
|
||||
}
|
||||
|
||||
private static class UpdateSercetImageThread extends BgThread {
|
||||
|
||||
private final Context mContext;
|
||||
|
||||
public UpdateSercetImageThread(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// TODO check usable space
|
||||
File dir = mContext.getExternalFilesDir(DIR_NAME);
|
||||
File image = new File(dir, IMAGE_NAME);
|
||||
BitmapFactory.Options opts = new BitmapFactory.Options();
|
||||
opts.inJustDecodeBounds = true;
|
||||
BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
|
||||
if (opts.outWidth <= 0 || opts.outHeight <= 0) {
|
||||
// Get image error, try to get image from internet
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
hh.download(SERCET_IMAGE_URL, mContext.getExternalFilesDir(DIR_NAME),
|
||||
IMAGE_NAME, false, null, null);
|
||||
}
|
||||
sIsGetSecretImage = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,205 +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.util;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.view.ContextThemeWrapper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.View.MeasureSpec;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewParent;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
|
||||
public final class ViewUtils {
|
||||
|
||||
public static ContextThemeWrapper sContextThemeWrapper;
|
||||
public static ContextThemeWrapper sDarkContextThemeWrapper;
|
||||
private static LayoutInflater sDialogViewInflater;
|
||||
private static LayoutInflater sDarkDialogViewInflater;
|
||||
|
||||
public static final void initDialogViewInflater(Context context) {
|
||||
sContextThemeWrapper = new ContextThemeWrapper(context, R.style.AppTheme_Dialog);
|
||||
sDarkContextThemeWrapper = new ContextThemeWrapper(context, R.style.AppTheme_Dark_Dialog);
|
||||
sDialogViewInflater = LayoutInflater.from(sContextThemeWrapper);
|
||||
sDarkDialogViewInflater = LayoutInflater.from(sDarkContextThemeWrapper);
|
||||
}
|
||||
|
||||
public static final View inflateDialogView(int resId, boolean dark) {
|
||||
LayoutInflater inflater = dark ? sDarkDialogViewInflater : sDialogViewInflater;
|
||||
return inflater.inflate(resId, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get view center location in window
|
||||
*
|
||||
* @param view
|
||||
* @param location
|
||||
*/
|
||||
public static void getCenterInWindows(View view, int[] location) {
|
||||
getLocationInWindow(view, location);
|
||||
location[0] += view.getWidth() / 2;
|
||||
location[1] += view.getHeight() / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get view location in window
|
||||
*
|
||||
* @param view
|
||||
* @param location
|
||||
*/
|
||||
public static void getLocationInWindow(View view, int[] location) {
|
||||
if (location == null || location.length < 2) {
|
||||
throw new IllegalArgumentException(
|
||||
"location must be an array of two integers");
|
||||
}
|
||||
|
||||
float[] position = new float[2];
|
||||
|
||||
position[0] = view.getLeft();
|
||||
position[1] = view.getTop();
|
||||
|
||||
ViewParent viewParent = view.getParent();
|
||||
while (viewParent instanceof View) {
|
||||
view = (View) viewParent;
|
||||
if (view.getId() == android.R.id.content) {
|
||||
break;
|
||||
}
|
||||
|
||||
position[0] -= view.getScrollX();
|
||||
position[1] -= view.getScrollY();
|
||||
|
||||
position[0] += view.getLeft();
|
||||
position[1] += view.getTop();
|
||||
|
||||
viewParent = view.getParent();
|
||||
}
|
||||
|
||||
location[0] = (int) (position[0] + 0.5f);
|
||||
location[1] = (int) (position[1] + 0.5f);
|
||||
}
|
||||
|
||||
public static View getAncestor(View view, int id) {
|
||||
ViewParent viewParent = view.getParent();
|
||||
while (viewParent instanceof View) {
|
||||
view = (View) viewParent;
|
||||
if (view.getId() == id)
|
||||
return view;
|
||||
viewParent = view.getParent();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a bitmap showing a screenshot of the view passed in.
|
||||
*
|
||||
* @param v
|
||||
* @return
|
||||
*/
|
||||
public static Bitmap getBitmapFromView(View v) {
|
||||
int width = v.getWidth();
|
||||
int height = v.getHeight();
|
||||
if (width == 0 && height == 0) {
|
||||
width = v.getMeasuredWidth();
|
||||
height = v.getMeasuredHeight();
|
||||
}
|
||||
Bitmap bitmap = Bitmap.createBitmap(width, height,
|
||||
Bitmap.Config.ARGB_8888);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
// TODO I need to know why I need it, when ScrollView
|
||||
canvas.translate(-v.getScrollX(), -v.getScrollY());
|
||||
v.draw(canvas);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
public static boolean isClickAction(MotionEvent event) {
|
||||
// TODO bad idea to check click
|
||||
return event.getAction() == MotionEvent.ACTION_UP
|
||||
&& System.nanoTime() / 1000000 - event.getDownTime() < 200;
|
||||
}
|
||||
|
||||
public static void removeFromParent(View view) {
|
||||
ViewParent vp = view.getParent();
|
||||
if (vp instanceof ViewGroup)
|
||||
((ViewGroup) vp).removeView(view);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method that removes the support for HardwareAcceleration from a
|
||||
* {@link View}.<br/>
|
||||
* <br/>
|
||||
* Check AOSP notice:<br/>
|
||||
*
|
||||
* <pre>
|
||||
* 'ComposeShader can only contain shaders of different types (a BitmapShader and a
|
||||
* LinearGradient for instance, but not two instances of BitmapShader)'. But, 'If your
|
||||
* application is affected by any of these missing features or limitations, you can turn
|
||||
* off hardware acceleration for just the affected portion of your application by calling
|
||||
* setLayerType(View.LAYER_TYPE_SOFTWARE, null).'
|
||||
* </pre>
|
||||
*
|
||||
* @param v
|
||||
* The view
|
||||
*/
|
||||
public static void removeHardwareAccelerationSupport(View v) {
|
||||
if (v.getLayerType() != View.LAYER_TYPE_SOFTWARE) {
|
||||
v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void measureView(View v, int width, int height) {
|
||||
int widthMeasureSpec;
|
||||
int heightMeasureSpec;
|
||||
if (width == ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
widthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
|
||||
MeasureSpec.UNSPECIFIED);
|
||||
else
|
||||
widthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(width, 0),
|
||||
MeasureSpec.EXACTLY);
|
||||
if (height == ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
|
||||
MeasureSpec.UNSPECIFIED);
|
||||
else
|
||||
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(height, 0),
|
||||
MeasureSpec.EXACTLY);
|
||||
|
||||
v.measure(widthMeasureSpec, heightMeasureSpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the supplied view is under the given point in the
|
||||
* parent view's coordinate system.
|
||||
*
|
||||
* @param view Child view of the parent to hit test
|
||||
* @param x X position to test in the parent's coordinate system
|
||||
* @param y Y position to test in the parent's coordinate system
|
||||
* @return true if the supplied view is under the given point, false otherwise
|
||||
*/
|
||||
public static boolean isViewUnder(View view, int x, int y) {
|
||||
if (view == null || view.getVisibility() != View.VISIBLE) {
|
||||
return false;
|
||||
}
|
||||
return x >= view.getLeft() &&
|
||||
x < view.getRight() &&
|
||||
y >= view.getTop() &&
|
||||
y < view.getBottom();
|
||||
}
|
||||
}
|
||||
@@ -1,158 +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.widget;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Color;
|
||||
import android.os.BatteryManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.drawable.BatteryDrawable;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
public class BatteryView extends TextView {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = BatteryView.class.getSimpleName();
|
||||
|
||||
private int mLevel = 0;
|
||||
private boolean mCharging = false;
|
||||
|
||||
private BatteryDrawable mDrawable;
|
||||
|
||||
private boolean mAttached = false;
|
||||
private boolean mIsChargerWorking = false;
|
||||
|
||||
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
|
||||
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
|
||||
* 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
|
||||
boolean charging = (intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
|
||||
== BatteryManager.BATTERY_STATUS_CHARGING);
|
||||
|
||||
if (mLevel != level || mCharging != charging) {
|
||||
mLevel = level;
|
||||
mCharging = charging;
|
||||
if (mCharging && mLevel != 100) {
|
||||
startCharger();
|
||||
} else {
|
||||
stopCharger();
|
||||
mDrawable.setElect(mLevel);
|
||||
}
|
||||
setText(String.valueOf(mLevel) + "%");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final Runnable mCharger = new Runnable() {
|
||||
|
||||
private int level = 0;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
level += 2;
|
||||
if (level > mLevel)
|
||||
level = 0;
|
||||
mDrawable.setElect(level, mLevel <= BatteryDrawable.WARN_LIMIT);
|
||||
getHandler().postDelayed(mCharger, 200);
|
||||
}
|
||||
};
|
||||
|
||||
public BatteryView(Context context) {
|
||||
super(context);
|
||||
init();
|
||||
}
|
||||
|
||||
public BatteryView(Context context, AttributeSet attrs) {
|
||||
this(context, attrs, 0);
|
||||
}
|
||||
|
||||
public BatteryView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
|
||||
init();
|
||||
|
||||
TypedArray typedArray = context.obtainStyledAttributes(
|
||||
attrs, R.styleable.BatteryView, defStyleAttr, 0);
|
||||
int color = typedArray.getColor(R.styleable.BatteryView_bvColor, Color.WHITE);
|
||||
typedArray.recycle();
|
||||
|
||||
mDrawable.setColor(color);
|
||||
}
|
||||
|
||||
private void init() {
|
||||
mDrawable = new BatteryDrawable();
|
||||
// TODO how to get size ?
|
||||
int height = Ui.dp2pix(12);
|
||||
mDrawable.setBounds(0, 0, (int) (height / 0.618f), height);
|
||||
setCompoundDrawables(mDrawable, null, null, null);
|
||||
setCompoundDrawablePadding(Ui.dp2pix(5));
|
||||
}
|
||||
|
||||
private void startCharger() {
|
||||
if (!mIsChargerWorking) {
|
||||
getHandler().post(mCharger);
|
||||
mIsChargerWorking = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void stopCharger() {
|
||||
if (mIsChargerWorking) {
|
||||
getHandler().removeCallbacks(mCharger);
|
||||
mIsChargerWorking = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow();
|
||||
|
||||
if (!mAttached) {
|
||||
mAttached = true;
|
||||
|
||||
registerReceiver();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow();
|
||||
|
||||
if (mAttached) {
|
||||
unregisterReceiver();
|
||||
stopCharger();
|
||||
mAttached = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void registerReceiver() {
|
||||
final IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
|
||||
getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
|
||||
}
|
||||
|
||||
private void unregisterReceiver() {
|
||||
getContext().unregisterReceiver(mIntentReceiver);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
public class ColorView extends View {
|
||||
|
||||
private int mColor;
|
||||
|
||||
public ColorView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public ColorView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public ColorView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public ColorView(Context context, AttributeSet attrs, int defStyleAttr,
|
||||
int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
if (mColor != color) {
|
||||
mColor = color;
|
||||
invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
canvas.drawColor(mColor);
|
||||
}
|
||||
}
|
||||
@@ -1,115 +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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
public class DrawerListView extends ListView {
|
||||
|
||||
private Context mContext;
|
||||
private DrawerListAdapter mAdapter;
|
||||
|
||||
private static final int DRAWABLE_SIDE = Ui.dp2pix(24);
|
||||
|
||||
public DrawerListView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
public DrawerListView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public DrawerListView(Context context, AttributeSet attrs,
|
||||
int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context);
|
||||
}
|
||||
|
||||
private void init(Context context) {
|
||||
mContext = context;
|
||||
mAdapter = new DrawerListAdapter();
|
||||
setAdapter(mAdapter);
|
||||
}
|
||||
|
||||
public void setData(Drawable[] drawableArray, CharSequence[] titleArray) {
|
||||
mAdapter.setData(drawableArray, titleArray);
|
||||
}
|
||||
|
||||
private class DrawerListAdapter extends BaseAdapter {
|
||||
|
||||
private Drawable[] mDrawableArray;
|
||||
private CharSequence[] mTitleArray;
|
||||
|
||||
private void setData(Drawable[] drawableArray, CharSequence[] titleArray) {
|
||||
if (drawableArray != null && titleArray != null) {
|
||||
if (drawableArray.length != titleArray.length)
|
||||
throw new java.lang.IllegalStateException("drawableArray.length != titleArray.length");
|
||||
} else if (drawableArray == null && titleArray == null) {
|
||||
throw new java.lang.IllegalStateException("drawableArray and titleArray should be all null or not null");
|
||||
}
|
||||
mDrawableArray = drawableArray;
|
||||
mTitleArray = titleArray;
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return mTitleArray == null ? 0 : mTitleArray.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getItem(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
if (convertView == null)
|
||||
convertView = LayoutInflater.from(mContext).inflate(R.layout.drawer_list_item, parent, false);
|
||||
|
||||
TextView tv = (TextView) convertView;
|
||||
Drawable d = mDrawableArray[position];
|
||||
CharSequence t = mTitleArray[position];
|
||||
tv.setText(t);
|
||||
d.setBounds(0, 0, DRAWABLE_SIDE, DRAWABLE_SIDE);
|
||||
tv.setCompoundDrawables(d, null, null, null);
|
||||
|
||||
return convertView;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,563 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2013 The Android Open Source Project
|
||||
* 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.widget;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.PropertyValuesHolder;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.support.v4.view.ViewCompat;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.view.ViewTreeObserver;
|
||||
import android.widget.AbsListView;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ListView;
|
||||
|
||||
/**
|
||||
* A custom listview which supports the preview of extra content corresponding to each cell
|
||||
* by clicking on the cell to hide and show the extra content.
|
||||
*/
|
||||
public class ExpandingListView extends ListView {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = ExpandingListView.class.getSimpleName();
|
||||
|
||||
private int mExpandingId;
|
||||
private boolean mShouldRemoveObserver = false;
|
||||
private boolean mAnimating = false;
|
||||
|
||||
private final List<View> mViewsToDraw = new ArrayList<View>();
|
||||
|
||||
private int[] mTranslate;
|
||||
|
||||
public ExpandingListView(Context context) {
|
||||
super(context);
|
||||
init();
|
||||
}
|
||||
|
||||
public ExpandingListView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
public ExpandingListView(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
setOnItemClickListener(mItemClickListener);
|
||||
}
|
||||
|
||||
public void setExpandingId(int id) {
|
||||
mExpandingId = id;
|
||||
}
|
||||
|
||||
public boolean isAnimating() {
|
||||
return mAnimating;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens for item clicks and expands or collapses the selected view depending on
|
||||
* its current state.
|
||||
*/
|
||||
private final AdapterView.OnItemClickListener mItemClickListener = new AdapterView
|
||||
.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
|
||||
if (view.findViewById(mExpandingId).getVisibility() == View.GONE) {
|
||||
expandView(view);
|
||||
} else {
|
||||
collapseView(view);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private int[] getTopAndBottomTranslationsE(int top, int bottom, int yDelta) {
|
||||
int yTranslateTop = 0;
|
||||
int yTranslateBottom = yDelta;
|
||||
|
||||
int height = bottom - top;
|
||||
int bottomLine = getHeight() - getPaddingBottom();
|
||||
|
||||
boolean isOverTop = top < getPaddingTop();
|
||||
boolean isBelowBottom = (top + height + yDelta) > bottomLine;
|
||||
if (isOverTop) {
|
||||
yTranslateTop = top - getPaddingTop();
|
||||
yTranslateBottom = yDelta - yTranslateTop;
|
||||
} else if (isBelowBottom){
|
||||
int deltaBelow = top + height + yDelta - bottomLine;
|
||||
yTranslateTop = top - deltaBelow < getPaddingTop() ? (top - getPaddingTop()) : deltaBelow;
|
||||
yTranslateBottom = yDelta - yTranslateTop;
|
||||
}
|
||||
|
||||
return new int[] {yTranslateTop, yTranslateBottom};
|
||||
}
|
||||
|
||||
private int[] getTopAndBottomTranslationsC(int top, int bottom, int yDelta, int firstTop, View view) {
|
||||
int yTranslateTop = 0;
|
||||
int yTranslateBottom = yDelta;
|
||||
|
||||
int bottomLine = getHeight() - getPaddingBottom();
|
||||
|
||||
int index = 0;
|
||||
final int childCount = getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
if (getChildAt(i).equals(view)) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int maxBottom = bottom;
|
||||
for (int i = index + 1; i < getChildCount(); i++) {
|
||||
View v = getChildAt(i);
|
||||
maxBottom += v.getVisibility() != View.GONE ? v.getHeight() + getDividerHeight() : 0;
|
||||
}
|
||||
|
||||
int newMaxBottom = maxBottom - yDelta;
|
||||
int maxYTranslateTop = getPaddingTop() - firstTop;
|
||||
|
||||
boolean isCollapsingAboveBottom = maxBottom >= bottomLine && newMaxBottom < bottomLine;
|
||||
|
||||
if (isCollapsingAboveBottom) {
|
||||
yTranslateTop = bottomLine - newMaxBottom;
|
||||
if (yTranslateTop > maxYTranslateTop)
|
||||
yTranslateTop = maxYTranslateTop;
|
||||
yTranslateBottom = yDelta - yTranslateTop;
|
||||
}
|
||||
|
||||
return new int[] {yTranslateTop, yTranslateBottom};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method expands the view that was clicked and animates all the views
|
||||
* around it to make room for the expanding view. There are several steps required
|
||||
* to do this which are outlined below.
|
||||
*
|
||||
* 1. Store the current top and bottom bounds of each visible item in the listview.
|
||||
* 2. Update the layout parameters of the selected view. In the context of this
|
||||
* method, the view should be originally collapsed and set to some custom height.
|
||||
* The layout parameters are updated so as to wrap the content of the additional
|
||||
* text that is to be displayed.
|
||||
*
|
||||
* After invoking a layout to take place, the listview will order all the items
|
||||
* such that there is space for each view. This layout will be independent of what
|
||||
* the bounds of the items were prior to the layout so two pre-draw passes will
|
||||
* be made. This is necessary because after the layout takes place, some views that
|
||||
* were visible before the layout may now be off bounds but a reference to these
|
||||
* views is required so the animation completes as intended.
|
||||
*
|
||||
* 3. The first predraw pass will set the bounds of all the visible items to
|
||||
* their original location before the layout took place and then force another
|
||||
* layout. Since the bounds of the cells cannot be set directly, the method
|
||||
* setSelectionFromTop can be used to achieve a very similar effect.
|
||||
* 4. The expanding view's bounds are animated to what the final values should be
|
||||
* from the original bounds.
|
||||
* 5. The bounds above the expanding view are animated upwards while the bounds
|
||||
* below the expanding view are animated downwards.
|
||||
* 6. The extra text is faded in as its contents become visible throughout the
|
||||
* animation process.
|
||||
*
|
||||
* It is important to note that the listview is disabled during the animation
|
||||
* because the scrolling behaviour is unpredictable if the bounds of the items
|
||||
* within the listview are not constant during the scroll.
|
||||
*/
|
||||
|
||||
private void expandView(final View view) {
|
||||
mAnimating = true;
|
||||
|
||||
final ExpandableListItem viewObject = (ExpandableListItem)getItemAtPosition
|
||||
(getPositionForView(view));
|
||||
|
||||
/* Store the original top and bottom bounds of all the cells.*/
|
||||
final int oldTop = view.getTop();
|
||||
final int oldBottom = view.getBottom();
|
||||
|
||||
final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();
|
||||
|
||||
int childCount = getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
ViewCompat.setHasTransientState(v, true);
|
||||
oldCoordinates.put(v, new int[] {v.getTop(), v.getBottom()});
|
||||
}
|
||||
|
||||
/* Update the layout so the extra content becomes visible.*/
|
||||
final View expandingLayout = view.findViewById(mExpandingId);
|
||||
expandingLayout.setVisibility(View.VISIBLE);
|
||||
|
||||
/* Add an onPreDraw Listener to the listview. onPreDraw will get invoked after onLayout
|
||||
* and onMeasure have run but before anything has been drawn. This
|
||||
* means that the final post layout properties for all the items have already been
|
||||
* determined, but still have not been rendered onto the screen.*/
|
||||
final ViewTreeObserver observer = getViewTreeObserver();
|
||||
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
|
||||
|
||||
@Override
|
||||
public boolean onPreDraw() {
|
||||
/* Determine if this is the first or second pass.*/
|
||||
if (!mShouldRemoveObserver) {
|
||||
mShouldRemoveObserver = true;
|
||||
|
||||
/* Calculate what the parameters should be for setSelectionFromTop.
|
||||
* The ListView must be offset in a way, such that after the animation
|
||||
* takes place, all the cells that remain visible are rendered completely
|
||||
* by the ListView.*/
|
||||
int newTop = view.getTop();
|
||||
int newBottom = view.getBottom();
|
||||
|
||||
int newHeight = newBottom - newTop;
|
||||
int oldHeight = oldBottom - oldTop;
|
||||
int delta = newHeight - oldHeight;
|
||||
|
||||
mTranslate = getTopAndBottomTranslationsE(oldTop, oldBottom, delta);
|
||||
|
||||
int currentTop = view.getTop();
|
||||
int futureTop = oldTop - mTranslate[0];
|
||||
|
||||
int firstChildStartTop = getChildAt(0).getTop();
|
||||
int firstVisiblePosition = getFirstVisiblePosition();
|
||||
int deltaTop = currentTop - futureTop;
|
||||
|
||||
int i;
|
||||
int childCount = getChildCount();
|
||||
for (i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
int height = v.getBottom() - Math.max(0, v.getTop());
|
||||
if (deltaTop - height > 0) {
|
||||
firstVisiblePosition++;
|
||||
deltaTop -= height;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
firstChildStartTop = 0;
|
||||
}
|
||||
|
||||
setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop - getPaddingTop());
|
||||
|
||||
/* Request another layout to update the layout parameters of the cells.*/
|
||||
requestLayout();
|
||||
|
||||
/* Return false such that the ListView does not redraw its contents on
|
||||
* this layout but only updates all the parameters associated with its
|
||||
* children.*/
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Remove the predraw listener so this method does not keep getting called. */
|
||||
mShouldRemoveObserver = false;
|
||||
observer.removeOnPreDrawListener(this);
|
||||
|
||||
int yTranslateTop = mTranslate[0];
|
||||
int yTranslateBottom = mTranslate[1];
|
||||
|
||||
ArrayList <Animator> animations = new ArrayList<Animator>();
|
||||
|
||||
int index = indexOfChild(view);
|
||||
|
||||
/* Loop through all the views that were on the screen before the cell was
|
||||
* expanded. Some cells will still be children of the ListView while
|
||||
* others will not. The cells that remain children of the ListView
|
||||
* simply have their bounds animated appropriately. The cells that are no
|
||||
* longer children of the ListView also have their bounds animated, but
|
||||
* must also be added to a list of views which will be drawn in dispatchDraw.*/
|
||||
for (View v: oldCoordinates.keySet()) {
|
||||
int[] old = oldCoordinates.get(v);
|
||||
v.setTop(old[0]);
|
||||
v.setBottom(old[1]);
|
||||
if (v.getParent() == null) {
|
||||
mViewsToDraw.add(v);
|
||||
int delta = old[0] < oldTop ? -yTranslateTop : yTranslateBottom;
|
||||
animations.add(getAnimation(v, delta, delta));
|
||||
} else {
|
||||
int i = indexOfChild(v);
|
||||
if (v != view) {
|
||||
int delta = i > index ? yTranslateBottom : -yTranslateTop;
|
||||
animations.add(getAnimation(v, delta, delta));
|
||||
}
|
||||
ViewCompat.setHasTransientState(v, false);
|
||||
}
|
||||
}
|
||||
|
||||
/* Adds animation for expanding the cell that was clicked. */
|
||||
animations.add(getAnimation(view, -yTranslateTop, yTranslateBottom));
|
||||
|
||||
/* Adds an animation for fading in the extra content. */
|
||||
animations.add(ObjectAnimator.ofFloat(view.findViewById(mExpandingId),
|
||||
View.ALPHA, 0, 1));
|
||||
|
||||
/* Disabled the ListView for the duration of the animation.*/
|
||||
setEnabled(false);
|
||||
setClickable(false);
|
||||
|
||||
/* Play all the animations created above together at the same time. */
|
||||
AnimatorSet s = new AnimatorSet();
|
||||
s.playTogether(animations);
|
||||
s.addListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mAnimating = false;
|
||||
viewObject.setExpanded(true);
|
||||
setEnabled(true);
|
||||
setClickable(true);
|
||||
if (mViewsToDraw.size() > 0) {
|
||||
for (View v : mViewsToDraw) {
|
||||
ViewCompat.setHasTransientState(v, false);
|
||||
}
|
||||
}
|
||||
mViewsToDraw.clear();
|
||||
}
|
||||
});
|
||||
s.start();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* By overriding dispatchDraw, we can draw the cells that disappear during the
|
||||
* expansion process. When the cell expands, some items below or above the expanding
|
||||
* cell may be moved off screen and are thus no longer children of the ListView's
|
||||
* layout. By storing a reference to these views prior to the layout, and
|
||||
* guaranteeing that these cells do not get recycled, the cells can be drawn
|
||||
* directly onto the canvas during the animation process. After the animation
|
||||
* completes, the references to the extra views can then be discarded.
|
||||
*/
|
||||
@Override
|
||||
protected void dispatchDraw(Canvas canvas) {
|
||||
super.dispatchDraw(canvas);
|
||||
|
||||
if (mViewsToDraw.size() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (View v: mViewsToDraw) {
|
||||
canvas.translate(0, v.getTop());
|
||||
v.draw(canvas);
|
||||
canvas.translate(0, -v.getTop());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method collapses the view that was clicked and animates all the views
|
||||
* around it to close around the collapsing view. There are several steps required
|
||||
* to do this which are outlined below.
|
||||
*
|
||||
* 1. Update the layout parameters of the view clicked so as to minimize its height
|
||||
* to the original collapsed (default) state.
|
||||
* 2. After invoking a layout, the listview will shift all the cells so as to display
|
||||
* them most efficiently. Therefore, during the first predraw pass, the listview
|
||||
* must be offset by some amount such that given the custom bound change upon
|
||||
* collapse, all the cells that need to be on the screen after the layout
|
||||
* are rendered by the listview.
|
||||
* 3. On the second predraw pass, all the items are first returned to their original
|
||||
* location (before the first layout).
|
||||
* 4. The collapsing view's bounds are animated to what the final values should be.
|
||||
* 5. The bounds above the collapsing view are animated downwards while the bounds
|
||||
* below the collapsing view are animated upwards.
|
||||
* 6. The extra text is faded out as its contents become visible throughout the
|
||||
* animation process.
|
||||
*/
|
||||
|
||||
private void collapseView(final View view) {
|
||||
mAnimating = true;
|
||||
|
||||
final ExpandableListItem viewObject = (ExpandableListItem)getItemAtPosition
|
||||
(getPositionForView(view));
|
||||
|
||||
/* Store the original top and bottom bounds of all the cells.*/
|
||||
final int oldTop = view.getTop();
|
||||
final int oldBottom = view.getBottom();
|
||||
final int firstTop = getChildAt(0).getTop();
|
||||
|
||||
final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();
|
||||
|
||||
int childCount = getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
ViewCompat.setHasTransientState(v, true);
|
||||
oldCoordinates.put(v, new int [] {v.getTop(), v.getBottom()});
|
||||
}
|
||||
|
||||
/* Update the layout so the extra content becomes gone.*/
|
||||
final View expandingLayout = view.findViewById(mExpandingId);
|
||||
expandingLayout.setVisibility(View.GONE);
|
||||
|
||||
/* Add an onPreDraw listener. */
|
||||
final ViewTreeObserver observer = getViewTreeObserver();
|
||||
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
|
||||
|
||||
@Override
|
||||
public boolean onPreDraw() {
|
||||
|
||||
if (!mShouldRemoveObserver) {
|
||||
/*Same as for expandingView, the parameters for setSelectionFromTop must
|
||||
* be determined such that the necessary cells of the ListView are rendered
|
||||
* and added to it.*/
|
||||
mShouldRemoveObserver = true;
|
||||
|
||||
expandingLayout.setVisibility(View.VISIBLE);
|
||||
|
||||
int newTop = view.getTop();
|
||||
int newBottom = view.getBottom();
|
||||
|
||||
int newHeight = newBottom - newTop;
|
||||
int oldHeight = oldBottom - oldTop;
|
||||
int deltaHeight = oldHeight - newHeight;
|
||||
|
||||
mTranslate = getTopAndBottomTranslationsC(oldTop, oldBottom, deltaHeight, firstTop, view);
|
||||
|
||||
int currentTop = view.getTop();
|
||||
int futureTop = oldTop + mTranslate[0];
|
||||
|
||||
int firstChildStartTop = getChildAt(0).getTop();
|
||||
int firstVisiblePosition = getFirstVisiblePosition();
|
||||
int deltaTop = currentTop - futureTop;
|
||||
|
||||
int i;
|
||||
int childCount = getChildCount();
|
||||
for (i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
int height = v.getBottom() - Math.max(0, v.getTop());
|
||||
if (deltaTop - height > 0) {
|
||||
firstVisiblePosition++;
|
||||
deltaTop -= height;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
firstChildStartTop = 0;
|
||||
}
|
||||
|
||||
setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop - getPaddingTop());
|
||||
|
||||
requestLayout();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
mShouldRemoveObserver = false;
|
||||
observer.removeOnPreDrawListener(this);
|
||||
|
||||
int yTranslateTop = mTranslate[0];
|
||||
int yTranslateBottom = mTranslate[1];
|
||||
|
||||
int index = indexOfChild(view);
|
||||
int childCount = getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
int [] old = oldCoordinates.get(v);
|
||||
if (old != null) {
|
||||
/* If the cell was present in the ListView before the collapse and
|
||||
* after the collapse then the bounds are reset to their old values.*/
|
||||
v.setTop(old[0]);
|
||||
v.setBottom(old[1]);
|
||||
ViewCompat.setHasTransientState(v, false);
|
||||
} else {
|
||||
/* If the cell is present in the ListView after the collapse but
|
||||
* not before the collapse then the bounds are calculated using
|
||||
* the bottom and top translation of the collapsing cell.*/
|
||||
int delta = i > index ? yTranslateBottom : -yTranslateTop;
|
||||
v.setTop(v.getTop() + delta);
|
||||
v.setBottom(v.getBottom() + delta);
|
||||
}
|
||||
}
|
||||
|
||||
final View expandingLayout = view.findViewById(mExpandingId);
|
||||
|
||||
/* Animates all the cells present on the screen after the collapse. */
|
||||
ArrayList <Animator> animations = new ArrayList<Animator>();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
View v = getChildAt(i);
|
||||
if (v != view) {
|
||||
float diff = i > index ? -yTranslateBottom : yTranslateTop;
|
||||
animations.add(getAnimation(v, diff, diff));
|
||||
}
|
||||
}
|
||||
|
||||
/* Adds animation for collapsing the cell that was clicked. */
|
||||
animations.add(getAnimation(view, yTranslateTop, -yTranslateBottom));
|
||||
|
||||
/* Adds an animation for fading out the extra content. */
|
||||
animations.add(ObjectAnimator.ofFloat(expandingLayout, View.ALPHA, 1, 0));
|
||||
|
||||
/* Disabled the ListView for the duration of the animation.*/
|
||||
setEnabled(false);
|
||||
setClickable(false);
|
||||
|
||||
/* Play all the animations created above together at the same time. */
|
||||
AnimatorSet s = new AnimatorSet();
|
||||
s.playTogether(animations);
|
||||
s.addListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mAnimating = false;
|
||||
expandingLayout.setVisibility(View.GONE);
|
||||
view.setLayoutParams(new AbsListView.LayoutParams(AbsListView
|
||||
.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
|
||||
viewObject.setExpanded(false);
|
||||
setEnabled(true);
|
||||
setClickable(true);
|
||||
/* Note that alpha must be set back to 1 in case this view is reused
|
||||
* by a cell that was expanded, but not yet collapsed, so its state
|
||||
* should persist in an expanded state with the extra content visible.*/
|
||||
expandingLayout.setAlpha(1);
|
||||
}
|
||||
});
|
||||
s.start();
|
||||
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes some view and the values by which its top and bottom bounds
|
||||
* should be changed by. Given these params, an animation which will animate
|
||||
* these bound changes is created and returned.
|
||||
*/
|
||||
private Animator getAnimation(final View view, float translateTop, float translateBottom) {
|
||||
|
||||
int top = view.getTop();
|
||||
int bottom = view.getBottom();
|
||||
|
||||
int endTop = (int)(top + translateTop);
|
||||
int endBottom = (int)(bottom + translateBottom);
|
||||
|
||||
PropertyValuesHolder translationTop = PropertyValuesHolder.ofInt("top", top, endTop);
|
||||
PropertyValuesHolder translationBottom = PropertyValuesHolder.ofInt("bottom", bottom,
|
||||
endBottom);
|
||||
|
||||
return ObjectAnimator.ofPropertyValuesHolder(view, translationTop, translationBottom);
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package com.hippo.ehviewer.widget;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
|
||||
public class FloatingActionButton extends View {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = FloatingActionButton.class.getSimpleName();
|
||||
|
||||
private final Paint mButtonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint mDrawablePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private Bitmap mBitmap;
|
||||
private int mColor;
|
||||
private final int mDrawableSide;
|
||||
private final float mShadowRadius;
|
||||
private final float mShadowDx;
|
||||
private final float mShadowDy;
|
||||
|
||||
private int mCircleX;
|
||||
private int mCircleY;
|
||||
private int mCircleRadius;
|
||||
private final Rect mSrc = new Rect();
|
||||
private final RectF mDst = new RectF();
|
||||
|
||||
|
||||
public FloatingActionButton(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public FloatingActionButton(Context context, AttributeSet attributeSet) {
|
||||
this(context, attributeSet, 0);
|
||||
}
|
||||
|
||||
public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
|
||||
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatingActionButton);
|
||||
mDrawableSide = a.getDimensionPixelSize(R.styleable.FloatingActionButton_fabDrawableSide, 72);
|
||||
mColor = a.getColor(R.styleable.FloatingActionButton_fabColor, Color.WHITE);
|
||||
mButtonPaint.setStyle(Paint.Style.FILL);
|
||||
mButtonPaint.setColor(mColor);
|
||||
mShadowRadius = a.getDimension(R.styleable.FloatingActionButton_fabShadowRadius, 10.0f);
|
||||
mShadowDx = a.getDimension(R.styleable.FloatingActionButton_fabShadowDx, 0.0f);
|
||||
mShadowDy = a.getDimension(R.styleable.FloatingActionButton_fabShadowDy, 3.0f);
|
||||
int shadowColor = a.getColor(R.styleable.FloatingActionButton_fabShadowColor, 0x8a000000);
|
||||
mButtonPaint.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy, shadowColor);
|
||||
Drawable drawable = a.getDrawable(R.styleable.FloatingActionButton_fabDrawable);
|
||||
if (drawable != null && drawable instanceof BitmapDrawable)
|
||||
mBitmap = ((BitmapDrawable) drawable).getBitmap();
|
||||
a.recycle();
|
||||
|
||||
setWillNotDraw(false);
|
||||
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
mColor = color;
|
||||
mButtonPaint.setColor(mColor);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
public void setDrawable(Drawable drawable) {
|
||||
mBitmap = ((BitmapDrawable) drawable).getBitmap();
|
||||
updateValue();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
public static int getDefaultSize(int size, int measureSpec) {
|
||||
int result = size;
|
||||
int specMode = MeasureSpec.getMode(measureSpec);
|
||||
int specSize = MeasureSpec.getSize(measureSpec);
|
||||
|
||||
switch (specMode) {
|
||||
case MeasureSpec.UNSPECIFIED:
|
||||
case MeasureSpec.AT_MOST:
|
||||
result = size;
|
||||
break;
|
||||
case MeasureSpec.EXACTLY:
|
||||
result = specSize;
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void updateValue() {
|
||||
float half = Math.min(getWidth(), getHeight()) / 2;
|
||||
mCircleX = (int) (half - mShadowDx);
|
||||
mCircleY = (int) (half - mShadowDy);
|
||||
mCircleRadius = (int) (half - mShadowRadius);
|
||||
float halfDrawableSide = mDrawableSide / 2.0f;
|
||||
if (mBitmap != null) {
|
||||
mSrc.set(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
|
||||
mDst.set(mCircleX - halfDrawableSide, mCircleY - halfDrawableSide, mCircleX + halfDrawableSide, mCircleY + halfDrawableSide);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
|
||||
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
|
||||
super.onLayout(changed, left, top, right, bottom);
|
||||
updateValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
canvas.drawCircle(mCircleX, mCircleY, mCircleRadius, mButtonPaint);
|
||||
if (null != mBitmap)
|
||||
canvas.drawBitmap(mBitmap, mSrc, mDst, mDrawablePaint);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
int color;
|
||||
if (event.getAction() == MotionEvent.ACTION_UP) {
|
||||
color = mColor;
|
||||
} else {
|
||||
color = darkenColor(mColor);
|
||||
}
|
||||
mButtonPaint.setColor(color);
|
||||
invalidate();
|
||||
return super.onTouchEvent(event);
|
||||
}
|
||||
|
||||
public static int darkenColor(int color) {
|
||||
float[] hsv = new float[3];
|
||||
Color.colorToHSV(color, hsv);
|
||||
hsv[2] *= 0.8f;
|
||||
return Color.HSVToColor(hsv);
|
||||
}
|
||||
}
|
||||
@@ -1,813 +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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Build;
|
||||
import android.support.v7.widget.DefaultItemAnimator;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.StaggeredGridLayoutManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.ImageLoader;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.cardview.CardViewSalon;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.ListParser;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView.FooterAdapter;
|
||||
import com.hippo.ehviewer.widget.recyclerview.MarginItemDecoration;
|
||||
import com.hippo.ehviewer.widget.refreshlayout.RefreshLayout;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GalleryListView extends FrameLayout implements RefreshLayout.OnHeaderRefreshListener,
|
||||
RefreshLayout.OnFooterRefreshListener {
|
||||
|
||||
private static final String TAG = GalleryListView.class.getSimpleName();
|
||||
|
||||
public static final int LIST_MODE_DETAIL = 0;
|
||||
public static final int LIST_MODE_THUMB = 1;
|
||||
|
||||
private static final int MODE_REFRESH = 0;
|
||||
private static final int MODE_NEXT_PAGE = 1;
|
||||
private static final int MODE_PRE_PAGE = 2;
|
||||
private static final int MODE_SOMEWHERE = 3;
|
||||
|
||||
private Context mContext;
|
||||
private GalleryListViewHelper mHelper;
|
||||
|
||||
private List<GalleryInfo> mGiList;
|
||||
|
||||
private RefreshLayout mRefreshLayout;
|
||||
private EasyRecyclerView mEasyRecyclerView;
|
||||
private RefreshTextView mRefreshTextView;
|
||||
|
||||
private int mListMode = LIST_MODE_DETAIL;
|
||||
|
||||
private GalleryAdapter mAdapter;
|
||||
private StaggeredGridLayoutManager mLayoutManager;
|
||||
private MarginItemDecoration mItemDecoration;
|
||||
private final int[] mFirstPositionTemp = new int[50]; // TODO
|
||||
|
||||
private long mTaskStamp;
|
||||
|
||||
/**
|
||||
* First index of current page
|
||||
*/
|
||||
private int mFirstIndex;
|
||||
/**
|
||||
* Last index of current page
|
||||
*/
|
||||
private int mLastIndex;
|
||||
private int mCurPage;
|
||||
private int mFirstPage = 0;
|
||||
private int mLastPage = 0;
|
||||
/**
|
||||
* The number of page in sum
|
||||
*/
|
||||
private int mPageNum;
|
||||
private int mItemPerPage;
|
||||
private int mGetMode;
|
||||
|
||||
private OnGetListListener mListener;
|
||||
|
||||
/**
|
||||
* If true, list will make showed item not changed after get
|
||||
*/
|
||||
private boolean mIsKeepPosition;
|
||||
|
||||
private int mTargetPage;
|
||||
private String mTargetUrl;
|
||||
private boolean isFootRefresh = false;
|
||||
|
||||
private LayoutInflater mInflater;
|
||||
|
||||
private int mListDetailThumbWidth;
|
||||
private int mListDetailThumbHeight;
|
||||
|
||||
private int mOldPaddingBottom;
|
||||
|
||||
public GalleryListView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs, 0, 0);
|
||||
}
|
||||
|
||||
public GalleryListView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context, attrs, defStyleAttr, 0);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public GalleryListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
mContext = context;
|
||||
mGiList = new ArrayList<>();
|
||||
mListener = new OnGetGalleryListListener();
|
||||
|
||||
LayoutInflater.from(mContext).inflate(R.layout.gallery_list_view, this);
|
||||
|
||||
mRefreshLayout = (RefreshLayout) findViewById(R.id.refresh_layout);
|
||||
mEasyRecyclerView = (EasyRecyclerView) mRefreshLayout.findViewById(R.id.easy_recycler_view);
|
||||
mRefreshTextView = (RefreshTextView) findViewById(R.id.refresh_text);
|
||||
|
||||
mAdapter = new GalleryAdapter(mContext, mGiList);
|
||||
mLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
|
||||
mItemDecoration = new MarginItemDecoration();
|
||||
mEasyRecyclerView.setOnScrollListener(new OnScrollListener());
|
||||
mEasyRecyclerView.setClipToPadding(false);
|
||||
mEasyRecyclerView.setAdapter(mAdapter);
|
||||
mEasyRecyclerView.setLayoutManager(mLayoutManager);
|
||||
mEasyRecyclerView.addItemDecoration(mItemDecoration);
|
||||
mEasyRecyclerView.setItemAnimator(new DefaultItemAnimator());
|
||||
mEasyRecyclerView.setHasFixedSize(true);
|
||||
setItemMargin(Ui.dp2pix(8)); // TODO for tablet margin should be greater
|
||||
|
||||
mRefreshTextView.setDefaultRefresh(R.string.click_retry, new RefreshTextView.OnRefreshListener() {
|
||||
@Override
|
||||
public void onRefresh() {
|
||||
retry();
|
||||
}
|
||||
});
|
||||
|
||||
mRefreshLayout.setHeaderEnable(true);
|
||||
mRefreshLayout.setFooterEnable(true);
|
||||
mRefreshLayout.setHeaderColorSchemeResources(
|
||||
R.color.refresh_color_1,
|
||||
R.color.refresh_color_2,
|
||||
R.color.refresh_color_3,
|
||||
R.color.refresh_color_4
|
||||
);
|
||||
mRefreshLayout.setFooterColorSchemeResources(
|
||||
R.color.refresh_color_1,
|
||||
R.color.refresh_color_2,
|
||||
R.color.refresh_color_3,
|
||||
R.color.refresh_color_4
|
||||
);
|
||||
mRefreshLayout.setOnHeaderRefreshListener(this);
|
||||
mRefreshLayout.setOnFooterRefreshListener(this);
|
||||
|
||||
mOldPaddingBottom = mEasyRecyclerView.getPaddingBottom();
|
||||
|
||||
// Caculate gallery detail height
|
||||
mInflater = LayoutInflater.from(mContext);
|
||||
View v = mInflater.inflate(R.layout.test_gallery_list_detail_thumb, null);
|
||||
((TextView) v.findViewById(R.id.title)).setText("haha\nhaha");
|
||||
((TextView) v.findViewById(R.id.uploader)).setText("haha");
|
||||
((RatingView) v.findViewById(R.id.rate)).setRating(2.3f);
|
||||
((TextView) v.findViewById(R.id.category)).setText("haha");
|
||||
ViewUtils.measureView(v, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
mListDetailThumbHeight = Math.max(v.getMeasuredHeight(), Ui.dp2pix(120));
|
||||
mListDetailThumbWidth = mListDetailThumbHeight * 2 / 3;
|
||||
}
|
||||
|
||||
public int getListMode() {
|
||||
return mListMode;
|
||||
}
|
||||
|
||||
public void setListMode(int listMode) {
|
||||
if (mListMode != listMode) {
|
||||
mListMode = listMode;
|
||||
// Update span
|
||||
updateSpanCount();
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isLandscape() {
|
||||
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
|
||||
}
|
||||
|
||||
private static final String[] KEY_SPAN_COUNT_ARRAY = {
|
||||
"list_detail_columns_portrait", "list_detail_columns_landscape",
|
||||
"list_thumb_columns_portrait", "list_thumb_columns_landscape"
|
||||
};
|
||||
|
||||
private static final int[] DEFAULT_SPAN_COUNT_ARRAY = {
|
||||
1, 2, 3, 5
|
||||
};
|
||||
|
||||
public void updateSpanCount() {
|
||||
int index = mListMode * 2 + (isLandscape() ? 1 : 0);
|
||||
try {
|
||||
mLayoutManager.setSpanCount(Config.getInt(KEY_SPAN_COUNT_ARRAY[index],
|
||||
DEFAULT_SPAN_COUNT_ARRAY[index]));
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void setGalleryListViewHelper(GalleryListViewHelper h) {
|
||||
mHelper = h;
|
||||
}
|
||||
|
||||
public void setPaddingTopAndBottom(int top, int bottom) {
|
||||
setPadding(getPaddingLeft(), top, getPaddingRight(), getPaddingBottom());
|
||||
mEasyRecyclerView.setPadding(mEasyRecyclerView.getPaddingLeft(), mEasyRecyclerView.getPaddingTop(),
|
||||
mEasyRecyclerView.getPaddingRight(), mOldPaddingBottom + bottom);
|
||||
}
|
||||
|
||||
private void setItemMargin(int margin) {
|
||||
int halfMargin = margin / 2;
|
||||
mItemDecoration.setMargin(margin);
|
||||
mEasyRecyclerView.setPadding(halfMargin, halfMargin,
|
||||
halfMargin, halfMargin);
|
||||
}
|
||||
|
||||
public void setEnabledHeader(boolean enabled) {
|
||||
mRefreshLayout.setHeaderEnable(enabled);
|
||||
}
|
||||
|
||||
public void setEnabledFooter(boolean enabled) {
|
||||
mRefreshLayout.setFooterEnable(enabled);
|
||||
}
|
||||
|
||||
public void setHeaderRefreshing(boolean refreshing) {
|
||||
mRefreshLayout.setHeaderRefreshing(refreshing);
|
||||
}
|
||||
|
||||
public void setOnItemClickListener(EasyRecyclerView.OnItemClickListener l) {
|
||||
mEasyRecyclerView.setOnItemClickListener(l);
|
||||
}
|
||||
|
||||
public void setOnItemLongClickListener(EasyRecyclerView.OnItemLongClickListener l) {
|
||||
mEasyRecyclerView.setOnItemLongClickListener(l);
|
||||
}
|
||||
|
||||
public void setChoiceMode(int choiceMode) {
|
||||
mEasyRecyclerView.setChoiceMode(choiceMode);
|
||||
}
|
||||
|
||||
public void setMultiChoiceModeListener(EasyRecyclerView.MultiChoiceModeListener listener) {
|
||||
mEasyRecyclerView.setMultiChoiceModeListener(listener);
|
||||
}
|
||||
|
||||
public void notifyDataSetChanged() {
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
|
||||
public void setNoneText(CharSequence text) {
|
||||
mRefreshTextView.setVisibility(View.VISIBLE);
|
||||
mRefreshTextView.setEmesg(text, false);
|
||||
}
|
||||
|
||||
public void onlyShowList() {
|
||||
mRefreshLayout.setVisibility(View.VISIBLE);
|
||||
mRefreshTextView.setRefreshing(false);
|
||||
mRefreshTextView.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
public void onlyShowNone() {
|
||||
mRefreshLayout.setVisibility(View.GONE);
|
||||
mRefreshTextView.setVisibility(View.VISIBLE);
|
||||
mRefreshTextView.setEmesg(R.string.none, false);
|
||||
}
|
||||
|
||||
private void getGallerys() {
|
||||
setGallerysLayout();
|
||||
|
||||
mTaskStamp = System.currentTimeMillis();
|
||||
mHelper.doGetGallerys(mTargetUrl, mTaskStamp, mListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onHeaderRefresh() {
|
||||
// It is invokened by user pull, so no need to
|
||||
if (mFirstPage > 0) {
|
||||
getPrePage(true);
|
||||
} else {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFooterRefresh() {
|
||||
if (!isRefreshing() && mLastPage < mPageNum - 1) {
|
||||
isFootRefresh = true;
|
||||
getNextPage(true);
|
||||
isFootRefresh = false;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void firstTimeRefresh() {
|
||||
// set mPullViewGroup gone, make wait view show
|
||||
mRefreshLayout.setVisibility(View.GONE);
|
||||
mRefreshTextView.setVisibility(View.VISIBLE);
|
||||
mRefreshTextView.setRefreshing(true);
|
||||
|
||||
refresh();
|
||||
}
|
||||
|
||||
private void setGallerysLayout() {
|
||||
if (mRefreshLayout.getVisibility() == View.VISIBLE) {
|
||||
if (!isFootRefresh)
|
||||
mRefreshLayout.setHeaderRefreshing(true);
|
||||
mRefreshTextView.setVisibility(View.GONE);
|
||||
} else {
|
||||
mRefreshLayout.setVisibility(View.GONE);
|
||||
mRefreshTextView.setVisibility(View.VISIBLE);
|
||||
mRefreshTextView.setRefreshing(true);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean retry() {
|
||||
// Need to update url, because mode may be changed
|
||||
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
|
||||
getGallerys();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to page 0.<br>
|
||||
* You should know you can refresh or not.
|
||||
*/
|
||||
public void refresh() {
|
||||
mGetMode = MODE_REFRESH;
|
||||
mTargetPage = 0;
|
||||
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
|
||||
mIsKeepPosition = false;
|
||||
getGallerys();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get previous page.<br>
|
||||
* You should know you can get previous page or not
|
||||
*
|
||||
* @param isKeepPosition
|
||||
*/
|
||||
protected void getPrePage(boolean isKeepPosition) {
|
||||
mGetMode = MODE_PRE_PAGE;
|
||||
mTargetPage = mFirstPage - 1;
|
||||
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
|
||||
mIsKeepPosition = isKeepPosition;
|
||||
getGallerys();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get next page.<br>
|
||||
* You should know you can get next page or not
|
||||
*
|
||||
* @param isKeepPosition
|
||||
*/
|
||||
protected void getNextPage(boolean isKeepPosition) {
|
||||
mGetMode = MODE_NEXT_PAGE;
|
||||
mTargetPage = mLastPage + 1;
|
||||
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
|
||||
mIsKeepPosition = isKeepPosition;
|
||||
getGallerys();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get some page.<br>
|
||||
* You should know you can get that page or not
|
||||
*
|
||||
* @param page
|
||||
*/
|
||||
protected void getSomewhere(int page) {
|
||||
mGetMode = MODE_SOMEWHERE;
|
||||
mTargetPage = page;
|
||||
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
|
||||
mIsKeepPosition = false;
|
||||
getGallerys();
|
||||
}
|
||||
|
||||
public void jumpTo(int page) {
|
||||
if (page >= mFirstPage && page <= mLastPage) {
|
||||
int position = (page - mFirstPage) * mItemPerPage;
|
||||
mLayoutManager.scrollToPosition(position);
|
||||
} else if (page == mFirstPage - 1) {
|
||||
getPrePage(false);
|
||||
} else if (page == mLastPage + 1) {
|
||||
getNextPage(false);
|
||||
} else {
|
||||
getSomewhere(page);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if actionbar or footer is refreshing
|
||||
*/
|
||||
public boolean isRefreshing() {
|
||||
return mRefreshLayout.isRefreshing();
|
||||
}
|
||||
|
||||
public boolean isGetGalleryOk() {
|
||||
return mRefreshLayout.getVisibility() == View.VISIBLE;
|
||||
}
|
||||
|
||||
public int getPageNum() {
|
||||
return mPageNum;
|
||||
}
|
||||
|
||||
public int getCurPage() {
|
||||
return mCurPage;
|
||||
}
|
||||
|
||||
public List<GalleryInfo> getGalleryList() {
|
||||
return mGiList;
|
||||
}
|
||||
|
||||
public GalleryInfo getGalleryInfo(int position) {
|
||||
return mGiList.get(position);
|
||||
}
|
||||
|
||||
public static interface OnGetListListener {
|
||||
public void onSuccess(long taskStamp, List<GalleryInfo> gis, int maxPage);
|
||||
public void onFailure(long taskStamp, String eMsg);
|
||||
}
|
||||
|
||||
private class OnGetGalleryListListener implements OnGetListListener, Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int preIndex = mLayoutManager.findFirstVisibleItemPositions(mFirstPositionTemp)[0] - 1;
|
||||
if (preIndex >= 0)
|
||||
mEasyRecyclerView.smoothScrollToPosition(preIndex);
|
||||
}
|
||||
|
||||
public void smoothScrollToPrePosition() {
|
||||
AppHandler.getInstance().post(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(long taskStamp, List<GalleryInfo> gis, int pageNum) {
|
||||
if (mTaskStamp != taskStamp)
|
||||
return;
|
||||
|
||||
if (pageNum == ListParser.TARGET_PAGE_IS_LAST)
|
||||
mPageNum = mTargetPage + 1;
|
||||
else
|
||||
mPageNum = pageNum;
|
||||
|
||||
int itemPerPage = gis == null ? 0 : gis.size();
|
||||
if (mItemPerPage < itemPerPage)
|
||||
mItemPerPage = itemPerPage;
|
||||
|
||||
if (mPageNum == 0) { // Get none
|
||||
onlyShowNone();
|
||||
|
||||
mFirstPage = 0;
|
||||
mLastPage = 0;
|
||||
mGiList.clear();
|
||||
mAdapter.notifyDataSetChanged();
|
||||
} else {
|
||||
onlyShowList();
|
||||
|
||||
int start;
|
||||
switch (mGetMode) {
|
||||
case MODE_REFRESH:
|
||||
mFirstPage = 0;
|
||||
mLastPage = 0;
|
||||
mGiList.clear();
|
||||
mGiList.addAll(gis);
|
||||
mAdapter.notifyDataSetChanged();
|
||||
// For current page
|
||||
mFirstIndex = 0;
|
||||
mLastIndex = gis.size() - 1;
|
||||
mCurPage = 0;
|
||||
|
||||
mLayoutManager.scrollToPosition(0);
|
||||
break;
|
||||
|
||||
case MODE_PRE_PAGE:
|
||||
mFirstPage--;
|
||||
mGiList.addAll(0, gis);
|
||||
mAdapter.notifyItemRangeInserted(0, gis.size());
|
||||
|
||||
if (mIsKeepPosition) {
|
||||
mFirstIndex += gis.size();
|
||||
mLastIndex += gis.size();
|
||||
smoothScrollToPrePosition();
|
||||
} else {
|
||||
mFirstIndex = 0;
|
||||
mLastIndex = gis.size()-1;
|
||||
mCurPage = mTargetPage;
|
||||
mLayoutManager.scrollToPosition(0);
|
||||
}
|
||||
break;
|
||||
|
||||
case MODE_NEXT_PAGE:
|
||||
mLastPage++;
|
||||
start = mGiList.size();
|
||||
mGiList.addAll(gis);
|
||||
mAdapter.notifyItemRangeInserted(start, gis.size());
|
||||
|
||||
if (!mIsKeepPosition) {
|
||||
mFirstIndex = mGiList.size() - gis.size();
|
||||
mLastIndex = mGiList.size() - 1;
|
||||
mCurPage = mTargetPage;
|
||||
mLayoutManager.scrollToPosition(0);
|
||||
}
|
||||
break;
|
||||
|
||||
case MODE_SOMEWHERE:
|
||||
mFirstPage = mTargetPage;
|
||||
mLastPage = mTargetPage;
|
||||
mGiList.clear();
|
||||
mGiList.addAll(gis);
|
||||
mAdapter.notifyDataSetChanged();
|
||||
// For current page
|
||||
mFirstIndex = 0;
|
||||
mLastIndex = gis.size() - 1;
|
||||
mCurPage = mTargetPage;
|
||||
|
||||
mLayoutManager.scrollToPosition(0);
|
||||
}
|
||||
}
|
||||
|
||||
mRefreshLayout.setHeaderRefreshing(false);
|
||||
mRefreshLayout.setFooterRefreshing(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(long taskStamp, String eMsg) {
|
||||
if (mTaskStamp != taskStamp)
|
||||
return;
|
||||
|
||||
switch (mGetMode) {
|
||||
case MODE_REFRESH:
|
||||
case MODE_SOMEWHERE:
|
||||
mRefreshLayout.setVisibility(View.GONE);
|
||||
mRefreshTextView.setVisibility(View.VISIBLE);
|
||||
if (eMsg.equals(mContext.getString(R.string.em_index_error))) {
|
||||
mRefreshTextView.setEmesg(eMsg, mContext.getString(R.string.click_first_page),
|
||||
new RefreshTextView.OnRefreshListener() {
|
||||
@Override
|
||||
public void onRefresh() {
|
||||
mRefreshTextView.setRefreshing(true);
|
||||
refresh();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
mRefreshTextView.setEmesg(eMsg, true);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
mRefreshTextView.setRefreshing(false);
|
||||
mRefreshTextView.setVisibility(View.GONE);
|
||||
MaterialToast.showToast(eMsg);
|
||||
}
|
||||
mRefreshLayout.setHeaderRefreshing(false);
|
||||
mRefreshLayout.setFooterRefreshing(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static interface GalleryListViewHelper {
|
||||
/**
|
||||
* Get url string for very page
|
||||
*
|
||||
* @param targetPage
|
||||
* @return
|
||||
*/
|
||||
public String getTargetUrl(int targetPage);
|
||||
|
||||
/**
|
||||
* Do get gallarys here, you shuold invoke the onSuccess or onFailure of
|
||||
* listener when over
|
||||
*
|
||||
* @param url
|
||||
* @param taskStamp
|
||||
* @param listener
|
||||
*/
|
||||
public void doGetGallerys(String url, long taskStamp, OnGetListListener listener);
|
||||
}
|
||||
|
||||
public class OnScrollListener extends RecyclerView.OnScrollListener {
|
||||
|
||||
@Override
|
||||
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
|
||||
switch (newState) {
|
||||
case RecyclerView.SCROLL_STATE_DRAGGING:
|
||||
ImageCache.getImageCache(mContext).setPauseDiskCache(true);
|
||||
break;
|
||||
case RecyclerView.SCROLL_STATE_IDLE:
|
||||
ImageCache.getImageCache(mContext).setPauseDiskCache(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
|
||||
// mRefreshLayout.onScrolled(recyclerView, dx, dy);
|
||||
|
||||
int itemCount = mLayoutManager.getChildCount();
|
||||
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPositions(mFirstPositionTemp)[0];
|
||||
|
||||
// itemCount might include some view can't be seen
|
||||
// Just check top line child and bottom line child
|
||||
int visibleItemCount = itemCount;
|
||||
int height = mEasyRecyclerView.getHeight();
|
||||
int span = mLayoutManager.getSpanCount();
|
||||
// Top line
|
||||
int start = 0;
|
||||
int end = Math.min(span, itemCount);
|
||||
for (int i = start; i < end; i++) {
|
||||
View view = mLayoutManager.getChildAt(i);
|
||||
if (view.getBottom() <= 0 || view.getTop() > height)
|
||||
visibleItemCount--;
|
||||
}
|
||||
// Bottom line
|
||||
start = Math.max(itemCount - 1 - span, 0);
|
||||
end = itemCount;
|
||||
for (int i = start; i < end; i++) {
|
||||
View view = mLayoutManager.getChildAt(i);
|
||||
if (view.getBottom() <= 0 || view.getTop() > height)
|
||||
visibleItemCount--;
|
||||
}
|
||||
|
||||
if (mItemPerPage == 0)
|
||||
return;
|
||||
if (mLastIndex == 0)
|
||||
mLastIndex = mItemPerPage - 1;
|
||||
int pageChanged = (firstVisibleItem - mFirstIndex) / mItemPerPage;
|
||||
if (pageChanged == 0)
|
||||
pageChanged = (firstVisibleItem + visibleItemCount - mLastIndex - 1) / mItemPerPage;
|
||||
|
||||
if (pageChanged != 0) {
|
||||
mCurPage = mCurPage + pageChanged;
|
||||
mFirstIndex += pageChanged * mItemPerPage;
|
||||
mLastIndex += pageChanged * mItemPerPage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class GalleryViewHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
public int viewType;
|
||||
public LoadImageView thumb;
|
||||
public TextView title;
|
||||
public TextView uploader;
|
||||
public TextView category;
|
||||
public RatingView rate;
|
||||
public TextView posted;
|
||||
public TextView simpleLanguage;
|
||||
|
||||
public GalleryViewHolder(View itemView, int viewType) {
|
||||
super(itemView);
|
||||
|
||||
this.viewType = viewType;
|
||||
switch (viewType) {
|
||||
case LIST_MODE_DETAIL:
|
||||
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
|
||||
title = (TextView) itemView.findViewById(R.id.title);
|
||||
category = (TextView) itemView.findViewById(R.id.category);
|
||||
uploader = (TextView) itemView.findViewById(R.id.uploader);
|
||||
rate = (RatingView) itemView.findViewById(R.id.rate);
|
||||
posted = (TextView) itemView.findViewById(R.id.posted);
|
||||
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
|
||||
|
||||
ViewGroup.LayoutParams lp = thumb.getLayoutParams();
|
||||
lp.width = mListDetailThumbWidth;
|
||||
lp.height = mListDetailThumbHeight;
|
||||
break;
|
||||
case LIST_MODE_THUMB:
|
||||
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
|
||||
category = (TextView) itemView.findViewById(R.id.category);
|
||||
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class GalleryAdapter extends EasyRecyclerView.FooterAdapter<GalleryViewHolder> {
|
||||
|
||||
private final Context mContext;
|
||||
private final List<GalleryInfo> mGiList;
|
||||
private final ImageLoader mImageLoader;
|
||||
|
||||
|
||||
public GalleryAdapter(Context context, List<GalleryInfo> gilist) {
|
||||
mContext = context;
|
||||
mGiList = gilist;
|
||||
mImageLoader = ImageLoader.getInstance(mContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryViewHolder onCreateAndBindFooterViewHolder(
|
||||
ViewGroup parent, View footerView) {
|
||||
return new GalleryViewHolder(footerView, FooterAdapter.TYPE_FOOTER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryViewHolder onCreateViewHolderActual(ViewGroup parent,
|
||||
int viewType) {
|
||||
int resId;
|
||||
if (viewType == LIST_MODE_DETAIL)
|
||||
resId = R.layout.gallery_list_detail_item;
|
||||
else
|
||||
resId = R.layout.gallery_list_thumb_item;
|
||||
View view = mInflater.inflate(resId, parent, false);
|
||||
CardViewSalon.reformWithShadow(view, new int[][]{
|
||||
new int[]{android.R.attr.state_pressed},
|
||||
new int[]{android.R.attr.state_activated},
|
||||
new int[]{}},
|
||||
new int[]{0xff84cae4, 0xff33b5e5, 0xFFFAFAFA}, null, false);
|
||||
return new GalleryViewHolder(view, viewType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolderActual(GalleryViewHolder holder,
|
||||
int position) {
|
||||
GalleryInfo gi = mGiList.get(position);
|
||||
final LoadImageView thumb = holder.thumb;
|
||||
final String key = String.valueOf(gi.gid);
|
||||
if (!key.equals(thumb.getKey())) {
|
||||
// Set new thumb
|
||||
thumb.setImageDrawable(null);
|
||||
thumb.setLoadInfo(gi.thumb, key);
|
||||
Bitmap b = ImageCache.getImageCache(getContext()).getFromMemory(key);
|
||||
if (b != null) {
|
||||
thumb.setContextImage(b, true, false);
|
||||
} else {
|
||||
mImageLoader.add(gi.thumb, String.valueOf(gi.gid),
|
||||
new LoadImageView.SimpleImageGetListener(thumb).setFixScaleType(true));
|
||||
}
|
||||
}
|
||||
// Set simple language
|
||||
TextView simpleLanguage = holder.simpleLanguage;
|
||||
if (gi.simpleLanguage == null) {
|
||||
simpleLanguage.setVisibility(View.GONE);
|
||||
} else {
|
||||
simpleLanguage.setVisibility(View.VISIBLE);
|
||||
simpleLanguage.setText(gi.simpleLanguage);
|
||||
}
|
||||
|
||||
// For detail mode
|
||||
if (holder.viewType == LIST_MODE_DETAIL) {
|
||||
// Set category
|
||||
TextView category = holder.category;
|
||||
String newText = Ui.getCategoryText(gi.category);
|
||||
if (!newText.equals(category.getText())) {
|
||||
category.setText(newText);
|
||||
category.setBackgroundColor(Ui.getCategoryColor(gi.category));
|
||||
}
|
||||
// Set manga title
|
||||
TextView title = holder.title;
|
||||
title.setText(gi.title);
|
||||
// Set uploder
|
||||
TextView uploader = holder.uploader;
|
||||
uploader.setText(gi.uploader);
|
||||
// Set star
|
||||
RatingView rate = holder.rate;
|
||||
rate.setRating(gi.rating);
|
||||
// set posted
|
||||
TextView posted = holder.posted;
|
||||
posted.setText(gi.posted);
|
||||
} else {
|
||||
// Set category
|
||||
TextView category = holder.category;
|
||||
String newText = Ui.getCategoryText(gi.category);
|
||||
if (!newText.equals(category.getText())) {
|
||||
category.setText(newText);
|
||||
category.setBackgroundColor(Ui.getCategoryColor(gi.category)
|
||||
& 0x00ffffff | 0xca000000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewTypeActual(int position) {
|
||||
return mListMode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCountActual() {
|
||||
return mGiList.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,299 +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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.os.Build;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.TouchDelegate;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
|
||||
public class HotspotTouchHelper implements View.OnTouchListener {
|
||||
|
||||
private final Hotspotable mOwner;
|
||||
|
||||
private boolean mPrePressed = false;
|
||||
private boolean mHasPerformedLongPress = false;
|
||||
|
||||
private CheckForLongPress mPendingCheckForLongPress = null;
|
||||
private CheckForTap mPendingCheckForTap = null;
|
||||
private PerformClick mPerformClick = null;
|
||||
private UnsetPressedState mUnsetPressedState = null;
|
||||
|
||||
/**
|
||||
* Cache the touch slop from the context that created the view.
|
||||
*/
|
||||
private int mTouchSlop = -1;
|
||||
|
||||
public HotspotTouchHelper(Hotspotable owner){
|
||||
mOwner = owner;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public boolean onTouch(View v, MotionEvent event) {
|
||||
final float x = event.getX();
|
||||
final float y = event.getY();
|
||||
|
||||
if (event.getAction() == MotionEvent.ACTION_DOWN ||
|
||||
event.getAction() == MotionEvent.ACTION_MOVE)
|
||||
mOwner.setHotspot(x, y);
|
||||
|
||||
if (!v.isEnabled()) {
|
||||
if (event.getAction() == MotionEvent.ACTION_UP && v.isPressed()) {
|
||||
v.setPressed(false);
|
||||
}
|
||||
// A disabled view that is clickable still consumes the touch
|
||||
// events, it just doesn't respond to them.
|
||||
return (v.isClickable() || v.isLongClickable());
|
||||
}
|
||||
|
||||
TouchDelegate touchDelegate = v.getTouchDelegate();
|
||||
if (touchDelegate != null) {
|
||||
if (touchDelegate.onTouchEvent(event)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (v.isClickable() || v.isLongClickable()) {
|
||||
switch (event.getAction()) {
|
||||
case MotionEvent.ACTION_UP:
|
||||
if (v.isPressed() || mPrePressed) {
|
||||
// take focus if we don't have it already and we should in
|
||||
// touch mode.
|
||||
boolean focusTaken = false;
|
||||
if (v.isFocusable() && v.isFocusableInTouchMode() && !v.isFocused()) {
|
||||
focusTaken = v.requestFocus();
|
||||
}
|
||||
|
||||
if (mPrePressed) {
|
||||
// The button is being released before we actually
|
||||
// showed it as pressed. Make it show the pressed
|
||||
// state now (before scheduling the click) to ensure
|
||||
// the user sees it.
|
||||
setPressed(v, true, x, y);
|
||||
}
|
||||
|
||||
if (!mHasPerformedLongPress) {
|
||||
// This is a tap, so remove the longpress check
|
||||
removeLongPressCallback(v);
|
||||
|
||||
// Only perform take click actions if we were in the pressed state
|
||||
if (!focusTaken) {
|
||||
// Use a Runnable and post this rather than calling
|
||||
// performClick directly. This lets other visual state
|
||||
// of the view update before click actions start.
|
||||
if (mPerformClick == null) {
|
||||
mPerformClick = new PerformClick(v);
|
||||
}
|
||||
if (!v.post(mPerformClick)) {
|
||||
v.performClick();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mUnsetPressedState == null) {
|
||||
mUnsetPressedState = new UnsetPressedState(v);
|
||||
}
|
||||
|
||||
if (mPrePressed) {
|
||||
v.postDelayed(mUnsetPressedState,
|
||||
ViewConfiguration.getPressedStateDuration());
|
||||
} else if (!v.post(mUnsetPressedState)) {
|
||||
// If the post failed, unpress right now
|
||||
mUnsetPressedState.run();
|
||||
}
|
||||
|
||||
removeTapCallback(v);
|
||||
}
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mHasPerformedLongPress = false;
|
||||
|
||||
if (performButtonActionOnTouchDown(v, event)) {
|
||||
break;
|
||||
}
|
||||
|
||||
mPrePressed = true;
|
||||
if (mPendingCheckForTap == null) {
|
||||
mPendingCheckForTap = new CheckForTap(v);
|
||||
}
|
||||
mPendingCheckForTap.x = event.getX();
|
||||
mPendingCheckForTap.y = event.getY();
|
||||
v.postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
v.setPressed(false);
|
||||
removeTapCallback(v);
|
||||
removeLongPressCallback(v);
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
mOwner.setHotspot(x, y);
|
||||
|
||||
if (mTouchSlop == -1)
|
||||
mTouchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
|
||||
|
||||
// Be lenient about moving outside of buttons
|
||||
if (!pointInView(v, x, y, mTouchSlop)) {
|
||||
// Outside button
|
||||
removeTapCallback(v);
|
||||
if (v.isPressed()) {
|
||||
// Remove any future long press/tap checks
|
||||
removeLongPressCallback(v);
|
||||
|
||||
v.setPressed(false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private void setPressed(View v, boolean pressed, float x, float y){
|
||||
v.setPressed(pressed);
|
||||
mOwner.setHotspot(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to determine whether the given point, in local coordinates,
|
||||
* is inside the view, where the area of the view is expanded by the slop factor.
|
||||
* This method is called while processing touch-move events to determine if the event
|
||||
* is still within the view.
|
||||
*/
|
||||
public boolean pointInView(View v, float localX, float localY, float slop) {
|
||||
return localX >= -slop && localY >= -slop && localX < ((v.getRight() - v.getLeft()) + slop) &&
|
||||
localY < ((v.getBottom() - v.getTop()) + slop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs button-related actions during a touch down event.
|
||||
*
|
||||
* @param event The event.
|
||||
* @return True if the down was consumed.
|
||||
*/
|
||||
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
|
||||
protected boolean performButtonActionOnTouchDown(View v, MotionEvent event) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
|
||||
if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
|
||||
if (v.showContextMenu()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the longpress detection timer.
|
||||
*/
|
||||
private void removeLongPressCallback(View v) {
|
||||
if (mPendingCheckForLongPress != null) {
|
||||
v.removeCallbacks(mPendingCheckForLongPress);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the tap detection timer.
|
||||
*/
|
||||
private void removeTapCallback(View v) {
|
||||
if (mPendingCheckForTap != null) {
|
||||
mPrePressed = false;
|
||||
v.removeCallbacks(mPendingCheckForTap);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkForLongClick(View v, int delayOffset) {
|
||||
if (v.isLongClickable()) {
|
||||
mHasPerformedLongPress = false;
|
||||
|
||||
if (mPendingCheckForLongPress == null) {
|
||||
mPendingCheckForLongPress = new CheckForLongPress(v);
|
||||
}
|
||||
v.postDelayed(mPendingCheckForLongPress,
|
||||
ViewConfiguration.getLongPressTimeout() - delayOffset);
|
||||
}
|
||||
}
|
||||
|
||||
private final class CheckForLongPress implements Runnable {
|
||||
|
||||
private final View mView;
|
||||
|
||||
public CheckForLongPress(View v) {
|
||||
mView = v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (mView.isPressed() && (mView.getParent() != null)) {
|
||||
if (mView.performLongClick()) {
|
||||
mHasPerformedLongPress = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class CheckForTap implements Runnable {
|
||||
public float x;
|
||||
public float y;
|
||||
private final View mView;
|
||||
|
||||
public CheckForTap(View v) {
|
||||
mView = v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mPrePressed = false;
|
||||
setPressed(mView, true, x, y);
|
||||
checkForLongClick(mView, ViewConfiguration.getTapTimeout());
|
||||
}
|
||||
}
|
||||
|
||||
private final class PerformClick implements Runnable {
|
||||
private final View mView;
|
||||
|
||||
public PerformClick(View v) {
|
||||
mView = v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mView.performClick();
|
||||
}
|
||||
}
|
||||
|
||||
private final class UnsetPressedState implements Runnable {
|
||||
private final View mView;
|
||||
|
||||
public UnsetPressedState(View v) {
|
||||
mView = v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mView.setPressed(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +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.widget;
|
||||
|
||||
public interface Hotspotable {
|
||||
|
||||
public void setHotspot(float x, float y);
|
||||
}
|
||||
@@ -1,64 +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.widget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
|
||||
public class RatingView extends TextView {
|
||||
|
||||
private static final char START_EMPTY = '\uFA73';
|
||||
private static final char START_HALF = '\uFA74';
|
||||
private static final char START_FULL = '\uFA75';
|
||||
|
||||
private int mRating = -1;
|
||||
|
||||
public RatingView(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
public RatingView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
public RatingView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
private void init(Context context) {
|
||||
setTypeface(((AppContext)context.getApplicationContext()).getFaceTypeface());
|
||||
}
|
||||
|
||||
public void setRating(float rating) {
|
||||
mRating = Math.min(10, Math.round(rating * 2));
|
||||
int fullNum = mRating / 2;
|
||||
int halfNum = mRating % 2;
|
||||
int emptyNum = 5 - fullNum - halfNum;
|
||||
StringBuilder sb = new StringBuilder(5);
|
||||
for (int i = 0; i < fullNum; i++)
|
||||
sb.append(START_FULL);
|
||||
if (halfNum == 1)
|
||||
sb.append(START_HALF);
|
||||
for (int i = 0; i < emptyNum; i++)
|
||||
sb.append(START_EMPTY);
|
||||
setText(sb.toString());
|
||||
}
|
||||
}
|
||||
@@ -1,64 +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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
public class SearchView extends android.widget.SearchView {
|
||||
|
||||
private static final String TAG = SearchView.class.getSimpleName();
|
||||
|
||||
private OnActionViewExpandedListener mListener;
|
||||
|
||||
public SearchView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public SearchView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public SearchView(Context context, AttributeSet attrs,
|
||||
int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActionViewExpanded() {
|
||||
super.onActionViewExpanded();
|
||||
|
||||
if (mListener != null)
|
||||
mListener.onActionViewExpanded();
|
||||
}
|
||||
|
||||
public void setOnActionViewExpandedListener(OnActionViewExpandedListener l) {
|
||||
mListener = l;
|
||||
}
|
||||
|
||||
public interface OnActionViewExpandedListener {
|
||||
public void onActionViewExpanded();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,598 +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.widget;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.os.Build;
|
||||
import android.support.v4.view.MotionEventCompat;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.animation.CycleInterpolator;
|
||||
|
||||
import com.hippo.ehviewer.util.AnimatorUtils;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.util.ZInterpolator;
|
||||
|
||||
public class SlidingLayout extends ViewGroup {
|
||||
|
||||
private static final String TAG = SlidingLayout.class.getSimpleName();
|
||||
|
||||
/*
|
||||
* There are three level, first is base level, second is reserved level, third is full screen level.
|
||||
*/
|
||||
|
||||
private static final int LEVEL_BASE = 0;
|
||||
private static final int LEVEL_RESERVED = 1;
|
||||
private static final int LEVEL_FULL_SCREEN = 2;
|
||||
|
||||
private int mLevel = LEVEL_BASE;
|
||||
|
||||
private View mChild;
|
||||
private int mMaxWidth;
|
||||
private int mSlop;
|
||||
private float mShowPercent = 0.0f;
|
||||
private boolean isBottom = true;
|
||||
|
||||
private int mPaddingLeft;
|
||||
private int mPaddingTop;
|
||||
private int mPaddingRight;
|
||||
private int mPaddingBottom;
|
||||
|
||||
private ValueAnimator mToBaseLevelAnimate;
|
||||
private ValueAnimator mToReservedLevelAnimate;
|
||||
private ValueAnimator mToFullScreenLevelAnimate;
|
||||
private SetYListener mToBaseLevelListener;
|
||||
private SetYListener mToReservedLevelListener;
|
||||
private SetYListener mToFullScreenLevelListener;
|
||||
|
||||
private float mInitialMotionX;
|
||||
private float mInitialMotionY;
|
||||
private float mLastMotionY;
|
||||
|
||||
private int mMinTop;
|
||||
private int mMaxTop;
|
||||
|
||||
/*
|
||||
* ---------------------- mFullScreenTop
|
||||
*
|
||||
* ---------------------- m5Top
|
||||
*
|
||||
*
|
||||
* ---------------------- m4Top
|
||||
*
|
||||
* ---------------------- mReservedTop
|
||||
*
|
||||
* ---------------------- m2Top
|
||||
*
|
||||
*
|
||||
* ---------------------- m1Top
|
||||
*
|
||||
* ---------------------- mBaseTop
|
||||
*/
|
||||
|
||||
private int mBaseTop;
|
||||
private int m1Top;
|
||||
private int m2Top;
|
||||
private int mReservedTop;
|
||||
private int m4Top;
|
||||
private int m5Top;
|
||||
private int mFullScreenTop;
|
||||
|
||||
private boolean mInHideAnimate = false;
|
||||
|
||||
private OnChildHideListener mOnChildHideListener;
|
||||
|
||||
private static final ZInterpolator ZINTERPOLATOR = new ZInterpolator();
|
||||
|
||||
public interface OnChildHideListener {
|
||||
public void onChildHide();
|
||||
}
|
||||
|
||||
|
||||
public SlidingLayout(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
public SlidingLayout(Context context, AttributeSet attrs,
|
||||
int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init();
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public SlidingLayout(Context context, AttributeSet attrs,
|
||||
int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
mMaxWidth = Ui.dp2pix(480);
|
||||
mSlop = Ui.dp2pix(0);
|
||||
|
||||
mToBaseLevelAnimate = new ValueAnimator();
|
||||
mToBaseLevelListener = new SetYListener();
|
||||
mToBaseLevelAnimate.addUpdateListener(mToBaseLevelListener);
|
||||
mToBaseLevelAnimate.setDuration(300);
|
||||
mToBaseLevelAnimate.setInterpolator(ZINTERPOLATOR);
|
||||
mToBaseLevelAnimate.addListener(new Animator.AnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationStart(Animator animation) {
|
||||
mInHideAnimate = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mLevel = LEVEL_BASE;
|
||||
if (mChild.getVisibility() != View.INVISIBLE)
|
||||
mChild.setVisibility(View.INVISIBLE);
|
||||
|
||||
if (mOnChildHideListener != null)
|
||||
mOnChildHideListener.onChildHide();
|
||||
|
||||
mInHideAnimate = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationCancel(Animator animation) {
|
||||
mInHideAnimate = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationRepeat(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
});
|
||||
|
||||
mToReservedLevelAnimate = new ValueAnimator();
|
||||
mToReservedLevelListener = new SetYListener();
|
||||
mToReservedLevelAnimate.addUpdateListener(mToReservedLevelListener);
|
||||
mToReservedLevelAnimate.setDuration(300);
|
||||
mToReservedLevelAnimate.setInterpolator(ZINTERPOLATOR);
|
||||
mToReservedLevelAnimate.addListener(new Animator.AnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationStart(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mLevel = LEVEL_RESERVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationCancel(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationRepeat(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
});
|
||||
|
||||
mToFullScreenLevelAnimate = new ValueAnimator();
|
||||
mToFullScreenLevelListener = new SetYListener();
|
||||
mToFullScreenLevelAnimate.addUpdateListener(mToFullScreenLevelListener);
|
||||
mToFullScreenLevelAnimate.setDuration(300);
|
||||
mToFullScreenLevelAnimate.setInterpolator(ZINTERPOLATOR);
|
||||
mToFullScreenLevelAnimate.addListener(new Animator.AnimatorListener() {
|
||||
@Override
|
||||
public void onAnimationStart(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mLevel = LEVEL_FULL_SCREEN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationCancel(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationRepeat(Animator animation) {
|
||||
// Empty
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private class SetYListener implements ValueAnimator.AnimatorUpdateListener {
|
||||
|
||||
private boolean mFirstShow = false;
|
||||
private int mStartTop;
|
||||
|
||||
public void reset() {
|
||||
mFirstShow = true;
|
||||
mStartTop = mChild.getTop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation) {
|
||||
int offsetY = (int) (float) (Float) animation.getAnimatedValue() - mChild.getTop();
|
||||
mChild.offsetTopAndBottom(offsetY);
|
||||
updateShowPercent();
|
||||
|
||||
if (mFirstShow && Math.abs(mStartTop - mChild.getTop()) > 5) {
|
||||
mFirstShow = false;
|
||||
invalidate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setOnChildHideListener(OnChildHideListener l) {
|
||||
mOnChildHideListener = l;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onFinishInflate() {
|
||||
final int childCount = getChildCount();
|
||||
if (childCount != 1)
|
||||
throw new IllegalStateException("There must be only one child");
|
||||
|
||||
mChild = getChildAt(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
|
||||
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
|
||||
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
|
||||
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
|
||||
|
||||
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY)
|
||||
throw new IllegalArgumentException(
|
||||
"SlidingDrawerLayout must be measured with MeasureSpec.EXACTLY.");
|
||||
|
||||
setMeasuredDimension(widthSize, heightSize);
|
||||
|
||||
final View child = mChild;
|
||||
if (child.getVisibility() != GONE) {
|
||||
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
|
||||
Math.min(widthSize - getPaddingLeft() - getPaddingRight(), mMaxWidth), MeasureSpec.EXACTLY);
|
||||
final int childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
|
||||
child.measure(childWidthSpec, childHeightSpec);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLayout(boolean changed, int l, int t, int r, int b) {
|
||||
final View child = mChild;
|
||||
final int width = r - l;
|
||||
final int height = b - t;
|
||||
final int childWidth = child.getMeasuredWidth();
|
||||
final int childHeight = child.getMeasuredHeight();
|
||||
mPaddingLeft = getPaddingLeft();
|
||||
mPaddingTop = getPaddingTop();
|
||||
mPaddingRight = getPaddingRight();
|
||||
mPaddingBottom = getPaddingBottom();
|
||||
|
||||
// Set mReservedLength and mFullScreenLength
|
||||
int heightWithoutPadding = height - mPaddingTop - mPaddingBottom;
|
||||
int defaultReservedLength = Math.min(heightWithoutPadding - Ui.dp2pix(48), Ui.dp2pix(248));
|
||||
int defaultFullScreenLength = Math.max(heightWithoutPadding, defaultReservedLength);
|
||||
int reservedLength = Math.min(defaultReservedLength, childHeight);
|
||||
int fullScreenLength = Math.min(defaultFullScreenLength, childHeight);
|
||||
|
||||
int showHeight = MathUtils.lerp(0, childHeight, mShowPercent);
|
||||
|
||||
int childLeft = mPaddingLeft + (width - mPaddingLeft - mPaddingRight - childWidth) / 2;
|
||||
|
||||
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
|
||||
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
|
||||
final int maxGap = Ui.dp2pix(32);
|
||||
final int brGap = Math.min(Math.abs((mBaseTop - mReservedTop) / 3), maxGap);
|
||||
final int rfGap = Math.min(Math.abs((mReservedTop - mFullScreenTop) / 3), maxGap);
|
||||
switch (vgrav) {
|
||||
case Gravity.TOP: {
|
||||
isBottom = false;
|
||||
mMinTop = mPaddingTop;
|
||||
mMaxTop = mMinTop + childHeight;
|
||||
mBaseTop = mMinTop;
|
||||
mReservedTop = mMinTop + reservedLength;
|
||||
mFullScreenTop = mMinTop + fullScreenLength;
|
||||
|
||||
m1Top = mBaseTop + brGap;
|
||||
m2Top = mReservedTop - brGap;
|
||||
m4Top = mReservedTop + rfGap;
|
||||
m5Top = mFullScreenTop - rfGap;
|
||||
|
||||
int childBottom = mMinTop + showHeight;
|
||||
child.layout(childLeft, childBottom - childHeight, childLeft + childWidth, childBottom);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
case Gravity.BOTTOM: {
|
||||
isBottom = true;
|
||||
mMaxTop = height - mPaddingBottom;
|
||||
mMinTop = mMaxTop - childHeight;
|
||||
mBaseTop = mMaxTop;
|
||||
mReservedTop = mMaxTop - reservedLength;
|
||||
mFullScreenTop = mMaxTop - fullScreenLength;
|
||||
|
||||
m1Top = mBaseTop - brGap;
|
||||
m2Top = mReservedTop + brGap;
|
||||
m4Top = mReservedTop - rfGap;
|
||||
m5Top = mFullScreenTop + rfGap;
|
||||
|
||||
int childTop = mMaxTop - showHeight;
|
||||
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
boolean getTouchEvent = false;
|
||||
final int action = MotionEventCompat.getActionMasked(ev);
|
||||
final float x = ev.getX();
|
||||
final float y = ev.getY();
|
||||
final boolean isChildUnder = ViewUtils.isViewUnder(mChild, (int) x, (int) y);
|
||||
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mInitialMotionX = x;
|
||||
mInitialMotionY = y;
|
||||
mLastMotionY = mInitialMotionY;
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
final float adx = Math.abs(x - mInitialMotionX);
|
||||
final float ady = Math.abs(y - mInitialMotionY);
|
||||
if (isChildUnder && adx > mSlop && ady > adx)
|
||||
getTouchEvent = true;
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
break;
|
||||
}
|
||||
|
||||
return getTouchEvent;
|
||||
}
|
||||
|
||||
private void updateShowPercent() {
|
||||
int top = mChild.getTop();
|
||||
mShowPercent = (isBottom ? (mMaxTop - top) : (top - mMinTop)) /
|
||||
(float) mChild.getHeight();
|
||||
}
|
||||
|
||||
private void cancelAnimator() {
|
||||
if (mToBaseLevelAnimate.isRunning())
|
||||
mToBaseLevelAnimate.cancel();
|
||||
if (mToReservedLevelAnimate.isRunning())
|
||||
mToReservedLevelAnimate.cancel();
|
||||
if (mToFullScreenLevelAnimate.isRunning())
|
||||
mToFullScreenLevelAnimate.cancel();
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
public boolean onTouchEvent(MotionEvent ev) {
|
||||
final int action = MotionEventCompat.getActionMasked(ev);
|
||||
final float x = ev.getX();
|
||||
final float y = ev.getY();
|
||||
boolean getTouchEvent = false;
|
||||
|
||||
cancelAnimator();
|
||||
|
||||
int top;
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mInitialMotionX = x;
|
||||
mInitialMotionY = y;
|
||||
mLastMotionY = mInitialMotionY;
|
||||
if (isShowing())
|
||||
getTouchEvent = true;
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
final float dy = y - mLastMotionY;
|
||||
mLastMotionY = y;
|
||||
getTouchEvent = true;
|
||||
|
||||
top = mChild.getTop();
|
||||
int newTop = top + (int) dy;
|
||||
newTop = MathUtils.clamp(newTop, mMinTop, mMaxTop);
|
||||
mChild.offsetTopAndBottom(newTop - top);
|
||||
updateShowPercent();
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
getTouchEvent = true;
|
||||
|
||||
top = mChild.getTop();
|
||||
if (isBottom) {
|
||||
switch (mLevel) {
|
||||
default:
|
||||
case LEVEL_BASE:
|
||||
if (top < mFullScreenTop)
|
||||
;
|
||||
else if (top < m4Top)
|
||||
toFullScreenLevel();
|
||||
else if (top < m1Top)
|
||||
toReservedLevel(false);
|
||||
else
|
||||
toBaseLevel();
|
||||
break;
|
||||
case LEVEL_RESERVED:
|
||||
if (top < mFullScreenTop)
|
||||
;
|
||||
else if (top < m4Top)
|
||||
toFullScreenLevel();
|
||||
else if (top < m2Top)
|
||||
toReservedLevel(false);
|
||||
else
|
||||
toBaseLevel();
|
||||
break;
|
||||
case LEVEL_FULL_SCREEN:
|
||||
if (top < mFullScreenTop)
|
||||
;
|
||||
else if (top < m5Top)
|
||||
toFullScreenLevel();
|
||||
else if (top < m2Top)
|
||||
toReservedLevel(false);
|
||||
else
|
||||
toBaseLevel();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// TODO
|
||||
}
|
||||
break;
|
||||
}
|
||||
return getTouchEvent;
|
||||
}
|
||||
|
||||
public void hide() {
|
||||
if (mChild.getVisibility() != View.INVISIBLE)
|
||||
mChild.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
|
||||
public boolean isShowing() {
|
||||
return mChild.getVisibility() == View.VISIBLE;
|
||||
}
|
||||
|
||||
public boolean isInHideAnimate() {
|
||||
return mInHideAnimate;
|
||||
}
|
||||
|
||||
public void toReservedLevel(boolean withShake) {
|
||||
cancelAnimator();
|
||||
// Show child
|
||||
if (mChild.getVisibility() != View.VISIBLE)
|
||||
mChild.setVisibility(View.VISIBLE);
|
||||
|
||||
mToReservedLevelListener.reset();
|
||||
mToReservedLevelAnimate.setFloatValues(mChild.getTop(), mReservedTop);
|
||||
|
||||
if (withShake) {
|
||||
AnimatorSet bouncer = new AnimatorSet();
|
||||
Animator delayAnimator = AnimatorUtils.createDelayAnimator(200);
|
||||
ValueAnimator shakeAnimator = ValueAnimator.ofFloat(mReservedTop,
|
||||
isBottom ? mReservedTop - Ui.dp2pix(8) : mReservedTop + Ui.dp2pix(8));
|
||||
shakeAnimator.setDuration(500);
|
||||
shakeAnimator.setInterpolator(new CycleInterpolator(1));
|
||||
shakeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation) {
|
||||
int offsetY = (int) (float) (Float) animation.getAnimatedValue() - mChild.getTop();
|
||||
mChild.offsetTopAndBottom(offsetY);
|
||||
updateShowPercent();
|
||||
}
|
||||
});
|
||||
bouncer.play(mToReservedLevelAnimate).before(delayAnimator);
|
||||
bouncer.play(delayAnimator).before(shakeAnimator);
|
||||
bouncer.start();
|
||||
|
||||
} else {
|
||||
mToReservedLevelAnimate.start();
|
||||
}
|
||||
}
|
||||
|
||||
public void toBaseLevel() {
|
||||
cancelAnimator();
|
||||
// Show child
|
||||
if (mChild.getVisibility() != View.VISIBLE)
|
||||
mChild.setVisibility(View.VISIBLE);
|
||||
|
||||
mToBaseLevelListener.reset();
|
||||
mToBaseLevelAnimate.setFloatValues(mChild.getTop(), mBaseTop);
|
||||
mToBaseLevelAnimate.start();
|
||||
}
|
||||
|
||||
public void toFullScreenLevel() {
|
||||
cancelAnimator();
|
||||
// Show child
|
||||
if (mChild.getVisibility() != View.VISIBLE)
|
||||
mChild.setVisibility(View.VISIBLE);
|
||||
|
||||
mToFullScreenLevelListener.reset();
|
||||
mToFullScreenLevelAnimate.setFloatValues(mChild.getTop(), mFullScreenTop);
|
||||
mToFullScreenLevelAnimate.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
|
||||
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
|
||||
return p instanceof LayoutParams
|
||||
? new LayoutParams((LayoutParams) p)
|
||||
: new LayoutParams(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
|
||||
return p instanceof LayoutParams && super.checkLayoutParams(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
|
||||
return new LayoutParams(getContext(), attrs);
|
||||
}
|
||||
|
||||
public static class LayoutParams extends ViewGroup.LayoutParams {
|
||||
|
||||
private static final int[] LAYOUT_ATTRS = new int[] {
|
||||
android.R.attr.layout_gravity
|
||||
};
|
||||
|
||||
public int gravity = Gravity.BOTTOM;
|
||||
|
||||
public LayoutParams(Context c, AttributeSet attrs) {
|
||||
super(c, attrs);
|
||||
|
||||
final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
|
||||
this.gravity = a.getInt(0, Gravity.BOTTOM);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
public LayoutParams(int width, int height) {
|
||||
super(width, height);
|
||||
}
|
||||
|
||||
public LayoutParams(int width, int height, int gravity) {
|
||||
this(width, height);
|
||||
this.gravity = gravity;
|
||||
}
|
||||
|
||||
public LayoutParams(LayoutParams source) {
|
||||
super(source);
|
||||
gravity = source.gravity;
|
||||
}
|
||||
|
||||
public LayoutParams(ViewGroup.LayoutParams source) {
|
||||
super(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +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.widget;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.SearchRecentSuggestions;
|
||||
|
||||
public class SuggestionHelper extends SearchRecentSuggestions {
|
||||
|
||||
private static final String QUERY = "query";
|
||||
private static final String ORDER_BY = "date DESC";
|
||||
|
||||
private static final int MAX_HISTORY_COUNT = 250;
|
||||
|
||||
private final List<String> mQueryList = new ArrayList<String>();
|
||||
|
||||
private static Map<String, SuggestionHelper> sInstances = new HashMap<String, SuggestionHelper>();
|
||||
|
||||
public static SuggestionHelper getInstance(Context context, String authority, int mode) {
|
||||
SuggestionHelper s = sInstances.get(authority);
|
||||
if (s == null) {
|
||||
s = new SuggestionHelper(context, authority, mode);
|
||||
sInstances.put(authority, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private SuggestionHelper(Context context, String authority, int mode) {
|
||||
super(context, authority, mode);
|
||||
|
||||
Uri suggestionsUri = Uri.parse("content://" + authority + "/suggestions");
|
||||
|
||||
// Get all suggestion
|
||||
ContentResolver cr = context.getContentResolver();
|
||||
Cursor cursor = cr.query(suggestionsUri, new String[]{QUERY}, null, null, ORDER_BY);
|
||||
while(cursor.moveToNext())
|
||||
mQueryList.add(cursor.getString(cursor.getColumnIndex(QUERY)));
|
||||
cursor.close();
|
||||
}
|
||||
|
||||
public List<String> getQueries() {
|
||||
return mQueryList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveRecentQuery(final String queryString, final String line2) {
|
||||
super.saveRecentQuery(queryString, line2);
|
||||
if (!mQueryList.contains(queryString))
|
||||
mQueryList.add(0, queryString);
|
||||
truncateHistory(MAX_HISTORY_COUNT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearHistory() {
|
||||
super.clearHistory();
|
||||
truncateHistory(0);
|
||||
}
|
||||
|
||||
private void truncateHistory(int maxEntries) {
|
||||
if (maxEntries == 0) {
|
||||
mQueryList.clear();
|
||||
} else {
|
||||
for (int i = mQueryList.size() - 1; i >= maxEntries; i--) {
|
||||
mQueryList.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,124 +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.widget;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.AutoCompleteTextView;
|
||||
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
|
||||
public class SuggestionTextView extends PrefixEditText {
|
||||
|
||||
private static final String TAG = SuggestionTextView.class.getSimpleName();
|
||||
|
||||
private List<String> mAllSuggestions;
|
||||
private ArrayAdapter<String> mAdapte;
|
||||
|
||||
private boolean mKeyboardIsShowing = true;
|
||||
|
||||
public SuggestionTextView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public SuggestionTextView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public SuggestionTextView(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
/**
|
||||
* We override this method to avoid an extra onItemClick being called on
|
||||
* the drop-down's OnItemClickListener by
|
||||
* {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
|
||||
* clicked with the trackball.
|
||||
*/
|
||||
@Override
|
||||
public void performCompletion() {
|
||||
}
|
||||
|
||||
/**
|
||||
* We override this method so that we can allow a threshold of zero,
|
||||
* which ACTV does not.
|
||||
*/
|
||||
@Override
|
||||
public boolean enoughToFilter() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
if (!isPopupShowing())
|
||||
showDropDown();
|
||||
|
||||
return super.onTouchEvent(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
|
||||
if (keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
// special case for the back key, we do not even try to send it
|
||||
// to the drop down list but instead, consume it immediately
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
|
||||
KeyEvent.DispatcherState state = getKeyDispatcherState();
|
||||
if (state != null) {
|
||||
state.startTracking(event, this);
|
||||
}
|
||||
return true;
|
||||
} else if (event.getAction() == KeyEvent.ACTION_UP) {
|
||||
KeyEvent.DispatcherState state = getKeyDispatcherState();
|
||||
if (state != null) {
|
||||
state.handleUpEvent(event);
|
||||
}
|
||||
if (event.isTracking() && !event.isCanceled()) {
|
||||
InputMethodManager imm = (InputMethodManager)
|
||||
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
if (imm != null && mKeyboardIsShowing) {
|
||||
imm.hideSoftInputFromWindow(getWindowToken(), 0);
|
||||
mKeyboardIsShowing = false;
|
||||
} else {
|
||||
clearFocus();
|
||||
mKeyboardIsShowing = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.onKeyPreIme(keyCode, event);
|
||||
}
|
||||
|
||||
public void setSuggestionHelper(SuggestionHelper helper) {
|
||||
if (helper != null) {
|
||||
mAllSuggestions = helper.getQueries();
|
||||
mAdapte = new ArrayAdapter<String>(ViewUtils.sContextThemeWrapper,
|
||||
android.R.layout.simple_dropdown_item_1line, mAllSuggestions);
|
||||
setAdapter(mAdapte);
|
||||
} else {
|
||||
mAllSuggestions = null;
|
||||
mAdapte = null;
|
||||
setAdapter(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,337 +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.widget;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.support.v4.view.ViewCompat;
|
||||
import android.view.View;
|
||||
import android.view.animation.AnimationUtils;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
|
||||
/**
|
||||
* Custom progress bar that shows a cycle of colors as widening circles that
|
||||
* overdraw each other. When finished, the bar is cleared from the inside out as
|
||||
* the main cycle continues. Before running, this can also indicate how close
|
||||
* the user is to triggering something (e.g. how far they need to pull down to
|
||||
* trigger a refresh).
|
||||
*/
|
||||
final class SwipeProgressBar {
|
||||
|
||||
// Default progress animation colors are grays.
|
||||
private final static int COLOR1 = 0xB3000000;
|
||||
private final static int COLOR2 = 0x80000000;
|
||||
private final static int COLOR3 = 0x4d000000;
|
||||
private final static int COLOR4 = 0x1a000000;
|
||||
|
||||
// The duration of the animation cycle.
|
||||
private static final int ANIMATION_DURATION_MS = 2000;
|
||||
|
||||
// The duration of the animation to clear the bar.
|
||||
private static final int FINISH_ANIMATION_DURATION_MS = 1000;
|
||||
|
||||
// Interpolator for varying the speed of the animation.
|
||||
private static final Interpolator INTERPOLATOR = BakedBezierInterpolator.getInstance();
|
||||
|
||||
private final Paint mPaint = new Paint();
|
||||
private final RectF mClipRect = new RectF();
|
||||
private float mTriggerPercentage;
|
||||
private long mStartTime;
|
||||
private long mFinishTime;
|
||||
private boolean mRunning;
|
||||
|
||||
// Colors used when rendering the animation,
|
||||
private int mColor1;
|
||||
private int mColor2;
|
||||
private int mColor3;
|
||||
private int mColor4;
|
||||
private final View mParent;
|
||||
|
||||
private final Rect mBounds = new Rect();
|
||||
|
||||
public SwipeProgressBar(View parent) {
|
||||
mParent = parent;
|
||||
mColor1 = COLOR1;
|
||||
mColor2 = COLOR2;
|
||||
mColor3 = COLOR3;
|
||||
mColor4 = COLOR4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the four colors used in the progress animation. The first color will
|
||||
* also be the color of the bar that grows in response to a user swipe
|
||||
* gesture.
|
||||
*
|
||||
* @param color1 Integer representation of a color.
|
||||
* @param color2 Integer representation of a color.
|
||||
* @param color3 Integer representation of a color.
|
||||
* @param color4 Integer representation of a color.
|
||||
*/
|
||||
void setColorScheme(int color1, int color2, int color3, int color4) {
|
||||
mColor1 = color1;
|
||||
mColor2 = color2;
|
||||
mColor3 = color3;
|
||||
mColor4 = color4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the progress the user has made toward triggering the swipe
|
||||
* gesture. and use this value to update the percentage of the trigger that
|
||||
* is shown.
|
||||
*/
|
||||
void setTriggerPercentage(float triggerPercentage) {
|
||||
mTriggerPercentage = triggerPercentage;
|
||||
mStartTime = 0;
|
||||
ViewCompat.postInvalidateOnAnimation(mParent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start showing the progress animation.
|
||||
*/
|
||||
void start() {
|
||||
if (!mRunning) {
|
||||
mTriggerPercentage = 0;
|
||||
mStartTime = AnimationUtils.currentAnimationTimeMillis();
|
||||
mRunning = true;
|
||||
mParent.postInvalidate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop showing the progress animation.
|
||||
*/
|
||||
void stop() {
|
||||
if (mRunning) {
|
||||
mTriggerPercentage = 0;
|
||||
mFinishTime = AnimationUtils.currentAnimationTimeMillis();
|
||||
mRunning = false;
|
||||
mParent.postInvalidate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Return whether the progress animation is currently running.
|
||||
*/
|
||||
boolean isRunning() {
|
||||
return mRunning || mFinishTime > 0;
|
||||
}
|
||||
|
||||
void draw(Canvas canvas) {
|
||||
final int width = mBounds.width();
|
||||
final int height = mBounds.height();
|
||||
final int cx = width / 2;
|
||||
final int cy = mBounds.top + height / 2;
|
||||
boolean drawTriggerWhileFinishing = false;
|
||||
int restoreCount = canvas.save();
|
||||
canvas.clipRect(mBounds);
|
||||
|
||||
if (mRunning || (mFinishTime > 0)) {
|
||||
long now = AnimationUtils.currentAnimationTimeMillis();
|
||||
long elapsed = (now - mStartTime) % ANIMATION_DURATION_MS;
|
||||
long iterations = (now - mStartTime) / ANIMATION_DURATION_MS;
|
||||
float rawProgress = (elapsed / (ANIMATION_DURATION_MS / 100f));
|
||||
|
||||
// If we're not running anymore, that means we're running through
|
||||
// the finish animation.
|
||||
if (!mRunning) {
|
||||
// If the finish animation is done, don't draw anything, and
|
||||
// don't repost.
|
||||
if ((now - mFinishTime) >= FINISH_ANIMATION_DURATION_MS) {
|
||||
mFinishTime = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, use a 0 opacity alpha layer to clear the animation
|
||||
// from the inside out. This layer will prevent the circles from
|
||||
// drawing within its bounds.
|
||||
long finishElapsed = (now - mFinishTime) % FINISH_ANIMATION_DURATION_MS;
|
||||
float finishProgress = (finishElapsed / (FINISH_ANIMATION_DURATION_MS / 100f));
|
||||
float pct = (finishProgress / 100f);
|
||||
// Radius of the circle is half of the screen.
|
||||
float clearRadius = width / 2 * INTERPOLATOR.getInterpolation(pct);
|
||||
mClipRect.set(cx - clearRadius, 0, cx + clearRadius, height);
|
||||
canvas.saveLayerAlpha(mClipRect, 0, 0);
|
||||
// Only draw the trigger if there is a space in the center of
|
||||
// this refreshing view that needs to be filled in by the
|
||||
// trigger. If the progress view is just still animating, let it
|
||||
// continue animating.
|
||||
drawTriggerWhileFinishing = true;
|
||||
}
|
||||
|
||||
// First fill in with the last color that would have finished drawing.
|
||||
if (iterations == 0) {
|
||||
canvas.drawColor(mColor1);
|
||||
} else {
|
||||
if (rawProgress >= 0 && rawProgress < 25) {
|
||||
canvas.drawColor(mColor4);
|
||||
} else if (rawProgress >= 25 && rawProgress < 50) {
|
||||
canvas.drawColor(mColor1);
|
||||
} else if (rawProgress >= 50 && rawProgress < 75) {
|
||||
canvas.drawColor(mColor2);
|
||||
} else {
|
||||
canvas.drawColor(mColor3);
|
||||
}
|
||||
}
|
||||
|
||||
// Then draw up to 4 overlapping concentric circles of varying radii, based on how far
|
||||
// along we are in the cycle.
|
||||
// progress 0-50 draw mColor2
|
||||
// progress 25-75 draw mColor3
|
||||
// progress 50-100 draw mColor4
|
||||
// progress 75 (wrap to 25) draw mColor1
|
||||
if ((rawProgress >= 0 && rawProgress <= 25)) {
|
||||
float pct = (((rawProgress + 25) * 2) / 100f);
|
||||
drawCircle(canvas, cx, cy, mColor1, pct);
|
||||
}
|
||||
if (rawProgress >= 0 && rawProgress <= 50) {
|
||||
float pct = ((rawProgress * 2) / 100f);
|
||||
drawCircle(canvas, cx, cy, mColor2, pct);
|
||||
}
|
||||
if (rawProgress >= 25 && rawProgress <= 75) {
|
||||
float pct = (((rawProgress - 25) * 2) / 100f);
|
||||
drawCircle(canvas, cx, cy, mColor3, pct);
|
||||
}
|
||||
if (rawProgress >= 50 && rawProgress <= 100) {
|
||||
float pct = (((rawProgress - 50) * 2) / 100f);
|
||||
drawCircle(canvas, cx, cy, mColor4, pct);
|
||||
}
|
||||
if ((rawProgress >= 75 && rawProgress <= 100)) {
|
||||
float pct = (((rawProgress - 75) * 2) / 100f);
|
||||
drawCircle(canvas, cx, cy, mColor1, pct);
|
||||
}
|
||||
if (mTriggerPercentage > 0 && drawTriggerWhileFinishing) {
|
||||
// There is some portion of trigger to draw. Restore the canvas,
|
||||
// then draw the trigger. Otherwise, the trigger does not appear
|
||||
// until after the bar has finished animating and appears to
|
||||
// just jump in at a larger width than expected.
|
||||
canvas.restoreToCount(restoreCount);
|
||||
restoreCount = canvas.save();
|
||||
canvas.clipRect(mBounds);
|
||||
drawTrigger(canvas, cx, cy);
|
||||
}
|
||||
// Keep running until we finish out the last cycle.
|
||||
ViewCompat.postInvalidateOnAnimation(mParent);
|
||||
} else {
|
||||
// Otherwise if we're in the middle of a trigger, draw that.
|
||||
if (mTriggerPercentage > 0 && mTriggerPercentage <= 1.0) {
|
||||
drawTrigger(canvas, cx, cy);
|
||||
}
|
||||
}
|
||||
canvas.restoreToCount(restoreCount);
|
||||
}
|
||||
|
||||
private void drawTrigger(Canvas canvas, int cx, int cy) {
|
||||
mPaint.setColor(mColor1);
|
||||
canvas.drawCircle(cx, cy, cx * mTriggerPercentage, mPaint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a circle centered in the view.
|
||||
*
|
||||
* @param canvas the canvas to draw on
|
||||
* @param cx the center x coordinate
|
||||
* @param cy the center y coordinate
|
||||
* @param color the color to draw
|
||||
* @param pct the percentage of the view that the circle should cover
|
||||
*/
|
||||
private void drawCircle(Canvas canvas, float cx, float cy, int color, float pct) {
|
||||
mPaint.setColor(color);
|
||||
canvas.save();
|
||||
canvas.translate(cx, cy);
|
||||
float radiusScale = INTERPOLATOR.getInterpolation(pct);
|
||||
canvas.scale(radiusScale, radiusScale);
|
||||
canvas.drawCircle(0, 0, cx, mPaint);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the drawing bounds of this SwipeProgressBar.
|
||||
*/
|
||||
void setBounds(int left, int top, int right, int bottom) {
|
||||
mBounds.left = left;
|
||||
mBounds.top = top;
|
||||
mBounds.right = right;
|
||||
mBounds.bottom = bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* A pre-baked bezier-curved interpolator for indeterminate progress animations.
|
||||
*/
|
||||
final static class BakedBezierInterpolator implements Interpolator {
|
||||
private static final BakedBezierInterpolator INSTANCE = new BakedBezierInterpolator();
|
||||
|
||||
public final static BakedBezierInterpolator getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use getInstance instead of instantiating.
|
||||
*/
|
||||
private BakedBezierInterpolator() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup table values.
|
||||
* Generated using a Bezier curve from (0,0) to (1,1) with control points:
|
||||
* P0 (0,0)
|
||||
* P1 (0.4, 0)
|
||||
* P2 (0.2, 1.0)
|
||||
* P3 (1.0, 1.0)
|
||||
*
|
||||
* Values sampled with x at regular intervals between 0 and 1.
|
||||
*/
|
||||
private static final float[] VALUES = new float[] {
|
||||
0.0f, 0.0002f, 0.0009f, 0.0019f, 0.0036f, 0.0059f, 0.0086f, 0.0119f, 0.0157f, 0.0209f,
|
||||
0.0257f, 0.0321f, 0.0392f, 0.0469f, 0.0566f, 0.0656f, 0.0768f, 0.0887f, 0.1033f, 0.1186f,
|
||||
0.1349f, 0.1519f, 0.1696f, 0.1928f, 0.2121f, 0.237f, 0.2627f, 0.2892f, 0.3109f, 0.3386f,
|
||||
0.3667f, 0.3952f, 0.4241f, 0.4474f, 0.4766f, 0.5f, 0.5234f, 0.5468f, 0.5701f, 0.5933f,
|
||||
0.6134f, 0.6333f, 0.6531f, 0.6698f, 0.6891f, 0.7054f, 0.7214f, 0.7346f, 0.7502f, 0.763f,
|
||||
0.7756f, 0.7879f, 0.8f, 0.8107f, 0.8212f, 0.8326f, 0.8415f, 0.8503f, 0.8588f, 0.8672f,
|
||||
0.8754f, 0.8833f, 0.8911f, 0.8977f, 0.9041f, 0.9113f, 0.9165f, 0.9232f, 0.9281f, 0.9328f,
|
||||
0.9382f, 0.9434f, 0.9476f, 0.9518f, 0.9557f, 0.9596f, 0.9632f, 0.9662f, 0.9695f, 0.9722f,
|
||||
0.9753f, 0.9777f, 0.9805f, 0.9826f, 0.9847f, 0.9866f, 0.9884f, 0.9901f, 0.9917f, 0.9931f,
|
||||
0.9944f, 0.9955f, 0.9964f, 0.9973f, 0.9981f, 0.9986f, 0.9992f, 0.9995f, 0.9998f, 1.0f, 1.0f
|
||||
};
|
||||
|
||||
private static final float STEP_SIZE = 1.0f / (VALUES.length - 1);
|
||||
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
if (input >= 1.0f) {
|
||||
return 1.0f;
|
||||
}
|
||||
|
||||
if (input <= 0f) {
|
||||
return 0f;
|
||||
}
|
||||
|
||||
int position = Math.min(
|
||||
(int)(input * (VALUES.length - 1)),
|
||||
VALUES.length - 2);
|
||||
|
||||
float quantized = position * STEP_SIZE;
|
||||
float difference = input - quantized;
|
||||
float weight = difference / STEP_SIZE;
|
||||
|
||||
return VALUES[position] + weight * (VALUES[position + 1] - VALUES[position]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.widget;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import com.hippo.ehviewer.effect.DrawableTransition;
|
||||
|
||||
public class TransitionLayout extends LinearLayout {
|
||||
|
||||
private Bitmap mBmp;
|
||||
private int mOldWidth;
|
||||
private int mOldHeight;
|
||||
|
||||
private static final String TAG = TransitionLayout.class.getSimpleName();
|
||||
|
||||
public TransitionLayout(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public TransitionLayout(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public TransitionLayout(Context context, AttributeSet attrs,
|
||||
int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public TransitionLayout(Context context, AttributeSet attrs,
|
||||
int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void dispatchDraw(Canvas canvas) {
|
||||
int width = getWidth();
|
||||
int height = getHeight();
|
||||
|
||||
if (mOldWidth != width || mOldHeight != height || mBmp == null) {
|
||||
mOldWidth = width;
|
||||
mOldHeight = height;
|
||||
|
||||
if (mBmp != null && !mBmp.isRecycled())
|
||||
mBmp.recycle();
|
||||
|
||||
mBmp = Bitmap.createBitmap(getWidth(), getHeight(),
|
||||
Bitmap.Config.ARGB_8888);
|
||||
Canvas c = new Canvas(mBmp);
|
||||
c.translate(-getScrollX(), -getScrollY());
|
||||
super.dispatchDraw(c);
|
||||
BitmapDrawable b = new BitmapDrawable(getResources(), mBmp);
|
||||
DrawableTransition.transit(b, false, 3000);
|
||||
setBackgroundDrawable(b);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow();
|
||||
setBackgroundDrawable(null);
|
||||
if (mBmp != null && !mBmp.isRecycled())
|
||||
mBmp.recycle();
|
||||
}
|
||||
}
|
||||
@@ -1,889 +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.widget.recyclerview;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.support.v4.util.LongSparseArray;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.StaggeredGridLayoutManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.SparseBooleanArray;
|
||||
import android.util.TypedValue;
|
||||
import android.view.ActionMode;
|
||||
import android.view.InputDevice;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AbsListView;
|
||||
import android.widget.Checkable;
|
||||
import android.widget.ListAdapter;
|
||||
|
||||
/**
|
||||
*
|
||||
* Get some code from twoway-view and AbsListView
|
||||
*
|
||||
* @author Hippo
|
||||
*
|
||||
*/
|
||||
public class EasyRecyclerView extends RecyclerView implements View.OnClickListener,
|
||||
View.OnLongClickListener {
|
||||
|
||||
private static final String TAG = EasyRecyclerView.class.getSimpleName();
|
||||
|
||||
private static final String STATE_KEY_CHOICE_MODE = "choiceMode";
|
||||
private static final String STATE_KEY_CHECKED_STATES = "checkedStates";
|
||||
private static final String STATE_KEY_CHECKED_ID_STATES = "checkedIdStates";
|
||||
private static final String STATE_KEY_CHECKED_COUNT = "checkedCount";
|
||||
|
||||
/**
|
||||
* Represents an invalid position. All valid positions are in the range 0 to 1 less than the
|
||||
* number of items in the current adapter.
|
||||
*/
|
||||
public static final int INVALID_POSITION = -1;
|
||||
|
||||
/**
|
||||
* Normal list that does not indicate choices
|
||||
*/
|
||||
public static final int CHOICE_MODE_NONE = 0;
|
||||
|
||||
/**
|
||||
* The list allows up to one choice
|
||||
*/
|
||||
public static final int CHOICE_MODE_SINGLE = 1;
|
||||
|
||||
/**
|
||||
* The list allows multiple choices
|
||||
*/
|
||||
public static final int CHOICE_MODE_MULTIPLE = 2;
|
||||
|
||||
/**
|
||||
* The list allows multiple choices in a modal selection mode
|
||||
*/
|
||||
public static final int CHOICE_MODE_MULTIPLE_MODAL = 3;
|
||||
|
||||
/**
|
||||
* Controls if/how the user may choose/check items in the list
|
||||
*/
|
||||
private int mChoiceMode = CHOICE_MODE_NONE;
|
||||
|
||||
/**
|
||||
* Controls CHOICE_MODE_MULTIPLE_MODAL. null when inactive.
|
||||
*/
|
||||
private ActionMode mChoiceActionMode;
|
||||
|
||||
/**
|
||||
* Wrapper for the multiple choice mode callback; AbsListView needs to perform
|
||||
* a few extra actions around what application code does.
|
||||
*/
|
||||
MultiChoiceModeWrapper mMultiChoiceModeCallback;
|
||||
|
||||
/**
|
||||
* Running count of how many items are currently checked
|
||||
*/
|
||||
private int mCheckedItemCount;
|
||||
|
||||
/**
|
||||
* Running state of which positions are currently checked
|
||||
*/
|
||||
private SparseBooleanArray mCheckStates;
|
||||
|
||||
/**
|
||||
* Running state of which IDs are currently checked.
|
||||
* If there is a value for a given key, the checked state for that ID is true
|
||||
* and the value holds the last known position in the adapter for that id.
|
||||
*/
|
||||
private LongSparseArray<Integer> mCheckedIdStates;
|
||||
|
||||
private OnItemClickListener mOnItemClickListener;
|
||||
private OnItemLongClickListener mOnItemLongClickListener;
|
||||
private boolean mNeedOnClickListener = false;
|
||||
private boolean mNeedOnLongClickListener = false;
|
||||
|
||||
private FooterAdapter mAdapter;
|
||||
|
||||
private float mVerticalScrollFactor = 0;
|
||||
|
||||
public EasyRecyclerView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public EasyRecyclerView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public EasyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
public View getFootView() {
|
||||
if (mAdapter != null)
|
||||
return mAdapter.getFooterView();
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isNeedOnClickListener() {
|
||||
if (mOnItemClickListener == null && mChoiceMode == CHOICE_MODE_NONE)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isNeedOnLongClickListener() {
|
||||
if (mOnItemLongClickListener != null || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
private void setAllOnClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnClickListener(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAllOnClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnClickListener(null);
|
||||
child.setClickable(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setAllOnLongClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnLongClickListener(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAllOnLongClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnLongClickListener(null);
|
||||
child.setLongClickable(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateOnClickState() {
|
||||
boolean newNeedOnClickListener = isNeedOnClickListener();
|
||||
if (mNeedOnClickListener != newNeedOnClickListener) {
|
||||
mNeedOnClickListener = newNeedOnClickListener;
|
||||
if (mNeedOnClickListener)
|
||||
setAllOnClickListener();
|
||||
else
|
||||
resetAllOnClickListener();
|
||||
}
|
||||
}
|
||||
|
||||
public void updateOnLongClickState() {
|
||||
boolean newNeedOnLongClickListener = isNeedOnLongClickListener();
|
||||
if (mNeedOnLongClickListener != newNeedOnLongClickListener) {
|
||||
mNeedOnLongClickListener = newNeedOnLongClickListener;
|
||||
if (mNeedOnLongClickListener)
|
||||
setAllOnLongClickListener();
|
||||
else
|
||||
resetAllOnLongClickListener();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback to be invoked when an item in the
|
||||
* RecyclerView has been clicked.
|
||||
*
|
||||
* @param listener The callback that will be invoked.
|
||||
*/
|
||||
public void setOnItemClickListener(OnItemClickListener listener) {
|
||||
mOnItemClickListener = listener;
|
||||
updateOnClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback to be invoked when an item in the
|
||||
* RecyclerView has been clicked and held.
|
||||
*
|
||||
* @param listener The callback that will be invoked.
|
||||
*/
|
||||
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
|
||||
mOnItemLongClickListener = listener;
|
||||
updateOnLongClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* adapter must be {@link com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView.FooterAdapter}
|
||||
*/
|
||||
@Override
|
||||
public void setAdapter(RecyclerView.Adapter adapter) {
|
||||
super.setAdapter(adapter);
|
||||
|
||||
mAdapter = (FooterAdapter) adapter;
|
||||
mAdapter.mHolder = this;
|
||||
if (adapter != null) {
|
||||
if (mChoiceMode != CHOICE_MODE_NONE && adapter.hasStableIds() &&
|
||||
mCheckedIdStates == null) {
|
||||
mCheckedIdStates = new LongSparseArray<Integer>();
|
||||
}
|
||||
}
|
||||
|
||||
if (mCheckStates != null) {
|
||||
mCheckStates.clear();
|
||||
}
|
||||
|
||||
if (mCheckedIdStates != null) {
|
||||
mCheckedIdStates.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of items currently selected. This will only be valid
|
||||
* if the choice mode is not {@link #CHOICE_MODE_NONE} (default).
|
||||
*
|
||||
* <p>To determine the specific items that are currently selected, use one of
|
||||
* the <code>getChecked*</code> methods.
|
||||
*
|
||||
* @return The number of items currently selected
|
||||
*
|
||||
* @see #getCheckedItemPosition()
|
||||
* @see #getCheckedItemPositions()
|
||||
* @see #getCheckedItemIds()
|
||||
*/
|
||||
public int getCheckedItemCount() {
|
||||
return mCheckedItemCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the checked state of the specified position. The result is only
|
||||
* valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
|
||||
* or {@link #CHOICE_MODE_MULTIPLE}.
|
||||
*
|
||||
* @param position The item whose checked state to return
|
||||
* @return The item's checked state or <code>false</code> if choice mode
|
||||
* is invalid
|
||||
*
|
||||
* @see #setChoiceMode(int)
|
||||
*/
|
||||
public boolean isItemChecked(int position) {
|
||||
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
|
||||
return mCheckStates.get(position);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently checked item. The result is only valid if the choice
|
||||
* mode has been set to {@link #CHOICE_MODE_SINGLE}.
|
||||
*
|
||||
* @return The position of the currently checked item or
|
||||
* {@link #INVALID_POSITION} if nothing is selected
|
||||
*
|
||||
* @see #setChoiceMode(int)
|
||||
*/
|
||||
public int getCheckedItemPosition() {
|
||||
if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) {
|
||||
return mCheckStates.keyAt(0);
|
||||
}
|
||||
|
||||
return INVALID_POSITION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the set of checked items in the list. The result is only valid if
|
||||
* the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
|
||||
*
|
||||
* @return A SparseBooleanArray which will return true for each call to
|
||||
* get(int position) where position is a checked position in the
|
||||
* list and false otherwise, or <code>null</code> if the choice
|
||||
* mode is set to {@link #CHOICE_MODE_NONE}.
|
||||
*/
|
||||
public SparseBooleanArray getCheckedItemPositions() {
|
||||
if (mChoiceMode != CHOICE_MODE_NONE) {
|
||||
return mCheckStates;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the set of checked items ids. The result is only valid if the
|
||||
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
|
||||
* has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
|
||||
*
|
||||
* @return A new array which contains the id of each checked item in the
|
||||
* list.
|
||||
*/
|
||||
public long[] getCheckedItemIds() {
|
||||
if (mChoiceMode == CHOICE_MODE_NONE || mCheckedIdStates == null || mAdapter == null) {
|
||||
return new long[0];
|
||||
}
|
||||
|
||||
final LongSparseArray<Integer> idStates = mCheckedIdStates;
|
||||
final int count = idStates.size();
|
||||
final long[] ids = new long[count];
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
ids[i] = idStates.keyAt(i);
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any choices previously set
|
||||
*/
|
||||
public void clearChoices() {
|
||||
if (mCheckStates != null) {
|
||||
mCheckStates.clear();
|
||||
}
|
||||
if (mCheckedIdStates != null) {
|
||||
mCheckedIdStates.clear();
|
||||
}
|
||||
mCheckedItemCount = 0;
|
||||
updateOnScreenCheckedViews();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the checked state of the specified position. The is only valid if
|
||||
* the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
|
||||
* {@link #CHOICE_MODE_MULTIPLE}.
|
||||
*
|
||||
* @param position The item whose checked state is to be checked
|
||||
* @param value The new checked state for the item
|
||||
*/
|
||||
public void setItemChecked(int position, boolean value) {
|
||||
if (mChoiceMode == CHOICE_MODE_NONE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Start selection mode if needed. We don't need to if we're unchecking something.
|
||||
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
|
||||
if (mMultiChoiceModeCallback == null ||
|
||||
!mMultiChoiceModeCallback.hasWrappedCallback()) {
|
||||
throw new IllegalStateException("AbsListView: attempted to start selection mode " +
|
||||
"for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " +
|
||||
"supplied. Call setMultiChoiceModeListener to set a callback.");
|
||||
}
|
||||
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
|
||||
}
|
||||
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
|
||||
boolean oldValue = mCheckStates.get(position);
|
||||
mCheckStates.put(position, value);
|
||||
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
|
||||
if (value) {
|
||||
mCheckedIdStates.put(mAdapter.getItemId(position), position);
|
||||
} else {
|
||||
mCheckedIdStates.delete(mAdapter.getItemId(position));
|
||||
}
|
||||
}
|
||||
if (oldValue != value) {
|
||||
if (value) {
|
||||
mCheckedItemCount++;
|
||||
} else {
|
||||
mCheckedItemCount--;
|
||||
}
|
||||
}
|
||||
if (mChoiceActionMode != null) {
|
||||
final long id = mAdapter.getItemId(position);
|
||||
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
|
||||
position, id, value);
|
||||
}
|
||||
} else {
|
||||
boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds();
|
||||
// Clear all values if we're checking something, or unchecking the currently
|
||||
// selected item
|
||||
if (value || isItemChecked(position)) {
|
||||
mCheckStates.clear();
|
||||
if (updateIds) {
|
||||
mCheckedIdStates.clear();
|
||||
}
|
||||
}
|
||||
// this may end up selecting the value we just cleared but this way
|
||||
// we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on
|
||||
if (value) {
|
||||
mCheckStates.put(position, true);
|
||||
if (updateIds) {
|
||||
mCheckedIdStates.put(mAdapter.getItemId(position), position);
|
||||
}
|
||||
mCheckedItemCount = 1;
|
||||
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
|
||||
mCheckedItemCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
updateOnScreenCheckedViews();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setChoiceMode(int)
|
||||
*
|
||||
* @return The current choice mode
|
||||
*/
|
||||
public int getChoiceMode() {
|
||||
return mChoiceMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the choice behavior for the List. By default, Lists do not have any choice behavior
|
||||
* ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the
|
||||
* List allows up to one item to be in a chosen state. By setting the choiceMode to
|
||||
* {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
|
||||
*
|
||||
* @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or
|
||||
* {@link #CHOICE_MODE_MULTIPLE}
|
||||
*/
|
||||
public void setChoiceMode(int choiceMode) {
|
||||
mChoiceMode = choiceMode;
|
||||
if (mChoiceActionMode != null) {
|
||||
mChoiceActionMode.finish();
|
||||
mChoiceActionMode = null;
|
||||
}
|
||||
if (mChoiceMode != CHOICE_MODE_NONE) {
|
||||
if (mCheckStates == null) {
|
||||
mCheckStates = new SparseBooleanArray(0);
|
||||
}
|
||||
if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) {
|
||||
mCheckedIdStates = new LongSparseArray<Integer>(0);
|
||||
}
|
||||
// Modal multi-choice mode only has choices when the mode is active. Clear them.
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
|
||||
clearChoices();
|
||||
}
|
||||
}
|
||||
|
||||
updateOnClickState();
|
||||
updateOnLongClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a {@link MultiChoiceModeListener} that will manage the lifecycle of the
|
||||
* selection {@link ActionMode}. Only used when the choice mode is set to
|
||||
* {@link #CHOICE_MODE_MULTIPLE_MODAL}.
|
||||
*
|
||||
* @param listener Listener that will manage the selection mode
|
||||
*
|
||||
* @see #setChoiceMode(int)
|
||||
*/
|
||||
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
|
||||
if (mMultiChoiceModeCallback == null) {
|
||||
mMultiChoiceModeCallback = new MultiChoiceModeWrapper();
|
||||
}
|
||||
mMultiChoiceModeCallback.setWrapped(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a quick, in-place update of the checked or activated state
|
||||
* on all visible item views. This should only be called when a valid
|
||||
* choice mode is active.
|
||||
*/
|
||||
private void updateOnScreenCheckedViews() {
|
||||
final int count = getChildCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
final View child = getChildAt(i);
|
||||
final int position = getChildPosition(child);
|
||||
setViewChecked(child, mCheckStates.get(position));
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
|
||||
public static void setViewChecked(View view, boolean checked) {
|
||||
final boolean useActivated = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
|
||||
if (view instanceof Checkable) {
|
||||
((Checkable) view).setChecked(checked);
|
||||
} else if (useActivated) {
|
||||
view.setActivated(checked);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onGenericMotionEvent(MotionEvent event) {
|
||||
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
|
||||
switch (event.getAction()) {
|
||||
case MotionEvent.ACTION_SCROLL: {
|
||||
if (getScrollState() != SCROLL_STATE_DRAGGING) {
|
||||
final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
|
||||
if (vscroll != 0) {
|
||||
final int delta = (int) (vscroll * getVerticalScrollFactor());
|
||||
scrollBy(0, -delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.onGenericMotionEvent(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a scale factor that determines the distance the view should scroll
|
||||
* vertically in response to {@link MotionEvent#ACTION_SCROLL}.
|
||||
* @return The vertical scroll scale factor.
|
||||
*/
|
||||
protected float getVerticalScrollFactor() {
|
||||
if (mVerticalScrollFactor == 0) {
|
||||
TypedValue outValue = new TypedValue();
|
||||
if (!getContext().getTheme().resolveAttribute(
|
||||
0x0101004d, outValue, true)) {//com.android.internal.R.attr.listPreferredItemHeight
|
||||
throw new IllegalStateException(
|
||||
"Expected theme to define listPreferredItemHeight.");
|
||||
}
|
||||
mVerticalScrollFactor = outValue.getDimension(
|
||||
getContext().getResources().getDisplayMetrics());
|
||||
}
|
||||
return mVerticalScrollFactor;
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public Parcelable onSaveInstanceState() {
|
||||
final Parcelable state = new Bundle(super.onSaveInstanceState());
|
||||
|
||||
state.putInt(STATE_KEY_CHOICE_MODE, mChoiceMode);
|
||||
state.putParcelable(STATE_KEY_CHECKED_STATES, mCheckStates);
|
||||
state.putParcelable(STATE_KEY_CHECKED_ID_STATES, mCheckedIdStates);
|
||||
state.putInt(STATE_KEY_CHECKED_COUNT, mCheckedItemCount);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
public void onRestoreInstanceState(Bundle state) {
|
||||
mChoiceMode = ChoiceMode.values()[state.getInt(STATE_KEY_CHOICE_MODE)];
|
||||
mCheckedStates = state.getParcelable(STATE_KEY_CHECKED_STATES);
|
||||
mCheckedIdStates = state.getParcelable(STATE_KEY_CHECKED_ID_STATES);
|
||||
mCheckedCount = state.getInt(STATE_KEY_CHECKED_COUNT);
|
||||
|
||||
// TODO confirm ids here
|
||||
}*/
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked.
|
||||
*/
|
||||
public interface OnItemClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened.
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the adapter.
|
||||
* @param id The row id of the item that was clicked.
|
||||
*
|
||||
* @return true if the callback consumed the click, false otherwise
|
||||
*/
|
||||
boolean onItemClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked and held.
|
||||
*/
|
||||
public interface OnItemLongClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked and held.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the list
|
||||
* @param id The row id of the item that was clicked
|
||||
*
|
||||
* @return true if the callback consumed the long click, false otherwise
|
||||
*/
|
||||
boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* EasyRecyclerView.OnItemTouchListener will not work fine
|
||||
* when item view's child need click action, because they make
|
||||
* touch event deliver different
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
final int position = getChildPosition(view);
|
||||
final long id = mAdapter.getItemId(position);
|
||||
|
||||
boolean dispatchItemClick = true;
|
||||
|
||||
if (mChoiceMode != CHOICE_MODE_NONE) {
|
||||
boolean checkedStateChanged = false;
|
||||
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE ||
|
||||
(mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) {
|
||||
boolean checked = !mCheckStates.get(position, false);
|
||||
mCheckStates.put(position, checked);
|
||||
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
|
||||
if (checked) {
|
||||
mCheckedIdStates.put(mAdapter.getItemId(position), position);
|
||||
} else {
|
||||
mCheckedIdStates.delete(mAdapter.getItemId(position));
|
||||
}
|
||||
}
|
||||
if (checked) {
|
||||
mCheckedItemCount++;
|
||||
} else {
|
||||
mCheckedItemCount--;
|
||||
}
|
||||
if (mChoiceActionMode != null) {
|
||||
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
|
||||
position, id, checked);
|
||||
dispatchItemClick = false;
|
||||
}
|
||||
checkedStateChanged = true;
|
||||
} else if (mChoiceMode == CHOICE_MODE_SINGLE) {
|
||||
boolean checked = !mCheckStates.get(position, false);
|
||||
if (checked) {
|
||||
mCheckStates.clear();
|
||||
mCheckStates.put(position, true);
|
||||
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
|
||||
mCheckedIdStates.clear();
|
||||
mCheckedIdStates.put(mAdapter.getItemId(position), position);
|
||||
}
|
||||
mCheckedItemCount = 1;
|
||||
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
|
||||
mCheckedItemCount = 0;
|
||||
}
|
||||
checkedStateChanged = true;
|
||||
}
|
||||
|
||||
if (checkedStateChanged) {
|
||||
updateOnScreenCheckedViews();
|
||||
}
|
||||
}
|
||||
|
||||
if (dispatchItemClick && mOnItemClickListener != null) {
|
||||
mOnItemClickListener.onItemClick(this, view, position, id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean onLongClick(View view) {
|
||||
final int position = getChildPosition(view);
|
||||
final long id = mAdapter.getItemId(position);
|
||||
|
||||
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
|
||||
if (mChoiceActionMode == null &&
|
||||
(mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
|
||||
setItemChecked(position, true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean handled = false;
|
||||
if (mOnItemLongClickListener != null) {
|
||||
handled = mOnItemLongClickListener.onItemLongClick(this, view,
|
||||
position, id);
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
/**
|
||||
* A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
|
||||
* It acts as the {@link ActionMode.Callback} for the selection mode and also receives
|
||||
* {@link #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user
|
||||
* selects and deselects list items.
|
||||
*/
|
||||
public interface MultiChoiceModeListener extends ActionMode.Callback {
|
||||
/**
|
||||
* Called when an item is checked or unchecked during selection mode.
|
||||
*
|
||||
* @param mode The {@link ActionMode} providing the selection mode
|
||||
* @param position Adapter position of the item that was checked or unchecked
|
||||
* @param id Adapter ID of the item that was checked or unchecked
|
||||
* @param checked <code>true</code> if the item is now checked, <code>false</code>
|
||||
* if the item is now unchecked.
|
||||
*/
|
||||
public void onItemCheckedStateChanged(ActionMode mode,
|
||||
int position, long id, boolean checked);
|
||||
}
|
||||
|
||||
class MultiChoiceModeWrapper implements MultiChoiceModeListener {
|
||||
private MultiChoiceModeListener mWrapped;
|
||||
|
||||
public void setWrapped(MultiChoiceModeListener wrapped) {
|
||||
mWrapped = wrapped;
|
||||
}
|
||||
|
||||
public boolean hasWrappedCallback() {
|
||||
return mWrapped != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
|
||||
if (mWrapped.onCreateActionMode(mode, menu)) {
|
||||
// Initialize checked graphic state?
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
|
||||
return mWrapped.onPrepareActionMode(mode, menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
|
||||
return mWrapped.onActionItemClicked(mode, item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyActionMode(ActionMode mode) {
|
||||
mWrapped.onDestroyActionMode(mode);
|
||||
mChoiceActionMode = null;
|
||||
|
||||
// Ending selection mode means deselecting everything.
|
||||
clearChoices();
|
||||
|
||||
requestLayout();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onItemCheckedStateChanged(ActionMode mode,
|
||||
int position, long id, boolean checked) {
|
||||
mWrapped.onItemCheckedStateChanged(mode, position, id, checked);
|
||||
|
||||
// If there are no items selected we no longer need the selection mode.
|
||||
if (getCheckedItemCount() == 0) {
|
||||
mode.finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class FooterAdapter<VH extends ViewHolder> extends RecyclerView.Adapter<VH> {
|
||||
|
||||
public static final int TYPE_FOOTER = Integer.MAX_VALUE;
|
||||
|
||||
private EasyRecyclerView mHolder;
|
||||
private View mFooterView;
|
||||
|
||||
public boolean hasFootView() {
|
||||
return mFooterView != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* footerView == null to remove foot view
|
||||
* @param footerView
|
||||
*/
|
||||
public void setFooterView(View footerView) {
|
||||
if (mFooterView == footerView)
|
||||
return;
|
||||
|
||||
int itemCountActual = getItemCountActual();
|
||||
View originView = mFooterView;
|
||||
mFooterView = footerView;
|
||||
if (originView != null) {
|
||||
if (mFooterView != null)
|
||||
notifyItemChanged(itemCountActual);
|
||||
else
|
||||
notifyItemRemoved(itemCountActual);
|
||||
} else {
|
||||
notifyItemInserted(itemCountActual);
|
||||
}
|
||||
}
|
||||
|
||||
public View getFooterView() {
|
||||
return mFooterView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
if (mFooterView != null && viewType == TYPE_FOOTER) {
|
||||
StaggeredGridLayoutManager.LayoutParams lp = new StaggeredGridLayoutManager.LayoutParams(
|
||||
StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT,
|
||||
StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT);
|
||||
lp.setFullSpan(true);
|
||||
mFooterView.setLayoutParams(lp);
|
||||
return onCreateAndBindFooterViewHolder(parent, mFooterView);
|
||||
} else {
|
||||
return onCreateViewHolderActual(parent, viewType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onBindViewHolder(VH holder, int position) {
|
||||
if (mFooterView == null || position != getItemCountActual()) {
|
||||
onBindViewHolderActual(holder, position);
|
||||
if (mHolder.mNeedOnClickListener)
|
||||
holder.itemView.setOnClickListener(mHolder);
|
||||
if (mHolder.mNeedOnLongClickListener)
|
||||
holder.itemView.setOnLongClickListener(mHolder);
|
||||
EasyRecyclerView.setViewChecked(holder.itemView,
|
||||
mHolder.isItemChecked(position));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getItemViewType(int position) {
|
||||
if (mFooterView != null && position == getItemCountActual())
|
||||
return TYPE_FOOTER;
|
||||
else
|
||||
return getItemViewTypeActual(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getItemCount() {
|
||||
int itemCount = getItemCountActual();
|
||||
if (mFooterView != null)
|
||||
itemCount++;
|
||||
return itemCount;
|
||||
}
|
||||
|
||||
public abstract VH onCreateAndBindFooterViewHolder(ViewGroup parent, View footerView);
|
||||
|
||||
public abstract VH onCreateViewHolderActual(ViewGroup parent, int viewType);
|
||||
|
||||
public abstract void onBindViewHolderActual(VH holder, int position);
|
||||
|
||||
/**
|
||||
* Foot view type is Integer.MAX_VALUE, do not be the same
|
||||
*
|
||||
* @param position
|
||||
* @return
|
||||
*/
|
||||
public int getItemViewTypeActual(int position) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public abstract int getItemCountActual();
|
||||
|
||||
}
|
||||
}
|
||||
-162
@@ -1,162 +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.widget.recyclerview;
|
||||
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.View;
|
||||
|
||||
public class LinearDividerItemDecoration extends RecyclerView.ItemDecoration {
|
||||
public static final int HORIZONTAL = LinearLayoutManager.HORIZONTAL;
|
||||
public static final int VERTICAL = LinearLayoutManager.VERTICAL;
|
||||
|
||||
private boolean mShowFirstDivider = false;
|
||||
private boolean mShowLastDivider = false;
|
||||
|
||||
private final Rect mRect;
|
||||
private final Paint mPaint;
|
||||
|
||||
private int mOrientation;
|
||||
private int mThickness;
|
||||
private int mPaddingStart = 0;
|
||||
private int mPaddingEnd = 0;
|
||||
|
||||
public LinearDividerItemDecoration(int orientation, int color, int thickness) {
|
||||
mRect = new Rect();
|
||||
mPaint = new Paint();
|
||||
mPaint.setStyle(Paint.Style.FILL);
|
||||
setOrientation(orientation);
|
||||
setColor(color);
|
||||
setThickness(thickness);
|
||||
}
|
||||
|
||||
public void setOrientation(int orientation) {
|
||||
if (orientation != HORIZONTAL && orientation != VERTICAL) {
|
||||
throw new IllegalArgumentException("invalid orientation");
|
||||
}
|
||||
mOrientation = orientation;
|
||||
}
|
||||
|
||||
public void setColor(int color) {
|
||||
mPaint.setColor(color);
|
||||
}
|
||||
|
||||
public void setThickness(int thickness) {
|
||||
mThickness = thickness;
|
||||
}
|
||||
|
||||
public void setShowFirstDivider(boolean showFirstDivider) {
|
||||
mShowFirstDivider = showFirstDivider;
|
||||
}
|
||||
|
||||
public void setShowLastDivider(boolean showLastDivider) {
|
||||
mShowLastDivider = showLastDivider;
|
||||
}
|
||||
|
||||
public void setPadding(int padding) {
|
||||
setPaddingStart(padding);
|
||||
setPaddingEnd(padding);
|
||||
}
|
||||
|
||||
public void setPaddingStart(int paddingStart) {
|
||||
mPaddingStart = paddingStart;
|
||||
}
|
||||
|
||||
public void setPaddingEnd(int paddingEnd) {
|
||||
mPaddingEnd = paddingEnd;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getItemOffsets(Rect outRect, View view,
|
||||
RecyclerView parent, RecyclerView.State state) {
|
||||
final int position = parent.getChildPosition(view);
|
||||
final int itemCount = parent.getAdapter().getItemCount();
|
||||
if (mOrientation == VERTICAL) {
|
||||
if (position == 0 && mShowFirstDivider)
|
||||
outRect.top = mThickness;
|
||||
outRect.bottom = mThickness;
|
||||
if (position == itemCount - 1 && !mShowLastDivider)
|
||||
outRect.bottom = 0;
|
||||
} else {
|
||||
if (position == 0 && mShowFirstDivider)
|
||||
outRect.left = mThickness;
|
||||
outRect.right = mThickness;
|
||||
if (position == itemCount - 1 && !mShowLastDivider)
|
||||
outRect.left = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDrawOver(Canvas c, RecyclerView parent,
|
||||
RecyclerView.State state) {
|
||||
int itemCount = parent.getAdapter().getItemCount();
|
||||
|
||||
if (mOrientation == VERTICAL) {
|
||||
final int left = parent.getPaddingLeft() + mPaddingStart;
|
||||
final int right = parent.getWidth() - parent.getPaddingRight() - mPaddingEnd;
|
||||
final int childCount = parent.getChildCount();
|
||||
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
final View child = parent.getChildAt(i);
|
||||
final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
|
||||
|
||||
if (i != childCount - 1 || mShowLastDivider
|
||||
|| parent.getChildPosition(child) != itemCount - 1) {
|
||||
final int top = child.getBottom() + lp.bottomMargin;
|
||||
final int bottom = top + mThickness;
|
||||
mRect.set(left, top, right, bottom);
|
||||
c.drawRect(mRect, mPaint);
|
||||
}
|
||||
|
||||
if (i == 0 && mShowFirstDivider && parent.getChildPosition(child) == 0) {
|
||||
final int bottom = child.getTop() + lp.topMargin;
|
||||
final int top = bottom - mThickness;
|
||||
mRect.set(left, top, right, bottom);
|
||||
c.drawRect(mRect, mPaint);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final int top = parent.getPaddingTop() + mPaddingStart;
|
||||
final int bottom = parent.getHeight() - parent.getPaddingBottom() - mPaddingEnd;
|
||||
final int childCount = parent.getChildCount();
|
||||
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
final View child = parent.getChildAt(i);
|
||||
final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
|
||||
|
||||
if (i != childCount - 1 || mShowLastDivider
|
||||
|| parent.getChildPosition(child) != itemCount - 1) {
|
||||
final int left = child.getRight() + lp.rightMargin;
|
||||
final int right = left + mThickness;
|
||||
mRect.set(left, top, right, bottom);
|
||||
c.drawRect(mRect, mPaint);
|
||||
}
|
||||
|
||||
if (i == 0 && mShowFirstDivider && parent.getChildPosition(child) == 0) {
|
||||
final int right = child.getLeft() + lp.leftMargin;
|
||||
final int left = right - mThickness;
|
||||
mRect.set(left, top, right, bottom);
|
||||
c.drawRect(mRect, mPaint);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +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.widget.recyclerview;
|
||||
|
||||
import android.graphics.Rect;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* Only work for StaggeredGridLayoutManager, FooterAdapter
|
||||
*
|
||||
* @author Hippo
|
||||
*
|
||||
*/
|
||||
public class MarginItemDecoration extends RecyclerView.ItemDecoration {
|
||||
|
||||
private int mHalfMargin;
|
||||
|
||||
@Override
|
||||
public void getItemOffsets(Rect outRect, View view,
|
||||
RecyclerView parent, RecyclerView.State state) {
|
||||
outRect.set(mHalfMargin, mHalfMargin, mHalfMargin, mHalfMargin);
|
||||
}
|
||||
|
||||
public void setMargin(int margin) {
|
||||
mHalfMargin = margin / 2;
|
||||
}
|
||||
|
||||
public int getMargin() {
|
||||
return mHalfMargin * 2;
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.widget.refreshlayout;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RadialGradient;
|
||||
import android.graphics.Shader;
|
||||
import android.graphics.drawable.ShapeDrawable;
|
||||
import android.graphics.drawable.shapes.OvalShape;
|
||||
import android.support.v4.view.ViewCompat;
|
||||
import android.view.animation.Animation;
|
||||
import android.widget.ImageView;
|
||||
|
||||
/**
|
||||
* Private class created to work around issues with AnimationListeners being
|
||||
* called before the animation is actually complete and support shadows on older
|
||||
* platforms.
|
||||
*
|
||||
* @hide
|
||||
*/
|
||||
class CircleImageView extends ImageView {
|
||||
|
||||
private static final int KEY_SHADOW_COLOR = 0x1E000000;
|
||||
private static final int FILL_SHADOW_COLOR = 0x3D000000;
|
||||
// PX
|
||||
private static final float X_OFFSET = 0f;
|
||||
private static final float Y_OFFSET = 1.75f;
|
||||
private static final float SHADOW_RADIUS = 3.5f;
|
||||
private static final int SHADOW_ELEVATION = 4;
|
||||
|
||||
private Animation.AnimationListener mListener;
|
||||
private int mShadowRadius;
|
||||
|
||||
public CircleImageView(Context context, int color, final float radius) {
|
||||
super(context);
|
||||
final float density = getContext().getResources().getDisplayMetrics().density;
|
||||
final int diameter = (int) (radius * density * 2);
|
||||
final int shadowYOffset = (int) (density * Y_OFFSET);
|
||||
final int shadowXOffset = (int) (density * X_OFFSET);
|
||||
|
||||
mShadowRadius = (int) (density * SHADOW_RADIUS);
|
||||
|
||||
ShapeDrawable circle;
|
||||
if (elevationSupported()) {
|
||||
circle = new ShapeDrawable(new OvalShape());
|
||||
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
|
||||
} else {
|
||||
OvalShape oval = new OvalShadow(mShadowRadius, diameter);
|
||||
circle = new ShapeDrawable(oval);
|
||||
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint());
|
||||
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
|
||||
KEY_SHADOW_COLOR);
|
||||
final int padding = mShadowRadius;
|
||||
// set padding so the inner image sits correctly within the shadow.
|
||||
setPadding(padding, padding, padding, padding);
|
||||
}
|
||||
circle.getPaint().setColor(color);
|
||||
setBackgroundDrawable(circle);
|
||||
}
|
||||
|
||||
private boolean elevationSupported() {
|
||||
return android.os.Build.VERSION.SDK_INT >= 21;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
|
||||
if (!elevationSupported()) {
|
||||
setMeasuredDimension(getMeasuredWidth() + mShadowRadius*2, getMeasuredHeight()
|
||||
+ mShadowRadius*2);
|
||||
}
|
||||
}
|
||||
|
||||
public void setAnimationListener(Animation.AnimationListener listener) {
|
||||
mListener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationStart() {
|
||||
super.onAnimationStart();
|
||||
if (mListener != null) {
|
||||
mListener.onAnimationStart(getAnimation());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd() {
|
||||
super.onAnimationEnd();
|
||||
if (mListener != null) {
|
||||
mListener.onAnimationEnd(getAnimation());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the background color of the circle image view.
|
||||
*
|
||||
* @param colorRes Id of a color resource.
|
||||
*/
|
||||
public void setBackgroundColorRes(int colorRes) {
|
||||
setBackgroundColor(getContext().getResources().getColor(colorRes));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBackgroundColor(int color) {
|
||||
if (getBackground() instanceof ShapeDrawable) {
|
||||
((ShapeDrawable) getBackground()).getPaint().setColor(color);
|
||||
}
|
||||
}
|
||||
|
||||
private class OvalShadow extends OvalShape {
|
||||
private RadialGradient mRadialGradient;
|
||||
private int mShadowRadius;
|
||||
private Paint mShadowPaint;
|
||||
private int mCircleDiameter;
|
||||
|
||||
public OvalShadow(int shadowRadius, int circleDiameter) {
|
||||
super();
|
||||
mShadowPaint = new Paint();
|
||||
mShadowRadius = shadowRadius;
|
||||
mCircleDiameter = circleDiameter;
|
||||
mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2,
|
||||
mShadowRadius, new int[] {
|
||||
FILL_SHADOW_COLOR, Color.TRANSPARENT
|
||||
}, null, Shader.TileMode.CLAMP);
|
||||
mShadowPaint.setShader(mRadialGradient);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas, Paint paint) {
|
||||
final int viewWidth = CircleImageView.this.getWidth();
|
||||
final int viewHeight = CircleImageView.this.getHeight();
|
||||
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
|
||||
mShadowPaint);
|
||||
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
|
||||
}
|
||||
}
|
||||
}
|
||||
-714
@@ -1,714 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.widget.refreshlayout;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Paint.Style;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Animatable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.support.annotation.IntDef;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.View;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.view.animation.Animation;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
import android.view.animation.Transformation;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Fancy progress indicator for Material theme.
|
||||
*
|
||||
* @hide
|
||||
*/
|
||||
class MaterialProgressDrawable extends Drawable implements Animatable {
|
||||
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
|
||||
private static final Interpolator END_CURVE_INTERPOLATOR = new EndCurveInterpolator();
|
||||
private static final Interpolator START_CURVE_INTERPOLATOR = new StartCurveInterpolator();
|
||||
private static final Interpolator EASE_INTERPOLATOR = new AccelerateDecelerateInterpolator();
|
||||
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
@IntDef({LARGE, DEFAULT})
|
||||
public @interface ProgressDrawableSize {}
|
||||
// Maps to ProgressBar.Large style
|
||||
static final int LARGE = 0;
|
||||
// Maps to ProgressBar default style
|
||||
static final int DEFAULT = 1;
|
||||
|
||||
// Maps to ProgressBar default style
|
||||
private static final int CIRCLE_DIAMETER = 40;
|
||||
private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
|
||||
private static final float STROKE_WIDTH = 2.5f;
|
||||
|
||||
// Maps to ProgressBar.Large style
|
||||
private static final int CIRCLE_DIAMETER_LARGE = 56;
|
||||
private static final float CENTER_RADIUS_LARGE = 12.5f;
|
||||
private static final float STROKE_WIDTH_LARGE = 3f;
|
||||
|
||||
private final int[] COLORS = new int[] {
|
||||
Color.BLACK
|
||||
};
|
||||
|
||||
/** The duration of a single progress spin in milliseconds. */
|
||||
private static final int ANIMATION_DURATION = 1000 * 80 / 60;
|
||||
|
||||
/** The number of points in the progress "star". */
|
||||
private static final float NUM_POINTS = 5f;
|
||||
/** The list of animators operating on this drawable. */
|
||||
private final ArrayList<Animation> mAnimators = new ArrayList<Animation>();
|
||||
|
||||
/** The indicator ring, used to manage animation state. */
|
||||
private final Ring mRing;
|
||||
|
||||
/** Canvas rotation in degrees. */
|
||||
private float mRotation;
|
||||
|
||||
/** Layout info for the arrowhead in dp */
|
||||
private static final int ARROW_WIDTH = 10;
|
||||
private static final int ARROW_HEIGHT = 5;
|
||||
private static final float ARROW_OFFSET_ANGLE = 5;
|
||||
|
||||
/** Layout info for the arrowhead for the large spinner in dp */
|
||||
private static final int ARROW_WIDTH_LARGE = 12;
|
||||
private static final int ARROW_HEIGHT_LARGE = 6;
|
||||
private static final float MAX_PROGRESS_ARC = .8f;
|
||||
|
||||
private Resources mResources;
|
||||
private View mParent;
|
||||
private Animation mAnimation;
|
||||
private float mRotationCount;
|
||||
private double mWidth;
|
||||
private double mHeight;
|
||||
boolean mFinishing;
|
||||
|
||||
public MaterialProgressDrawable(Context context, View parent) {
|
||||
mParent = parent;
|
||||
mResources = context.getResources();
|
||||
|
||||
mRing = new Ring(mCallback);
|
||||
mRing.setColors(COLORS);
|
||||
|
||||
updateSizes(DEFAULT);
|
||||
setupAnimators();
|
||||
}
|
||||
|
||||
private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
|
||||
double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) {
|
||||
final Ring ring = mRing;
|
||||
final DisplayMetrics metrics = mResources.getDisplayMetrics();
|
||||
final float screenDensity = metrics.density;
|
||||
|
||||
mWidth = progressCircleWidth * screenDensity;
|
||||
mHeight = progressCircleHeight * screenDensity;
|
||||
ring.setStrokeWidth((float) strokeWidth * screenDensity);
|
||||
ring.setCenterRadius(centerRadius * screenDensity);
|
||||
ring.setColorIndex(0);
|
||||
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
|
||||
ring.setInsets((int) mWidth, (int) mHeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the overall size for the progress spinner. This updates the radius
|
||||
* and stroke width of the ring.
|
||||
*
|
||||
* @param size One of {@link #LARGE} or
|
||||
* {@link #DEFAULT}
|
||||
*/
|
||||
public void updateSizes(@ProgressDrawableSize int size) {
|
||||
if (size == LARGE) {
|
||||
setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
|
||||
STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
|
||||
} else {
|
||||
setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
|
||||
ARROW_WIDTH, ARROW_HEIGHT);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param show Set to true to display the arrowhead on the progress spinner.
|
||||
*/
|
||||
public void showArrow(boolean show) {
|
||||
mRing.setShowArrow(show);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param scale Set the scale of the arrowhead for the spinner.
|
||||
*/
|
||||
public void setArrowScale(float scale) {
|
||||
mRing.setArrowScale(scale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the start and end trim for the progress spinner arc.
|
||||
*
|
||||
* @param startAngle start angle
|
||||
* @param endAngle end angle
|
||||
*/
|
||||
public void setStartEndTrim(float startAngle, float endAngle) {
|
||||
mRing.setStartTrim(startAngle);
|
||||
mRing.setEndTrim(endAngle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the amount of rotation to apply to the progress spinner.
|
||||
*
|
||||
* @param rotation Rotation is from [0..1]
|
||||
*/
|
||||
public void setProgressRotation(float rotation) {
|
||||
mRing.setRotation(rotation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the background color of the circle image view.
|
||||
*/
|
||||
public void setBackgroundColor(int color) {
|
||||
mRing.setBackgroundColor(color);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the colors used in the progress animation from color resources.
|
||||
* The first color will also be the color of the bar that grows in response
|
||||
* to a user swipe gesture.
|
||||
*
|
||||
* @param colors
|
||||
*/
|
||||
public void setColorSchemeColors(int... colors) {
|
||||
mRing.setColors(colors);
|
||||
mRing.setColorIndex(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicHeight() {
|
||||
return (int) mHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntrinsicWidth() {
|
||||
return (int) mWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas c) {
|
||||
final Rect bounds = getBounds();
|
||||
final int saveCount = c.save();
|
||||
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
|
||||
mRing.draw(c, bounds);
|
||||
c.restoreToCount(saveCount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAlpha(int alpha) {
|
||||
mRing.setAlpha(alpha);
|
||||
}
|
||||
|
||||
public int getAlpha() {
|
||||
return mRing.getAlpha();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setColorFilter(ColorFilter colorFilter) {
|
||||
mRing.setColorFilter(colorFilter);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
void setRotation(float rotation) {
|
||||
mRotation = rotation;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private float getRotation() {
|
||||
return mRotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOpacity() {
|
||||
return PixelFormat.TRANSLUCENT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
final ArrayList<Animation> animators = mAnimators;
|
||||
final int N = animators.size();
|
||||
for (int i = 0; i < N; i++) {
|
||||
final Animation animator = animators.get(i);
|
||||
if (animator.hasStarted() && !animator.hasEnded()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
mAnimation.reset();
|
||||
mRing.storeOriginals();
|
||||
// Already showing some part of the ring
|
||||
if (mRing.getEndTrim() != mRing.getStartTrim()) {
|
||||
mFinishing = true;
|
||||
mAnimation.setDuration(ANIMATION_DURATION/2);
|
||||
mParent.startAnimation(mAnimation);
|
||||
} else {
|
||||
mRing.setColorIndex(0);
|
||||
mRing.resetOriginals();
|
||||
mAnimation.setDuration(ANIMATION_DURATION);
|
||||
mParent.startAnimation(mAnimation);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
mParent.clearAnimation();
|
||||
setRotation(0);
|
||||
mRing.setShowArrow(false);
|
||||
mRing.setColorIndex(0);
|
||||
mRing.resetOriginals();
|
||||
}
|
||||
|
||||
private void applyFinishTranslation(float interpolatedTime, Ring ring) {
|
||||
// shrink back down and complete a full rotation before
|
||||
// starting other circles
|
||||
// Rotation goes between [0..1].
|
||||
float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
|
||||
+ 1f);
|
||||
final float startTrim = ring.getStartingStartTrim()
|
||||
+ (ring.getStartingEndTrim() - ring.getStartingStartTrim()) * interpolatedTime;
|
||||
ring.setStartTrim(startTrim);
|
||||
final float rotation = ring.getStartingRotation()
|
||||
+ ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
|
||||
ring.setRotation(rotation);
|
||||
}
|
||||
|
||||
private void setupAnimators() {
|
||||
final Ring ring = mRing;
|
||||
final Animation animation = new Animation() {
|
||||
@Override
|
||||
public void applyTransformation(float interpolatedTime, Transformation t) {
|
||||
if (mFinishing) {
|
||||
applyFinishTranslation(interpolatedTime, ring);
|
||||
} else {
|
||||
// The minProgressArc is calculated from 0 to create an
|
||||
// angle that
|
||||
// matches the stroke width.
|
||||
final float minProgressArc = (float) Math.toRadians(
|
||||
ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
|
||||
final float startingEndTrim = ring.getStartingEndTrim();
|
||||
final float startingTrim = ring.getStartingStartTrim();
|
||||
final float startingRotation = ring.getStartingRotation();
|
||||
|
||||
// Offset the minProgressArc to where the endTrim is
|
||||
// located.
|
||||
final float minArc = MAX_PROGRESS_ARC - minProgressArc;
|
||||
final float endTrim = startingEndTrim + (minArc
|
||||
* START_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
|
||||
ring.setEndTrim(endTrim);
|
||||
|
||||
final float startTrim = startingTrim + (MAX_PROGRESS_ARC
|
||||
* END_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
|
||||
ring.setStartTrim(startTrim);
|
||||
|
||||
final float rotation = startingRotation + (0.25f * interpolatedTime);
|
||||
ring.setRotation(rotation);
|
||||
|
||||
float groupRotation = ((720.0f / NUM_POINTS) * interpolatedTime)
|
||||
+ (720.0f * (mRotationCount / NUM_POINTS));
|
||||
setRotation(groupRotation);
|
||||
}
|
||||
}
|
||||
};
|
||||
animation.setRepeatCount(Animation.INFINITE);
|
||||
animation.setRepeatMode(Animation.RESTART);
|
||||
animation.setInterpolator(LINEAR_INTERPOLATOR);
|
||||
animation.setAnimationListener(new Animation.AnimationListener() {
|
||||
|
||||
@Override
|
||||
public void onAnimationStart(Animation animation) {
|
||||
mRotationCount = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animation animation) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationRepeat(Animation animation) {
|
||||
ring.storeOriginals();
|
||||
ring.goToNextColor();
|
||||
ring.setStartTrim(ring.getEndTrim());
|
||||
if (mFinishing) {
|
||||
// finished closing the last ring from the swipe gesture; go
|
||||
// into progress mode
|
||||
mFinishing = false;
|
||||
animation.setDuration(ANIMATION_DURATION);
|
||||
ring.setShowArrow(false);
|
||||
} else {
|
||||
mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
|
||||
}
|
||||
}
|
||||
});
|
||||
mAnimation = animation;
|
||||
}
|
||||
|
||||
private final Callback mCallback = new Callback() {
|
||||
@Override
|
||||
public void invalidateDrawable(Drawable d) {
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scheduleDrawable(Drawable d, Runnable what, long when) {
|
||||
scheduleSelf(what, when);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unscheduleDrawable(Drawable d, Runnable what) {
|
||||
unscheduleSelf(what);
|
||||
}
|
||||
};
|
||||
|
||||
private static class Ring {
|
||||
private final RectF mTempBounds = new RectF();
|
||||
private final Paint mPaint = new Paint();
|
||||
private final Paint mArrowPaint = new Paint();
|
||||
|
||||
private final Callback mCallback;
|
||||
|
||||
private float mStartTrim = 0.0f;
|
||||
private float mEndTrim = 0.0f;
|
||||
private float mRotation = 0.0f;
|
||||
private float mStrokeWidth = 5.0f;
|
||||
private float mStrokeInset = 2.5f;
|
||||
|
||||
private int[] mColors;
|
||||
// mColorIndex represents the offset into the available mColors that the
|
||||
// progress circle should currently display. As the progress circle is
|
||||
// animating, the mColorIndex moves by one to the next available color.
|
||||
private int mColorIndex;
|
||||
private float mStartingStartTrim;
|
||||
private float mStartingEndTrim;
|
||||
private float mStartingRotation;
|
||||
private boolean mShowArrow;
|
||||
private Path mArrow;
|
||||
private float mArrowScale;
|
||||
private double mRingCenterRadius;
|
||||
private int mArrowWidth;
|
||||
private int mArrowHeight;
|
||||
private int mAlpha;
|
||||
private final Paint mCirclePaint = new Paint();
|
||||
private int mBackgroundColor;
|
||||
|
||||
public Ring(Callback callback) {
|
||||
mCallback = callback;
|
||||
|
||||
mPaint.setStrokeCap(Paint.Cap.SQUARE);
|
||||
mPaint.setAntiAlias(true);
|
||||
mPaint.setStyle(Style.STROKE);
|
||||
|
||||
mArrowPaint.setStyle(Style.FILL);
|
||||
mArrowPaint.setAntiAlias(true);
|
||||
}
|
||||
|
||||
public void setBackgroundColor(int color) {
|
||||
mBackgroundColor = color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the dimensions of the arrowhead.
|
||||
*
|
||||
* @param width Width of the hypotenuse of the arrow head
|
||||
* @param height Height of the arrow point
|
||||
*/
|
||||
public void setArrowDimensions(float width, float height) {
|
||||
mArrowWidth = (int) width;
|
||||
mArrowHeight = (int) height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the progress spinner
|
||||
*/
|
||||
public void draw(Canvas c, Rect bounds) {
|
||||
final RectF arcBounds = mTempBounds;
|
||||
arcBounds.set(bounds);
|
||||
arcBounds.inset(mStrokeInset, mStrokeInset);
|
||||
|
||||
final float startAngle = (mStartTrim + mRotation) * 360;
|
||||
final float endAngle = (mEndTrim + mRotation) * 360;
|
||||
float sweepAngle = endAngle - startAngle;
|
||||
|
||||
mPaint.setColor(mColors[mColorIndex]);
|
||||
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
|
||||
|
||||
drawTriangle(c, startAngle, sweepAngle, bounds);
|
||||
|
||||
if (mAlpha < 255) {
|
||||
mCirclePaint.setColor(mBackgroundColor);
|
||||
mCirclePaint.setAlpha(255 - mAlpha);
|
||||
c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2,
|
||||
mCirclePaint);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
|
||||
if (mShowArrow) {
|
||||
if (mArrow == null) {
|
||||
mArrow = new Path();
|
||||
mArrow.setFillType(Path.FillType.EVEN_ODD);
|
||||
} else {
|
||||
mArrow.reset();
|
||||
}
|
||||
|
||||
// Adjust the position of the triangle so that it is inset as
|
||||
// much as the arc, but also centered on the arc.
|
||||
float inset = (int) mStrokeInset / 2 * mArrowScale;
|
||||
float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
|
||||
float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());
|
||||
|
||||
// Update the path each time. This works around an issue in SKIA
|
||||
// where concatenating a rotation matrix to a scale matrix
|
||||
// ignored a starting negative rotation. This appears to have
|
||||
// been fixed as of API 21.
|
||||
mArrow.moveTo(0, 0);
|
||||
mArrow.lineTo(mArrowWidth * mArrowScale, 0);
|
||||
mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
|
||||
* mArrowScale));
|
||||
mArrow.offset(x - inset, y);
|
||||
mArrow.close();
|
||||
// draw a triangle
|
||||
mArrowPaint.setColor(mColors[mColorIndex]);
|
||||
c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
|
||||
bounds.exactCenterY());
|
||||
c.drawPath(mArrow, mArrowPaint);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the colors the progress spinner alternates between.
|
||||
*
|
||||
* @param colors Array of integers describing the colors. Must be non-<code>null</code>.
|
||||
*/
|
||||
public void setColors(@NonNull int[] colors) {
|
||||
mColors = colors;
|
||||
// if colors are reset, make sure to reset the color index as well
|
||||
setColorIndex(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index Index into the color array of the color to display in
|
||||
* the progress spinner.
|
||||
*/
|
||||
public void setColorIndex(int index) {
|
||||
mColorIndex = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Proceed to the next available ring color. This will automatically
|
||||
* wrap back to the beginning of colors.
|
||||
*/
|
||||
public void goToNextColor() {
|
||||
mColorIndex = (mColorIndex + 1) % (mColors.length);
|
||||
}
|
||||
|
||||
public void setColorFilter(ColorFilter filter) {
|
||||
mPaint.setColorFilter(filter);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param alpha Set the alpha of the progress spinner and associated arrowhead.
|
||||
*/
|
||||
public void setAlpha(int alpha) {
|
||||
mAlpha = alpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Current alpha of the progress spinner and arrowhead.
|
||||
*/
|
||||
public int getAlpha() {
|
||||
return mAlpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param strokeWidth Set the stroke width of the progress spinner in pixels.
|
||||
*/
|
||||
public void setStrokeWidth(float strokeWidth) {
|
||||
mStrokeWidth = strokeWidth;
|
||||
mPaint.setStrokeWidth(strokeWidth);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public float getStrokeWidth() {
|
||||
return mStrokeWidth;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public void setStartTrim(float startTrim) {
|
||||
mStartTrim = startTrim;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public float getStartTrim() {
|
||||
return mStartTrim;
|
||||
}
|
||||
|
||||
public float getStartingStartTrim() {
|
||||
return mStartingStartTrim;
|
||||
}
|
||||
|
||||
public float getStartingEndTrim() {
|
||||
return mStartingEndTrim;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public void setEndTrim(float endTrim) {
|
||||
mEndTrim = endTrim;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public float getEndTrim() {
|
||||
return mEndTrim;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public void setRotation(float rotation) {
|
||||
mRotation = rotation;
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public float getRotation() {
|
||||
return mRotation;
|
||||
}
|
||||
|
||||
public void setInsets(int width, int height) {
|
||||
final float minEdge = (float) Math.min(width, height);
|
||||
float insets;
|
||||
if (mRingCenterRadius <= 0 || minEdge < 0) {
|
||||
insets = (float) Math.ceil(mStrokeWidth / 2.0f);
|
||||
} else {
|
||||
insets = (float) (minEdge / 2.0f - mRingCenterRadius);
|
||||
}
|
||||
mStrokeInset = insets;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public float getInsets() {
|
||||
return mStrokeInset;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param centerRadius Inner radius in px of the circle the progress
|
||||
* spinner arc traces.
|
||||
*/
|
||||
public void setCenterRadius(double centerRadius) {
|
||||
mRingCenterRadius = centerRadius;
|
||||
}
|
||||
|
||||
public double getCenterRadius() {
|
||||
return mRingCenterRadius;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param show Set to true to show the arrow head on the progress spinner.
|
||||
*/
|
||||
public void setShowArrow(boolean show) {
|
||||
if (mShowArrow != show) {
|
||||
mShowArrow = show;
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param scale Set the scale of the arrowhead for the spinner.
|
||||
*/
|
||||
public void setArrowScale(float scale) {
|
||||
if (scale != mArrowScale) {
|
||||
mArrowScale = scale;
|
||||
invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The amount the progress spinner is currently rotated, between [0..1].
|
||||
*/
|
||||
public float getStartingRotation() {
|
||||
return mStartingRotation;
|
||||
}
|
||||
|
||||
/**
|
||||
* If the start / end trim are offset to begin with, store them so that
|
||||
* animation starts from that offset.
|
||||
*/
|
||||
public void storeOriginals() {
|
||||
mStartingStartTrim = mStartTrim;
|
||||
mStartingEndTrim = mEndTrim;
|
||||
mStartingRotation = mRotation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the progress spinner to default rotation, start and end angles.
|
||||
*/
|
||||
public void resetOriginals() {
|
||||
mStartingStartTrim = 0;
|
||||
mStartingEndTrim = 0;
|
||||
mStartingRotation = 0;
|
||||
setStartTrim(0);
|
||||
setEndTrim(0);
|
||||
setRotation(0);
|
||||
}
|
||||
|
||||
private void invalidateSelf() {
|
||||
mCallback.invalidateDrawable(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Squishes the interpolation curve into the second half of the animation.
|
||||
*/
|
||||
private static class EndCurveInterpolator extends AccelerateDecelerateInterpolator {
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
return super.getInterpolation(Math.max(0, (input - 0.5f) * 2.0f));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Squishes the interpolation curve into the first half of the animation.
|
||||
*/
|
||||
private static class StartCurveInterpolator extends AccelerateDecelerateInterpolator {
|
||||
@Override
|
||||
public float getInterpolation(float input) {
|
||||
return super.getInterpolation(Math.min(1, input * 2.0f));
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 924 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user