mirror of
https://github.com/seven332/EhViewer
synced 2026-11-30 11:08:04 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20441479b6 | ||
|
|
af67773c26 | ||
|
|
486493eba6 | ||
|
|
1be8159fe9 | ||
|
|
b7b6f66e6b | ||
|
|
09642346fc | ||
|
|
fdd2d57de1 | ||
|
|
4d52f674b2 | ||
|
|
e4cc1fbd52 | ||
|
|
6c740199cc | ||
|
|
1c0b06120c | ||
|
|
a302d150e1 | ||
|
|
70d87817c8 | ||
|
|
aeb49f4bb6 | ||
|
|
e3134bbea1 | ||
|
|
87a18bac94 | ||
|
|
cfe0ca9801 | ||
|
|
3b25fcf45c | ||
|
|
cfe8ba06ab | ||
|
|
9116312875 | ||
|
|
9b067c9296 | ||
|
|
f750922dce | ||
|
|
ccc298ac1e | ||
|
|
fbced66a4e | ||
|
|
b0a21d8487 | ||
|
|
662f81e07d | ||
|
|
1f03e05424 | ||
|
|
2da8ebe75f | ||
|
|
2092171440 | ||
|
|
9ba87db1f0 | ||
|
|
447ef9a510 | ||
|
|
23936ff844 | ||
|
|
29f2723919 | ||
|
|
65feff57c0 | ||
|
|
017ee1c538 | ||
|
|
0059edd194 | ||
|
|
88a22b8545 | ||
|
|
024511c249 | ||
|
|
7b763a4f2a | ||
|
|
5bfc033d2d | ||
|
|
101b1cf256 | ||
|
|
38bd1e1f37 | ||
|
|
58b34a4bb2 | ||
|
|
00b7feab69 | ||
|
|
c69715d866 | ||
|
|
c8b347eed2 | ||
|
|
41b160227f | ||
|
|
697e0026c5 | ||
|
|
0f9bec5645 | ||
|
|
40784ea5a5 | ||
|
|
6fcbdc284d | ||
|
|
4084dc26df | ||
|
|
c71a8fc468 | ||
|
|
35df91190a | ||
|
|
5c44251762 | ||
|
|
4ddf33b4c1 | ||
|
|
2d97cd375c | ||
|
|
01cf1a8be4 | ||
|
|
2fdc42acc4 | ||
|
|
85ea7550f4 | ||
|
|
68d17c3ca8 | ||
|
|
409e8a093b | ||
|
|
f7e63ca386 | ||
|
|
77403b3032 | ||
|
|
3b7673c14e | ||
|
|
7ecac0db9e | ||
|
|
aedadff3a7 | ||
|
|
7b5cd5df9b | ||
|
|
6918a8776e | ||
|
|
9b821e875e | ||
|
|
29fadae5ab | ||
|
|
3d329979d4 | ||
|
|
2027b806df | ||
|
|
b18cdd04ce | ||
|
|
281eb12f0c | ||
|
|
5022ce2b54 | ||
|
|
063fa658f2 | ||
|
|
59dccfa513 | ||
|
|
471919682e | ||
|
|
0335e4338b | ||
|
|
857366f8d6 | ||
|
|
3d32fd7bcc | ||
|
|
f4aae2a027 | ||
|
|
a69be45099 | ||
|
|
4985945dcb | ||
|
|
e197ce3fe2 | ||
|
|
02e1185ebe | ||
|
|
b992602b2d | ||
|
|
0782469760 | ||
|
|
938c1a2e88 | ||
|
|
0a2c442b75 | ||
|
|
6b6c50f8cc | ||
|
|
fd7ea32942 | ||
|
|
d02e211ee3 | ||
|
|
6d8d16d1f8 | ||
|
|
af8c480588 | ||
|
|
5d0e035b35 | ||
|
|
f8e51c3ff7 | ||
|
|
9cb7d20dfc | ||
|
|
245bdc14ce | ||
|
|
f29090ee12 | ||
|
|
f1d4540558 | ||
|
|
497438c0a1 | ||
|
|
b407e38733 | ||
|
|
0fd27bf7fa | ||
|
|
45a9906731 | ||
|
|
7ee2dfc581 | ||
|
|
1c2aff9bbb | ||
|
|
fd5d07b2f2 |
No files matched your search
@@ -1,9 +0,0 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,8 @@
|
||||
.gradle
|
||||
/local.properties
|
||||
.DS_Store
|
||||
/build
|
||||
/src
|
||||
*.iml
|
||||
.idea
|
||||
/captures
|
||||
@@ -1,33 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,4 +0,0 @@
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
|
||||
org.eclipse.jdt.core.compiler.compliance=1.6
|
||||
org.eclipse.jdt.core.compiler.source=1.6
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module external.linked.project.id="EhViewer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="java-gradle" name="Java-Gradle">
|
||||
<configuration>
|
||||
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
|
||||
<option name="BUILDABLE" value="false" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
-202
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,13 +1,70 @@
|
||||
# EhViewer
|
||||
|
||||
这是一个 Android 平台上的 E-Hentai 阅读应用。<br>
|
||||
E-Hentai Application for Android.
|
||||
这是一个 Android 平台上的 E-Hentai 阅读应用。访问 [EhViewer](http://www.ehviewer.com/) 网站以获取更多信息。<br>
|
||||
EhViewer is an E-Hentai Application for Android. Visit [EhViewer](http://www.ehviewer.com/)(Chinese Only) website for more information.
|
||||
|
||||
# Build
|
||||
|
||||
导入 Android Studio 即可。<br>
|
||||
Just import into Android Studio.
|
||||
|
||||
# Thanks
|
||||
|
||||
- [android-gif-drawable](https://github.com/koral--/android-gif-drawable)
|
||||
- 参考 gif 解码
|
||||
- [ActionBar-PullToRefresh](https://github.com/chrisbanes/ActionBar-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [ActionBarSherlocke](https://github.com/JakeWharton/ActionBarSherlock)
|
||||
- 曾用来对 4.0 一些系统兼容
|
||||
- [Android-PullToRefresh](https://github.com/chrisbanes/Android-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [AndroidStaggeredGrid](https://github.com/etsy/AndroidStaggeredGrid)
|
||||
- 列表控件
|
||||
- [Apollo-CM](https://github.com/adneal/Apollo-CM)
|
||||
- 缓存机制
|
||||
- [DiskLruCache](https://github.com/JakeWharton/DiskLruCache)
|
||||
- 缓存机制
|
||||
- [FloatingActionButton](https://github.com/FaizMalkani/FloatingActionButton)
|
||||
- 按钮控件
|
||||
- [GIFLIB](http://giflib.sourceforge.net)
|
||||
- gif 解码
|
||||
- [Gloria Hallelujah](https://www.google.com/fonts/specimen/Gloria+Hallelujah)
|
||||
- 启动界面字体
|
||||
- [ImageLoadingPattern](https://github.com/rnrneverdies/ImageLoadingPattern)
|
||||
- 图片过渡效果
|
||||
- [libjpeg-turbo](http://www.libjpeg-turbo.org)
|
||||
- jpge 解码
|
||||
- [libpng](http://www.libpng.org/pub/png/libpng.html)
|
||||
- png 解码
|
||||
- [material-menu](https://github.com/balysv/material-menu)
|
||||
- 抽屉指示器
|
||||
- [OpenCC](https://github.com/BYVoid/OpenCC)
|
||||
- 繁化工作
|
||||
- [Slabo](https://github.com/TiroTypeworks/Slabo)
|
||||
- 图标字体
|
||||
- [SlidingMenu](https://github.com/jfeinstein10/SlidingMenu)
|
||||
- 曾作为抽屉控件
|
||||
- [source-code-pro](https://github.com/adobe/source-code-pro)
|
||||
- 刷新控件字体
|
||||
- [svg-android](https://code.google.com/p/svg-android/)
|
||||
- svg 解析
|
||||
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
|
||||
- 状态栏背景设置
|
||||
- [twoway-view](https://github.com/lucasr/twoway-view)
|
||||
- RecyclerView 使用方法
|
||||
- [zlib](http://www.zlib.net)
|
||||
- 辅助 png 解码
|
||||
- [Android Open Source Project](http://source.android.com)
|
||||
- 很多很多
|
||||
- [commons-lang](http://commons.apache.org/proper/commons-lang)
|
||||
- 很多很多
|
||||
|
||||
# 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>
|
||||
部分文件采用 [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) 授权([列表](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)).
|
||||
some files are licensed under the [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) ([list](rc/list2)).
|
||||
@@ -0,0 +1,3 @@
|
||||
/build
|
||||
/src/main/obj
|
||||
/src/main/libs
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EhViewer" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="android-gradle" name="Android-Gradle">
|
||||
<configuration>
|
||||
<option name="GRADLE_PROJECT_PATH" value=":app" />
|
||||
</configuration>
|
||||
</facet>
|
||||
<facet type="android" name="Android">
|
||||
<configuration>
|
||||
<option name="SELECTED_BUILD_VARIANT" value="debug" />
|
||||
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
|
||||
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
|
||||
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
|
||||
<afterSyncTasks>
|
||||
<task>generateDebugSources</task>
|
||||
</afterSyncTasks>
|
||||
<option name="ALLOW_USER_CONFIGURATION" value="false" />
|
||||
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
|
||||
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
|
||||
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
|
||||
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
|
||||
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
|
||||
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/recyclerview-v7/22.2.1/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/22.2.1/jars" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-safeguard" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/instant-run-support" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-v4-22.2.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-22.2.1" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-annotations-22.2.1" level="project" />
|
||||
<orderEntry type="module" module-name="vector" exported="" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,72 @@
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion '22.0.1'
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.hippo.ehviewer"
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 22
|
||||
versionCode 47
|
||||
versionName "0.6.16.3"
|
||||
}
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
release {
|
||||
minifyEnabled true
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
checkReleaseBuilds false
|
||||
// Or, if you prefer, you can continue to check for errors in release builds,
|
||||
// but continue the build even when errors are found:
|
||||
abortOnError false
|
||||
}
|
||||
|
||||
// Disable default NdkCompile task
|
||||
// Set new jni lib dir
|
||||
sourceSets.main {
|
||||
jni.srcDirs = []
|
||||
jniLibs.srcDir 'src/main/libs'
|
||||
}
|
||||
|
||||
// noinspection GroovyAssignabilityCheck
|
||||
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
|
||||
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
|
||||
def ndkBuilder
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
ndkBuilder = 'ndk-build.cmd'
|
||||
} else {
|
||||
ndkBuilder = 'ndk-build'
|
||||
}
|
||||
commandLine "$ndkDir\\$ndkBuilder",
|
||||
'-C', file('src/main').absolutePath,
|
||||
'NDK_DEBUG=0',
|
||||
'NDK_TOOLCHAIN_VERSION=clang',
|
||||
'-j4'
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile) {
|
||||
compileTask -> compileTask.dependsOn ndkBuild
|
||||
}
|
||||
}
|
||||
|
||||
clean {
|
||||
delete file('src/main/obj').absolutePath
|
||||
delete file('src/main/libs').absolutePath
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(dir: 'libs', include: ['*.jar'])
|
||||
compile project(':vector')
|
||||
compile 'com.android.support:support-v4:22.2.1'
|
||||
compile 'com.android.support:recyclerview-v7:22.2.1'
|
||||
}
|
||||
Binary file not shown.
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# By default, the flags in this file are appended to flags specified
|
||||
# in E:\Android\android-sdk/tools/proguard/proguard-android.txt
|
||||
# You can edit the include path and order by changing the proguardFiles
|
||||
# directive in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# Add any project specific keep options here:
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
-keep class com.hippo.ehviewer.widget.SearchView {*;}
|
||||
|
||||
-keep class com.hippo.ehviewer.gallery.image.Image {*;}
|
||||
|
||||
-keep class com.hippo.ehviewer.gallery.image.GifImage {*;}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.drawable.MaterialProgressDrawable$Ring {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class * extends com.hippo.ehviewer.windowsanimate.Sprite {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class * extends android.graphics.drawable.Drawable {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.effect.ripple.Ripple {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
-keepclassmembers class com.hippo.ehviewer.effect.ripple.RippleBackground {
|
||||
void set*(***);
|
||||
*** get*();
|
||||
}
|
||||
|
||||
# For VectorResources
|
||||
-keep class android.content.res.VectorResources {*;}
|
||||
|
||||
# I want to track the error in them
|
||||
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,9 @@
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.hippo.ehviewer"
|
||||
android:versionCode="21"
|
||||
android:versionName="0.6.0" >
|
||||
|
||||
<uses-sdk
|
||||
android:minSdkVersion="14"
|
||||
android:targetSdkVersion="19" />
|
||||
<manifest
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.hippo.ehviewer">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
@@ -33,15 +28,17 @@
|
||||
android:allowBackup="true"
|
||||
android:hardwareAccelerated="true"
|
||||
android:largeHeap="true"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:supportsRtl="true"
|
||||
android:icon="@mipmap/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" >
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent.Translucent" >
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
@@ -50,7 +47,7 @@
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryListActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:launchMode="singleTop"
|
||||
android:screenOrientation="behind"
|
||||
@@ -63,9 +60,18 @@
|
||||
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"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden" >
|
||||
<intent-filter>
|
||||
@@ -73,6 +79,7 @@
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="http" />
|
||||
<data android:scheme="https" />
|
||||
<data android:host="exhentai.org" />
|
||||
<data android:host="g.e-hentai.org" />
|
||||
<data android:host="lofi.e-hentai.org" />
|
||||
@@ -82,32 +89,37 @@
|
||||
|
||||
<activity
|
||||
android:name=".ui.GalleryActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.NoActionBar" >
|
||||
android:theme="@style/AppTheme.Dark.NoActionBar" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.SettingsActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_settings"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/preference_settings_title"
|
||||
android:screenOrientation="behind" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.FavouriteActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_favorite"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/favourite"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.HistoryActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/history"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.ListActivity" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.DownloadActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:icon="@drawable/ic_action_download"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/download"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="behind"
|
||||
@@ -117,9 +129,45 @@
|
||||
android:value=".ui.GalleryListActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.SecretActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:screenOrientation="behind"
|
||||
android:theme="@style/AppTheme.NoActionBar.Transparent" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.PatternProtectionActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/AppTheme" >
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.EnterPatternActivity"
|
||||
android:configChanges="orientation|screenSize|uiMode"
|
||||
android:label="@string/app_name"
|
||||
android:screenOrientation="portrait"
|
||||
android:theme="@style/AppTheme" >
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".service.DownloadService"
|
||||
android:label="DownloadService" />
|
||||
|
||||
<provider
|
||||
android:name=".SimpleSuggestionProvider"
|
||||
android:authorities="com.hippo.ehviewer.SimpleSuggestionProvider"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver android:name=".receiver.RestPatternReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.provider.Telephony.SECRET_CODE"/>
|
||||
<data android:scheme="android_secret_code" android:host="110722"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
</manifest>
|
||||
Binary file not shown.
Binary file not shown.
+9
-10
@@ -16,27 +16,26 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import android.content.Context;
|
||||
|
||||
import com.google.analytics.tracking.android.EasyTracker;
|
||||
import com.google.analytics.tracking.android.MapBuilder;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
|
||||
import android.content.Context;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class Analytics {
|
||||
|
||||
|
||||
private static final String KEY_GALLERY = "gallery";
|
||||
private static final String KEY_OPEN = "open";
|
||||
private static final String KEY_READ = "read";
|
||||
private static final String KEY_DOWNLOAD = "download";
|
||||
private static final String KEY_ADD_TO_FAVORITE = "add_to_favorite";
|
||||
|
||||
|
||||
private static void doGallery(Context context, int gid, String token, String method) {
|
||||
if (!Config.getAllowAnalyics())
|
||||
return;
|
||||
|
||||
|
||||
try {
|
||||
JSONObject js = new JSONObject();
|
||||
js.put("gid", gid).put("token", token);
|
||||
@@ -44,19 +43,19 @@ public class Analytics {
|
||||
easyTracker.send(MapBuilder.createEvent(KEY_GALLERY, method, js.toString(), null).build());
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
|
||||
|
||||
public static void openGallery(Context context, int gid, String token) {
|
||||
doGallery(context, gid, token, KEY_OPEN);
|
||||
}
|
||||
|
||||
|
||||
public static void readGallery(Context context, int gid, String token) {
|
||||
doGallery(context, gid, token, KEY_READ);
|
||||
}
|
||||
|
||||
|
||||
public static void downloadGallery(Context context, int gid, String token) {
|
||||
doGallery(context, gid, token, KEY_DOWNLOAD);
|
||||
}
|
||||
|
||||
|
||||
public static void addToFavoriteGallery(Context context, int gid, String token) {
|
||||
doGallery(context, gid, token, KEY_ADD_TO_FAVORITE);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.graphics.Typeface;
|
||||
import android.view.ContextThemeWrapper;
|
||||
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SlidingDrawerLayout;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.Thread.UncaughtExceptionHandler;
|
||||
|
||||
public class AppContext extends Application implements UncaughtExceptionHandler {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = AppContext.class.getSimpleName();
|
||||
|
||||
private Thread.UncaughtExceptionHandler mDefaultHandler;
|
||||
|
||||
private Typeface mFaceTypeface;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
// Do catch error prepare
|
||||
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
|
||||
Context mContextThemeWrapper = new ContextThemeWrapper(this, R.style.AppTheme);
|
||||
ViewUtils.initDialogViewInflater(this);
|
||||
|
||||
// Init everything
|
||||
Ui.init(mContextThemeWrapper);
|
||||
Config.init(mContextThemeWrapper);
|
||||
Log.init(mContextThemeWrapper);
|
||||
Crash.init(mContextThemeWrapper);
|
||||
EhClient.createInstance(mContextThemeWrapper);
|
||||
FavoriteHelper.init(mContextThemeWrapper);
|
||||
Data.createInstance(mContextThemeWrapper);
|
||||
ExDownloaderManager.createInstance(mContextThemeWrapper);
|
||||
MaterialToast.setContext(mContextThemeWrapper);
|
||||
|
||||
mFaceTypeface = Typeface.createFromAsset(getAssets(),"fonts/face.ttf");
|
||||
|
||||
// Set drawer margin
|
||||
SlidingDrawerLayout.setDefaultMinDrawerMargin(Ui.ACTION_BAR_HEIGHT * 2);
|
||||
|
||||
// Add .nomedia or delete it
|
||||
File nomedia = new File(Config.getDownloadPath(), ".nomedia");
|
||||
if (Config.getMediaScan()) {
|
||||
nomedia.delete();
|
||||
} else {
|
||||
try {
|
||||
new FileOutputStream(nomedia).close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
|
||||
// Update proxy urls
|
||||
HttpHelper.updateProxyUrls(mContextThemeWrapper);
|
||||
|
||||
String keyVersionCode = "version_code";
|
||||
int oldVersion = Config.getInt(keyVersionCode, Integer.MAX_VALUE);
|
||||
// Fix <=22 login error
|
||||
if (oldVersion <= 22)
|
||||
EhInfo.getInstance(mContextThemeWrapper).logout();
|
||||
|
||||
// Fix <=25 Update
|
||||
if (oldVersion <= 25) {
|
||||
File downloadDir = new File(Config.getDownloadPath());
|
||||
String cachePath = getExternalCacheDir() != null
|
||||
? getExternalCacheDir().getPath()
|
||||
: getCacheDir().getPath();
|
||||
File oldEdInfoDir = new File(cachePath, "ExDownloaderManager");
|
||||
String[] list = downloadDir.list();
|
||||
if (list != null && list.length != 0) {
|
||||
for (String str : list) {
|
||||
int index = str.indexOf('-');
|
||||
if (index == -1)
|
||||
continue;
|
||||
String gid = str.substring(0, index);
|
||||
File gDir = new File(downloadDir, str);
|
||||
// Move download info file
|
||||
File oldInfoFile = new File(oldEdInfoDir, gid);
|
||||
File newInfoFile = new File(gDir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
if (!oldInfoFile.exists())
|
||||
continue;
|
||||
try {
|
||||
FileOutputStream fos = new FileOutputStream(newInfoFile);
|
||||
// Add last page
|
||||
byte[] bs = {'0', '0', '0', '0', '0', '0', '0', '0', '\n'};
|
||||
fos.write(bs);
|
||||
Utils.copy(new FileInputStream(oldInfoFile), fos);
|
||||
} catch (Throwable e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Delete old exdownload info dir
|
||||
Utils.deleteDirInThread(oldEdInfoDir);
|
||||
}
|
||||
|
||||
// Update version code
|
||||
try {
|
||||
PackageInfo pi= getPackageManager().getPackageInfo(getPackageName(), 0);
|
||||
Config.setInt(keyVersionCode, pi.versionCode);
|
||||
} catch (NameNotFoundException e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void onLowMemory() {
|
||||
ImageCache.getImageCache(this).clearMemory();
|
||||
super.onLowMemory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uncaughtException(Thread thread, Throwable ex) {
|
||||
if (!handleException(ex) && mDefaultHandler != null) {
|
||||
mDefaultHandler.uncaughtException(thread, ex);
|
||||
}
|
||||
android.os.Process.killProcess(android.os.Process.myPid());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
private boolean handleException(Throwable ex) {
|
||||
if (ex == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Crash.saveCrashInfo2File(ex);
|
||||
return true;
|
||||
} catch (Throwable tr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Typeface getFaceTypeface() {
|
||||
return mFaceTypeface;
|
||||
}
|
||||
}
|
||||
-5
@@ -25,7 +25,6 @@ import com.hippo.ehviewer.util.Constants;
|
||||
|
||||
public class AppHandler extends Handler {
|
||||
|
||||
public static final int IMAGE_LOADER_TAG = 0x0;
|
||||
public static final int HTTP_HELPER_TAG = 0x1;
|
||||
|
||||
private static Handler sInstance;
|
||||
@@ -43,10 +42,6 @@ public class AppHandler extends Handler {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
switch(msg.what) {
|
||||
case IMAGE_LOADER_TAG:
|
||||
ImageLoader.LoadTask task = (ImageLoader.LoadTask)msg.obj;
|
||||
task.listener.onGetImage(task.key, task.bitmap);
|
||||
break;
|
||||
|
||||
case HTTP_HELPER_TAG:
|
||||
HttpHelper.Package p = (HttpHelper.Package)msg.obj;
|
||||
+42
-20
@@ -16,19 +16,25 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Message;
|
||||
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.cache.AnyCache;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class ImageLoader {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = ImageLoader.class.getSimpleName();
|
||||
|
||||
public static final int STATE_NONE = 0;
|
||||
public static final int STATE_FROM_MEMORY = 1;
|
||||
public static final int STATE_FROM_DISK = 2;
|
||||
public static final int STATE_FROM_NETWORK = 3;
|
||||
|
||||
private static ImageLoader sInstance;
|
||||
|
||||
class LoadTask {
|
||||
@@ -36,6 +42,7 @@ public class ImageLoader {
|
||||
public String key;
|
||||
public OnGetImageListener listener;
|
||||
public Bitmap bitmap;
|
||||
public int state;
|
||||
|
||||
public LoadTask(String url, String key, OnGetImageListener listener) {
|
||||
this.url = url;
|
||||
@@ -46,19 +53,17 @@ public class ImageLoader {
|
||||
|
||||
private final Context mContext;
|
||||
private final Stack<LoadTask> mLoadTasks;
|
||||
private final ImageCache mImageCache;
|
||||
private final AnyCache<Bitmap> mImageCache;
|
||||
private final ImageDownloader mImageDownloader;
|
||||
|
||||
public ImageLoader(Context context) {
|
||||
private ImageLoader(Context context) {
|
||||
mLoadTasks = new Stack<LoadTask>();
|
||||
mImageDownloader = new ImageDownloader();
|
||||
|
||||
mContext = context;
|
||||
mImageCache = ImageCache.getInstance(mContext);
|
||||
mImageCache = ImageCache.getImageCache(mContext);
|
||||
|
||||
Thread thread = new Thread(new LoadFromCacheTask());
|
||||
thread.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
|
||||
thread.start();
|
||||
new BgThread(new LoadFromCacheTask()).start();
|
||||
}
|
||||
|
||||
public final static ImageLoader getInstance(final Context context) {
|
||||
@@ -75,6 +80,20 @@ public class ImageLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private class LoadImageCallback implements Runnable {
|
||||
|
||||
private final LoadTask mLoadTask;
|
||||
|
||||
private LoadImageCallback(LoadTask task) {
|
||||
mLoadTask = task;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
mLoadTask.listener.onGetImage(mLoadTask.key, mLoadTask.bitmap, mLoadTask.state);
|
||||
}
|
||||
}
|
||||
|
||||
private class LoadFromCacheTask implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -90,12 +109,13 @@ public class ImageLoader {
|
||||
loadTask = mLoadTasks.pop();
|
||||
}
|
||||
|
||||
int[] state = new int[1];
|
||||
String key = loadTask.key;
|
||||
loadTask.bitmap = mImageCache.getCachedBitmap(key);
|
||||
loadTask.bitmap = mImageCache.get(key);
|
||||
loadTask.state = state[0];
|
||||
|
||||
if (loadTask.bitmap != null)
|
||||
AppHandler.getInstance().sendMessage(
|
||||
Message.obtain(null, AppHandler.IMAGE_LOADER_TAG, loadTask));
|
||||
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
|
||||
else
|
||||
mImageDownloader.add(loadTask);
|
||||
}
|
||||
@@ -115,9 +135,7 @@ public class ImageLoader {
|
||||
synchronized (mDownloadTasks) {
|
||||
mDownloadTasks.push(loadTask);
|
||||
if (mWorkingThreadNum < MAX_DOWNLOAD_THREADS) {
|
||||
Thread thread = new Thread(new DownloadImageTask());
|
||||
thread.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
|
||||
thread.start();
|
||||
new BgThread(new DownloadImageTask()).start();
|
||||
mWorkingThreadNum++;
|
||||
}
|
||||
}
|
||||
@@ -140,10 +158,14 @@ public class ImageLoader {
|
||||
|
||||
// TODO use proxy to get image
|
||||
loadTask.bitmap = httpHelper.getImage(loadTask.url);
|
||||
mImageCache.addBitmapToCache(loadTask.key, loadTask.bitmap);
|
||||
if (loadTask.bitmap != null) {
|
||||
mImageCache.put(loadTask.key, loadTask.bitmap);
|
||||
loadTask.state = STATE_FROM_NETWORK;
|
||||
} else {
|
||||
loadTask.state = STATE_NONE;
|
||||
}
|
||||
|
||||
AppHandler.getInstance().sendMessage(
|
||||
Message.obtain(null, AppHandler.IMAGE_LOADER_TAG, loadTask));
|
||||
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,6 +177,6 @@ public class ImageLoader {
|
||||
* @param key
|
||||
* @param bmp
|
||||
*/
|
||||
void onGetImage(String key, Bitmap bmp);
|
||||
void onGetImage(String key, Bitmap bmp, int state);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Bundle;
|
||||
import android.text.util.Linkify;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
|
||||
import com.hippo.ehviewer.network.Network;
|
||||
import com.hippo.ehviewer.ui.AbsActivity;
|
||||
import com.hippo.ehviewer.ui.EnterPatternActivity;
|
||||
import com.hippo.ehviewer.ui.GalleryListActivity;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.SimpleImageView;
|
||||
import com.hippo.vector.VectorDrawable;
|
||||
|
||||
public class StartActivity extends AbsActivity {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = StartActivity.class.getSimpleName();
|
||||
|
||||
private static final int REQUEST_CODE_PATTERN = 0;
|
||||
|
||||
private static final int CHECK_WARING = 0;
|
||||
private static final int CHECK_ANALYTICS = 1;
|
||||
private static final int CHECK_NETWORK = 2;
|
||||
private static final int CHECK_CRASH = 3;
|
||||
|
||||
private static final String KEY_ALLOWED = "allowed";
|
||||
private static final String KEY_SET_ANALYTICS = "set_analyics";
|
||||
|
||||
private String lastCrash;
|
||||
private boolean isEnterPattern = false;
|
||||
private boolean isAnimationOver = false;
|
||||
private boolean isCheckOver = false;
|
||||
|
||||
private MaterialAlertDialog createWarningDialog() {
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dailog_waring_title)
|
||||
.setMessage(R.string.dailog_waring_plain)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
Config.setBoolean(KEY_ALLOWED, true);
|
||||
check(CHECK_ANALYTICS);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
finish();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createAllowAnalyicsDialog() {
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dailog_analyics_title)
|
||||
.setMessageAutoLink(Linkify.WEB_URLS)
|
||||
.setMessage(R.string.dailog_analyics_plain)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
Config.setAllowAnalyics(true);
|
||||
check(CHECK_NETWORK);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
Config.setAllowAnalyics(false);
|
||||
check(CHECK_NETWORK);
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createNetworkDialog(int state) {
|
||||
int mesgId;
|
||||
switch (state) {
|
||||
case Network.NETWORK_STATE_MOBILE:
|
||||
mesgId = R.string.dailog_network_mobile_title;
|
||||
break;
|
||||
case Network.NETWORK_STATE_NONE:
|
||||
default:
|
||||
mesgId = R.string.dailog_network_none_title;
|
||||
break;
|
||||
}
|
||||
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.warning).setMessage(mesgId)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
check(CHECK_CRASH);
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
finish();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
private AlertDialog createSendCrashDialog() {
|
||||
View view = ViewUtils.inflateDialogView(R.layout.send_crash, false);
|
||||
final EditText et = (EditText) view.findViewById(R.id.description_of_user);
|
||||
return new MaterialAlertDialog.Builder(this).setCancelable(false)
|
||||
.setTitle(R.string.dialog_send_crash_title)
|
||||
.setView(view, true)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
switch (which) {
|
||||
case MaterialAlertDialog.POSITIVE:
|
||||
// A wait dialog
|
||||
new MaterialAlertDialog.Builder(StartActivity.this)
|
||||
.setCancelable(false)
|
||||
.setTitle(R.string.wait)
|
||||
.setMessage(R.string.dialog_wait_send_crash_msg)
|
||||
.setPositiveButton(android.R.string.ok)
|
||||
.setButtonListener(
|
||||
new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
checkOver();
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
ActivityHelper.sendEmail(StartActivity.this, "ehviewersu@gmail.com", "I found a bug in EhViewer !", lastCrash + "======== Description ========\n" + et.getText().toString());
|
||||
lastCrash = null;
|
||||
break;
|
||||
case MaterialAlertDialog.NEGATIVE:
|
||||
lastCrash = null;
|
||||
checkOver();
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
// Disable animate
|
||||
overridePendingTransition(0, 0);
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.start_activity);
|
||||
|
||||
TextView text = (TextView) findViewById(R.id.text);
|
||||
text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/GloriaHallelujah.ttf"));
|
||||
SimpleImageView image = (SimpleImageView) findViewById(R.id.image);
|
||||
image.setDrawable(VectorDrawable.create(this, R.drawable.sad_pandroid));
|
||||
|
||||
// Update secret image here
|
||||
int state = Network.getNetworkState(this);
|
||||
if (state == Network.NETWORK_STATE_WIFI) {
|
||||
Secret.updateSecretImage(this);
|
||||
}
|
||||
|
||||
AppHandler.getInstance().postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!StartActivity.this.isFinishing()) {
|
||||
if (isCheckOver && isEnterPattern)
|
||||
redirectTo();
|
||||
isAnimationOver = true;
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
check(CHECK_WARING);
|
||||
|
||||
// Enter Pattern
|
||||
String pattern = Config.getPatternProtection();
|
||||
if (LockPatternUtils.isPatternVaild(pattern)) {
|
||||
// Start activity to enter pattern
|
||||
Intent intent = new Intent(this, EnterPatternActivity.class);
|
||||
startActivityForResult(intent, REQUEST_CODE_PATTERN);
|
||||
} else {
|
||||
isEnterPattern = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
if (requestCode == REQUEST_CODE_PATTERN) {
|
||||
if (resultCode == RESULT_OK) {
|
||||
if (isAnimationOver && isCheckOver)
|
||||
redirectTo();
|
||||
isEnterPattern = true;
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Order is 1. check waring 2. check analyics 3. check network 4. check
|
||||
* crash 5. check external storage
|
||||
*
|
||||
* @param order
|
||||
*/
|
||||
private void check(int order) {
|
||||
switch (order) {
|
||||
case CHECK_WARING:
|
||||
if (!Config.getBoolean(KEY_ALLOWED, false)) {
|
||||
createWarningDialog().show();
|
||||
return;
|
||||
}
|
||||
case CHECK_ANALYTICS:
|
||||
if (!Config.getBoolean(KEY_SET_ANALYTICS, false)) {
|
||||
Config.setBoolean(KEY_SET_ANALYTICS, true);
|
||||
createAllowAnalyicsDialog().show();
|
||||
return;
|
||||
}
|
||||
case CHECK_NETWORK:
|
||||
int state = Network.getNetworkState(this);
|
||||
if (state != Network.NETWORK_STATE_WIFI) {
|
||||
createNetworkDialog(state).show();
|
||||
return;
|
||||
}
|
||||
case CHECK_CRASH:
|
||||
if ((lastCrash = Crash.getLastCrash()) != null) {
|
||||
createSendCrashDialog().show();
|
||||
return;
|
||||
}
|
||||
}
|
||||
checkOver();
|
||||
}
|
||||
|
||||
private void checkOver() {
|
||||
if (isAnimationOver && isEnterPattern)
|
||||
redirectTo();
|
||||
isCheckOver = true;
|
||||
}
|
||||
|
||||
private void redirectTo() {
|
||||
Intent intent = new Intent(this, GalleryListActivity.class);
|
||||
startActivity(intent);
|
||||
finish();
|
||||
}
|
||||
}
|
||||
+14
-11
@@ -16,11 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
@@ -28,13 +23,19 @@ import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.net.Uri;
|
||||
import android.os.Process;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
// TODO return onFailure when downloading update or check update
|
||||
// TODO add disable to achieve
|
||||
|
||||
@@ -42,7 +43,6 @@ public class UpdateHelper implements Runnable {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = "UpdateHelper";
|
||||
|
||||
private static final String UPDATE_API = "http://www.ehviewer.com/API";
|
||||
private static final String HEADER = "Ehviewer-";
|
||||
private static final String FOOTER = ".apk";
|
||||
|
||||
@@ -114,7 +114,7 @@ public class UpdateHelper implements Runnable {
|
||||
|
||||
jo.put("detail", detailJO);
|
||||
|
||||
_package.body = hp.postJson(UPDATE_API, jo);
|
||||
_package.body = hp.postJson(EhClient.API_EHVIEWER, jo);
|
||||
_package.emesg = hp.getEMsg();
|
||||
send(_package);
|
||||
} catch (NameNotFoundException e) {
|
||||
@@ -129,9 +129,7 @@ public class UpdateHelper implements Runnable {
|
||||
}
|
||||
|
||||
public void checkUpdate() {
|
||||
Thread thread = new Thread(this);
|
||||
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
||||
thread.start();
|
||||
new BgThread(this).start();
|
||||
}
|
||||
|
||||
private class Respond implements Runnable {
|
||||
@@ -256,5 +254,10 @@ public class UpdateHelper implements Runnable {
|
||||
}
|
||||
setEnabled(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
-92
@@ -14,12 +14,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.widget;
|
||||
package com.hippo.ehviewer.app;
|
||||
|
||||
import java.text.NumberFormat;
|
||||
import com.hippo.ehviewer.R;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Handler;
|
||||
@@ -32,53 +31,46 @@ import android.view.View;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
public class ProgressDialogBulider extends DialogBuilder{
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
|
||||
public class MaterialProgressDialog extends MaterialAlertDialog {
|
||||
|
||||
|
||||
/** Creates a ProgressDialog with a circular, spinning progress
|
||||
* bar. This is not the default.
|
||||
* bar. This is the default.
|
||||
*/
|
||||
public static final int STYLE_SPINNER = 0;
|
||||
|
||||
|
||||
/** Creates a ProgressDialog with a horizontal progress bar.
|
||||
*/
|
||||
public static final int STYLE_HORIZONTAL = 1;
|
||||
|
||||
|
||||
private ProgressBar mProgress;
|
||||
private TextView mMessageView;
|
||||
|
||||
|
||||
private int mProgressStyle = STYLE_HORIZONTAL;
|
||||
private TextView mProgressNumber;
|
||||
private String mProgressNumberFormat;
|
||||
private TextView mProgressPercent;
|
||||
private NumberFormat mProgressPercentFormat;
|
||||
|
||||
|
||||
private int mMax;
|
||||
private int mProgressVal;
|
||||
private int mSecondaryProgressVal;
|
||||
private int mIncrementBy;
|
||||
private int mIncrementSecondaryBy;
|
||||
private Drawable mProgressDrawable;
|
||||
private Drawable mIndeterminateDrawable;
|
||||
private CharSequence mMessage;
|
||||
private boolean mIndeterminate;
|
||||
|
||||
private boolean mHasStarted = true;
|
||||
|
||||
private boolean mHasStarted;
|
||||
private Handler mViewUpdateHandler;
|
||||
|
||||
private void initFormats() {
|
||||
mProgressNumberFormat = "%1d/%2d";
|
||||
mProgressPercentFormat = NumberFormat.getPercentInstance();
|
||||
mProgressPercentFormat.setMaximumFractionDigits(0);
|
||||
}
|
||||
|
||||
@SuppressLint("HandlerLeak")
|
||||
public ProgressDialogBulider(Context context) {
|
||||
super(context);
|
||||
|
||||
|
||||
|
||||
@SuppressLint({ "InflateParams", "HandlerLeak" })
|
||||
protected MaterialProgressDialog(Builder builder) {
|
||||
super(builder);
|
||||
initFormats();
|
||||
LayoutInflater inflater = LayoutInflater.from(context);
|
||||
|
||||
LayoutInflater inflater = LayoutInflater.from(builder.mContext);
|
||||
if (mProgressStyle == STYLE_HORIZONTAL) {
|
||||
|
||||
|
||||
/* Use a separate handler to update the text views as they
|
||||
* must be updated on the same thread that created them.
|
||||
*/
|
||||
@@ -86,7 +78,7 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
super.handleMessage(msg);
|
||||
|
||||
|
||||
/* Update the number and percent */
|
||||
int progress = mProgress.getProgress();
|
||||
int max = mProgress.getMax();
|
||||
@@ -118,59 +110,62 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
mMessageView = (TextView) view.findViewById(R.id.message);
|
||||
setView(view, false);
|
||||
}
|
||||
if (mMax > 0) {
|
||||
setMax(mMax);
|
||||
}
|
||||
if (mProgressVal > 0) {
|
||||
setProgress(mProgressVal);
|
||||
}
|
||||
if (mSecondaryProgressVal > 0) {
|
||||
setSecondaryProgress(mSecondaryProgressVal);
|
||||
}
|
||||
if (mIncrementBy > 0) {
|
||||
incrementProgressBy(mIncrementBy);
|
||||
}
|
||||
if (mIncrementSecondaryBy > 0) {
|
||||
incrementSecondaryProgressBy(mIncrementSecondaryBy);
|
||||
}
|
||||
if (mProgressDrawable != null) {
|
||||
setProgressDrawable(mProgressDrawable);
|
||||
}
|
||||
if (mIndeterminateDrawable != null) {
|
||||
setIndeterminateDrawable(mIndeterminateDrawable);
|
||||
}
|
||||
if (mMessage != null) {
|
||||
setMessage(mMessage);
|
||||
}
|
||||
setIndeterminate(mIndeterminate);
|
||||
onProgressChanged();
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
private void initFormats() {
|
||||
mProgressNumberFormat = "%1d/%2d";
|
||||
mProgressPercentFormat = NumberFormat.getPercentInstance();
|
||||
mProgressPercentFormat.setMaximumFractionDigits(0);
|
||||
}
|
||||
|
||||
|
||||
public static MaterialProgressDialog create(Context context, CharSequence title) {
|
||||
return create(context, title, false, null);
|
||||
}
|
||||
|
||||
public static MaterialProgressDialog create(Context context, CharSequence title,
|
||||
boolean cancelable) {
|
||||
return create(context, title, cancelable, null);
|
||||
}
|
||||
|
||||
public static MaterialProgressDialog create(Context context, CharSequence title,
|
||||
boolean cancelable, OnCancelListener cancelListener) {
|
||||
|
||||
MaterialProgressDialog.Builder builder = new MaterialProgressDialog.Builder(context);
|
||||
builder.setTitle(title);
|
||||
builder.setCancelable(cancelable);
|
||||
builder.setOnCancelListener(cancelListener);
|
||||
return new MaterialProgressDialog(builder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AlertDialog create() {
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
mHasStarted = true;
|
||||
return super.create();
|
||||
}*/
|
||||
|
||||
public ProgressDialogBulider setProgress(int value) {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
mHasStarted = false;
|
||||
}
|
||||
|
||||
public void setProgress(int value) {
|
||||
if (mHasStarted) {
|
||||
mProgress.setProgress(value);
|
||||
onProgressChanged();
|
||||
} else {
|
||||
mProgressVal = value;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ProgressDialogBulider setSecondaryProgress(int secondaryProgress) {
|
||||
public void setSecondaryProgress(int secondaryProgress) {
|
||||
if (mProgress != null) {
|
||||
mProgress.setSecondaryProgress(secondaryProgress);
|
||||
onProgressChanged();
|
||||
} else {
|
||||
mSecondaryProgressVal = secondaryProgress;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getProgress() {
|
||||
@@ -194,22 +189,19 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
return mMax;
|
||||
}
|
||||
|
||||
public ProgressDialogBulider setMax(int max) {
|
||||
public void setMax(int max) {
|
||||
if (mProgress != null) {
|
||||
mProgress.setMax(max);
|
||||
onProgressChanged();
|
||||
} else {
|
||||
mMax = max;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public void incrementProgressBy(int diff) {
|
||||
if (mProgress != null) {
|
||||
mProgress.incrementProgressBy(diff);
|
||||
onProgressChanged();
|
||||
} else {
|
||||
mIncrementBy += diff;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,36 +209,25 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
if (mProgress != null) {
|
||||
mProgress.incrementSecondaryProgressBy(diff);
|
||||
onProgressChanged();
|
||||
} else {
|
||||
mIncrementSecondaryBy += diff;
|
||||
}
|
||||
}
|
||||
|
||||
public ProgressDialogBulider setProgressDrawable(Drawable d) {
|
||||
public void setProgressDrawable(Drawable d) {
|
||||
if (mProgress != null) {
|
||||
mProgress.setProgressDrawable(d);
|
||||
} else {
|
||||
mProgressDrawable = d;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ProgressDialogBulider setIndeterminateDrawable(Drawable d) {
|
||||
public void setIndeterminateDrawable(Drawable d) {
|
||||
if (mProgress != null) {
|
||||
mProgress.setIndeterminateDrawable(d);
|
||||
} else {
|
||||
mIndeterminateDrawable = d;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ProgressDialogBulider setIndeterminate(boolean indeterminate) {
|
||||
public void setIndeterminate(boolean indeterminate) {
|
||||
if (mProgress != null) {
|
||||
mProgress.setIndeterminate(indeterminate);
|
||||
} else {
|
||||
mIndeterminate = indeterminate;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isIndeterminate() {
|
||||
@@ -255,21 +236,18 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
}
|
||||
return mIndeterminate;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ProgressDialogBulider setMessage(CharSequence message) {
|
||||
public void setMessage(CharSequence message) {
|
||||
if (mProgress != null) {
|
||||
if (mProgressStyle == STYLE_HORIZONTAL) {
|
||||
super.setMessage(message);
|
||||
} else {
|
||||
mMessageView.setText(message);
|
||||
}
|
||||
} else {
|
||||
mMessage = message;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public void setProgressStyle(int style) {
|
||||
mProgressStyle = style;
|
||||
}
|
||||
@@ -299,7 +277,7 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
mProgressPercentFormat = format;
|
||||
onProgressChanged();
|
||||
}
|
||||
|
||||
|
||||
private void onProgressChanged() {
|
||||
if (mProgressStyle == STYLE_HORIZONTAL) {
|
||||
if (mViewUpdateHandler != null && !mViewUpdateHandler.hasMessages(0)) {
|
||||
@@ -307,4 +285,5 @@ public class ProgressDialogBulider extends DialogBuilder{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.cache;
|
||||
|
||||
import android.os.Looper;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.util.LruCache;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public abstract class AnyCache<V> {
|
||||
|
||||
private static final String TAG = AnyCache.class.getSimpleName();
|
||||
|
||||
private LruCache<String, V> mMemoryCache;
|
||||
private @Nullable DiskCache<V> mDiskCache;
|
||||
|
||||
private final boolean mHasMemoryCache;
|
||||
private final boolean mHasDiskCache;
|
||||
|
||||
/**
|
||||
* Used to temporarily pause the disk cache while scrolling
|
||||
*/
|
||||
public boolean mPauseDiskAccess = false;
|
||||
private final Object mPauseLock = new Object();
|
||||
|
||||
private final Object mDiskCacheLock = new Object();
|
||||
|
||||
public AnyCache(AnyCacheParams params) {
|
||||
params.isValid();
|
||||
mHasMemoryCache = params.hasMemoryCache;
|
||||
mHasDiskCache = params.hasDiskCache;
|
||||
|
||||
if (mHasMemoryCache) {
|
||||
initMemoryCache(params.memoryCacheMaxSize);
|
||||
}
|
||||
|
||||
if (mHasDiskCache) {
|
||||
initDiskCache(params.diskCacheDir, params.diskCacheMaxSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void initMemoryCache(int maxSize) {
|
||||
mMemoryCache = new MemoryCahce<>(maxSize, this);
|
||||
}
|
||||
|
||||
private void initDiskCache(File cacheDir, int maxSize) {
|
||||
// Set up disk cache
|
||||
synchronized (mDiskCacheLock) {
|
||||
try {
|
||||
mDiskCache = new DiskCache<>(cacheDir, maxSize, this);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Can't create disk cache", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected abstract int sizeOf(String key, V value);
|
||||
|
||||
protected abstract V read(InputStream is);
|
||||
|
||||
protected abstract boolean write(OutputStream os, V value);
|
||||
|
||||
/**
|
||||
* Check if have memory cache
|
||||
*
|
||||
* @return true if have memory cache
|
||||
*/
|
||||
public boolean hasMemoryCache() {
|
||||
return mHasMemoryCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if have disk cache
|
||||
*
|
||||
* @return true if have disk cache
|
||||
*/
|
||||
public boolean hasDiskCache() {
|
||||
return mHasDiskCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get, null for miss or no memory cache
|
||||
*/
|
||||
public V getFromMemory(String key) {
|
||||
if (mHasMemoryCache) {
|
||||
return mMemoryCache.get(key);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get, null for miss or no memory cache or get error
|
||||
*/
|
||||
public V getFromDisk(String key) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
return mDiskCache.get(diskKey);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value from memory cache and disk cache. If miss in memory cache and
|
||||
* get in disk cache, it will put value from disk cache to memory cache.
|
||||
*
|
||||
* @param key the key to get value
|
||||
* @return the value you get
|
||||
*/
|
||||
public V get(String key) {
|
||||
V value = getFromMemory(key);
|
||||
|
||||
if (value != null) {
|
||||
// Get it in memory cache
|
||||
return value;
|
||||
}
|
||||
|
||||
value = getFromDisk(key);
|
||||
|
||||
if (value != null) {
|
||||
// Get it in disk cache
|
||||
putToMemory(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to memory cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return false if no memory cache
|
||||
*/
|
||||
public boolean putToMemory(String key, V value) {
|
||||
if (mHasMemoryCache) {
|
||||
mMemoryCache.put(key, value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to disk cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return false if no disk cache or get error
|
||||
*/
|
||||
public boolean putToDisk(String key, V value) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
mDiskCache.put(diskKey, value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put value to memory cache and disk cache
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void put(String key, V value) {
|
||||
putToMemory(key, value);
|
||||
putToDisk(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to temporarily pause the disk cache while the user is scrolling to
|
||||
* improve scrolling.
|
||||
*
|
||||
* @param pause True to temporarily pause the disk cache, false otherwise.
|
||||
*/
|
||||
public void setPauseDiskCache(final boolean pause) {
|
||||
synchronized (mPauseLock) {
|
||||
if (mPauseDiskAccess != pause) {
|
||||
mPauseDiskAccess = pause;
|
||||
if (!pause) {
|
||||
mPauseLock.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void waitUntilUnpaused() {
|
||||
synchronized (mPauseLock) {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) {
|
||||
while (mPauseDiskAccess) {
|
||||
try {
|
||||
mPauseLock.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// ignored, we'll start waiting again
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts all of the items from the memory cache
|
||||
*/
|
||||
public void clearMemory() {
|
||||
if (mHasMemoryCache) {
|
||||
mMemoryCache.evictAll();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear disk cache
|
||||
*/
|
||||
public void clearDisk() {
|
||||
if (mHasDiskCache) {
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null && !mDiskCache.isClosed()) {
|
||||
try {
|
||||
mDiskCache.delete();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "AnyCache clearCache", e);
|
||||
}
|
||||
File cacheDir = mDiskCache.getCacheDir();
|
||||
int maxSize = mDiskCache.getMaxSize();
|
||||
mDiskCache = null;
|
||||
initDiskCache(cacheDir, maxSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
if (mHasDiskCache) {
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
try {
|
||||
mDiskCache.flush();
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "AnyCache flush", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts all of the items from the memory cache and lets the system know
|
||||
* now would be a good time to garbage collect
|
||||
*/
|
||||
public void clear() {
|
||||
clearMemory();
|
||||
clearDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* A hashing method that changes a string (like a URL) into a hash suitable
|
||||
* for using as a disk filename.
|
||||
*
|
||||
* @param key The key used to store the file
|
||||
*/
|
||||
private static String hashKeyForDisk(final String key) {
|
||||
String cacheKey;
|
||||
try {
|
||||
final MessageDigest digest = MessageDigest.getInstance("MD5");
|
||||
digest.update(key.getBytes());
|
||||
cacheKey = bytesToHexString(digest.digest());
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
cacheKey = String.valueOf(key.hashCode());
|
||||
}
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* http://stackoverflow.com/questions/332079
|
||||
*
|
||||
* @param bytes The bytes to convert.
|
||||
* @return A {@link String} converted from the bytes of a hashable key used
|
||||
* to store a filename on the disk, to hex digits.
|
||||
*/
|
||||
private static String bytesToHexString(final byte[] bytes) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (final byte b : bytes) {
|
||||
final String hex = Integer.toHexString(0xFF & b);
|
||||
if (hex.length() == 1) {
|
||||
builder.append('0');
|
||||
}
|
||||
builder.append(hex);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A holder class that contains cache parameters.
|
||||
*/
|
||||
public static class AnyCacheParams {
|
||||
|
||||
public boolean hasMemoryCache = false;
|
||||
public int memoryCacheMaxSize = 0;
|
||||
public boolean hasDiskCache = false;
|
||||
public File diskCacheDir = null;
|
||||
public int diskCacheMaxSize = 0;
|
||||
|
||||
/**
|
||||
* Check AnyCacheParams is valid
|
||||
*
|
||||
* @throws IllegalStateException
|
||||
*/
|
||||
public void isValid() throws IllegalStateException {
|
||||
if (!hasMemoryCache && !hasDiskCache) {
|
||||
throw new IllegalStateException("No memory cache and no disk cache. What can I do for you?");
|
||||
}
|
||||
|
||||
if (hasMemoryCache && memoryCacheMaxSize <= 0) {
|
||||
throw new IllegalStateException("Memory cache max size must be bigger than 0.");
|
||||
}
|
||||
|
||||
if (hasDiskCache) {
|
||||
if (diskCacheDir == null) {
|
||||
throw new IllegalStateException("Disk cache dir can't be null.");
|
||||
}
|
||||
if (diskCacheMaxSize <= 0) {
|
||||
throw new IllegalStateException("Disk cache max size must be bigger than 0.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MemoryCahce<E> extends LruCache<String, E> {
|
||||
|
||||
public AnyCache<E> mParent;
|
||||
|
||||
public MemoryCahce(int maxSize, AnyCache<E> parent) {
|
||||
super(maxSize);
|
||||
mParent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int sizeOf(String key, E value) {
|
||||
return mParent.sizeOf(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DiskCache<E> {
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
private DiskLruCache mDiskLruCache;
|
||||
private AnyCache<E> mParent;
|
||||
|
||||
private File mCacheDir;
|
||||
private int mMaxSize;
|
||||
|
||||
public DiskCache(File cacheDir, int size, AnyCache<E> parent) throws IOException {
|
||||
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
|
||||
mParent = parent;
|
||||
|
||||
mCacheDir = cacheDir;
|
||||
mMaxSize = size;
|
||||
}
|
||||
|
||||
public File getCacheDir() {
|
||||
return mCacheDir;
|
||||
}
|
||||
|
||||
public int getMaxSize() {
|
||||
return mMaxSize;
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return mDiskLruCache.isClosed();
|
||||
}
|
||||
|
||||
public void delete() throws IOException {
|
||||
mDiskLruCache.delete();
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
mDiskLruCache.flush();
|
||||
}
|
||||
|
||||
public E get(String key) {
|
||||
DiskLruCache.Snapshot snapshot = null;
|
||||
try {
|
||||
snapshot = mDiskLruCache.get(key);
|
||||
if ( snapshot == null ) {
|
||||
// Miss
|
||||
return null;
|
||||
}
|
||||
|
||||
final InputStream in = snapshot.getInputStream(0);
|
||||
if (in != null) {
|
||||
final BufferedInputStream buffIn =
|
||||
new BufferedInputStream(in, IO_BUFFER_SIZE);
|
||||
return mParent.read(buffIn);
|
||||
} else {
|
||||
// Can't get InputStream
|
||||
return null;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
Util.closeQuietly(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean put(String key, E value) {
|
||||
DiskLruCache.Editor editor = null;
|
||||
OutputStream os = null;
|
||||
boolean completeEdit = false;
|
||||
try {
|
||||
editor = mDiskLruCache.edit(key);
|
||||
if (editor == null) {
|
||||
// The editor is in progress
|
||||
return false;
|
||||
}
|
||||
|
||||
os = editor.newOutputStream(0);
|
||||
if (os != null) {
|
||||
final BufferedOutputStream buffOut =
|
||||
new BufferedOutputStream(os, IO_BUFFER_SIZE);
|
||||
boolean result = mParent.write(buffOut, value);
|
||||
completeEdit = true;
|
||||
editor.commit();
|
||||
return result;
|
||||
} else {
|
||||
// Can't get OutputStream
|
||||
completeEdit = true;
|
||||
editor.abort();
|
||||
return false;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Util.closeQuietly(os);
|
||||
try {
|
||||
if (!completeEdit && editor != null) {
|
||||
editor.abort();
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,943 @@
|
||||
/*
|
||||
* 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.cache;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class ImageCache extends AnyCache<Bitmap>{
|
||||
|
||||
private static final String TAG = "ImageCache";
|
||||
|
||||
/**
|
||||
* Default memory cache size as a percent of device memory class
|
||||
*/
|
||||
private static final float MEM_CACHE_DIVIDER = 0.25f;
|
||||
|
||||
/**
|
||||
* Compression settings when writing images to disk cache
|
||||
*/
|
||||
private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
|
||||
|
||||
/**
|
||||
* Image compression quality
|
||||
*/
|
||||
private static final int COMPRESS_QUALITY = 98;
|
||||
|
||||
private static ImageCache sImageCache;
|
||||
|
||||
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
|
||||
if (sImageCache == null) {
|
||||
final ActivityManager activityManager = (ActivityManager)context
|
||||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
|
||||
* 1024 * 1024);
|
||||
|
||||
AnyCacheParams params = new AnyCacheParams();
|
||||
params.hasMemoryCache = true;
|
||||
params.memoryCacheMaxSize = memoryCacheMax;
|
||||
params.hasDiskCache = true;
|
||||
params.diskCacheDir = getDiskCacheDir(context, TAG);
|
||||
params.diskCacheMaxSize = 20 * 1024 * 1024;
|
||||
|
||||
sImageCache = new ImageCache(params);
|
||||
}
|
||||
return sImageCache;
|
||||
}
|
||||
|
||||
public ImageCache(AnyCacheParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int sizeOf(String key, Bitmap value) {
|
||||
return value.getByteCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Bitmap read(InputStream is) {
|
||||
return BitmapFactory.decodeStream(is);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean write(OutputStream os, Bitmap value) {
|
||||
return value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the external app cache directory
|
||||
*
|
||||
* @param context The {@link Context} to use
|
||||
* @return The external cache directory
|
||||
*/
|
||||
private static File getExternalCacheDir(final Context context) {
|
||||
return context.getExternalCacheDir();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a usable cache directory (external if available, internal otherwise)
|
||||
*
|
||||
* @param context The {@link Context} to use
|
||||
* @param uniqueName A unique directory name to append to the cache
|
||||
* directory
|
||||
* @return The cache directory
|
||||
*/
|
||||
private static File getDiskCacheDir(final Context context, final String uniqueName) {
|
||||
// getExternalCacheDir(context) returns null if external storage is not ready
|
||||
final String cachePath = getExternalCacheDir(context) != null
|
||||
? getExternalCacheDir(context).getPath()
|
||||
: context.getCacheDir().getPath();
|
||||
return new File(cachePath, uniqueName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+5
@@ -98,4 +98,9 @@ public class ApiGalleryDetail extends ApiGalleryInfo
|
||||
public String[] getTags() {
|
||||
return apiTags;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo toGalleryInfo() {
|
||||
return new GalleryInfo(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File renamed without changes.
+288
-19
@@ -21,26 +21,41 @@ import java.util.List;
|
||||
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.hippo.ehviewer.Analytics;
|
||||
import com.hippo.ehviewer.service.DownloadService;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.SqlUtils;
|
||||
|
||||
// TODO
|
||||
// what a mess
|
||||
// refactoring
|
||||
|
||||
/**
|
||||
* @author Hippo
|
||||
*
|
||||
* Ver 2: 移除 read 表,添加 Download 表
|
||||
* Ver 3: Download 表添加下载时间项
|
||||
* Ver 4: 添历史记录
|
||||
*/
|
||||
public class Data {
|
||||
private static final String TAG = "Data";
|
||||
|
||||
private static final int VERSION = 2;
|
||||
private static final int VERSION = 4;
|
||||
private static final String DB_NAME = "data";
|
||||
|
||||
private static final String TABLE_GALLERY = "gallery";
|
||||
private static final String TABLE_LOCAL_FAVOURITE = "local_favourite";
|
||||
private static final String TABLE_TAG = "tag";
|
||||
private static final String TABLE_DOWNLOAD = "download";
|
||||
private static final String TABLE_HISTORY = "history";
|
||||
|
||||
private static final String COLUMN_GID = "gid";
|
||||
private static final String COLUMN_TOKEN = "token";
|
||||
@@ -63,6 +78,8 @@ public class Data {
|
||||
private static final String COLUMN_STATE = "state";
|
||||
private static final String COLUMN_LEGACY = "legacy";
|
||||
|
||||
private static final String COLUMN_DATE = "date";
|
||||
|
||||
private final SparseArray<GalleryInfo> mGallerys;
|
||||
|
||||
private long mTagRowNum;
|
||||
@@ -87,11 +104,11 @@ public class Data {
|
||||
|
||||
public Data(Context context) {
|
||||
mContext = context;
|
||||
mGallerys = new SparseArray<GalleryInfo>();
|
||||
|
||||
mDBHelper = new DBHelper(mContext);
|
||||
mDatabase = mDBHelper.getWritableDatabase();
|
||||
|
||||
mGallerys = new SparseArray<GalleryInfo>();
|
||||
|
||||
getTags();
|
||||
getLocalFavourites();
|
||||
getDownloads();
|
||||
@@ -110,10 +127,10 @@ public class Data {
|
||||
* @param gid
|
||||
* @return
|
||||
*/
|
||||
public GalleryInfo getGallery(int gid) {
|
||||
public GalleryInfo getGallery(SQLiteDatabase db, int gid) {
|
||||
GalleryInfo galleryInfo = mGallerys.get(gid);
|
||||
if (galleryInfo == null) {
|
||||
Cursor cursor = mDatabase.rawQuery("select * from " + TABLE_GALLERY + " where " + COLUMN_GID + "=?",
|
||||
Cursor cursor = db.rawQuery("select * from " + TABLE_GALLERY + " where " + COLUMN_GID + "=?",
|
||||
new String[]{String.valueOf(gid)});
|
||||
if (cursor.moveToFirst()) {
|
||||
galleryInfo = new GalleryInfo();
|
||||
@@ -200,7 +217,7 @@ public class Data {
|
||||
values.put(COLUMN_REFERENCE, reference);
|
||||
|
||||
if (isInsert) { // Set
|
||||
long id = mDatabase.insert(TABLE_GALLERY, null, values);
|
||||
mDatabase.insert(TABLE_GALLERY, null, values);
|
||||
} else { // Update
|
||||
mDatabase.update(TABLE_GALLERY, values, COLUMN_GID + "=?", new String[]{String.valueOf(gid)});
|
||||
}
|
||||
@@ -253,15 +270,18 @@ public class Data {
|
||||
|
||||
/****** download ******/
|
||||
private synchronized void getDownloads() {
|
||||
boolean startService = false;
|
||||
boolean keepDownloadService = Config.getKeepDownloadService();
|
||||
mDownloads = new ArrayList<DownloadInfo>();
|
||||
|
||||
Cursor cursor = mDatabase.rawQuery("select * from "
|
||||
+ TABLE_DOWNLOAD, null);
|
||||
Cursor cursor = mDatabase.rawQuery("select * from " + TABLE_DOWNLOAD
|
||||
+ " order by " + COLUMN_DATE + " asc", null);
|
||||
|
||||
if (cursor.moveToFirst()) {
|
||||
while (!cursor.isAfterLast()) {
|
||||
|
||||
int gid = cursor.getInt(0);
|
||||
GalleryInfo galleryInfo = getGallery(gid);
|
||||
GalleryInfo galleryInfo = getGallery(mDatabase, gid);
|
||||
if (galleryInfo == null) {
|
||||
cursor.moveToNext();
|
||||
continue;
|
||||
@@ -269,8 +289,14 @@ public class Data {
|
||||
int mode = cursor.getInt(1);
|
||||
int state = cursor.getInt(2);
|
||||
int legacy = cursor.getInt(3);
|
||||
if (state == DownloadInfo.STATE_WAIT || state == DownloadInfo.STATE_DOWNLOAD)
|
||||
state = DownloadInfo.STATE_NONE;
|
||||
if (state == DownloadInfo.STATE_WAIT || state == DownloadInfo.STATE_DOWNLOAD) {
|
||||
if (keepDownloadService) {
|
||||
state = DownloadInfo.STATE_WAIT;
|
||||
startService = true;
|
||||
} else {
|
||||
state = DownloadInfo.STATE_NONE;
|
||||
}
|
||||
}
|
||||
|
||||
DownloadInfo downloadInfo = new DownloadInfo(
|
||||
galleryInfo, mode, state, legacy);
|
||||
@@ -280,6 +306,11 @@ public class Data {
|
||||
}
|
||||
}
|
||||
cursor.close();
|
||||
|
||||
if (startService) {
|
||||
Intent it = new Intent(mContext, DownloadService.class);
|
||||
mContext.startService(it);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,6 +342,12 @@ public class Data {
|
||||
return re;
|
||||
}
|
||||
|
||||
/**
|
||||
* If exits, just update
|
||||
*
|
||||
* @param downloadInfo
|
||||
* @return
|
||||
*/
|
||||
public synchronized boolean addDownload(DownloadInfo downloadInfo) {
|
||||
GalleryInfo galleryInfo = downloadInfo.galleryInfo;
|
||||
int gid = galleryInfo.gid;
|
||||
@@ -335,6 +372,9 @@ public class Data {
|
||||
COLUMN_GID + "=?", new String[]{String.valueOf(galleryInfo.gid)});
|
||||
return false;
|
||||
} else {
|
||||
// If not update, set date
|
||||
values.put(COLUMN_DATE, System.currentTimeMillis());
|
||||
|
||||
if (mDatabase.insert(TABLE_DOWNLOAD, null,
|
||||
values) != -1) { // If add ok
|
||||
mDownloads.add(downloadInfo);
|
||||
@@ -386,6 +426,48 @@ public class Data {
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized void setDownloadState(int gid, int state) {
|
||||
setDownloadState(getDownload(gid), state);
|
||||
}
|
||||
|
||||
public synchronized void setDownloadState(DownloadInfo di, int state) {
|
||||
if (di == null || di.state == state)
|
||||
return;
|
||||
|
||||
di.state = state;
|
||||
// Update in db
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(COLUMN_STATE, state);
|
||||
mDatabase.update(TABLE_DOWNLOAD, values,
|
||||
COLUMN_GID + "=?", new String[]{String.valueOf(di.galleryInfo.gid)});
|
||||
}
|
||||
|
||||
/**
|
||||
* If state is STATE_NONE or state is STATE_FINISH and legacy is not 0,
|
||||
* make state STATE_WAIT
|
||||
*/
|
||||
public synchronized void startAllDownload() {
|
||||
for (DownloadInfo di : mDownloads) {
|
||||
if (di.state == DownloadInfo.STATE_NONE ||
|
||||
(di.state == DownloadInfo.STATE_FINISH && di.legacy != 0)) {
|
||||
setDownloadState(di, DownloadInfo.STATE_WAIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If state is STATE_WAIT or STATE_DOWNLOAD,
|
||||
* make state STATE_NONE
|
||||
*/
|
||||
public synchronized void stopAllDownload() {
|
||||
for (DownloadInfo di : mDownloads) {
|
||||
if (di.state == DownloadInfo.STATE_WAIT ||
|
||||
di.state == DownloadInfo.STATE_DOWNLOAD) {
|
||||
setDownloadState(di, DownloadInfo.STATE_NONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/****** local favourite ******/
|
||||
private synchronized void getLocalFavourites() {
|
||||
mLocalFavourites = new ArrayList<GalleryInfo>();
|
||||
@@ -395,8 +477,9 @@ public class Data {
|
||||
if (cursor.moveToFirst()) {
|
||||
while (!cursor.isAfterLast()) {
|
||||
int gid = cursor.getInt(0);
|
||||
GalleryInfo galleryInfo = getGallery(gid);
|
||||
mLocalFavourites.add(galleryInfo);
|
||||
GalleryInfo galleryInfo = getGallery(mDatabase, gid);
|
||||
if (galleryInfo != null)
|
||||
mLocalFavourites.add(galleryInfo);
|
||||
cursor.moveToNext();
|
||||
}
|
||||
}
|
||||
@@ -593,6 +676,113 @@ public class Data {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static final int NONE = 0x0;
|
||||
public static final int BROWSE = 0x1;
|
||||
public static final int READ = 0x2;
|
||||
|
||||
public synchronized List<HistoryItem> getHistory(int mode, boolean desc) {
|
||||
List<HistoryItem> history = new ArrayList<>();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("select * from ").append(TABLE_HISTORY);
|
||||
boolean first = true;
|
||||
if (mode != 0) {
|
||||
sb.append(" where " + COLUMN_MODE + " in (");
|
||||
for (int b = 1; b <= READ; b <<= 1) {
|
||||
if ((mode & b) != 0) {
|
||||
sb.append(first ? "" : ", ").append(b);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
sb.append(")");
|
||||
}
|
||||
sb.append(" order by ").append(COLUMN_DATE).append(desc ? " desc" : " asc");
|
||||
|
||||
Log.d(TAG, sb.toString());
|
||||
|
||||
Cursor cursor = mDatabase.rawQuery(sb.toString(), null);
|
||||
if (cursor.moveToFirst()) {
|
||||
while (!cursor.isAfterLast()) {
|
||||
int gid = cursor.getInt(0);
|
||||
GalleryInfo gi = getGallery(mDatabase, gid);
|
||||
if (gi != null) {
|
||||
history.add(new HistoryItem(gi, cursor.getInt(1), cursor.getLong(2)));
|
||||
}
|
||||
cursor.moveToNext();
|
||||
}
|
||||
}
|
||||
cursor.close();
|
||||
|
||||
return history;
|
||||
}
|
||||
|
||||
public synchronized int containsHistory(int gid) {
|
||||
int re;
|
||||
Cursor cursor = mDatabase.rawQuery("select * from "
|
||||
+ TABLE_HISTORY + " where " + COLUMN_GID + "=?",
|
||||
new String[]{String.valueOf(gid)});
|
||||
if (cursor.moveToFirst())
|
||||
re = cursor.getInt(1);
|
||||
else
|
||||
re = NONE;
|
||||
cursor.close();
|
||||
return re;
|
||||
}
|
||||
|
||||
private int checkMode(int mode) {
|
||||
return MathUtils.clamp(mode, NONE, READ);
|
||||
}
|
||||
|
||||
public synchronized void addHistory(GalleryInfo gi, int mode) {
|
||||
mode = checkMode(mode);
|
||||
|
||||
long curDate = System.currentTimeMillis();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(COLUMN_GID, gi.gid);
|
||||
values.put(COLUMN_DATE, curDate);
|
||||
|
||||
int curMode = checkMode(containsHistory(gi.gid));
|
||||
if (curMode == NONE) {
|
||||
// Add new record
|
||||
values.put(COLUMN_MODE, mode);
|
||||
mDatabase.insert(TABLE_HISTORY, null, values);
|
||||
addGallery(gi);
|
||||
|
||||
truncateHistory(Config.getMaxHistoryCount());
|
||||
} else {
|
||||
// Update record
|
||||
int newMode = Math.max(curMode, mode);
|
||||
values.put(COLUMN_MODE, newMode);
|
||||
mDatabase.update(TABLE_HISTORY, values,
|
||||
COLUMN_GID + "=?", new String[]{String.valueOf(gi.gid)});
|
||||
updateGallery(gi);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void deleteHistory(int gid) {
|
||||
mDatabase.delete(TABLE_HISTORY, COLUMN_GID + "=?", new String[]{String.valueOf(gid)});
|
||||
deleteGallery(gid);
|
||||
}
|
||||
|
||||
public void clearHistory() {
|
||||
truncateHistory(0);
|
||||
}
|
||||
|
||||
protected synchronized void truncateHistory(int maxEntries) {
|
||||
if (maxEntries < 0) {
|
||||
return;
|
||||
} else if (maxEntries == 0) {
|
||||
mDatabase.delete(TABLE_HISTORY, null, null);
|
||||
} else {
|
||||
try {
|
||||
mDatabase.execSQL("delete from " + TABLE_HISTORY + " where " + COLUMN_GID
|
||||
+ " in " + "(select " + COLUMN_GID + " from " + TABLE_HISTORY
|
||||
+ " order by " + COLUMN_DATE + " desc limit " + maxEntries
|
||||
+ ", -1);");
|
||||
} catch(Throwable e){}
|
||||
}
|
||||
}
|
||||
|
||||
public class DBHelper extends SQLiteOpenHelper {
|
||||
|
||||
public DBHelper(Context context) {
|
||||
@@ -635,11 +825,14 @@ public class Data {
|
||||
db.execSQL(CreateTag);
|
||||
|
||||
// download
|
||||
createDownloadTable(db);
|
||||
createDownloadTableVer3(db);
|
||||
|
||||
// History
|
||||
createHistoryTable(db);
|
||||
}
|
||||
|
||||
private void createDownloadTable(SQLiteDatabase db) {
|
||||
String CreateDownload = "create table "
|
||||
private void createDownloadTableVer2(SQLiteDatabase db) {
|
||||
String createDownload = "create table "
|
||||
+ TABLE_DOWNLOAD + "("
|
||||
+ COLUMN_GID + " integer primary key,"
|
||||
+ COLUMN_MODE + " integer,"
|
||||
@@ -647,7 +840,77 @@ public class Data {
|
||||
+ COLUMN_LEGACY + " integer,"
|
||||
+ "foreign key(" + COLUMN_GID + ") references " + TABLE_GALLERY + "(" + COLUMN_GID + "));";
|
||||
|
||||
SqlUtils.exeSQLSafely(db, CreateDownload);
|
||||
SqlUtils.exeSQLSafely(db, createDownload);
|
||||
}
|
||||
|
||||
private synchronized List<DownloadInfo> getDownloadsVer2(SQLiteDatabase db) {
|
||||
List<DownloadInfo> list = new ArrayList<DownloadInfo>();
|
||||
|
||||
Cursor cursor = db.rawQuery("select * from " + TABLE_DOWNLOAD,
|
||||
null);
|
||||
|
||||
if (cursor.moveToFirst()) {
|
||||
while (!cursor.isAfterLast()) {
|
||||
|
||||
int gid = cursor.getInt(0);
|
||||
GalleryInfo galleryInfo = getGallery(db, gid);
|
||||
if (galleryInfo == null) {
|
||||
cursor.moveToNext();
|
||||
continue;
|
||||
}
|
||||
int mode = cursor.getInt(1);
|
||||
int state = cursor.getInt(2);
|
||||
int legacy = cursor.getInt(3);
|
||||
if (state == DownloadInfo.STATE_WAIT || state == DownloadInfo.STATE_DOWNLOAD)
|
||||
state = DownloadInfo.STATE_NONE;
|
||||
|
||||
DownloadInfo downloadInfo = new DownloadInfo(
|
||||
galleryInfo, mode, state, legacy);
|
||||
list.add(downloadInfo);
|
||||
|
||||
cursor.moveToNext();
|
||||
}
|
||||
}
|
||||
cursor.close();
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private void createDownloadTableVer3(SQLiteDatabase db) {
|
||||
String createDownload = "create table "
|
||||
+ TABLE_DOWNLOAD + "("
|
||||
+ COLUMN_GID + " integer primary key,"
|
||||
+ COLUMN_MODE + " integer,"
|
||||
+ COLUMN_STATE + " integer,"
|
||||
+ COLUMN_LEGACY + " integer,"
|
||||
+ COLUMN_DATE + " long,"
|
||||
+ "foreign key(" + COLUMN_GID + ") references " + TABLE_GALLERY + "(" + COLUMN_GID + "));";
|
||||
|
||||
SqlUtils.exeSQLSafely(db, createDownload);
|
||||
}
|
||||
|
||||
public void addDownloadInfoVer3(SQLiteDatabase db, List<DownloadInfo> l) {
|
||||
for (int i = 0; i < l.size(); i++) {
|
||||
DownloadInfo di = l.get(i);
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(COLUMN_GID, di.galleryInfo.gid);
|
||||
values.put(COLUMN_MODE, di.mode);
|
||||
values.put(COLUMN_STATE, di.state);
|
||||
values.put(COLUMN_LEGACY, di.legacy);
|
||||
values.put(COLUMN_DATE, (long) i);
|
||||
db.insert(TABLE_DOWNLOAD, null, values);
|
||||
}
|
||||
}
|
||||
|
||||
private void createHistoryTable(SQLiteDatabase db) {
|
||||
String createDownload = "create table "
|
||||
+ TABLE_HISTORY + "("
|
||||
+ COLUMN_GID + " integer primary key,"
|
||||
+ COLUMN_MODE + " integer,"
|
||||
+ COLUMN_DATE + " long,"
|
||||
+ "foreign key(" + COLUMN_GID + ") references " + TABLE_GALLERY + "(" + COLUMN_GID + "));";
|
||||
|
||||
SqlUtils.exeSQLSafely(db, createDownload);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -656,8 +919,14 @@ public class Data {
|
||||
case 1:
|
||||
SqlUtils.dropTable(db, TABLE_DOWNLOAD);
|
||||
SqlUtils.dropTable(db, "read");
|
||||
createDownloadTable(db);
|
||||
break;
|
||||
createDownloadTableVer2(db);
|
||||
case 2:
|
||||
List<DownloadInfo> l = getDownloadsVer2(db);
|
||||
SqlUtils.dropTable(db, TABLE_DOWNLOAD);
|
||||
createDownloadTableVer3(db);
|
||||
addDownloadInfoVer3(db, l);
|
||||
case 3:
|
||||
createHistoryTable(db);
|
||||
case VERSION:
|
||||
break;
|
||||
default:
|
||||
+14
-2
@@ -16,8 +16,10 @@
|
||||
|
||||
package com.hippo.ehviewer.data;
|
||||
|
||||
import com.hippo.ehviewer.widget.ExpandableListItem;
|
||||
|
||||
public class DownloadInfo {
|
||||
|
||||
public class DownloadInfo implements ExpandableListItem {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = DownloadInfo.class.getSimpleName();
|
||||
|
||||
@@ -35,7 +37,7 @@ public class DownloadInfo {
|
||||
public volatile int total = -1;
|
||||
public volatile int legacy;
|
||||
|
||||
public boolean selected = false;
|
||||
private boolean mExpanded = false;
|
||||
|
||||
public DownloadInfo(GalleryInfo gi, int mode) {
|
||||
this.galleryInfo = gi;
|
||||
@@ -48,4 +50,14 @@ public class DownloadInfo {
|
||||
this.state = state;
|
||||
this.legacy = legacy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExpanded(boolean expanded) {
|
||||
mExpanded = expanded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getExpanded() {
|
||||
return mExpanded;
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.hippo.ehviewer.data;
|
||||
|
||||
import android.util.Pair;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@@ -37,12 +39,17 @@ public class GalleryDetail extends GalleryInfo
|
||||
*/
|
||||
public LinkedHashMap<String, LinkedList<String>> tags;
|
||||
|
||||
public boolean isFavorite;
|
||||
|
||||
// For Preview
|
||||
public int previewSum;
|
||||
public int previewPerPage;
|
||||
public PreviewList[] previewLists;
|
||||
public List<Comment> comments;
|
||||
|
||||
public String torrentUrl;
|
||||
public Pair<String, String>[] torrents;
|
||||
|
||||
public GalleryDetail() {}
|
||||
|
||||
public GalleryDetail(GalleryInfo galleryInfo) {
|
||||
@@ -84,7 +91,7 @@ public class GalleryDetail extends GalleryInfo
|
||||
|
||||
@Override
|
||||
public PreviewList getPreview(int page) {
|
||||
if (page >= 0 && page < previewLists.length)
|
||||
if (page >= 0 && previewLists != null && page < previewLists.length)
|
||||
return previewLists[page];
|
||||
else
|
||||
return null;
|
||||
@@ -92,7 +99,15 @@ public class GalleryDetail extends GalleryInfo
|
||||
|
||||
@Override
|
||||
public void setPreview(int page, PreviewList previewList) {
|
||||
if (page >= 0 && page < previewLists.length)
|
||||
if (previewLists == null && previewSum > 0)
|
||||
previewLists = new PreviewList[previewSum];
|
||||
|
||||
if (page >= 0 && previewLists != null && page < previewLists.length)
|
||||
previewLists[page] = previewList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo toGalleryInfo() {
|
||||
return new GalleryInfo(this);
|
||||
}
|
||||
}
|
||||
+34
-3
@@ -61,9 +61,9 @@ public class GalleryInfo implements Parcelable {
|
||||
|
||||
public static final String[] S_LANG_PATTERNS = {
|
||||
"[(\\[]eng(?:lish)?[)\\]]",
|
||||
"[((\\[]chinese[))\\]]|[汉漢]化",
|
||||
"[((\\[]chinese[))\\]]|[汉漢]化|中[国國][语語]|中文|[(\\[]CN[)\\]]",
|
||||
"[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]",
|
||||
"[(\\[]korean[)\\]]",
|
||||
"[(\\[]korean?[)\\]]",
|
||||
"[(\\[]rus(?:sian)?[)\\]]",
|
||||
"[(\\[]fr(?:ench)?[)\\]]",
|
||||
"[(\\[]portuguese",
|
||||
@@ -76,7 +76,6 @@ public class GalleryInfo implements Parcelable {
|
||||
"[(\\[]dutch[)\\]]",
|
||||
};
|
||||
|
||||
|
||||
public int gid;
|
||||
public String token;
|
||||
public String title;
|
||||
@@ -85,6 +84,14 @@ public class GalleryInfo implements Parcelable {
|
||||
public String thumb;
|
||||
public String uploader;
|
||||
public float rating;
|
||||
/**
|
||||
* Will not be recond
|
||||
*/
|
||||
public int thumbWidth;
|
||||
/**
|
||||
* Will not be recond
|
||||
*/
|
||||
public int thumbHeight;
|
||||
/**
|
||||
* language get from title
|
||||
*/
|
||||
@@ -131,6 +138,30 @@ public class GalleryInfo implements Parcelable {
|
||||
dest.writeString(simpleLanguage);
|
||||
}
|
||||
|
||||
public GalleryInfo() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public GalleryInfo(GalleryInfo gi) {
|
||||
gid = gi.gid;
|
||||
token = gi.token;
|
||||
title = gi.title;
|
||||
posted = gi.posted;
|
||||
category = gi.category;
|
||||
thumb = gi.thumb;
|
||||
uploader = gi.uploader;
|
||||
rating = gi.rating;
|
||||
simpleLanguage = gi.simpleLanguage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof GalleryInfo && ((GalleryInfo) o).gid == gid)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public final void generateSLang() {
|
||||
for (int i = 0; i < S_LANGS.length; i++) {
|
||||
if (Pattern.compile(S_LANG_PATTERNS[i], Pattern.CASE_INSENSITIVE).matcher(title).find()) {
|
||||
-5
@@ -46,11 +46,6 @@ public class GalleryPopular extends GalleryInfo {
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
super.writeToParcel(dest, flags);
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-4
@@ -83,9 +83,7 @@ public class LargePreviewList extends PreviewList {
|
||||
// Add to read in Data
|
||||
Intent intent = new Intent(mActivity,
|
||||
GalleryActivity.class);
|
||||
intent.putExtra(GalleryActivity.KEY_GID, mPi.getGid());
|
||||
intent.putExtra(GalleryActivity.KEY_TOKEN, mPi.getToken());
|
||||
intent.putExtra(GalleryActivity.KEY_TITLE, mPi.getTitle());
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mPi.toGalleryInfo());
|
||||
intent.putExtra(GalleryActivity.KEY_START_INDEX, _index);
|
||||
mActivity.startActivity(intent);
|
||||
}
|
||||
@@ -115,7 +113,7 @@ public class LargePreviewList extends PreviewList {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGetImage(String key, Bitmap bmp) {
|
||||
public void onGetImage(String key, Bitmap bmp, int state) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
+60
-37
@@ -21,6 +21,7 @@ import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.network.UrlBuilder;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
@@ -214,98 +215,120 @@ public class ListUrls {
|
||||
}
|
||||
|
||||
public String getUrl(int mode) {
|
||||
StringBuilder url = new StringBuilder(EhClient.getUrlHeader(mode));
|
||||
|
||||
switch (mMode) {
|
||||
case MODE_POPULAR:
|
||||
return null;
|
||||
|
||||
case MODE_IMAGE_SEARCH:
|
||||
if (mResultUrl == null) {
|
||||
if (mResultUrl == null)
|
||||
return null;
|
||||
} else {
|
||||
else
|
||||
return mResultUrl + "&page=" + page;
|
||||
}
|
||||
|
||||
case MODE_TAG:
|
||||
// Add tag
|
||||
url.append("tag/");
|
||||
StringBuilder sb = new StringBuilder(EhClient.getUrlHeader(mode));
|
||||
sb.append("tag/");
|
||||
if (mTag != null) {
|
||||
String[] tag = mTag.split("\\s+");
|
||||
try {
|
||||
for (int i = 0; i < tag.length; i++)
|
||||
tag[i] = URLEncoder.encode(tag[i], "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {}
|
||||
url.append(Utils.join(tag, '+'));
|
||||
sb.append(Utils.join(tag, '+'));
|
||||
|
||||
// Add page
|
||||
url.append("/").append(page);
|
||||
sb.append("/").append(page);
|
||||
} else {
|
||||
url.append(page);
|
||||
sb.append(page);
|
||||
}
|
||||
break;
|
||||
return sb.toString();
|
||||
|
||||
case MODE_NORMAL:
|
||||
case MODE_UPLOADER:
|
||||
default:
|
||||
String header = EhClient.getUrlHeader(mode);
|
||||
boolean isNeedFooter = false;
|
||||
UrlBuilder ub;
|
||||
// Add category
|
||||
if (category != NONE) {
|
||||
isNeedFooter = true;
|
||||
if (NUM_CATEGORY) {
|
||||
url.append(category).append('?');
|
||||
ub = new UrlBuilder(header + category);
|
||||
} else {
|
||||
url.append("?");
|
||||
if ((category & DOUJINSHI) == 0) url.append("f_doujinshi=0&"); else url.append("f_doujinshi=1&");
|
||||
if ((category & MANGA) == 0) url.append("f_manga=0&"); else url.append("f_manga=1&");
|
||||
if ((category & ARTIST_CG) == 0) url.append("f_artistcg=0&"); else url.append("f_artistcg=1&");
|
||||
if ((category & GAME_CG) == 0) url.append("f_gamecg=0&"); else url.append("f_gamecg=1&");
|
||||
if ((category & WESTERN) == 0) url.append("f_western=0&"); else url.append("f_western=1&");
|
||||
if ((category & NON_H) == 0) url.append("f_non-h=0&"); else url.append("f_non-h=1&");
|
||||
if ((category & IMAGE_SET) == 0) url.append("f_imageset=0&"); else url.append("f_imageset=1&");
|
||||
if ((category & COSPLAY) == 0) url.append("f_cosplay=0&"); else url.append("f_cosplay=1&");
|
||||
if ((category & ASIAN_PORN) == 0) url.append("f_asianporn=0&"); else url.append("f_asianporn=1&");
|
||||
if ((category & MISC) == 0) url.append("f_misc=0&"); else url.append("f_misc=1&");
|
||||
ub = new UrlBuilder(header);
|
||||
ub.addQuery("f_doujinshi", ((category & DOUJINSHI) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_manga", ((category & MANGA) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_artistcg", ((category & ARTIST_CG) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_gamecg", ((category & GAME_CG) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_western", ((category & WESTERN) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_non-h", ((category & NON_H) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_imageset", ((category & IMAGE_SET) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_cosplay", ((category & COSPLAY) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_asianporn", ((category & ASIAN_PORN) == 0) ? "0" : "1");
|
||||
ub.addQuery("f_misc", ((category & MISC) == 0) ? "0" : "1");
|
||||
}
|
||||
} else {
|
||||
url.append('?');
|
||||
ub = new UrlBuilder(header);
|
||||
}
|
||||
|
||||
// Add search item
|
||||
if (search != null) {
|
||||
isNeedFooter = true;
|
||||
url.append("f_search=");
|
||||
|
||||
String[] tag = search.split("\\s+");
|
||||
try {
|
||||
for (int i = 0; i < tag.length; i++)
|
||||
tag[i] = URLEncoder.encode(tag[i], "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {}
|
||||
url.append(Utils.join(tag, '+')).append("&");
|
||||
|
||||
ub.addQuery("f_search", Utils.join(tag, '+'));
|
||||
}
|
||||
|
||||
// Add page
|
||||
url.append("page=").append(page).append("&");
|
||||
if (page != 0) {
|
||||
ub.addQuery("page", page);
|
||||
}
|
||||
|
||||
// Add foot
|
||||
if (isNeedFooter) url.append("f_apply=Apply+Filter");
|
||||
if (isNeedFooter) ub.addQuery("f_apply", "Apply+Filter");
|
||||
|
||||
// Add advance search
|
||||
if (isAdvance()) {
|
||||
url.append("&advsearch=1");
|
||||
if((advsearchType & SNAME) != 0) url.append("&f_sname=on");
|
||||
if((advsearchType & STAGS) != 0) url.append("&f_stags=on");
|
||||
if((advsearchType & SDESC) != 0) url.append("&f_sdesc=on");
|
||||
if((advsearchType & STORR) != 0) url.append("&f_storr=on");
|
||||
if((advsearchType & STO) != 0) url.append("&f_sto=on");
|
||||
if((advsearchType & STD1) != 0) url.append("&f_sdt1=on");
|
||||
if((advsearchType & STD2) != 0) url.append("&f_sdt2=on");
|
||||
if((advsearchType & SH) != 0) url.append("&f_sh=on");
|
||||
ub.addQuery("advsearch", "1");
|
||||
if((advsearchType & SNAME) != 0) ub.addQuery("f_sname", "on");
|
||||
if((advsearchType & STAGS) != 0) ub.addQuery("f_stags", "on");
|
||||
if((advsearchType & SDESC) != 0) ub.addQuery("f_sdesc", "on");
|
||||
if((advsearchType & STORR) != 0) ub.addQuery("f_storr", "on");
|
||||
if((advsearchType & STO) != 0) ub.addQuery("f_sto", "on");
|
||||
if((advsearchType & STD1) != 0) ub.addQuery("f_sdt1", "on");
|
||||
if((advsearchType & STD2) != 0) ub.addQuery("f_sdt2", "on");
|
||||
if((advsearchType & SH) != 0) ub.addQuery("f_sh", "on");
|
||||
|
||||
// Set min star
|
||||
if (isMinRating()) url.append("&f_sr=on&f_srdd=").append(minRating);
|
||||
if (isMinRating()) {
|
||||
ub.addQuery("f_sr", "on");
|
||||
ub.addQuery("f_srdd", minRating);
|
||||
}
|
||||
}
|
||||
return ub.build();
|
||||
}
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
switch (mMode) {
|
||||
case MODE_NORMAL:
|
||||
case MODE_UPLOADER:
|
||||
return search;
|
||||
case MODE_TAG:
|
||||
return mTag;
|
||||
case MODE_POPULAR:
|
||||
case MODE_IMAGE_SEARCH:
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
+5
@@ -96,4 +96,9 @@ public class LofiGalleryDetail extends LofiGalleryInfo
|
||||
public String[] getTags() {
|
||||
return lofiTags;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryInfo toGalleryInfo() {
|
||||
return new GalleryInfo(this);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
+17
-9
@@ -16,8 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer.data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
@@ -31,6 +29,8 @@ import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.ui.GalleryActivity;
|
||||
import com.hippo.ehviewer.widget.SimpleGridLayout;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class NormalPreviewList extends PreviewList{
|
||||
|
||||
public class Item {
|
||||
@@ -113,7 +113,7 @@ public class NormalPreviewList extends PreviewList{
|
||||
int index = mTargetPage * mPi.getPreviewPerPage(); // it is display index
|
||||
int rowIndex = 0;
|
||||
for (NormalPreviewList.Row row : rowArray) {
|
||||
for (NormalPreviewList.Item item : row.itemArray) {
|
||||
for (int i = 0; i < row.itemArray.size(); i++) {
|
||||
View view = inflater.inflate(R.layout.preview_item, null);
|
||||
|
||||
((TextView)view.findViewById(R.id.text)).setText(String.valueOf(index + 1));
|
||||
@@ -125,9 +125,7 @@ public class NormalPreviewList extends PreviewList{
|
||||
// Add to read in Data
|
||||
Intent intent = new Intent(mActivity,
|
||||
GalleryActivity.class);
|
||||
intent.putExtra(GalleryActivity.KEY_GID, mPi.getGid());
|
||||
intent.putExtra(GalleryActivity.KEY_TOKEN, mPi.getToken());
|
||||
intent.putExtra(GalleryActivity.KEY_TITLE, mPi.getTitle());
|
||||
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mPi.toGalleryInfo());
|
||||
intent.putExtra(GalleryActivity.KEY_START_INDEX, _index);
|
||||
mActivity.startActivity(intent);
|
||||
}
|
||||
@@ -154,7 +152,7 @@ public class NormalPreviewList extends PreviewList{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGetImage(String key, Bitmap bmp) {
|
||||
public void onGetImage(String key, Bitmap bmp, int state) {
|
||||
if (mTargetPage != mHolder.getCurPreviewPage())
|
||||
return;
|
||||
|
||||
@@ -168,10 +166,20 @@ public class NormalPreviewList extends PreviewList{
|
||||
int i = row.startIndex;
|
||||
for(Item item : row.itemArray) {
|
||||
|
||||
if (item.xOffset + item.width > maxWidth)
|
||||
if (item.xOffset + item.width > maxWidth) {
|
||||
item.width = maxWidth - item.xOffset;
|
||||
if (item.yOffset + item.height > maxHeight)
|
||||
if (item.width <= 0) {
|
||||
// Bad area
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (item.yOffset + item.height > maxHeight) {
|
||||
item.height = maxHeight - item.yOffset;
|
||||
if (item.height <= 0) {
|
||||
// Bad area
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Bitmap bitmap = Bitmap.createBitmap(bmp, item.xOffset, item.yOffset, item.width, item.height);
|
||||
|
||||
((ImageView)mViewGroup.getChildAt(i).findViewById(R.id.image)).setImageBitmap(bitmap);
|
||||
+2
@@ -47,4 +47,6 @@ public interface PreviewImpl {
|
||||
*/
|
||||
public void setPreview(int page, PreviewList previewList);
|
||||
|
||||
public GalleryInfo toGalleryInfo();
|
||||
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,695 @@
|
||||
/*
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,5 @@
|
||||
package com.hippo.ehviewer.drawable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.TimeInterpolator;
|
||||
@@ -18,6 +16,8 @@ import android.os.Build;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
// Get from android.graphics.drawable.MaterialProgressDrawable
|
||||
public class MaterialProgressDrawable extends Drawable implements Animatable {
|
||||
private static final TimeInterpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
|
||||
+9
-1
@@ -20,21 +20,29 @@ import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
public class OvalDrawable extends Drawable {
|
||||
|
||||
private final Paint mPaint;
|
||||
private final RectF mRectF;
|
||||
|
||||
public OvalDrawable(int color) {
|
||||
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
|
||||
mPaint.setColor(color);
|
||||
mRectF = new RectF();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onBoundsChange(Rect bounds) {
|
||||
mRectF.set(bounds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(Canvas canvas) {
|
||||
canvas.drawOval(new RectF(this.getBounds()), mPaint);
|
||||
canvas.drawOval(mRectF, mPaint);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* 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();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File renamed without changes.
+59
-42
@@ -16,6 +16,13 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import com.hippo.ehviewer.data.Comment;
|
||||
import com.hippo.ehviewer.data.LargePreviewList;
|
||||
import com.hippo.ehviewer.data.NormalPreviewList;
|
||||
import com.hippo.ehviewer.data.PreviewList;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -23,12 +30,6 @@ import java.util.LinkedList;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.hippo.ehviewer.data.Comment;
|
||||
import com.hippo.ehviewer.data.LargePreviewList;
|
||||
import com.hippo.ehviewer.data.NormalPreviewList;
|
||||
import com.hippo.ehviewer.data.PreviewList;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class DetailParser {
|
||||
|
||||
private static final String OFFENSIVE_STRING =
|
||||
@@ -62,15 +63,15 @@ public class DetailParser {
|
||||
public String language;
|
||||
public int people;
|
||||
public float rating;
|
||||
public boolean isFavorite;
|
||||
public String firstPage;
|
||||
public int previewPerPage;
|
||||
public int previewSum;
|
||||
public LinkedHashMap<String, LinkedList<String>> tags;
|
||||
public PreviewList previewList;
|
||||
/**
|
||||
* If no comment, just an empty list
|
||||
**/
|
||||
public LinkedList<Comment> comments;
|
||||
public int torrentNumber;
|
||||
public String torrentUrl;
|
||||
|
||||
public void reset() {
|
||||
eMesg = null;
|
||||
@@ -94,6 +95,8 @@ public class DetailParser {
|
||||
tags = null;
|
||||
previewList = null;
|
||||
comments = null;
|
||||
torrentNumber = 0;
|
||||
torrentUrl = null;
|
||||
}
|
||||
|
||||
public int parser(String body, int mode) {
|
||||
@@ -117,30 +120,43 @@ public class DetailParser {
|
||||
return PINING;
|
||||
}
|
||||
|
||||
p = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
eMesg = m.group(1);
|
||||
return ERROR;
|
||||
}
|
||||
|
||||
// Get detail
|
||||
if ((mode & DETAIL) != 0) {
|
||||
p = Pattern
|
||||
.compile("<div id=\"gd1\"><img src=\"([^\"]+)\"[^<>]+/></div>" // thumb
|
||||
+ "</div>"
|
||||
.compile("<div id=\"gd1\">.+?background:transparent url\\(([^\"]+)\\).+?" // thumb
|
||||
+ "<div id=\"gd2\">"
|
||||
+ "<h1 id=\"gn\">([^<>]+)</h1>" // title
|
||||
+ "<h1 id=\"gj\">([^<>]*)</h1>" // title_jpn might be empty string
|
||||
+ "</div>"
|
||||
+ ".+"
|
||||
+ "<div id=\"gdc\"><a[^<>]+><[^<>]*alt=\"([\\w|\\-]+)\"[^<>]*/></a></div>" // category
|
||||
+ ".+?"
|
||||
+ "<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>"
|
||||
+ ".+?"
|
||||
+ "<div id=\"gdc\"><a[^<>]+><[^<>]*alt=\"([\\w|\\-]+)\"[^<>]*></a></div>" // category
|
||||
+ "<div id=\"gdn\"><a[^<>]+>([^<>]+)</a>" // uploader
|
||||
+ ".+"
|
||||
+ ".+?"
|
||||
+ "<tr><td[^<>]*>Posted:</td><td[^<>]*>([\\w|\\-|\\s|:]+)</td></tr>" // posted
|
||||
+ "<tr><td[^<>]*>Images:</td><td[^<>]*>([\\d]+) @ ([\\w|\\.|\\s]+)</td></tr>" // pages and size
|
||||
+ "<tr><td[^<>]*>Resized:</td><td[^<>]*>([^<>]+)</td></tr>" // resized
|
||||
//+ "<tr><td[^<>]*>Images:</td><td[^<>]*>([\\d]+) @ ([\\w|\\.|\\s]+)</td></tr>" // pages and size
|
||||
//+ "<tr><td[^<>]*>Resized:</td><td[^<>]*>([^<>]+)</td></tr>" // resized
|
||||
+ "<tr><td[^<>]*>Parent:</td><td[^<>]*>(?:<a[^<>]*>)?([^<>]+)(?:</a>)?</td></tr>" // parent
|
||||
+ "<tr><td[^<>]*>Visible:</td><td[^<>]*>([^<>]+)</td></tr>" // visible
|
||||
+ "<tr><td[^<>]*>Language:</td><td[^<>]*>([^<>]+)</td></tr>" // language
|
||||
+ ".+"
|
||||
+ "<td id=\"grt3\">\\(<span id=\"rating_count\">([\\d|,]+)</span>\\)</td>" // people
|
||||
+ "<tr><td[^<>]*>Language:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>[^<>]*</span>)?</td></tr>" // language
|
||||
+ "<tr><td[^<>]*>File Size:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>([^<>]+)</span>)?</td></tr>" // File size and resize
|
||||
+ "<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d|,]+) pages</td></tr>" // pages
|
||||
+ "<tr><td[^<>]*>Favorited:</td><[^<>]*>([^<>]+)</td></tr>" // Favorite times ([\d|,]+) times or Never
|
||||
+ ".+?"
|
||||
+ "<td id=\"grt3\"><span id=\"rating_count\">([\\d|,]+)</span></td>" // people
|
||||
+ "</tr>"
|
||||
+ "<tr><td[^<>]*>([^<>]+)</td>" // rating
|
||||
+ ".+"
|
||||
+ ".+?"
|
||||
+ "<a id=\"favoritelink\"[^<>]*>(.+?)</a>"
|
||||
+ ".+?"
|
||||
+ "<div id=\"gdt\"><div[^<>]*>(?:<div[^<>]*>)?<a[^<>]*href=\"([^<>\"]+)\"[^<>]*>"); // get firstPage
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
@@ -149,30 +165,35 @@ public class DetailParser {
|
||||
thumb = Utils.unescapeXml(m.group(1));
|
||||
title = Utils.unescapeXml(m.group(2));
|
||||
title_jpn = Utils.unescapeXml(m.group(3));
|
||||
category = EhClient.getType(m.group(4));
|
||||
uploader = m.group(5);
|
||||
posted = m.group(6);
|
||||
pages = Integer.parseInt(m.group(7));
|
||||
size = m.group(8);
|
||||
resized = m.group(9);
|
||||
parent = m.group(10);
|
||||
visible = m.group(11);
|
||||
language = m.group(12);
|
||||
people = Integer.parseInt(m.group(13).replace(",", ""));
|
||||
torrentUrl = Utils.unescapeXml(m.group(4));
|
||||
torrentNumber = Utils.parseIntSafely(m.group(5), 0);
|
||||
category = EhUtils.getCategory(m.group(6));
|
||||
uploader = m.group(7);
|
||||
posted = m.group(8);
|
||||
parent = m.group(9);
|
||||
visible = m.group(10);
|
||||
language = Utils.unescapeXml(m.group(11)).trim();
|
||||
size = Utils.unescapeXml(m.group(12)).trim();
|
||||
resized = m.group(13);
|
||||
pages = Integer.parseInt(m.group(14).replace(",", ""));
|
||||
// favoriteTimes = m.group(15)
|
||||
people = Integer.parseInt(m.group(16).replace(",", ""));
|
||||
|
||||
Pattern pattern = Pattern.compile("([\\d|\\.]+)");
|
||||
Matcher matcher = pattern.matcher(m.group(14));
|
||||
Matcher matcher = pattern.matcher(m.group(17));
|
||||
if (matcher.find())
|
||||
rating = Float.parseFloat(matcher.group(1));
|
||||
else
|
||||
rating = Float.NaN;
|
||||
|
||||
firstPage = m.group(15);
|
||||
isFavorite = "Favorite Gallery".equals(m.group(18));
|
||||
|
||||
firstPage = m.group(19);
|
||||
}
|
||||
}
|
||||
// Get tag
|
||||
if ((mode & TAG) != 0) {
|
||||
tags = new LinkedHashMap<String, LinkedList<String>>();
|
||||
tags = new LinkedHashMap<>();
|
||||
p = Pattern
|
||||
.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
|
||||
m = p.matcher(body);
|
||||
@@ -203,23 +224,19 @@ public class DetailParser {
|
||||
isLargePreview = true;
|
||||
|
||||
if (isLargePreview) {
|
||||
previewList = new LargePreviewList();
|
||||
p = Pattern.compile("<div class=\"gdtl\".+?<a href=\"(.+?)\"><img.+?src=\"(.+?)\"");
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
if (previewList == null) {
|
||||
re |= PREVIEW;
|
||||
previewList = new LargePreviewList();
|
||||
}
|
||||
re |= PREVIEW;
|
||||
((LargePreviewList)previewList).addItem(m.group(2), m.group(1));
|
||||
}
|
||||
} else {
|
||||
previewList = new NormalPreviewList();
|
||||
p = Pattern.compile("<div[^<>]*class=\"gdtm\"[^<>]*><div[^<>]*width:(\\d+)[^<>]*height:(\\d+)[^<>]*\\((.+?)\\)[^<>]*-(\\d+)px[^<>]*><a[^<>]*href=\"(.+?)\"[^<>]*>");
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
if (previewList == null) {
|
||||
re |= PREVIEW;
|
||||
previewList = new NormalPreviewList();
|
||||
}
|
||||
re |= PREVIEW;
|
||||
((NormalPreviewList)previewList).addItem(m.group(3), m.group(4), "0", m.group(1),
|
||||
m.group(2), m.group(5));
|
||||
}
|
||||
@@ -231,7 +248,7 @@ public class DetailParser {
|
||||
// Get comment
|
||||
if ((mode & COMMENT) != 0) {
|
||||
p = Pattern
|
||||
.compile("<div class=\"c3\">Posted on ([^<>]+) by <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c7\"");
|
||||
.compile("<div class=\"c3\">Posted on ([^<>]+) by: <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
|
||||
m = p.matcher(body);
|
||||
comments = new LinkedList<Comment>();
|
||||
while (m.find()) {
|
||||
File renamed without changes.
+39
-14
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -50,7 +52,7 @@ public class EdDetailParser {
|
||||
isLastPage = true;
|
||||
|
||||
// Parser preview
|
||||
p = Pattern.compile("<div class=\"gi\"[^>]*><a href=\"http://lofi.e-hentai.org/s/(\\w+)/\\d+-(\\d+)\"[^>]*>");
|
||||
p = Pattern.compile("<div class=\"gi\"[^>]*><a href=\"https?://lofi.e-hentai.org/s/(\\w+)/\\d+-(\\d+)\"[^>]*>");
|
||||
m = p.matcher(body);
|
||||
boolean first = true;
|
||||
while(m.find()) {
|
||||
@@ -73,32 +75,55 @@ public class EdDetailParser {
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
previewPageNum = Integer.valueOf(m.group(1).replace(",", ""));
|
||||
else
|
||||
else {
|
||||
Log.e("TAG", "get needPreviewInfo failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
p = Pattern.compile("<td class=\"gdt1\">Images:</td><td class=\"gdt2\">([\\d,]+) ");
|
||||
p = Pattern.compile("<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d|,]+) pages</td></tr>");
|
||||
m = p.matcher(body);
|
||||
if (m.find())
|
||||
imageNum = Integer.valueOf(m.group(1).replace(",", ""));
|
||||
else
|
||||
else {
|
||||
Log.e("TAG", "get needPreviewInfo failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Parser preview
|
||||
p = Pattern.compile("<div class=\"gdtm\"[^>]*><div[^>]*><a href=\"http://exhentai.org/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
|
||||
boolean first = true;
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
if (body.contains("<div class=\"gdtl\"")) {
|
||||
p = Pattern.compile("<div class=\"gdtl\"[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
|
||||
} else {
|
||||
p = Pattern.compile("<div class=\"gdtm\"[^>]*><div[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
pageTokenArray = new LinkedList<String>();
|
||||
previewStartIndex = Integer.parseInt(m.group(2)) - 1;
|
||||
first = false;
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
pageTokenArray.add(m.group(1));
|
||||
}
|
||||
if (first)
|
||||
|
||||
|
||||
|
||||
if (first) {
|
||||
Log.e("TAG", "get gdtm");
|
||||
return false;
|
||||
else
|
||||
} else
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+282
-284
@@ -16,37 +16,41 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Handler;
|
||||
import android.os.Process;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.util.Pair;
|
||||
|
||||
import com.hippo.ehviewer.Analytics;
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.data.ApiGalleryInfo;
|
||||
import com.hippo.ehviewer.data.Comment;
|
||||
import com.hippo.ehviewer.data.GalleryDetail;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.data.GalleryPopular;
|
||||
import com.hippo.ehviewer.data.LofiGalleryDetail;
|
||||
import com.hippo.ehviewer.data.PreviewList;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Handler;
|
||||
import android.os.Process;
|
||||
|
||||
import com.hippo.ehviewer.Analytics;
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.data.Comment;
|
||||
import com.hippo.ehviewer.data.GalleryDetail;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.data.GalleryPopular;
|
||||
import com.hippo.ehviewer.data.ListUrls;
|
||||
import com.hippo.ehviewer.data.LofiGalleryDetail;
|
||||
import com.hippo.ehviewer.data.PreviewList;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class EhClient {
|
||||
@SuppressWarnings("unused")
|
||||
@@ -59,18 +63,18 @@ public class EhClient {
|
||||
public static final int MODE_LOFI = 0x2;
|
||||
|
||||
public static final String API_G = "http://g.e-hentai.org/api.php";
|
||||
public static final String API_EX = "http://exhentai.org/api.php";
|
||||
public static final String API_EX = "https://exhentai.org/api.php";
|
||||
public static final long APIUID = 1363542;
|
||||
public static final String APIKEY = "f4b5407ab1727b9d08d7";
|
||||
|
||||
private static final String LOGIN_URL = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
|
||||
private static final String FORUMS_URL = "http://forums.e-hentai.org/index.php";
|
||||
public static final String LOGIN_URL = "https://forums.e-hentai.org/index.php?act=Login&CODE=01";
|
||||
private static final String FORUMS_URL = "https://forums.e-hentai.org/index.php";
|
||||
|
||||
public static final String HEADER_G = "http://g.e-hentai.org/";
|
||||
public static final String HEADER_EX = "http://exhentai.org/";
|
||||
public static final String HEADER_EX = "https://exhentai.org/";
|
||||
public static final String HEADER_LOFI = "http://lofi.e-hentai.org/";
|
||||
|
||||
private static final String API_EHVIEWER = "http://www.ehviewer.com/API";
|
||||
public static final String API_EHVIEWER = "http://www.ehviewer.com/API";
|
||||
|
||||
/* Avatar get code */
|
||||
public static final int GET_AVATAR_OK = 0x0;
|
||||
@@ -119,7 +123,7 @@ public class EhClient {
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public String getDetailUrl(int gid, String token) {
|
||||
public static String getDetailUrl(int gid, String token) {
|
||||
return getDetailUrl(gid, token, 0, Config.getMode());
|
||||
}
|
||||
|
||||
@@ -129,7 +133,7 @@ public class EhClient {
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public String getDetailUrl(int gid, String token, int pageNum) {
|
||||
public static String getDetailUrl(int gid, String token, int pageNum) {
|
||||
return getDetailUrl(gid, token, pageNum, Config.getMode());
|
||||
}
|
||||
|
||||
@@ -153,11 +157,15 @@ public class EhClient {
|
||||
sb.append(HEADER_G);
|
||||
break;
|
||||
}
|
||||
return sb.append("g/").append(gid).append("/").append(token)
|
||||
.append("/?p=").append(pageNum).toString();
|
||||
sb.append("g/").append(gid).append('/').append(token).append('/');
|
||||
if (pageNum > 0) {
|
||||
sb.append("?p=").append(pageNum);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String getPageUrl(int gid, String token, int pageNum) {
|
||||
public static String getPageUrl(int gid, String token, int pageNum) {
|
||||
return getPageUrl(gid, token, pageNum, Config.getMode());
|
||||
}
|
||||
|
||||
@@ -179,7 +187,7 @@ public class EhClient {
|
||||
.append("-").append(pageNum).toString();
|
||||
}
|
||||
|
||||
public String getApiUrl() {
|
||||
public static String getApiUrl() {
|
||||
return getApiUrl(Config.getApiMode());
|
||||
}
|
||||
|
||||
@@ -193,11 +201,29 @@ public class EhClient {
|
||||
}
|
||||
}
|
||||
|
||||
public String getFavoriteUrl(int index, int page) {
|
||||
return getFavoriteUrl(Config.getApiMode(), index, page);
|
||||
public static String getFavoriteUrl(int page) {
|
||||
return getFavoriteUrl(Config.getApiMode(), page);
|
||||
}
|
||||
|
||||
public static String getFavoriteUrl(int mode, int index, int page) {
|
||||
public static String getFavoriteUrl(int mode, int page) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
switch (mode) {
|
||||
case MODE_EX:
|
||||
sb.append(HEADER_EX);
|
||||
break;
|
||||
case MODE_G:
|
||||
default:
|
||||
sb.append(HEADER_G);
|
||||
break;
|
||||
}
|
||||
return sb.append("favorites.php?page=").append(page).toString();
|
||||
}
|
||||
|
||||
public static String getFavoriteUrlWithCat(int index, int page) {
|
||||
return getFavoriteUrlWithCat(Config.getApiMode(), index, page);
|
||||
}
|
||||
|
||||
public static String getFavoriteUrlWithCat(int mode, int index, int page) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
switch (mode) {
|
||||
case MODE_EX:
|
||||
@@ -212,26 +238,6 @@ public class EhClient {
|
||||
.append(page).toString();
|
||||
}
|
||||
|
||||
public interface OnGetMangaUrlListener {
|
||||
public void onSuccess(Object checkFlag, String[] arg);
|
||||
public void onFailure(Object checkFlag, String eMsg);
|
||||
}
|
||||
|
||||
public interface OnGetImageListener {
|
||||
public void onSuccess(Object checkFlag, Object res);
|
||||
public void onFailure(int eMsgId);
|
||||
}
|
||||
|
||||
public interface OnGetGalleryMetadataListener {
|
||||
public void onSuccess(Map<String, GalleryInfo> lmds);
|
||||
public void onFailure(String eMsg);
|
||||
}
|
||||
|
||||
public interface OnGetGalleryTokensListener {
|
||||
public void onSuccess(Map<String, String> tokens);
|
||||
public void onFailure(String eMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* True if Login
|
||||
* @return
|
||||
@@ -264,7 +270,7 @@ public class EhClient {
|
||||
/**
|
||||
* Return avatar, if not return default avatar
|
||||
*/
|
||||
public Bitmap getAvatar() {
|
||||
public Drawable getAvatar() {
|
||||
return mInfo.getAvatar();
|
||||
}
|
||||
|
||||
@@ -370,12 +376,12 @@ public class EhClient {
|
||||
}
|
||||
String avatarUrl = m.group(1);
|
||||
if (!avatarUrl.startsWith("http"))
|
||||
avatarUrl = "http://forums.e-hentai.org/" + avatarUrl;
|
||||
avatarUrl = "https://forums.e-hentai.org/" + avatarUrl;
|
||||
// Get avatar
|
||||
Bitmap avatar = hp.getImage(avatarUrl);
|
||||
// Set avatar if not null
|
||||
if (avatar != null)
|
||||
mInfo.setAvatar(avatar);
|
||||
mInfo.setAvatar(new BitmapDrawable(EhClient.this.mContext.getResources(), avatar));
|
||||
// notification
|
||||
listener.onGetAvatar(GET_AVATAR_OK);
|
||||
}
|
||||
@@ -529,7 +535,7 @@ public class EhClient {
|
||||
public static String getFileSearchUrl(int apiMode) {
|
||||
switch (apiMode) {
|
||||
case MODE_EX:
|
||||
return "http://ul.exhentai.org/image_lookup.php";
|
||||
return "https://ul.exhentai.org/image_lookup.php";
|
||||
case MODE_G:
|
||||
default:
|
||||
return "http://ul.e-hentai.org/image_lookup.php";
|
||||
@@ -687,13 +693,13 @@ public class EhClient {
|
||||
| DetailParser.PREVIEW_INFO | DetailParser.PREVIEW
|
||||
| DetailParser.COMMENT);
|
||||
if (result == DetailParser.OFFENSIVE) {
|
||||
md.firstPage = "offensive";
|
||||
responder = new GetGDetaiResponder(listener, md);
|
||||
responder = new GetGDetaiResponder(listener, "offensive");
|
||||
} else if (result == DetailParser.PINING) {
|
||||
md.firstPage = "pining";
|
||||
responder = new GetGDetaiResponder(listener, md);
|
||||
responder = new GetGDetaiResponder(listener, "pining");
|
||||
} else if ((result & (DetailParser.DETAIL | DetailParser.PREVIEW_INFO |
|
||||
DetailParser.PREVIEW)) != 0) {
|
||||
DetailParser.PREVIEW)) == (DetailParser.DETAIL | DetailParser.PREVIEW_INFO |
|
||||
DetailParser.PREVIEW)) {
|
||||
// At least get detail and preview
|
||||
md.thumb = parser.thumb;
|
||||
md.title = parser.title;
|
||||
md.title_jpn = parser.title_jpn;
|
||||
@@ -711,11 +717,17 @@ public class EhClient {
|
||||
md.firstPage = parser.firstPage;
|
||||
md.previewPerPage = parser.previewPerPage;
|
||||
md.previewSum = parser.previewSum;
|
||||
md.isFavorite = parser.isFavorite;
|
||||
|
||||
md.tags = parser.tags;
|
||||
md.previewLists = new PreviewList[md.previewSum];
|
||||
md.previewLists[0] = parser.previewList;
|
||||
md.comments = parser.comments;
|
||||
|
||||
md.torrentUrl = parser.torrentUrl;
|
||||
//noinspection unchecked
|
||||
md.torrents = new Pair[Math.max(parser.torrentNumber, 0)];
|
||||
|
||||
responder = new GetGDetaiResponder(listener, md);
|
||||
} else if (result == DetailParser.ERROR) {
|
||||
responder = new GetGDetaiResponder(listener, parser.eMesg);
|
||||
@@ -731,6 +743,62 @@ public class EhClient {
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public interface OnGetTorrentListener {
|
||||
void onSuccess(@NonNull Pair<String, String>[] torrents);
|
||||
void onFailure(String eMsg);
|
||||
}
|
||||
|
||||
private class GetTorrentResponder implements Runnable {
|
||||
private final boolean isOk;
|
||||
private final OnGetTorrentListener listener;
|
||||
private final Pair<String, String>[] torrents;
|
||||
private final String eMesg;
|
||||
|
||||
public GetTorrentResponder(OnGetTorrentListener listener, Pair<String, String>[] torrents) {
|
||||
this.isOk = true;
|
||||
this.listener = listener;
|
||||
this.torrents = torrents;
|
||||
this.eMesg = null;
|
||||
}
|
||||
|
||||
public GetTorrentResponder(OnGetTorrentListener listener, String eMsg) {
|
||||
this.isOk = false;
|
||||
this.listener = listener;
|
||||
this.torrents = null;
|
||||
this.eMesg = eMsg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (isOk)
|
||||
listener.onSuccess(torrents);
|
||||
else
|
||||
listener.onFailure(eMesg);
|
||||
}
|
||||
}
|
||||
|
||||
public void getTorrent(final String url, final Pair<String, String>[] torrents,
|
||||
final OnGetTorrentListener listener) {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
String body = hh.get(url);
|
||||
GetTorrentResponder responder;
|
||||
if (body == null) {
|
||||
responder = new GetTorrentResponder(listener, hh.getEMsg());
|
||||
} else if (!body.contains("<")) {
|
||||
responder = new GetTorrentResponder(listener, body);
|
||||
} else {
|
||||
responder = new GetTorrentResponder(listener, TorrentParser.parse(body, torrents));
|
||||
}
|
||||
mHandler.post(responder);
|
||||
}
|
||||
});
|
||||
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
// Get lofi gallery Detail
|
||||
public interface OnGetLGDetailListener {
|
||||
public void onSuccess(LofiGalleryDetail md, boolean isLastPage);
|
||||
@@ -884,7 +952,7 @@ public class EhClient {
|
||||
|
||||
public void comment(final String detailUrl, final String comment,
|
||||
final OnCommentListener listener) {
|
||||
new Thread(new Runnable() {
|
||||
new BgThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
HttpHelper hp = new HttpHelper(mContext);
|
||||
@@ -1089,56 +1157,6 @@ public class EhClient {
|
||||
}).start();
|
||||
}
|
||||
|
||||
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 getType(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 getType(int type) {
|
||||
int i;
|
||||
for (i = 0; i < CATEGORY_VALUES.length - 1; i++) {
|
||||
if (CATEGORY_VALUES[i] == type)
|
||||
break;
|
||||
}
|
||||
return CATEGORY_STRINGS[i][0];
|
||||
}
|
||||
|
||||
|
||||
// modifyFavorite
|
||||
public interface OnModifyFavoriteListener {
|
||||
void onSuccess(List<GalleryInfo> gis, int pageNum);
|
||||
@@ -1172,7 +1190,7 @@ public class EhClient {
|
||||
*/
|
||||
public void modifyFavorite(final int[] gids, final int dstCat, final int srcCat,
|
||||
final OnModifyFavoriteListener listener) {
|
||||
new Thread(new Runnable() {
|
||||
new BgThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
int i;
|
||||
@@ -1212,7 +1230,7 @@ public class EhClient {
|
||||
args[i] = new String[]{"modifygids[]", String.valueOf(gids[i-1])};
|
||||
args[i] = new String[]{"apply", "Apply"};
|
||||
|
||||
hp.postForm(getFavoriteUrl(srcCat, 0), args);
|
||||
hp.postForm(getFavoriteUrlWithCat(srcCat, 0), args);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
@@ -1230,7 +1248,7 @@ public class EhClient {
|
||||
listener.onFailure(e.getMessage());
|
||||
return;
|
||||
}
|
||||
new Thread(new Runnable() {
|
||||
new BgThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
HttpHelper hp = new HttpHelper(mContext);
|
||||
@@ -1259,9 +1277,9 @@ public class EhClient {
|
||||
gi.gid = j.getInt("gid");
|
||||
gi.token = j.getString("token");
|
||||
gi.title = Utils.unescapeXml(j.getString("title"));
|
||||
gi.posted = AppContext.sFormatter.format(Long.parseLong(j.getString("posted")) * 1000);
|
||||
gi.posted = Utils.sDate.format(Long.parseLong(j.getString("posted")) * 1000);
|
||||
gi.thumb = j.getString("thumb");
|
||||
gi.category = getType(j.getString("category"));
|
||||
gi.category = EhUtils.getCategory(j.getString("category"));
|
||||
gi.uploader = j.getString("uploader");
|
||||
gi.rating = Float.parseFloat(j.getString("rating"));
|
||||
gi.generateSLang();
|
||||
@@ -1289,183 +1307,163 @@ public class EhClient {
|
||||
}).start();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
private static class GetGalleryMetadataPackage {
|
||||
public Map<String, ListMangaDetail> lmds;
|
||||
public OnGetGalleryMetadataListener listener;
|
||||
|
||||
public GetGalleryMetadataPackage(Map<String, ListMangaDetail> lmds,
|
||||
OnGetGalleryMetadataListener listener) {
|
||||
this.lmds = lmds;
|
||||
this.listener = listener;
|
||||
}
|
||||
public interface OnGetApiGalleryInfoListener {
|
||||
public void onSuccess(Object checkFlag, ApiGalleryInfo[] agiArray);
|
||||
public void onFailure(Object checkFlag, String eMsg);
|
||||
}
|
||||
|
||||
private static Handler getGalleryMetadataHandler = new Handler() {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
OnGetGalleryMetadataListener listener =
|
||||
((GetGalleryMetadataPackage) msg.obj).listener;
|
||||
Map<String, ListMangaDetail> lmds =
|
||||
((GetGalleryMetadataPackage) msg.obj).lmds;
|
||||
if (lmds == null || lmds.size() == 0)
|
||||
listener.onFailure(msg.what);
|
||||
else
|
||||
listener.onSuccess(lmds);
|
||||
};
|
||||
};
|
||||
private class GetApiGalleryInfoResponder implements Runnable {
|
||||
private final boolean isOk;
|
||||
private final OnGetApiGalleryInfoListener listener;
|
||||
private final Object checkFlag;
|
||||
private final ApiGalleryInfo[] agiArray;
|
||||
private final String eMesg;
|
||||
|
||||
private static class GetGalleryMetadataRunnable implements Runnable {
|
||||
private String[][] gidTokens;
|
||||
private OnGetGalleryMetadataListener listener;
|
||||
|
||||
public GetGalleryMetadataRunnable(String[][] gidTokens,
|
||||
OnGetGalleryMetadataListener listener) {
|
||||
this.gidTokens = gidTokens;
|
||||
public GetApiGalleryInfoResponder(OnGetApiGalleryInfoListener listener,
|
||||
Object checkFlag, ApiGalleryInfo[] agiArray) {
|
||||
this.isOk = true;
|
||||
this.listener = listener;
|
||||
this.checkFlag = checkFlag;
|
||||
this.agiArray = agiArray;
|
||||
this.eMesg = null;
|
||||
}
|
||||
|
||||
public GetApiGalleryInfoResponder(OnGetApiGalleryInfoListener listener,
|
||||
Object checkFlag, String eMsg) {
|
||||
this.isOk = false;
|
||||
this.listener = listener;
|
||||
this.checkFlag = checkFlag;
|
||||
this.agiArray = null;
|
||||
this.eMesg = eMsg;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int errorMessageId = R.string.em_unknown_error;
|
||||
Map<String, ListMangaDetail> lmds = new HashMap<String, ListMangaDetail>();
|
||||
if (isOk)
|
||||
listener.onSuccess(checkFlag, agiArray);
|
||||
else
|
||||
listener.onFailure(checkFlag, eMesg);
|
||||
}
|
||||
}
|
||||
|
||||
// Create post string
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
strBuf.append("{\"method\": \"gdata\",\"gidlist\": [");
|
||||
for (String[] item: gidTokens)
|
||||
strBuf.append("[" + item[0] + ",\"" + item[1] + "\"],");
|
||||
strBuf.delete(strBuf.length()-1, strBuf.length());
|
||||
strBuf.append("]}");
|
||||
StringBuffer sb = new StringBuffer();
|
||||
errorMessageId = postJson(API_URL, strBuf.toString(),sb);
|
||||
if (sb.length() != 0) {
|
||||
String pageContent = sb.toString();
|
||||
private ApiGalleryInfo Json2Agi(JSONObject js) throws JSONException {
|
||||
ApiGalleryInfo agi = new ApiGalleryInfo();
|
||||
agi.gid = js.getInt("gid");
|
||||
agi.token = js.getString("token");
|
||||
agi.archiver_key = js.getString("archiver_key");
|
||||
agi.title = js.getString("title");
|
||||
agi.title_jpn = js.getString("title_jpn");
|
||||
agi.category = EhUtils.getCategory(js.getString("category"));
|
||||
agi.thumb = js.getString("thumb");
|
||||
agi.uploader = js.getString("uploader");
|
||||
agi.posted = Utils.sDate.format(Long.parseLong(js.getString("posted")) * 1000);
|
||||
agi.filecount = js.getString("filecount");
|
||||
agi.filesize = js.getLong("filesize");
|
||||
agi.expunged = js.getBoolean("expunged");
|
||||
agi.rating = Float.parseFloat(js.getString("rating"));
|
||||
agi.torrentcount = js.getString("torrentcount");
|
||||
JSONArray tags = js.getJSONArray("tags");
|
||||
agi.apiTags = new String[tags.length()];
|
||||
for (int j = 0; j < tags.length(); j++)
|
||||
agi.apiTags[j] = tags.getString(j);
|
||||
return agi;
|
||||
}
|
||||
|
||||
public void getApiGalleryInfo(final Object checkFlag, final int[] gids, final String[] tokens, final OnGetApiGalleryInfoListener l) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
GetApiGalleryInfoResponder responder;
|
||||
ApiGalleryInfo[] agiArray;
|
||||
int requstLen;
|
||||
// Create json
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm");
|
||||
JSONObject jsonObject = new JSONObject(pageContent);
|
||||
JSONArray jsonArray = jsonObject.getJSONArray("gmetadata");
|
||||
for (int i = 0; i < jsonArray.length(); i++) {
|
||||
JSONObject jo = jsonArray.getJSONObject(i);
|
||||
if (jo.getString("error") != null)
|
||||
continue;
|
||||
ListMangaDetail lmd = new ListMangaDetail();
|
||||
lmd.gid = Long.toString(jo.getLong("gid"));
|
||||
lmd.token = jo.getString("token");
|
||||
lmd.archiver_key = jo.getString("archiver_key");
|
||||
lmd.title = jo.getString("title");
|
||||
lmd.title_jpn = jo.getString("title_jpn");
|
||||
lmd.category = getType(jo.getString("category"));
|
||||
lmd.thumb = jo.getString("thumb");
|
||||
lmd.uploader = jo.getString("uploader");
|
||||
lmd.posted = fm.format(Long.parseLong(jo.getString("posted")) * 1000);
|
||||
lmd.filecount = jo.getString("filecount");
|
||||
lmd.filesize = jo.getLong("filesize");
|
||||
lmd.expunged = jo.getBoolean("expunged");
|
||||
lmd.rating = jo.getString("rating");
|
||||
lmd.torrentcount = jo.getString("torrentcount");
|
||||
JSONArray ja = jo.getJSONArray("tags");
|
||||
int length = ja.length();
|
||||
lmd.tags = new String[1][length+1];
|
||||
lmd.tags[0][0] = "all";
|
||||
for (int j = 1; j < length+1; j++)
|
||||
lmd.tags[0][j] = ja.getString(j);
|
||||
|
||||
lmds.put(lmd.gid, lmd);
|
||||
json.put("method", "gdata");
|
||||
JSONArray jsonA = new JSONArray();
|
||||
requstLen = Math.min(gids.length, tokens.length);
|
||||
agiArray = new ApiGalleryInfo[requstLen];
|
||||
for (int i = 0; i < requstLen; i++) {
|
||||
JSONArray ja = new JSONArray();
|
||||
ja.put(gids[i]);
|
||||
ja.put(tokens[i]);
|
||||
jsonA.put(ja);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorMessageId = R.string.em_parser_error;
|
||||
json.put("gidlist", jsonA);
|
||||
} catch (Throwable e) {
|
||||
responder = new GetApiGalleryInfoResponder(l, null, "Create json error");
|
||||
mHandler.post(responder);
|
||||
return;
|
||||
}
|
||||
// Post
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
String body = hh.postJson(getApiUrl(), json);
|
||||
if (body != null) {
|
||||
try {
|
||||
json = new JSONObject(body);
|
||||
JSONArray jsonA = (JSONArray) json.get("gmetadata");
|
||||
for (int i = 0; i < jsonA.length(); i++) {
|
||||
ApiGalleryInfo agi = Json2Agi(jsonA.getJSONObject(i));
|
||||
// Add to agiArray
|
||||
for (int j = 0; j < requstLen; j++) {
|
||||
if (agi.gid == gids[j])
|
||||
agiArray[j] = agi;
|
||||
}
|
||||
}
|
||||
responder = new GetApiGalleryInfoResponder(l, checkFlag, agiArray);
|
||||
} catch (Throwable e) {
|
||||
responder = new GetApiGalleryInfoResponder(l, checkFlag, "Json error");
|
||||
}
|
||||
} else {
|
||||
responder = new GetApiGalleryInfoResponder(l, checkFlag, hh.getEMsg());
|
||||
}
|
||||
mHandler.post(responder);
|
||||
}
|
||||
Message msg = new Message();
|
||||
msg.what = errorMessageId;
|
||||
msg.obj = new GetGalleryMetadataPackage(lmds, listener);
|
||||
getGalleryMetadataHandler.sendMessage(msg);
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public static void getGalleryMetadata(String[][] gidTokens,
|
||||
OnGetGalleryMetadataListener listener) {
|
||||
new Thread(new GetGalleryMetadataRunnable(gidTokens,
|
||||
listener)).start();
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static class GetGalleryTokensPackage {
|
||||
public Map<String, String> tokens;
|
||||
public OnGetGalleryTokensListener listener;
|
||||
|
||||
public GetGalleryTokensPackage(Map<String, String> tokens,
|
||||
OnGetGalleryTokensListener listener) {
|
||||
this.tokens = tokens;
|
||||
this.listener = listener;
|
||||
public ApiGalleryInfo[] getApiGalleryInfo(int[] gids, String[] tokens) {
|
||||
ApiGalleryInfo[] agiArray;
|
||||
int requstLen;
|
||||
// Create json
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("method", "gdata");
|
||||
JSONArray jsonA = new JSONArray();
|
||||
requstLen = Math.min(gids.length, tokens.length);
|
||||
agiArray = new ApiGalleryInfo[requstLen];
|
||||
for (int i = 0; i < requstLen; i++) {
|
||||
JSONArray ja = new JSONArray();
|
||||
ja.put(gids[i]);
|
||||
ja.put(tokens[i]);
|
||||
jsonA.put(ja);
|
||||
}
|
||||
json.put("gidlist", jsonA);
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Handler getGalleryTokensHandler = new Handler() {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
OnGetGalleryTokensListener listener =
|
||||
((GetGalleryTokensPackage) msg.obj).listener;
|
||||
Map<String, String> tokens =
|
||||
((GetGalleryTokensPackage) msg.obj).tokens;
|
||||
if (tokens == null || tokens.size() == 0)
|
||||
listener.onFailure(msg.what);
|
||||
else
|
||||
listener.onSuccess(tokens);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
private static class GetGalleryTokensRunnable implements Runnable {
|
||||
private String gid;
|
||||
private String token;
|
||||
private String[] pages;
|
||||
private OnGetGalleryMetadataListener listener;
|
||||
|
||||
public GetGalleryTokensRunnable(String gid, String token, String[] pages,
|
||||
OnGetGalleryMetadataListener listener) {
|
||||
this.gid = gid;
|
||||
this.token = token;
|
||||
this.pages = pages;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int errorMessageId = R.string.em_unknown_error;
|
||||
Map<String, String> tokens = new HashMap<String, String>();
|
||||
|
||||
// Create post string
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
strBuf.append("{\"method\": \"gtoken\",\"pagelist\": [");
|
||||
for (String item: pages)
|
||||
strBuf.append("[" + gid + ",\"" + token + "\"," + item + "],");
|
||||
strBuf.delete(strBuf.length()-1, strBuf.length());
|
||||
strBuf.append("]}");
|
||||
|
||||
Log.i(TAG, strBuf.toString());
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
errorMessageId = postJson(API_URL, strBuf.toString(),sb);
|
||||
if (sb.length() != 0) {
|
||||
String pageContent = sb.toString();
|
||||
Log.d(TAG, pageContent);
|
||||
// Post api
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
String body = hh.postJson(getApiUrl(), json);
|
||||
if (body == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
json = new JSONObject(body);
|
||||
JSONArray jsonA = (JSONArray) json.get("gmetadata");
|
||||
for (int i = 0; i < jsonA.length(); i++) {
|
||||
ApiGalleryInfo agi = Json2Agi(jsonA.getJSONObject(i));
|
||||
// Add to agiArray
|
||||
for (int j = 0; j < requstLen; j++) {
|
||||
if (agi.gid == gids[j])
|
||||
agiArray[j] = agi;
|
||||
}
|
||||
}
|
||||
return agiArray;
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
private static void getGalleryTokens(String gid, String token, String[] pages,
|
||||
OnGetGalleryMetadataListener listener) {
|
||||
new Thread(new GetGalleryTokensRunnable(gid, token, pages,
|
||||
listener)).start();
|
||||
}*/
|
||||
|
||||
}
|
||||
+118
-48
@@ -16,6 +16,19 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.vector.VectorDrawable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -23,17 +36,9 @@ import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Hippo
|
||||
@@ -46,12 +51,12 @@ public class EhInfo {
|
||||
private static final String DIR_NAME = "file";
|
||||
private static final String AVATAR_NAME = "avatar.png";
|
||||
private static final Bitmap.CompressFormat AVATAR_FORMAT = Bitmap.CompressFormat.PNG;
|
||||
private static Bitmap DEFAULT_AVATAR;
|
||||
private static Drawable DEFAULT_AVATAR;
|
||||
|
||||
public static final String EX_HOST = "exhentai.org";
|
||||
public static final String[] COOKIABLE_HOSTS = {"exhentai.org",
|
||||
"g.e-hentai.org", "forums.e-hentai.org", "ul.exhentai.org",
|
||||
"ul.e-hentai.org", "lofi.e-hentai.org"};
|
||||
public static final String[] COOKIABLE_SITE_ARRAY = {
|
||||
"exhentai.org",
|
||||
"e-hentai.org"};
|
||||
|
||||
private static final String KEY_LOGIN = "login";
|
||||
private static final boolean DEFAULT_LOGIN = false;
|
||||
@@ -59,9 +64,9 @@ public class EhInfo {
|
||||
private static final String KEY_DISPLAYNAME = "displayname";
|
||||
private static final String DEFAULT_NAME = "Hippo";
|
||||
private static final String KEY_MEMBER_ID = "ipb_member_id";
|
||||
private static final String DEFAULT_MEMBER_ID = "1936857";
|
||||
private static final String DEFAULT_MEMBER_ID = null;
|
||||
private static final String KEY_PASS_HASH = "ipb_pass_hash";
|
||||
private static final String DEFAULT_PASS_HASH = "725e2726990bc34ae3852bb4f7c7879a";
|
||||
private static final String DEFAULT_PASS_HASH = null;
|
||||
|
||||
private final Context mContext;
|
||||
private final SharedPreferences mInfoPref;
|
||||
@@ -69,14 +74,20 @@ public class EhInfo {
|
||||
private boolean mIsLogin;
|
||||
private String mUsername;
|
||||
private String mDisplayname;
|
||||
private Bitmap mAvatar;
|
||||
private BitmapDrawable mAvatar;
|
||||
private int mDefaultCat;
|
||||
private String mPreviewMode;
|
||||
private int mExculdeTagGroup;
|
||||
private String mExculdeLanguage;
|
||||
|
||||
private boolean mHAHProxy;
|
||||
private String mHAHIp;
|
||||
private String mHAHPort;
|
||||
private String mHAHPasskey;
|
||||
|
||||
private static EhInfo sInstance;
|
||||
|
||||
private Bitmap getAvatarFromFile() {
|
||||
private BitmapDrawable getAvatarFromFile() {
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
File avatarFile = new File(dir, AVATAR_NAME);
|
||||
if (!avatarFile.exists())
|
||||
@@ -85,7 +96,7 @@ public class EhInfo {
|
||||
InputStream is = null;
|
||||
try {
|
||||
is = new FileInputStream(avatarFile);
|
||||
return BitmapFactory.decodeStream(is);
|
||||
return (BitmapDrawable) BitmapDrawable.createFromStream(is, null);
|
||||
} catch (FileNotFoundException e) {
|
||||
return null;
|
||||
} finally {
|
||||
@@ -97,8 +108,7 @@ public class EhInfo {
|
||||
mContext = context;
|
||||
mInfoPref = mContext.getSharedPreferences(PREF_NAME, 0);
|
||||
if (DEFAULT_AVATAR == null)
|
||||
DEFAULT_AVATAR = BitmapFactory.decodeStream(
|
||||
context.getResources().openRawResource(R.drawable.default_avatar));
|
||||
DEFAULT_AVATAR = VectorDrawable.create(context, R.drawable.default_avatar);
|
||||
|
||||
mIsLogin = mInfoPref.getBoolean(KEY_LOGIN, DEFAULT_LOGIN);
|
||||
mUsername = mInfoPref.getString(KEY_USERNAME, DEFAULT_NAME);
|
||||
@@ -109,28 +119,65 @@ public class EhInfo {
|
||||
mPreviewMode = Config.getPreviewMode();
|
||||
mExculdeTagGroup = Config.getExculdeTagGroup();
|
||||
mExculdeLanguage = Config.getExculdeLanguage();
|
||||
mHAHProxy = Config.getHAHProxy();
|
||||
mHAHIp = Config.getHAHIp();
|
||||
mHAHPort = Config.getHAHPort();
|
||||
mHAHPasskey = Config.getHAHPasskey();
|
||||
updateUconfig();
|
||||
};
|
||||
}
|
||||
|
||||
private String getUconfigString(String previewMode) {
|
||||
return new StringBuilder().append("cats_").append(mDefaultCat)
|
||||
.append("-ts_").append(previewMode == null ? mPreviewMode : previewMode)
|
||||
.append("-xns_").append(mExculdeTagGroup)
|
||||
.append("-xl_").append(mExculdeLanguage)
|
||||
.append("-tl_m-uh_y-tr_2-prn_n-dm_l-ar_0-rc_0-rx_0-ry_0-sa_y-oi_n-qb_n-tf_n-hp_-hk_-ms_n-mt_n")
|
||||
.toString();
|
||||
String proxy;
|
||||
if (!mHAHProxy || TextUtils.isEmpty(mHAHIp) || TextUtils.isEmpty(mHAHPort)) {
|
||||
proxy = "";
|
||||
} else {
|
||||
proxy = mHAHIp + "%3A" + mHAHPort;
|
||||
}
|
||||
|
||||
return "cats_" + mDefaultCat
|
||||
+ "-ts_" + (previewMode == null ? mPreviewMode : previewMode)
|
||||
+ "-xns_" + mExculdeTagGroup
|
||||
+ "-xl_" + mExculdeLanguage
|
||||
+ "-hp_" + proxy
|
||||
+ "-hk_" + mHAHPasskey
|
||||
+ "-prn_" + (TextUtils.isEmpty(proxy) ? "n" : "y")
|
||||
+ "-tl_m-uh_y-tr_2-dm_l-ar_0-rc_0-rx_0-ry_0-sa_y-oi_n-qb_n-tf_n-ms_n-mt_n";
|
||||
}
|
||||
|
||||
private void updateUconfig() {
|
||||
mUconfig = getUconfigString(null);
|
||||
}
|
||||
|
||||
public final static EhInfo getInstance(final Context context) {
|
||||
public static EhInfo getInstance(final Context context) {
|
||||
if (sInstance == null)
|
||||
sInstance = new EhInfo(context.getApplicationContext());
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
public static boolean isEhSite(URL url) {
|
||||
String host = url.getHost();
|
||||
int length = host.length();
|
||||
int dotCount = 0;
|
||||
int i = length;
|
||||
while(i-- != 0) {
|
||||
char ch = host.charAt(i);
|
||||
if (ch == '.') {
|
||||
dotCount++;
|
||||
}
|
||||
if (dotCount == 2) {
|
||||
// Get it
|
||||
break;
|
||||
}
|
||||
}
|
||||
String site = host.substring(MathUtils.clamp(i+1, 0, length));
|
||||
|
||||
for (String h : EhInfo.COOKIABLE_SITE_ARRAY) {
|
||||
if (h.equals(site))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String getCookie(String cookieStr, String key) {
|
||||
String value = null;
|
||||
int index1 = -1;
|
||||
@@ -147,22 +194,24 @@ public class EhInfo {
|
||||
}
|
||||
|
||||
public void storeCookie(HttpURLConnection conn) {
|
||||
String ipb_member_id;
|
||||
String ipb_pass_hash;
|
||||
|
||||
List<String> cookieList = conn.getHeaderFields().get("Set-Cookie");
|
||||
if (cookieList == null)
|
||||
return;
|
||||
SharedPreferences.Editor editor = mInfoPref.edit();
|
||||
for (String str : cookieList) {
|
||||
ipb_member_id = getCookie(str, KEY_MEMBER_ID);
|
||||
ipb_pass_hash = getCookie(str, KEY_PASS_HASH);
|
||||
|
||||
if (ipb_member_id != null)
|
||||
editor.putString(KEY_MEMBER_ID, ipb_member_id);
|
||||
if (ipb_pass_hash != null)
|
||||
editor.putString(KEY_PASS_HASH, ipb_pass_hash);
|
||||
for (String str : cookieList) {
|
||||
setCookie(str);
|
||||
}
|
||||
}
|
||||
|
||||
public void setCookie(String cookie) {
|
||||
SharedPreferences.Editor editor = mInfoPref.edit();
|
||||
String ipb_member_id = getCookie(cookie, KEY_MEMBER_ID);
|
||||
String ipb_pass_hash = getCookie(cookie, KEY_PASS_HASH);
|
||||
|
||||
if (ipb_member_id != null)
|
||||
editor.putString(KEY_MEMBER_ID, ipb_member_id);
|
||||
if (ipb_pass_hash != null)
|
||||
editor.putString(KEY_PASS_HASH, ipb_pass_hash);
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
@@ -171,11 +220,20 @@ public class EhInfo {
|
||||
}
|
||||
|
||||
public void setCookie(HttpURLConnection conn, String previewMode) {
|
||||
String cookie = "ipb_member_id=" + mInfoPref.getString(KEY_MEMBER_ID, DEFAULT_MEMBER_ID) +
|
||||
"; ipb_pass_hash=" + mInfoPref.getString(KEY_PASS_HASH, DEFAULT_PASS_HASH) +
|
||||
"; uconfig=" + (previewMode == null ? mUconfig : getUconfigString(previewMode)) +
|
||||
"; xres=" + Config.getLofiResolution();
|
||||
conn.setRequestProperty("Cookie", cookie);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String id = mInfoPref.getString(KEY_MEMBER_ID, DEFAULT_MEMBER_ID);
|
||||
String hash = mInfoPref.getString(KEY_PASS_HASH, DEFAULT_PASS_HASH);
|
||||
sb.append("uconfig=").append(previewMode == null ? mUconfig : getUconfigString(previewMode))
|
||||
.append("; xres=").append(Config.getLofiResolution());
|
||||
if (id != null)
|
||||
sb.append("; ipb_member_id=").append(id);
|
||||
if (hash != null)
|
||||
sb.append("; ipb_pass_hash=").append(hash);
|
||||
// Fake
|
||||
sb.append("; igneous=");
|
||||
sb.append("; lv=");
|
||||
|
||||
conn.setRequestProperty("Cookie", sb.toString());
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
@@ -196,7 +254,7 @@ public class EhInfo {
|
||||
mIsLogin = false;
|
||||
// Remove avatar
|
||||
if (mAvatar != null) {
|
||||
mAvatar.recycle();
|
||||
mAvatar.getBitmap().recycle();
|
||||
mAvatar = null;
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
File avatarFile = new File(dir, AVATAR_NAME);
|
||||
@@ -216,11 +274,11 @@ public class EhInfo {
|
||||
return mDisplayname;
|
||||
}
|
||||
|
||||
public Bitmap getAvatar() {
|
||||
public Drawable getAvatar() {
|
||||
return isLogin() && mAvatar != null ? mAvatar : DEFAULT_AVATAR;
|
||||
}
|
||||
|
||||
public void setAvatar(Bitmap avatar) {
|
||||
public void setAvatar(BitmapDrawable avatar) {
|
||||
mAvatar = avatar;
|
||||
|
||||
File dir = mContext.getDir(DIR_NAME, 0);
|
||||
@@ -228,7 +286,7 @@ public class EhInfo {
|
||||
OutputStream os = null;
|
||||
try {
|
||||
os = new FileOutputStream(avatarFile);
|
||||
avatar.compress(AVATAR_FORMAT, 100, os);
|
||||
avatar.getBitmap().compress(AVATAR_FORMAT, 100, os);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
@@ -255,4 +313,16 @@ public class EhInfo {
|
||||
mExculdeLanguage = exculdeLanguage;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setHAHProxy(boolean hahProxy) {
|
||||
mHAHProxy = hahProxy;
|
||||
updateUconfig();
|
||||
}
|
||||
|
||||
public void setHAHProxy(String ip, String port, String passkey) {
|
||||
mHAHIp = ip;
|
||||
mHAHPort = port;
|
||||
mHAHPasskey = passkey;
|
||||
updateUconfig();
|
||||
}
|
||||
}
|
||||
+193
-56
@@ -16,36 +16,45 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.AutoExpandArray;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.AutoExpandArray;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class ExDownloader implements Runnable {
|
||||
// TODO what a mess
|
||||
public final class ExDownloader implements Runnable {
|
||||
|
||||
private static final String TAG = ExDownloader.class.getSimpleName();
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
private static final int WORKER_NUM = 3;
|
||||
|
||||
private static final String[] URL_509_SUFFIX_ARRAY = {
|
||||
"/509.gif",
|
||||
"/509s.gif"
|
||||
};
|
||||
|
||||
private final Context mContext;
|
||||
private final ExDownloaderManager mManager;
|
||||
@@ -75,8 +84,9 @@ public class ExDownloader implements Runnable {
|
||||
|
||||
private volatile int mCurRequestPageIndex = -1;
|
||||
|
||||
private final Worker[] mWorkerArray = new Worker[WORKER_NUM];
|
||||
private final HttpHelper.DownloadControlor[] mControlorArray = new HttpHelper.DownloadControlor[WORKER_NUM];
|
||||
private final int mWorkerNum;
|
||||
private final Worker[] mWorkerArray;
|
||||
private final HttpHelper.DownloadControlor[] mControlorArray;
|
||||
|
||||
private final Object mPageTokenLock = new Object();
|
||||
private final Object mWorkerLock = new Object();
|
||||
@@ -94,7 +104,9 @@ public class ExDownloader implements Runnable {
|
||||
private volatile long mLastUpdateSpeedTime = 0;
|
||||
private volatile long mAccumulateSize;
|
||||
private volatile HashSet<Integer> mDownloadIndexSet;
|
||||
private volatile Object mDownloadLock = new Object();
|
||||
private final Object mDownloadLock = new Object();
|
||||
|
||||
private int mCurReadIndex = 0;
|
||||
|
||||
/**
|
||||
* Do no work in UI thread
|
||||
@@ -113,27 +125,27 @@ public class ExDownloader implements Runnable {
|
||||
*/
|
||||
public interface ListenerForDownload {
|
||||
public void onStart(int gid);
|
||||
public void onGetSum(int gid, int sum);
|
||||
public void onDownload(int gid, int downloadSize, int totalSize);
|
||||
public void onUpdateSpeed(int gid, int speed);
|
||||
public void onDownloadOver(int gid, int legacy);
|
||||
}
|
||||
|
||||
ExDownloader(int gid, String token, String title, int mode) {
|
||||
mContext = AppContext.getInstance();
|
||||
ExDownloader(Context context, int gid, String token, String title, int mode) {
|
||||
mContext = context;
|
||||
mManager = ExDownloaderManager.getInstance();
|
||||
mGid = gid;
|
||||
mToken = token;
|
||||
mTitle = title;
|
||||
mMode = mode;
|
||||
|
||||
mWorkerNum = Config.getDownloadThread();
|
||||
mWorkerArray = new Worker[mWorkerNum];
|
||||
mControlorArray = new HttpHelper.DownloadControlor[mWorkerNum];
|
||||
|
||||
// Make sure dir
|
||||
mDir = EhUtils.getGalleryDir(mGid, mTitle);
|
||||
Utils.ensureDir(mDir, true);
|
||||
// Create mark file
|
||||
File makeFile = new File(mDir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
try {
|
||||
new FileOutputStream(makeFile).close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
|
||||
public void setListenerForImageSet(ListenerForImageSet l) {
|
||||
@@ -201,13 +213,17 @@ public class ExDownloader implements Runnable {
|
||||
return mToken;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return mTitle;
|
||||
}
|
||||
|
||||
public void setDownloadMode(boolean downloadMode) {
|
||||
synchronized (mDownloadLock) {
|
||||
if (downloadMode) {
|
||||
setStartIndex(0);
|
||||
if (mDownloadIndexSet == null)
|
||||
mDownloadIndexSet = new HashSet<Integer>();
|
||||
if (mLfd != null)
|
||||
if (mDownloadMode && mLfd != null)
|
||||
mLfd.onStart(mGid);
|
||||
} else {
|
||||
mDownloadIndexSet = null;
|
||||
@@ -218,7 +234,7 @@ public class ExDownloader implements Runnable {
|
||||
|
||||
public void setStartIndex(int startIndex) {
|
||||
if (mDownloadMode) {
|
||||
setTargetIndex(startIndex);
|
||||
addTargetIndex(startIndex);
|
||||
} else {
|
||||
if (mImageNum != -1 && startIndex >= mImageNum)
|
||||
mStartIndex = 0;
|
||||
@@ -230,7 +246,7 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
public void setTargetIndex(int index) {
|
||||
public void addTargetIndex(int index) {
|
||||
if (mImageNum != -1 && index >= mImageNum)
|
||||
return;
|
||||
|
||||
@@ -239,11 +255,20 @@ public class ExDownloader implements Runnable {
|
||||
ensureWorkers();
|
||||
}
|
||||
|
||||
public void setCurReadIndex(final int index) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
writeCurReadIndex(index);
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public int getMaxEnsureIndex() {
|
||||
if (mImageNum != -1) {
|
||||
return mImageNum - 1;
|
||||
} else {
|
||||
return Math.max(Math.max(Math.max(mStartIndex - 1,
|
||||
return Math.max(Math.max(Math.max(mStartIndex,
|
||||
Math.max(mCurMaxPreviewPage, mPreviewPageNum - 1) * mPreviewPerPage),
|
||||
mPageTokeArray.maxValidIndex()), 0);
|
||||
}
|
||||
@@ -277,13 +302,13 @@ public class ExDownloader implements Runnable {
|
||||
if (mMainThread != null)
|
||||
return;
|
||||
|
||||
mMainThread = new Thread(this);
|
||||
mMainThread = new BgThread(this);
|
||||
mMainThread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
|
||||
mMainThread.start();
|
||||
}
|
||||
|
||||
private File getExDownloadInfoFile() {
|
||||
return new File(mManager.getExDownloadInfoDir(), String.valueOf(mGid));
|
||||
return new File(mDir, EhUtils.EH_DOWNLOAD_FILENAME);
|
||||
}
|
||||
|
||||
private boolean checkMode(int samlpe, int target) {
|
||||
@@ -295,6 +320,7 @@ public class ExDownloader implements Runnable {
|
||||
* This function parser the download info file.<br>
|
||||
* The file look like this:<br>
|
||||
* <code>
|
||||
* 00000000<br>
|
||||
* 728874<br>
|
||||
* 306429c222<br>
|
||||
* 1<br>
|
||||
@@ -312,7 +338,7 @@ public class ExDownloader implements Runnable {
|
||||
* @param ediFile
|
||||
* @return
|
||||
*/
|
||||
private boolean parserEdiFile(File ediFile) {
|
||||
private synchronized boolean parserEdiFile(File ediFile) {
|
||||
if (!ediFile.exists() || !ediFile.isFile() || !ediFile.canRead()
|
||||
|| !ediFile.canWrite())
|
||||
return false;
|
||||
@@ -321,6 +347,8 @@ public class ExDownloader implements Runnable {
|
||||
try {
|
||||
is = new BufferedInputStream(new FileInputStream(ediFile),
|
||||
IO_BUFFER_SIZE);
|
||||
// skip read index
|
||||
Utils.readAsciiLine(is);
|
||||
if (mGid != Integer.valueOf(Utils.readAsciiLine(is)) ||
|
||||
!mToken.equals(Utils.readAsciiLine(is)))
|
||||
return false;
|
||||
@@ -372,9 +400,11 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
private void writeEdiFile(File ediFile) {
|
||||
private synchronized void writeEdiFile(File ediFile) {
|
||||
try {
|
||||
FileWriter writer = new FileWriter(ediFile);
|
||||
writer.write(String.format("%08x", mCurReadIndex));
|
||||
writer.write("\n");
|
||||
writer.write(String.valueOf(mGid));
|
||||
writer.write("\n");
|
||||
writer.write(mToken);
|
||||
@@ -398,8 +428,27 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
|
||||
private synchronized void writeCurReadIndex(int index) {
|
||||
mCurReadIndex = index;
|
||||
try {
|
||||
RandomAccessFile raf = new RandomAccessFile(getExDownloadInfoFile(), "rw");
|
||||
raf.write(String.format("%08x", mCurReadIndex).getBytes());
|
||||
raf.close();
|
||||
} catch (Throwable e) {}
|
||||
}
|
||||
|
||||
public static int readCurReadIndex(int gid, String title) {
|
||||
try {
|
||||
RandomAccessFile raf = new RandomAccessFile(new File(EhUtils.getGalleryDir(gid, title),
|
||||
EhUtils.EH_DOWNLOAD_FILENAME), "r");
|
||||
int index = Integer.parseInt(raf.readLine(), 16);
|
||||
raf.close();
|
||||
return index;
|
||||
} catch (Throwable e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,11 +459,12 @@ public class ExDownloader implements Runnable {
|
||||
hh.setPreviewMode("m");
|
||||
String body = hh.get(url);
|
||||
if (body == null)
|
||||
throw new Exception(hh.getEMsg() != null ? hh.getEMsg() : "Http error");
|
||||
throw new Exception(hh.getEMsg() != null ? hh.getEMsg() : "Http error, body == null");
|
||||
if (!edp.parser(body, mMode, needPreviewInfo))
|
||||
throw new Exception(edp.emsg != null ? edp.emsg : "Parser error");
|
||||
throw new Exception(edp.emsg != null ? edp.emsg : "Parser error, body is \n" + body);
|
||||
if (edp.previewStartIndex != pageIndex * mPreviewPerPage)
|
||||
throw new Exception("预测与实际不匹配");
|
||||
throw new Exception("预测与实际不匹配, 预测: " + edp.previewStartIndex +
|
||||
", 实际: " + pageIndex * mPreviewPerPage + ", body is \n" + body);
|
||||
|
||||
List<String> pageTokenArray = edp.pageTokenArray;
|
||||
if (needPreviewInfo)
|
||||
@@ -424,7 +474,7 @@ public class ExDownloader implements Runnable {
|
||||
if (edp.isLastPage) {
|
||||
mPreviewPageNum = pageIndex + 1;
|
||||
mImageNum = pageIndex * mPreviewPerPage + pageTokenArray.size();
|
||||
} else if (!edp.isLastPage && mPreviewPageNum == -1) {
|
||||
} else if (mPreviewPageNum == -1) {
|
||||
mCurMaxPreviewPage = Math.max(mCurMaxPreviewPage, pageIndex + 1);
|
||||
}
|
||||
} else {
|
||||
@@ -467,6 +517,18 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
private static final int BE_NOTIFY_ID = -3;
|
||||
|
||||
private static final void show509Notification(Context context) {
|
||||
NotificationManager notifyManager = (NotificationManager) context
|
||||
.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
|
||||
mBuilder.setSmallIcon(R.drawable.ic_stat_eh).setContentTitle(context.getString(R.string.notification_be_title))
|
||||
.setContentText(context.getString(R.string.notification_be_mesg))
|
||||
.setOngoing(false).setAutoCancel(true);
|
||||
notifyManager.notify(BE_NOTIFY_ID, mBuilder.build());
|
||||
}
|
||||
|
||||
// TODO for download , when to claim download completed
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -474,10 +536,13 @@ public class ExDownloader implements Runnable {
|
||||
try {
|
||||
File ediFile = getExDownloadInfoFile();
|
||||
if (!parserEdiFile(ediFile) || mPreviewPerPage == -1 ||
|
||||
(mMode == EhClient.MODE_EX && mImageNum == -1)) {
|
||||
((mMode == EhClient.MODE_EX || mMode == EhClient.MODE_G) && mImageNum == -1)) {
|
||||
getDetailInfo(0, ediFile, true);
|
||||
}
|
||||
|
||||
if (mLfd != null)
|
||||
mLfd.onGetSum(mGid, mImageNum);
|
||||
|
||||
ensureWorkers();
|
||||
|
||||
// A loop to get page token
|
||||
@@ -522,7 +587,7 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
// TODO get error
|
||||
Log.f(e);
|
||||
|
||||
synchronized (mDownloadLock) {
|
||||
if (mDownloadMode && mLfd != null && mDownloadIndexSet != null) {
|
||||
@@ -540,7 +605,7 @@ public class ExDownloader implements Runnable {
|
||||
Log.d(TAG, "ExDownloader over");
|
||||
}
|
||||
|
||||
private class Worker extends Thread {
|
||||
private class Worker extends BgThread {
|
||||
|
||||
private final int mIndex;
|
||||
|
||||
@@ -595,11 +660,15 @@ public class ExDownloader implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO what if download failed ? what to do ?
|
||||
@Override
|
||||
public void run() {
|
||||
HttpDownloadListener listener = new HttpDownloadListener();
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
ImagePageParser ipp = new ImagePageParser();
|
||||
HttpHelper.DownloadOption option = new HttpHelper.DownloadOption();
|
||||
|
||||
option.setAllowFixingExtension(true);
|
||||
|
||||
while (true) {
|
||||
// Check stop
|
||||
@@ -668,31 +737,94 @@ public class ExDownloader implements Runnable {
|
||||
hh.reset();
|
||||
ipp.reset();
|
||||
String body = hh.get(EhClient.getPageUrl(mGid, pageToken, targetIndex + 1, mMode)
|
||||
+ (i == 1 ? "?nl=48" : ""));
|
||||
+ ((i == 1) ? "?nl=48" : ""));
|
||||
if (ipp.parser(body, mMode)) {
|
||||
// Download image
|
||||
HttpHelper.DownloadControlor c = mControlorArray[mIndex];
|
||||
String imageUrl = ipp.imageUrl;
|
||||
String filename = EhUtils.getImageFilename(targetIndex, Utils.getExtension(imageUrl, "jpg"));
|
||||
// Just put filename to mImageFilenameArray
|
||||
mImageFilenameArray.set(targetIndex, filename);
|
||||
hh.reset();
|
||||
if (hh.download(imageUrl, mDir, filename, false, c, listener) == null) {
|
||||
|
||||
if (Config.getDownloadOriginImage() && ipp.originalImageUrl != null) {
|
||||
|
||||
Log.d(TAG, "Download origin image");
|
||||
|
||||
// Download orgin image
|
||||
String imageUrl = ipp.originalImageUrl;
|
||||
// Guess filename
|
||||
String filename = EhUtils.getImageFilename(targetIndex, "jpg");
|
||||
// Download
|
||||
hh.reset();
|
||||
if (hh.download(imageUrl, mDir, filename, true, c, listener) == null) {
|
||||
if (i == 1) {
|
||||
// TODO download error
|
||||
Log.d(TAG, "download error");
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadOriginEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (hh.getException() instanceof HttpHelper.BandwidthExceededException) {
|
||||
// Get 509
|
||||
show509Notification(mContext);
|
||||
break;
|
||||
} else {
|
||||
String newImageUrl = hh.getLastUrl();
|
||||
if (newImageUrl != null) {
|
||||
// Try download from proxy
|
||||
hh.reset();
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(newImageUrl, mDir, filename, option, c, listener) == null) {
|
||||
// Download failed
|
||||
Log.d(TAG, "Download failed");
|
||||
} else {
|
||||
// Download successful
|
||||
Log.d(TAG, "Download successful");
|
||||
}
|
||||
} else {
|
||||
// Download failed
|
||||
Log.d(TAG, "Download failed");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Download successful
|
||||
Log.d(TAG, "Download successful");
|
||||
}
|
||||
|
||||
// No need to refresh image url
|
||||
break;
|
||||
} else {
|
||||
// Download scale image
|
||||
String imageUrl = ipp.imageUrl;
|
||||
|
||||
//Check 509 gif
|
||||
boolean get509 = false;
|
||||
for (String suffix : URL_509_SUFFIX_ARRAY) {
|
||||
if (imageUrl.endsWith(suffix)) {
|
||||
// Get 509 gif here
|
||||
get509 = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (get509) {
|
||||
show509Notification(mContext);
|
||||
break;
|
||||
}
|
||||
|
||||
// Guess filename
|
||||
String filename = EhUtils.getImageFilename(targetIndex, Utils.getExtension(imageUrl, "jpg"));
|
||||
// Don't put into mImageFilenameArray, because extension maybe be wrong
|
||||
// mImageFilenameArray.set(targetIndex, filename);
|
||||
hh.reset();
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
hh.reset();
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (i == 1) {
|
||||
// TODO download error
|
||||
Log.d(TAG, "download error");
|
||||
}
|
||||
} else {
|
||||
// download ok
|
||||
Log.d(TAG, "download ok proxy");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// download ok
|
||||
Log.d(TAG, "download ok proxy");
|
||||
Log.d(TAG, "download ok");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// download ok
|
||||
Log.d(TAG, "download ok");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// TODO parser error, Do somthing
|
||||
@@ -790,5 +922,10 @@ public class ExDownloader implements Runnable {
|
||||
lastPercent = 0.0f;
|
||||
lastDownloadSize = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-22
@@ -16,52 +16,35 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.hippo.ehviewer.AppContext;
|
||||
|
||||
public class ExDownloaderManager {
|
||||
|
||||
private static final String TAG = ExDownloaderManager.class.getSimpleName();
|
||||
|
||||
private final Context mContext;
|
||||
private final SparseArray<ExDownloader> mExDownloadList;
|
||||
private final File mExDownloadInfoDir;
|
||||
|
||||
private static ExDownloaderManager sInstance;
|
||||
|
||||
public static void createInstance() {
|
||||
sInstance = new ExDownloaderManager();
|
||||
public static void createInstance(Context context) {
|
||||
sInstance = new ExDownloaderManager(context.getApplicationContext());
|
||||
}
|
||||
|
||||
public static ExDownloaderManager getInstance() {
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
private ExDownloaderManager() {
|
||||
mContext = AppContext.getInstance();
|
||||
private ExDownloaderManager(Context context) {
|
||||
mContext = context;
|
||||
mExDownloadList = new SparseArray<ExDownloader>();
|
||||
// Init download info dir
|
||||
String cachePath = mContext.getExternalCacheDir() != null
|
||||
? mContext.getExternalCacheDir().getPath()
|
||||
: mContext.getCacheDir().getPath();
|
||||
mExDownloadInfoDir = new File(cachePath, TAG);
|
||||
if (!mExDownloadInfoDir.exists()) {
|
||||
mExDownloadInfoDir.mkdirs();
|
||||
}
|
||||
}
|
||||
|
||||
File getExDownloadInfoDir() {
|
||||
return mExDownloadInfoDir;
|
||||
}
|
||||
|
||||
public synchronized ExDownloader getExDownloader(int gid, String token, String title, int mode) {
|
||||
ExDownloader exDownloader = mExDownloadList.get(gid);
|
||||
if (exDownloader == null) {
|
||||
exDownloader = new ExDownloader(gid, token, title, mode);
|
||||
exDownloader = new ExDownloader(mContext, gid, token, title, mode);
|
||||
mExDownloadList.append(gid, exDownloader);
|
||||
}
|
||||
exDownloader.occupy();
|
||||
+15
-6
@@ -16,19 +16,21 @@
|
||||
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class ImagePageParser {
|
||||
|
||||
public String imageUrl;
|
||||
public String originalImageUrl;
|
||||
public int gid;
|
||||
public String token;
|
||||
|
||||
public void reset() {
|
||||
imageUrl = null;
|
||||
originalImageUrl = null;
|
||||
gid = 0;
|
||||
token = null;
|
||||
}
|
||||
@@ -59,15 +61,22 @@ public class ImagePageParser {
|
||||
}
|
||||
|
||||
} else {
|
||||
p = Pattern.compile("<div id=\"i3\">.+?<img id=\"img\" src=\"(.+?)\""
|
||||
+ ".+?"
|
||||
+ "<div id=\"i5\"><div class=\"sb\"><a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)");
|
||||
p = Pattern.compile(
|
||||
"<(?:/iframe|div id=\"i3\")[^>]*><a[^>]*><img[^>]*src=\"(.+?)\"" +
|
||||
".+?" +
|
||||
"<div class=\"sb\"><a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)");
|
||||
m = p.matcher(body);
|
||||
|
||||
if (m.find()) {
|
||||
imageUrl = Utils.unescapeXml(m.group(1));
|
||||
gid = Integer.parseInt(m.group(2));
|
||||
token = m.group(3);
|
||||
|
||||
p = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
originalImageUrl = Utils.unescapeXml(
|
||||
new StringBuilder(m.group(1)).append("fullimg.php").append(m.group(2)).toString());
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
+73
-12
@@ -22,6 +22,7 @@ import java.util.regex.Pattern;
|
||||
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.data.LofiGalleryInfo;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class ListParser {
|
||||
@@ -84,7 +85,7 @@ public class ListParser {
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
lgi.category = EhClient.getType(m.group(5));
|
||||
lgi.category = EhUtils.getCategory(m.group(5));
|
||||
String tags = m.group(6);
|
||||
if (tags.equals("-"))
|
||||
lgi.lofiTags = null;
|
||||
@@ -117,8 +118,65 @@ public class ListParser {
|
||||
return ALL;
|
||||
}
|
||||
|
||||
case EhClient.MODE_G:
|
||||
case EhClient.MODE_EX:
|
||||
p = Pattern.compile("<a[^<>]+>([\\d]+)</a></td><td[^<>]+>(?:<a[^<>]+>)?&");
|
||||
m = p.matcher(body);
|
||||
if (m.find()) {
|
||||
pageNum = Integer.parseInt(m.group(1));
|
||||
} else if (body.contains("No hits found</p>")) {
|
||||
pageNum = 0;
|
||||
return NOT_FOUND;
|
||||
} else {
|
||||
return PARSER_ERROR;
|
||||
}
|
||||
|
||||
p = Pattern.compile("<td class=\"itdc\">(?:<a.+?>)?<img.+?alt=\"(.+?)\".+?/>(?:</a>)?</td>" // category
|
||||
+ "<td.+?>(.+?)</td>" // posted
|
||||
+ "<td.+?><div.+?><div.+?height:(\\d+)px; width:(\\d+)px\">"
|
||||
+ "(?:<img.+?src=\"(.+?)\".+?alt=\"(.+?)\" style.+?/>"
|
||||
+ "|inits~([^<>\"~]+~[^<>\"~]+)~([^<>]+))" // thumb and title
|
||||
+ "</div>"
|
||||
+ ".+?"
|
||||
+ "<div class=\"it5\"><a href=\"([^<>\"]+)\"[^<>]+>(.+?)</a></div>" // url and title
|
||||
+ ".+?"
|
||||
+ "<div class=\"ir it4r\" style=\"([^<>\"]+)\">" // rating
|
||||
+ ".+?"
|
||||
+ "<td class=\"itu\"><div><a.+?>(.+?)</a>"); // uploader
|
||||
m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
|
||||
gi.category = EhUtils.getCategory(m.group(1));
|
||||
gi.posted = m.group(2);
|
||||
gi.thumbHeight = Integer.parseInt(m.group(3));
|
||||
gi.thumbWidth = Integer.parseInt(m.group(4));
|
||||
|
||||
if (m.group(5) == null) {
|
||||
gi.thumb = Utils.unescapeXml("http://"
|
||||
+ m.group(7).replace('~', '/'));
|
||||
gi.title = Utils.unescapeXml(m.group(8));
|
||||
} else {
|
||||
gi.thumb = Utils.unescapeXml(m.group(5));
|
||||
gi.title = Utils.unescapeXml(m.group(6));
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern
|
||||
.compile("/(\\d+)/(\\w+)");
|
||||
Matcher matcher = pattern.matcher(m.group(9));
|
||||
if (matcher.find()) {
|
||||
gi.gid = Integer.parseInt(matcher.group(1));
|
||||
gi.token = matcher.group(2);
|
||||
} else
|
||||
continue;
|
||||
|
||||
gi.rating = Float.parseFloat(getRate(m.group(11)));
|
||||
gi.uploader = m.group(12);
|
||||
gi.generateSLang();
|
||||
|
||||
giList.add(gi);
|
||||
}
|
||||
return ALL;
|
||||
case EhClient.MODE_G:
|
||||
default:
|
||||
p = Pattern.compile("<a[^<>]+>([\\d]+)</a></td><td[^<>]+>(?:<a[^<>]+>)?&");
|
||||
m = p.matcher(body);
|
||||
@@ -133,7 +191,7 @@ public class ListParser {
|
||||
|
||||
p = Pattern.compile("<td class=\"itdc\">(?:<a.+?>)?<img.+?alt=\"(.+?)\".+?/>(?:</a>)?</td>" // category
|
||||
+ "<td.+?>(.+?)</td>" // posted
|
||||
+ "<td.+?><div.+?><div.+?>"
|
||||
+ "<td.+?><div.+?><div.+?height:(\\d+)px; width:(\\d+)px\">"
|
||||
+ "(?:<img.+?src=\"(.+?)\".+?alt=\"(.+?)\" style.+?/>"
|
||||
+ "|init~([^<>\"~]+~[^<>\"~]+)~([^<>]+))" // thumb and title
|
||||
+ "</div>"
|
||||
@@ -147,28 +205,31 @@ public class ListParser {
|
||||
while (m.find()) {
|
||||
GalleryInfo gi = new GalleryInfo();
|
||||
|
||||
gi.category = EhClient.getType(m.group(1));
|
||||
gi.category = EhUtils.getCategory(m.group(1));
|
||||
gi.posted = m.group(2);
|
||||
if (m.group(3) == null) {
|
||||
gi.thumbHeight = Integer.parseInt(m.group(3));
|
||||
gi.thumbWidth = Integer.parseInt(m.group(4));
|
||||
|
||||
if (m.group(5) == null) {
|
||||
gi.thumb = Utils.unescapeXml("http://"
|
||||
+ m.group(5).replace('~', '/'));
|
||||
gi.title = Utils.unescapeXml(m.group(6));
|
||||
+ m.group(7).replace('~', '/'));
|
||||
gi.title = Utils.unescapeXml(m.group(8));
|
||||
} else {
|
||||
gi.thumb = Utils.unescapeXml(m.group(3));
|
||||
gi.title = Utils.unescapeXml(m.group(4));
|
||||
gi.thumb = Utils.unescapeXml(m.group(5));
|
||||
gi.title = Utils.unescapeXml(m.group(6));
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern
|
||||
.compile("/(\\d+)/(\\w+)");
|
||||
Matcher matcher = pattern.matcher(m.group(7));
|
||||
Matcher matcher = pattern.matcher(m.group(9));
|
||||
if (matcher.find()) {
|
||||
gi.gid = Integer.parseInt(matcher.group(1));
|
||||
gi.token = matcher.group(2);
|
||||
} else
|
||||
continue;
|
||||
|
||||
gi.rating = Float.parseFloat(getRate(m.group(9)));
|
||||
gi.uploader = m.group(10);
|
||||
gi.rating = Float.parseFloat(getRate(m.group(11)));
|
||||
gi.uploader = m.group(12);
|
||||
gi.generateSLang();
|
||||
|
||||
giList.add(gi);
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,77 @@
|
||||
package com.hippo.ehviewer.ehclient;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Pair;
|
||||
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class TorrentParser {
|
||||
|
||||
/**
|
||||
*
|
||||
* @return the param or new instance if size changed
|
||||
*/
|
||||
public static Pair<String, String>[] parse(String body, @Nullable Pair<String, String>[] torrents) {
|
||||
List<Pair<String, String>> torrentList;
|
||||
int arrayLength;
|
||||
int size = 0;
|
||||
|
||||
if (torrents == null) {
|
||||
arrayLength = 0;
|
||||
torrentList = new LinkedList<>();
|
||||
} else {
|
||||
arrayLength = torrents.length;
|
||||
torrentList = null;
|
||||
}
|
||||
|
||||
Pattern p = Pattern.compile("<td colspan=\"5\"> <a href=\"([^\"]+)\">([^<>]*)</a></td>");
|
||||
Matcher m = p.matcher(body);
|
||||
while (m.find()) {
|
||||
size++;
|
||||
|
||||
if (size > arrayLength && torrentList == null) {
|
||||
torrentList = new LinkedList<>();
|
||||
// Copy data
|
||||
int copySize = size - 1;
|
||||
for (int i = 0; i < copySize; i++) {
|
||||
torrentList.add(torrents[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove ?p= to make torrent redistributable
|
||||
String url = m.group(1);
|
||||
if (url == null) {
|
||||
size--;
|
||||
continue;
|
||||
}
|
||||
int index = url.indexOf("?p=");
|
||||
if (index != -1) {
|
||||
url = url.substring(0, index);
|
||||
}
|
||||
|
||||
Pair<String, String> newItem = new Pair<>(url, Utils.unescapeXml(m.group(2)));
|
||||
if (torrentList != null) {
|
||||
torrentList.add(newItem);
|
||||
} else {
|
||||
torrents[size - 1] = newItem;
|
||||
}
|
||||
}
|
||||
|
||||
if (torrentList != null) {
|
||||
//noinspection unchecked,SuspiciousToArrayCall
|
||||
return (Pair<String, String>[]) torrentList.toArray(new Pair[torrentList.size()]);
|
||||
} else if (size == arrayLength){
|
||||
return torrents;
|
||||
} else {
|
||||
//noinspection unchecked
|
||||
Pair<String, String>[] result = new Pair[size];
|
||||
System.arraycopy(torrents, 0, result, 0, size);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+805
-418
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-35
@@ -16,29 +16,28 @@
|
||||
|
||||
package com.hippo.ehviewer.gallery.data;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Movie;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloader;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
|
||||
import com.hippo.ehviewer.gallery.image.Image;
|
||||
import com.hippo.ehviewer.util.AutoExpandArray;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = ImageSet.class.getSimpleName();
|
||||
|
||||
/**
|
||||
@@ -54,8 +53,8 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
private final File mDir;
|
||||
private final AutoExpandArray<String> mImageFilenameArray;
|
||||
private ImageListener mListener;
|
||||
private final Queue<DecodeInfo> mDecodeQueue = new ConcurrentLinkedQueue<DecodeInfo>();
|
||||
private final SparseArray<Float> mPercentMap = new SparseArray<Float>(5);
|
||||
private final Queue<DecodeInfo> mDecodeQueue = new ConcurrentLinkedQueue<>();
|
||||
private final Map<Integer, Float> mPercentMap = new ConcurrentHashMap<>(5);
|
||||
private final DecodeWorker mDecodeWorker;
|
||||
/** If true, then wake Worker, worker will stop **/
|
||||
private volatile boolean mStopWork = false;
|
||||
@@ -97,8 +96,8 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
// Init ExDownloader
|
||||
mEdManager = ExDownloaderManager.getInstance();
|
||||
mExDownloader = mEdManager.getExDownloader(gid, token, title, Config.getMode());
|
||||
mExDownloader.setStartIndex(startIndex);
|
||||
mExDownloader.setListenerForImageSet(this);
|
||||
mExDownloader.setStartIndex(startIndex);
|
||||
|
||||
mImageFilenameArray = mExDownloader.getImageFilenameArray();
|
||||
|
||||
@@ -123,22 +122,36 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
mListener = l;
|
||||
}
|
||||
|
||||
public void setTargetIndex(int index) {
|
||||
mExDownloader.setTargetIndex(index);
|
||||
public void addTargetIndex(int index) {
|
||||
mExDownloader.addTargetIndex(index);
|
||||
}
|
||||
|
||||
public void setStartIndex(int startIndex) {
|
||||
mExDownloader.setStartIndex(startIndex);
|
||||
}
|
||||
|
||||
public Object getImage(int index) {
|
||||
// Try to get file name
|
||||
public void setCurReadIndex(int index) {
|
||||
mExDownloader.setCurReadIndex(index);
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return mExDownloader.getTitle();
|
||||
}
|
||||
|
||||
public File getImageFile(int index) {
|
||||
File file = null;
|
||||
String name = getImageFilename(index);
|
||||
if (name != null)
|
||||
file = new File(mDir, name);
|
||||
return file;
|
||||
}
|
||||
|
||||
private String getImageFilename(int index) {
|
||||
String filename = mImageFilenameArray.get(index);
|
||||
if (filename == null) {
|
||||
// Just guess filename
|
||||
for (String possibleFilename : EhUtils.getPossibleImageFilenames(index)) {
|
||||
File file = new File(mDir, possibleFilename);
|
||||
if (file.exists()) {
|
||||
if (new File(mDir, possibleFilename).exists()) {
|
||||
// Get filename
|
||||
filename = possibleFilename;
|
||||
mImageFilenameArray.set(index, filename);
|
||||
@@ -146,8 +159,23 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
}
|
||||
}
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
public void redownload(int index) {
|
||||
String filename = getImageFilename(index);
|
||||
if (filename != null) {
|
||||
// Delete file
|
||||
new File(mDir, filename).delete();
|
||||
}
|
||||
mExDownloader.addTargetIndex(index);
|
||||
mListener.onGetImage(index);
|
||||
}
|
||||
|
||||
public Object getImage(int index) {
|
||||
String filename = getImageFilename(index);
|
||||
Float percent;
|
||||
|
||||
if ((percent = mPercentMap.get(index)) != null) {
|
||||
return percent;
|
||||
} else if (mExDownloader.isDownloading(index)) {
|
||||
@@ -178,7 +206,7 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
mEdManager.freeExDownloader(mExDownloader);
|
||||
}
|
||||
|
||||
private class DecodeWorker extends Thread {
|
||||
private class DecodeWorker extends BgThread {
|
||||
@Override
|
||||
public void run() {
|
||||
DecodeInfo decodeInfo;
|
||||
@@ -200,21 +228,17 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
|
||||
// do decode
|
||||
final int index = decodeInfo.index;
|
||||
String filename = decodeInfo.filename;
|
||||
boolean isGif = Utils.getExtension(filename, "jpg").equals("gif");
|
||||
FileInputStream fis;
|
||||
String pathName = Utils.getPathName(mDir.getPath(), decodeInfo.filename);
|
||||
Object res = null;
|
||||
try {
|
||||
fis = new FileInputStream(new File(mDir, filename));
|
||||
if (isGif) {
|
||||
res = Movie.decodeStream(fis);
|
||||
} else {
|
||||
BitmapFactory.Options opt = new BitmapFactory.Options();
|
||||
// TODO why only ARGB_8888 always work well, other may slit image
|
||||
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
|
||||
res = BitmapFactory.decodeStream(fis, null, opt);
|
||||
}
|
||||
} catch (FileNotFoundException e) {}
|
||||
|
||||
if (Utils.SUPPORT_IMAGE && Config.getCustomCodec()) {
|
||||
res = Image.decodeFile(pathName, Config.getDecodeFormat());
|
||||
} else {
|
||||
if (Utils.getExtension(pathName, "jpg").equals("gif"))
|
||||
res = Movie.decodeFile(pathName);
|
||||
else
|
||||
res = BitmapFactory.decodeFile(pathName);
|
||||
}
|
||||
|
||||
final Object _res = res;
|
||||
// Post to UI thread
|
||||
@@ -243,8 +267,7 @@ public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
|
||||
@Override
|
||||
public void onDownloading(final int index, final float percent) {
|
||||
mPercentMap.append(index, percent);
|
||||
|
||||
mPercentMap.put(index, percent);
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
+3
-2
@@ -19,8 +19,8 @@ package com.hippo.ehviewer.gallery.glrenderer;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
import android.graphics.RectF;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
|
||||
// BasicTexture is a Texture corresponds to a real GL texture.
|
||||
@@ -28,7 +28,6 @@ import com.hippo.ehviewer.util.MathUtils;
|
||||
// If a BasicTexture is loaded into GL memory, it has a GL texture id.
|
||||
public abstract class BasicTexture implements Texture {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = "BasicTexture";
|
||||
protected static final int UNSPECIFIED = -1;
|
||||
|
||||
@@ -53,6 +52,7 @@ public abstract class BasicTexture implements Texture {
|
||||
protected GLCanvas mCanvasRef = null;
|
||||
private static WeakHashMap<BasicTexture, Object> sAllTextures
|
||||
= new WeakHashMap<BasicTexture, Object>();
|
||||
@SuppressWarnings("rawtypes")
|
||||
private static ThreadLocal sInFinalizer = new ThreadLocal();
|
||||
|
||||
protected BasicTexture(GLCanvas canvas, int id, int state) {
|
||||
@@ -185,6 +185,7 @@ public abstract class BasicTexture implements Texture {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void finalize() {
|
||||
sInFinalizer.set(BasicTexture.class);
|
||||
recycle();
|
||||
+1
-2
@@ -16,9 +16,8 @@
|
||||
|
||||
package com.hippo.ehviewer.gallery.glrenderer;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
// BitmapTexture is a texture whose content is specified by a fixed Bitmap.
|
||||
//
|
||||
+1
-1
@@ -34,8 +34,8 @@ abstract class CanvasTexture extends UploadedTexture {
|
||||
setOpaque(false);
|
||||
}
|
||||
|
||||
@SuppressLint("WrongCall")
|
||||
@Override
|
||||
@SuppressLint("WrongCall")
|
||||
protected Bitmap onGetBitmap() {
|
||||
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, mConfig);
|
||||
mCanvas = new Canvas(bitmap);
|
||||
File renamed without changes.
+1
-1
@@ -20,7 +20,7 @@ package com.hippo.ehviewer.gallery.glrenderer;
|
||||
// Before drawing, setSize() should be called.
|
||||
public class ExtTexture extends BasicTexture {
|
||||
|
||||
private int mTarget;
|
||||
private final int mTarget;
|
||||
|
||||
public ExtTexture(GLCanvas canvas, int target) {
|
||||
GLId glId = canvas.getGLId();
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
-14
@@ -20,8 +20,6 @@ import android.graphics.Bitmap;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
|
||||
import javax.microedition.khronos.opengles.GL11;
|
||||
|
||||
//
|
||||
// GLCanvas gives a convenient interface to draw using OpenGL.
|
||||
//
|
||||
@@ -179,18 +177,6 @@ public interface GLCanvas {
|
||||
public abstract void texSubImage2D(BasicTexture texture, int xOffset, int yOffset,
|
||||
Bitmap bitmap,
|
||||
int format, int type);
|
||||
|
||||
/**
|
||||
* Calls glTexSubImage2D to upload a bitmap to the texture.
|
||||
*
|
||||
* @param texture The target texture to write to.
|
||||
* @param xOffset Specifies a texel offset in the x direction within the
|
||||
* texture array.
|
||||
* @param yOffset Specifies a texel offset in the y direction within the
|
||||
* texture array.
|
||||
*/
|
||||
public abstract void texSubImage2D(BasicTexture texture, int xOffset, int yOffset,
|
||||
Bitmap bitmap);
|
||||
|
||||
/**
|
||||
* Generates buffers and uploads the buffer data.
|
||||
+3
-11
@@ -28,19 +28,19 @@ import javax.microedition.khronos.opengles.GL11Ext;
|
||||
import javax.microedition.khronos.opengles.GL11ExtensionPack;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.opengl.GLU;
|
||||
import android.opengl.GLUtils;
|
||||
import android.opengl.Matrix;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.util.IntArray;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
public class GLES11Canvas implements GLCanvas {
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = "GLCanvasImp";
|
||||
|
||||
private static final float OPAQUE_ALPHA = 0.95f;
|
||||
@@ -557,7 +557,6 @@ public class GLES11Canvas implements GLCanvas {
|
||||
mGLState.setBlendEnabled(mBlendEnabled && (!from.isOpaque()
|
||||
|| !Utils.isOpaque(toColor) || alpha < OPAQUE_ALPHA));
|
||||
|
||||
final GL11 gl = mGL;
|
||||
if (!bindTexture(from)) return;
|
||||
|
||||
// Interpolate the RGB and alpha values between both textures.
|
||||
@@ -591,7 +590,6 @@ public class GLES11Canvas implements GLCanvas {
|
||||
private int mTextureTarget = GL11.GL_TEXTURE_2D;
|
||||
private boolean mBlendEnabled = true;
|
||||
private float mLineWidth = 1.0f;
|
||||
private final boolean mLineSmooth = false;
|
||||
|
||||
public GLState(GL11 gl) {
|
||||
mGL = gl;
|
||||
@@ -817,6 +815,7 @@ public class GLES11Canvas implements GLCanvas {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("DefaultLocale")
|
||||
public void dumpStatisticsAndClear() {
|
||||
String line = String.format(
|
||||
"MESH:%d, TEX_OES:%d, TEX_RECT:%d, FILL_RECT:%d, LINE:%d",
|
||||
@@ -959,13 +958,6 @@ public class GLES11Canvas implements GLCanvas {
|
||||
GLUtils.texSubImage2D(target, 0, xOffset, yOffset, bitmap, format, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void texSubImage2D(BasicTexture texture, int xOffset, int yOffset, Bitmap bitmap) {
|
||||
int target = texture.getTarget();
|
||||
mGL.glBindTexture(target, texture.getId());
|
||||
GLUtils.texSubImage2D(target, 0, xOffset, yOffset, bitmap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int uploadBuffer(FloatBuffer buf) {
|
||||
return uploadBuffer(buf, Float.SIZE / Byte.SIZE);
|
||||
File renamed without changes.
+3
-9
@@ -22,15 +22,16 @@ import java.nio.FloatBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.opengl.GLES20;
|
||||
import android.opengl.GLUtils;
|
||||
import android.opengl.Matrix;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hippo.ehviewer.util.IntArray;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
|
||||
public class GLES20Canvas implements GLCanvas {
|
||||
// ************** Constants **********************
|
||||
@@ -818,6 +819,7 @@ public class GLES20Canvas implements GLCanvas {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressLint("DefaultLocale")
|
||||
public void dumpStatisticsAndClear() {
|
||||
String line = String.format("MESH:%d, TEX_RECT:%d, FILL_RECT:%d, LINE:%d", mCountDrawMesh,
|
||||
mCountTextureRect, mCountFillRect, mCountDrawLine);
|
||||
@@ -938,14 +940,6 @@ public class GLES20Canvas implements GLCanvas {
|
||||
GLUtils.texSubImage2D(target, 0, xOffset, yOffset, bitmap, format, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void texSubImage2D(BasicTexture texture, int xOffset, int yOffset, Bitmap bitmap) {
|
||||
int target = texture.getTarget();
|
||||
GLES20.glBindTexture(target, texture.getId());
|
||||
checkError();
|
||||
GLUtils.texSubImage2D(target, 0, xOffset, yOffset, bitmap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int uploadBuffer(FloatBuffer buf) {
|
||||
return uploadBuffer(buf, FLOAT_SIZE);
|
||||
Loaded 100 of 1149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user