mirror of
https://github.com/seven332/EhViewer
synced 2026-11-30 02:58: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 |
No files matched your search
+4
-2
@@ -1,6 +1,8 @@
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/src
|
||||
*.iml
|
||||
.idea
|
||||
/captures
|
||||
Generated
-1
@@ -1 +0,0 @@
|
||||
EhViewer
|
||||
Generated
-23
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<option name="DEFAULT_COMPILER" value="Javac" />
|
||||
<resourceExtensions />
|
||||
<wildcardResourcePatterns>
|
||||
<entry name="!?*.java" />
|
||||
<entry name="!?*.form" />
|
||||
<entry name="!?*.class" />
|
||||
<entry name="!?*.groovy" />
|
||||
<entry name="!?*.scala" />
|
||||
<entry name="!?*.flex" />
|
||||
<entry name="!?*.kt" />
|
||||
<entry name="!?*.clj" />
|
||||
</wildcardResourcePatterns>
|
||||
<annotationProcessing>
|
||||
<profile default="true" name="Default" enabled="false">
|
||||
<processorPath useClasspath="true" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
||||
|
||||
Generated
-3
@@ -1,3 +0,0 @@
|
||||
<component name="CopyrightManager">
|
||||
<settings default="" />
|
||||
</component>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" defaultCharsetForPropertiesFiles="UTF-8">
|
||||
<file url="PROJECT" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-18
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleJvm" value="1.7" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0" is_locked="false">
|
||||
<option name="myName" value="Project Default" />
|
||||
<option name="myLocal" value="false" />
|
||||
<inspection_tool class="LoggerInitializedWithForeignClass" enabled="false" level="WARNING" enabled_by_default="false">
|
||||
<option name="loggerClassName" value="org.apache.log4j.Logger,org.slf4j.LoggerFactory,org.apache.commons.logging.LogFactory,java.util.logging.Logger" />
|
||||
<option name="loggerFactoryMethodName" value="getLogger,getLogger,getLog,getLogger" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
|
||||
<option name="processCode" value="true" />
|
||||
<option name="processLiterals" value="true" />
|
||||
<option name="processComments" value="true" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="PROJECT_PROFILE" value="Project Default" />
|
||||
<option name="USE_PROJECT_PROFILE" value="true" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
Generated
-33
@@ -1,33 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EntryPointsManager">
|
||||
<entry_points version="2.0" />
|
||||
</component>
|
||||
<component name="NullableNotNullManager">
|
||||
<option name="myDefaultNullable" value="org.jetbrains.annotations.Nullable" />
|
||||
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
|
||||
<option name="myNullables">
|
||||
<value>
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
|
||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
|
||||
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
|
||||
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
<option name="myNotNulls">
|
||||
<value>
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
|
||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
|
||||
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
|
||||
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-10
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/EhViewer.iml" filepath="$PROJECT_DIR$/EhViewer.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
||||
Generated
-5
@@ -1,5 +0,0 @@
|
||||
<component name="DependencyValidationManager">
|
||||
<state>
|
||||
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
|
||||
</state>
|
||||
</component>
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<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" />
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# EhViewer
|
||||
|
||||
这是一个 Android 平台上的 E-Hentai 阅读应用。访问 [EhViewer](http://www.ehviewer.com/) 网站以获取更多信息。<br>
|
||||
EhViewer is an E-Hentai Application for Android. Visit [EhViewer](http://www.ehviewer.com/)(Chinese Only) website for more information.
|
||||
|
||||
# Build
|
||||
|
||||
导入 Android Studio 即可。<br>
|
||||
Just import into Android Studio.
|
||||
|
||||
# Thanks
|
||||
|
||||
- [android-gif-drawable](https://github.com/koral--/android-gif-drawable)
|
||||
- 参考 gif 解码
|
||||
- [ActionBar-PullToRefresh](https://github.com/chrisbanes/ActionBar-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [ActionBarSherlocke](https://github.com/JakeWharton/ActionBarSherlock)
|
||||
- 曾用来对 4.0 一些系统兼容
|
||||
- [Android-PullToRefresh](https://github.com/chrisbanes/Android-PullToRefresh)
|
||||
- 曾作为刷新控件
|
||||
- [AndroidStaggeredGrid](https://github.com/etsy/AndroidStaggeredGrid)
|
||||
- 列表控件
|
||||
- [Apollo-CM](https://github.com/adneal/Apollo-CM)
|
||||
- 缓存机制
|
||||
- [DiskLruCache](https://github.com/JakeWharton/DiskLruCache)
|
||||
- 缓存机制
|
||||
- [FloatingActionButton](https://github.com/FaizMalkani/FloatingActionButton)
|
||||
- 按钮控件
|
||||
- [GIFLIB](http://giflib.sourceforge.net)
|
||||
- gif 解码
|
||||
- [Gloria Hallelujah](https://www.google.com/fonts/specimen/Gloria+Hallelujah)
|
||||
- 启动界面字体
|
||||
- [ImageLoadingPattern](https://github.com/rnrneverdies/ImageLoadingPattern)
|
||||
- 图片过渡效果
|
||||
- [libjpeg-turbo](http://www.libjpeg-turbo.org)
|
||||
- jpge 解码
|
||||
- [libpng](http://www.libpng.org/pub/png/libpng.html)
|
||||
- png 解码
|
||||
- [material-menu](https://github.com/balysv/material-menu)
|
||||
- 抽屉指示器
|
||||
- [OpenCC](https://github.com/BYVoid/OpenCC)
|
||||
- 繁化工作
|
||||
- [Slabo](https://github.com/TiroTypeworks/Slabo)
|
||||
- 图标字体
|
||||
- [SlidingMenu](https://github.com/jfeinstein10/SlidingMenu)
|
||||
- 曾作为抽屉控件
|
||||
- [source-code-pro](https://github.com/adobe/source-code-pro)
|
||||
- 刷新控件字体
|
||||
- [svg-android](https://code.google.com/p/svg-android/)
|
||||
- svg 解析
|
||||
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
|
||||
- 状态栏背景设置
|
||||
- [twoway-view](https://github.com/lucasr/twoway-view)
|
||||
- RecyclerView 使用方法
|
||||
- [zlib](http://www.zlib.net)
|
||||
- 辅助 png 解码
|
||||
- [Android Open Source Project](http://source.android.com)
|
||||
- 很多很多
|
||||
- [commons-lang](http://commons.apache.org/proper/commons-lang)
|
||||
- 很多很多
|
||||
|
||||
# License
|
||||
|
||||
本项目内容采用 [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) 授权,
|
||||
部分文件采用 [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) 授权([列表](rc/list1)),
|
||||
部分文件采用 [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) 授权([列表](rc/list2))。
|
||||
<br>
|
||||
The content of this project itself is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0),
|
||||
some files are licensed under the [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) ([list](rc/list1)),
|
||||
some files are licensed under the [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) ([list](rc/list2)).
|
||||
@@ -1 +1,3 @@
|
||||
/build
|
||||
/src/main/obj
|
||||
/src/main/libs
|
||||
+110
-94
@@ -1,95 +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" />
|
||||
<option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
|
||||
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
|
||||
<option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
|
||||
<option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
|
||||
<option name="ALLOW_USER_CONFIGURATION" value="false" />
|
||||
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
|
||||
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
|
||||
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
|
||||
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="false">
|
||||
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
|
||||
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" exported="" name="support-v4-22.0.0" level="project" />
|
||||
<orderEntry type="library" exported="" name="svg-android-2.0.6" level="project" />
|
||||
<orderEntry type="library" exported="" name="support-annotations-22.0.0" level="project" />
|
||||
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
|
||||
<orderEntry type="library" exported="" name="recyclerview-v7-22.0.0" level="project" />
|
||||
</component>
|
||||
<?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>
|
||||
+47
-6
@@ -1,15 +1,17 @@
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion "22"
|
||||
buildToolsVersion '22.0.1'
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.hippo.ehviewer"
|
||||
minSdkVersion 14
|
||||
targetSdkVersion 22
|
||||
versionCode 40
|
||||
versionName "0.6.14"
|
||||
versionCode 47
|
||||
versionName "0.6.16.3"
|
||||
}
|
||||
buildTypes {
|
||||
debug {
|
||||
@@ -21,11 +23,50 @@ android {
|
||||
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 'com.android.support:support-v4:22.0.0'
|
||||
compile 'com.android.support:recyclerview-v7:22.0.0'
|
||||
compile 'com.github.japgolly.android:svg-android:2.0.6'
|
||||
compile project(':vector')
|
||||
compile 'com.android.support:support-v4:22.2.1'
|
||||
compile 'com.android.support:recyclerview-v7:22.2.1'
|
||||
}
|
||||
Vendored
+3
@@ -48,5 +48,8 @@
|
||||
*** get*();
|
||||
}
|
||||
|
||||
# For VectorResources
|
||||
-keep class android.content.res.VectorResources {*;}
|
||||
|
||||
# I want to track the error in them
|
||||
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
|
||||
@@ -79,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" />
|
||||
@@ -135,6 +136,22 @@
|
||||
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" />
|
||||
@@ -144,6 +161,13 @@
|
||||
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>
|
||||
@@ -23,16 +23,16 @@ 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.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
@@ -72,7 +72,7 @@ public class AppContext extends Application implements UncaughtExceptionHandler
|
||||
Log.init(mContextThemeWrapper);
|
||||
Crash.init(mContextThemeWrapper);
|
||||
EhClient.createInstance(mContextThemeWrapper);
|
||||
Favorite.init(mContextThemeWrapper);
|
||||
FavoriteHelper.init(mContextThemeWrapper);
|
||||
Data.createInstance(mContextThemeWrapper);
|
||||
ExDownloaderManager.createInstance(mContextThemeWrapper);
|
||||
MaterialToast.setContext(mContextThemeWrapper);
|
||||
@@ -148,7 +148,7 @@ public class AppContext extends Application implements UncaughtExceptionHandler
|
||||
*/
|
||||
@Override
|
||||
public void onLowMemory() {
|
||||
ImageCache.getImageCache(this).evictAll();
|
||||
ImageCache.getImageCache(this).clearMemory();
|
||||
super.onLowMemory();
|
||||
}
|
||||
|
||||
@@ -162,10 +162,15 @@ public class AppContext extends Application implements UncaughtExceptionHandler
|
||||
}
|
||||
|
||||
private boolean handleException(Throwable ex) {
|
||||
if (ex == null)
|
||||
if (ex == null) {
|
||||
return false;
|
||||
Crash.saveCrashInfo2File(ex);
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
Crash.saveCrashInfo2File(ex);
|
||||
return true;
|
||||
} catch (Throwable tr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Typeface getFaceTypeface() {
|
||||
|
||||
@@ -23,25 +23,29 @@ import android.os.Bundle;
|
||||
import android.text.util.Linkify;
|
||||
import android.view.View;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.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.AppUtils;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Crash;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.larvalabs.svgandroid.SVGBuilder;
|
||||
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;
|
||||
@@ -51,6 +55,7 @@ public class StartActivity extends AbsActivity {
|
||||
private static final String KEY_SET_ANALYTICS = "set_analyics";
|
||||
|
||||
private String lastCrash;
|
||||
private boolean isEnterPattern = false;
|
||||
private boolean isAnimationOver = false;
|
||||
private boolean isCheckOver = false;
|
||||
|
||||
@@ -160,9 +165,7 @@ public class StartActivity extends AbsActivity {
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
AppUtils.sendEmail(StartActivity.this, "ehviewersu@gmail.com",
|
||||
"I found a bug in EhViewer !",
|
||||
lastCrash + "======== Description ========\n" + et.getText().toString());
|
||||
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:
|
||||
@@ -185,9 +188,8 @@ public class StartActivity extends AbsActivity {
|
||||
|
||||
TextView text = (TextView) findViewById(R.id.text);
|
||||
text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/GloriaHallelujah.ttf"));
|
||||
ImageView image = (ImageView) findViewById(R.id.image);
|
||||
image.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
|
||||
image.setImageDrawable(new SVGBuilder().readFromResource(getResources(), R.raw.sad_pandroid).build().getDrawable());
|
||||
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);
|
||||
@@ -198,12 +200,37 @@ public class StartActivity extends AbsActivity {
|
||||
AppHandler.getInstance().postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (isCheckOver)
|
||||
redirectTo();
|
||||
isAnimationOver = true;
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -241,7 +268,7 @@ public class StartActivity extends AbsActivity {
|
||||
}
|
||||
|
||||
private void checkOver() {
|
||||
if (isAnimationOver)
|
||||
if (isAnimationOver && isEnterPattern)
|
||||
redirectTo();
|
||||
isCheckOver = true;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -36,6 +31,11 @@ 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
|
||||
|
||||
@@ -254,5 +254,10 @@ public class UpdateHelper implements Runnable {
|
||||
}
|
||||
setEnabled(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+191
-60
@@ -35,40 +35,64 @@ public abstract class AnyCache<V> {
|
||||
|
||||
private static final String TAG = AnyCache.class.getSimpleName();
|
||||
|
||||
private @Nullable LruCache<String, V> mMemoryCache;
|
||||
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);
|
||||
|
||||
public void setMemoryCache(int maxSize) {
|
||||
mMemoryCache = new MemoryCahce<V>(maxSize, this);
|
||||
}
|
||||
|
||||
public void setDiskCache(File cacheDir, int maxSize) {
|
||||
try {
|
||||
mDiskCache = new DiskCache<V>(cacheDir, maxSize, this);
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "Can't create disk cache", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if have memory cache
|
||||
*
|
||||
* @return true if have memory cache
|
||||
*/
|
||||
public boolean hasMemoryCache() {
|
||||
return mMemoryCache != null;
|
||||
return mHasMemoryCache;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +101,7 @@ public abstract class AnyCache<V> {
|
||||
* @return true if have disk cache
|
||||
*/
|
||||
public boolean hasDiskCache() {
|
||||
return mDiskCache != null;
|
||||
return mHasDiskCache;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,7 +111,7 @@ public abstract class AnyCache<V> {
|
||||
* @return the value you get, null for miss or no memory cache
|
||||
*/
|
||||
public V getFromMemory(String key) {
|
||||
if (mMemoryCache != null) {
|
||||
if (mHasMemoryCache) {
|
||||
return mMemoryCache.get(key);
|
||||
} else {
|
||||
return null;
|
||||
@@ -101,12 +125,19 @@ public abstract class AnyCache<V> {
|
||||
* @return the value you get, null for miss or no memory cache or get error
|
||||
*/
|
||||
public V getFromDisk(String key) {
|
||||
if (mDiskCache != null) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
return mDiskCache.get(diskKey);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
return mDiskCache.get(diskKey);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -120,28 +151,22 @@ public abstract class AnyCache<V> {
|
||||
* @return the value you get
|
||||
*/
|
||||
public V get(String key) {
|
||||
V value;
|
||||
if (mMemoryCache != null) {
|
||||
value = mMemoryCache.get(key);
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
V value = getFromMemory(key);
|
||||
|
||||
if (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
value = mDiskCache.get(diskKey);
|
||||
// Put value to memory cach
|
||||
if (value != null && mMemoryCache != null) {
|
||||
mMemoryCache.put(key, value);
|
||||
}
|
||||
if (value != null) {
|
||||
// Get it in memory cache
|
||||
return value;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
value = getFromDisk(key);
|
||||
|
||||
if (value != null) {
|
||||
// Get it in disk cache
|
||||
putToMemory(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,7 +177,7 @@ public abstract class AnyCache<V> {
|
||||
* @return false if no memory cache
|
||||
*/
|
||||
public boolean putToMemory(String key, V value) {
|
||||
if (mMemoryCache != null) {
|
||||
if (mHasMemoryCache) {
|
||||
mMemoryCache.put(key, value);
|
||||
return true;
|
||||
} else {
|
||||
@@ -168,12 +193,20 @@ public abstract class AnyCache<V> {
|
||||
* @return false if no disk cache or get error
|
||||
*/
|
||||
public boolean putToDisk(String key, V value) {
|
||||
if (mDiskCache != null) {
|
||||
if (mHasDiskCache) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
return mDiskCache.put(diskKey, value);
|
||||
|
||||
synchronized (mDiskCacheLock) {
|
||||
if (mDiskCache != null) {
|
||||
mDiskCache.put(diskKey, value);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
@@ -186,17 +219,8 @@ public abstract class AnyCache<V> {
|
||||
* @param value the value
|
||||
*/
|
||||
public void put(String key, V value) {
|
||||
if (mMemoryCache != null) {
|
||||
mMemoryCache.put(key, value);
|
||||
}
|
||||
|
||||
if (mDiskCache != null) {
|
||||
// Wait for pause
|
||||
waitUntilUnpaused();
|
||||
|
||||
String diskKey = hashKeyForDisk(key);
|
||||
mDiskCache.put(diskKey, value);
|
||||
}
|
||||
putToMemory(key, value);
|
||||
putToDisk(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -230,15 +254,57 @@ public abstract class AnyCache<V> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 evictAll() {
|
||||
if (mMemoryCache != null) {
|
||||
mMemoryCache.evictAll();
|
||||
}
|
||||
System.gc();
|
||||
public void clear() {
|
||||
clearMemory();
|
||||
clearDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -278,6 +344,43 @@ public abstract class AnyCache<V> {
|
||||
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;
|
||||
@@ -298,12 +401,38 @@ public abstract class AnyCache<V> {
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
public DiskLruCache mDiskLruCache;
|
||||
public AnyCache<E> mParent;
|
||||
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) {
|
||||
@@ -335,6 +464,7 @@ public abstract class AnyCache<V> {
|
||||
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) {
|
||||
@@ -347,18 +477,19 @@ public abstract class AnyCache<V> {
|
||||
final BufferedOutputStream buffOut =
|
||||
new BufferedOutputStream(os, IO_BUFFER_SIZE);
|
||||
boolean result = mParent.write(buffOut, value);
|
||||
mDiskLruCache.flush();
|
||||
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 (editor != null) {
|
||||
if (!completeEdit && editor != null) {
|
||||
editor.abort();
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
|
||||
+15
-15
@@ -49,25 +49,25 @@ public class ImageCache extends AnyCache<Bitmap>{
|
||||
|
||||
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
|
||||
if (sImageCache == null) {
|
||||
sImageCache = new ImageCache(context.getApplicationContext());
|
||||
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;
|
||||
}
|
||||
|
||||
private ImageCache(Context context) {
|
||||
final ActivityManager activityManager = (ActivityManager)context
|
||||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
|
||||
* 1024 * 1024);
|
||||
setMemoryCache(memoryCacheMax);
|
||||
|
||||
File diskCacheDir = getDiskCacheDir(context, TAG);
|
||||
if (diskCacheDir != null) {
|
||||
if (!diskCacheDir.exists()) {
|
||||
diskCacheDir.mkdirs();
|
||||
}
|
||||
setDiskCache(diskCacheDir, 20 * 1024 * 1024);
|
||||
}
|
||||
public ImageCache(AnyCacheParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -681,7 +681,7 @@ public class Data {
|
||||
public static final int READ = 0x2;
|
||||
|
||||
public synchronized List<HistoryItem> getHistory(int mode, boolean desc) {
|
||||
List<HistoryItem> history = new ArrayList<HistoryItem>();
|
||||
List<HistoryItem> history = new ArrayList<>();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("select * from ").append(TABLE_HISTORY);
|
||||
@@ -759,6 +759,11 @@ public class Data {
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void deleteHistory(int gid) {
|
||||
mDatabase.delete(TABLE_HISTORY, COLUMN_GID + "=?", new String[]{String.valueOf(gid)});
|
||||
deleteGallery(gid);
|
||||
}
|
||||
|
||||
public void clearHistory() {
|
||||
truncateHistory(0);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
@@ -166,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);
|
||||
|
||||
@@ -63,12 +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;
|
||||
public LinkedList<Comment> comments;
|
||||
public int torrentNumber;
|
||||
public String torrentUrl;
|
||||
|
||||
public void reset() {
|
||||
eMesg = null;
|
||||
@@ -92,6 +95,8 @@ public class DetailParser {
|
||||
tags = null;
|
||||
previewList = null;
|
||||
comments = null;
|
||||
torrentNumber = 0;
|
||||
torrentUrl = null;
|
||||
}
|
||||
|
||||
public int parser(String body, int mode) {
|
||||
@@ -125,16 +130,17 @@ public class DetailParser {
|
||||
// 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>"
|
||||
+ ".+"
|
||||
+ ".+?"
|
||||
+ "<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
|
||||
@@ -144,11 +150,13 @@ public class DetailParser {
|
||||
+ "<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()) {
|
||||
@@ -157,26 +165,30 @@ public class DetailParser {
|
||||
thumb = Utils.unescapeXml(m.group(1));
|
||||
title = Utils.unescapeXml(m.group(2));
|
||||
title_jpn = Utils.unescapeXml(m.group(3));
|
||||
category = EhUtils.getCategory(m.group(4));
|
||||
uploader = m.group(5);
|
||||
posted = m.group(6);
|
||||
parent = m.group(7);
|
||||
visible = m.group(8);
|
||||
language = Utils.unescapeXml(m.group(9)).trim();
|
||||
size = Utils.unescapeXml(m.group(10)).trim();
|
||||
resized = m.group(11);
|
||||
pages = Integer.parseInt(m.group(12).replace(",", ""));
|
||||
// favoriteTimes = m.group(13)
|
||||
people = Integer.parseInt(m.group(14).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(15));
|
||||
Matcher matcher = pattern.matcher(m.group(17));
|
||||
if (matcher.find())
|
||||
rating = Float.parseFloat(matcher.group(1));
|
||||
else
|
||||
rating = Float.NaN;
|
||||
|
||||
firstPage = m.group(16);
|
||||
isFavorite = "Favorite Gallery".equals(m.group(18));
|
||||
|
||||
firstPage = m.group(19);
|
||||
}
|
||||
}
|
||||
// Get tag
|
||||
|
||||
@@ -52,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()) {
|
||||
@@ -94,7 +94,7 @@ public class EdDetailParser {
|
||||
|
||||
boolean first = true;
|
||||
if (body.contains("<div class=\"gdtl\"")) {
|
||||
p = Pattern.compile("<div class=\"gdtl\"[^>]*><a href=\"http://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
p = Pattern.compile("<div class=\"gdtl\"[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
@@ -106,7 +106,7 @@ public class EdDetailParser {
|
||||
}
|
||||
|
||||
} else {
|
||||
p = Pattern.compile("<div class=\"gdtm\"[^>]*><div[^>]*><a href=\"http://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
p = Pattern.compile("<div class=\"gdtm\"[^>]*><div[^>]*><a href=\"https?://[^/]+/s/(\\w+)/\\d+-(\\d+)\">");
|
||||
m = p.matcher(body);
|
||||
while(m.find()) {
|
||||
if (first) {
|
||||
|
||||
@@ -22,6 +22,8 @@ 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;
|
||||
@@ -47,7 +49,6 @@ 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;
|
||||
|
||||
@@ -62,15 +63,15 @@ 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";
|
||||
|
||||
public 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/";
|
||||
|
||||
public static final String API_EHVIEWER = "http://www.ehviewer.com/API";
|
||||
@@ -122,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());
|
||||
}
|
||||
|
||||
@@ -132,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());
|
||||
}
|
||||
|
||||
@@ -156,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());
|
||||
}
|
||||
|
||||
@@ -182,7 +187,7 @@ public class EhClient {
|
||||
.append("-").append(pageNum).toString();
|
||||
}
|
||||
|
||||
public String getApiUrl() {
|
||||
public static String getApiUrl() {
|
||||
return getApiUrl(Config.getApiMode());
|
||||
}
|
||||
|
||||
@@ -196,7 +201,7 @@ public class EhClient {
|
||||
}
|
||||
}
|
||||
|
||||
public String getFavoriteUrl(int page) {
|
||||
public static String getFavoriteUrl(int page) {
|
||||
return getFavoriteUrl(Config.getApiMode(), page);
|
||||
}
|
||||
|
||||
@@ -214,7 +219,7 @@ public class EhClient {
|
||||
return sb.append("favorites.php?page=").append(page).toString();
|
||||
}
|
||||
|
||||
public String getFavoriteUrlWithCat(int index, int page) {
|
||||
public static String getFavoriteUrlWithCat(int index, int page) {
|
||||
return getFavoriteUrlWithCat(Config.getApiMode(), index, page);
|
||||
}
|
||||
|
||||
@@ -233,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
|
||||
@@ -391,7 +376,7 @@ 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
|
||||
@@ -550,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";
|
||||
@@ -708,11 +693,9 @@ 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)) == (DetailParser.DETAIL | DetailParser.PREVIEW_INFO |
|
||||
DetailParser.PREVIEW)) {
|
||||
@@ -734,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);
|
||||
@@ -754,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);
|
||||
|
||||
@@ -25,8 +25,9 @@ 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.larvalabs.svgandroid.SVGBuilder;
|
||||
import com.hippo.vector.VectorDrawable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
@@ -35,6 +36,7 @@ import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -52,9 +54,9 @@ public class EhInfo {
|
||||
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;
|
||||
@@ -106,7 +108,7 @@ public class EhInfo {
|
||||
mContext = context;
|
||||
mInfoPref = mContext.getSharedPreferences(PREF_NAME, 0);
|
||||
if (DEFAULT_AVATAR == null)
|
||||
DEFAULT_AVATAR = new SVGBuilder().readFromResource(context.getResources(), R.raw.default_avatar).build().getDrawable();
|
||||
DEFAULT_AVATAR = VectorDrawable.create(context, R.drawable.default_avatar);
|
||||
|
||||
mIsLogin = mInfoPref.getBoolean(KEY_LOGIN, DEFAULT_LOGIN);
|
||||
mUsername = mInfoPref.getString(KEY_USERNAME, DEFAULT_NAME);
|
||||
@@ -146,12 +148,36 @@ public class EhInfo {
|
||||
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;
|
||||
|
||||
@@ -51,11 +51,9 @@ public final class ExDownloader implements Runnable {
|
||||
|
||||
private static final int IO_BUFFER_SIZE = 8 * 1024;
|
||||
|
||||
private static final String[] URL_ARRAY_509 = new String[] {
|
||||
"http://ehgt.org/g/509.gif",
|
||||
"http://ehgt.org/g/509s.gif",
|
||||
"http://st.exhentai.net/img/509.gif",
|
||||
"http://st.exhentai.net/img/509s.gif"
|
||||
private static final String[] URL_509_SUFFIX_ARRAY = {
|
||||
"/509.gif",
|
||||
"/509s.gif"
|
||||
};
|
||||
|
||||
private final Context mContext;
|
||||
@@ -668,6 +666,9 @@ public final class ExDownloader implements Runnable {
|
||||
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
|
||||
@@ -751,7 +752,8 @@ public final class ExDownloader implements Runnable {
|
||||
String filename = EhUtils.getImageFilename(targetIndex, "jpg");
|
||||
// Download
|
||||
hh.reset();
|
||||
if (hh.downloadOriginEhImage(imageUrl, mDir, filename, false, c, listener) == null) {
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadOriginEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (hh.getException() instanceof HttpHelper.BandwidthExceededException) {
|
||||
// Get 509
|
||||
show509Notification(mContext);
|
||||
@@ -761,7 +763,8 @@ public final class ExDownloader implements Runnable {
|
||||
if (newImageUrl != null) {
|
||||
// Try download from proxy
|
||||
hh.reset();
|
||||
if (hh.downloadEhImage(newImageUrl, mDir, filename, true, c, listener) == null) {
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(newImageUrl, mDir, filename, option, c, listener) == null) {
|
||||
// Download failed
|
||||
Log.d(TAG, "Download failed");
|
||||
} else {
|
||||
@@ -786,9 +789,8 @@ public final class ExDownloader implements Runnable {
|
||||
|
||||
//Check 509 gif
|
||||
boolean get509 = false;
|
||||
int length = URL_ARRAY_509.length;
|
||||
for (int j = 0; j < length; j++) {
|
||||
if (URL_ARRAY_509[j].equals(imageUrl)) {
|
||||
for (String suffix : URL_509_SUFFIX_ARRAY) {
|
||||
if (imageUrl.endsWith(suffix)) {
|
||||
// Get 509 gif here
|
||||
get509 = true;
|
||||
break;
|
||||
@@ -804,9 +806,11 @@ public final class ExDownloader implements Runnable {
|
||||
// Don't put into mImageFilenameArray, because extension maybe be wrong
|
||||
// mImageFilenameArray.set(targetIndex, filename);
|
||||
hh.reset();
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, false, c, listener) == null) {
|
||||
option.setUseProxy(false);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
hh.reset();
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, true, c, listener) == null) {
|
||||
option.setUseProxy(true);
|
||||
if (hh.downloadEhImage(imageUrl, mDir, filename, option, c, listener) == null) {
|
||||
if (i == 1) {
|
||||
// TODO download error
|
||||
Log.d(TAG, "download error");
|
||||
@@ -918,5 +922,10 @@ public final class ExDownloader implements Runnable {
|
||||
lastPercent = 0.0f;
|
||||
lastDownloadSize = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer.gallery;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Movie;
|
||||
@@ -52,6 +50,8 @@ import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ZInterpolator;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class GalleryView extends GLView implements ImageSet.ImageListener,
|
||||
Runnable {
|
||||
@SuppressWarnings("unused")
|
||||
@@ -958,6 +958,25 @@ public class GalleryView extends GLView implements ImageSet.ImageListener,
|
||||
return false;
|
||||
}
|
||||
|
||||
public void showPreviousPage() {
|
||||
// TODO goto bottom first the to pre page
|
||||
resetSizePosition(PRE_TARGET_INDEX);
|
||||
if (!goToPrePage()) {
|
||||
// Get to first page
|
||||
MaterialToast.showToast(mContext.getString(R.string.first_page));
|
||||
}
|
||||
}
|
||||
|
||||
public void showNextPage() {
|
||||
// TODO goto bottom first the to pre page
|
||||
resetSizePosition(NEXT_TARGET_INDEX);
|
||||
if (!goToNextPage()) {
|
||||
// Get to last page
|
||||
MaterialToast.showToast(mContext.getString(isEnsureSize ?
|
||||
R.string.the_last_page : R.string.wait_for_more));
|
||||
}
|
||||
}
|
||||
|
||||
private class MyGestureListener implements GestureRecognizer.Listener {
|
||||
|
||||
private boolean isScale = false;
|
||||
@@ -1184,25 +1203,6 @@ public class GalleryView extends GLView implements ImageSet.ImageListener,
|
||||
mDoubleTapRunner.setInterpolator(new ZInterpolator(0.5f));
|
||||
}
|
||||
|
||||
private void onTapPre() {
|
||||
// TODO goto bottom first the to pre page
|
||||
resetSizePosition(PRE_TARGET_INDEX);
|
||||
if (!goToPrePage()) {
|
||||
// Get to first page
|
||||
MaterialToast.showToast(mContext.getString(R.string.first_page));
|
||||
}
|
||||
}
|
||||
|
||||
private void onTapNext() {
|
||||
// TODO goto bottom first the to pre page
|
||||
resetSizePosition(NEXT_TARGET_INDEX);
|
||||
if (!goToNextPage()) {
|
||||
// Get to last page
|
||||
MaterialToast.showToast(mContext.getString(isEnsureSize ?
|
||||
R.string.the_last_page : R.string.wait_for_more));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSingleTapConfirmed(float x, float y) {
|
||||
if (mScrollState != SCROLL_NONE) {
|
||||
@@ -1224,18 +1224,18 @@ public class GalleryView extends GLView implements ImageSet.ImageListener,
|
||||
|
||||
if (Utils.isInArea(leftArea, (int) x, (int) y)) {
|
||||
if (isRightToLeft())
|
||||
onTapNext();
|
||||
showNextPage();
|
||||
else
|
||||
onTapPre();
|
||||
showPreviousPage();
|
||||
|
||||
} else if (Utils.isInArea(topArea, (int) x, (int) y)) {
|
||||
zoom(true);
|
||||
|
||||
} else if (Utils.isInArea(rightArea, (int) x, (int) y)) {
|
||||
if (isRightToLeft())
|
||||
onTapPre();
|
||||
showPreviousPage();
|
||||
else
|
||||
onTapNext();
|
||||
showNextPage();
|
||||
|
||||
} else if (Utils.isInArea(bottomArea, (int) x, (int) y)) {
|
||||
zoom(false);
|
||||
|
||||
@@ -16,13 +16,8 @@
|
||||
|
||||
package com.hippo.ehviewer.gallery.data;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Movie;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.ehclient.ExDownloader;
|
||||
@@ -35,6 +30,12 @@ import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class ImageSet implements ExDownloader.ListenerForImageSet {
|
||||
|
||||
private static final String TAG = ImageSet.class.getSimpleName();
|
||||
@@ -52,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;
|
||||
@@ -266,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() {
|
||||
|
||||
+27
-7
@@ -14,21 +14,24 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
public final class AppUtils {
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
// TODO add common error tip
|
||||
public static void sendEmail(@NonNull Activity from, @NonNull String email,
|
||||
public final class ActivityHelper {
|
||||
|
||||
public static boolean sendEmail(@NonNull Activity from, @NonNull String address,
|
||||
@Nullable String subject, @Nullable String text) {
|
||||
Intent i = new Intent(Intent.ACTION_SENDTO);
|
||||
i.setData(Uri.parse("mailto:" + email));
|
||||
i.setData(Uri.parse("mailto:" + address));
|
||||
if (subject != null) {
|
||||
i.putExtra(Intent.EXTRA_SUBJECT, subject);
|
||||
}
|
||||
@@ -38,8 +41,25 @@ public final class AppUtils {
|
||||
|
||||
try {
|
||||
from.startActivity(i);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return true;
|
||||
} catch (ActivityNotFoundException e) {
|
||||
MaterialToast.showToast(R.string.em_cant_find_activity);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean share(@NonNull Activity from, String text) {
|
||||
Intent sendIntent = new Intent();
|
||||
sendIntent.setAction(Intent.ACTION_SEND);
|
||||
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
|
||||
sendIntent.setType("text/plain");
|
||||
|
||||
try {
|
||||
from.startActivity(sendIntent);
|
||||
return true;
|
||||
} catch (ActivityNotFoundException e) {
|
||||
MaterialToast.showToast(R.string.em_cant_find_activity);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class Downloader implements Runnable, HttpHelper.OnDownloadListener {
|
||||
|
||||
private Context mContext;
|
||||
private String mUrl;
|
||||
private File mDir;
|
||||
private String mFilename;
|
||||
|
||||
private boolean mIsRunning = false;
|
||||
|
||||
public Downloader(Context context, String url, File dir, String filename) {
|
||||
mContext = context.getApplicationContext();
|
||||
mUrl = url;
|
||||
mDir = dir;
|
||||
mFilename = filename;
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return mIsRunning;
|
||||
}
|
||||
|
||||
public void startDownload() {
|
||||
if (mIsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
mIsRunning = true;
|
||||
new BgThread(this).start();
|
||||
MaterialToast.showToast(R.string.start_saving_torrent);
|
||||
}
|
||||
|
||||
public void post(Runnable runnable) {
|
||||
AppHandler.getInstance().post(runnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
HttpHelper.DownloadOption dOpt = new HttpHelper.DownloadOption();
|
||||
dOpt.setUseProxy(false);
|
||||
dOpt.setAllowFixingExtension(true);
|
||||
dOpt.setAllowFixingName(true);
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
final boolean ok = HttpHelper.DOWNLOAD_OK_STR.equals(
|
||||
hh.download(mUrl, mDir, mFilename, null, null, this));
|
||||
post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
MaterialToast.showToast(ok ?
|
||||
String.format(mContext.getString(R.string.save_torrent_successful),
|
||||
mDir.getAbsolutePath() + File.separatorChar + mFilename) :
|
||||
mContext.getString(R.string.save_torrent_failed));
|
||||
}
|
||||
});
|
||||
mIsRunning = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStartConnect() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStartDownload(int totalSize) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadStatusUpdate(int downloadSize, int totalSize) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadOver(int status, String eMsg) {
|
||||
// Empty
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpdateFilename(String newFilename) {
|
||||
mFilename = newFilename;
|
||||
}
|
||||
}
|
||||
+34
-8
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.AlertDialog;
|
||||
@@ -31,9 +31,11 @@ import com.hippo.ehviewer.app.MaterialAlertDialog;
|
||||
import com.hippo.ehviewer.data.Data;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class Favorite {
|
||||
public class FavoriteHelper {
|
||||
|
||||
private static Context mContext;
|
||||
private static Resources mResources;
|
||||
@@ -53,15 +55,19 @@ public class Favorite {
|
||||
}
|
||||
}
|
||||
|
||||
public static void addToFavorite(final Context context, GalleryInfo gi) {
|
||||
int defaultFavorite = Config.getDefaultFavorite();
|
||||
public static void addToFavorite(final Context context, final GalleryInfo gi,
|
||||
final OnAddToFavoriteListener listener) {
|
||||
final int defaultFavorite = Config.getDefaultFavorite();
|
||||
switch (defaultFavorite) {
|
||||
case -2:
|
||||
Favorite.getAddToFavoriteDialog(context, gi).show();
|
||||
FavoriteHelper.getAddToFavoriteDialog(context, gi, listener).show();
|
||||
break;
|
||||
case -1:
|
||||
Data.getInstance().addLocalFavourite(gi);
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, -1);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
EhClient.getInstance().addToFavorite(gi.gid,
|
||||
@@ -69,19 +75,24 @@ public class Favorite {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, defaultFavorite);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
MaterialToast.showToast(R.string.failed_to_add);
|
||||
if (listener != null) {
|
||||
listener.onFailure(eMsg, gi, defaultFavorite);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
public static AlertDialog getAddToFavoriteDialog(final Context context, final GalleryInfo gi) {
|
||||
|
||||
// TODO List do not work final
|
||||
public static AlertDialog getAddToFavoriteDialog(final Context context, final GalleryInfo gi,
|
||||
final OnAddToFavoriteListener listener) {
|
||||
|
||||
View view = ViewUtils.inflateDialogView(R.layout.add_to_favorite, false);
|
||||
final CheckBox cb = (CheckBox) view.findViewById(R.id.set_default);
|
||||
@@ -97,10 +108,14 @@ public class Favorite {
|
||||
|
||||
if (cb.isChecked())
|
||||
Config.setDefaultFavorite(position - 1);
|
||||
final int favoriteSlot = position - 1;
|
||||
|
||||
switch (position) {
|
||||
case 0:
|
||||
Data.getInstance().addLocalFavourite(gi);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, favoriteSlot);
|
||||
}
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
break;
|
||||
default:
|
||||
@@ -109,10 +124,16 @@ public class Favorite {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
MaterialToast.showToast(R.string.toast_add_favourite);
|
||||
if (listener != null) {
|
||||
listener.onSuccess(gi, favoriteSlot);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
MaterialToast.showToast(R.string.failed_to_add);
|
||||
if (listener != null) {
|
||||
listener.onFailure(eMsg, gi, favoriteSlot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -124,4 +145,9 @@ public class Favorite {
|
||||
.setView(view, false).setNegativeButton(android.R.string.cancel)
|
||||
.setPositiveButton(android.R.string.ok).create();
|
||||
}
|
||||
|
||||
public interface OnAddToFavoriteListener {
|
||||
void onSuccess(GalleryInfo gi, int slot);
|
||||
void onFailure(String eMsg, GalleryInfo gi, int slot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* com.hippo.ehviewer.miscellaneous is a group of stuff combine more than one scopes
|
||||
*/
|
||||
package com.hippo.ehviewer.miscellaneous;
|
||||
@@ -16,35 +16,12 @@
|
||||
|
||||
package com.hippo.ehviewer.network;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.SocketException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.os.Message;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.webkit.MimeTypeMap;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
@@ -62,6 +39,32 @@ import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.SocketException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* It is not thread safe
|
||||
*
|
||||
@@ -80,13 +83,20 @@ public class HttpHelper {
|
||||
public static final int DOWNLOAD_FAIL_CODE = 0x1;
|
||||
public static final int DOWNLOAD_STOP_CODE = 0x2;
|
||||
|
||||
// User-Agent from H@H
|
||||
public static final String DEFAULT_USER_AGENT =
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) " +
|
||||
"Gecko/20080201 Firefox/2.0.0.12";
|
||||
public static final String USER_AGENT = DEFAULT_USER_AGENT;
|
||||
//System.getProperty("http.agent", DEFAULT_USER_AGENT);
|
||||
|
||||
private static final String DEFAULT_CHARSET = "utf-8";
|
||||
private static final String CHARSET_KEY = "charset=";
|
||||
|
||||
// TODO Get proxy list from server
|
||||
private static String[] sProxyUrls = Config.DEFAULT_PROXY_URLS;
|
||||
private static volatile int sProxyIndex = MathUtils.random(0, sProxyUrls.length);
|
||||
private static Object sProxyIndexLock = new Object();
|
||||
private static final Object sProxyIndexLock = new Object();
|
||||
|
||||
public class Package {
|
||||
public Object obj;
|
||||
@@ -217,15 +227,6 @@ public class HttpHelper {
|
||||
return mLastUrl;
|
||||
}
|
||||
|
||||
private boolean isUrlCookiable(URL url) {
|
||||
String host = url.getHost();
|
||||
for (String h : EhInfo.COOKIABLE_HOSTS) {
|
||||
if (h.equals(host))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void setPreviewMode(String previewMode) {
|
||||
mPreviewMode = previewMode;
|
||||
}
|
||||
@@ -242,7 +243,7 @@ public class HttpHelper {
|
||||
try {
|
||||
url = (mLastUrl == null ? rh.getUrl() : new URL(mLastUrl));
|
||||
|
||||
isCookiable = isUrlCookiable(url);
|
||||
isCookiable = EhInfo.isEhSite(url);
|
||||
|
||||
while (isCookiable) {
|
||||
synchronized(ehLock) {
|
||||
@@ -261,7 +262,7 @@ public class HttpHelper {
|
||||
while (redirectionCount++ < Constants.MAX_REDIRECTS) {
|
||||
conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setInstanceFollowRedirects(false);
|
||||
conn.setRequestProperty("User-Agent", Constants.userAgent);
|
||||
conn.setRequestProperty("User-Agent", USER_AGENT);
|
||||
conn.setConnectTimeout(Config.getHttpConnectTimeout());
|
||||
conn.setReadTimeout(Config.getHttpReadTimeout());
|
||||
// Set cookie if necessary
|
||||
@@ -345,13 +346,51 @@ public class HttpHelper {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* parse string like <code>haha=hehe; fere=bfdgds</code>
|
||||
*/
|
||||
public static @NonNull Map<String, String> parseMap(@Nullable String raw) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
if (raw != null) {
|
||||
String[] pieces = raw.split(";");
|
||||
for (String p : pieces) {
|
||||
int index = p.indexOf('=');
|
||||
if (index != -1) {
|
||||
String key = p.substring(0, index).trim();
|
||||
String value = p.substring(index + 1).trim();
|
||||
|
||||
// value might be "blabla", remove "
|
||||
int valueLength = value.length();
|
||||
if (value.length() > 1 && value.charAt(0) == '"' &&
|
||||
value.charAt(valueLength - 1) == '"') {
|
||||
value = value.substring(1, valueLength - 1);
|
||||
}
|
||||
map.put(key.toLowerCase(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
public static @Nullable String getMime(HttpURLConnection conn) {
|
||||
String contentType = conn.getContentType();
|
||||
// looks like text/html; charset=ISO-8859-4 or text/html
|
||||
int index = contentType.indexOf(';');
|
||||
if (index != -1) {
|
||||
return contentType.substring(0, index);
|
||||
} else {
|
||||
return contentType;
|
||||
}
|
||||
}
|
||||
|
||||
private interface RequestHelper {
|
||||
|
||||
/**
|
||||
* Get the URL to connect
|
||||
* @return
|
||||
*/
|
||||
public URL getUrl() throws MalformedURLException;
|
||||
URL getUrl() throws MalformedURLException;
|
||||
|
||||
/**
|
||||
* Add header or do something else for HttpURLConnection before connect
|
||||
@@ -359,7 +398,7 @@ public class HttpHelper {
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
public void onBeforeConnect(HttpURLConnection conn) throws Exception;
|
||||
void onBeforeConnect(HttpURLConnection conn) throws Exception;
|
||||
|
||||
/**
|
||||
* Get what do you need from HttpURLConnection after connect
|
||||
@@ -368,13 +407,13 @@ public class HttpHelper {
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public Object onAfterConnect(HttpURLConnection conn) throws Exception;
|
||||
Object onAfterConnect(HttpURLConnection conn) throws Exception;
|
||||
|
||||
/**
|
||||
* Handle exception
|
||||
* @param e
|
||||
*/
|
||||
public void onGetException(Exception e);
|
||||
void onGetException(Exception e);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -716,19 +755,18 @@ public class HttpHelper {
|
||||
public void onGetException(Exception e) {}
|
||||
}
|
||||
|
||||
public static interface OnDownloadListener {
|
||||
public void onDownloadStartConnect();
|
||||
public interface OnDownloadListener {
|
||||
void onDownloadStartConnect();
|
||||
/**
|
||||
* If totalSize -1 for can't get length info
|
||||
* @param totalSize
|
||||
*/
|
||||
public void onDownloadStartDownload(int totalSize);
|
||||
void onDownloadStartDownload(int totalSize);
|
||||
/**
|
||||
* If totalSize -1 for can't get length info
|
||||
* @param totalSize
|
||||
*/
|
||||
public void onDownloadStatusUpdate(int downloadSize, int totalSize);
|
||||
public void onDownloadOver(int status, String eMsg);
|
||||
void onDownloadStatusUpdate(int downloadSize, int totalSize);
|
||||
void onDownloadOver(int status, String eMsg);
|
||||
void onUpdateFilename(String newFilename);
|
||||
}
|
||||
|
||||
public static class DownloadControlor {
|
||||
@@ -747,34 +785,71 @@ public class HttpHelper {
|
||||
}
|
||||
}
|
||||
|
||||
public static class DownloadOption {
|
||||
|
||||
public boolean mAllowFixingName = false;
|
||||
public boolean mAllowFixingExtension = false;
|
||||
public boolean mUseProxy = false;
|
||||
|
||||
public boolean isAllowFixingName() {
|
||||
return mAllowFixingName;
|
||||
}
|
||||
|
||||
public void setAllowFixingName(boolean allowFixingName) {
|
||||
mAllowFixingName = allowFixingName;
|
||||
}
|
||||
|
||||
public boolean isAllowFixingExtension() {
|
||||
return mAllowFixingExtension;
|
||||
}
|
||||
|
||||
public void setAllowFixingExtension(boolean allowFixingExtension) {
|
||||
mAllowFixingExtension = allowFixingExtension;
|
||||
}
|
||||
|
||||
public boolean isUseProxy() {
|
||||
return mUseProxy;
|
||||
}
|
||||
|
||||
public void setUseProxy(boolean useProxy) {
|
||||
mUseProxy = useProxy;
|
||||
}
|
||||
}
|
||||
|
||||
private class DownloadHelper implements RequestHelper {
|
||||
|
||||
private static final String DOWNLOAD_EXTENSION = ".download";
|
||||
|
||||
private final String mUrl;
|
||||
private final File mDir;
|
||||
private String mFileName;
|
||||
private @NonNull final String mUrl;
|
||||
private @NonNull final File mDir;
|
||||
private @NonNull String mFilename;
|
||||
private File mFile;
|
||||
private File mTempFile;
|
||||
private final boolean mIsProxy;
|
||||
private final DownloadControlor mControlor;
|
||||
private final OnDownloadListener mListener;
|
||||
private @NonNull DownloadOption mOption;
|
||||
private @Nullable final DownloadControlor mControlor;
|
||||
private @Nullable final OnDownloadListener mListener;
|
||||
private int mContentLength;
|
||||
private int mReceivedSize;
|
||||
|
||||
public DownloadHelper(String url, File dir, String fileName, boolean isProxy,
|
||||
DownloadControlor controlor, OnDownloadListener listener) {
|
||||
public DownloadHelper(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
mUrl = url;
|
||||
mDir = dir;
|
||||
mFileName = fileName;
|
||||
mIsProxy = isProxy;
|
||||
mFilename = filename;
|
||||
if (option == null) {
|
||||
mOption = new DownloadOption();
|
||||
} else {
|
||||
mOption = option;
|
||||
}
|
||||
mControlor = controlor;
|
||||
mListener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getUrl() throws MalformedURLException {
|
||||
return new URL(mIsProxy? getProxyUrl() : mUrl);
|
||||
return new URL(mOption.isUseProxy() ? getProxyUrl() : mUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -782,7 +857,7 @@ public class HttpHelper {
|
||||
if (mControlor != null && mControlor.isStop())
|
||||
throw new StopRequestException();
|
||||
|
||||
if (mIsProxy) {
|
||||
if (mOption.isUseProxy()) {
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setUseCaches(false);
|
||||
@@ -796,8 +871,10 @@ public class HttpHelper {
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setRequestProperty("Range", "bytes=0-");
|
||||
}
|
||||
if (mListener != null)
|
||||
|
||||
if (mListener != null) {
|
||||
mListener.onDownloadStartConnect();
|
||||
}
|
||||
}
|
||||
|
||||
private int getContentLength(HttpURLConnection conn) {
|
||||
@@ -827,47 +904,98 @@ public class HttpHelper {
|
||||
return contentLength;
|
||||
}
|
||||
|
||||
protected String fixNewExtension(String ext) {
|
||||
return null;
|
||||
public String getSuitableFilename(HttpURLConnection conn) {
|
||||
String contentDisposition = conn.getHeaderField("Content-Disposition");
|
||||
Map<String, String> map = parseMap(contentDisposition);
|
||||
return map.get("filename");
|
||||
}
|
||||
|
||||
protected String onFixName(String newName) {
|
||||
return newName;
|
||||
}
|
||||
|
||||
protected String onFixExtension(String newExtension) {
|
||||
return newExtension;
|
||||
}
|
||||
|
||||
protected String fixFilename(HttpURLConnection conn) {
|
||||
String originalName;
|
||||
String originalExtension;
|
||||
String newName = null;
|
||||
String newExtension = null;
|
||||
String[] temp = new String[2];
|
||||
|
||||
// get originalName and originalExtension
|
||||
Utils.getNameAndExtension(mFilename, temp);
|
||||
originalName = temp[0];
|
||||
originalExtension = temp[1];
|
||||
|
||||
String suitableFilename = getSuitableFilename(conn);
|
||||
if (suitableFilename != null) {
|
||||
Utils.getNameAndExtension(suitableFilename, temp);
|
||||
newName = temp[0];
|
||||
newExtension = temp[1];
|
||||
} else {
|
||||
String mime = getMime(conn);
|
||||
if (mime != null) {
|
||||
MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
|
||||
originalExtension = mimeMap.getExtensionFromMimeType(mime);
|
||||
}
|
||||
}
|
||||
|
||||
if (newName == null) {
|
||||
newName = originalName;
|
||||
}
|
||||
if (mOption.isAllowFixingName()) {
|
||||
newName = onFixName(newName);
|
||||
} else {
|
||||
newName = originalName;
|
||||
}
|
||||
|
||||
if (newExtension == null) {
|
||||
newExtension = originalExtension;
|
||||
}
|
||||
if (mOption.isAllowFixingExtension()) {
|
||||
newExtension = onFixExtension(newExtension);
|
||||
} else {
|
||||
newExtension = originalExtension;
|
||||
}
|
||||
|
||||
String newFilename = newName;
|
||||
if (newExtension != null) {
|
||||
newFilename = newFilename + '.' + newExtension;
|
||||
}
|
||||
|
||||
return newFilename;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Object onAfterConnect(HttpURLConnection conn) throws Exception {
|
||||
// Check stop
|
||||
if (mControlor != null && mControlor.isStop())
|
||||
if (mControlor != null && mControlor.isStop()) {
|
||||
throw new StopRequestException();
|
||||
}
|
||||
|
||||
String contentType = conn.getContentType();
|
||||
int index = contentType.indexOf(';');
|
||||
if (index != -1)
|
||||
contentType = contentType.substring(0, index);
|
||||
String oldFilename = mFilename;
|
||||
|
||||
if (mOption.isAllowFixingName() || mOption.isAllowFixingExtension()) {
|
||||
mFilename = fixFilename(conn);
|
||||
}
|
||||
|
||||
// TODO Should check first
|
||||
if (!oldFilename.equals(mFilename) && mListener != null) {
|
||||
mListener.onUpdateFilename(mFilename);
|
||||
}
|
||||
|
||||
mContentLength = getContentLength(conn);
|
||||
if (mListener != null)
|
||||
mListener.onDownloadStartDownload(mContentLength);
|
||||
|
||||
// Fix extension
|
||||
MimeTypeMap mime = MimeTypeMap.getSingleton();
|
||||
String newExtension = mime.getExtensionFromMimeType(contentType);
|
||||
if (newExtension == null) {
|
||||
index = contentType.lastIndexOf('/');
|
||||
if (index != -1)
|
||||
newExtension = contentType.substring(index + 1);
|
||||
}
|
||||
newExtension = fixNewExtension(newExtension);
|
||||
if (newExtension != null) {
|
||||
index = mFileName.lastIndexOf('.');
|
||||
if (index == -1) {
|
||||
mFileName = mFileName + '.' + newExtension;
|
||||
} else {
|
||||
mFileName = mFileName.substring(0, index) + '.' + newExtension;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure parent exist
|
||||
mDir.mkdirs();
|
||||
mFile = new File(mDir, mFileName);
|
||||
mTempFile = new File(mDir, mFileName + DOWNLOAD_EXTENSION);
|
||||
mFile = new File(mDir, mFilename);
|
||||
mTempFile = new File(mDir, mFilename + DOWNLOAD_EXTENSION);
|
||||
// Transfer
|
||||
transferData(conn.getInputStream(), new FileOutputStream(mTempFile));
|
||||
// Get ok, rename
|
||||
@@ -917,44 +1045,48 @@ public class HttpHelper {
|
||||
throw new UncompletedException("Received size is " + mReceivedSize
|
||||
+ ", but ContentLength is " + mContentLength);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private class DownloadEhImageHelper extends DownloadHelper {
|
||||
|
||||
public DownloadEhImageHelper(String url, File dir, String fileName,
|
||||
boolean isProxy, DownloadControlor controlor,
|
||||
OnDownloadListener listener) {
|
||||
super(url, dir, fileName, isProxy, controlor, listener);
|
||||
public DownloadEhImageHelper(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
super(url, dir, filename, option, controlor, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String fixNewExtension(String ext) {
|
||||
protected String onFixExtension(String ext) {
|
||||
int length = EhUtils.POSSIBLE_IMAGE_EXTENSION_ARRAY.length;
|
||||
int i;
|
||||
for (i = 0; i < length; i++) {
|
||||
if (EhUtils.POSSIBLE_IMAGE_EXTENSION_ARRAY[i].equals(ext))
|
||||
if (EhUtils.POSSIBLE_IMAGE_EXTENSION_ARRAY[i].equals(ext)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i == length)
|
||||
if (i == length) {
|
||||
ext = EhUtils.DEFAULT_IMAGE_EXTENSION;
|
||||
}
|
||||
return ext;
|
||||
}
|
||||
}
|
||||
|
||||
private class DownloadOriginEhImageHelper extends DownloadEhImageHelper {
|
||||
|
||||
public DownloadOriginEhImageHelper(String url, File dir, String fileName,
|
||||
boolean isProxy, DownloadControlor controlor,
|
||||
OnDownloadListener listener) {
|
||||
super(url, dir, fileName, isProxy, controlor, listener);
|
||||
public DownloadOriginEhImageHelper(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
super(url, dir, filename, option, controlor, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object onAfterConnect(HttpURLConnection conn) throws Exception {
|
||||
if (mLastUrl == null)
|
||||
if (mLastUrl == null) {
|
||||
throw new BandwidthExceededException();
|
||||
}
|
||||
|
||||
return super.onAfterConnect(conn);
|
||||
}
|
||||
@@ -1003,7 +1135,7 @@ public class HttpHelper {
|
||||
/**
|
||||
* Post form data, multipart/form-data
|
||||
* @param url
|
||||
* @param datas
|
||||
* @param dataList
|
||||
* @return
|
||||
*/
|
||||
public String postFormData(String url, List<FormData> dataList) {
|
||||
@@ -1019,33 +1151,40 @@ public class HttpHelper {
|
||||
return (Bitmap) requst(new GetImageHelper(url));
|
||||
}
|
||||
|
||||
public String download(String url, File dir, String file, boolean isProxy,
|
||||
DownloadControlor controlor, OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadHelper(url, dir, file, isProxy,
|
||||
controlor, listener));
|
||||
public String download(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadHelper(url, dir, filename,
|
||||
option, controlor, listener));
|
||||
}
|
||||
|
||||
public void downloadInThread(final String url, final File dir,
|
||||
final String file, final boolean isProxy,
|
||||
final DownloadControlor controlor, final OnDownloadListener listener) {
|
||||
public void downloadInThread(@NonNull final String url, @NonNull final File dir,
|
||||
@NonNull final String filename, @Nullable final DownloadOption option,
|
||||
@Nullable final DownloadControlor controlor,
|
||||
@Nullable final OnDownloadListener listener) {
|
||||
new BgThread() {
|
||||
@Override
|
||||
public void run() {
|
||||
download(url, dir, file, isProxy, controlor, listener);
|
||||
download(url, dir, filename, option, controlor, listener);
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
public String downloadEhImage(String url, File dir, String file, boolean isProxy,
|
||||
DownloadControlor controlor, OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadEhImageHelper(url, dir, file, isProxy,
|
||||
controlor, listener));
|
||||
public String downloadEhImage(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadEhImageHelper(url, dir, filename,
|
||||
option, controlor, listener));
|
||||
}
|
||||
|
||||
public String downloadOriginEhImage(String url, File dir, String file, boolean isProxy,
|
||||
DownloadControlor controlor, OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadOriginEhImageHelper(url, dir, file, isProxy,
|
||||
controlor, listener));
|
||||
public String downloadOriginEhImage(@NonNull String url, @NonNull File dir,
|
||||
@NonNull String filename, @Nullable DownloadOption option,
|
||||
@Nullable DownloadControlor controlor,
|
||||
@Nullable OnDownloadListener listener) {
|
||||
return (String) requst(new DownloadOriginEhImageHelper(url, dir, filename,
|
||||
option, controlor, listener));
|
||||
}
|
||||
|
||||
/** Exceptions **/
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hippo.ehviewer.receiver;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
public class RestPatternReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
Config.setPatternProtection("");
|
||||
MaterialToast.showToast(R.string.reset_pattern_protection);
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
@@ -38,6 +35,9 @@ import com.hippo.ehviewer.ui.DownloadActivity;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DownloadService extends Service
|
||||
implements ExDownloader.ListenerForDownload {
|
||||
|
||||
@@ -311,9 +311,6 @@ public class DownloadService extends Service
|
||||
|
||||
mBuilder = new NotificationCompat.Builder(mContext);
|
||||
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
|
||||
Intent intent = new Intent(DownloadService.this,DownloadActivity.class);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
mBuilder.setContentIntent(pendingIntent);
|
||||
mBuilder.setOngoing(true).setAutoCancel(false);
|
||||
|
||||
// Add action
|
||||
@@ -328,6 +325,15 @@ public class DownloadService extends Service
|
||||
mBuilder.addAction(R.drawable.ic_action_close, getString(R.string.stop_all), piStopAll);
|
||||
}
|
||||
|
||||
private void setPendingIntent() {
|
||||
Intent intent = new Intent(DownloadService.this, DownloadActivity.class);
|
||||
intent.setAction(DownloadActivity.ACTION_SPECIFIC_GALLERY);
|
||||
intent.putExtra(DownloadActivity.KEY_SPECIFIC_GALLERY_GID, mCurDownloadInfo.galleryInfo.gid);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0,
|
||||
intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
mBuilder.setContentIntent(pendingIntent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart(int gid) {
|
||||
if (mCurDownloadInfo == null)
|
||||
@@ -337,6 +343,7 @@ public class DownloadService extends Service
|
||||
mCurDownloadInfo.total = -1;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.start_download) + " " + gid)
|
||||
.setContentText(null)
|
||||
@@ -355,6 +362,7 @@ public class DownloadService extends Service
|
||||
mCurDownloadInfo.total = sum;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(null)
|
||||
@@ -375,6 +383,7 @@ public class DownloadService extends Service
|
||||
mCurDownloadInfo.total = totalSize;
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(mSpeedStr)
|
||||
@@ -398,6 +407,7 @@ public class DownloadService extends Service
|
||||
mSpeedStr = Utils.sizeToString(speed) + "/S";
|
||||
|
||||
ensureNotification();
|
||||
setPendingIntent();
|
||||
|
||||
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
|
||||
.setContentText(mSpeedStr)
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.ui;
|
||||
import android.app.Activity;
|
||||
|
||||
import com.google.analytics.tracking.android.EasyTracker;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
@@ -31,6 +32,13 @@ public abstract class AbsActivity extends Activity {
|
||||
Ui.adjustOrientation(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
|
||||
ImageCache.getImageCache(this).flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
|
||||
@@ -20,7 +20,7 @@ import android.content.res.Configuration;
|
||||
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
|
||||
public class AbsTranslucentActivity extends AbsActivity {
|
||||
public class AbsTranslucentActivity extends StatsActivity {
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(Configuration newConfig) {
|
||||
|
||||
@@ -16,8 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
@@ -58,8 +56,14 @@ import com.hippo.ehviewer.widget.FitWindowView;
|
||||
import com.hippo.ehviewer.widget.LoadImageView;
|
||||
import com.hippo.ehviewer.windowsanimate.WindowsAnimate;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class DownloadActivity extends AbsTranslucentActivity implements FitWindowView.OnFitSystemWindowsListener {
|
||||
|
||||
public static final String ACTION_SPECIFIC_GALLERY = "com.hippo.ehviewer.ui.DownloadActivity.SPECIFIC_GALLERY";
|
||||
|
||||
public static final String KEY_SPECIFIC_GALLERY_GID = "specific_gallery_gid";
|
||||
|
||||
private AppContext mAppContext;
|
||||
private WindowsAnimate mWindowsAnimate;
|
||||
private int mThemeColor;
|
||||
@@ -121,6 +125,20 @@ public class DownloadActivity extends AbsTranslucentActivity implements FitWindo
|
||||
mThemeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(mThemeColor));
|
||||
Ui.colorStatusBarL(this, mThemeColor);
|
||||
|
||||
// Go to specific gid
|
||||
Intent intent = getIntent();
|
||||
if (intent != null && ACTION_SPECIFIC_GALLERY.equals(intent.getAction())) {
|
||||
int specificGid = intent.getIntExtra(KEY_SPECIFIC_GALLERY_GID, -1);
|
||||
if (specificGid != -1) {
|
||||
int size = mDownloads.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (mDownloads.get(i).galleryInfo.gid == specificGid) {
|
||||
mList.setSelection(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternView;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class EnterPatternActivity extends AbsActivity {
|
||||
|
||||
private static final String KEY_LAST_BAD_PATTERN_RETRY = "last_bad_pattern_retry";
|
||||
|
||||
private static final int MAX_RETRY_TIMES = 5;
|
||||
|
||||
private int mRetryTimes = 0;
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_enter_pattern);
|
||||
|
||||
// Set random color
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
// Can't try if bad retry happened in 10 mins
|
||||
long lastBadRetry = Config.getLong(KEY_LAST_BAD_PATTERN_RETRY, 0);
|
||||
if (System.currentTimeMillis() - lastBadRetry < 1000 * 60 * 10) {
|
||||
mRetryTimes = 10;
|
||||
}
|
||||
|
||||
final TextView textView = (TextView) findViewById(R.id.text);
|
||||
LockPatternView patternView = (LockPatternView) findViewById(R.id.pattern_view);
|
||||
patternView.setOnPatternListener(new LockPatternView.OnPatternListener() {
|
||||
@Override
|
||||
public void onPatternStart() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternCleared() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPatternDetected(List<LockPatternView.Cell> pattern) {
|
||||
if (mRetryTimes > MAX_RETRY_TIMES) {
|
||||
textView.setText(R.string.no_more_retries);
|
||||
Config.setLong(KEY_LAST_BAD_PATTERN_RETRY, System.currentTimeMillis());
|
||||
} else {
|
||||
String enterPatter = LockPatternUtils.patternToString(pattern);
|
||||
if (enterPatter.equals(Config.getPatternProtection())) {
|
||||
setResult(RESULT_OK);
|
||||
finish();
|
||||
} else {
|
||||
textView.setText(R.string.error_pattern);
|
||||
}
|
||||
}
|
||||
mRetryTimes++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.ActionableToastBar;
|
||||
import com.hippo.ehviewer.widget.ActionableToastBar.ActionClickedListener;
|
||||
@@ -127,14 +127,14 @@ public class FavouriteActivity extends AbsTranslucentActivity
|
||||
private void initLocalFavorite() {
|
||||
mGalleryListView.setEnabledHeader(false);
|
||||
mGalleryListView.setEnabledFooter(false);
|
||||
setTitle(Favorite.FAVORITE_TITLES[mMenuIndex]);
|
||||
setTitle(FavoriteHelper.FAVORITE_TITLES[mMenuIndex]);
|
||||
mGalleryListView.refresh();
|
||||
}
|
||||
|
||||
private void initFavorite() {
|
||||
mGalleryListView.setEnabledHeader(true);
|
||||
mGalleryListView.setEnabledFooter(true);
|
||||
setTitle(Favorite.FAVORITE_TITLES[mMenuIndex]);
|
||||
setTitle(FavoriteHelper.FAVORITE_TITLES[mMenuIndex]);
|
||||
mGalleryListView.refresh();
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ public class FavouriteActivity extends AbsTranslucentActivity
|
||||
if (convertView == null)
|
||||
convertView = LayoutInflater.from(FavouriteActivity.this).inflate(R.layout.menu_item, parent, false);
|
||||
TextView tv = (TextView)convertView;
|
||||
tv.setText(Favorite.FAVORITE_TITLES[position]);
|
||||
tv.setText(FavoriteHelper.FAVORITE_TITLES[position]);
|
||||
if (position == 0) {
|
||||
Drawable dr = mResources.getDrawable(R.drawable.ic_setting_panda_light);
|
||||
dr.setBounds(0, 0, Ui.dp2pix(36), Ui.dp2pix(36));
|
||||
@@ -236,7 +236,7 @@ public class FavouriteActivity extends AbsTranslucentActivity
|
||||
return;
|
||||
|
||||
mMenuIndex = position;
|
||||
setTitle(Favorite.FAVORITE_TITLES[mMenuIndex]);
|
||||
setTitle(FavoriteHelper.FAVORITE_TITLES[mMenuIndex]);
|
||||
if (mMenuIndex == 0)
|
||||
initLocalFavorite();
|
||||
else
|
||||
@@ -417,7 +417,7 @@ public class FavouriteActivity extends AbsTranslucentActivity
|
||||
|
||||
private AlertDialog createMoveDialog(final ActionMode mode) {
|
||||
return new MaterialAlertDialog.Builder(this).setTitle(R.string.where_to_move)
|
||||
.setItems(Favorite.FAVORITE_TITLES, new MaterialAlertDialog.OnClickListener() {
|
||||
.setItems(FavoriteHelper.FAVORITE_TITLES, new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int position) {
|
||||
if (mMenuIndex == position) {
|
||||
|
||||
@@ -16,8 +16,6 @@
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Dialog;
|
||||
import android.content.Intent;
|
||||
@@ -25,6 +23,8 @@ import android.content.res.Configuration;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
@@ -48,16 +48,19 @@ import com.hippo.ehviewer.gallery.ui.GLRootView;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.FullScreenHelper;
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.Messenger;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.widget.ColorView;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SlidingLayout;
|
||||
|
||||
public class GalleryActivity extends AbsActivity
|
||||
import java.io.File;
|
||||
|
||||
public class GalleryActivity extends StatsActivity
|
||||
implements GalleryView.GalleryViewListener, SeekBar.OnSeekBarChangeListener,
|
||||
FullScreenHelper.OnFullScreenBrokenListener, CompoundButton.OnCheckedChangeListener,
|
||||
SlidingLayout.OnChildHideListener, AdapterView.OnItemSelectedListener,
|
||||
View.OnClickListener, Utils.OnCopyOverListener {
|
||||
View.OnClickListener, Utils.OnCopyOverListener, Messenger.Receiver {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private final static String TAG = GalleryActivity.class.getSimpleName();
|
||||
@@ -110,6 +113,8 @@ public class GalleryActivity extends AbsActivity
|
||||
|
||||
private Dialog mSendDialog;
|
||||
|
||||
private boolean mVolumePage;
|
||||
|
||||
private final Runnable mFullScreenTask = new Runnable() {
|
||||
@Override public void run() {
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
@@ -126,8 +131,7 @@ public class GalleryActivity extends AbsActivity
|
||||
|
||||
@Override
|
||||
public void onCopyOver(boolean success, File src, File dst) {
|
||||
MaterialToast.showToast(success ? String.format(getString(R.string.save_successful), dst.getPath())
|
||||
: getString(R.string.save_failed));
|
||||
MaterialToast.showToast(success ? String.format(getString(R.string.save_successful), dst.getPath()) : getString(R.string.save_failed));
|
||||
if (success)
|
||||
Config.setString(KEY_LAST_SAVE_IMAGE_FILE_PATH, dst.getParent());
|
||||
}
|
||||
@@ -267,6 +271,9 @@ public class GalleryActivity extends AbsActivity
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.gl_root_group);
|
||||
|
||||
mVolumePage = Config.getVolumePage();
|
||||
Messenger.getInstance().register(Config.MESSENGER_ID_VOLUME_PAGE, this);
|
||||
|
||||
mFullScreenHelper = new FullScreenHelper(this);
|
||||
mFullScreenHelper.setOnFullScreenBrokenListener(this);
|
||||
mFullScreenHelper.setFullScreen(true);
|
||||
@@ -298,7 +305,7 @@ public class GalleryActivity extends AbsActivity
|
||||
mSendDialog = createSendDialog();
|
||||
|
||||
Intent intent = getIntent();
|
||||
mGi = (GalleryInfo) intent.getParcelableExtra(KEY_GALLERY_INFO);
|
||||
mGi = intent.getParcelableExtra(KEY_GALLERY_INFO);
|
||||
|
||||
if (mGi == null) {
|
||||
// Get error force finish
|
||||
@@ -382,6 +389,8 @@ public class GalleryActivity extends AbsActivity
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
|
||||
Messenger.getInstance().unregister(Config.MESSENGER_ID_VOLUME_PAGE, this);
|
||||
|
||||
if (mImageSet != null)
|
||||
mImageSet.free();
|
||||
if (mGalleryView != null)
|
||||
@@ -416,6 +425,42 @@ public class GalleryActivity extends AbsActivity
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKeyDown (int keyCode, @NonNull KeyEvent event) {
|
||||
switch (keyCode) {
|
||||
case KeyEvent.KEYCODE_VOLUME_DOWN:
|
||||
if (mVolumePage) {
|
||||
mGalleryView.showNextPage();
|
||||
return true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
case KeyEvent.KEYCODE_VOLUME_UP:
|
||||
if (mVolumePage) {
|
||||
mGalleryView.showPreviousPage();
|
||||
return true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT:
|
||||
case KeyEvent.KEYCODE_PAGE_UP:
|
||||
mGalleryView.showPreviousPage();
|
||||
return true;
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT:
|
||||
case KeyEvent.KEYCODE_PAGE_DOWN:
|
||||
mGalleryView.showNextPage();
|
||||
return true;
|
||||
}
|
||||
return super.onKeyDown(keyCode, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceive(int id, Object obj) {
|
||||
if (obj instanceof Boolean) {
|
||||
mVolumePage = (Boolean) obj;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTapCenter() {
|
||||
if (!mConfigSliding.isShowing()) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import android.animation.Animator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.AlertDialog;
|
||||
import android.app.Dialog;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Context;
|
||||
@@ -27,15 +28,17 @@ import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.text.Html;
|
||||
import android.util.Pair;
|
||||
import android.view.ContextThemeWrapper;
|
||||
import android.view.Gravity;
|
||||
import android.view.LayoutInflater;
|
||||
@@ -45,9 +48,12 @@ import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.animation.AlphaAnimation;
|
||||
import android.view.animation.Animation;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ListView;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextSwitcher;
|
||||
import android.widget.TextView;
|
||||
@@ -75,13 +81,15 @@ import com.hippo.ehviewer.drawable.OvalDrawable;
|
||||
import com.hippo.ehviewer.effect.ripple.RippleSalon;
|
||||
import com.hippo.ehviewer.ehclient.DetailUrlParser;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.cache.AnyCache;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
|
||||
import com.hippo.ehviewer.miscellaneous.Downloader;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.service.DownloadService;
|
||||
import com.hippo.ehviewer.util.AppConfig;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Constants;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.AutoWrapLayout;
|
||||
import com.hippo.ehviewer.widget.FitWindowView;
|
||||
@@ -99,6 +107,7 @@ import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.widget.recyclerview.LinearDividerItemDecoration;
|
||||
import com.hippo.ehviewer.windowsanimate.WindowsAnimate;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@@ -111,17 +120,25 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
ProgressiveRatingBar.OnUserRateListener, PreviewList.PreviewHolder,
|
||||
View.OnLayoutChangeListener, EasyRecyclerView.OnItemClickListener,
|
||||
EasyRecyclerView.OnItemLongClickListener, RefreshTextView.OnRefreshListener,
|
||||
FitWindowView.OnFitSystemWindowsListener {
|
||||
FitWindowView.OnFitSystemWindowsListener, FavoriteHelper.OnAddToFavoriteListener {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String TAG = GalleryDetailActivity.class.getSimpleName();
|
||||
|
||||
public static final String KEY_G_INFO = "gallery_info";
|
||||
|
||||
private static final int FAVORITE_NONE = 0x0;
|
||||
private static final int FAVORITE_LOCAL = 0x1;
|
||||
private static final int FAVORITE_ACCOUNT = 0x2;
|
||||
|
||||
private static int sGid;
|
||||
private static String sToken;
|
||||
|
||||
private AppContext mAppContext;
|
||||
private Resources mResources;
|
||||
private EhClient mClient;
|
||||
private WindowsAnimate mWindowsAnimate;
|
||||
private Data mData;
|
||||
private GalleryInfo mGalleryInfo;
|
||||
|
||||
private int mRunningAnimateNum = 0;
|
||||
@@ -137,10 +154,12 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
private SuperButton mReadButton;
|
||||
private TextView mCategory;
|
||||
private TextView mMoreOfUploader;
|
||||
private TextView mTorrent;
|
||||
private TextView mSimilar;
|
||||
private TextSwitcher mRatingText;
|
||||
private ProgressiveRatingBar mRating;
|
||||
private TextView mFavorite;
|
||||
private TextView mShare;
|
||||
private TextView mRate;
|
||||
private TextView mCommentMoreText;
|
||||
private SimpleGridLayout mPreview;
|
||||
@@ -173,6 +192,8 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
private FloatingActionButton mReply;
|
||||
|
||||
private OvalDrawable mCategoryDrawable;
|
||||
private Drawable mFavoriteDrawable;
|
||||
private Drawable mFavoriteOutlineDrawable;
|
||||
private Drawable mRateDrawable;
|
||||
private Drawable mCheckmarkDrawable;
|
||||
|
||||
@@ -187,6 +208,9 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
private String mOldReply;
|
||||
private boolean mReplyPositive;
|
||||
|
||||
private int mFavoriteState = FAVORITE_NONE;
|
||||
private boolean mIsDoingFavorite = false;
|
||||
|
||||
private AlertDialog createGoToDialog() {
|
||||
CharSequence[] items = new CharSequence[((PreviewImpl)mGalleryInfo).getPreviewPageNum()];
|
||||
for (int i = 0; i < items.length; i++)
|
||||
@@ -210,7 +234,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
|
||||
private GalleryInfo handleIntent(Intent intent) {
|
||||
GalleryInfo gi = null;
|
||||
if (intent.getAction() == "android.intent.action.VIEW") {
|
||||
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
|
||||
// Start from url
|
||||
DetailUrlParser parser = new DetailUrlParser();
|
||||
if (parser.parser(intent.getData().getPath())) {
|
||||
@@ -229,7 +253,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
} else {
|
||||
//
|
||||
gi = (GalleryInfo)(intent.getParcelableExtra(KEY_G_INFO));
|
||||
gi = intent.getParcelableExtra(KEY_G_INFO);
|
||||
if (gi != null) {
|
||||
// Add history
|
||||
Data.getInstance().addHistory(gi, Data.BROWSE);
|
||||
@@ -271,10 +295,17 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
}*/
|
||||
|
||||
public static String getCurrentGallery() {
|
||||
return sGid + "/" + sToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
mWindowsAnimate.free();
|
||||
|
||||
sGid = 0;
|
||||
sToken = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -286,6 +317,9 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
// If no GalleryInfo pass, just finish
|
||||
finish();
|
||||
|
||||
sGid = mGalleryInfo.gid;
|
||||
sToken = mGalleryInfo.token;
|
||||
|
||||
setContentView(R.layout.gallery_detail);
|
||||
setTitle(String.valueOf(mGalleryInfo.gid));
|
||||
|
||||
@@ -293,6 +327,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
mClient = EhClient.getInstance();
|
||||
mWindowsAnimate = new WindowsAnimate();
|
||||
mWindowsAnimate.init(this);
|
||||
mData = Data.getInstance();
|
||||
|
||||
mResources = getResources();
|
||||
|
||||
@@ -331,10 +366,12 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
mReadButton = (SuperButton) findViewById(R.id.read);
|
||||
mCategory = (TextView) findViewById(R.id.category);
|
||||
mMoreOfUploader = (TextView) findViewById(R.id.more_of_uploader);
|
||||
mTorrent = (TextView) findViewById(R.id.torrent);
|
||||
mSimilar = (TextView) findViewById(R.id.similar);
|
||||
mRatingText = (TextSwitcher) mDetailRate.findViewById(R.id.rating_text);
|
||||
mRating = (ProgressiveRatingBar) mDetailRate.findViewById(R.id.rating);
|
||||
mFavorite = (TextView) findViewById(R.id.favorite);
|
||||
mShare = (TextView) findViewById(R.id.share);
|
||||
mRate = (TextView) findViewById(R.id.rate);
|
||||
mCommentMoreText = (TextView) findViewById(R.id.comment_more_text);
|
||||
mPreview = (SimpleGridLayout) findViewById(R.id.preview);
|
||||
@@ -355,12 +392,19 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
Drawable moreOfUploaderDrawable = mResources.getDrawable(R.drawable.ic_more_of_uploader);
|
||||
moreOfUploaderDrawable.setBounds(rect);
|
||||
mMoreOfUploader.setCompoundDrawables(null, moreOfUploaderDrawable, null, null);
|
||||
Drawable torrentDrawable = mResources.getDrawable(R.drawable.ic_torrent);
|
||||
torrentDrawable.setBounds(rect);
|
||||
mTorrent.setCompoundDrawables(null, torrentDrawable, null, null);
|
||||
Drawable similarDrawable = mResources.getDrawable(R.drawable.ic_similar);
|
||||
similarDrawable.setBounds(rect);
|
||||
mSimilar.setCompoundDrawables(null, similarDrawable, null, null);
|
||||
Drawable favoriteDrawable = mResources.getDrawable(R.drawable.ic_favorite);
|
||||
favoriteDrawable.setBounds(rect);
|
||||
mFavorite.setCompoundDrawables(null, favoriteDrawable, null, null);
|
||||
mFavoriteDrawable = mResources.getDrawable(R.drawable.ic_favorite);
|
||||
mFavoriteDrawable.setBounds(rect);
|
||||
mFavoriteOutlineDrawable = mResources.getDrawable(R.drawable.ic_favorite_outline);
|
||||
mFavoriteOutlineDrawable.setBounds(rect);
|
||||
Drawable shareDrawable = mResources.getDrawable(R.drawable.ic_share);
|
||||
shareDrawable.setBounds(rect);
|
||||
mShare.setCompoundDrawables(null, shareDrawable, null, null);
|
||||
mRateDrawable = mResources.getDrawable(R.drawable.ic_rate);
|
||||
mRateDrawable.setBounds(rect);
|
||||
mCheckmarkDrawable = mResources.getDrawable(R.drawable.ic_checkmark);
|
||||
@@ -397,9 +441,11 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
mReadButton.setOnClickListener(this);
|
||||
mCategory.setOnClickListener(this);
|
||||
mMoreOfUploader.setOnClickListener(this);
|
||||
mTorrent.setOnClickListener(this);
|
||||
mSimilar.setOnClickListener(this);
|
||||
mRating.setOnUserRateListener(this);
|
||||
mFavorite.setOnClickListener(this);
|
||||
mShare.setOnClickListener(this);
|
||||
mRate.setOnClickListener(this);
|
||||
mDetailMore.setOnTouchListener(this);
|
||||
mDetailComment.setOnTouchListener(this);
|
||||
@@ -602,6 +648,16 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
}
|
||||
|
||||
private void updateFavoriteButton() {
|
||||
if (mFavoriteState == FAVORITE_NONE) {
|
||||
mFavorite.setText(R.string.add_to_favorites);
|
||||
mFavorite.setCompoundDrawables(null, mFavoriteOutlineDrawable, null, null);
|
||||
} else {
|
||||
mFavorite.setText(R.string.remove_from_favorites);
|
||||
mFavorite.setCompoundDrawables(null, mFavoriteDrawable, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GalleryDetail
|
||||
* LofiGalleryDetail
|
||||
@@ -634,17 +690,31 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
mDetailActions.setVisibility(View.VISIBLE);
|
||||
mCategory.setText(Ui.getCategoryText(mGalleryInfo.category));
|
||||
mCategoryDrawable.setColor(Ui.getCategoryColor(mGalleryInfo.category));
|
||||
mTorrent.setVisibility(View.GONE);
|
||||
|
||||
// Detail
|
||||
mDividerAM.setVisibility(View.VISIBLE);
|
||||
mDetailMore.setVisibility(View.VISIBLE);
|
||||
|
||||
// Favorite
|
||||
if (mData.containsLocalFavourite(mGalleryInfo.gid)) {
|
||||
mFavoriteState |= FAVORITE_LOCAL;
|
||||
}
|
||||
|
||||
if (mGalleryInfo instanceof GalleryDetail) {
|
||||
GalleryDetail galleryDetail = (GalleryDetail)mGalleryInfo;
|
||||
((TextView)mDetailMore.findViewById(R.id.language)).setText(
|
||||
getString(R.string.language) + ": " + galleryDetail.language);
|
||||
((TextView)mDetailMore.findViewById(R.id.posted)).setText(galleryDetail.posted);
|
||||
((TextView)mDetailMore.findViewById(R.id.pages)).setText(
|
||||
getString(R.string.pages) + ": " + String.valueOf(galleryDetail.pages));
|
||||
|
||||
if (galleryDetail.isFavorite) {
|
||||
mFavoriteState |= FAVORITE_ACCOUNT;
|
||||
}
|
||||
|
||||
if (galleryDetail.torrents != null && galleryDetail.torrents.length > 0) {
|
||||
mTorrent.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
((TextView)mDetailMore.findViewById(R.id.language)).setText(getString(R.string.language) + ": " + galleryDetail.language);
|
||||
((TextView) mDetailMore.findViewById(R.id.posted)).setText(galleryDetail.posted);
|
||||
((TextView) mDetailMore.findViewById(R.id.pages)).setText(getString(R.string.pages) + ": " + String.valueOf(galleryDetail.pages));
|
||||
((TextView)mDetailMore.findViewById(R.id.size)).setText(
|
||||
getString(R.string.size) + ": " + galleryDetail.size);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
@@ -667,9 +737,10 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
((TextView)mMoreDetailScroll.findViewById(R.id.more_detail)).setText(sb.toString());
|
||||
} else if (mGalleryInfo instanceof LofiGalleryDetail) {
|
||||
LofiGalleryDetail lofiGalleryDetail = (LofiGalleryDetail)mGalleryInfo;
|
||||
((TextView)mDetailMore.findViewById(R.id.language)).setVisibility(View.GONE);
|
||||
((TextView)mDetailMore.findViewById(R.id.posted)).setVisibility(View.GONE);
|
||||
((TextView)mDetailMore.findViewById(R.id.pages)).setVisibility(View.GONE);
|
||||
|
||||
(mDetailMore.findViewById(R.id.language)).setVisibility(View.GONE);
|
||||
(mDetailMore.findViewById(R.id.posted)).setVisibility(View.GONE);
|
||||
(mDetailMore.findViewById(R.id.pages)).setVisibility(View.GONE);
|
||||
((TextView)mDetailMore.findViewById(R.id.size)).setText(lofiGalleryDetail.posted);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("gid: ").append(lofiGalleryDetail.gid).append("\n\n")
|
||||
@@ -686,6 +757,8 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
// TODO
|
||||
}
|
||||
|
||||
updateFavoriteButton();
|
||||
|
||||
// Rate
|
||||
mDividerMR.setVisibility(View.VISIBLE);
|
||||
mDetailRate.setVisibility(View.VISIBLE);
|
||||
@@ -863,6 +936,8 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
intent.putExtra(GalleryListActivity.KEY_MODE, ListUrls.MODE_UPLOADER);
|
||||
intent.putExtra(GalleryListActivity.KEY_UPLOADER, mGalleryInfo.uploader);
|
||||
startActivity(intent);
|
||||
} else if (v == mTorrent) {
|
||||
showTorrentDialog();
|
||||
} else if (v == mSimilar) {
|
||||
Intent intent = new Intent(this, GalleryListActivity.class);
|
||||
intent.setAction(GalleryListActivity.ACTION_GALLERY_LIST);
|
||||
@@ -871,7 +946,38 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
intent.putExtra(GalleryListActivity.KEY_IMAGE_URL, mGalleryInfo.thumb);
|
||||
startActivity(intent);
|
||||
} else if (v == mFavorite) {
|
||||
Favorite.addToFavorite(this, mGalleryInfo);
|
||||
if (!mIsDoingFavorite) {
|
||||
if (mFavoriteState == FAVORITE_NONE) {
|
||||
mIsDoingFavorite = true;
|
||||
FavoriteHelper.addToFavorite(this, mGalleryInfo, this);
|
||||
} else {
|
||||
if ((mFavoriteState & FAVORITE_LOCAL) != 0) {
|
||||
mData.deleteLocalFavourite(mGalleryInfo.gid);
|
||||
mFavoriteState &= ~FAVORITE_LOCAL;
|
||||
|
||||
updateFavoriteButton();
|
||||
}
|
||||
if ((mFavoriteState & FAVORITE_ACCOUNT) != 0) {
|
||||
mIsDoingFavorite = true;
|
||||
mClient.addToFavorite(mGalleryInfo.gid, mGalleryInfo.token, -1, null, new EhClient.OnAddToFavoriteListener() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
mIsDoingFavorite = false;
|
||||
mFavoriteState &= ~FAVORITE_ACCOUNT;
|
||||
updateFavoriteButton();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
mIsDoingFavorite = false;
|
||||
updateFavoriteButton();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (v == mShare) {
|
||||
ActivityHelper.share(this, EhClient.getDetailUrl(mGalleryInfo.gid, mGalleryInfo.token));
|
||||
} else if (v == mRate) {
|
||||
if (isCheckmark) {
|
||||
int rating = (int)(mRating.getRating() * 2 + 0.5);
|
||||
@@ -1010,6 +1116,88 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
}
|
||||
|
||||
private Dialog mTorrentDialog = null;
|
||||
private View mTorrentProgress = null;
|
||||
private ListView mTorrentListView = null;
|
||||
|
||||
public void showTorrentDialog() {
|
||||
if (mTorrentDialog != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@SuppressLint("InflateParams")
|
||||
View view = getLayoutInflater().inflate(R.layout.dialog_torrent, null);
|
||||
mTorrentProgress = view.findViewById(R.id.progress);
|
||||
mTorrentListView = (ListView) view.findViewById(R.id.list);
|
||||
|
||||
mTorrentDialog = new MaterialAlertDialog.Builder(this)
|
||||
.setTitle(R.string.torrent)
|
||||
.setView(view, false)
|
||||
.setNegativeButton(android.R.string.cancel)
|
||||
.setOnDismissListener(new MaterialAlertDialog.OnDismissListener() {
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
mTorrentDialog = null;
|
||||
mTorrentProgress = null;
|
||||
mTorrentListView = null;
|
||||
}
|
||||
}).show();
|
||||
|
||||
final GalleryDetail galleryDetail = (GalleryDetail) mGalleryInfo;
|
||||
mClient.getTorrent(galleryDetail.torrentUrl, galleryDetail.torrents, new EhClient.OnGetTorrentListener() {
|
||||
@Override
|
||||
public void onSuccess(@NonNull Pair<String, String>[] torrents) {
|
||||
galleryDetail.torrents = torrents;
|
||||
|
||||
if (mTorrentProgress != null && mTorrentListView != null) {
|
||||
mTorrentProgress.setVisibility(View.GONE);
|
||||
mTorrentListView.setVisibility(View.VISIBLE);
|
||||
|
||||
int length = torrents.length;
|
||||
String[] data = new String[torrents.length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
data[i] = torrents[i].second;
|
||||
}
|
||||
mTorrentListView.setAdapter(new ArrayAdapter<>(
|
||||
ViewUtils.sContextThemeWrapper,
|
||||
R.layout.select_dialog_item,
|
||||
data));
|
||||
mTorrentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
|
||||
if (mTorrentDialog != null) {
|
||||
mTorrentDialog.dismiss();
|
||||
}
|
||||
|
||||
File dir = AppConfig.getTorrentDir();
|
||||
if (dir == null) {
|
||||
MaterialToast.showToast("Can't storage device"); // TODO
|
||||
return;
|
||||
}
|
||||
|
||||
final String url = galleryDetail.torrents[position].first;
|
||||
String name = galleryDetail.torrents[position].second;
|
||||
Downloader d = new Downloader(
|
||||
GalleryDetailActivity.this,
|
||||
url,
|
||||
dir, Utils.standardizeFilename(name + ".torrent")); // Torrent will be updated
|
||||
d.startDownload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(String eMsg) {
|
||||
if (mTorrentDialog != null) {
|
||||
mTorrentDialog.dismiss();
|
||||
}
|
||||
|
||||
MaterialToast.showToast(eMsg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLayoutChange(View v, int left, int top, int right,
|
||||
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
|
||||
@@ -1161,14 +1349,28 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
@Override
|
||||
public void onScrollStateChanged(ResponedScrollView view, int state) {
|
||||
if (view == mDetailScroll) {
|
||||
/*
|
||||
AnyCache<Bitmap> imageCache = ImageCache.getImageCache(this);
|
||||
if (state == ResponedScrollView.SCROLL_START)
|
||||
imageCache.setPauseDiskCache(true);
|
||||
else
|
||||
imageCache.setPauseDiskCache(false);
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(GalleryInfo gi, int slot) {
|
||||
mIsDoingFavorite = false;
|
||||
mFavoriteState |= slot == -1 ? FAVORITE_LOCAL : FAVORITE_ACCOUNT;
|
||||
updateFavoriteButton();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(String eMsg, GalleryInfo gi, int slot) {
|
||||
mIsDoingFavorite = false;
|
||||
}
|
||||
|
||||
private class GDetailGetListener
|
||||
implements EhClient.OnGetGDetailListener {
|
||||
@Override
|
||||
@@ -1262,7 +1464,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
|
||||
}
|
||||
|
||||
private class CommentAdapter extends EasyRecyclerView.FooterAdapter<CommentHolder> {
|
||||
private class CommentAdapter extends RecyclerView.Adapter<CommentHolder> {
|
||||
|
||||
private final LayoutInflater mInflater;
|
||||
|
||||
@@ -1271,14 +1473,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommentHolder onCreateAndBindFooterViewHolder(ViewGroup parent,
|
||||
View footerView) {
|
||||
// No footer
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommentHolder onCreateViewHolderActual(ViewGroup parent,
|
||||
public CommentHolder onCreateViewHolder(ViewGroup parent,
|
||||
int viewType) {
|
||||
View view = mInflater.inflate(R.layout.comments_item, parent, false);
|
||||
RippleSalon.addRipple(view, ColorStateList.valueOf(0x40000000)); // TODO
|
||||
@@ -1286,7 +1481,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolderActual(CommentHolder holder, int position) {
|
||||
public void onBindViewHolder(CommentHolder holder, int position) {
|
||||
final Comment comment = ((GalleryDetail) mGalleryInfo).comments.get(position);
|
||||
|
||||
holder.userView.setText(comment.user);
|
||||
@@ -1295,7 +1490,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCountActual() {
|
||||
public int getItemCount() {
|
||||
if (mGalleryInfo instanceof GalleryDetail) {
|
||||
GalleryDetail galleryDetail = (GalleryDetail)mGalleryInfo;
|
||||
if (galleryDetail.comments == null)
|
||||
@@ -1306,7 +1501,5 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -73,7 +73,7 @@ import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.service.DownloadService;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.DialogUtils;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
@@ -84,6 +84,7 @@ import com.hippo.ehviewer.widget.GalleryListView;
|
||||
import com.hippo.ehviewer.widget.GalleryListView.OnGetListListener;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
import com.hippo.ehviewer.widget.SearchView;
|
||||
import com.hippo.ehviewer.widget.SimpleImageView;
|
||||
import com.hippo.ehviewer.widget.SlidingDrawerLayout;
|
||||
import com.hippo.ehviewer.widget.SuggestionHelper;
|
||||
import com.hippo.ehviewer.widget.SuggestionTextView;
|
||||
@@ -162,7 +163,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
|
||||
private View mUserPanel;
|
||||
private DrawerListView mMenuList;
|
||||
private ImageView mAvatar;
|
||||
private SimpleImageView mAvatar;
|
||||
private TextView mUsernameView;
|
||||
private Button mLoginButton;
|
||||
private Button mRegisterButton;
|
||||
@@ -204,7 +205,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
// private int mListModeThumbHeight;
|
||||
|
||||
private void toRegister() {
|
||||
Uri uri = Uri.parse("http://forums.e-hentai.org/index.php?act=Reg");
|
||||
Uri uri = Uri.parse("https://forums.e-hentai.org/index.php?act=Reg");
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
startActivity(intent);
|
||||
}
|
||||
@@ -550,16 +551,16 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
public boolean onClick(MaterialAlertDialog dialog, int position) {
|
||||
final GalleryInfo gi = mGalleryListView.getGalleryInfo(longClickItemIndex);
|
||||
switch (position) {
|
||||
case 0: // Add favourite item
|
||||
Favorite.addToFavorite(GalleryListActivity.this, gi);
|
||||
break;
|
||||
case 1:
|
||||
Intent it = new Intent(GalleryListActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_ADD);
|
||||
it.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
|
||||
startService(it);
|
||||
MaterialToast.showToast(R.string.toast_add_download);
|
||||
break;
|
||||
case 0: // Add favourite item
|
||||
FavoriteHelper.addToFavorite(GalleryListActivity.this, gi, null);
|
||||
break;
|
||||
case 1:
|
||||
Intent it = new Intent(GalleryListActivity.this, DownloadService.class);
|
||||
it.setAction(DownloadService.ACTION_ADD);
|
||||
it.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
|
||||
startService(it);
|
||||
MaterialToast.showToast(R.string.toast_add_download);
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1027,7 +1028,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
|
||||
mUserPanel = mLeftMenu.findViewById(R.id.user_panel);
|
||||
mMenuList = (DrawerListView) mLeftMenu.findViewById(R.id.list_menu_item_list);
|
||||
mAvatar = (ImageView) mUserPanel.findViewById(R.id.avatar);
|
||||
mAvatar = (SimpleImageView) mUserPanel.findViewById(R.id.avatar);
|
||||
mUsernameView = (TextView) mUserPanel.findViewById(R.id.user);
|
||||
mLoginButton = (Button) mUserPanel.findViewById(R.id.login);
|
||||
mRegisterButton = (Button) mUserPanel.findViewById(R.id.register);
|
||||
@@ -1416,8 +1417,16 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
case R.id.action_add:
|
||||
// TODO
|
||||
if (lus != null) {
|
||||
String suggestionName = null;
|
||||
int mode = lus.getMode();
|
||||
if (mode == ListUrls.MODE_NORMAL || mode == ListUrls.MODE_UPLOADER) {
|
||||
suggestionName = lus.getSearch();
|
||||
} else if (mode == ListUrls.MODE_TAG) {
|
||||
suggestionName = lus.getTag();
|
||||
}
|
||||
View view = ViewUtils.inflateDialogView(R.layout.set_name, false);
|
||||
final EditText et = (EditText) view.findViewById(R.id.set_name_edit);
|
||||
et.setText(suggestionName);
|
||||
new MaterialAlertDialog.Builder(this).setTitle("添加当前状态至快速搜索") // TODO
|
||||
.setView(view, true)
|
||||
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
|
||||
@@ -1470,7 +1479,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
HttpHelper hh = new HttpHelper(GalleryListActivity.this);
|
||||
hh.downloadInThread(url, new File(Config.getDownloadPath()), fileName,
|
||||
false, null, new UpdateHelper.UpdateListener(
|
||||
null, null, new UpdateHelper.UpdateListener(
|
||||
GalleryListActivity.this, fileName));
|
||||
}
|
||||
return true;
|
||||
@@ -1507,7 +1516,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
|
||||
switch (state) {
|
||||
case LOGIN:
|
||||
mAvatar.setImageDrawable(mClient.getAvatar());
|
||||
mAvatar.setDrawable(mClient.getAvatar());
|
||||
mUsernameView.setVisibility(View.GONE);
|
||||
mLoginButton.setVisibility(View.VISIBLE);
|
||||
mRegisterButton.setVisibility(View.VISIBLE);
|
||||
@@ -1515,7 +1524,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
mWaitLogView.setVisibility(View.GONE);
|
||||
break;
|
||||
case LOGOUT:
|
||||
mAvatar.setImageDrawable(mClient.getAvatar());
|
||||
mAvatar.setDrawable(mClient.getAvatar());
|
||||
mUsernameView.setText(mClient.getDisplayname());
|
||||
mUsernameView.setVisibility(View.VISIBLE);
|
||||
mLoginButton.setVisibility(View.GONE);
|
||||
@@ -1524,7 +1533,7 @@ public class GalleryListActivity extends AbsTranslucentActivity implements View.
|
||||
mWaitLogView.setVisibility(View.GONE);
|
||||
break;
|
||||
case WAIT:
|
||||
mAvatar.setImageDrawable(mClient.getAvatar());
|
||||
mAvatar.setDrawable(mClient.getAvatar());
|
||||
mUsernameView.setVisibility(View.GONE);
|
||||
mLoginButton.setVisibility(View.GONE);
|
||||
mRegisterButton.setVisibility(View.GONE);
|
||||
|
||||
@@ -16,15 +16,13 @@
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Dialog;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
@@ -43,6 +41,10 @@ import com.hippo.ehviewer.widget.FitWindowView;
|
||||
import com.hippo.ehviewer.widget.GalleryListView;
|
||||
import com.hippo.ehviewer.widget.GalleryListView.OnGetListListener;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.widget.recyclerview.SwipeToDismissTouchListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HistoryActivity extends AbsTranslucentActivity
|
||||
implements EasyRecyclerView.OnItemClickListener, MaterialAlertDialog.OnClickListener,
|
||||
@@ -175,6 +177,37 @@ public class HistoryActivity extends AbsTranslucentActivity
|
||||
mGalleryListView.setEnabledFooter(false);
|
||||
mGalleryListView.setOnItemClickListener(this);
|
||||
|
||||
SwipeToDismissTouchListener.DismissCallbacks callbacks = new SwipeToDismissTouchListener.DismissCallbacks() {
|
||||
@Override
|
||||
public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) {
|
||||
return SwipeToDismissTouchListener.SwipeDirection.BOTH;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) {
|
||||
for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) {
|
||||
// TODO After delete all show NONE tip
|
||||
int position = data.position;
|
||||
mData.deleteHistory(mGalleryListView.getGalleryInfo(position).gid);
|
||||
mGalleryListView.removeGalleryInfo(position);
|
||||
mGalleryListView.getGalleryAdapter().notifyItemRemoved(data.position);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResetMotion() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTouchDown() {
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
mGalleryListView.addOnItemTouchListener(
|
||||
new SwipeToDismissTouchListener(mGalleryListView.getEasyRecyclerView(), callbacks));
|
||||
|
||||
createFilterDialog();
|
||||
createClearDialog();
|
||||
}
|
||||
@@ -219,7 +252,7 @@ public class HistoryActivity extends AbsTranslucentActivity
|
||||
OnGetListListener listener) {
|
||||
if (url.equals(HISTORY_URL)) {
|
||||
List<GalleryInfo> giList = new ArrayList<GalleryInfo>(mData.getHistory(mFilterMode, true));
|
||||
if (giList == null || giList.size() == 0)
|
||||
if (giList.size() == 0)
|
||||
listener.onSuccess(taskStamp, giList, 0);
|
||||
else
|
||||
listener.onSuccess(taskStamp, giList, 1);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.LockPatternUtils;
|
||||
import com.hippo.ehviewer.widget.LockPatternView;
|
||||
|
||||
public class PatternProtectionActivity extends AbsActivity implements View.OnClickListener{
|
||||
|
||||
private TextView mTextView;
|
||||
private LockPatternView mPatternView;
|
||||
private View mCancel;
|
||||
private View mOK;
|
||||
|
||||
@SuppressWarnings("ConstantConditions")
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_pattern_protection);
|
||||
|
||||
// Set random color
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
// Menu
|
||||
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
|
||||
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
|
||||
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
|
||||
|
||||
mTextView = (TextView) findViewById(R.id.text);
|
||||
mPatternView = (LockPatternView) findViewById(R.id.pattern_view);
|
||||
mCancel = findViewById(R.id.cancel);
|
||||
mOK = findViewById(R.id.ok);
|
||||
|
||||
mOK.setOnClickListener(this);
|
||||
mCancel.setOnClickListener(this);
|
||||
|
||||
String pattern = Config.getPatternProtection();
|
||||
boolean setPattern = LockPatternUtils.isPatternVaild(pattern);
|
||||
Resources resources = getResources();
|
||||
int patternProtectionStateId = setPattern ?
|
||||
R.string.pattern_protection_set : R.string.pattern_protection_not_set;
|
||||
mTextView.setText(resources.getString(patternProtectionStateId) + "\n\n" +
|
||||
getString(R.string.pattern_protection_warning));
|
||||
|
||||
if (setPattern) {
|
||||
mPatternView.setPattern(LockPatternView.DisplayMode.Correct, LockPatternUtils.stringToPattern(pattern));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
finish();
|
||||
return true;
|
||||
}
|
||||
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (v == mOK) {
|
||||
Config.setPatternProtection(mPatternView.getPatternString());
|
||||
finish();
|
||||
} else if (v == mCancel) {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,6 @@
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.os.SystemClock;
|
||||
@@ -27,11 +25,11 @@ import android.widget.ImageView;
|
||||
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.effect.DrawableTransition;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.widget.MaterialToast;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SecretActivity extends AbsActivity implements View.OnClickListener {
|
||||
|
||||
private final long[] mHits = new long[3];
|
||||
@@ -47,9 +45,6 @@ public class SecretActivity extends AbsActivity implements View.OnClickListener
|
||||
return;
|
||||
}
|
||||
|
||||
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
|
||||
Ui.colorStatusBarL(this, themeColor);
|
||||
|
||||
ImageView iv = new ImageView(this);
|
||||
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
|
||||
iv.setImageBitmap(mBmp);
|
||||
|
||||
@@ -57,14 +57,17 @@ import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
|
||||
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ehclient.EhInfo;
|
||||
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
|
||||
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
import com.hippo.ehviewer.preference.ListPreference;
|
||||
import com.hippo.ehviewer.util.AppUtils;
|
||||
import com.hippo.ehviewer.util.BgThread;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Constants;
|
||||
import com.hippo.ehviewer.util.DialogUtils;
|
||||
import com.hippo.ehviewer.util.EhUtils;
|
||||
import com.hippo.ehviewer.util.Favorite;
|
||||
import com.hippo.ehviewer.util.Log;
|
||||
import com.hippo.ehviewer.util.Messenger;
|
||||
import com.hippo.ehviewer.util.Secret;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.Utils;
|
||||
@@ -233,9 +236,9 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
mHAHProxyConfig.setOnPreferenceClickListener(this);
|
||||
|
||||
int i = 0;
|
||||
String[] entrise = new String[Favorite.FAVORITE_TITLES.length + 1];
|
||||
String[] entrise = new String[FavoriteHelper.FAVORITE_TITLES.length + 1];
|
||||
entrise[i++] = getString(R.string.none);
|
||||
for (String str : Favorite.FAVORITE_TITLES)
|
||||
for (String str : FavoriteHelper.FAVORITE_TITLES)
|
||||
entrise[i++] = str;
|
||||
mDefaultFavorite.setEntries(entrise);
|
||||
}
|
||||
@@ -400,11 +403,13 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
}
|
||||
|
||||
public static class ReadFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceClickListener {
|
||||
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
|
||||
|
||||
private static final String KEY_VOLUME_PAGE = "volume_page";
|
||||
private static final String KEY_CUSTOM_CODEC = "custom_codec";
|
||||
private static final String KEY_CLEAN_REDUNDANCY = "clean_redundancy";
|
||||
|
||||
private CheckBoxPreference mVolumePage;
|
||||
private CheckBoxPreference mCustomCodec;
|
||||
private Preference mCleanRedundancy;
|
||||
|
||||
@@ -415,6 +420,8 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
addPreferencesFromResource(R.xml.read_settings);
|
||||
|
||||
mVolumePage = (CheckBoxPreference) findPreference(KEY_VOLUME_PAGE);
|
||||
mVolumePage.setOnPreferenceChangeListener(this);
|
||||
mCustomCodec = (CheckBoxPreference) findPreference(KEY_CUSTOM_CODEC);
|
||||
mCleanRedundancy = findPreference(KEY_CLEAN_REDUNDANCY);
|
||||
mCleanRedundancy.setOnPreferenceClickListener(this);
|
||||
@@ -428,6 +435,17 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
final String key = preference.getKey();
|
||||
switch (key) {
|
||||
case KEY_VOLUME_PAGE:
|
||||
Messenger.getInstance().notify(Config.MESSENGER_ID_VOLUME_PAGE, newValue);
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isInDownloadList(List<DownloadInfo> diList, String filename) {
|
||||
for (DownloadInfo di : diList)
|
||||
if (filename.startsWith(String.valueOf(di.galleryInfo.gid)))
|
||||
@@ -668,11 +686,17 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
}
|
||||
|
||||
public static class AdvancedFragment extends PreferenceFragment implements
|
||||
Preference.OnPreferenceClickListener {
|
||||
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
|
||||
|
||||
private static final String KEY_FIX_DIRNAME = "fix_dirname";
|
||||
private static final String KEY_LOGIN_VIA_COOKIE = "login_via_cookie";
|
||||
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
|
||||
private static final String KEY_SHOW_APPLICATION_STATS = "show_application_stats";
|
||||
|
||||
private Preference mFixDirname;
|
||||
private Preference mLoginViaCookie;
|
||||
private Preference mPatternProtection;
|
||||
private Preference mShowApplicationStats;
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
@@ -681,6 +705,12 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
|
||||
mFixDirname = findPreference(KEY_FIX_DIRNAME);
|
||||
mFixDirname.setOnPreferenceClickListener(this);
|
||||
mLoginViaCookie = findPreference(KEY_LOGIN_VIA_COOKIE);
|
||||
mLoginViaCookie.setOnPreferenceClickListener(this);
|
||||
mPatternProtection = findPreference(KEY_PATTERN_PROTECTION);
|
||||
mPatternProtection.setOnPreferenceClickListener(this);
|
||||
mShowApplicationStats = findPreference(KEY_SHOW_APPLICATION_STATS);
|
||||
mShowApplicationStats.setOnPreferenceChangeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -779,6 +809,42 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
});
|
||||
}
|
||||
}.start();
|
||||
|
||||
} else if (KEY_LOGIN_VIA_COOKIE.equals(key)) {
|
||||
LinearLayout ll = (LinearLayout) ViewUtils.inflateDialogView(R.layout.login_via_cookie, false);
|
||||
final EditText ipbMemberId = (EditText) ll.findViewById(R.id.ipb_member_id);
|
||||
final EditText ipbPassHash = (EditText) ll.findViewById(R.id.ipb_pass_hash);
|
||||
|
||||
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.login_via_cookie_title)
|
||||
.setView(ll, true).setPositiveButton(android.R.string.ok).setNegativeButton(android.R.string.cancel)
|
||||
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
|
||||
@Override
|
||||
public boolean onClick(MaterialAlertDialog dialog, int which) {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
String id = ipbMemberId.getText().toString();
|
||||
String hash = ipbPassHash.getText().toString();
|
||||
EhInfo ehInfo = EhInfo.getInstance(getActivity());
|
||||
ehInfo.setCookie("ipb_member_id=" + id + "; ipb_pass_hash=" + hash);
|
||||
ehInfo.login("User", "User");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}).show();
|
||||
} else if (KEY_PATTERN_PROTECTION.equals(key)) {
|
||||
Intent intent = new Intent(getActivity(), PatternProtectionActivity.class);
|
||||
getActivity().startActivity(intent);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
final String key = preference.getKey();
|
||||
if (KEY_SHOW_APPLICATION_STATS.equals(key)) {
|
||||
|
||||
Log.d("TAG","KEY_SHOW_APPLICATION_STATS");
|
||||
|
||||
Messenger.getInstance().notify(Constants.MESSENGER_ID_SHOW_APP_STATUS, newValue);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -865,8 +931,7 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
}
|
||||
|
||||
} else if (KEY_AUTHOR.equals(key)) {
|
||||
AppUtils.sendEmail(getActivity(), "ehviewersu@gmail.com",
|
||||
"About EhViewer", null);
|
||||
ActivityHelper.sendEmail(getActivity(), "ehviewersu@gmail.com", "About EhViewer", null);
|
||||
|
||||
} else if (KEY_TWITTER.equals(key)) {
|
||||
new MaterialAlertDialog.Builder(getActivity())
|
||||
@@ -937,7 +1002,7 @@ public class SettingsActivity extends AbsPreferenceActivity {
|
||||
if (which == MaterialAlertDialog.POSITIVE) {
|
||||
HttpHelper hh = new HttpHelper(getActivity());
|
||||
hh.downloadInThread(url, new File(Config.getDownloadPath()),
|
||||
fileName, false, null, new UpdateHelper.UpdateListener(
|
||||
fileName, null, null, new UpdateHelper.UpdateListener(
|
||||
getActivity(), fileName));
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.ui;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.res.Resources;
|
||||
import android.os.Bundle;
|
||||
import android.os.Debug;
|
||||
import android.os.Handler;
|
||||
import android.view.Gravity;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Constants;
|
||||
import com.hippo.ehviewer.util.Messenger;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public abstract class StatsActivity extends AbsActivity {
|
||||
|
||||
private static final int DEFAULT_MESSAGE_SIZE = 128;
|
||||
private static final long STATS_CLOCK_INTERVAL_MS = 1000;
|
||||
private static final int BYTES_IN_MEGABYTE = 1024 * 1024;
|
||||
|
||||
private TextView mStatsTextView;
|
||||
private boolean mShowStats;
|
||||
private Runnable mStatsClockTickRunnable;
|
||||
private Handler mHandler;
|
||||
|
||||
private Messenger.Receiver mReceiver = new Messenger.Receiver() {
|
||||
@Override
|
||||
public void onReceive(int id, Object obj) {
|
||||
if (obj instanceof Boolean) {
|
||||
boolean showStats = (Boolean) obj;
|
||||
if (mShowStats != showStats) {
|
||||
mShowStats = showStats;
|
||||
ViewGroup vg = (ViewGroup) getWindow().getDecorView();
|
||||
if (showStats) {
|
||||
vg.addView(mStatsTextView, generateLayoutParams());
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
} else {
|
||||
vg.removeView(mStatsTextView);
|
||||
cancelNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@SuppressLint("RtlHardcoded")
|
||||
private ViewGroup.LayoutParams generateLayoutParams() {
|
||||
Resources resources = getResources();
|
||||
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.gravity = Gravity.TOP | Gravity.RIGHT;
|
||||
lp.topMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_top);
|
||||
lp.rightMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_right);
|
||||
return lp;
|
||||
}
|
||||
|
||||
private boolean isShowStats() {
|
||||
return Config.getShowApplicationStats();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
mStatsTextView = new TextView(this);
|
||||
mHandler = AppHandler.getInstance();
|
||||
mStatsClockTickRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
}
|
||||
};
|
||||
Messenger.getInstance().register(
|
||||
Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
|
||||
|
||||
if (isShowStats()) {
|
||||
mShowStats = true;
|
||||
((ViewGroup) getWindow().getDecorView()).addView(mStatsTextView,
|
||||
generateLayoutParams());
|
||||
} else {
|
||||
mShowStats = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
Messenger.getInstance().unregister(Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
if (mShowStats) {
|
||||
updateStats();
|
||||
scheduleNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
|
||||
if (mShowStats) {
|
||||
cancelNextStatsClockTick();
|
||||
}
|
||||
}
|
||||
|
||||
private void scheduleNextStatsClockTick() {
|
||||
mHandler.postDelayed(mStatsClockTickRunnable, STATS_CLOCK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private void cancelNextStatsClockTick() {
|
||||
mHandler.removeCallbacks(mStatsClockTickRunnable);
|
||||
}
|
||||
|
||||
private void updateStats() {
|
||||
final Runtime runtime = Runtime.getRuntime();
|
||||
final long heapMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
final StringBuilder sb = new StringBuilder(DEFAULT_MESSAGE_SIZE);
|
||||
appendSize(sb, "Java heap size: ", heapMemory, "\n");
|
||||
appendSize(sb, "Native heap size: ", Debug.getNativeHeapAllocatedSize(), "\n");
|
||||
mStatsTextView.setText(sb.toString());
|
||||
}
|
||||
|
||||
private static void appendSize(StringBuilder sb, String prefix, long bytes, String suffix) {
|
||||
String value = String.format(Locale.getDefault(), "%.2f", (float) bytes / BYTES_IN_MEGABYTE);
|
||||
appendValue(sb, prefix, value + " MB", suffix);
|
||||
}
|
||||
|
||||
private static void appendValue(StringBuilder sb, String prefix, String value, String suffix) {
|
||||
sb.append(prefix).append(value).append(suffix);
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,8 @@ public class WebViewLoginActivity extends AbsActivity {
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
CookieManager.getInstance().removeAllCookie();
|
||||
WebView wv = new WebView(this);
|
||||
CookieManager.getInstance().removeAllCookie();
|
||||
wv.getSettings().setJavaScriptEnabled(true);
|
||||
wv.setWebViewClient(new LoginWebViewClient());
|
||||
wv.loadUrl(EhClient.LOGIN_URL);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import android.os.Environment;
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Something about this app
|
||||
*/
|
||||
public final class AppConfig {
|
||||
|
||||
private static final String APP_DIRNAME = "EhViewer";
|
||||
private static final String CRASH_DIRNAME = "crash";
|
||||
private static final String DOWNLOAD_DIRNAME = "download";
|
||||
private static final String TORRENT_DIRNAME = "torrent";
|
||||
|
||||
public static @Nullable File getAppDir() {
|
||||
if (Environment.getExternalStorageState()
|
||||
.equals(Environment.MEDIA_MOUNTED)) {
|
||||
return new File(Environment.getExternalStorageDirectory(), APP_DIRNAME);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable File getFileInAppDir(String filename) {
|
||||
File appFolder = getAppDir();
|
||||
if (appFolder != null) {
|
||||
return new File(appFolder, filename);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable File getCrashDir() {
|
||||
return getFileInAppDir(CRASH_DIRNAME);
|
||||
}
|
||||
|
||||
public static @Nullable File getDownloadDir() {
|
||||
return getFileInAppDir(DOWNLOAD_DIRNAME);
|
||||
}
|
||||
|
||||
public static @Nullable File getTorrentDir() {
|
||||
return getFileInAppDir(TORRENT_DIRNAME);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,14 @@ public final class Config {
|
||||
|
||||
private static SharedPreferences mConfigPre;
|
||||
|
||||
public static final int MESSENGER_ID_VOLUME_PAGE;
|
||||
|
||||
static {
|
||||
Messenger messenger = Messenger.getInstance();
|
||||
MESSENGER_ID_VOLUME_PAGE = messenger.newId();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Init Config
|
||||
*
|
||||
@@ -87,6 +95,14 @@ public final class Config {
|
||||
mConfigPre.edit().putInt(key, value).apply();
|
||||
}
|
||||
|
||||
public static long getLong(String key, long defValue) {
|
||||
return mConfigPre.getLong(key, defValue);
|
||||
}
|
||||
|
||||
public static void setLong(String key, long value) {
|
||||
mConfigPre.edit().putLong(key, value).apply();
|
||||
}
|
||||
|
||||
public static String getString(String key, String defValue) {
|
||||
return mConfigPre.getString(key, defValue);
|
||||
}
|
||||
@@ -343,6 +359,9 @@ public final class Config {
|
||||
private static final String KEY_START_POSITION = "start_position";
|
||||
private static final int DEFAULT_START_POSITION = 1;
|
||||
|
||||
private static final String KEY_VOLUME_PAGE = "volume_page";
|
||||
private static final boolean DEFAULT_VOLUME_PAGE = false;
|
||||
|
||||
private static final String KEY_GALLERY_SHOW_CLOCK = "gallery_show_clock";
|
||||
private static final boolean DEFAULT_GALLERY_SHOW_CLOCK = true;
|
||||
|
||||
@@ -395,6 +414,15 @@ public final class Config {
|
||||
setBoolean(KEY_KEEP_SCREEN_ON, value);
|
||||
}
|
||||
|
||||
public static void setVolumePage(boolean value) {
|
||||
setBoolean(KEY_VOLUME_PAGE, value);
|
||||
}
|
||||
|
||||
public static boolean getVolumePage() {
|
||||
return getBoolean(KEY_VOLUME_PAGE, DEFAULT_VOLUME_PAGE);
|
||||
}
|
||||
|
||||
|
||||
public static boolean getShowClock() {
|
||||
return getBoolean(KEY_GALLERY_SHOW_CLOCK, DEFAULT_GALLERY_SHOW_CLOCK);
|
||||
}
|
||||
@@ -542,6 +570,12 @@ public final class Config {
|
||||
private static final String KEY_EH_MIN_INTERVAL = "eh_min_interval";
|
||||
private static final int DEFAULT_EH_MIN_INTERVAL = 0;
|
||||
|
||||
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
|
||||
private static final String DEFAULT_PATTERN_PROTECTION = "";
|
||||
|
||||
private static final String KEY_SHOW_APPLICATION_STATS = "show_application_stats";
|
||||
private static final boolean DEFAULT_SHOW_APPLICATION_STATS = false;
|
||||
|
||||
public static int getHttpRetry() {
|
||||
return getIntFromStr(KEY_HTTP_RETRY, DEFAULT_HTTP_RETRY);
|
||||
}
|
||||
@@ -558,6 +592,22 @@ public final class Config {
|
||||
return getIntFromStr(KEY_EH_MIN_INTERVAL, DEFAULT_EH_MIN_INTERVAL);
|
||||
}
|
||||
|
||||
public static String getPatternProtection() {
|
||||
return getString(KEY_PATTERN_PROTECTION, DEFAULT_PATTERN_PROTECTION);
|
||||
}
|
||||
|
||||
public static void setPatternProtection(String value) {
|
||||
setString(KEY_PATTERN_PROTECTION, value);
|
||||
}
|
||||
|
||||
public static boolean getShowApplicationStats() {
|
||||
return getBoolean(KEY_SHOW_APPLICATION_STATS, DEFAULT_SHOW_APPLICATION_STATS);
|
||||
}
|
||||
|
||||
public static void setShowApplicationStats(boolean value) {
|
||||
setBoolean(KEY_SHOW_APPLICATION_STATS, value);
|
||||
}
|
||||
|
||||
|
||||
/****** About ******/
|
||||
|
||||
|
||||
@@ -24,10 +24,15 @@ public final class Constants {
|
||||
public static final int ANIMATE_TIME = 300;
|
||||
|
||||
public static final int HTTP_TEMP_REDIRECT = 307;
|
||||
public static String defaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36";
|
||||
public static String userAgent = System.getProperty("http.agent", defaultUserAgent);
|
||||
public static final int DEFAULT_TIMEOUT = 5 * 1000;
|
||||
public static final int MAX_REDIRECTS = 5;
|
||||
|
||||
public static final int BUFFER_SIZE = 4096;
|
||||
|
||||
public static final int MESSENGER_ID_SHOW_APP_STATUS;
|
||||
|
||||
static {
|
||||
Messenger messenger = Messenger.getInstance();
|
||||
MESSENGER_ID_SHOW_APP_STATUS = messenger.newId();
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,7 @@
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageInfo;
|
||||
@@ -32,6 +25,17 @@ import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
|
||||
import com.hippo.ehviewer.ehclient.EhClient;
|
||||
import com.hippo.ehviewer.ui.GalleryDetailActivity;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
public class Crash {
|
||||
private static final String TAG = "Crash";
|
||||
|
||||
@@ -85,6 +89,7 @@ public class Crash {
|
||||
*
|
||||
* @param ex The throwable to store
|
||||
*/
|
||||
@SuppressLint("CommitPrefEdits")
|
||||
public static void saveCrashInfo2File(Throwable ex) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
collectDeviceInfo(sb);
|
||||
@@ -94,8 +99,8 @@ public class Crash {
|
||||
sb.append("======== CrashInfo ========\n").append(result).append("\n");
|
||||
try {
|
||||
long timestamp = System.currentTimeMillis();
|
||||
String time = Utils.sDate.format(System.currentTimeMillis());
|
||||
String fileName = "crash-" + time + "-" + timestamp + ".log";
|
||||
//String time = Utils.sDate.format(System.currentTimeMillis());
|
||||
String fileName = "crash-" + timestamp + ".log";
|
||||
String path = null;
|
||||
boolean position = false;
|
||||
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
||||
@@ -119,6 +124,7 @@ public class Crash {
|
||||
editor.putBoolean(NEW_CRAHS, true);
|
||||
editor.putBoolean(LAST_CRASH_POSITION, position);
|
||||
editor.putString(LAST_CRASH_NAME, fileName);
|
||||
// Save it immediately
|
||||
editor.commit();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "An error occured while writing crash file...", e);
|
||||
@@ -133,37 +139,50 @@ public class Crash {
|
||||
String versionName = pi.versionName == null ? "null" : pi.versionName;
|
||||
String versionCode = String.valueOf(pi.versionCode);
|
||||
sb.append("======== PackageInfo ========\n");
|
||||
sb.append("PackageName=" + pi.packageName + "\n");
|
||||
sb.append("VersionName=" + versionName + "\n");
|
||||
sb.append("VersionCode=" + versionCode + "\n");
|
||||
sb.append("PackageName=").append(pi.packageName).append("\n");
|
||||
sb.append("VersionName=").append(versionName).append("\n");
|
||||
sb.append("VersionCode=").append(versionCode).append("\n");
|
||||
sb.append("Signature=").append(PackageUtils.getSignature(mContext, pi.packageName)).append("\n");
|
||||
sb.append("\n");
|
||||
}
|
||||
} catch (NameNotFoundException e) {
|
||||
Log.e(TAG, "an error occured when collect package info", e);
|
||||
|
||||
sb.append("======== PackageInfo ========\n");
|
||||
sb.append("Can't get package information\n");
|
||||
sb.append("\n");
|
||||
}
|
||||
|
||||
// Runtime
|
||||
sb.append("======== Runtime ========\n");
|
||||
sb.append("Source=").append(EhClient.getUrlHeader()).append("\n");
|
||||
sb.append("Gallery=").append(GalleryDetailActivity.getCurrentGallery()).append("\n");
|
||||
sb.append("\n");
|
||||
|
||||
// Device info
|
||||
sb.append("======== DeviceInfo ========\n");
|
||||
sb.append("BOARD=" + Build.BOARD + "\n");
|
||||
sb.append("BOOTLOADER=" + Build.BOOTLOADER + "\n");
|
||||
sb.append("CPU_ABI=" + Build.CPU_ABI + "\n");
|
||||
sb.append("CPU_ABI2=" + Build.CPU_ABI2 + "\n");
|
||||
sb.append("DEVICE=" + Build.DEVICE + "\n");
|
||||
sb.append("DISPLAY=" + Build.DISPLAY + "\n");
|
||||
sb.append("FINGERPRINT=" + Build.FINGERPRINT + "\n");
|
||||
sb.append("HARDWARE=" + Build.HARDWARE + "\n");
|
||||
sb.append("HOST=" + Build.HOST + "\n");
|
||||
sb.append("ID=" + Build.ID + "\n");
|
||||
sb.append("MANUFACTURER=" + Build.MANUFACTURER + "\n");
|
||||
sb.append("MODEL=" + Build.MODEL + "\n");
|
||||
sb.append("PRODUCT=" + Build.PRODUCT + "\n");
|
||||
sb.append("RADIO=" + Build.getRadioVersion() + "\n");
|
||||
sb.append("SERIAL=" + Build.SERIAL + "\n");
|
||||
sb.append("TAGS=" + Build.TAGS + "\n");
|
||||
sb.append("TYPE=" + Build.TYPE + "\n");
|
||||
sb.append("USER=" + Build.USER + "\n");
|
||||
sb.append("CODENAME=" + Build.VERSION.CODENAME + "\n");
|
||||
sb.append("INCREMENTAL=" + Build.VERSION.INCREMENTAL + "\n");
|
||||
sb.append("RELEASE=" + Build.VERSION.RELEASE + "\n");
|
||||
sb.append("SDK=" + Build.VERSION.SDK_INT + "\n");
|
||||
sb.append("BOARD=").append(Build.BOARD).append("\n");
|
||||
sb.append("BOOTLOADER=").append(Build.BOOTLOADER).append("\n");
|
||||
sb.append("CPU_ABI=").append(Build.CPU_ABI).append("\n");
|
||||
sb.append("CPU_ABI2=").append(Build.CPU_ABI2).append("\n");
|
||||
sb.append("DEVICE=").append(Build.DEVICE).append("\n");
|
||||
sb.append("DISPLAY=").append(Build.DISPLAY).append("\n");
|
||||
sb.append("FINGERPRINT=").append(Build.FINGERPRINT).append("\n");
|
||||
sb.append("HARDWARE=").append(Build.HARDWARE).append("\n");
|
||||
sb.append("HOST=").append(Build.HOST).append("\n");
|
||||
sb.append("ID=").append(Build.ID).append("\n");
|
||||
sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n");
|
||||
sb.append("MODEL=").append(Build.MODEL).append("\n");
|
||||
sb.append("PRODUCT=").append(Build.PRODUCT).append("\n");
|
||||
sb.append("RADIO=").append(Build.getRadioVersion()).append("\n");
|
||||
sb.append("SERIAL=").append(Build.SERIAL).append("\n");
|
||||
sb.append("TAGS=").append(Build.TAGS).append("\n");
|
||||
sb.append("TYPE=").append(Build.TYPE).append("\n");
|
||||
sb.append("USER=").append(Build.USER).append("\n");
|
||||
sb.append("CODENAME=").append(Build.VERSION.CODENAME).append("\n");
|
||||
sb.append("INCREMENTAL=").append(Build.VERSION.INCREMENTAL).append("\n");
|
||||
sb.append("RELEASE=").append(Build.VERSION.RELEASE).append("\n");
|
||||
sb.append("SDK=").append(Build.VERSION.SDK_INT).append("\n");
|
||||
sb.append("\n");
|
||||
}
|
||||
|
||||
@@ -199,7 +218,7 @@ public class Crash {
|
||||
DataInputStream din = new DataInputStream(new FileInputStream(lastCrashFile));
|
||||
din.readFully(buffer);
|
||||
din.close();
|
||||
configPre.edit().putBoolean(NEW_CRAHS, false).commit();
|
||||
configPre.edit().putBoolean(NEW_CRAHS, false).apply();
|
||||
return new String(buffer);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "An error occured while reading crash file...", e);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
public final class IntIdGenerator {
|
||||
|
||||
private int mId = 0;
|
||||
|
||||
private IntIdGenerator() {
|
||||
// Empty
|
||||
}
|
||||
|
||||
public synchronized int nextId() {
|
||||
return mId++;
|
||||
}
|
||||
|
||||
public static IntIdGenerator create() {
|
||||
return new IntIdGenerator();
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,14 @@ public final class MathUtils {
|
||||
return (float) Math.sqrt(x * x + y * y + z * z);
|
||||
}
|
||||
|
||||
public static boolean near(float x1, float y1, float x2, float y2, float slop) {
|
||||
return dist(x1, y1, x2, y2) < slop;
|
||||
}
|
||||
|
||||
public static boolean near(float x1, float y1, float z1, float x2, float y2, float z2, float slop) {
|
||||
return dist(x1, y1, z1, x2, y2, z2) < slop;
|
||||
}
|
||||
|
||||
public static float mag(float a, float b) {
|
||||
return (float) Math.hypot(a, b);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Messenger {
|
||||
|
||||
private IntIdGenerator mIdGenerator;
|
||||
|
||||
private SparseArray<Set<Receiver>> mReceiverSetMap;
|
||||
|
||||
private static Messenger sInstance;
|
||||
|
||||
public static Messenger getInstance() {
|
||||
if (sInstance == null) {
|
||||
sInstance = new Messenger();
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
|
||||
private Messenger() {
|
||||
mIdGenerator = IntIdGenerator.create();
|
||||
mReceiverSetMap = new SparseArray<>();
|
||||
}
|
||||
|
||||
public int newId() {
|
||||
return mIdGenerator.nextId();
|
||||
}
|
||||
|
||||
public void notify(final int id, final Object obj) {
|
||||
// Make sure do it in UI thread
|
||||
AppHandler.getInstance().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
|
||||
if (receiverSet != null) {
|
||||
for (Receiver receiver : receiverSet) {
|
||||
receiver.onReceive(id, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void register(int id, Receiver receiver) {
|
||||
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
|
||||
if (receiverSet == null) {
|
||||
receiverSet = new HashSet<>();
|
||||
mReceiverSetMap.put(id, receiverSet);
|
||||
}
|
||||
|
||||
receiverSet.add(receiver);
|
||||
}
|
||||
|
||||
public void unregister(int id, Receiver receiver) {
|
||||
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
|
||||
if (receiverSet != null) {
|
||||
receiverSet.remove(receiver);
|
||||
if (receiverSet.isEmpty()) {
|
||||
mReceiverSetMap.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface Receiver {
|
||||
void onReceive(final int id, final Object obj);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.Signature;
|
||||
|
||||
public final class PackageUtils {
|
||||
|
||||
private static final String TAG = PackageUtils.class.getSimpleName();
|
||||
|
||||
public static String getSignature(Context context, String packageName) {
|
||||
try {
|
||||
@SuppressLint("PackageManagerGetSignatures")
|
||||
PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
|
||||
Signature[] ss = pi.signatures;
|
||||
if (ss != null && ss.length >= 1) {
|
||||
return Utils.computeSHA1(ss[0].toByteArray());
|
||||
} else {
|
||||
Log.e(TAG, "Can't find signature in package " + packageName);
|
||||
}
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
Log.e(TAG, "Can't find package " + packageName, e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,14 @@
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
|
||||
import com.hippo.ehviewer.network.HttpHelper;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public final class Secret {
|
||||
|
||||
private static final String DIR_NAME = "images";
|
||||
@@ -81,7 +81,7 @@ public final class Secret {
|
||||
// Get image error, try to get image from internet
|
||||
HttpHelper hh = new HttpHelper(mContext);
|
||||
hh.download(SERCET_IMAGE_URL, mContext.getExternalFilesDir(DIR_NAME),
|
||||
IMAGE_NAME, false, null, null);
|
||||
IMAGE_NAME, null, null, null);
|
||||
}
|
||||
sIsGetSecretImage = false;
|
||||
}
|
||||
|
||||
@@ -370,7 +370,9 @@ public class Ui {
|
||||
actionBar.setHomeButtonEnabled(true);
|
||||
actionBar.setDisplayHomeAsUpEnabled(true);
|
||||
actionBar.setHomeAsUpIndicator(d);
|
||||
actionBar.setIcon(null);
|
||||
// actionBar.setIcon(null) may cause crash in Meizu lollipop
|
||||
actionBar.setIcon(new ColorDrawable());
|
||||
actionBar.setElevation(dp2pix(4.0f));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,18 @@
|
||||
|
||||
package com.hippo.ehviewer.util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Build;
|
||||
import android.os.Vibrator;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.text.TextUtils;
|
||||
import android.webkit.MimeTypeMap;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.EOFException;
|
||||
@@ -26,6 +38,8 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Collection;
|
||||
@@ -33,17 +47,6 @@ import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Build;
|
||||
import android.os.Vibrator;
|
||||
import android.text.TextUtils;
|
||||
import android.webkit.MimeTypeMap;
|
||||
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
|
||||
public final class Utils {
|
||||
@SuppressWarnings("unused")
|
||||
private static String TAG = Utils.class.getSimpleName();
|
||||
@@ -742,4 +745,51 @@ public final class Utils {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Move to FileUtils
|
||||
public static void getNameAndExtension(@NonNull String filename,
|
||||
@NonNull String[] container) {
|
||||
if (container.length != 2) {
|
||||
throw new IllegalStateException("container must be an array of two integers");
|
||||
}
|
||||
|
||||
int index = filename.lastIndexOf('.');
|
||||
if (index == -1) {
|
||||
container[0] = filename;
|
||||
container[1] = null;
|
||||
} else {
|
||||
container[0] = filename.substring(0, index);
|
||||
container[1] = filename.substring(index + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return looks like A1:43:6B:34... or null
|
||||
*/
|
||||
public static String computeSHA1(final byte[] certRaw) {
|
||||
StringBuilder sb = new StringBuilder(59);
|
||||
MessageDigest md;
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA1");
|
||||
byte[] sha1 = md.digest(certRaw);
|
||||
int length = sha1.length;
|
||||
for (int i = 0; i < length; i++) {
|
||||
if (i != 0) {
|
||||
sb.append(':');
|
||||
}
|
||||
byte b = sha1[i];
|
||||
String appendStr = Integer.toString(b & 0xff, 16);
|
||||
if (appendStr.length() == 1) {
|
||||
sb.append(0);
|
||||
}
|
||||
sb.append(appendStr);
|
||||
}
|
||||
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
catch (NoSuchAlgorithmException ex) {
|
||||
Log.e(TAG, "Can't final Algorithm SHA1", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,4 +202,9 @@ public final class ViewUtils {
|
||||
y >= view.getTop() &&
|
||||
y < view.getBottom();
|
||||
}
|
||||
|
||||
public static void transformPointToViewLocal(float[] point, View parent, View child) {
|
||||
point[0] += parent.getScrollX() - child.getLeft();
|
||||
point[1] += parent.getScrollY() - child.getTop();
|
||||
}
|
||||
}
|
||||
@@ -34,15 +34,14 @@ import android.widget.TextView;
|
||||
import com.hippo.ehviewer.AppHandler;
|
||||
import com.hippo.ehviewer.ImageLoader;
|
||||
import com.hippo.ehviewer.R;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.cardview.CardViewSalon;
|
||||
import com.hippo.ehviewer.data.GalleryInfo;
|
||||
import com.hippo.ehviewer.ehclient.ListParser;
|
||||
import com.hippo.ehviewer.cache.ImageCache;
|
||||
import com.hippo.ehviewer.util.Config;
|
||||
import com.hippo.ehviewer.util.Ui;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
|
||||
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView.FooterAdapter;
|
||||
import com.hippo.ehviewer.widget.recyclerview.MarginItemDecoration;
|
||||
import com.hippo.ehviewer.widget.refreshlayout.RefreshLayout;
|
||||
|
||||
@@ -229,6 +228,14 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
}
|
||||
}
|
||||
|
||||
public EasyRecyclerView getEasyRecyclerView() {
|
||||
return mEasyRecyclerView;
|
||||
}
|
||||
|
||||
public GalleryAdapter getGalleryAdapter() {
|
||||
return mAdapter;
|
||||
}
|
||||
|
||||
public void setGalleryListViewHelper(GalleryListViewHelper h) {
|
||||
mHelper = h;
|
||||
}
|
||||
@@ -274,6 +281,10 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
mEasyRecyclerView.setMultiChoiceModeListener(listener);
|
||||
}
|
||||
|
||||
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
|
||||
mEasyRecyclerView.addOnItemTouchListener(listener);
|
||||
}
|
||||
|
||||
public void notifyDataSetChanged() {
|
||||
mAdapter.notifyDataSetChanged();
|
||||
}
|
||||
@@ -447,6 +458,10 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
return mGiList.get(position);
|
||||
}
|
||||
|
||||
public GalleryInfo removeGalleryInfo(int position) {
|
||||
return mGiList.remove(position);
|
||||
}
|
||||
|
||||
public static interface OnGetListListener {
|
||||
public void onSuccess(long taskStamp, List<GalleryInfo> gis, int maxPage);
|
||||
public void onFailure(long taskStamp, String eMsg);
|
||||
@@ -612,6 +627,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
|
||||
@Override
|
||||
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
|
||||
/*
|
||||
switch (newState) {
|
||||
case RecyclerView.SCROLL_STATE_DRAGGING:
|
||||
ImageCache.getImageCache(mContext).setPauseDiskCache(true);
|
||||
@@ -620,6 +636,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
ImageCache.getImageCache(mContext).setPauseDiskCache(false);
|
||||
break;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -704,7 +721,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
}
|
||||
}
|
||||
|
||||
public class GalleryAdapter extends EasyRecyclerView.FooterAdapter<GalleryViewHolder> {
|
||||
public class GalleryAdapter extends RecyclerView.Adapter<GalleryViewHolder> {
|
||||
|
||||
private final Context mContext;
|
||||
private final List<GalleryInfo> mGiList;
|
||||
@@ -718,13 +735,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryViewHolder onCreateAndBindFooterViewHolder(
|
||||
ViewGroup parent, View footerView) {
|
||||
return new GalleryViewHolder(footerView, FooterAdapter.TYPE_FOOTER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GalleryViewHolder onCreateViewHolderActual(ViewGroup parent,
|
||||
public GalleryViewHolder onCreateViewHolder(ViewGroup parent,
|
||||
int viewType) {
|
||||
int resId;
|
||||
if (viewType == LIST_MODE_DETAIL)
|
||||
@@ -741,8 +752,10 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolderActual(GalleryViewHolder holder,
|
||||
public void onBindViewHolder(GalleryViewHolder holder,
|
||||
int position) {
|
||||
mEasyRecyclerView.checkItemCheckedState(holder.itemView, position);
|
||||
|
||||
GalleryInfo gi = mGiList.get(position);
|
||||
final LoadImageView thumb = holder.thumb;
|
||||
final String key = String.valueOf(gi.gid);
|
||||
@@ -801,12 +814,12 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnHead
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewTypeActual(int position) {
|
||||
public int getItemViewType(int position) {
|
||||
return mListMode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCountActual() {
|
||||
public int getItemCount() {
|
||||
return mGiList.size();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright (C) 2007 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.widget;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Utilities for the lock pattern and its settings.
|
||||
*/
|
||||
public class LockPatternUtils {
|
||||
|
||||
/**
|
||||
* Deserialize a pattern.
|
||||
* @param string The pattern serialized with {@link #patternToString}
|
||||
* @return The pattern.
|
||||
*/
|
||||
public static List<LockPatternView.Cell> stringToPattern(String string) {
|
||||
List<LockPatternView.Cell> result = new ArrayList<>();
|
||||
|
||||
final byte[] bytes = string.getBytes();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
byte b = bytes[i];
|
||||
result.add(LockPatternView.Cell.of(b / 3, b % 3));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a pattern.
|
||||
* @param pattern The pattern.
|
||||
* @return The pattern in string form.
|
||||
*/
|
||||
public static String patternToString(List<LockPatternView.Cell> pattern) {
|
||||
if (pattern == null) {
|
||||
return "";
|
||||
}
|
||||
final int patternSize = pattern.size();
|
||||
|
||||
byte[] res = new byte[patternSize];
|
||||
for (int i = 0; i < patternSize; i++) {
|
||||
LockPatternView.Cell cell = pattern.get(i);
|
||||
res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
|
||||
}
|
||||
return new String(res);
|
||||
}
|
||||
|
||||
public static boolean isPatternVaild(String pattern) {
|
||||
byte[] bytes = pattern.getBytes();
|
||||
if (bytes.length <= 9 && bytes.length >= 2) {
|
||||
for (byte b : bytes) {
|
||||
if (b >= 9 || b < 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright (C) 2015 Hippo Seven
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.widget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.support.annotation.DrawableRes;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
public class SimpleImageView extends View implements Drawable.Callback {
|
||||
|
||||
private Drawable mDrawable;
|
||||
|
||||
private boolean mKeepAspect = true;
|
||||
|
||||
private static final int[] LAYOUT_ATTRS = new int[] {
|
||||
android.R.attr.src
|
||||
};
|
||||
|
||||
public SimpleImageView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs);
|
||||
}
|
||||
|
||||
public SimpleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context, attrs);
|
||||
}
|
||||
|
||||
private void init(Context context, AttributeSet attrs) {
|
||||
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
|
||||
setDrawable(a.getDrawable(0));
|
||||
a.recycle();
|
||||
|
||||
// Mostly drawable is VectorDrawable, it has cache already
|
||||
setWillNotCacheDrawing(true);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public void setDrawable(@DrawableRes int resId) {
|
||||
setDrawable(getContext().getResources().getDrawable(resId));
|
||||
}
|
||||
|
||||
public void setDrawable(Drawable drawable) {
|
||||
if (mDrawable != null) {
|
||||
mDrawable.setCallback(null);
|
||||
}
|
||||
mDrawable = drawable;
|
||||
if (mDrawable != null) {
|
||||
mDrawable.setCallback(this);
|
||||
}
|
||||
requestLayout();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invalidateDrawable(@NonNull Drawable who) {
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getSuggestedMinimumWidth() {
|
||||
int superMinWidth = super.getSuggestedMinimumWidth();
|
||||
return (mDrawable == null) ? superMinWidth :
|
||||
Math.max(superMinWidth, mDrawable.getMinimumWidth() + getPaddingLeft() + getPaddingRight());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getSuggestedMinimumHeight() {
|
||||
int superMinHeight = super.getSuggestedMinimumHeight();
|
||||
return (mDrawable == null) ? superMinHeight :
|
||||
Math.max(superMinHeight, mDrawable.getMinimumHeight() + getPaddingTop() + getPaddingBottom());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
|
||||
super.onLayout(changed, left, top, right, bottom);
|
||||
|
||||
if (mDrawable != null) {
|
||||
int paddingLeft = getPaddingLeft();
|
||||
int paddingTop = getPaddingTop();
|
||||
int paddingRight = getPaddingRight();
|
||||
int paddingBottom = getPaddingBottom();
|
||||
|
||||
int canvasWidth = right - left - paddingLeft - paddingRight;
|
||||
int canvasHeight = bottom - top - paddingTop - paddingBottom;
|
||||
int intrinsicWidth = mDrawable.getIntrinsicWidth();
|
||||
int intrinsicHeight = mDrawable.getIntrinsicHeight();
|
||||
|
||||
if (mKeepAspect && intrinsicWidth > 0 && intrinsicHeight > 0) {
|
||||
int drawWidth;
|
||||
int drawHeight;
|
||||
float canvasAspect = canvasWidth / canvasHeight;
|
||||
float drawableAspect = intrinsicWidth / intrinsicHeight;
|
||||
if (drawableAspect > canvasAspect) {
|
||||
drawWidth = (int) (canvasHeight * drawableAspect);
|
||||
drawHeight = canvasHeight;
|
||||
} else {
|
||||
drawWidth = canvasWidth;
|
||||
drawHeight = (int) (canvasWidth / drawableAspect);
|
||||
}
|
||||
|
||||
int drawLeft = paddingLeft + ((canvasWidth - drawWidth) / 2);
|
||||
int drawTop = paddingTop + ((canvasHeight - drawHeight) / 2);
|
||||
mDrawable.setBounds(drawLeft, drawTop,
|
||||
drawLeft + drawWidth, drawTop + drawHeight);
|
||||
} else {
|
||||
mDrawable.setBounds(paddingLeft, paddingTop,
|
||||
paddingLeft + canvasWidth, paddingTop + canvasHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
if (mDrawable != null) {
|
||||
mDrawable.draw(canvas);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014 Hippo Seven
|
||||
* Copyright (C) 2014-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.
|
||||
@@ -8,7 +8,6 @@
|
||||
* 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.
|
||||
@@ -16,37 +15,34 @@
|
||||
|
||||
package com.hippo.ehviewer.widget.recyclerview;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.support.v4.util.LongSparseArray;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.StaggeredGridLayoutManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.SparseBooleanArray;
|
||||
import android.util.TypedValue;
|
||||
import android.view.ActionMode;
|
||||
import android.view.HapticFeedbackConstants;
|
||||
import android.view.InputDevice;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.SoundEffectConstants;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AbsListView;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.accessibility.AccessibilityEvent;
|
||||
import android.widget.Checkable;
|
||||
import android.widget.ListAdapter;
|
||||
|
||||
import com.hippo.ehviewer.util.MathUtils;
|
||||
import com.hippo.ehviewer.util.ViewUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
* Get some code from twoway-view and AbsListView
|
||||
*
|
||||
* @author Hippo
|
||||
*
|
||||
* Add setOnItemClickListener, setOnItemLongClickListener and setChoiceMode for
|
||||
* RecyclerView
|
||||
*/
|
||||
public class EasyRecyclerView extends RecyclerView implements View.OnClickListener,
|
||||
View.OnLongClickListener {
|
||||
|
||||
private static final String TAG = EasyRecyclerView.class.getSimpleName();
|
||||
// Get some code from twoway-view and AbsListView.
|
||||
public class EasyRecyclerView extends RecyclerView {
|
||||
|
||||
private static final String STATE_KEY_CHOICE_MODE = "choiceMode";
|
||||
private static final String STATE_KEY_CHECKED_STATES = "checkedStates";
|
||||
@@ -112,15 +108,27 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
*/
|
||||
private LongSparseArray<Integer> mCheckedIdStates;
|
||||
|
||||
private OnItemClickListener mOnItemClickListener;
|
||||
private OnItemLongClickListener mOnItemLongClickListener;
|
||||
private boolean mNeedOnClickListener = false;
|
||||
private boolean mNeedOnLongClickListener = false;
|
||||
|
||||
private FooterAdapter mAdapter;
|
||||
private Adapter mAdapter;
|
||||
|
||||
private float mVerticalScrollFactor = 0;
|
||||
|
||||
// For click and long click
|
||||
private boolean mPrePressed = false;
|
||||
private boolean mHasPerformedLongPress = false;
|
||||
private View mMotionView;
|
||||
private int mMotionPosition;
|
||||
private CheckForTap mPendingCheckForTap;
|
||||
private CheckForLongPress mPendingCheckForLongPress;
|
||||
private UnsetPressedState mUnsetPressedState;
|
||||
private PerformClick mPerformClick;
|
||||
private final float[] mTmpPoint = new float[2];
|
||||
private int mTouchSlop = -1;
|
||||
private float mStartX;
|
||||
private float mStartY;
|
||||
private OnItemClickListener mOnItemClickListener;
|
||||
private OnItemLongClickListener mOnItemLongClickListener;
|
||||
|
||||
|
||||
public EasyRecyclerView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
@@ -133,131 +141,19 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
public View getFootView() {
|
||||
if (mAdapter != null)
|
||||
return mAdapter.getFooterView();
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isNeedOnClickListener() {
|
||||
if (mOnItemClickListener == null && mChoiceMode == CHOICE_MODE_NONE)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isNeedOnLongClickListener() {
|
||||
if (mOnItemLongClickListener != null || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
private void setAllOnClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnClickListener(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAllOnClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnClickListener(null);
|
||||
child.setClickable(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setAllOnLongClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnLongClickListener(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAllOnLongClickListener() {
|
||||
final int count = getChildCount();
|
||||
final View footView = getFootView();
|
||||
for (int i = 0; i < count; i++) {
|
||||
View child = getChildAt(i);
|
||||
if (child != footView) {
|
||||
child.setOnLongClickListener(null);
|
||||
child.setLongClickable(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateOnClickState() {
|
||||
boolean newNeedOnClickListener = isNeedOnClickListener();
|
||||
if (mNeedOnClickListener != newNeedOnClickListener) {
|
||||
mNeedOnClickListener = newNeedOnClickListener;
|
||||
if (mNeedOnClickListener)
|
||||
setAllOnClickListener();
|
||||
else
|
||||
resetAllOnClickListener();
|
||||
}
|
||||
}
|
||||
|
||||
public void updateOnLongClickState() {
|
||||
boolean newNeedOnLongClickListener = isNeedOnLongClickListener();
|
||||
if (mNeedOnLongClickListener != newNeedOnLongClickListener) {
|
||||
mNeedOnLongClickListener = newNeedOnLongClickListener;
|
||||
if (mNeedOnLongClickListener)
|
||||
setAllOnLongClickListener();
|
||||
else
|
||||
resetAllOnLongClickListener();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback to be invoked when an item in the
|
||||
* RecyclerView has been clicked.
|
||||
*
|
||||
* @param listener The callback that will be invoked.
|
||||
*/
|
||||
public void setOnItemClickListener(OnItemClickListener listener) {
|
||||
mOnItemClickListener = listener;
|
||||
updateOnClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback to be invoked when an item in the
|
||||
* RecyclerView has been clicked and held.
|
||||
*
|
||||
* @param listener The callback that will be invoked.
|
||||
*/
|
||||
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
|
||||
mOnItemLongClickListener = listener;
|
||||
updateOnLongClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* adapter must be {@link com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView.FooterAdapter}
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void setAdapter(RecyclerView.Adapter adapter) {
|
||||
|
||||
super.setAdapter(adapter);
|
||||
|
||||
mAdapter = (FooterAdapter) adapter;
|
||||
mAdapter.mHolder = this;
|
||||
mAdapter = adapter;
|
||||
if (adapter != null) {
|
||||
if (mChoiceMode != CHOICE_MODE_NONE && adapter.hasStableIds() &&
|
||||
mCheckedIdStates == null) {
|
||||
mCheckedIdStates = new LongSparseArray<Integer>();
|
||||
mCheckedIdStates = new LongSparseArray<>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,6 +195,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
* @see #setChoiceMode(int)
|
||||
*/
|
||||
public boolean isItemChecked(int position) {
|
||||
//noinspection SimplifiableIfStatement
|
||||
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
|
||||
return mCheckStates.get(position);
|
||||
}
|
||||
@@ -342,7 +239,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
/**
|
||||
* Returns the set of checked items ids. The result is only valid if the
|
||||
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
|
||||
* has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
|
||||
* has stable IDs. ({@link android.widget.ListAdapter#hasStableIds()} == {@code true})
|
||||
*
|
||||
* @return A new array which contains the id of each checked item in the
|
||||
* list.
|
||||
@@ -394,7 +291,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
|
||||
if (mMultiChoiceModeCallback == null ||
|
||||
!mMultiChoiceModeCallback.hasWrappedCallback()) {
|
||||
throw new IllegalStateException("AbsListView: attempted to start selection mode " +
|
||||
throw new IllegalStateException("EasyRecyclerView: attempted to start selection mode " +
|
||||
"for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " +
|
||||
"supplied. Call setMultiChoiceModeListener to set a callback.");
|
||||
}
|
||||
@@ -478,16 +375,14 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
mCheckStates = new SparseBooleanArray(0);
|
||||
}
|
||||
if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) {
|
||||
mCheckedIdStates = new LongSparseArray<Integer>(0);
|
||||
mCheckedIdStates = new LongSparseArray<>(0);
|
||||
}
|
||||
// Modal multi-choice mode only has choices when the mode is active. Clear them.
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
|
||||
clearChoices();
|
||||
setLongClickable(true);
|
||||
}
|
||||
}
|
||||
|
||||
updateOnClickState();
|
||||
updateOnLongClickState();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -515,17 +410,15 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
final int count = getChildCount();
|
||||
for (int i = 0; i < count; i++) {
|
||||
final View child = getChildAt(i);
|
||||
final int position = getChildPosition(child);
|
||||
final int position = getChildAdapterPosition(child);
|
||||
setViewChecked(child, mCheckStates.get(position));
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
|
||||
public static void setViewChecked(View view, boolean checked) {
|
||||
final boolean useActivated = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
|
||||
if (view instanceof Checkable) {
|
||||
((Checkable) view).setChecked(checked);
|
||||
} else if (useActivated) {
|
||||
} else {
|
||||
view.setActivated(checked);
|
||||
}
|
||||
}
|
||||
@@ -550,7 +443,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
|
||||
/**
|
||||
* Gets a scale factor that determines the distance the view should scroll
|
||||
* vertically in response to {@link MotionEvent#ACTION_SCROLL}.
|
||||
* vertically in response to {@link android.view.MotionEvent#ACTION_SCROLL}.
|
||||
* @return The vertical scroll scale factor.
|
||||
*/
|
||||
protected float getVerticalScrollFactor() {
|
||||
@@ -567,81 +460,179 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
return mVerticalScrollFactor;
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public Parcelable onSaveInstanceState() {
|
||||
final Parcelable state = new Bundle(super.onSaveInstanceState());
|
||||
public boolean onTouchEvent(MotionEvent ev) {
|
||||
if (!isEnabled()) {
|
||||
// A disabled view that is clickable still consumes the touch
|
||||
// events, it just doesn't respond to them.
|
||||
return isClickable() || isLongClickable();
|
||||
}
|
||||
|
||||
state.putInt(STATE_KEY_CHOICE_MODE, mChoiceMode);
|
||||
state.putParcelable(STATE_KEY_CHECKED_STATES, mCheckStates);
|
||||
state.putParcelable(STATE_KEY_CHECKED_ID_STATES, mCheckedIdStates);
|
||||
state.putInt(STATE_KEY_CHECKED_COUNT, mCheckedItemCount);
|
||||
switch (ev.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN: {
|
||||
onTouchDown(ev);
|
||||
break;
|
||||
}
|
||||
|
||||
return state;
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
onTouchMove(ev);
|
||||
break;
|
||||
}
|
||||
|
||||
case MotionEvent.ACTION_UP: {
|
||||
onTouchUp(ev);
|
||||
break;
|
||||
}
|
||||
|
||||
case MotionEvent.ACTION_CANCEL: {
|
||||
onTouchCancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
super.onTouchEvent(ev);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void onRestoreInstanceState(Bundle state) {
|
||||
mChoiceMode = ChoiceMode.values()[state.getInt(STATE_KEY_CHOICE_MODE)];
|
||||
mCheckedStates = state.getParcelable(STATE_KEY_CHECKED_STATES);
|
||||
mCheckedIdStates = state.getParcelable(STATE_KEY_CHECKED_ID_STATES);
|
||||
mCheckedCount = state.getInt(STATE_KEY_CHECKED_COUNT);
|
||||
private void onTouchDown(MotionEvent ev) {
|
||||
final float x = ev.getX();
|
||||
final float y = ev.getY();
|
||||
mStartX = x;
|
||||
mStartY = y;
|
||||
|
||||
// TODO confirm ids here
|
||||
}*/
|
||||
mMotionView = findChildViewUnder(x, y);
|
||||
mMotionPosition = getChildAdapterPosition(mMotionView);
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked.
|
||||
*/
|
||||
public interface OnItemClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened.
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the adapter.
|
||||
* @param id The row id of the item that was clicked.
|
||||
*
|
||||
* @return true if the callback consumed the click, false otherwise
|
||||
*/
|
||||
boolean onItemClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
if (mMotionView != null && mMotionPosition >= 0) {
|
||||
mHasPerformedLongPress = false;
|
||||
|
||||
mPrePressed = true;
|
||||
if (mPendingCheckForTap == null) {
|
||||
mPendingCheckForTap = new CheckForTap();
|
||||
}
|
||||
mPendingCheckForTap.x = x;
|
||||
mPendingCheckForTap.y = y;
|
||||
mPendingCheckForTap.v = mMotionView;
|
||||
mPendingCheckForTap.p = mMotionPosition;
|
||||
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
|
||||
|
||||
} else {
|
||||
mMotionView = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked and held.
|
||||
*/
|
||||
public interface OnItemLongClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked and held.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the list
|
||||
* @param id The row id of the item that was clicked
|
||||
*
|
||||
* @return true if the callback consumed the long click, false otherwise
|
||||
*/
|
||||
boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
private void onTouchMove(MotionEvent ev) {
|
||||
if (mTouchSlop == -1)
|
||||
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
|
||||
|
||||
if (mMotionView != null && mMotionPosition >= 0 &&
|
||||
!MathUtils.near(mStartX, mStartY, ev.getX(), ev.getY(), mTouchSlop)) {
|
||||
removeTapCallback();
|
||||
if (mMotionView.isPressed()) {
|
||||
// Remove any future long press/tap checks
|
||||
removeLongPressCallback();
|
||||
mMotionView.setPressed(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onTouchUp(MotionEvent ev) {
|
||||
View motionView = mMotionView;
|
||||
int motionPosition = mMotionPosition;
|
||||
|
||||
/*
|
||||
* EasyRecyclerView.OnItemTouchListener will not work fine
|
||||
* when item view's child need click action, because they make
|
||||
* touch event deliver different
|
||||
*/
|
||||
if (motionView != null && motionPosition >= 0) {
|
||||
final float x = ev.getX();
|
||||
final float y = ev.getY();
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
final int position = getChildPosition(view);
|
||||
final long id = mAdapter.getItemId(position);
|
||||
if (motionView.isPressed() || mPrePressed) {
|
||||
// The button is being released before we actually
|
||||
// showed it as pressed. Make it show the pressed
|
||||
// state now (before scheduling the click) to ensure
|
||||
// the user sees it.
|
||||
final float[] point = mTmpPoint;
|
||||
point[0] = x;
|
||||
point[1] = y;
|
||||
ViewUtils.transformPointToViewLocal(point, EasyRecyclerView.this, motionView);
|
||||
setPressed(motionView, true, point[0], point[1]);
|
||||
|
||||
if (!mHasPerformedLongPress) {
|
||||
// This is a tap, so remove the longpress check
|
||||
removeLongPressCallback();
|
||||
|
||||
// Use a Runnable and post this rather than calling
|
||||
// performClick directly. This lets other visual state
|
||||
// of the view update before click actions start.
|
||||
if (mPerformClick == null) {
|
||||
mPerformClick = new PerformClick();
|
||||
}
|
||||
mPerformClick.v = motionView;
|
||||
mPerformClick.p = motionPosition;
|
||||
mPerformClick.rememberWindowAttachCount();
|
||||
if (!post(mPerformClick)) {
|
||||
mPerformClick.run();
|
||||
}
|
||||
}
|
||||
|
||||
if (mUnsetPressedState == null) {
|
||||
mUnsetPressedState = new UnsetPressedState();
|
||||
}
|
||||
|
||||
mUnsetPressedState.v = motionView;
|
||||
if (mPrePressed) {
|
||||
postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration());
|
||||
} else if (!post(mUnsetPressedState)) {
|
||||
// If the post failed, unpress right now
|
||||
mUnsetPressedState.run();
|
||||
}
|
||||
|
||||
removeTapCallback();
|
||||
}
|
||||
|
||||
// Release
|
||||
mMotionView = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void onTouchCancel() {
|
||||
if (mMotionView != null && mMotionPosition >= 0) {
|
||||
mMotionView.setPressed(false);
|
||||
removeTapCallback();
|
||||
removeLongPressCallback();
|
||||
|
||||
// Release motion view
|
||||
mMotionView = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void removeTapCallback() {
|
||||
if (mPendingCheckForTap != null) {
|
||||
mPrePressed = false;
|
||||
removeCallbacks(mPendingCheckForTap);
|
||||
mPendingCheckForTap.v = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void removeLongPressCallback() {
|
||||
if (mPendingCheckForLongPress != null) {
|
||||
removeCallbacks(mPendingCheckForLongPress);
|
||||
mPendingCheckForLongPress.v = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void setPressed(View v, boolean pressed, float x, float y){
|
||||
v.setPressed(pressed);
|
||||
if (pressed && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
v.drawableHotspotChanged(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean performItemClick(View view, int position, long id) {
|
||||
boolean handled = false;
|
||||
boolean dispatchItemClick = true;
|
||||
|
||||
if (mChoiceMode != CHOICE_MODE_NONE) {
|
||||
handled = true;
|
||||
boolean checkedStateChanged = false;
|
||||
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE ||
|
||||
@@ -687,36 +678,244 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
}
|
||||
}
|
||||
|
||||
if (dispatchItemClick && mOnItemClickListener != null) {
|
||||
mOnItemClickListener.onItemClick(this, view, position, id);
|
||||
if (dispatchItemClick) {
|
||||
if (mOnItemClickListener != null) {
|
||||
playSoundEffect(SoundEffectConstants.CLICK);
|
||||
mOnItemClickListener.onItemClick(this, view, position, id);
|
||||
if (view != null) {
|
||||
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
return handled;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean onLongClick(View view) {
|
||||
final int position = getChildPosition(view);
|
||||
final long id = mAdapter.getItemId(position);
|
||||
|
||||
private boolean performItemLongPress(final View child,
|
||||
final int longPressPosition, final long longPressId) {
|
||||
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
|
||||
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
|
||||
if (mChoiceActionMode == null &&
|
||||
(mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
|
||||
setItemChecked(position, true);
|
||||
setItemChecked(longPressPosition, true);
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean handled = false;
|
||||
if (mOnItemLongClickListener != null) {
|
||||
handled = mOnItemLongClickListener.onItemLongClick(this, view,
|
||||
position, id);
|
||||
handled = mOnItemLongClickListener.onItemLongClick(this, child,
|
||||
longPressPosition, longPressId);
|
||||
}
|
||||
if (handled) {
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
/**
|
||||
* A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
|
||||
* Register a callback to be invoked when an item in this AdapterView has
|
||||
* been clicked.
|
||||
*
|
||||
* @param listener The callback that will be invoked.
|
||||
*/
|
||||
public void setOnItemClickListener(OnItemClickListener listener) {
|
||||
mOnItemClickListener = listener;
|
||||
}
|
||||
|
||||
|
||||
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
|
||||
if (!isLongClickable()) {
|
||||
setLongClickable(true);
|
||||
}
|
||||
mOnItemLongClickListener = listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* If choice mode is set, call it in {@link Adapter#onBindViewHolder}
|
||||
*/
|
||||
public void checkItemCheckedState(View view, int position) {
|
||||
setViewChecked(view, isItemChecked(position));
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public Parcelable onSaveInstanceState() {
|
||||
final Parcelable state = new Bundle(super.onSaveInstanceState());
|
||||
|
||||
state.putInt(STATE_KEY_CHOICE_MODE, mChoiceMode);
|
||||
state.putParcelable(STATE_KEY_CHECKED_STATES, mCheckStates);
|
||||
state.putParcelable(STATE_KEY_CHECKED_ID_STATES, mCheckedIdStates);
|
||||
state.putInt(STATE_KEY_CHECKED_COUNT, mCheckedItemCount);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
public void onRestoreInstanceState(Bundle state) {
|
||||
mChoiceMode = ChoiceMode.values()[state.getInt(STATE_KEY_CHOICE_MODE)];
|
||||
mCheckedStates = state.getParcelable(STATE_KEY_CHECKED_STATES);
|
||||
mCheckedIdStates = state.getParcelable(STATE_KEY_CHECKED_ID_STATES);
|
||||
mCheckedCount = state.getInt(STATE_KEY_CHECKED_COUNT);
|
||||
|
||||
// TODO confirm ids here
|
||||
}*/
|
||||
|
||||
private final class CheckForTap implements Runnable {
|
||||
float x;
|
||||
float y;
|
||||
View v;
|
||||
int p;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
View view = v;
|
||||
int position = p;
|
||||
if (view != null && position >= 0) {
|
||||
|
||||
mPrePressed = false;
|
||||
final float[] point = mTmpPoint;
|
||||
point[0] = x;
|
||||
point[1] = y;
|
||||
ViewUtils.transformPointToViewLocal(point, EasyRecyclerView.this, view);
|
||||
setPressed(v, true, point[0], point[1]);
|
||||
|
||||
if (isLongClickable()) {
|
||||
mHasPerformedLongPress = false;
|
||||
|
||||
if (mPendingCheckForLongPress == null) {
|
||||
mPendingCheckForLongPress = new CheckForLongPress();
|
||||
}
|
||||
mPendingCheckForLongPress.rememberWindowAttachCount();
|
||||
mPendingCheckForLongPress.v = view;
|
||||
mPendingCheckForLongPress.p = position;
|
||||
postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout() -
|
||||
ViewConfiguration.getTapTimeout());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Release
|
||||
v = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private class CheckForLongPress extends WindowRunnnable implements Runnable {
|
||||
View v;
|
||||
int p;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
View view = v;
|
||||
int position = p;
|
||||
if (view != null && position >= 0 && view.isPressed() && view.getParent() != null) {
|
||||
boolean handled = false;
|
||||
|
||||
if (sameWindow()) {
|
||||
handled = performItemLongPress(view, position, getAdapter().getItemId(position));
|
||||
}
|
||||
if (handled) {
|
||||
mHasPerformedLongPress = true;
|
||||
view.setPressed(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Release
|
||||
v = null;
|
||||
}
|
||||
}
|
||||
|
||||
private final class UnsetPressedState implements Runnable {
|
||||
View v;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (v != null) {
|
||||
v.setPressed(false);
|
||||
|
||||
// Release
|
||||
v = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PerformClick extends WindowRunnnable implements Runnable {
|
||||
View v;
|
||||
int p;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
View view = v;
|
||||
int position = p;
|
||||
if (view != null && position >= 0 && sameWindow()) {
|
||||
performItemClick(view, position, mAdapter.getItemId(position));
|
||||
}
|
||||
|
||||
// Release
|
||||
v = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A base class for Runnables that will check that their view is still attached to
|
||||
* the original window as when the Runnable was created.
|
||||
*
|
||||
*/
|
||||
private class WindowRunnnable {
|
||||
private int mOriginalAttachCount;
|
||||
|
||||
public void rememberWindowAttachCount() {
|
||||
mOriginalAttachCount = getWindowAttachCount();
|
||||
}
|
||||
|
||||
public boolean sameWindow() {
|
||||
return getWindowAttachCount() == mOriginalAttachCount;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked.
|
||||
*/
|
||||
public interface OnItemClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened.
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the adapter.
|
||||
* @param id The row id of the item that was clicked.
|
||||
*
|
||||
* @return true if the callback consumed the click, false otherwise
|
||||
*/
|
||||
boolean onItemClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be invoked when an item in the
|
||||
* EasyRecyclerView has been clicked and held.
|
||||
*/
|
||||
public interface OnItemLongClickListener {
|
||||
/**
|
||||
* Callback method to be invoked when an item in the EasyRecyclerView
|
||||
* has been clicked and held.
|
||||
*
|
||||
* @param parent The EasyRecyclerView where the click happened
|
||||
* @param view The view within the EasyRecyclerView that was clicked
|
||||
* @param position The position of the view in the list
|
||||
* @param id The row id of the item that was clicked
|
||||
*
|
||||
* @return true if the callback consumed the long click, false otherwise
|
||||
*/
|
||||
boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A MultiChoiceModeListener receives events for {@link android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
|
||||
* It acts as the {@link ActionMode.Callback} for the selection mode and also receives
|
||||
* {@link #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user
|
||||
* selects and deselects list items.
|
||||
@@ -731,7 +930,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
* @param checked <code>true</code> if the item is now checked, <code>false</code>
|
||||
* if the item is now unchecked.
|
||||
*/
|
||||
public void onItemCheckedStateChanged(ActionMode mode,
|
||||
void onItemCheckedStateChanged(ActionMode mode,
|
||||
int position, long id, boolean checked);
|
||||
}
|
||||
|
||||
@@ -750,6 +949,7 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
|
||||
if (mWrapped.onCreateActionMode(mode, menu)) {
|
||||
// Initialize checked graphic state?
|
||||
setLongClickable(false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -774,6 +974,8 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
clearChoices();
|
||||
|
||||
requestLayout();
|
||||
|
||||
setLongClickable(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -787,103 +989,4 @@ public class EasyRecyclerView extends RecyclerView implements View.OnClickListen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static abstract class FooterAdapter<VH extends ViewHolder> extends RecyclerView.Adapter<VH> {
|
||||
|
||||
public static final int TYPE_FOOTER = Integer.MAX_VALUE;
|
||||
|
||||
private EasyRecyclerView mHolder;
|
||||
private View mFooterView;
|
||||
|
||||
public boolean hasFootView() {
|
||||
return mFooterView != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* footerView == null to remove foot view
|
||||
* @param footerView
|
||||
*/
|
||||
public void setFooterView(View footerView) {
|
||||
if (mFooterView == footerView)
|
||||
return;
|
||||
|
||||
int itemCountActual = getItemCountActual();
|
||||
View originView = mFooterView;
|
||||
mFooterView = footerView;
|
||||
if (originView != null) {
|
||||
if (mFooterView != null)
|
||||
notifyItemChanged(itemCountActual);
|
||||
else
|
||||
notifyItemRemoved(itemCountActual);
|
||||
} else {
|
||||
notifyItemInserted(itemCountActual);
|
||||
}
|
||||
}
|
||||
|
||||
public View getFooterView() {
|
||||
return mFooterView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
if (mFooterView != null && viewType == TYPE_FOOTER) {
|
||||
StaggeredGridLayoutManager.LayoutParams lp = new StaggeredGridLayoutManager.LayoutParams(
|
||||
StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT,
|
||||
StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT);
|
||||
lp.setFullSpan(true);
|
||||
mFooterView.setLayoutParams(lp);
|
||||
return onCreateAndBindFooterViewHolder(parent, mFooterView);
|
||||
} else {
|
||||
return onCreateViewHolderActual(parent, viewType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onBindViewHolder(VH holder, int position) {
|
||||
if (mFooterView == null || position != getItemCountActual()) {
|
||||
onBindViewHolderActual(holder, position);
|
||||
if (mHolder.mNeedOnClickListener)
|
||||
holder.itemView.setOnClickListener(mHolder);
|
||||
if (mHolder.mNeedOnLongClickListener)
|
||||
holder.itemView.setOnLongClickListener(mHolder);
|
||||
EasyRecyclerView.setViewChecked(holder.itemView,
|
||||
mHolder.isItemChecked(position));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getItemViewType(int position) {
|
||||
if (mFooterView != null && position == getItemCountActual())
|
||||
return TYPE_FOOTER;
|
||||
else
|
||||
return getItemViewTypeActual(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getItemCount() {
|
||||
int itemCount = getItemCountActual();
|
||||
if (mFooterView != null)
|
||||
itemCount++;
|
||||
return itemCount;
|
||||
}
|
||||
|
||||
public abstract VH onCreateAndBindFooterViewHolder(ViewGroup parent, View footerView);
|
||||
|
||||
public abstract VH onCreateViewHolderActual(ViewGroup parent, int viewType);
|
||||
|
||||
public abstract void onBindViewHolderActual(VH holder, int position);
|
||||
|
||||
/**
|
||||
* Foot view type is Integer.MAX_VALUE, do not be the same
|
||||
*
|
||||
* @param position
|
||||
* @return
|
||||
*/
|
||||
public int getItemViewTypeActual(int position) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public abstract int getItemCountActual();
|
||||
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
/*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.hippo.ehviewer.widget.recyclerview;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.VelocityTracker;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Based on Roman Nurik's Android-SwipeToDismiss lib <a href="https://github.com/romannurik/Android-SwipeToDismiss">https://github.com/romannurik/Android-SwipeToDismiss</a>
|
||||
* <p/>
|
||||
* RecyclerView.OnItemTouchListener that allows items to be swiped and dismissed.
|
||||
* <p/>
|
||||
* Typical usage:
|
||||
* <p/>
|
||||
* <pre>
|
||||
* {@code
|
||||
* swipeToDismissTouchListener = new SwipeToDismissTouchListener(recyclerView, new SwipeToDismissTouchListener.DismissCallbacks() {
|
||||
* @Override
|
||||
* public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) {
|
||||
* return SwipeToDismissTouchListener.SwipeDirection.RIGHT;
|
||||
* }
|
||||
* @Override
|
||||
* public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) {
|
||||
* for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) {
|
||||
* adapter.removeItem(data.position);
|
||||
* adapter.notifyItemRemoved(data.position);
|
||||
* }
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
public class SwipeToDismissTouchListener implements RecyclerView.OnItemTouchListener {
|
||||
|
||||
private final RecyclerView mRecyclerView;
|
||||
private int mSlop;
|
||||
private int mMinFlingVelocity;
|
||||
private int mMaxFlingVelocity;
|
||||
private long mAnimationTime;
|
||||
|
||||
private DismissCallbacks mCallbacks;
|
||||
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
|
||||
|
||||
// Transient properties
|
||||
private float mDownX;
|
||||
private float mDownY;
|
||||
private boolean mSwiping;
|
||||
private int mSwipingSlop;
|
||||
private VelocityTracker mVelocityTracker;
|
||||
private float mTranslationX;
|
||||
private boolean mPaused = false;
|
||||
private View mSwipeView;
|
||||
private int mDismissCount = 0;
|
||||
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
|
||||
private SwipeDirection mAllowedSwipeDirection = SwipeDirection.NONE;
|
||||
|
||||
|
||||
private int[] notToDismissPositionArray;
|
||||
|
||||
/**
|
||||
* Constructs a new swipe-to-dismiss OnItemTouchListener for RecyclerView
|
||||
*
|
||||
* @param recyclerView RecyclerView
|
||||
* @param callbacks The callback to trigger when the user has indicated that she would like to
|
||||
* dismiss this view.
|
||||
*/
|
||||
public SwipeToDismissTouchListener(RecyclerView recyclerView, DismissCallbacks callbacks) {
|
||||
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
|
||||
mSlop = vc.getScaledTouchSlop();
|
||||
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 4;
|
||||
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
|
||||
mAnimationTime = recyclerView.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
|
||||
mRecyclerView = recyclerView;
|
||||
mCallbacks = callbacks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new swipe-to-dismiss OnItemTouchListener for RecyclerView
|
||||
*
|
||||
* @param recyclerView RecyclerView
|
||||
* @param callbacks The callback to trigger when the user has indicated that she would like to
|
||||
* dismiss this view.
|
||||
*/
|
||||
public SwipeToDismissTouchListener(RecyclerView recyclerView, DismissCallbacks callbacks, int[] notToDismiss) {
|
||||
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
|
||||
mSlop = vc.getScaledTouchSlop();
|
||||
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 4;
|
||||
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
|
||||
mAnimationTime = recyclerView.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
|
||||
mRecyclerView = recyclerView;
|
||||
mCallbacks = callbacks;
|
||||
notToDismissPositionArray = notToDismiss;
|
||||
}
|
||||
|
||||
public int[] getNotToDismissPositionArray() {
|
||||
return notToDismissPositionArray;
|
||||
}
|
||||
|
||||
public void setNotToDismissPositionArray(int[] notToDismissPositionArray) {
|
||||
this.notToDismissPositionArray = notToDismissPositionArray;
|
||||
}
|
||||
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
mPaused = !enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
|
||||
motionEvent.offsetLocation(mTranslationX, 0);
|
||||
|
||||
switch (motionEvent.getActionMasked()) {
|
||||
case MotionEvent.ACTION_UP: {
|
||||
up(motionEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case MotionEvent.ACTION_CANCEL: {
|
||||
cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
move(motionEvent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestDisallowInterceptTouchEvent(boolean b) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(final RecyclerView view, MotionEvent motionEvent) {
|
||||
if (mPaused) return false;
|
||||
// offset because the view is translated during swipe
|
||||
motionEvent.offsetLocation(mTranslationX, 0);
|
||||
|
||||
if (mViewWidth < 2) {
|
||||
mViewWidth = view.getWidth();
|
||||
}
|
||||
|
||||
switch (motionEvent.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN: {
|
||||
return down(motionEvent);
|
||||
}
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
return move(motionEvent);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean down(MotionEvent motionEvent) {
|
||||
|
||||
if (mPaused) return false;
|
||||
|
||||
mDownX = motionEvent.getRawX();
|
||||
mDownY = motionEvent.getRawY();
|
||||
mSwipeView = mRecyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
|
||||
if (mSwipeView == null) return false;
|
||||
int pos = mRecyclerView.getChildLayoutPosition(mSwipeView);
|
||||
if (notToDismissPositionArray != null && notToDismissPositionArray.length > 0) {
|
||||
for (int notToDismiss : notToDismissPositionArray) {
|
||||
if (pos == notToDismiss) return false;
|
||||
}
|
||||
}
|
||||
mAllowedSwipeDirection = mCallbacks.dismissDirection(pos);
|
||||
if (mAllowedSwipeDirection != SwipeDirection.NONE) {
|
||||
|
||||
mVelocityTracker = VelocityTracker.obtain();
|
||||
mVelocityTracker.addMovement(motionEvent);
|
||||
return false;
|
||||
}
|
||||
resetMotion();
|
||||
return false;
|
||||
}
|
||||
|
||||
private void cancel() {
|
||||
if (mVelocityTracker == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
mSwipeView.animate()
|
||||
.translationX(0)
|
||||
.alpha(1)
|
||||
.setDuration(mAnimationTime)
|
||||
.setListener(null);
|
||||
mVelocityTracker.recycle();
|
||||
mVelocityTracker = null;
|
||||
mTranslationX = 0;
|
||||
mDownX = 0;
|
||||
mDownY = 0;
|
||||
mSwiping = false;
|
||||
mSwipeView = null;
|
||||
}
|
||||
|
||||
private void up(MotionEvent motionEvent) {
|
||||
if (mPaused || mVelocityTracker == null || mSwipeView == null) {
|
||||
return;
|
||||
}
|
||||
mSwipeView.setPressed(false);
|
||||
float deltaX = motionEvent.getRawX() - mDownX;
|
||||
mVelocityTracker.addMovement(motionEvent);
|
||||
mVelocityTracker.computeCurrentVelocity(1000);
|
||||
float velocityX = mVelocityTracker.getXVelocity();
|
||||
float absVelocityX = Math.abs(velocityX);
|
||||
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
|
||||
boolean dismiss = false;
|
||||
boolean dismissRight = false;
|
||||
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
|
||||
dismiss = true;
|
||||
dismissRight = deltaX > 0;
|
||||
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
|
||||
&& absVelocityY < absVelocityX
|
||||
&& absVelocityY < absVelocityX && mSwiping) {
|
||||
// dismiss only if flinging in the same direction as dragging
|
||||
dismiss = (velocityX < 0) == (deltaX < 0);
|
||||
dismissRight = mVelocityTracker.getXVelocity() > 0;
|
||||
}
|
||||
if (dismiss) {
|
||||
// dismiss
|
||||
final int pos = mRecyclerView.getChildLayoutPosition(mSwipeView);
|
||||
final View swipeViewCopy = mSwipeView;
|
||||
final SwipeDirection swipeDirection = dismissRight ? SwipeDirection.RIGHT : SwipeDirection.LEFT;
|
||||
++mDismissCount;
|
||||
mSwipeView.animate()
|
||||
.translationX(dismissRight ? mViewWidth : -mViewWidth)
|
||||
.alpha(0)
|
||||
.setDuration(mAnimationTime);
|
||||
|
||||
//this is instead of unreliable onAnimationEnd callback
|
||||
swipeViewCopy.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
performDismiss(swipeViewCopy, pos, swipeDirection);
|
||||
swipeViewCopy.setTranslationX(0);
|
||||
// swipeViewCopy.setAlpha(1);
|
||||
|
||||
}
|
||||
}, mAnimationTime + 100);
|
||||
|
||||
} else if (mSwiping) {
|
||||
// cancel
|
||||
mSwipeView.animate()
|
||||
.translationX(0)
|
||||
.alpha(1)
|
||||
.setDuration(mAnimationTime)
|
||||
.setListener(null);
|
||||
}
|
||||
|
||||
|
||||
resetMotion();
|
||||
}
|
||||
|
||||
private boolean move(MotionEvent motionEvent) {
|
||||
if (mSwipeView == null || mVelocityTracker == null || mPaused) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mVelocityTracker.addMovement(motionEvent);
|
||||
float deltaX = motionEvent.getRawX() - mDownX;
|
||||
float deltaY = motionEvent.getRawY() - mDownY;
|
||||
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
|
||||
mSwiping = true;
|
||||
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
|
||||
mSwipeView.setPressed(false);
|
||||
|
||||
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
|
||||
cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
|
||||
mSwipeView.onTouchEvent(cancelEvent);
|
||||
}
|
||||
|
||||
//Prevent swipes to disallowed directions
|
||||
if ((deltaX < 0 && mAllowedSwipeDirection == SwipeDirection.RIGHT) || (deltaX > 0 && mAllowedSwipeDirection == SwipeDirection.LEFT)) {
|
||||
resetMotion();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mSwiping) {
|
||||
mCallbacks.onTouchDown();
|
||||
mTranslationX = deltaX;
|
||||
mSwipeView.setTranslationX(deltaX - mSwipingSlop);
|
||||
mSwipeView.setAlpha(Math.max(0f, Math.min(1f,
|
||||
1f - 2f * Math.abs(deltaX) / mViewWidth)));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void resetMotion() {
|
||||
if (mVelocityTracker != null) {
|
||||
mVelocityTracker.recycle();
|
||||
mVelocityTracker = null;
|
||||
}
|
||||
mCallbacks.onResetMotion();
|
||||
mTranslationX = 0;
|
||||
mDownX = 0;
|
||||
mDownY = 0;
|
||||
mSwiping = false;
|
||||
mSwipeView = null;
|
||||
mAllowedSwipeDirection = SwipeDirection.NONE;
|
||||
}
|
||||
|
||||
private void performDismiss(View dismissView, int pos, SwipeDirection direction) {
|
||||
--mDismissCount;
|
||||
mPendingDismisses.add(new PendingDismissData(pos, dismissView, direction));
|
||||
if (mDismissCount == 0) {
|
||||
Collections.sort(mPendingDismisses);
|
||||
List<PendingDismissData> dismissData = new ArrayList<>(mPendingDismisses);
|
||||
mCallbacks.onDismiss(mRecyclerView, dismissData);
|
||||
mPendingDismisses.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public interface DismissCallbacks {
|
||||
SwipeDirection dismissDirection(int position);
|
||||
|
||||
void onDismiss(RecyclerView view, List<PendingDismissData> dismissData);
|
||||
|
||||
void onResetMotion();
|
||||
|
||||
void onTouchDown();
|
||||
}
|
||||
|
||||
|
||||
public class PendingDismissData implements Comparable<PendingDismissData> {
|
||||
public int position;
|
||||
public View view;
|
||||
public SwipeDirection direction;
|
||||
|
||||
public PendingDismissData(int position, View view, SwipeDirection direction) {
|
||||
this.position = position;
|
||||
this.view = view;
|
||||
this.direction = direction;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(@NonNull PendingDismissData other) {
|
||||
return other.position - position;
|
||||
}
|
||||
}
|
||||
|
||||
public enum SwipeDirection {
|
||||
LEFT, RIGHT, BOTH, NONE
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
LOCAL_PATH := $(call my-dir)
|
||||
|
||||
##################################################
|
||||
### libjpeg-turbo ###
|
||||
##################################################
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := libjpeg-turbo
|
||||
LOCAL_SRC_FILES:= \
|
||||
libjpeg-turbo/jaricom.c \
|
||||
libjpeg-turbo/jcomapi.c \
|
||||
libjpeg-turbo/jdapimin.c \
|
||||
libjpeg-turbo/jdapistd.c \
|
||||
libjpeg-turbo/jdarith.c \
|
||||
libjpeg-turbo/jdatadst.c \
|
||||
libjpeg-turbo/jdatadst-tj.c \
|
||||
libjpeg-turbo/jdatasrc.c \
|
||||
libjpeg-turbo/jdatasrc-tj.c \
|
||||
libjpeg-turbo/jdcoefct.c \
|
||||
libjpeg-turbo/jdcolor.c \
|
||||
libjpeg-turbo/jddctmgr.c \
|
||||
libjpeg-turbo/jdhuff.c \
|
||||
libjpeg-turbo/jdinput.c \
|
||||
libjpeg-turbo/jdmainct.c \
|
||||
libjpeg-turbo/jdmarker.c \
|
||||
libjpeg-turbo/jdmaster.c \
|
||||
libjpeg-turbo/jdmerge.c \
|
||||
libjpeg-turbo/jdphuff.c \
|
||||
libjpeg-turbo/jdpostct.c \
|
||||
libjpeg-turbo/jdsample.c \
|
||||
libjpeg-turbo/jdtrans.c \
|
||||
libjpeg-turbo/jerror.c \
|
||||
libjpeg-turbo/jfdctflt.c \
|
||||
libjpeg-turbo/jfdctfst.c \
|
||||
libjpeg-turbo/jfdctint.c \
|
||||
libjpeg-turbo/jidctflt.c \
|
||||
libjpeg-turbo/jidctfst.c \
|
||||
libjpeg-turbo/jidctint.c \
|
||||
libjpeg-turbo/jidctred.c \
|
||||
libjpeg-turbo/jmemmgr.c \
|
||||
libjpeg-turbo/jmemnobs.c \
|
||||
libjpeg-turbo/jquant1.c \
|
||||
libjpeg-turbo/jquant2.c \
|
||||
libjpeg-turbo/jutils.c
|
||||
LOCAL_CFLAGS := -O3 -DANDROID
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),$(filter $(TARGET_ARCH_ABI), armeabi armeabi-v7a))
|
||||
# Don't add -mfpu=neon
|
||||
# Some arm v7 cpu do not support neon,
|
||||
# libjpeg-turbo can check neon in init_simd()
|
||||
# through parse_proc_cpuinfo()
|
||||
#LOCAL_CFLAGS += -mfpu=neon
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/simd/jsimd_arm.c \
|
||||
libjpeg-turbo/simd/jsimd_arm_neon.S
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/simd/jsimd_arm64.c \
|
||||
libjpeg-turbo/simd/jsimd_arm64_neon.S
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),x86)
|
||||
LOCAL_ASMFLAGS := -DELF -DPIC
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/simd/jsimd_i386.c \
|
||||
libjpeg-turbo/simd/jsimdcpu.asm \
|
||||
libjpeg-turbo/simd/jfdctflt-3dn.asm \
|
||||
libjpeg-turbo/simd/jidctflt-3dn.asm \
|
||||
libjpeg-turbo/simd/jquant-3dn.asm \
|
||||
libjpeg-turbo/simd/jccolor-mmx.asm \
|
||||
libjpeg-turbo/simd/jcgray-mmx.asm \
|
||||
libjpeg-turbo/simd/jcsample-mmx.asm \
|
||||
libjpeg-turbo/simd/jdcolor-mmx.asm \
|
||||
libjpeg-turbo/simd/jdmerge-mmx.asm \
|
||||
libjpeg-turbo/simd/jdsample-mmx.asm \
|
||||
libjpeg-turbo/simd/jfdctfst-mmx.asm \
|
||||
libjpeg-turbo/simd/jfdctint-mmx.asm \
|
||||
libjpeg-turbo/simd/jidctfst-mmx.asm \
|
||||
libjpeg-turbo/simd/jidctint-mmx.asm \
|
||||
libjpeg-turbo/simd/jidctred-mmx.asm \
|
||||
libjpeg-turbo/simd/jquant-mmx.asm \
|
||||
libjpeg-turbo/simd/jfdctflt-sse.asm \
|
||||
libjpeg-turbo/simd/jidctflt-sse.asm \
|
||||
libjpeg-turbo/simd/jquant-sse.asm \
|
||||
libjpeg-turbo/simd/jccolor-sse2.asm \
|
||||
libjpeg-turbo/simd/jcgray-sse2.asm \
|
||||
libjpeg-turbo/simd/jcsample-sse2.asm \
|
||||
libjpeg-turbo/simd/jdcolor-sse2.asm \
|
||||
libjpeg-turbo/simd/jdmerge-sse2.asm \
|
||||
libjpeg-turbo/simd/jdsample-sse2.asm \
|
||||
libjpeg-turbo/simd/jfdctfst-sse2.asm \
|
||||
libjpeg-turbo/simd/jfdctint-sse2.asm \
|
||||
libjpeg-turbo/simd/jidctflt-sse2.asm \
|
||||
libjpeg-turbo/simd/jidctfst-sse2.asm \
|
||||
libjpeg-turbo/simd/jidctint-sse2.asm \
|
||||
libjpeg-turbo/simd/jidctred-sse2.asm \
|
||||
libjpeg-turbo/simd/jquantf-sse2.asm \
|
||||
libjpeg-turbo/simd/jquanti-sse2.asm
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),x86_64)
|
||||
LOCAL_ASMFLAGS := -D__x86_64__ -DELF -DPIC
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/simd/jsimd_x86_64.c \
|
||||
libjpeg-turbo/simd/jfdctflt-sse-64.asm \
|
||||
libjpeg-turbo/simd/jccolor-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jcgray-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jcsample-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jdcolor-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jdmerge-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jdsample-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jfdctfst-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jfdctint-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jidctflt-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jidctfst-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jidctint-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jidctred-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jquantf-sse2-64.asm \
|
||||
libjpeg-turbo/simd/jquanti-sse2-64.asm
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),mips)
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/simd/jsimd_mips.c \
|
||||
libjpeg-turbo/simd/jsimd_mips_dspr2.S
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),mips64)
|
||||
LOCAL_SRC_FILES += \
|
||||
libjpeg-turbo/jsimd_none.c
|
||||
endif
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
|
||||
##################################################
|
||||
### libz ###
|
||||
##################################################
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := libz
|
||||
LOCAL_SRC_FILES := \
|
||||
zlib/adler32.c \
|
||||
zlib/crc32.c \
|
||||
zlib/inffast.c \
|
||||
zlib/inflate.c \
|
||||
zlib/inftrees.c \
|
||||
zlib/trees.c \
|
||||
zlib/zutil.c
|
||||
LOCAL_CFLAGS := -O3 -DANDROID
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
|
||||
##################################################
|
||||
### libpng ###
|
||||
##################################################
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := libpng
|
||||
LOCAL_SRC_FILES := \
|
||||
libpng/png.c \
|
||||
libpng/pngerror.c \
|
||||
libpng/pngget.c \
|
||||
libpng/pngmem.c \
|
||||
libpng/pngpread.c \
|
||||
libpng/pngread.c \
|
||||
libpng/pngrio.c \
|
||||
libpng/pngrtran.c \
|
||||
libpng/pngrutil.c \
|
||||
libpng/pngset.c \
|
||||
libpng/pngtrans.c
|
||||
LOCAL_CFLAGS := -O3 -DANDROID
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
|
||||
# Add -mfpu=neon
|
||||
# libpng only check neon when add -mfpu=neon
|
||||
LOCAL_CFLAGS += -mfpu=neon
|
||||
endif
|
||||
|
||||
ifeq ($(TARGET_ARCH_ABI),$(filter $(TARGET_ARCH_ABI), armeabi armeabi-v7a arm64-v8a))
|
||||
LOCAL_SRC_FILES += \
|
||||
libpng/arm/arm_init.c \
|
||||
libpng/arm/filter_neon_intrinsics.c \
|
||||
libpng/arm/filter_neon.S
|
||||
endif
|
||||
|
||||
LOCAL_STATIC_LIBRARIES := libz
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
|
||||
##################################################
|
||||
### libgif ###
|
||||
##################################################
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := libgif
|
||||
LOCAL_SRC_FILES := \
|
||||
giflib/dgif_lib.c \
|
||||
giflib/gif_hash.c \
|
||||
giflib/gifalloc.c
|
||||
LOCAL_CFLAGS := -O3 -DANDROID
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
|
||||
##################################################
|
||||
### libimage ###
|
||||
##################################################
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
RELEASE_FLAG := true
|
||||
|
||||
LOCAL_MODULE := libimage
|
||||
LOCAL_SRC_FILES := \
|
||||
image.c \
|
||||
jpeg.c \
|
||||
png.c \
|
||||
gif.c \
|
||||
utils.c
|
||||
LOCAL_CFLAGS := -O3 -DANDROID
|
||||
LOCAL_STATIC_LIBRARIES := libjpeg-turbo libpng libgif
|
||||
LOCAL_LDLIBS := -lGLESv2
|
||||
|
||||
ifdef RELEASE_FLAG
|
||||
LOCAL_CFLAGS += -DRELEASE
|
||||
else
|
||||
LOCAL_LDLIBS += -llog
|
||||
endif
|
||||
|
||||
include $(BUILD_SHARED_LIBRARY)
|
||||
@@ -0,0 +1,3 @@
|
||||
APP_ABI := armeabi armeabi-v7a x86
|
||||
APP_PLATFORM := android-9
|
||||
APP_OPTIM := release
|
||||
@@ -0,0 +1,574 @@
|
||||
#include "gif.h"
|
||||
#include "utils.h"
|
||||
|
||||
//#define STRICT_FORMAT_89A
|
||||
|
||||
#define USE_PIXELS 0
|
||||
#define USE_BAK 1
|
||||
#define SET_BG 2
|
||||
|
||||
static int errorCode;
|
||||
|
||||
// TODO is GIF87a work fine ?
|
||||
|
||||
/*
|
||||
* Return NULL if error
|
||||
*/
|
||||
static JNIEnv* getEnv(GifFileType* gif) {
|
||||
if (gif == NULL)
|
||||
return NULL;
|
||||
|
||||
JNIEnv* env = NULL;
|
||||
StreamContainer* sc = (StreamContainer*) (gif->UserData);
|
||||
if (sc != NULL) {
|
||||
JavaVM* jvm = sc->jvm;
|
||||
(*jvm)->AttachCurrentThread(jvm, &env, NULL);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
static int streamReadFun(GifFileType* gif, GifByteType* bytes, int size) {
|
||||
StreamContainer* sc = (StreamContainer*) gif->UserData;
|
||||
JNIEnv* env = getEnv(gif);
|
||||
|
||||
if (env == NULL)
|
||||
return 0;
|
||||
|
||||
(*env)->MonitorEnter(env, sc->stream);
|
||||
|
||||
if (sc->buffer == NULL) {
|
||||
jbyteArray buffer = (*env)->NewByteArray(env, size < 256 ? 256 : size);
|
||||
sc->buffer = (jbyteArray) (*env)->NewGlobalRef(env, buffer);
|
||||
} else {
|
||||
jsize bufLen = (*env)->GetArrayLength(env, sc->buffer);
|
||||
if (bufLen < size) {
|
||||
(*env)->DeleteGlobalRef(env, sc->buffer);
|
||||
sc->buffer = NULL;
|
||||
|
||||
jbyteArray buffer = (*env)->NewByteArray(env, size);
|
||||
sc->buffer = (*env)->NewGlobalRef(env, buffer);
|
||||
}
|
||||
}
|
||||
|
||||
int len = (*env)->CallIntMethod(env, sc->stream, sc->readMID, sc->buffer, 0,
|
||||
size);
|
||||
if ((*env)->ExceptionOccurred(env)) {
|
||||
(*env)->ExceptionClear(env);
|
||||
len = 0;
|
||||
} else if (len > 0) {
|
||||
(*env)->GetByteArrayRegion(env, sc->buffer, 0, len, bytes);
|
||||
}
|
||||
|
||||
(*env)->MonitorExit(env, sc->stream);
|
||||
|
||||
return len >= 0 ? len : 0;
|
||||
}
|
||||
|
||||
static int fileReadFun(GifFileType* gif, GifByteType* bytes, int size) {
|
||||
FILE* fp = (FILE*) gif->UserData;
|
||||
return fread(bytes, 1, size, fp);
|
||||
}
|
||||
|
||||
/*
|
||||
* stack store the index to draw
|
||||
* stack capacity should be imageCount * sizeof(int).
|
||||
* When read it, use from tail to head
|
||||
*/
|
||||
static void getDrawStack(GIF* gif, int targetIndex, int* which, int* stack,
|
||||
int* stackSize) {
|
||||
int i;
|
||||
int *disposals = gif->disposals;
|
||||
int pxlIndex = gif->pxlIndex;
|
||||
int bakIndex = gif->bakIndex;
|
||||
|
||||
*which = SET_BG;
|
||||
*stackSize = 0;
|
||||
|
||||
for (i = targetIndex; i >= 0;) {
|
||||
if (i == pxlIndex) {
|
||||
*which = USE_PIXELS;
|
||||
break;
|
||||
} else if (i == bakIndex) {
|
||||
*which = USE_BAK;
|
||||
break;
|
||||
}
|
||||
|
||||
// Add index to stack
|
||||
stack[*stackSize] = i;
|
||||
(*stackSize)++;
|
||||
|
||||
// If it is first index, break;
|
||||
if (i == 0)
|
||||
break;
|
||||
|
||||
switch (disposals[--i]) {
|
||||
case DISPOSAL_UNSPECIFIED:
|
||||
case DISPOSE_DO_NOT:
|
||||
break;
|
||||
case DISPOSE_BACKGROUND:
|
||||
// Just out of while(),
|
||||
i = -1;
|
||||
break;
|
||||
case DISPOSE_PREVIOUS:
|
||||
i--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static inline bool getColorFromTableRGB(const ColorMapObject* cmap, int index,
|
||||
rgb* color) {
|
||||
if (cmap == NULL || index < 0 || index >= cmap->ColorCount)
|
||||
return false;
|
||||
GifColorType gct = cmap->Colors[index];
|
||||
color->red = gct.Red;
|
||||
color->green = gct.Green;
|
||||
color->blue = gct.Blue;
|
||||
return true;
|
||||
}
|
||||
|
||||
static inline bool getColorFromTableRGBA(const ColorMapObject* cmap, int index,
|
||||
rgba* color) {
|
||||
if (cmap == NULL || index < 0 || index >= cmap->ColorCount)
|
||||
return false;
|
||||
GifColorType gct = cmap->Colors[index];
|
||||
color->red = gct.Red;
|
||||
color->green = gct.Green;
|
||||
color->blue = gct.Blue;
|
||||
color->alpha = 0xff;
|
||||
return true;
|
||||
}
|
||||
|
||||
static inline bool getColorFromTableLUM(const ColorMapObject* cmap, int index,
|
||||
lum* color) {
|
||||
if (cmap == NULL || index < 0 || index >= cmap->ColorCount)
|
||||
return false;
|
||||
GifColorType gct = cmap->Colors[index];
|
||||
color->l = getVFrowRGB(gct.Red, gct.Green, gct.Blue);
|
||||
return true;
|
||||
}
|
||||
|
||||
static inline bool getColorFromTableLUMA(const ColorMapObject* cmap, int index,
|
||||
luma* color) {
|
||||
if (cmap == NULL || index < 0 || index >= cmap->ColorCount)
|
||||
return false;
|
||||
GifColorType gct = cmap->Colors[index];
|
||||
color->l = getVFrowRGB(gct.Red, gct.Green, gct.Blue);
|
||||
color->a = 0xff;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void setBgRGB(GIF* gif, rgb* pixels) {
|
||||
GifFileType* gifFile = gif->gifFile;
|
||||
int num = gifFile->SWidth * gifFile->SHeight;
|
||||
int size = num * sizeof(rgb);
|
||||
rgb color;
|
||||
if (getColorFromTableRGB(gifFile->SColorMap, gifFile->SBackGroundColor, &color))
|
||||
eraseRGB(pixels, num, color);
|
||||
else
|
||||
memset(pixels, BG_LUM, size);
|
||||
}
|
||||
|
||||
static void setBgRGBA(GIF* gif, rgba* pixels) {
|
||||
GifFileType* gifFile = gif->gifFile;
|
||||
int num = gifFile->SWidth * gifFile->SHeight;
|
||||
int size = num * sizeof(rgba);
|
||||
rgba color;
|
||||
if (getColorFromTableRGBA(gifFile->SColorMap, gifFile->SBackGroundColor, &color)) {
|
||||
eraseRGBA(pixels, num, color);
|
||||
color.red = BG_LUM;
|
||||
color.green = BG_LUM;
|
||||
color.blue = BG_LUM;
|
||||
color.red = 0xff;
|
||||
}
|
||||
eraseRGBA(pixels, num, color);
|
||||
}
|
||||
|
||||
static void setBgLUM(GIF* gif, lum* pixels) {
|
||||
GifFileType* gifFile = gif->gifFile;
|
||||
int num = gifFile->SWidth * gifFile->SHeight;
|
||||
int size = num * sizeof(lum);
|
||||
lum color;
|
||||
if (getColorFromTableLUM(gifFile->SColorMap, gifFile->SBackGroundColor, &color))
|
||||
eraseLUM(pixels, num, color);
|
||||
else
|
||||
memset(pixels, BG_LUM, size);
|
||||
}
|
||||
|
||||
static void setBgLUMA(GIF* gif, luma* pixels) {
|
||||
GifFileType* gifFile = gif->gifFile;
|
||||
int num = gifFile->SWidth * gifFile->SHeight;
|
||||
int size = num * sizeof(lum);
|
||||
luma color;
|
||||
if (!getColorFromTableLUMA(gifFile->SColorMap, gifFile->SBackGroundColor, &color)) {
|
||||
color.l = BG_LUM;
|
||||
color.a = 0xff;
|
||||
}
|
||||
eraseLUMA(pixels, num, color);
|
||||
}
|
||||
|
||||
static void setBg(GIF* gif, void* pixels) {
|
||||
switch (gif->format) {
|
||||
case GL_RGB:
|
||||
setBgRGB(gif, pixels);
|
||||
break;
|
||||
case GL_RGBA:
|
||||
setBgRGBA(gif, pixels);
|
||||
break;
|
||||
case GL_LUMINANCE:
|
||||
setBgLUM(gif, pixels);
|
||||
break;
|
||||
case GL_LUMINANCE_ALPHA:
|
||||
setBgLUMA(gif, pixels);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static inline void copyLineRGB(GifByteType* src, rgb* dst,
|
||||
const ColorMapObject* cmap, int tran, int width) {
|
||||
for (; width > 0; width--, src++, dst++) {
|
||||
int index = *src;
|
||||
if (tran == -1 || *src != tran)
|
||||
getColorFromTableRGB(cmap, *src, dst);
|
||||
}
|
||||
}
|
||||
|
||||
static inline void copyLineRGBA(GifByteType* src, rgba* dst,
|
||||
const ColorMapObject* cmap, int tran, int width) {
|
||||
for (; width > 0; width--, src++, dst++) {
|
||||
int index = *src;
|
||||
if (tran == -1 || *src != tran)
|
||||
getColorFromTableRGBA(cmap, *src, dst);
|
||||
}
|
||||
}
|
||||
|
||||
static inline void copyLineLUM(GifByteType* src, lum* dst,
|
||||
const ColorMapObject* cmap, int tran, int width) {
|
||||
for (; width > 0; width--, src++, dst++) {
|
||||
int index = *src;
|
||||
if (tran == -1 || *src != tran)
|
||||
getColorFromTableLUM(cmap, *src, dst);
|
||||
}
|
||||
}
|
||||
|
||||
static inline void copyLineLUMA(GifByteType* src, luma* dst,
|
||||
const ColorMapObject* cmap, int tran, int width) {
|
||||
for (; width > 0; width--, src++, dst++) {
|
||||
int index = *src;
|
||||
if (tran == -1 || *src != tran)
|
||||
getColorFromTableLUMA(cmap, *src, dst);
|
||||
}
|
||||
}
|
||||
|
||||
static void drawFrame(GIF* gif, void* pixels, int index) {
|
||||
GifFileType* gifFile = gif->gifFile;
|
||||
int ScreenWidth = gifFile->SWidth;
|
||||
int ScreenHeight = gifFile->SHeight;
|
||||
SavedImage cur = gifFile->SavedImages[index];
|
||||
GifImageDesc gid = cur.ImageDesc;
|
||||
ColorMapObject *cmap = gid.ColorMap;
|
||||
int tran = gif->trans[index];
|
||||
GifByteType* src;
|
||||
rgb* dst1;
|
||||
rgba* dst2;
|
||||
lum* dst3;
|
||||
luma* dst4;
|
||||
|
||||
if (cmap == NULL)
|
||||
cmap = gifFile->SColorMap;
|
||||
if (cmap != NULL) {
|
||||
src = cur.RasterBits;
|
||||
int copyWidth = gid.Width;
|
||||
int copyHeight = gid.Height;
|
||||
if (copyWidth + gid.Left > ScreenWidth)
|
||||
copyWidth = ScreenWidth - gid.Left;
|
||||
if (copyHeight + gid.Top > ScreenHeight)
|
||||
copyHeight = ScreenHeight - gid.Top;
|
||||
|
||||
if (copyWidth > 0 && copyHeight > 0) {
|
||||
switch (gif->format) {
|
||||
case GL_RGB:
|
||||
dst1 = (rgb*)pixels + gid.Top * ScreenWidth + gid.Left;
|
||||
for (; copyHeight > 0; copyHeight--, src += gid.Width, dst1 += ScreenWidth)
|
||||
copyLineRGB(src, dst1, cmap, tran, copyWidth);
|
||||
break;
|
||||
case GL_RGBA:
|
||||
dst2 = (rgba*)pixels + gid.Top * ScreenWidth + gid.Left;
|
||||
for (; copyHeight > 0; copyHeight--, src += gid.Width, dst2 += ScreenWidth)
|
||||
copyLineRGBA(src, dst2, cmap, tran, copyWidth);
|
||||
break;
|
||||
case GL_LUMINANCE:
|
||||
dst3 = (lum*)pixels + gid.Top * ScreenWidth + gid.Left;
|
||||
for (; copyHeight > 0; copyHeight--, src += gid.Width, dst3 += ScreenWidth)
|
||||
copyLineLUM(src, dst3, cmap, tran, copyWidth);
|
||||
break;
|
||||
case GL_LUMINANCE_ALPHA:
|
||||
dst4 = (luma*)pixels + gid.Top * ScreenWidth + gid.Left;
|
||||
for (; copyHeight > 0; copyHeight--, src += gid.Width, dst4 += ScreenWidth)
|
||||
copyLineLUMA(src, dst4, cmap, tran, copyWidth);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void render(GIF* gif, int index) {
|
||||
|
||||
int i;
|
||||
int width = gif->gifFile->SWidth;
|
||||
int height = gif->gifFile->SHeight;
|
||||
int imageCount = gif->gifFile->ImageCount;
|
||||
int which, stackSize;
|
||||
int stack[imageCount];
|
||||
void* tempPoint;
|
||||
int tempInt;
|
||||
|
||||
getDrawStack(gif, index, &which, stack, &stackSize);
|
||||
|
||||
// prepare pixels
|
||||
switch (which) {
|
||||
case USE_PIXELS:
|
||||
break;
|
||||
case USE_BAK:
|
||||
// switch pixel and bak
|
||||
tempPoint = gif->bak;
|
||||
gif->bak = gif->pixels;
|
||||
gif->pixels = tempPoint;
|
||||
tempInt = gif->bakIndex;
|
||||
gif->bakIndex = gif->pxlIndex;
|
||||
gif->pxlIndex = tempInt;
|
||||
break;
|
||||
case SET_BG:
|
||||
// Set bg
|
||||
setBg(gif, gif->pixels);
|
||||
break;
|
||||
}
|
||||
|
||||
// Draw frame
|
||||
for (stackSize--; stackSize >= 0; stackSize--)
|
||||
drawFrame(gif, gif->pixels, stack[stackSize]);
|
||||
|
||||
// render in screen
|
||||
glTexSubImage2D(DEFAULT_TARGET, 0, 0, 0, width,
|
||||
height, gif->format, DEFAULT_TYPE, gif->pixels);
|
||||
|
||||
// update pxlIndex
|
||||
gif->pxlIndex = index;
|
||||
|
||||
// Set back if necessary
|
||||
if (index + 1 < imageCount && gif->disposals[index + 1] == DISPOSE_PREVIOUS &&
|
||||
gif->bakIndex != gif->pxlIndex) {
|
||||
int size;
|
||||
switch (gif->format) {
|
||||
case GL_RGB:
|
||||
size = width * height * sizeof(rgb);
|
||||
break;
|
||||
case GL_RGBA:
|
||||
size = width * height * sizeof(rgba);
|
||||
break;
|
||||
case GL_LUMINANCE:
|
||||
size = width * height * sizeof(lum);
|
||||
break;
|
||||
case GL_LUMINANCE_ALPHA:
|
||||
size = width * height * sizeof(luma);
|
||||
break;
|
||||
}
|
||||
if (gif->bak == NULL)
|
||||
gif->bak = malloc(size);
|
||||
if (gif->bak != NULL) {
|
||||
memcpy(gif->bak, gif->pixels, size);
|
||||
gif->bakIndex = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static GIF* analysisGifFileType(GifFileType* gifFile, int format, int* delays) {
|
||||
|
||||
int i;
|
||||
int* trans;
|
||||
int* disposals;
|
||||
GIF* gif;
|
||||
GraphicsControlBlock gcb;
|
||||
|
||||
int imageCount = gifFile->ImageCount;
|
||||
|
||||
gif = (GIF*) malloc(sizeof(GIF));
|
||||
if (gif == NULL)
|
||||
return NULL;
|
||||
|
||||
gif->gifFile = gifFile;
|
||||
gif->trans = (int*) malloc(imageCount * sizeof(int));
|
||||
gif->disposals = (int*) malloc(imageCount * sizeof(int));
|
||||
gif->format = format;
|
||||
switch (format) {
|
||||
case GL_RGB:
|
||||
gif->pixels = malloc(gifFile->SWidth * gifFile->SHeight * sizeof(rgb));
|
||||
break;
|
||||
case GL_RGBA:
|
||||
gif->pixels = malloc(gifFile->SWidth * gifFile->SHeight * sizeof(rgba));
|
||||
break;
|
||||
case GL_LUMINANCE:
|
||||
gif->pixels = malloc(gifFile->SWidth * gifFile->SHeight * sizeof(lum));
|
||||
break;
|
||||
case GL_LUMINANCE_ALPHA:
|
||||
gif->pixels = malloc(gifFile->SWidth * gifFile->SHeight * sizeof(luma));
|
||||
break;
|
||||
}
|
||||
gif->pxlIndex = -1;
|
||||
gif->bak = NULL;
|
||||
gif->bakIndex = -1;
|
||||
|
||||
if (gif->trans == NULL || gif->disposals == NULL || gif->pixels == NULL) {
|
||||
free(gif->pixels);
|
||||
free(gif->disposals);
|
||||
free(gif->trans);
|
||||
free(gif);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
trans = gif->trans;
|
||||
disposals = gif->disposals;
|
||||
for (i = 0; i < imageCount; i++) {
|
||||
if (DGifSavedExtensionToGCB(gifFile, i, &gcb) != GIF_OK) {
|
||||
delays[i] = DEFAULT_DELAY;
|
||||
trans[i] = -1;
|
||||
disposals[i] = 0;
|
||||
} else {
|
||||
delays[i] = gcb.DelayTime * 10;
|
||||
trans[i] = gcb.TransparentColor;
|
||||
disposals[i] = gcb.DisposalMode;
|
||||
if (delays[i] <= 0)
|
||||
delays[i] = DEFAULT_DELAY;
|
||||
}
|
||||
}
|
||||
|
||||
return gif;
|
||||
}
|
||||
|
||||
jobject getObjFromGifFileType(JNIEnv* env, GifFileType* gifFile, int format) {
|
||||
|
||||
int realWidth, slurp, imageCount;
|
||||
int* delays;
|
||||
GIF* gif;
|
||||
jintArray delayArray;
|
||||
jclass gifClazz;
|
||||
jmethodID constructor;
|
||||
|
||||
// Fix width, for not RGBA, but I will tell others the real width
|
||||
realWidth = gifFile->SWidth;
|
||||
if (format != GL_RGBA)
|
||||
gifFile->SWidth = nextMulOf4(realWidth);
|
||||
|
||||
// Slurp
|
||||
slurp = DGifSlurp(gifFile);
|
||||
#ifdef STRICT_FORMAT_89A
|
||||
if (slurp != GIF_OK)
|
||||
return NULL;
|
||||
#endif
|
||||
|
||||
// Check image count
|
||||
imageCount = gifFile->ImageCount;
|
||||
if (imageCount < 1)
|
||||
return NULL;
|
||||
|
||||
// delays malloc
|
||||
delays = (int*) malloc(imageCount * sizeof(int));
|
||||
if (delays == NULL)
|
||||
return NULL;
|
||||
|
||||
// analysis GifFileType
|
||||
gif = analysisGifFileType(gifFile, format, delays);
|
||||
if (gif == NULL) {
|
||||
free(delays);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Copy value
|
||||
delayArray = (*env)->NewIntArray(env, imageCount);
|
||||
(*env)->SetIntArrayRegion(env, delayArray, 0, imageCount, delays);
|
||||
free(delays);
|
||||
|
||||
gifClazz = (*env)->FindClass(env,
|
||||
"com/hippo/ehviewer/gallery/image/GifImage");
|
||||
constructor = (*env)->GetMethodID(env, gifClazz, "<init>",
|
||||
"(JIIIII[I)V");
|
||||
if (constructor == 0) {
|
||||
GIF_Free((JNIEnv*)NULL, gif);
|
||||
return NULL;
|
||||
} else {
|
||||
return (*env)->NewObject(env, gifClazz, constructor, (jlong) (intptr_t) gif,
|
||||
FILE_FORMAT_GIF, realWidth, gifFile->SHeight, format,
|
||||
DEFAULT_TYPE, delayArray);
|
||||
}
|
||||
}
|
||||
|
||||
jobject GIF_DecodeStream(JNIEnv* env, jobject is, jint format) {
|
||||
|
||||
StreamContainer* sc;
|
||||
GifFileType* gifFile;
|
||||
jobject gifImage;
|
||||
|
||||
if (format == FORMAT_AUTO)
|
||||
format = FORMAT_RGB;
|
||||
|
||||
sc = getStreamContainer(env, is);
|
||||
if (sc == NULL)
|
||||
return NULL;
|
||||
|
||||
// Open gif file
|
||||
gifFile = DGifOpen(sc, &streamReadFun, &errorCode);
|
||||
if (gifFile == NULL) {
|
||||
closeStreamContainer(env, sc);
|
||||
clearException(env);
|
||||
freeStreamContainer(env, sc);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
gifImage = getObjFromGifFileType(env, gifFile, format);
|
||||
if (gifImage == NULL)
|
||||
DGifCloseFile(gifFile, &errorCode);
|
||||
|
||||
closeStreamContainer(env, sc);
|
||||
clearException(env);
|
||||
freeStreamContainer(env, sc);
|
||||
|
||||
return gifImage;
|
||||
}
|
||||
|
||||
jobject GIF_DecodeFileHandler(JNIEnv* env, FILE* fp, jint format) {
|
||||
|
||||
GifFileType* gifFile;
|
||||
jobject gifImage;
|
||||
|
||||
if (format == FORMAT_AUTO)
|
||||
format = FORMAT_RGB;
|
||||
|
||||
gifFile = DGifOpen(fp, &fileReadFun, &errorCode);
|
||||
if (gifFile == NULL)
|
||||
return NULL;
|
||||
|
||||
gifImage = getObjFromGifFileType(env, gifFile, format);
|
||||
if (gifImage == NULL)
|
||||
DGifCloseFile(gifFile, &errorCode);
|
||||
|
||||
return gifImage;
|
||||
}
|
||||
|
||||
void GIF_Render(JNIEnv* env, GIF* gif, int format, int index) {
|
||||
|
||||
if (format != gif->format)
|
||||
return;
|
||||
|
||||
render(gif, index);
|
||||
}
|
||||
|
||||
void GIF_Free(JNIEnv* env, GIF* gif) {
|
||||
|
||||
DGifCloseFile(gif->gifFile, &errorCode);
|
||||
free(gif->trans);
|
||||
free(gif->disposals);
|
||||
free(gif->pixels);
|
||||
free(gif->bak);
|
||||
free(gif);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef GIF_H_
|
||||
#define GIF_H_
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#include "image.h"
|
||||
#include "giflib/gif_lib.h"
|
||||
|
||||
#define DEFAULT_DELAY 100
|
||||
|
||||
typedef struct {
|
||||
GifFileType* gifFile;
|
||||
int* trans;
|
||||
int* disposals;
|
||||
int format;
|
||||
void* pixels;
|
||||
int pxlIndex;
|
||||
void* bak;
|
||||
int bakIndex;
|
||||
} GIF;
|
||||
|
||||
jobject GIF_DecodeStream(JNIEnv* env, jobject is, jint format);
|
||||
jobject GIF_DecodeFileHandler(JNIEnv* env, FILE* fp, jint format);
|
||||
void GIF_Render(JNIEnv* env, GIF* gif, int format, int index);
|
||||
void GIF_Free(JNIEnv* env, GIF* gif);
|
||||
|
||||
#endif /* GIF_H_ */
|
||||
@@ -0,0 +1,72 @@
|
||||
/* config.h. Generated from config.h.in by configure. */
|
||||
/* config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#define HAVE_DLFCN_H 1
|
||||
|
||||
/* Define to 1 if you have the <fcntl.h> header file. */
|
||||
#define HAVE_FCNTL_H 1
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#define HAVE_INTTYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <limits.h> header file. */
|
||||
#define HAVE_LIMITS_H 1
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#define HAVE_MEMORY_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdarg.h> header file. */
|
||||
#define HAVE_STDARG_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#define HAVE_STDINT_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#define HAVE_STRINGS_H 1
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#define HAVE_UNISTD_H 1
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#define LT_OBJDIR ".libs/"
|
||||
|
||||
/* Name of package */
|
||||
#define PACKAGE "giflib"
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#define PACKAGE_BUGREPORT "esr@thyrsus.com"
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#define PACKAGE_NAME "giflib"
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#define PACKAGE_STRING "giflib 5.1.1"
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#define PACKAGE_TARNAME "giflib"
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#define PACKAGE_URL ""
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#define PACKAGE_VERSION "5.1.1"
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define STDC_HEADERS 1
|
||||
|
||||
/* Version number of package */
|
||||
#define VERSION "5.1.1"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
/*****************************************************************************
|
||||
|
||||
gif_hash.c -- module to support the following operations:
|
||||
|
||||
1. InitHashTable - initialize hash table.
|
||||
2. ClearHashTable - clear the hash table to an empty state.
|
||||
2. InsertHashTable - insert one item into data structure.
|
||||
3. ExistsHashTable - test if item exists in data structure.
|
||||
|
||||
This module is used to hash the GIF codes during encoding.
|
||||
|
||||
*****************************************************************************/
|
||||
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "gif_lib.h"
|
||||
#include "gif_hash.h"
|
||||
#include "gif_lib_private.h"
|
||||
|
||||
/* #define DEBUG_HIT_RATE Debug number of misses per hash Insert/Exists. */
|
||||
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
static long NumberOfTests = 0,
|
||||
NumberOfMisses = 0;
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
|
||||
static int KeyItem(uint32_t Item);
|
||||
|
||||
/******************************************************************************
|
||||
Initialize HashTable - allocate the memory needed and clear it. *
|
||||
******************************************************************************/
|
||||
GifHashTableType *_InitHashTable(void)
|
||||
{
|
||||
GifHashTableType *HashTable;
|
||||
|
||||
if ((HashTable = (GifHashTableType *) malloc(sizeof(GifHashTableType)))
|
||||
== NULL)
|
||||
return NULL;
|
||||
|
||||
_ClearHashTable(HashTable);
|
||||
|
||||
return HashTable;
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Routine to clear the HashTable to an empty state. *
|
||||
This part is a little machine depended. Use the commented part otherwise. *
|
||||
******************************************************************************/
|
||||
void _ClearHashTable(GifHashTableType *HashTable)
|
||||
{
|
||||
memset(HashTable -> HTable, 0xFF, HT_SIZE * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Routine to insert a new Item into the HashTable. The data is assumed to be *
|
||||
new one. *
|
||||
******************************************************************************/
|
||||
void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code)
|
||||
{
|
||||
int HKey = KeyItem(Key);
|
||||
uint32_t *HTable = HashTable -> HTable;
|
||||
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
NumberOfTests++;
|
||||
NumberOfMisses++;
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
|
||||
while (HT_GET_KEY(HTable[HKey]) != 0xFFFFFL) {
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
NumberOfMisses++;
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
HKey = (HKey + 1) & HT_KEY_MASK;
|
||||
}
|
||||
HTable[HKey] = HT_PUT_KEY(Key) | HT_PUT_CODE(Code);
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Routine to test if given Key exists in HashTable and if so returns its code *
|
||||
Returns the Code if key was found, -1 if not. *
|
||||
******************************************************************************/
|
||||
int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key)
|
||||
{
|
||||
int HKey = KeyItem(Key);
|
||||
uint32_t *HTable = HashTable -> HTable, HTKey;
|
||||
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
NumberOfTests++;
|
||||
NumberOfMisses++;
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
|
||||
while ((HTKey = HT_GET_KEY(HTable[HKey])) != 0xFFFFFL) {
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
NumberOfMisses++;
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
if (Key == HTKey) return HT_GET_CODE(HTable[HKey]);
|
||||
HKey = (HKey + 1) & HT_KEY_MASK;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Routine to generate an HKey for the hashtable out of the given unique key. *
|
||||
The given Key is assumed to be 20 bits as follows: lower 8 bits are the *
|
||||
new postfix character, while the upper 12 bits are the prefix code. *
|
||||
Because the average hit ratio is only 2 (2 hash references per entry), *
|
||||
evaluating more complex keys (such as twin prime keys) does not worth it! *
|
||||
******************************************************************************/
|
||||
static int KeyItem(uint32_t Item)
|
||||
{
|
||||
return ((Item >> 12) ^ Item) & HT_KEY_MASK;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_HIT_RATE
|
||||
/******************************************************************************
|
||||
Debugging routine to print the hit ratio - number of times the hash table *
|
||||
was tested per operation. This routine was used to test the KeyItem routine *
|
||||
******************************************************************************/
|
||||
void HashTablePrintHitRatio(void)
|
||||
{
|
||||
printf("Hash Table Hit Ratio is %ld/%ld = %ld%%.\n",
|
||||
NumberOfMisses, NumberOfTests,
|
||||
NumberOfMisses * 100 / NumberOfTests);
|
||||
}
|
||||
#endif /* DEBUG_HIT_RATE */
|
||||
|
||||
/* end */
|
||||
@@ -0,0 +1,39 @@
|
||||
/******************************************************************************
|
||||
|
||||
gif_hash.h - magfic constants and declarations for GIF LZW
|
||||
|
||||
******************************************************************************/
|
||||
|
||||
#ifndef _GIF_HASH_H_
|
||||
#define _GIF_HASH_H_
|
||||
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define HT_SIZE 8192 /* 12bits = 4096 or twice as big! */
|
||||
#define HT_KEY_MASK 0x1FFF /* 13bits keys */
|
||||
#define HT_KEY_NUM_BITS 13 /* 13bits keys */
|
||||
#define HT_MAX_KEY 8191 /* 13bits - 1, maximal code possible */
|
||||
#define HT_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
|
||||
|
||||
/* The 32 bits of the long are divided into two parts for the key & code: */
|
||||
/* 1. The code is 12 bits as our compression algorithm is limited to 12bits */
|
||||
/* 2. The key is 12 bits Prefix code + 8 bit new char or 20 bits. */
|
||||
/* The key is the upper 20 bits. The code is the lower 12. */
|
||||
#define HT_GET_KEY(l) (l >> 12)
|
||||
#define HT_GET_CODE(l) (l & 0x0FFF)
|
||||
#define HT_PUT_KEY(l) (l << 12)
|
||||
#define HT_PUT_CODE(l) (l & 0x0FFF)
|
||||
|
||||
typedef struct GifHashTableType {
|
||||
uint32_t HTable[HT_SIZE];
|
||||
} GifHashTableType;
|
||||
|
||||
GifHashTableType *_InitHashTable(void);
|
||||
void _ClearHashTable(GifHashTableType *HashTable);
|
||||
void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code);
|
||||
int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key);
|
||||
|
||||
#endif /* _GIF_HASH_H_ */
|
||||
|
||||
/* end */
|
||||
@@ -0,0 +1,309 @@
|
||||
/******************************************************************************
|
||||
|
||||
gif_lib.h - service library for decoding and encoding GIF images
|
||||
|
||||
*****************************************************************************/
|
||||
|
||||
#ifndef _GIF_LIB_H_
|
||||
#define _GIF_LIB_H_ 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#define GIFLIB_MAJOR 5
|
||||
#define GIFLIB_MINOR 1
|
||||
#define GIFLIB_RELEASE 1
|
||||
|
||||
#define GIF_ERROR 0
|
||||
#define GIF_OK 1
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define GIF_STAMP "GIFVER" /* First chars in file - GIF stamp. */
|
||||
#define GIF_STAMP_LEN sizeof(GIF_STAMP) - 1
|
||||
#define GIF_VERSION_POS 3 /* Version first character in stamp. */
|
||||
#define GIF87_STAMP "GIF87a" /* First chars in file - GIF stamp. */
|
||||
#define GIF89_STAMP "GIF89a" /* First chars in file - GIF stamp. */
|
||||
|
||||
typedef unsigned char GifPixelType;
|
||||
typedef unsigned char *GifRowType;
|
||||
typedef unsigned char GifByteType;
|
||||
typedef unsigned int GifPrefixType;
|
||||
typedef int GifWord;
|
||||
|
||||
typedef struct GifColorType {
|
||||
GifByteType Red, Green, Blue;
|
||||
} GifColorType;
|
||||
|
||||
typedef struct ColorMapObject {
|
||||
int ColorCount;
|
||||
int BitsPerPixel;
|
||||
bool SortFlag;
|
||||
GifColorType *Colors; /* on malloc(3) heap */
|
||||
} ColorMapObject;
|
||||
|
||||
typedef struct GifImageDesc {
|
||||
GifWord Left, Top, Width, Height; /* Current image dimensions. */
|
||||
bool Interlace; /* Sequential/Interlaced lines. */
|
||||
ColorMapObject *ColorMap; /* The local color map */
|
||||
} GifImageDesc;
|
||||
|
||||
typedef struct ExtensionBlock {
|
||||
int ByteCount;
|
||||
GifByteType *Bytes; /* on malloc(3) heap */
|
||||
int Function; /* The block function code */
|
||||
#define CONTINUE_EXT_FUNC_CODE 0x00 /* continuation subblock */
|
||||
#define COMMENT_EXT_FUNC_CODE 0xfe /* comment */
|
||||
#define GRAPHICS_EXT_FUNC_CODE 0xf9 /* graphics control (GIF89) */
|
||||
#define PLAINTEXT_EXT_FUNC_CODE 0x01 /* plaintext */
|
||||
#define APPLICATION_EXT_FUNC_CODE 0xff /* application block */
|
||||
} ExtensionBlock;
|
||||
|
||||
typedef struct SavedImage {
|
||||
GifImageDesc ImageDesc;
|
||||
GifByteType *RasterBits; /* on malloc(3) heap */
|
||||
int ExtensionBlockCount; /* Count of extensions before image */
|
||||
ExtensionBlock *ExtensionBlocks; /* Extensions before image */
|
||||
} SavedImage;
|
||||
|
||||
typedef struct GifFileType {
|
||||
GifWord SWidth, SHeight; /* Size of virtual canvas */
|
||||
GifWord SColorResolution; /* How many colors can we generate? */
|
||||
GifWord SBackGroundColor; /* Background color for virtual canvas */
|
||||
GifByteType AspectByte; /* Used to compute pixel aspect ratio */
|
||||
ColorMapObject *SColorMap; /* Global colormap, NULL if nonexistent. */
|
||||
int ImageCount; /* Number of current image (both APIs) */
|
||||
GifImageDesc Image; /* Current image (low-level API) */
|
||||
SavedImage *SavedImages; /* Image sequence (high-level API) */
|
||||
int ExtensionBlockCount; /* Count extensions past last image */
|
||||
ExtensionBlock *ExtensionBlocks; /* Extensions past last image */
|
||||
int Error; /* Last error condition reported */
|
||||
void *UserData; /* hook to attach user data (TVT) */
|
||||
void *Private; /* Don't mess with this! */
|
||||
} GifFileType;
|
||||
|
||||
#define GIF_ASPECT_RATIO(n) ((n)+15.0/64.0)
|
||||
|
||||
typedef enum {
|
||||
UNDEFINED_RECORD_TYPE,
|
||||
SCREEN_DESC_RECORD_TYPE,
|
||||
IMAGE_DESC_RECORD_TYPE, /* Begin with ',' */
|
||||
EXTENSION_RECORD_TYPE, /* Begin with '!' */
|
||||
TERMINATE_RECORD_TYPE /* Begin with ';' */
|
||||
} GifRecordType;
|
||||
|
||||
/* func type to read gif data from arbitrary sources (TVT) */
|
||||
typedef int (*InputFunc) (GifFileType *, GifByteType *, int);
|
||||
|
||||
/* func type to write gif data to arbitrary targets.
|
||||
* Returns count of bytes written. (MRB)
|
||||
*/
|
||||
typedef int (*OutputFunc) (GifFileType *, const GifByteType *, int);
|
||||
|
||||
/******************************************************************************
|
||||
GIF89 structures
|
||||
******************************************************************************/
|
||||
|
||||
typedef struct GraphicsControlBlock {
|
||||
int DisposalMode;
|
||||
#define DISPOSAL_UNSPECIFIED 0 /* No disposal specified. */
|
||||
#define DISPOSE_DO_NOT 1 /* Leave image in place */
|
||||
#define DISPOSE_BACKGROUND 2 /* Set area too background color */
|
||||
#define DISPOSE_PREVIOUS 3 /* Restore to previous content */
|
||||
bool UserInputFlag; /* User confirmation required before disposal */
|
||||
int DelayTime; /* pre-display delay in 0.01sec units */
|
||||
int TransparentColor; /* Palette index for transparency, -1 if none */
|
||||
#define NO_TRANSPARENT_COLOR -1
|
||||
} GraphicsControlBlock;
|
||||
|
||||
/******************************************************************************
|
||||
GIF encoding routines
|
||||
******************************************************************************/
|
||||
|
||||
/* Main entry points */
|
||||
GifFileType *EGifOpenFileName(const char *GifFileName,
|
||||
const bool GifTestExistence, int *Error);
|
||||
GifFileType *EGifOpenFileHandle(const int GifFileHandle, int *Error);
|
||||
GifFileType *EGifOpen(void *userPtr, OutputFunc writeFunc, int *Error);
|
||||
int EGifSpew(GifFileType * GifFile);
|
||||
const char *EGifGetGifVersion(GifFileType *GifFile); /* new in 5.x */
|
||||
int EGifCloseFile(GifFileType *GifFile, int *ErrorCode);
|
||||
|
||||
#define E_GIF_SUCCEEDED 0
|
||||
#define E_GIF_ERR_OPEN_FAILED 1 /* And EGif possible errors. */
|
||||
#define E_GIF_ERR_WRITE_FAILED 2
|
||||
#define E_GIF_ERR_HAS_SCRN_DSCR 3
|
||||
#define E_GIF_ERR_HAS_IMAG_DSCR 4
|
||||
#define E_GIF_ERR_NO_COLOR_MAP 5
|
||||
#define E_GIF_ERR_DATA_TOO_BIG 6
|
||||
#define E_GIF_ERR_NOT_ENOUGH_MEM 7
|
||||
#define E_GIF_ERR_DISK_IS_FULL 8
|
||||
#define E_GIF_ERR_CLOSE_FAILED 9
|
||||
#define E_GIF_ERR_NOT_WRITEABLE 10
|
||||
|
||||
/* These are legacy. You probably do not want to call them directly */
|
||||
int EGifPutScreenDesc(GifFileType *GifFile,
|
||||
const int GifWidth, const int GifHeight,
|
||||
const int GifColorRes,
|
||||
const int GifBackGround,
|
||||
const ColorMapObject *GifColorMap);
|
||||
int EGifPutImageDesc(GifFileType *GifFile,
|
||||
const int GifLeft, const int GifTop,
|
||||
const int GifWidth, const int GifHeight,
|
||||
const bool GifInterlace,
|
||||
const ColorMapObject *GifColorMap);
|
||||
void EGifSetGifVersion(GifFileType *GifFile, const bool gif89);
|
||||
int EGifPutLine(GifFileType *GifFile, GifPixelType *GifLine,
|
||||
int GifLineLen);
|
||||
int EGifPutPixel(GifFileType *GifFile, const GifPixelType GifPixel);
|
||||
int EGifPutComment(GifFileType *GifFile, const char *GifComment);
|
||||
int EGifPutExtensionLeader(GifFileType *GifFile, const int GifExtCode);
|
||||
int EGifPutExtensionBlock(GifFileType *GifFile,
|
||||
const int GifExtLen, const void *GifExtension);
|
||||
int EGifPutExtensionTrailer(GifFileType *GifFile);
|
||||
int EGifPutExtension(GifFileType *GifFile, const int GifExtCode,
|
||||
const int GifExtLen,
|
||||
const void *GifExtension);
|
||||
int EGifPutCode(GifFileType *GifFile, int GifCodeSize,
|
||||
const GifByteType *GifCodeBlock);
|
||||
int EGifPutCodeNext(GifFileType *GifFile,
|
||||
const GifByteType *GifCodeBlock);
|
||||
|
||||
/******************************************************************************
|
||||
GIF decoding routines
|
||||
******************************************************************************/
|
||||
|
||||
/* Main entry points */
|
||||
GifFileType *DGifOpenFileName(const char *GifFileName, int *Error);
|
||||
GifFileType *DGifOpenFileHandle(int GifFileHandle, int *Error);
|
||||
int DGifSlurp(GifFileType * GifFile);
|
||||
GifFileType *DGifOpen(void *userPtr, InputFunc readFunc, int *Error); /* new one (TVT) */
|
||||
int DGifCloseFile(GifFileType * GifFile, int *ErrorCode);
|
||||
|
||||
#define D_GIF_SUCCEEDED 0
|
||||
#define D_GIF_ERR_OPEN_FAILED 101 /* And DGif possible errors. */
|
||||
#define D_GIF_ERR_READ_FAILED 102
|
||||
#define D_GIF_ERR_NOT_GIF_FILE 103
|
||||
#define D_GIF_ERR_NO_SCRN_DSCR 104
|
||||
#define D_GIF_ERR_NO_IMAG_DSCR 105
|
||||
#define D_GIF_ERR_NO_COLOR_MAP 106
|
||||
#define D_GIF_ERR_WRONG_RECORD 107
|
||||
#define D_GIF_ERR_DATA_TOO_BIG 108
|
||||
#define D_GIF_ERR_NOT_ENOUGH_MEM 109
|
||||
#define D_GIF_ERR_CLOSE_FAILED 110
|
||||
#define D_GIF_ERR_NOT_READABLE 111
|
||||
#define D_GIF_ERR_IMAGE_DEFECT 112
|
||||
#define D_GIF_ERR_EOF_TOO_SOON 113
|
||||
|
||||
/* These are legacy. You probably do not want to call them directly */
|
||||
int DGifGetScreenDesc(GifFileType *GifFile);
|
||||
int DGifGetRecordType(GifFileType *GifFile, GifRecordType *GifType);
|
||||
int DGifGetImageDesc(GifFileType *GifFile);
|
||||
int DGifGetLine(GifFileType *GifFile, GifPixelType *GifLine, int GifLineLen);
|
||||
int DGifGetPixel(GifFileType *GifFile, GifPixelType GifPixel);
|
||||
int DGifGetComment(GifFileType *GifFile, char *GifComment);
|
||||
int DGifGetExtension(GifFileType *GifFile, int *GifExtCode,
|
||||
GifByteType **GifExtension);
|
||||
int DGifGetExtensionNext(GifFileType *GifFile, GifByteType **GifExtension);
|
||||
int DGifGetCode(GifFileType *GifFile, int *GifCodeSize,
|
||||
GifByteType **GifCodeBlock);
|
||||
int DGifGetCodeNext(GifFileType *GifFile, GifByteType **GifCodeBlock);
|
||||
int DGifGetLZCodes(GifFileType *GifFile, int *GifCode);
|
||||
|
||||
|
||||
/******************************************************************************
|
||||
Color table quantization (deprecated)
|
||||
******************************************************************************/
|
||||
int GifQuantizeBuffer(unsigned int Width, unsigned int Height,
|
||||
int *ColorMapSize, GifByteType * RedInput,
|
||||
GifByteType * GreenInput, GifByteType * BlueInput,
|
||||
GifByteType * OutputBuffer,
|
||||
GifColorType * OutputColorMap);
|
||||
|
||||
/******************************************************************************
|
||||
Error handling and reporting.
|
||||
******************************************************************************/
|
||||
extern const char *GifErrorString(int ErrorCode); /* new in 2012 - ESR */
|
||||
|
||||
/*****************************************************************************
|
||||
Everything below this point is new after version 1.2, supporting `slurp
|
||||
mode' for doing I/O in two big belts with all the image-bashing in core.
|
||||
******************************************************************************/
|
||||
|
||||
/******************************************************************************
|
||||
Color map handling from gif_alloc.c
|
||||
******************************************************************************/
|
||||
|
||||
extern ColorMapObject *GifMakeMapObject(int ColorCount,
|
||||
const GifColorType *ColorMap);
|
||||
extern void GifFreeMapObject(ColorMapObject *Object);
|
||||
extern ColorMapObject *GifUnionColorMap(const ColorMapObject *ColorIn1,
|
||||
const ColorMapObject *ColorIn2,
|
||||
GifPixelType ColorTransIn2[]);
|
||||
extern int GifBitSize(int n);
|
||||
|
||||
/******************************************************************************
|
||||
Support for the in-core structures allocation (slurp mode).
|
||||
******************************************************************************/
|
||||
|
||||
extern void GifApplyTranslation(SavedImage *Image, GifPixelType Translation[]);
|
||||
extern int GifAddExtensionBlock(int *ExtensionBlock_Count,
|
||||
ExtensionBlock **ExtensionBlocks,
|
||||
int Function,
|
||||
unsigned int Len, unsigned char ExtData[]);
|
||||
extern void GifFreeExtensions(int *ExtensionBlock_Count,
|
||||
ExtensionBlock **ExtensionBlocks);
|
||||
extern SavedImage *GifMakeSavedImage(GifFileType *GifFile,
|
||||
const SavedImage *CopyFrom);
|
||||
extern void GifFreeSavedImages(GifFileType *GifFile);
|
||||
|
||||
/******************************************************************************
|
||||
5.x functions for GIF89 graphics control blocks
|
||||
******************************************************************************/
|
||||
|
||||
int DGifExtensionToGCB(const size_t GifExtensionLength,
|
||||
const GifByteType *GifExtension,
|
||||
GraphicsControlBlock *GCB);
|
||||
size_t EGifGCBToExtension(const GraphicsControlBlock *GCB,
|
||||
GifByteType *GifExtension);
|
||||
|
||||
int DGifSavedExtensionToGCB(GifFileType *GifFile,
|
||||
int ImageIndex,
|
||||
GraphicsControlBlock *GCB);
|
||||
int EGifGCBToSavedExtension(const GraphicsControlBlock *GCB,
|
||||
GifFileType *GifFile,
|
||||
int ImageIndex);
|
||||
|
||||
/******************************************************************************
|
||||
The library's internal utility font
|
||||
******************************************************************************/
|
||||
|
||||
#define GIF_FONT_WIDTH 8
|
||||
#define GIF_FONT_HEIGHT 8
|
||||
extern const unsigned char GifAsciiTable8x8[][GIF_FONT_WIDTH];
|
||||
|
||||
extern void GifDrawText8x8(SavedImage *Image,
|
||||
const int x, const int y,
|
||||
const char *legend, const int color);
|
||||
|
||||
extern void GifDrawBox(SavedImage *Image,
|
||||
const int x, const int y,
|
||||
const int w, const int d, const int color);
|
||||
|
||||
extern void GifDrawRectangle(SavedImage *Image,
|
||||
const int x, const int y,
|
||||
const int w, const int d, const int color);
|
||||
|
||||
extern void GifDrawBoxedText8x8(SavedImage *Image,
|
||||
const int x, const int y,
|
||||
const char *legend,
|
||||
const int border, const int bg, const int fg);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
#endif /* _GIF_LIB_H */
|
||||
|
||||
/* end */
|
||||
@@ -0,0 +1,59 @@
|
||||
/****************************************************************************
|
||||
|
||||
gif_lib_private.h - internal giflib routines and structures
|
||||
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _GIF_LIB_PRIVATE_H
|
||||
#define _GIF_LIB_PRIVATE_H
|
||||
|
||||
#include "gif_lib.h"
|
||||
#include "gif_hash.h"
|
||||
|
||||
#define EXTENSION_INTRODUCER 0x21
|
||||
#define DESCRIPTOR_INTRODUCER 0x2c
|
||||
#define TERMINATOR_INTRODUCER 0x3b
|
||||
|
||||
#define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
|
||||
#define LZ_BITS 12
|
||||
|
||||
#define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */
|
||||
#define FIRST_CODE 4097 /* Impossible code, to signal first. */
|
||||
#define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */
|
||||
|
||||
#define FILE_STATE_WRITE 0x01
|
||||
#define FILE_STATE_SCREEN 0x02
|
||||
#define FILE_STATE_IMAGE 0x04
|
||||
#define FILE_STATE_READ 0x08
|
||||
|
||||
#define IS_READABLE(Private) (Private->FileState & FILE_STATE_READ)
|
||||
#define IS_WRITEABLE(Private) (Private->FileState & FILE_STATE_WRITE)
|
||||
|
||||
typedef struct GifFilePrivateType {
|
||||
GifWord FileState, FileHandle, /* Where all this data goes to! */
|
||||
BitsPerPixel, /* Bits per pixel (Codes uses at least this + 1). */
|
||||
ClearCode, /* The CLEAR LZ code. */
|
||||
EOFCode, /* The EOF LZ code. */
|
||||
RunningCode, /* The next code algorithm can generate. */
|
||||
RunningBits, /* The number of bits required to represent RunningCode. */
|
||||
MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */
|
||||
LastCode, /* The code before the current code. */
|
||||
CrntCode, /* Current algorithm code. */
|
||||
StackPtr, /* For character stack (see below). */
|
||||
CrntShiftState; /* Number of bits in CrntShiftDWord. */
|
||||
unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */
|
||||
unsigned long PixelCount; /* Number of pixels in image. */
|
||||
FILE *File; /* File as stream. */
|
||||
InputFunc Read; /* function to read gif input (TVT) */
|
||||
OutputFunc Write; /* function to write gif output (MRB) */
|
||||
GifByteType Buf[256]; /* Compressed input is buffered here. */
|
||||
GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */
|
||||
GifByteType Suffix[LZ_MAX_CODE + 1]; /* So we can trace the codes. */
|
||||
GifPrefixType Prefix[LZ_MAX_CODE + 1];
|
||||
GifHashTableType *HashTable;
|
||||
bool gif89;
|
||||
} GifFilePrivateType;
|
||||
|
||||
#endif /* _GIF_LIB_PRIVATE_H */
|
||||
|
||||
/* end */
|
||||
@@ -0,0 +1,411 @@
|
||||
/*****************************************************************************
|
||||
|
||||
GIF construction tools
|
||||
|
||||
****************************************************************************/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "gif_lib.h"
|
||||
|
||||
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
|
||||
|
||||
/******************************************************************************
|
||||
Miscellaneous utility functions
|
||||
******************************************************************************/
|
||||
|
||||
/* return smallest bitfield size n will fit in */
|
||||
int
|
||||
GifBitSize(int n)
|
||||
{
|
||||
register int i;
|
||||
|
||||
for (i = 1; i <= 8; i++)
|
||||
if ((1 << i) >= n)
|
||||
break;
|
||||
return (i);
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Color map object functions
|
||||
******************************************************************************/
|
||||
|
||||
/*
|
||||
* Allocate a color map of given size; initialize with contents of
|
||||
* ColorMap if that pointer is non-NULL.
|
||||
*/
|
||||
ColorMapObject *
|
||||
GifMakeMapObject(int ColorCount, const GifColorType *ColorMap)
|
||||
{
|
||||
ColorMapObject *Object;
|
||||
|
||||
/*** FIXME: Our ColorCount has to be a power of two. Is it necessary to
|
||||
* make the user know that or should we automatically round up instead? */
|
||||
if (ColorCount != (1 << GifBitSize(ColorCount))) {
|
||||
return ((ColorMapObject *) NULL);
|
||||
}
|
||||
|
||||
Object = (ColorMapObject *)malloc(sizeof(ColorMapObject));
|
||||
if (Object == (ColorMapObject *) NULL) {
|
||||
return ((ColorMapObject *) NULL);
|
||||
}
|
||||
|
||||
Object->Colors = (GifColorType *)calloc(ColorCount, sizeof(GifColorType));
|
||||
if (Object->Colors == (GifColorType *) NULL) {
|
||||
free(Object);
|
||||
return ((ColorMapObject *) NULL);
|
||||
}
|
||||
|
||||
Object->ColorCount = ColorCount;
|
||||
Object->BitsPerPixel = GifBitSize(ColorCount);
|
||||
Object->SortFlag = false;
|
||||
|
||||
if (ColorMap != NULL) {
|
||||
memcpy((char *)Object->Colors,
|
||||
(char *)ColorMap, ColorCount * sizeof(GifColorType));
|
||||
}
|
||||
|
||||
return (Object);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
Free a color map object
|
||||
*******************************************************************************/
|
||||
void
|
||||
GifFreeMapObject(ColorMapObject *Object)
|
||||
{
|
||||
if (Object != NULL) {
|
||||
(void)free(Object->Colors);
|
||||
(void)free(Object);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
void
|
||||
DumpColorMap(ColorMapObject *Object,
|
||||
FILE * fp)
|
||||
{
|
||||
if (Object != NULL) {
|
||||
int i, j, Len = Object->ColorCount;
|
||||
|
||||
for (i = 0; i < Len; i += 4) {
|
||||
for (j = 0; j < 4 && j < Len; j++) {
|
||||
(void)fprintf(fp, "%3d: %02x %02x %02x ", i + j,
|
||||
Object->Colors[i + j].Red,
|
||||
Object->Colors[i + j].Green,
|
||||
Object->Colors[i + j].Blue);
|
||||
}
|
||||
(void)fprintf(fp, "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif /* DEBUG */
|
||||
|
||||
/*******************************************************************************
|
||||
Compute the union of two given color maps and return it. If result can't
|
||||
fit into 256 colors, NULL is returned, the allocated union otherwise.
|
||||
ColorIn1 is copied as is to ColorUnion, while colors from ColorIn2 are
|
||||
copied iff they didn't exist before. ColorTransIn2 maps the old
|
||||
ColorIn2 into the ColorUnion color map table./
|
||||
*******************************************************************************/
|
||||
ColorMapObject *
|
||||
GifUnionColorMap(const ColorMapObject *ColorIn1,
|
||||
const ColorMapObject *ColorIn2,
|
||||
GifPixelType ColorTransIn2[])
|
||||
{
|
||||
int i, j, CrntSlot, RoundUpTo, NewGifBitSize;
|
||||
ColorMapObject *ColorUnion;
|
||||
|
||||
/*
|
||||
* We don't worry about duplicates within either color map; if
|
||||
* the caller wants to resolve those, he can perform unions
|
||||
* with an empty color map.
|
||||
*/
|
||||
|
||||
/* Allocate table which will hold the result for sure. */
|
||||
ColorUnion = GifMakeMapObject(MAX(ColorIn1->ColorCount,
|
||||
ColorIn2->ColorCount) * 2, NULL);
|
||||
|
||||
if (ColorUnion == NULL)
|
||||
return (NULL);
|
||||
|
||||
/*
|
||||
* Copy ColorIn1 to ColorUnion.
|
||||
*/
|
||||
for (i = 0; i < ColorIn1->ColorCount; i++)
|
||||
ColorUnion->Colors[i] = ColorIn1->Colors[i];
|
||||
CrntSlot = ColorIn1->ColorCount;
|
||||
|
||||
/*
|
||||
* Potentially obnoxious hack:
|
||||
*
|
||||
* Back CrntSlot down past all contiguous {0, 0, 0} slots at the end
|
||||
* of table 1. This is very useful if your display is limited to
|
||||
* 16 colors.
|
||||
*/
|
||||
while (ColorIn1->Colors[CrntSlot - 1].Red == 0
|
||||
&& ColorIn1->Colors[CrntSlot - 1].Green == 0
|
||||
&& ColorIn1->Colors[CrntSlot - 1].Blue == 0)
|
||||
CrntSlot--;
|
||||
|
||||
/* Copy ColorIn2 to ColorUnion (use old colors if they exist): */
|
||||
for (i = 0; i < ColorIn2->ColorCount && CrntSlot <= 256; i++) {
|
||||
/* Let's see if this color already exists: */
|
||||
for (j = 0; j < ColorIn1->ColorCount; j++)
|
||||
if (memcmp (&ColorIn1->Colors[j], &ColorIn2->Colors[i],
|
||||
sizeof(GifColorType)) == 0)
|
||||
break;
|
||||
|
||||
if (j < ColorIn1->ColorCount)
|
||||
ColorTransIn2[i] = j; /* color exists in Color1 */
|
||||
else {
|
||||
/* Color is new - copy it to a new slot: */
|
||||
ColorUnion->Colors[CrntSlot] = ColorIn2->Colors[i];
|
||||
ColorTransIn2[i] = CrntSlot++;
|
||||
}
|
||||
}
|
||||
|
||||
if (CrntSlot > 256) {
|
||||
GifFreeMapObject(ColorUnion);
|
||||
return ((ColorMapObject *) NULL);
|
||||
}
|
||||
|
||||
NewGifBitSize = GifBitSize(CrntSlot);
|
||||
RoundUpTo = (1 << NewGifBitSize);
|
||||
|
||||
if (RoundUpTo != ColorUnion->ColorCount) {
|
||||
register GifColorType *Map = ColorUnion->Colors;
|
||||
|
||||
/*
|
||||
* Zero out slots up to next power of 2.
|
||||
* We know these slots exist because of the way ColorUnion's
|
||||
* start dimension was computed.
|
||||
*/
|
||||
for (j = CrntSlot; j < RoundUpTo; j++)
|
||||
Map[j].Red = Map[j].Green = Map[j].Blue = 0;
|
||||
|
||||
/* perhaps we can shrink the map? */
|
||||
if (RoundUpTo < ColorUnion->ColorCount) {
|
||||
GifColorType *new_map = (GifColorType *)realloc(Map,
|
||||
sizeof(GifColorType) * RoundUpTo);
|
||||
if( new_map == NULL ) {
|
||||
GifFreeMapObject(ColorUnion);
|
||||
return ((ColorMapObject *) NULL);
|
||||
}
|
||||
ColorUnion->Colors = new_map;
|
||||
}
|
||||
}
|
||||
|
||||
ColorUnion->ColorCount = RoundUpTo;
|
||||
ColorUnion->BitsPerPixel = NewGifBitSize;
|
||||
|
||||
return (ColorUnion);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
Apply a given color translation to the raster bits of an image
|
||||
*******************************************************************************/
|
||||
void
|
||||
GifApplyTranslation(SavedImage *Image, GifPixelType Translation[])
|
||||
{
|
||||
register int i;
|
||||
register int RasterSize = Image->ImageDesc.Height * Image->ImageDesc.Width;
|
||||
|
||||
for (i = 0; i < RasterSize; i++)
|
||||
Image->RasterBits[i] = Translation[Image->RasterBits[i]];
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Extension record functions
|
||||
******************************************************************************/
|
||||
int
|
||||
GifAddExtensionBlock(int *ExtensionBlockCount,
|
||||
ExtensionBlock **ExtensionBlocks,
|
||||
int Function,
|
||||
unsigned int Len,
|
||||
unsigned char ExtData[])
|
||||
{
|
||||
ExtensionBlock *ep;
|
||||
|
||||
if (*ExtensionBlocks == NULL)
|
||||
*ExtensionBlocks=(ExtensionBlock *)malloc(sizeof(ExtensionBlock));
|
||||
else {
|
||||
ExtensionBlock* ep_new = (ExtensionBlock *)realloc(*ExtensionBlocks,
|
||||
sizeof(ExtensionBlock) *
|
||||
(*ExtensionBlockCount + 1));
|
||||
if( ep_new == NULL )
|
||||
return (GIF_ERROR);
|
||||
*ExtensionBlocks = ep_new;
|
||||
}
|
||||
|
||||
if (*ExtensionBlocks == NULL)
|
||||
return (GIF_ERROR);
|
||||
|
||||
ep = &(*ExtensionBlocks)[(*ExtensionBlockCount)++];
|
||||
|
||||
ep->Function = Function;
|
||||
ep->ByteCount=Len;
|
||||
ep->Bytes = (GifByteType *)malloc(ep->ByteCount);
|
||||
if (ep->Bytes == NULL)
|
||||
return (GIF_ERROR);
|
||||
|
||||
if (ExtData != NULL) {
|
||||
memcpy(ep->Bytes, ExtData, Len);
|
||||
}
|
||||
|
||||
return (GIF_OK);
|
||||
}
|
||||
|
||||
void
|
||||
GifFreeExtensions(int *ExtensionBlockCount,
|
||||
ExtensionBlock **ExtensionBlocks)
|
||||
{
|
||||
ExtensionBlock *ep;
|
||||
|
||||
if (*ExtensionBlocks == NULL)
|
||||
return;
|
||||
|
||||
for (ep = *ExtensionBlocks;
|
||||
ep < (*ExtensionBlocks + *ExtensionBlockCount);
|
||||
ep++)
|
||||
(void)free((char *)ep->Bytes);
|
||||
(void)free((char *)*ExtensionBlocks);
|
||||
*ExtensionBlocks = NULL;
|
||||
*ExtensionBlockCount = 0;
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
Image block allocation functions
|
||||
******************************************************************************/
|
||||
|
||||
/* Private Function:
|
||||
* Frees the last image in the GifFile->SavedImages array
|
||||
*/
|
||||
void
|
||||
FreeLastSavedImage(GifFileType *GifFile)
|
||||
{
|
||||
SavedImage *sp;
|
||||
|
||||
if ((GifFile == NULL) || (GifFile->SavedImages == NULL))
|
||||
return;
|
||||
|
||||
/* Remove one SavedImage from the GifFile */
|
||||
GifFile->ImageCount--;
|
||||
sp = &GifFile->SavedImages[GifFile->ImageCount];
|
||||
|
||||
/* Deallocate its Colormap */
|
||||
if (sp->ImageDesc.ColorMap != NULL) {
|
||||
GifFreeMapObject(sp->ImageDesc.ColorMap);
|
||||
sp->ImageDesc.ColorMap = NULL;
|
||||
}
|
||||
|
||||
/* Deallocate the image data */
|
||||
if (sp->RasterBits != NULL)
|
||||
free((char *)sp->RasterBits);
|
||||
|
||||
/* Deallocate any extensions */
|
||||
GifFreeExtensions(&sp->ExtensionBlockCount, &sp->ExtensionBlocks);
|
||||
|
||||
/*** FIXME: We could realloc the GifFile->SavedImages structure but is
|
||||
* there a point to it? Saves some memory but we'd have to do it every
|
||||
* time. If this is used in GifFreeSavedImages then it would be inefficient
|
||||
* (The whole array is going to be deallocated.) If we just use it when
|
||||
* we want to free the last Image it's convenient to do it here.
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
* Append an image block to the SavedImages array
|
||||
*/
|
||||
SavedImage *
|
||||
GifMakeSavedImage(GifFileType *GifFile, const SavedImage *CopyFrom)
|
||||
{
|
||||
if (GifFile->SavedImages == NULL)
|
||||
GifFile->SavedImages = (SavedImage *)malloc(sizeof(SavedImage));
|
||||
else
|
||||
GifFile->SavedImages = (SavedImage *)realloc(GifFile->SavedImages,
|
||||
sizeof(SavedImage) * (GifFile->ImageCount + 1));
|
||||
|
||||
if (GifFile->SavedImages == NULL)
|
||||
return ((SavedImage *)NULL);
|
||||
else {
|
||||
SavedImage *sp = &GifFile->SavedImages[GifFile->ImageCount++];
|
||||
memset((char *)sp, '\0', sizeof(SavedImage));
|
||||
|
||||
if (CopyFrom != NULL) {
|
||||
memcpy((char *)sp, CopyFrom, sizeof(SavedImage));
|
||||
|
||||
/*
|
||||
* Make our own allocated copies of the heap fields in the
|
||||
* copied record. This guards against potential aliasing
|
||||
* problems.
|
||||
*/
|
||||
|
||||
/* first, the local color map */
|
||||
if (sp->ImageDesc.ColorMap != NULL) {
|
||||
sp->ImageDesc.ColorMap = GifMakeMapObject(
|
||||
CopyFrom->ImageDesc.ColorMap->ColorCount,
|
||||
CopyFrom->ImageDesc.ColorMap->Colors);
|
||||
if (sp->ImageDesc.ColorMap == NULL) {
|
||||
FreeLastSavedImage(GifFile);
|
||||
return (SavedImage *)(NULL);
|
||||
}
|
||||
}
|
||||
|
||||
/* next, the raster */
|
||||
sp->RasterBits = (unsigned char *)malloc(sizeof(GifPixelType) *
|
||||
CopyFrom->ImageDesc.Height *
|
||||
CopyFrom->ImageDesc.Width);
|
||||
if (sp->RasterBits == NULL) {
|
||||
FreeLastSavedImage(GifFile);
|
||||
return (SavedImage *)(NULL);
|
||||
}
|
||||
memcpy(sp->RasterBits, CopyFrom->RasterBits,
|
||||
sizeof(GifPixelType) * CopyFrom->ImageDesc.Height *
|
||||
CopyFrom->ImageDesc.Width);
|
||||
|
||||
/* finally, the extension blocks */
|
||||
if (sp->ExtensionBlocks != NULL) {
|
||||
sp->ExtensionBlocks = (ExtensionBlock *)malloc(
|
||||
sizeof(ExtensionBlock) *
|
||||
CopyFrom->ExtensionBlockCount);
|
||||
if (sp->ExtensionBlocks == NULL) {
|
||||
FreeLastSavedImage(GifFile);
|
||||
return (SavedImage *)(NULL);
|
||||
}
|
||||
memcpy(sp->ExtensionBlocks, CopyFrom->ExtensionBlocks,
|
||||
sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount);
|
||||
}
|
||||
}
|
||||
|
||||
return (sp);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
GifFreeSavedImages(GifFileType *GifFile)
|
||||
{
|
||||
SavedImage *sp;
|
||||
|
||||
if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) {
|
||||
return;
|
||||
}
|
||||
for (sp = GifFile->SavedImages;
|
||||
sp < GifFile->SavedImages + GifFile->ImageCount; sp++) {
|
||||
if (sp->ImageDesc.ColorMap != NULL) {
|
||||
GifFreeMapObject(sp->ImageDesc.ColorMap);
|
||||
sp->ImageDesc.ColorMap = NULL;
|
||||
}
|
||||
|
||||
if (sp->RasterBits != NULL)
|
||||
free((char *)sp->RasterBits);
|
||||
|
||||
GifFreeExtensions(&sp->ExtensionBlockCount, &sp->ExtensionBlocks);
|
||||
}
|
||||
free((char *)GifFile->SavedImages);
|
||||
GifFile->SavedImages = NULL;
|
||||
}
|
||||
|
||||
/* end */
|
||||
@@ -0,0 +1,176 @@
|
||||
#include "image.h"
|
||||
#include "jpeg.h"
|
||||
#include "gif.h"
|
||||
#include "png.h"
|
||||
#include "giflib/gif_lib.h"
|
||||
|
||||
static int checkFormat(int format) {
|
||||
if (format != FORMAT_AUTO && format != FORMAT_GRAY && format != FORMAT_GRAY_ALPHA
|
||||
&& format != FORMAT_RGB && format != FORMAT_RGBA)
|
||||
return FORMAT_AUTO;
|
||||
else
|
||||
return format;
|
||||
}
|
||||
|
||||
// TODO
|
||||
static int detectFileFormat() {
|
||||
return FILE_FORMAT_GIF;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
static FILE* detectFileFormatPathName(const char* namePath, int* format) {
|
||||
|
||||
char jpegSig[2] = {0xFF, 0xD8};
|
||||
char pngSig[2] = {137, 80};
|
||||
char gifSig[2] = {71, 73};
|
||||
char buf[2];
|
||||
|
||||
FILE* fp = fopen(namePath, "r");
|
||||
if (fp == NULL) {
|
||||
*format = FILE_FORMAT_UNKNOWN;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (fread(buf, 1, 2, fp) != 2) {
|
||||
fclose(fp);
|
||||
*format = FILE_FORMAT_UNKNOWN;
|
||||
return NULL;
|
||||
}
|
||||
rewind(fp);
|
||||
|
||||
if (!memcmp(buf, jpegSig, 2))
|
||||
*format = FILE_FORMAT_JPEG;
|
||||
else if (!memcmp(buf, pngSig, 2))
|
||||
*format = FILE_FORMAT_PNG;
|
||||
else if (!memcmp(buf, gifSig, 2))
|
||||
*format = FILE_FORMAT_GIF;
|
||||
else
|
||||
*format = FILE_FORMAT_UNKNOWN;
|
||||
|
||||
return fp;
|
||||
}
|
||||
|
||||
JNIEXPORT jobject JNICALL
|
||||
Java_com_hippo_ehviewer_gallery_image_Image_nativeDecodeStream(JNIEnv* env,
|
||||
jclass clazz, jobject is, jint format) {
|
||||
|
||||
format = checkFormat(format);
|
||||
|
||||
switch (detectFileFormat()) {
|
||||
case FILE_FORMAT_JPEG:
|
||||
return JPEG_DecodeStream(env, is, format);
|
||||
|
||||
case FILE_FORMAT_PNG:
|
||||
return PNG_DecodeStream(env, is, format);
|
||||
|
||||
case FILE_FORMAT_BMP:
|
||||
return NULL;
|
||||
|
||||
case FILE_FORMAT_GIF:
|
||||
return GIF_DecodeStream(env, is, format);
|
||||
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jobject JNICALL
|
||||
Java_com_hippo_ehviewer_gallery_image_Image_nativeDecodeFile(JNIEnv* env,
|
||||
jclass clazz, jstring namePath, jint format) {
|
||||
|
||||
int fileFormat;
|
||||
const char *str;
|
||||
FILE* fp;
|
||||
jobject image;
|
||||
|
||||
format = checkFormat(format);
|
||||
str = (*env)->GetStringUTFChars(env, namePath, 0);
|
||||
|
||||
fp = detectFileFormatPathName(str, &fileFormat);
|
||||
if (fp == NULL) {
|
||||
(*env)->ReleaseStringUTFChars(env, namePath, str);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
switch (fileFormat) {
|
||||
case FILE_FORMAT_JPEG:
|
||||
image = JPEG_DecodeFileHandler(env, fp, format);
|
||||
break;
|
||||
case FILE_FORMAT_PNG:
|
||||
image = PNG_DecodeFileHandler(env, fp, format);
|
||||
break;
|
||||
case FILE_FORMAT_BMP:
|
||||
image = NULL;
|
||||
break;
|
||||
case FILE_FORMAT_GIF:
|
||||
image = GIF_DecodeFileHandler(env, fp, format);
|
||||
break;
|
||||
default:
|
||||
image = NULL;
|
||||
break;
|
||||
}
|
||||
|
||||
(*env)->ReleaseStringUTFChars(env, namePath, str);
|
||||
fclose(fp);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hippo_ehviewer_gallery_image_Image_nativeFree(JNIEnv* env,
|
||||
jclass clazz, jlong nativeImage, jint fileFormat) {
|
||||
|
||||
switch (fileFormat) {
|
||||
case FILE_FORMAT_JPEG:
|
||||
JPEG_Free(env, (JPEG*) (intptr_t) nativeImage);
|
||||
break;
|
||||
case FILE_FORMAT_PNG:
|
||||
PNG_Free(env, (PNG*) (intptr_t) nativeImage);
|
||||
break;
|
||||
case FILE_FORMAT_BMP:
|
||||
break;
|
||||
case FILE_FORMAT_GIF:
|
||||
GIF_Free(env, (GIF*) (intptr_t) nativeImage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hippo_ehviewer_gallery_image_Image_nativeRender(JNIEnv* env,
|
||||
jclass clazz, jint format, jint type, jlong nativeImage, jint fileFormat) {
|
||||
|
||||
switch (fileFormat) {
|
||||
case FILE_FORMAT_JPEG:
|
||||
JPEG_Render(env, (JPEG*) (intptr_t) nativeImage, format);
|
||||
break;
|
||||
case FILE_FORMAT_PNG:
|
||||
PNG_Render(env, (PNG*) (intptr_t) nativeImage, format);
|
||||
break;
|
||||
case FILE_FORMAT_BMP:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hippo_ehviewer_gallery_image_GifImage_nativeRender(JNIEnv* env,
|
||||
jclass clazz, jint format, jint type, jlong nativeImage, jint fileFormat,
|
||||
jint index) {
|
||||
|
||||
if (type != DEFAULT_TYPE || fileFormat != FILE_FORMAT_GIF)
|
||||
return;
|
||||
|
||||
GIF_Render(env, (GIF*) (intptr_t) nativeImage, format, index);
|
||||
}
|
||||
|
||||
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
JNIEnv* env;
|
||||
if ((*vm)->GetEnv(vm, (void**) (&env), JNI_VERSION_1_6) != JNI_OK)
|
||||
return -1;
|
||||
g_jvm = vm;
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
|
||||
void JNI_OnUnload(JavaVM *vm, void *reserved) {
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#include <jni.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <GLES2/gl2.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#ifndef IMAGE_H_
|
||||
#define IMAGE_H_
|
||||
|
||||
#ifdef RELEASE
|
||||
|
||||
#define LOGV(...)
|
||||
#define LOGD(...)
|
||||
#define LOGI(...)
|
||||
#define LOGW(...)
|
||||
#define LOGE(...)
|
||||
#define LOGF(...)
|
||||
|
||||
#else
|
||||
|
||||
#define TAG "libimage"
|
||||
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG ,__VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG ,__VA_ARGS__)
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG ,__VA_ARGS__)
|
||||
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG ,__VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG ,__VA_ARGS__)
|
||||
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, TAG ,__VA_ARGS__)
|
||||
|
||||
#endif /* RELEASE */
|
||||
|
||||
typedef unsigned char byte;
|
||||
|
||||
typedef struct {
|
||||
byte l;
|
||||
} lum;
|
||||
|
||||
typedef struct {
|
||||
byte l;
|
||||
byte a;
|
||||
} luma;
|
||||
|
||||
typedef struct {
|
||||
byte red;
|
||||
byte green;
|
||||
byte blue;
|
||||
} rgb;
|
||||
|
||||
typedef struct {
|
||||
byte red;
|
||||
byte green;
|
||||
byte blue;
|
||||
byte alpha;
|
||||
} rgba;
|
||||
|
||||
#define DEFAULT_TARGET GL_TEXTURE_2D
|
||||
#define DEFAULT_TYPE GL_UNSIGNED_BYTE
|
||||
|
||||
#define FILE_FORMAT_UNKNOWN -1
|
||||
#define FILE_FORMAT_JPEG 0x0
|
||||
#define FILE_FORMAT_PNG 0x1
|
||||
#define FILE_FORMAT_BMP 0x2
|
||||
#define FILE_FORMAT_GIF 0x3
|
||||
|
||||
#define FORMAT_AUTO 0x0
|
||||
#define FORMAT_GRAY GL_LUMINANCE
|
||||
#define FORMAT_GRAY_ALPHA GL_LUMINANCE_ALPHA
|
||||
#define FORMAT_RGB GL_RGB
|
||||
#define FORMAT_RGBA GL_RGBA
|
||||
|
||||
#define BG_LUM 0x21
|
||||
static rgb defaultBgColorRGB ={0x21, 0x21, 0x21};
|
||||
|
||||
JavaVM *g_jvm;
|
||||
|
||||
#endif /* IMAGE_H_ */
|
||||
@@ -0,0 +1,147 @@
|
||||
#include <setjmp.h>
|
||||
|
||||
#include "image.h"
|
||||
#include "jpeg.h"
|
||||
#include "libjpeg-turbo/jpeglib.h"
|
||||
|
||||
struct my_error_mgr {
|
||||
struct jpeg_error_mgr pub;
|
||||
jmp_buf setjmp_buffer;
|
||||
};
|
||||
|
||||
typedef struct my_error_mgr * my_error_ptr;
|
||||
|
||||
char emsg[JMSG_LENGTH_MAX];
|
||||
|
||||
static void my_error_exit(j_common_ptr cinfo) {
|
||||
my_error_ptr myerr = (my_error_ptr) cinfo->err;
|
||||
(*cinfo->err->format_message)(cinfo, emsg);
|
||||
longjmp(myerr->setjmp_buffer, 1);
|
||||
}
|
||||
|
||||
jobject JPEG_DecodeStream(JNIEnv* env, jobject is, jint format) {
|
||||
// TODO
|
||||
return NULL;
|
||||
}
|
||||
|
||||
jobject JPEG_DecodeFileHandler(JNIEnv* env, FILE* fp, jint format) {
|
||||
|
||||
JPEG* jpeg;
|
||||
struct jpeg_decompress_struct cinfo;
|
||||
struct my_error_mgr jerr;
|
||||
JSAMPARRAY buffer;
|
||||
void* data;
|
||||
int realStride;
|
||||
int fakeWidth;
|
||||
int fakeStride;
|
||||
int readLines;
|
||||
jclass imageClazz;
|
||||
jmethodID constructor;
|
||||
|
||||
jpeg = (JPEG*) malloc(sizeof(JPEG));
|
||||
if (jpeg == NULL)
|
||||
return NULL;
|
||||
|
||||
cinfo.err = jpeg_std_error(&jerr.pub);
|
||||
jerr.pub.error_exit = my_error_exit;
|
||||
if (setjmp(jerr.setjmp_buffer)) {
|
||||
LOGE("%s", emsg);
|
||||
free(jpeg);
|
||||
jpeg_destroy_decompress(&cinfo);
|
||||
return NULL;
|
||||
}
|
||||
jpeg_create_decompress(&cinfo);
|
||||
jpeg_stdio_src(&cinfo, fp);
|
||||
jpeg_read_header(&cinfo, TRUE);
|
||||
|
||||
// Set png format
|
||||
switch (format) {
|
||||
case FORMAT_AUTO:
|
||||
if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
|
||||
format = FORMAT_GRAY;
|
||||
cinfo.out_color_space == JCS_GRAYSCALE;
|
||||
} else {
|
||||
format = FORMAT_RGB;
|
||||
cinfo.out_color_space = JCS_RGB;
|
||||
}
|
||||
break;
|
||||
case FORMAT_RGB:
|
||||
cinfo.out_color_space = JCS_RGB;
|
||||
break;
|
||||
case FORMAT_RGBA:
|
||||
cinfo.out_color_space = JCS_EXT_RGBA;
|
||||
break;
|
||||
case FORMAT_GRAY:
|
||||
cinfo.out_color_space = JCS_GRAYSCALE;
|
||||
break;
|
||||
default:
|
||||
format = FORMAT_RGB;
|
||||
cinfo.out_color_space = JCS_RGB;
|
||||
break;
|
||||
}
|
||||
|
||||
jpeg_start_decompress(&cinfo);
|
||||
|
||||
// Set
|
||||
realStride = cinfo.output_width * cinfo.output_components;
|
||||
fakeWidth = format != FORMAT_RGBA ? nextMulOf4(cinfo.output_width) : cinfo.output_width;
|
||||
fakeStride = fakeWidth * cinfo.output_components;
|
||||
data = malloc(fakeStride * cinfo.output_height);
|
||||
if (data == NULL) {
|
||||
free(jpeg);
|
||||
jpeg_finish_decompress(&cinfo);
|
||||
jpeg_destroy_decompress(&cinfo);
|
||||
return NULL;
|
||||
}
|
||||
buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE,
|
||||
realStride, 3);
|
||||
jpeg->data = data;
|
||||
jpeg->format = format;
|
||||
jpeg->width = fakeWidth;
|
||||
jpeg->height = cinfo.output_height;
|
||||
|
||||
while (cinfo.output_scanline < cinfo.output_height) {
|
||||
readLines = jpeg_read_scanlines(&cinfo, buffer, 3);
|
||||
switch(readLines) {
|
||||
case 3:
|
||||
memcpy(data, buffer[0], realStride);
|
||||
data += fakeStride;
|
||||
case 2:
|
||||
memcpy(data, buffer[readLines - 2], realStride);
|
||||
data += fakeStride;
|
||||
case 1:
|
||||
memcpy(data, buffer[readLines - 1], realStride);
|
||||
data += fakeStride;
|
||||
}
|
||||
}
|
||||
|
||||
jpeg_finish_decompress(&cinfo);
|
||||
jpeg_destroy_decompress(&cinfo);
|
||||
|
||||
imageClazz = (*env)->FindClass(env,
|
||||
"com/hippo/ehviewer/gallery/image/Image");
|
||||
constructor = (*env)->GetMethodID(env, imageClazz, "<init>",
|
||||
"(JIIIII)V");
|
||||
if (constructor == 0) {
|
||||
JPEG_Free((JNIEnv*)NULL, jpeg);
|
||||
return NULL;
|
||||
} else {
|
||||
return (*env)->NewObject(env, imageClazz, constructor, (jlong) (intptr_t) jpeg,
|
||||
FILE_FORMAT_JPEG, cinfo.output_width, cinfo.output_height, format,
|
||||
DEFAULT_TYPE);
|
||||
}
|
||||
}
|
||||
|
||||
void JPEG_Render(JNIEnv* env, JPEG* jpeg, int format) {
|
||||
if (format != jpeg->format)
|
||||
return;
|
||||
|
||||
glTexSubImage2D(DEFAULT_TARGET, 0, 0, 0, jpeg->width,
|
||||
jpeg->height, format, DEFAULT_TYPE, jpeg->data);
|
||||
}
|
||||
|
||||
void JPEG_Free(JNIEnv* env, JPEG* jpeg) {
|
||||
|
||||
free(jpeg->data);
|
||||
free(jpeg);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef JPEG_H_
|
||||
#define JPEG_H_
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#include "image.h"
|
||||
|
||||
typedef struct {
|
||||
void* data;
|
||||
int width;
|
||||
int height;
|
||||
int format;
|
||||
} JPEG;
|
||||
|
||||
jobject JPEG_DecodeStream(JNIEnv* env, jobject is, jint format);
|
||||
jobject JPEG_DecodeFileHandler(JNIEnv* env, FILE* fp, jint format);
|
||||
void JPEG_Render(JNIEnv* env, JPEG* jpeg, int format);
|
||||
void JPEG_Free(JNIEnv* env, JPEG* jpeg);
|
||||
|
||||
#endif /* JPEG_H_ */
|
||||
@@ -0,0 +1,10 @@
|
||||
# simd/jsimdext.inc
|
||||
|
||||
%define EXTN(name) _ %+ name<br>
|
||||
to<br>
|
||||
%define EXTN(name) name<br>
|
||||
or ld error for x86 and x86_64
|
||||
|
||||
# Add cmyk to rgb, cmyk to gray
|
||||
|
||||
In jdcolor.c, jdcolext.c
|
||||
@@ -0,0 +1,145 @@
|
||||
/* config.h. Generated from config.h.in by configure. */
|
||||
/* config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* use 8 or 12 */
|
||||
/* #undef BITS_IN_JSAMPLE */
|
||||
|
||||
/* libjpeg-turbo build number */
|
||||
#define BUILD "20150109"
|
||||
|
||||
/* Support arithmetic encoding */
|
||||
#define C_ARITH_CODING_SUPPORTED 1
|
||||
|
||||
/* Support arithmetic decoding */
|
||||
#define D_ARITH_CODING_SUPPORTED 1
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#define HAVE_DLFCN_H 1
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#define HAVE_INTTYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <jni.h> header file. */
|
||||
/* #undef HAVE_JNI_H */
|
||||
|
||||
/* Define to 1 if you have the <locale.h> header file. */
|
||||
#define HAVE_LOCALE_H 1
|
||||
|
||||
/* Define to 1 if you have the `memcpy' function. */
|
||||
#define HAVE_MEMCPY 1
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#define HAVE_MEMORY_H 1
|
||||
|
||||
/* Define to 1 if you have the `memset' function. */
|
||||
#define HAVE_MEMSET 1
|
||||
|
||||
/* Define to 1 if you have the <stddef.h> header file. */
|
||||
#define HAVE_STDDEF_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#define HAVE_STDINT_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#define HAVE_STRINGS_H 1
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#define HAVE_UNISTD_H 1
|
||||
|
||||
/* Define to 1 if the system has the type `unsigned char'. */
|
||||
#define HAVE_UNSIGNED_CHAR 1
|
||||
|
||||
/* Define to 1 if the system has the type `unsigned short'. */
|
||||
#define HAVE_UNSIGNED_SHORT 1
|
||||
|
||||
/* Compiler does not support pointers to undefined structures. */
|
||||
/* #undef INCOMPLETE_TYPES_BROKEN */
|
||||
|
||||
/* How to obtain function inlining. */
|
||||
#define INLINE inline __attribute__((always_inline))
|
||||
|
||||
/* libjpeg API version */
|
||||
#define JPEG_LIB_VERSION 62
|
||||
|
||||
/* libjpeg-turbo version */
|
||||
#define LIBJPEG_TURBO_VERSION 1.4.0
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#define LT_OBJDIR ".libs/"
|
||||
|
||||
/* Support in-memory source/destination managers */
|
||||
#define MEM_SRCDST_SUPPORTED 1
|
||||
|
||||
/* Define if you have BSD-like bzero and bcopy in <strings.h> rather than
|
||||
memset/memcpy in <string.h>. */
|
||||
/* #undef NEED_BSD_STRINGS */
|
||||
|
||||
/* Define if you need to include <sys/types.h> to get size_t. */
|
||||
#define NEED_SYS_TYPES_H 1
|
||||
|
||||
/* Name of package */
|
||||
#define PACKAGE "libjpeg-turbo"
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#define PACKAGE_BUGREPORT ""
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#define PACKAGE_NAME "libjpeg-turbo"
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#define PACKAGE_STRING "libjpeg-turbo 1.4.0"
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#define PACKAGE_TARNAME "libjpeg-turbo"
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#define PACKAGE_URL ""
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#define PACKAGE_VERSION "1.4.0"
|
||||
|
||||
/* Define if your (broken) compiler shifts signed values as if they were
|
||||
unsigned. */
|
||||
/* #undef RIGHT_SHIFT_IS_UNSIGNED */
|
||||
|
||||
/* The size of `long', as computed by sizeof. */
|
||||
#define SIZEOF_LONG 8
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define STDC_HEADERS 1
|
||||
|
||||
/* Version number of package */
|
||||
#define VERSION "1.4.0"
|
||||
|
||||
/* Use accelerated SIMD routines. */
|
||||
#define WITH_SIMD 1
|
||||
|
||||
/* Define to 1 if type `char' is unsigned and you are not using gcc. */
|
||||
#ifndef __CHAR_UNSIGNED__
|
||||
/* # undef __CHAR_UNSIGNED__ */
|
||||
#endif
|
||||
|
||||
/* Define to empty if `const' does not conform to ANSI C. */
|
||||
/* #undef const */
|
||||
|
||||
/* Define to `__inline__' or `__inline' if that's what the C compiler
|
||||
calls it, or to nothing if 'inline' is not supported under any name. */
|
||||
#ifndef __cplusplus
|
||||
/* #undef inline */
|
||||
#endif
|
||||
|
||||
/* Define to `unsigned int' if <sys/types.h> does not define. */
|
||||
/* #undef size_t */
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* jaricom.c
|
||||
*
|
||||
* Developed 1997-2009 by Guido Vollbeding.
|
||||
* This file is part of the Independent JPEG Group's software.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains probability estimation tables for common use in
|
||||
* arithmetic entropy encoding and decoding routines.
|
||||
*
|
||||
* This data represents Table D.2 in the JPEG spec (ISO/IEC IS 10918-1
|
||||
* and CCITT Recommendation ITU-T T.81) and Table 24 in the JBIG spec
|
||||
* (ISO/IEC IS 11544 and CCITT Recommendation ITU-T T.82).
|
||||
*/
|
||||
|
||||
#define JPEG_INTERNALS
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
|
||||
/* The following #define specifies the packing of the four components
|
||||
* into the compact INT32 representation.
|
||||
* Note that this formula must match the actual arithmetic encoder
|
||||
* and decoder implementation. The implementation has to be changed
|
||||
* if this formula is changed.
|
||||
* The current organization is leaned on Markus Kuhn's JBIG
|
||||
* implementation (jbig_tab.c).
|
||||
*/
|
||||
|
||||
#define V(i,a,b,c,d) (((INT32)a << 16) | ((INT32)c << 8) | ((INT32)d << 7) | b)
|
||||
|
||||
const INT32 jpeg_aritab[113+1] = {
|
||||
/*
|
||||
* Index, Qe_Value, Next_Index_LPS, Next_Index_MPS, Switch_MPS
|
||||
*/
|
||||
V( 0, 0x5a1d, 1, 1, 1 ),
|
||||
V( 1, 0x2586, 14, 2, 0 ),
|
||||
V( 2, 0x1114, 16, 3, 0 ),
|
||||
V( 3, 0x080b, 18, 4, 0 ),
|
||||
V( 4, 0x03d8, 20, 5, 0 ),
|
||||
V( 5, 0x01da, 23, 6, 0 ),
|
||||
V( 6, 0x00e5, 25, 7, 0 ),
|
||||
V( 7, 0x006f, 28, 8, 0 ),
|
||||
V( 8, 0x0036, 30, 9, 0 ),
|
||||
V( 9, 0x001a, 33, 10, 0 ),
|
||||
V( 10, 0x000d, 35, 11, 0 ),
|
||||
V( 11, 0x0006, 9, 12, 0 ),
|
||||
V( 12, 0x0003, 10, 13, 0 ),
|
||||
V( 13, 0x0001, 12, 13, 0 ),
|
||||
V( 14, 0x5a7f, 15, 15, 1 ),
|
||||
V( 15, 0x3f25, 36, 16, 0 ),
|
||||
V( 16, 0x2cf2, 38, 17, 0 ),
|
||||
V( 17, 0x207c, 39, 18, 0 ),
|
||||
V( 18, 0x17b9, 40, 19, 0 ),
|
||||
V( 19, 0x1182, 42, 20, 0 ),
|
||||
V( 20, 0x0cef, 43, 21, 0 ),
|
||||
V( 21, 0x09a1, 45, 22, 0 ),
|
||||
V( 22, 0x072f, 46, 23, 0 ),
|
||||
V( 23, 0x055c, 48, 24, 0 ),
|
||||
V( 24, 0x0406, 49, 25, 0 ),
|
||||
V( 25, 0x0303, 51, 26, 0 ),
|
||||
V( 26, 0x0240, 52, 27, 0 ),
|
||||
V( 27, 0x01b1, 54, 28, 0 ),
|
||||
V( 28, 0x0144, 56, 29, 0 ),
|
||||
V( 29, 0x00f5, 57, 30, 0 ),
|
||||
V( 30, 0x00b7, 59, 31, 0 ),
|
||||
V( 31, 0x008a, 60, 32, 0 ),
|
||||
V( 32, 0x0068, 62, 33, 0 ),
|
||||
V( 33, 0x004e, 63, 34, 0 ),
|
||||
V( 34, 0x003b, 32, 35, 0 ),
|
||||
V( 35, 0x002c, 33, 9, 0 ),
|
||||
V( 36, 0x5ae1, 37, 37, 1 ),
|
||||
V( 37, 0x484c, 64, 38, 0 ),
|
||||
V( 38, 0x3a0d, 65, 39, 0 ),
|
||||
V( 39, 0x2ef1, 67, 40, 0 ),
|
||||
V( 40, 0x261f, 68, 41, 0 ),
|
||||
V( 41, 0x1f33, 69, 42, 0 ),
|
||||
V( 42, 0x19a8, 70, 43, 0 ),
|
||||
V( 43, 0x1518, 72, 44, 0 ),
|
||||
V( 44, 0x1177, 73, 45, 0 ),
|
||||
V( 45, 0x0e74, 74, 46, 0 ),
|
||||
V( 46, 0x0bfb, 75, 47, 0 ),
|
||||
V( 47, 0x09f8, 77, 48, 0 ),
|
||||
V( 48, 0x0861, 78, 49, 0 ),
|
||||
V( 49, 0x0706, 79, 50, 0 ),
|
||||
V( 50, 0x05cd, 48, 51, 0 ),
|
||||
V( 51, 0x04de, 50, 52, 0 ),
|
||||
V( 52, 0x040f, 50, 53, 0 ),
|
||||
V( 53, 0x0363, 51, 54, 0 ),
|
||||
V( 54, 0x02d4, 52, 55, 0 ),
|
||||
V( 55, 0x025c, 53, 56, 0 ),
|
||||
V( 56, 0x01f8, 54, 57, 0 ),
|
||||
V( 57, 0x01a4, 55, 58, 0 ),
|
||||
V( 58, 0x0160, 56, 59, 0 ),
|
||||
V( 59, 0x0125, 57, 60, 0 ),
|
||||
V( 60, 0x00f6, 58, 61, 0 ),
|
||||
V( 61, 0x00cb, 59, 62, 0 ),
|
||||
V( 62, 0x00ab, 61, 63, 0 ),
|
||||
V( 63, 0x008f, 61, 32, 0 ),
|
||||
V( 64, 0x5b12, 65, 65, 1 ),
|
||||
V( 65, 0x4d04, 80, 66, 0 ),
|
||||
V( 66, 0x412c, 81, 67, 0 ),
|
||||
V( 67, 0x37d8, 82, 68, 0 ),
|
||||
V( 68, 0x2fe8, 83, 69, 0 ),
|
||||
V( 69, 0x293c, 84, 70, 0 ),
|
||||
V( 70, 0x2379, 86, 71, 0 ),
|
||||
V( 71, 0x1edf, 87, 72, 0 ),
|
||||
V( 72, 0x1aa9, 87, 73, 0 ),
|
||||
V( 73, 0x174e, 72, 74, 0 ),
|
||||
V( 74, 0x1424, 72, 75, 0 ),
|
||||
V( 75, 0x119c, 74, 76, 0 ),
|
||||
V( 76, 0x0f6b, 74, 77, 0 ),
|
||||
V( 77, 0x0d51, 75, 78, 0 ),
|
||||
V( 78, 0x0bb6, 77, 79, 0 ),
|
||||
V( 79, 0x0a40, 77, 48, 0 ),
|
||||
V( 80, 0x5832, 80, 81, 1 ),
|
||||
V( 81, 0x4d1c, 88, 82, 0 ),
|
||||
V( 82, 0x438e, 89, 83, 0 ),
|
||||
V( 83, 0x3bdd, 90, 84, 0 ),
|
||||
V( 84, 0x34ee, 91, 85, 0 ),
|
||||
V( 85, 0x2eae, 92, 86, 0 ),
|
||||
V( 86, 0x299a, 93, 87, 0 ),
|
||||
V( 87, 0x2516, 86, 71, 0 ),
|
||||
V( 88, 0x5570, 88, 89, 1 ),
|
||||
V( 89, 0x4ca9, 95, 90, 0 ),
|
||||
V( 90, 0x44d9, 96, 91, 0 ),
|
||||
V( 91, 0x3e22, 97, 92, 0 ),
|
||||
V( 92, 0x3824, 99, 93, 0 ),
|
||||
V( 93, 0x32b4, 99, 94, 0 ),
|
||||
V( 94, 0x2e17, 93, 86, 0 ),
|
||||
V( 95, 0x56a8, 95, 96, 1 ),
|
||||
V( 96, 0x4f46, 101, 97, 0 ),
|
||||
V( 97, 0x47e5, 102, 98, 0 ),
|
||||
V( 98, 0x41cf, 103, 99, 0 ),
|
||||
V( 99, 0x3c3d, 104, 100, 0 ),
|
||||
V( 100, 0x375e, 99, 93, 0 ),
|
||||
V( 101, 0x5231, 105, 102, 0 ),
|
||||
V( 102, 0x4c0f, 106, 103, 0 ),
|
||||
V( 103, 0x4639, 107, 104, 0 ),
|
||||
V( 104, 0x415e, 103, 99, 0 ),
|
||||
V( 105, 0x5627, 105, 106, 1 ),
|
||||
V( 106, 0x50e7, 108, 107, 0 ),
|
||||
V( 107, 0x4b85, 109, 103, 0 ),
|
||||
V( 108, 0x5597, 110, 109, 0 ),
|
||||
V( 109, 0x504f, 111, 107, 0 ),
|
||||
V( 110, 0x5a10, 110, 111, 1 ),
|
||||
V( 111, 0x5522, 112, 109, 0 ),
|
||||
V( 112, 0x59eb, 112, 111, 1 ),
|
||||
/*
|
||||
* This last entry is used for fixed probability estimate of 0.5
|
||||
* as recommended in Section 10.3 Table 5 of ITU-T Rec. T.851.
|
||||
*/
|
||||
V( 113, 0x5a1d, 113, 113, 0 )
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* jcomapi.c
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1994-1997, Thomas G. Lane.0
|
||||
* It was modified by The libjpeg-turbo Project to include only code relevant
|
||||
* to libjpeg-turbo.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains application interface routines that are used for both
|
||||
* compression and decompression.
|
||||
*/
|
||||
|
||||
#define JPEG_INTERNALS
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
|
||||
|
||||
/*
|
||||
* Abort processing of a JPEG compression or decompression operation,
|
||||
* but don't destroy the object itself.
|
||||
*
|
||||
* For this, we merely clean up all the nonpermanent memory pools.
|
||||
* Note that temp files (virtual arrays) are not allowed to belong to
|
||||
* the permanent pool, so we will be able to close all temp files here.
|
||||
* Closing a data source or destination, if necessary, is the application's
|
||||
* responsibility.
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_abort (j_common_ptr cinfo)
|
||||
{
|
||||
int pool;
|
||||
|
||||
/* Do nothing if called on a not-initialized or destroyed JPEG object. */
|
||||
if (cinfo->mem == NULL)
|
||||
return;
|
||||
|
||||
/* Releasing pools in reverse order might help avoid fragmentation
|
||||
* with some (brain-damaged) malloc libraries.
|
||||
*/
|
||||
for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
|
||||
(*cinfo->mem->free_pool) (cinfo, pool);
|
||||
}
|
||||
|
||||
/* Reset overall state for possible reuse of object */
|
||||
if (cinfo->is_decompressor) {
|
||||
cinfo->global_state = DSTATE_START;
|
||||
/* Try to keep application from accessing now-deleted marker list.
|
||||
* A bit kludgy to do it here, but this is the most central place.
|
||||
*/
|
||||
((j_decompress_ptr) cinfo)->marker_list = NULL;
|
||||
} else {
|
||||
cinfo->global_state = CSTATE_START;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Destruction of a JPEG object.
|
||||
*
|
||||
* Everything gets deallocated except the master jpeg_compress_struct itself
|
||||
* and the error manager struct. Both of these are supplied by the application
|
||||
* and must be freed, if necessary, by the application. (Often they are on
|
||||
* the stack and so don't need to be freed anyway.)
|
||||
* Closing a data source or destination, if necessary, is the application's
|
||||
* responsibility.
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_destroy (j_common_ptr cinfo)
|
||||
{
|
||||
/* We need only tell the memory manager to release everything. */
|
||||
/* NB: mem pointer is NULL if memory mgr failed to initialize. */
|
||||
if (cinfo->mem != NULL)
|
||||
(*cinfo->mem->self_destruct) (cinfo);
|
||||
cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
|
||||
cinfo->global_state = 0; /* mark it destroyed */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Convenience routines for allocating quantization and Huffman tables.
|
||||
* (Would jutils.c be a more reasonable place to put these?)
|
||||
*/
|
||||
|
||||
GLOBAL(JQUANT_TBL *)
|
||||
jpeg_alloc_quant_table (j_common_ptr cinfo)
|
||||
{
|
||||
JQUANT_TBL *tbl;
|
||||
|
||||
tbl = (JQUANT_TBL *)
|
||||
(*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, sizeof(JQUANT_TBL));
|
||||
tbl->sent_table = FALSE; /* make sure this is false in any new table */
|
||||
return tbl;
|
||||
}
|
||||
|
||||
|
||||
GLOBAL(JHUFF_TBL *)
|
||||
jpeg_alloc_huff_table (j_common_ptr cinfo)
|
||||
{
|
||||
JHUFF_TBL *tbl;
|
||||
|
||||
tbl = (JHUFF_TBL *)
|
||||
(*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, sizeof(JHUFF_TBL));
|
||||
tbl->sent_table = FALSE; /* make sure this is false in any new table */
|
||||
return tbl;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/* jconfig.h. Generated from jconfig.h.in by configure. */
|
||||
/* Version ID for the JPEG library.
|
||||
* Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
|
||||
*/
|
||||
#define JPEG_LIB_VERSION 62
|
||||
|
||||
/* libjpeg-turbo version */
|
||||
#define LIBJPEG_TURBO_VERSION 1.4.0
|
||||
|
||||
/* Support arithmetic encoding */
|
||||
#define C_ARITH_CODING_SUPPORTED 1
|
||||
|
||||
/* Support arithmetic decoding */
|
||||
#define D_ARITH_CODING_SUPPORTED 1
|
||||
|
||||
/*
|
||||
* Define BITS_IN_JSAMPLE as either
|
||||
* 8 for 8-bit sample values (the usual setting)
|
||||
* 12 for 12-bit sample values
|
||||
* Only 8 and 12 are legal data precisions for lossy JPEG according to the
|
||||
* JPEG standard, and the IJG code does not support anything else!
|
||||
* We do not support run-time selection of data precision, sorry.
|
||||
*/
|
||||
|
||||
#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
|
||||
|
||||
/* Define to 1 if you have the <locale.h> header file. */
|
||||
#define HAVE_LOCALE_H 1
|
||||
|
||||
/* Define to 1 if you have the <stddef.h> header file. */
|
||||
#define HAVE_STDDEF_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if the system has the type `unsigned char'. */
|
||||
#define HAVE_UNSIGNED_CHAR 1
|
||||
|
||||
/* Define to 1 if the system has the type `unsigned short'. */
|
||||
#define HAVE_UNSIGNED_SHORT 1
|
||||
|
||||
/* Compiler does not support pointers to undefined structures. */
|
||||
/* #undef INCOMPLETE_TYPES_BROKEN */
|
||||
|
||||
/* Support in-memory source/destination managers */
|
||||
#define MEM_SRCDST_SUPPORTED 1
|
||||
|
||||
/* Define if you have BSD-like bzero and bcopy in <strings.h> rather than
|
||||
memset/memcpy in <string.h>. */
|
||||
/* #undef NEED_BSD_STRINGS */
|
||||
|
||||
/* Define if you need to include <sys/types.h> to get size_t. */
|
||||
#define NEED_SYS_TYPES_H 1
|
||||
|
||||
/* Define if your (broken) compiler shifts signed values as if they were
|
||||
unsigned. */
|
||||
/* #undef RIGHT_SHIFT_IS_UNSIGNED */
|
||||
|
||||
/* Use accelerated SIMD routines. */
|
||||
#define WITH_SIMD 1
|
||||
|
||||
/* Define to 1 if type `char' is unsigned and you are not using gcc. */
|
||||
#ifndef __CHAR_UNSIGNED__
|
||||
/* # undef __CHAR_UNSIGNED__ */
|
||||
#endif
|
||||
|
||||
/* Define to empty if `const' does not conform to ANSI C. */
|
||||
/* #undef const */
|
||||
|
||||
/* Define to `unsigned int' if <sys/types.h> does not define. */
|
||||
/* #undef size_t */
|
||||
@@ -0,0 +1,12 @@
|
||||
/* jconfigint.h. Generated from jconfigint.h.in by configure. */
|
||||
/* libjpeg-turbo build number */
|
||||
#define BUILD "20150109"
|
||||
|
||||
/* How to obtain function inlining. */
|
||||
#define INLINE inline __attribute__((always_inline))
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#define PACKAGE_NAME "libjpeg-turbo"
|
||||
|
||||
/* Version number of package */
|
||||
#define VERSION "1.4.0"
|
||||
@@ -0,0 +1,397 @@
|
||||
/*
|
||||
* jdapimin.c
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1994-1998, Thomas G. Lane.
|
||||
* It was modified by The libjpeg-turbo Project to include only code relevant
|
||||
* to libjpeg-turbo.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains application interface code for the decompression half
|
||||
* of the JPEG library. These are the "minimum" API routines that may be
|
||||
* needed in either the normal full-decompression case or the
|
||||
* transcoding-only case.
|
||||
*
|
||||
* Most of the routines intended to be called directly by an application
|
||||
* are in this file or in jdapistd.c. But also see jcomapi.c for routines
|
||||
* shared by compression and decompression, and jdtrans.c for the transcoding
|
||||
* case.
|
||||
*/
|
||||
|
||||
#define JPEG_INTERNALS
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
|
||||
|
||||
/*
|
||||
* Initialization of a JPEG decompression object.
|
||||
* The error manager must already be set up (in case memory manager fails).
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
|
||||
{
|
||||
int i;
|
||||
|
||||
/* Guard against version mismatches between library and caller. */
|
||||
cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
|
||||
if (version != JPEG_LIB_VERSION)
|
||||
ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
|
||||
if (structsize != sizeof(struct jpeg_decompress_struct))
|
||||
ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
|
||||
(int) sizeof(struct jpeg_decompress_struct), (int) structsize);
|
||||
|
||||
/* For debugging purposes, we zero the whole master structure.
|
||||
* But the application has already set the err pointer, and may have set
|
||||
* client_data, so we have to save and restore those fields.
|
||||
* Note: if application hasn't set client_data, tools like Purify may
|
||||
* complain here.
|
||||
*/
|
||||
{
|
||||
struct jpeg_error_mgr * err = cinfo->err;
|
||||
void * client_data = cinfo->client_data; /* ignore Purify complaint here */
|
||||
MEMZERO(cinfo, sizeof(struct jpeg_decompress_struct));
|
||||
cinfo->err = err;
|
||||
cinfo->client_data = client_data;
|
||||
}
|
||||
cinfo->is_decompressor = TRUE;
|
||||
|
||||
/* Initialize a memory manager instance for this object */
|
||||
jinit_memory_mgr((j_common_ptr) cinfo);
|
||||
|
||||
/* Zero out pointers to permanent structures. */
|
||||
cinfo->progress = NULL;
|
||||
cinfo->src = NULL;
|
||||
|
||||
for (i = 0; i < NUM_QUANT_TBLS; i++)
|
||||
cinfo->quant_tbl_ptrs[i] = NULL;
|
||||
|
||||
for (i = 0; i < NUM_HUFF_TBLS; i++) {
|
||||
cinfo->dc_huff_tbl_ptrs[i] = NULL;
|
||||
cinfo->ac_huff_tbl_ptrs[i] = NULL;
|
||||
}
|
||||
|
||||
/* Initialize marker processor so application can override methods
|
||||
* for COM, APPn markers before calling jpeg_read_header.
|
||||
*/
|
||||
cinfo->marker_list = NULL;
|
||||
jinit_marker_reader(cinfo);
|
||||
|
||||
/* And initialize the overall input controller. */
|
||||
jinit_input_controller(cinfo);
|
||||
|
||||
/* OK, I'm ready */
|
||||
cinfo->global_state = DSTATE_START;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Destruction of a JPEG decompression object
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_destroy_decompress (j_decompress_ptr cinfo)
|
||||
{
|
||||
jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Abort processing of a JPEG decompression operation,
|
||||
* but don't destroy the object itself.
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_abort_decompress (j_decompress_ptr cinfo)
|
||||
{
|
||||
jpeg_abort((j_common_ptr) cinfo); /* use common routine */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Set default decompression parameters.
|
||||
*/
|
||||
|
||||
LOCAL(void)
|
||||
default_decompress_parms (j_decompress_ptr cinfo)
|
||||
{
|
||||
/* Guess the input colorspace, and set output colorspace accordingly. */
|
||||
/* (Wish JPEG committee had provided a real way to specify this...) */
|
||||
/* Note application may override our guesses. */
|
||||
switch (cinfo->num_components) {
|
||||
case 1:
|
||||
cinfo->jpeg_color_space = JCS_GRAYSCALE;
|
||||
cinfo->out_color_space = JCS_GRAYSCALE;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
if (cinfo->saw_JFIF_marker) {
|
||||
cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
|
||||
} else if (cinfo->saw_Adobe_marker) {
|
||||
switch (cinfo->Adobe_transform) {
|
||||
case 0:
|
||||
cinfo->jpeg_color_space = JCS_RGB;
|
||||
break;
|
||||
case 1:
|
||||
cinfo->jpeg_color_space = JCS_YCbCr;
|
||||
break;
|
||||
default:
|
||||
WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
|
||||
cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
/* Saw no special markers, try to guess from the component IDs */
|
||||
int cid0 = cinfo->comp_info[0].component_id;
|
||||
int cid1 = cinfo->comp_info[1].component_id;
|
||||
int cid2 = cinfo->comp_info[2].component_id;
|
||||
|
||||
if (cid0 == 1 && cid1 == 2 && cid2 == 3)
|
||||
cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
|
||||
else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
|
||||
cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
|
||||
else {
|
||||
TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
|
||||
cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
|
||||
}
|
||||
}
|
||||
/* Always guess RGB is proper output colorspace. */
|
||||
cinfo->out_color_space = JCS_RGB;
|
||||
break;
|
||||
|
||||
case 4:
|
||||
if (cinfo->saw_Adobe_marker) {
|
||||
switch (cinfo->Adobe_transform) {
|
||||
case 0:
|
||||
cinfo->jpeg_color_space = JCS_CMYK;
|
||||
break;
|
||||
case 2:
|
||||
cinfo->jpeg_color_space = JCS_YCCK;
|
||||
break;
|
||||
default:
|
||||
WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
|
||||
cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
/* No special markers, assume straight CMYK. */
|
||||
cinfo->jpeg_color_space = JCS_CMYK;
|
||||
}
|
||||
cinfo->out_color_space = JCS_CMYK;
|
||||
break;
|
||||
|
||||
default:
|
||||
cinfo->jpeg_color_space = JCS_UNKNOWN;
|
||||
cinfo->out_color_space = JCS_UNKNOWN;
|
||||
break;
|
||||
}
|
||||
|
||||
/* Set defaults for other decompression parameters. */
|
||||
cinfo->scale_num = 1; /* 1:1 scaling */
|
||||
cinfo->scale_denom = 1;
|
||||
cinfo->output_gamma = 1.0;
|
||||
cinfo->buffered_image = FALSE;
|
||||
cinfo->raw_data_out = FALSE;
|
||||
cinfo->dct_method = JDCT_DEFAULT;
|
||||
cinfo->do_fancy_upsampling = TRUE;
|
||||
cinfo->do_block_smoothing = TRUE;
|
||||
cinfo->quantize_colors = FALSE;
|
||||
/* We set these in case application only sets quantize_colors. */
|
||||
cinfo->dither_mode = JDITHER_FS;
|
||||
#ifdef QUANT_2PASS_SUPPORTED
|
||||
cinfo->two_pass_quantize = TRUE;
|
||||
#else
|
||||
cinfo->two_pass_quantize = FALSE;
|
||||
#endif
|
||||
cinfo->desired_number_of_colors = 256;
|
||||
cinfo->colormap = NULL;
|
||||
/* Initialize for no mode change in buffered-image mode. */
|
||||
cinfo->enable_1pass_quant = FALSE;
|
||||
cinfo->enable_external_quant = FALSE;
|
||||
cinfo->enable_2pass_quant = FALSE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Decompression startup: read start of JPEG datastream to see what's there.
|
||||
* Need only initialize JPEG object and supply a data source before calling.
|
||||
*
|
||||
* This routine will read as far as the first SOS marker (ie, actual start of
|
||||
* compressed data), and will save all tables and parameters in the JPEG
|
||||
* object. It will also initialize the decompression parameters to default
|
||||
* values, and finally return JPEG_HEADER_OK. On return, the application may
|
||||
* adjust the decompression parameters and then call jpeg_start_decompress.
|
||||
* (Or, if the application only wanted to determine the image parameters,
|
||||
* the data need not be decompressed. In that case, call jpeg_abort or
|
||||
* jpeg_destroy to release any temporary space.)
|
||||
* If an abbreviated (tables only) datastream is presented, the routine will
|
||||
* return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
|
||||
* re-use the JPEG object to read the abbreviated image datastream(s).
|
||||
* It is unnecessary (but OK) to call jpeg_abort in this case.
|
||||
* The JPEG_SUSPENDED return code only occurs if the data source module
|
||||
* requests suspension of the decompressor. In this case the application
|
||||
* should load more source data and then re-call jpeg_read_header to resume
|
||||
* processing.
|
||||
* If a non-suspending data source is used and require_image is TRUE, then the
|
||||
* return code need not be inspected since only JPEG_HEADER_OK is possible.
|
||||
*
|
||||
* This routine is now just a front end to jpeg_consume_input, with some
|
||||
* extra error checking.
|
||||
*/
|
||||
|
||||
GLOBAL(int)
|
||||
jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
|
||||
{
|
||||
int retcode;
|
||||
|
||||
if (cinfo->global_state != DSTATE_START &&
|
||||
cinfo->global_state != DSTATE_INHEADER)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
|
||||
retcode = jpeg_consume_input(cinfo);
|
||||
|
||||
switch (retcode) {
|
||||
case JPEG_REACHED_SOS:
|
||||
retcode = JPEG_HEADER_OK;
|
||||
break;
|
||||
case JPEG_REACHED_EOI:
|
||||
if (require_image) /* Complain if application wanted an image */
|
||||
ERREXIT(cinfo, JERR_NO_IMAGE);
|
||||
/* Reset to start state; it would be safer to require the application to
|
||||
* call jpeg_abort, but we can't change it now for compatibility reasons.
|
||||
* A side effect is to free any temporary memory (there shouldn't be any).
|
||||
*/
|
||||
jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
|
||||
retcode = JPEG_HEADER_TABLES_ONLY;
|
||||
break;
|
||||
case JPEG_SUSPENDED:
|
||||
/* no work */
|
||||
break;
|
||||
}
|
||||
|
||||
return retcode;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Consume data in advance of what the decompressor requires.
|
||||
* This can be called at any time once the decompressor object has
|
||||
* been created and a data source has been set up.
|
||||
*
|
||||
* This routine is essentially a state machine that handles a couple
|
||||
* of critical state-transition actions, namely initial setup and
|
||||
* transition from header scanning to ready-for-start_decompress.
|
||||
* All the actual input is done via the input controller's consume_input
|
||||
* method.
|
||||
*/
|
||||
|
||||
GLOBAL(int)
|
||||
jpeg_consume_input (j_decompress_ptr cinfo)
|
||||
{
|
||||
int retcode = JPEG_SUSPENDED;
|
||||
|
||||
/* NB: every possible DSTATE value should be listed in this switch */
|
||||
switch (cinfo->global_state) {
|
||||
case DSTATE_START:
|
||||
/* Start-of-datastream actions: reset appropriate modules */
|
||||
(*cinfo->inputctl->reset_input_controller) (cinfo);
|
||||
/* Initialize application's data source module */
|
||||
(*cinfo->src->init_source) (cinfo);
|
||||
cinfo->global_state = DSTATE_INHEADER;
|
||||
/*FALLTHROUGH*/
|
||||
case DSTATE_INHEADER:
|
||||
retcode = (*cinfo->inputctl->consume_input) (cinfo);
|
||||
if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
|
||||
/* Set up default parameters based on header data */
|
||||
default_decompress_parms(cinfo);
|
||||
/* Set global state: ready for start_decompress */
|
||||
cinfo->global_state = DSTATE_READY;
|
||||
}
|
||||
break;
|
||||
case DSTATE_READY:
|
||||
/* Can't advance past first SOS until start_decompress is called */
|
||||
retcode = JPEG_REACHED_SOS;
|
||||
break;
|
||||
case DSTATE_PRELOAD:
|
||||
case DSTATE_PRESCAN:
|
||||
case DSTATE_SCANNING:
|
||||
case DSTATE_RAW_OK:
|
||||
case DSTATE_BUFIMAGE:
|
||||
case DSTATE_BUFPOST:
|
||||
case DSTATE_STOPPING:
|
||||
retcode = (*cinfo->inputctl->consume_input) (cinfo);
|
||||
break;
|
||||
default:
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
}
|
||||
return retcode;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Have we finished reading the input file?
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_input_complete (j_decompress_ptr cinfo)
|
||||
{
|
||||
/* Check for valid jpeg object */
|
||||
if (cinfo->global_state < DSTATE_START ||
|
||||
cinfo->global_state > DSTATE_STOPPING)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
return cinfo->inputctl->eoi_reached;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Is there more than one scan?
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_has_multiple_scans (j_decompress_ptr cinfo)
|
||||
{
|
||||
/* Only valid after jpeg_read_header completes */
|
||||
if (cinfo->global_state < DSTATE_READY ||
|
||||
cinfo->global_state > DSTATE_STOPPING)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
return cinfo->inputctl->has_multiple_scans;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Finish JPEG decompression.
|
||||
*
|
||||
* This will normally just verify the file trailer and release temp storage.
|
||||
*
|
||||
* Returns FALSE if suspended. The return value need be inspected only if
|
||||
* a suspending data source is used.
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_finish_decompress (j_decompress_ptr cinfo)
|
||||
{
|
||||
if ((cinfo->global_state == DSTATE_SCANNING ||
|
||||
cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
|
||||
/* Terminate final pass of non-buffered mode */
|
||||
if (cinfo->output_scanline < cinfo->output_height)
|
||||
ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
|
||||
(*cinfo->master->finish_output_pass) (cinfo);
|
||||
cinfo->global_state = DSTATE_STOPPING;
|
||||
} else if (cinfo->global_state == DSTATE_BUFIMAGE) {
|
||||
/* Finishing after a buffered-image operation */
|
||||
cinfo->global_state = DSTATE_STOPPING;
|
||||
} else if (cinfo->global_state != DSTATE_STOPPING) {
|
||||
/* STOPPING = repeat call after a suspension, anything else is error */
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
}
|
||||
/* Read until EOI */
|
||||
while (! cinfo->inputctl->eoi_reached) {
|
||||
if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
|
||||
return FALSE; /* Suspend, come back later */
|
||||
}
|
||||
/* Do final cleanup */
|
||||
(*cinfo->src->term_source) (cinfo);
|
||||
/* We can use jpeg_abort to release memory and reset global_state */
|
||||
jpeg_abort((j_common_ptr) cinfo);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
* jdapistd.c
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1994-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2010, D. R. Commander.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains application interface code for the decompression half
|
||||
* of the JPEG library. These are the "standard" API routines that are
|
||||
* used in the normal full-decompression case. They are not used by a
|
||||
* transcoding-only application. Note that if an application links in
|
||||
* jpeg_start_decompress, it will end up linking in the entire decompressor.
|
||||
* We thus must separate this file from jdapimin.c to avoid linking the
|
||||
* whole decompression library into a transcoder.
|
||||
*/
|
||||
|
||||
#define JPEG_INTERNALS
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
#include "jpegcomp.h"
|
||||
|
||||
|
||||
/* Forward declarations */
|
||||
LOCAL(boolean) output_pass_setup (j_decompress_ptr cinfo);
|
||||
|
||||
|
||||
/*
|
||||
* Decompression initialization.
|
||||
* jpeg_read_header must be completed before calling this.
|
||||
*
|
||||
* If a multipass operating mode was selected, this will do all but the
|
||||
* last pass, and thus may take a great deal of time.
|
||||
*
|
||||
* Returns FALSE if suspended. The return value need be inspected only if
|
||||
* a suspending data source is used.
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_start_decompress (j_decompress_ptr cinfo)
|
||||
{
|
||||
if (cinfo->global_state == DSTATE_READY) {
|
||||
/* First call: initialize master control, select active modules */
|
||||
jinit_master_decompress(cinfo);
|
||||
if (cinfo->buffered_image) {
|
||||
/* No more work here; expecting jpeg_start_output next */
|
||||
cinfo->global_state = DSTATE_BUFIMAGE;
|
||||
return TRUE;
|
||||
}
|
||||
cinfo->global_state = DSTATE_PRELOAD;
|
||||
}
|
||||
if (cinfo->global_state == DSTATE_PRELOAD) {
|
||||
/* If file has multiple scans, absorb them all into the coef buffer */
|
||||
if (cinfo->inputctl->has_multiple_scans) {
|
||||
#ifdef D_MULTISCAN_FILES_SUPPORTED
|
||||
for (;;) {
|
||||
int retcode;
|
||||
/* Call progress monitor hook if present */
|
||||
if (cinfo->progress != NULL)
|
||||
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
|
||||
/* Absorb some more input */
|
||||
retcode = (*cinfo->inputctl->consume_input) (cinfo);
|
||||
if (retcode == JPEG_SUSPENDED)
|
||||
return FALSE;
|
||||
if (retcode == JPEG_REACHED_EOI)
|
||||
break;
|
||||
/* Advance progress counter if appropriate */
|
||||
if (cinfo->progress != NULL &&
|
||||
(retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
|
||||
if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
|
||||
/* jdmaster underestimated number of scans; ratchet up one scan */
|
||||
cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
ERREXIT(cinfo, JERR_NOT_COMPILED);
|
||||
#endif /* D_MULTISCAN_FILES_SUPPORTED */
|
||||
}
|
||||
cinfo->output_scan_number = cinfo->input_scan_number;
|
||||
} else if (cinfo->global_state != DSTATE_PRESCAN)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
/* Perform any dummy output passes, and set up for the final pass */
|
||||
return output_pass_setup(cinfo);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Set up for an output pass, and perform any dummy pass(es) needed.
|
||||
* Common subroutine for jpeg_start_decompress and jpeg_start_output.
|
||||
* Entry: global_state = DSTATE_PRESCAN only if previously suspended.
|
||||
* Exit: If done, returns TRUE and sets global_state for proper output mode.
|
||||
* If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
|
||||
*/
|
||||
|
||||
LOCAL(boolean)
|
||||
output_pass_setup (j_decompress_ptr cinfo)
|
||||
{
|
||||
if (cinfo->global_state != DSTATE_PRESCAN) {
|
||||
/* First call: do pass setup */
|
||||
(*cinfo->master->prepare_for_output_pass) (cinfo);
|
||||
cinfo->output_scanline = 0;
|
||||
cinfo->global_state = DSTATE_PRESCAN;
|
||||
}
|
||||
/* Loop over any required dummy passes */
|
||||
while (cinfo->master->is_dummy_pass) {
|
||||
#ifdef QUANT_2PASS_SUPPORTED
|
||||
/* Crank through the dummy pass */
|
||||
while (cinfo->output_scanline < cinfo->output_height) {
|
||||
JDIMENSION last_scanline;
|
||||
/* Call progress monitor hook if present */
|
||||
if (cinfo->progress != NULL) {
|
||||
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
|
||||
cinfo->progress->pass_limit = (long) cinfo->output_height;
|
||||
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
|
||||
}
|
||||
/* Process some data */
|
||||
last_scanline = cinfo->output_scanline;
|
||||
(*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
|
||||
&cinfo->output_scanline, (JDIMENSION) 0);
|
||||
if (cinfo->output_scanline == last_scanline)
|
||||
return FALSE; /* No progress made, must suspend */
|
||||
}
|
||||
/* Finish up dummy pass, and set up for another one */
|
||||
(*cinfo->master->finish_output_pass) (cinfo);
|
||||
(*cinfo->master->prepare_for_output_pass) (cinfo);
|
||||
cinfo->output_scanline = 0;
|
||||
#else
|
||||
ERREXIT(cinfo, JERR_NOT_COMPILED);
|
||||
#endif /* QUANT_2PASS_SUPPORTED */
|
||||
}
|
||||
/* Ready for application to drive output pass through
|
||||
* jpeg_read_scanlines or jpeg_read_raw_data.
|
||||
*/
|
||||
cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Read some scanlines of data from the JPEG decompressor.
|
||||
*
|
||||
* The return value will be the number of lines actually read.
|
||||
* This may be less than the number requested in several cases,
|
||||
* including bottom of image, data source suspension, and operating
|
||||
* modes that emit multiple scanlines at a time.
|
||||
*
|
||||
* Note: we warn about excess calls to jpeg_read_scanlines() since
|
||||
* this likely signals an application programmer error. However,
|
||||
* an oversize buffer (max_lines > scanlines remaining) is not an error.
|
||||
*/
|
||||
|
||||
GLOBAL(JDIMENSION)
|
||||
jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
|
||||
JDIMENSION max_lines)
|
||||
{
|
||||
JDIMENSION row_ctr;
|
||||
|
||||
if (cinfo->global_state != DSTATE_SCANNING)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
if (cinfo->output_scanline >= cinfo->output_height) {
|
||||
WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Call progress monitor hook if present */
|
||||
if (cinfo->progress != NULL) {
|
||||
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
|
||||
cinfo->progress->pass_limit = (long) cinfo->output_height;
|
||||
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
|
||||
}
|
||||
|
||||
/* Process some data */
|
||||
row_ctr = 0;
|
||||
(*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
|
||||
cinfo->output_scanline += row_ctr;
|
||||
return row_ctr;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Alternate entry point to read raw data.
|
||||
* Processes exactly one iMCU row per call, unless suspended.
|
||||
*/
|
||||
|
||||
GLOBAL(JDIMENSION)
|
||||
jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
|
||||
JDIMENSION max_lines)
|
||||
{
|
||||
JDIMENSION lines_per_iMCU_row;
|
||||
|
||||
if (cinfo->global_state != DSTATE_RAW_OK)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
if (cinfo->output_scanline >= cinfo->output_height) {
|
||||
WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Call progress monitor hook if present */
|
||||
if (cinfo->progress != NULL) {
|
||||
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
|
||||
cinfo->progress->pass_limit = (long) cinfo->output_height;
|
||||
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
|
||||
}
|
||||
|
||||
/* Verify that at least one iMCU row can be returned. */
|
||||
lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->_min_DCT_scaled_size;
|
||||
if (max_lines < lines_per_iMCU_row)
|
||||
ERREXIT(cinfo, JERR_BUFFER_SIZE);
|
||||
|
||||
/* Decompress directly into user's buffer. */
|
||||
if (! (*cinfo->coef->decompress_data) (cinfo, data))
|
||||
return 0; /* suspension forced, can do nothing more */
|
||||
|
||||
/* OK, we processed one iMCU row. */
|
||||
cinfo->output_scanline += lines_per_iMCU_row;
|
||||
return lines_per_iMCU_row;
|
||||
}
|
||||
|
||||
|
||||
/* Additional entry points for buffered-image mode. */
|
||||
|
||||
#ifdef D_MULTISCAN_FILES_SUPPORTED
|
||||
|
||||
/*
|
||||
* Initialize for an output pass in buffered-image mode.
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
|
||||
{
|
||||
if (cinfo->global_state != DSTATE_BUFIMAGE &&
|
||||
cinfo->global_state != DSTATE_PRESCAN)
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
/* Limit scan number to valid range */
|
||||
if (scan_number <= 0)
|
||||
scan_number = 1;
|
||||
if (cinfo->inputctl->eoi_reached &&
|
||||
scan_number > cinfo->input_scan_number)
|
||||
scan_number = cinfo->input_scan_number;
|
||||
cinfo->output_scan_number = scan_number;
|
||||
/* Perform any dummy output passes, and set up for the real pass */
|
||||
return output_pass_setup(cinfo);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Finish up after an output pass in buffered-image mode.
|
||||
*
|
||||
* Returns FALSE if suspended. The return value need be inspected only if
|
||||
* a suspending data source is used.
|
||||
*/
|
||||
|
||||
GLOBAL(boolean)
|
||||
jpeg_finish_output (j_decompress_ptr cinfo)
|
||||
{
|
||||
if ((cinfo->global_state == DSTATE_SCANNING ||
|
||||
cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
|
||||
/* Terminate this pass. */
|
||||
/* We do not require the whole pass to have been completed. */
|
||||
(*cinfo->master->finish_output_pass) (cinfo);
|
||||
cinfo->global_state = DSTATE_BUFPOST;
|
||||
} else if (cinfo->global_state != DSTATE_BUFPOST) {
|
||||
/* BUFPOST = repeat call after a suspension, anything else is error */
|
||||
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
|
||||
}
|
||||
/* Read markers looking for SOS or EOI */
|
||||
while (cinfo->input_scan_number <= cinfo->output_scan_number &&
|
||||
! cinfo->inputctl->eoi_reached) {
|
||||
if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
|
||||
return FALSE; /* Suspend, come back later */
|
||||
}
|
||||
cinfo->global_state = DSTATE_BUFIMAGE;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
#endif /* D_MULTISCAN_FILES_SUPPORTED */
|
||||
@@ -0,0 +1,763 @@
|
||||
/*
|
||||
* jdarith.c
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Developed 1997-2009 by Guido Vollbeding.
|
||||
* It was modified by The libjpeg-turbo Project to include only code relevant
|
||||
* to libjpeg-turbo.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains portable arithmetic entropy decoding routines for JPEG
|
||||
* (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
|
||||
*
|
||||
* Both sequential and progressive modes are supported in this single module.
|
||||
*
|
||||
* Suspension is not currently supported in this module.
|
||||
*/
|
||||
|
||||
#define JPEG_INTERNALS
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
|
||||
|
||||
/* Expanded entropy decoder object for arithmetic decoding. */
|
||||
|
||||
typedef struct {
|
||||
struct jpeg_entropy_decoder pub; /* public fields */
|
||||
|
||||
INT32 c; /* C register, base of coding interval + input bit buffer */
|
||||
INT32 a; /* A register, normalized size of coding interval */
|
||||
int ct; /* bit shift counter, # of bits left in bit buffer part of C */
|
||||
/* init: ct = -16 */
|
||||
/* run: ct = 0..7 */
|
||||
/* error: ct = -1 */
|
||||
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
|
||||
int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
|
||||
|
||||
unsigned int restarts_to_go; /* MCUs left in this restart interval */
|
||||
|
||||
/* Pointers to statistics areas (these workspaces have image lifespan) */
|
||||
unsigned char * dc_stats[NUM_ARITH_TBLS];
|
||||
unsigned char * ac_stats[NUM_ARITH_TBLS];
|
||||
|
||||
/* Statistics bin for coding with fixed probability 0.5 */
|
||||
unsigned char fixed_bin[4];
|
||||
} arith_entropy_decoder;
|
||||
|
||||
typedef arith_entropy_decoder * arith_entropy_ptr;
|
||||
|
||||
/* The following two definitions specify the allocation chunk size
|
||||
* for the statistics area.
|
||||
* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
|
||||
* 49 statistics bins for DC, and 245 statistics bins for AC coding.
|
||||
*
|
||||
* We use a compact representation with 1 byte per statistics bin,
|
||||
* thus the numbers directly represent byte sizes.
|
||||
* This 1 byte per statistics bin contains the meaning of the MPS
|
||||
* (more probable symbol) in the highest bit (mask 0x80), and the
|
||||
* index into the probability estimation state machine table
|
||||
* in the lower bits (mask 0x7F).
|
||||
*/
|
||||
|
||||
#define DC_STAT_BINS 64
|
||||
#define AC_STAT_BINS 256
|
||||
|
||||
|
||||
LOCAL(int)
|
||||
get_byte (j_decompress_ptr cinfo)
|
||||
/* Read next input byte; we do not support suspension in this module. */
|
||||
{
|
||||
struct jpeg_source_mgr * src = cinfo->src;
|
||||
|
||||
if (src->bytes_in_buffer == 0)
|
||||
if (! (*src->fill_input_buffer) (cinfo))
|
||||
ERREXIT(cinfo, JERR_CANT_SUSPEND);
|
||||
src->bytes_in_buffer--;
|
||||
return GETJOCTET(*src->next_input_byte++);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* The core arithmetic decoding routine (common in JPEG and JBIG).
|
||||
* This needs to go as fast as possible.
|
||||
* Machine-dependent optimization facilities
|
||||
* are not utilized in this portable implementation.
|
||||
* However, this code should be fairly efficient and
|
||||
* may be a good base for further optimizations anyway.
|
||||
*
|
||||
* Return value is 0 or 1 (binary decision).
|
||||
*
|
||||
* Note: I've changed the handling of the code base & bit
|
||||
* buffer register C compared to other implementations
|
||||
* based on the standards layout & procedures.
|
||||
* While it also contains both the actual base of the
|
||||
* coding interval (16 bits) and the next-bits buffer,
|
||||
* the cut-point between these two parts is floating
|
||||
* (instead of fixed) with the bit shift counter CT.
|
||||
* Thus, we also need only one (variable instead of
|
||||
* fixed size) shift for the LPS/MPS decision, and
|
||||
* we can get away with any renormalization update
|
||||
* of C (except for new data insertion, of course).
|
||||
*
|
||||
* I've also introduced a new scheme for accessing
|
||||
* the probability estimation state machine table,
|
||||
* derived from Markus Kuhn's JBIG implementation.
|
||||
*/
|
||||
|
||||
LOCAL(int)
|
||||
arith_decode (j_decompress_ptr cinfo, unsigned char *st)
|
||||
{
|
||||
register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
|
||||
register unsigned char nl, nm;
|
||||
register INT32 qe, temp;
|
||||
register int sv, data;
|
||||
|
||||
/* Renormalization & data input per section D.2.6 */
|
||||
while (e->a < 0x8000L) {
|
||||
if (--e->ct < 0) {
|
||||
/* Need to fetch next data byte */
|
||||
if (cinfo->unread_marker)
|
||||
data = 0; /* stuff zero data */
|
||||
else {
|
||||
data = get_byte(cinfo); /* read next input byte */
|
||||
if (data == 0xFF) { /* zero stuff or marker code */
|
||||
do data = get_byte(cinfo);
|
||||
while (data == 0xFF); /* swallow extra 0xFF bytes */
|
||||
if (data == 0)
|
||||
data = 0xFF; /* discard stuffed zero byte */
|
||||
else {
|
||||
/* Note: Different from the Huffman decoder, hitting
|
||||
* a marker while processing the compressed data
|
||||
* segment is legal in arithmetic coding.
|
||||
* The convention is to supply zero data
|
||||
* then until decoding is complete.
|
||||
*/
|
||||
cinfo->unread_marker = data;
|
||||
data = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
e->c = (e->c << 8) | data; /* insert data into C register */
|
||||
if ((e->ct += 8) < 0) /* update bit shift counter */
|
||||
/* Need more initial bytes */
|
||||
if (++e->ct == 0)
|
||||
/* Got 2 initial bytes -> re-init A and exit loop */
|
||||
e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
|
||||
}
|
||||
e->a <<= 1;
|
||||
}
|
||||
|
||||
/* Fetch values from our compact representation of Table D.2:
|
||||
* Qe values and probability estimation state machine
|
||||
*/
|
||||
sv = *st;
|
||||
qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */
|
||||
nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */
|
||||
nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */
|
||||
|
||||
/* Decode & estimation procedures per sections D.2.4 & D.2.5 */
|
||||
temp = e->a - qe;
|
||||
e->a = temp;
|
||||
temp <<= e->ct;
|
||||
if (e->c >= temp) {
|
||||
e->c -= temp;
|
||||
/* Conditional LPS (less probable symbol) exchange */
|
||||
if (e->a < qe) {
|
||||
e->a = qe;
|
||||
*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
|
||||
} else {
|
||||
e->a = qe;
|
||||
*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
|
||||
sv ^= 0x80; /* Exchange LPS/MPS */
|
||||
}
|
||||
} else if (e->a < 0x8000L) {
|
||||
/* Conditional MPS (more probable symbol) exchange */
|
||||
if (e->a < qe) {
|
||||
*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
|
||||
sv ^= 0x80; /* Exchange LPS/MPS */
|
||||
} else {
|
||||
*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
|
||||
}
|
||||
}
|
||||
|
||||
return sv >> 7;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Check for a restart marker & resynchronize decoder.
|
||||
*/
|
||||
|
||||
LOCAL(void)
|
||||
process_restart (j_decompress_ptr cinfo)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
int ci;
|
||||
jpeg_component_info * compptr;
|
||||
|
||||
/* Advance past the RSTn marker */
|
||||
if (! (*cinfo->marker->read_restart_marker) (cinfo))
|
||||
ERREXIT(cinfo, JERR_CANT_SUSPEND);
|
||||
|
||||
/* Re-initialize statistics areas */
|
||||
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
|
||||
compptr = cinfo->cur_comp_info[ci];
|
||||
if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
|
||||
MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
|
||||
/* Reset DC predictions to 0 */
|
||||
entropy->last_dc_val[ci] = 0;
|
||||
entropy->dc_context[ci] = 0;
|
||||
}
|
||||
if (! cinfo->progressive_mode || cinfo->Ss) {
|
||||
MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
|
||||
}
|
||||
}
|
||||
|
||||
/* Reset arithmetic decoding variables */
|
||||
entropy->c = 0;
|
||||
entropy->a = 0;
|
||||
entropy->ct = -16; /* force reading 2 initial bytes to fill C */
|
||||
|
||||
/* Reset restart counter */
|
||||
entropy->restarts_to_go = cinfo->restart_interval;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Arithmetic MCU decoding.
|
||||
* Each of these routines decodes and returns one MCU's worth of
|
||||
* arithmetic-compressed coefficients.
|
||||
* The coefficients are reordered from zigzag order into natural array order,
|
||||
* but are not dequantized.
|
||||
*
|
||||
* The i'th block of the MCU is stored into the block pointed to by
|
||||
* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
|
||||
*/
|
||||
|
||||
/*
|
||||
* MCU decoding for DC initial scan (either spectral selection,
|
||||
* or first pass of successive approximation).
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
JBLOCKROW block;
|
||||
unsigned char *st;
|
||||
int blkn, ci, tbl, sign;
|
||||
int v, m;
|
||||
|
||||
/* Process restart marker if needed */
|
||||
if (cinfo->restart_interval) {
|
||||
if (entropy->restarts_to_go == 0)
|
||||
process_restart(cinfo);
|
||||
entropy->restarts_to_go--;
|
||||
}
|
||||
|
||||
if (entropy->ct == -1) return TRUE; /* if error do nothing */
|
||||
|
||||
/* Outer loop handles each block in the MCU */
|
||||
|
||||
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
|
||||
block = MCU_data[blkn];
|
||||
ci = cinfo->MCU_membership[blkn];
|
||||
tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
|
||||
|
||||
/* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
|
||||
|
||||
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
|
||||
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
|
||||
|
||||
/* Figure F.19: Decode_DC_DIFF */
|
||||
if (arith_decode(cinfo, st) == 0)
|
||||
entropy->dc_context[ci] = 0;
|
||||
else {
|
||||
/* Figure F.21: Decoding nonzero value v */
|
||||
/* Figure F.22: Decoding the sign of v */
|
||||
sign = arith_decode(cinfo, st + 1);
|
||||
st += 2; st += sign;
|
||||
/* Figure F.23: Decoding the magnitude category of v */
|
||||
if ((m = arith_decode(cinfo, st)) != 0) {
|
||||
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
|
||||
while (arith_decode(cinfo, st)) {
|
||||
if ((m <<= 1) == 0x8000) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* magnitude overflow */
|
||||
return TRUE;
|
||||
}
|
||||
st += 1;
|
||||
}
|
||||
}
|
||||
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
|
||||
if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
|
||||
entropy->dc_context[ci] = 0; /* zero diff category */
|
||||
else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
|
||||
entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
|
||||
else
|
||||
entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */
|
||||
v = m;
|
||||
/* Figure F.24: Decoding the magnitude bit pattern of v */
|
||||
st += 14;
|
||||
while (m >>= 1)
|
||||
if (arith_decode(cinfo, st)) v |= m;
|
||||
v += 1; if (sign) v = -v;
|
||||
entropy->last_dc_val[ci] += v;
|
||||
}
|
||||
|
||||
/* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
|
||||
(*block)[0] = (JCOEF) (entropy->last_dc_val[ci] << cinfo->Al);
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* MCU decoding for AC initial scan (either spectral selection,
|
||||
* or first pass of successive approximation).
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
JBLOCKROW block;
|
||||
unsigned char *st;
|
||||
int tbl, sign, k;
|
||||
int v, m;
|
||||
|
||||
/* Process restart marker if needed */
|
||||
if (cinfo->restart_interval) {
|
||||
if (entropy->restarts_to_go == 0)
|
||||
process_restart(cinfo);
|
||||
entropy->restarts_to_go--;
|
||||
}
|
||||
|
||||
if (entropy->ct == -1) return TRUE; /* if error do nothing */
|
||||
|
||||
/* There is always only one block per MCU */
|
||||
block = MCU_data[0];
|
||||
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
|
||||
|
||||
/* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
|
||||
|
||||
/* Figure F.20: Decode_AC_coefficients */
|
||||
for (k = cinfo->Ss; k <= cinfo->Se; k++) {
|
||||
st = entropy->ac_stats[tbl] + 3 * (k - 1);
|
||||
if (arith_decode(cinfo, st)) break; /* EOB flag */
|
||||
while (arith_decode(cinfo, st + 1) == 0) {
|
||||
st += 3; k++;
|
||||
if (k > cinfo->Se) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* spectral overflow */
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
/* Figure F.21: Decoding nonzero value v */
|
||||
/* Figure F.22: Decoding the sign of v */
|
||||
sign = arith_decode(cinfo, entropy->fixed_bin);
|
||||
st += 2;
|
||||
/* Figure F.23: Decoding the magnitude category of v */
|
||||
if ((m = arith_decode(cinfo, st)) != 0) {
|
||||
if (arith_decode(cinfo, st)) {
|
||||
m <<= 1;
|
||||
st = entropy->ac_stats[tbl] +
|
||||
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
|
||||
while (arith_decode(cinfo, st)) {
|
||||
if ((m <<= 1) == 0x8000) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* magnitude overflow */
|
||||
return TRUE;
|
||||
}
|
||||
st += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
v = m;
|
||||
/* Figure F.24: Decoding the magnitude bit pattern of v */
|
||||
st += 14;
|
||||
while (m >>= 1)
|
||||
if (arith_decode(cinfo, st)) v |= m;
|
||||
v += 1; if (sign) v = -v;
|
||||
/* Scale and output coefficient in natural (dezigzagged) order */
|
||||
(*block)[jpeg_natural_order[k]] = (JCOEF) (v << cinfo->Al);
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* MCU decoding for DC successive approximation refinement scan.
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
unsigned char *st;
|
||||
int p1, blkn;
|
||||
|
||||
/* Process restart marker if needed */
|
||||
if (cinfo->restart_interval) {
|
||||
if (entropy->restarts_to_go == 0)
|
||||
process_restart(cinfo);
|
||||
entropy->restarts_to_go--;
|
||||
}
|
||||
|
||||
st = entropy->fixed_bin; /* use fixed probability estimation */
|
||||
p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
|
||||
|
||||
/* Outer loop handles each block in the MCU */
|
||||
|
||||
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
|
||||
/* Encoded data is simply the next bit of the two's-complement DC value */
|
||||
if (arith_decode(cinfo, st))
|
||||
MCU_data[blkn][0][0] |= p1;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* MCU decoding for AC successive approximation refinement scan.
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
JBLOCKROW block;
|
||||
JCOEFPTR thiscoef;
|
||||
unsigned char *st;
|
||||
int tbl, k, kex;
|
||||
int p1, m1;
|
||||
|
||||
/* Process restart marker if needed */
|
||||
if (cinfo->restart_interval) {
|
||||
if (entropy->restarts_to_go == 0)
|
||||
process_restart(cinfo);
|
||||
entropy->restarts_to_go--;
|
||||
}
|
||||
|
||||
if (entropy->ct == -1) return TRUE; /* if error do nothing */
|
||||
|
||||
/* There is always only one block per MCU */
|
||||
block = MCU_data[0];
|
||||
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
|
||||
|
||||
p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
|
||||
m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
|
||||
|
||||
/* Establish EOBx (previous stage end-of-block) index */
|
||||
for (kex = cinfo->Se; kex > 0; kex--)
|
||||
if ((*block)[jpeg_natural_order[kex]]) break;
|
||||
|
||||
for (k = cinfo->Ss; k <= cinfo->Se; k++) {
|
||||
st = entropy->ac_stats[tbl] + 3 * (k - 1);
|
||||
if (k > kex)
|
||||
if (arith_decode(cinfo, st)) break; /* EOB flag */
|
||||
for (;;) {
|
||||
thiscoef = *block + jpeg_natural_order[k];
|
||||
if (*thiscoef) { /* previously nonzero coef */
|
||||
if (arith_decode(cinfo, st + 2)) {
|
||||
if (*thiscoef < 0)
|
||||
*thiscoef += m1;
|
||||
else
|
||||
*thiscoef += p1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (arith_decode(cinfo, st + 1)) { /* newly nonzero coef */
|
||||
if (arith_decode(cinfo, entropy->fixed_bin))
|
||||
*thiscoef = m1;
|
||||
else
|
||||
*thiscoef = p1;
|
||||
break;
|
||||
}
|
||||
st += 3; k++;
|
||||
if (k > cinfo->Se) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* spectral overflow */
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Decode one MCU's worth of arithmetic-compressed coefficients.
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
jpeg_component_info * compptr;
|
||||
JBLOCKROW block;
|
||||
unsigned char *st;
|
||||
int blkn, ci, tbl, sign, k;
|
||||
int v, m;
|
||||
|
||||
/* Process restart marker if needed */
|
||||
if (cinfo->restart_interval) {
|
||||
if (entropy->restarts_to_go == 0)
|
||||
process_restart(cinfo);
|
||||
entropy->restarts_to_go--;
|
||||
}
|
||||
|
||||
if (entropy->ct == -1) return TRUE; /* if error do nothing */
|
||||
|
||||
/* Outer loop handles each block in the MCU */
|
||||
|
||||
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
|
||||
block = MCU_data[blkn];
|
||||
ci = cinfo->MCU_membership[blkn];
|
||||
compptr = cinfo->cur_comp_info[ci];
|
||||
|
||||
/* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
|
||||
|
||||
tbl = compptr->dc_tbl_no;
|
||||
|
||||
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
|
||||
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
|
||||
|
||||
/* Figure F.19: Decode_DC_DIFF */
|
||||
if (arith_decode(cinfo, st) == 0)
|
||||
entropy->dc_context[ci] = 0;
|
||||
else {
|
||||
/* Figure F.21: Decoding nonzero value v */
|
||||
/* Figure F.22: Decoding the sign of v */
|
||||
sign = arith_decode(cinfo, st + 1);
|
||||
st += 2; st += sign;
|
||||
/* Figure F.23: Decoding the magnitude category of v */
|
||||
if ((m = arith_decode(cinfo, st)) != 0) {
|
||||
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
|
||||
while (arith_decode(cinfo, st)) {
|
||||
if ((m <<= 1) == 0x8000) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* magnitude overflow */
|
||||
return TRUE;
|
||||
}
|
||||
st += 1;
|
||||
}
|
||||
}
|
||||
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
|
||||
if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
|
||||
entropy->dc_context[ci] = 0; /* zero diff category */
|
||||
else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
|
||||
entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
|
||||
else
|
||||
entropy->dc_context[ci] = 4 + (sign * 4); /* small diff category */
|
||||
v = m;
|
||||
/* Figure F.24: Decoding the magnitude bit pattern of v */
|
||||
st += 14;
|
||||
while (m >>= 1)
|
||||
if (arith_decode(cinfo, st)) v |= m;
|
||||
v += 1; if (sign) v = -v;
|
||||
entropy->last_dc_val[ci] += v;
|
||||
}
|
||||
|
||||
(*block)[0] = (JCOEF) entropy->last_dc_val[ci];
|
||||
|
||||
/* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
|
||||
|
||||
tbl = compptr->ac_tbl_no;
|
||||
|
||||
/* Figure F.20: Decode_AC_coefficients */
|
||||
for (k = 1; k <= DCTSIZE2 - 1; k++) {
|
||||
st = entropy->ac_stats[tbl] + 3 * (k - 1);
|
||||
if (arith_decode(cinfo, st)) break; /* EOB flag */
|
||||
while (arith_decode(cinfo, st + 1) == 0) {
|
||||
st += 3; k++;
|
||||
if (k > DCTSIZE2 - 1) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* spectral overflow */
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
/* Figure F.21: Decoding nonzero value v */
|
||||
/* Figure F.22: Decoding the sign of v */
|
||||
sign = arith_decode(cinfo, entropy->fixed_bin);
|
||||
st += 2;
|
||||
/* Figure F.23: Decoding the magnitude category of v */
|
||||
if ((m = arith_decode(cinfo, st)) != 0) {
|
||||
if (arith_decode(cinfo, st)) {
|
||||
m <<= 1;
|
||||
st = entropy->ac_stats[tbl] +
|
||||
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
|
||||
while (arith_decode(cinfo, st)) {
|
||||
if ((m <<= 1) == 0x8000) {
|
||||
WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
|
||||
entropy->ct = -1; /* magnitude overflow */
|
||||
return TRUE;
|
||||
}
|
||||
st += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
v = m;
|
||||
/* Figure F.24: Decoding the magnitude bit pattern of v */
|
||||
st += 14;
|
||||
while (m >>= 1)
|
||||
if (arith_decode(cinfo, st)) v |= m;
|
||||
v += 1; if (sign) v = -v;
|
||||
(*block)[jpeg_natural_order[k]] = (JCOEF) v;
|
||||
}
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Initialize for an arithmetic-compressed scan.
|
||||
*/
|
||||
|
||||
METHODDEF(void)
|
||||
start_pass (j_decompress_ptr cinfo)
|
||||
{
|
||||
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
|
||||
int ci, tbl;
|
||||
jpeg_component_info * compptr;
|
||||
|
||||
if (cinfo->progressive_mode) {
|
||||
/* Validate progressive scan parameters */
|
||||
if (cinfo->Ss == 0) {
|
||||
if (cinfo->Se != 0)
|
||||
goto bad;
|
||||
} else {
|
||||
/* need not check Ss/Se < 0 since they came from unsigned bytes */
|
||||
if (cinfo->Se < cinfo->Ss || cinfo->Se > DCTSIZE2 - 1)
|
||||
goto bad;
|
||||
/* AC scans may have only one component */
|
||||
if (cinfo->comps_in_scan != 1)
|
||||
goto bad;
|
||||
}
|
||||
if (cinfo->Ah != 0) {
|
||||
/* Successive approximation refinement scan: must have Al = Ah-1. */
|
||||
if (cinfo->Ah-1 != cinfo->Al)
|
||||
goto bad;
|
||||
}
|
||||
if (cinfo->Al > 13) { /* need not check for < 0 */
|
||||
bad:
|
||||
ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
|
||||
cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
|
||||
}
|
||||
/* Update progression status, and verify that scan order is legal.
|
||||
* Note that inter-scan inconsistencies are treated as warnings
|
||||
* not fatal errors ... not clear if this is right way to behave.
|
||||
*/
|
||||
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
|
||||
int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
|
||||
int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
|
||||
if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
|
||||
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
|
||||
for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
|
||||
int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
|
||||
if (cinfo->Ah != expected)
|
||||
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
|
||||
coef_bit_ptr[coefi] = cinfo->Al;
|
||||
}
|
||||
}
|
||||
/* Select MCU decoding routine */
|
||||
if (cinfo->Ah == 0) {
|
||||
if (cinfo->Ss == 0)
|
||||
entropy->pub.decode_mcu = decode_mcu_DC_first;
|
||||
else
|
||||
entropy->pub.decode_mcu = decode_mcu_AC_first;
|
||||
} else {
|
||||
if (cinfo->Ss == 0)
|
||||
entropy->pub.decode_mcu = decode_mcu_DC_refine;
|
||||
else
|
||||
entropy->pub.decode_mcu = decode_mcu_AC_refine;
|
||||
}
|
||||
} else {
|
||||
/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
|
||||
* This ought to be an error condition, but we make it a warning.
|
||||
*/
|
||||
if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
|
||||
(cinfo->Se < DCTSIZE2 && cinfo->Se != DCTSIZE2 - 1))
|
||||
WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
|
||||
/* Select MCU decoding routine */
|
||||
entropy->pub.decode_mcu = decode_mcu;
|
||||
}
|
||||
|
||||
/* Allocate & initialize requested statistics areas */
|
||||
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
|
||||
compptr = cinfo->cur_comp_info[ci];
|
||||
if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
|
||||
tbl = compptr->dc_tbl_no;
|
||||
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
|
||||
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
|
||||
if (entropy->dc_stats[tbl] == NULL)
|
||||
entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
|
||||
((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
|
||||
MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
|
||||
/* Initialize DC predictions to 0 */
|
||||
entropy->last_dc_val[ci] = 0;
|
||||
entropy->dc_context[ci] = 0;
|
||||
}
|
||||
if (! cinfo->progressive_mode || cinfo->Ss) {
|
||||
tbl = compptr->ac_tbl_no;
|
||||
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
|
||||
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
|
||||
if (entropy->ac_stats[tbl] == NULL)
|
||||
entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
|
||||
((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
|
||||
MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
|
||||
}
|
||||
}
|
||||
|
||||
/* Initialize arithmetic decoding variables */
|
||||
entropy->c = 0;
|
||||
entropy->a = 0;
|
||||
entropy->ct = -16; /* force reading 2 initial bytes to fill C */
|
||||
|
||||
/* Initialize restart counter */
|
||||
entropy->restarts_to_go = cinfo->restart_interval;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Module initialization routine for arithmetic entropy decoding.
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jinit_arith_decoder (j_decompress_ptr cinfo)
|
||||
{
|
||||
arith_entropy_ptr entropy;
|
||||
int i;
|
||||
|
||||
entropy = (arith_entropy_ptr)
|
||||
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
|
||||
sizeof(arith_entropy_decoder));
|
||||
cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
|
||||
entropy->pub.start_pass = start_pass;
|
||||
|
||||
/* Mark tables unallocated */
|
||||
for (i = 0; i < NUM_ARITH_TBLS; i++) {
|
||||
entropy->dc_stats[i] = NULL;
|
||||
entropy->ac_stats[i] = NULL;
|
||||
}
|
||||
|
||||
/* Initialize index for fixed probability estimation */
|
||||
entropy->fixed_bin[0] = 113;
|
||||
|
||||
if (cinfo->progressive_mode) {
|
||||
/* Create progression status table */
|
||||
int *coef_bit_ptr, ci;
|
||||
cinfo->coef_bits = (int (*)[DCTSIZE2])
|
||||
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
|
||||
cinfo->num_components*DCTSIZE2*sizeof(int));
|
||||
coef_bit_ptr = & cinfo->coef_bits[0][0];
|
||||
for (ci = 0; ci < cinfo->num_components; ci++)
|
||||
for (i = 0; i < DCTSIZE2; i++)
|
||||
*coef_bit_ptr++ = -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* jdatadst-tj.c
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1994-1996, Thomas G. Lane.
|
||||
* Modified 2009-2012 by Guido Vollbeding.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2011, 2014 D. R. Commander.
|
||||
* For conditions of distribution and use, see the accompanying README file.
|
||||
*
|
||||
* This file contains compression data destination routines for the case of
|
||||
* emitting JPEG data to memory or to a file (or any stdio stream).
|
||||
* While these routines are sufficient for most applications,
|
||||
* some will want to use a different destination manager.
|
||||
* IMPORTANT: we assume that fwrite() will correctly transcribe an array of
|
||||
* JOCTETs into 8-bit-wide elements on external storage. If char is wider
|
||||
* than 8 bits on your machine, you may need to do some tweaking.
|
||||
*/
|
||||
|
||||
/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
|
||||
#include "jinclude.h"
|
||||
#include "jpeglib.h"
|
||||
#include "jerror.h"
|
||||
|
||||
#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
|
||||
extern void * malloc (size_t size);
|
||||
extern void free (void *ptr);
|
||||
#endif
|
||||
|
||||
|
||||
#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
|
||||
|
||||
|
||||
/* Expanded data destination object for memory output */
|
||||
|
||||
typedef struct {
|
||||
struct jpeg_destination_mgr pub; /* public fields */
|
||||
|
||||
unsigned char ** outbuffer; /* target buffer */
|
||||
unsigned long * outsize;
|
||||
unsigned char * newbuffer; /* newly allocated buffer */
|
||||
JOCTET * buffer; /* start of buffer */
|
||||
size_t bufsize;
|
||||
boolean alloc;
|
||||
} my_mem_destination_mgr;
|
||||
|
||||
typedef my_mem_destination_mgr * my_mem_dest_ptr;
|
||||
|
||||
|
||||
/*
|
||||
* Initialize destination --- called by jpeg_start_compress
|
||||
* before any data is actually written.
|
||||
*/
|
||||
|
||||
METHODDEF(void)
|
||||
init_mem_destination (j_compress_ptr cinfo)
|
||||
{
|
||||
/* no work necessary here */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Empty the output buffer --- called whenever buffer fills up.
|
||||
*
|
||||
* In typical applications, this should write the entire output buffer
|
||||
* (ignoring the current state of next_output_byte & free_in_buffer),
|
||||
* reset the pointer & count to the start of the buffer, and return TRUE
|
||||
* indicating that the buffer has been dumped.
|
||||
*
|
||||
* In applications that need to be able to suspend compression due to output
|
||||
* overrun, a FALSE return indicates that the buffer cannot be emptied now.
|
||||
* In this situation, the compressor will return to its caller (possibly with
|
||||
* an indication that it has not accepted all the supplied scanlines). The
|
||||
* application should resume compression after it has made more room in the
|
||||
* output buffer. Note that there are substantial restrictions on the use of
|
||||
* suspension --- see the documentation.
|
||||
*
|
||||
* When suspending, the compressor will back up to a convenient restart point
|
||||
* (typically the start of the current MCU). next_output_byte & free_in_buffer
|
||||
* indicate where the restart point will be if the current call returns FALSE.
|
||||
* Data beyond this point will be regenerated after resumption, so do not
|
||||
* write it out when emptying the buffer externally.
|
||||
*/
|
||||
|
||||
METHODDEF(boolean)
|
||||
empty_mem_output_buffer (j_compress_ptr cinfo)
|
||||
{
|
||||
size_t nextsize;
|
||||
JOCTET * nextbuffer;
|
||||
my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest;
|
||||
|
||||
if (!dest->alloc) ERREXIT(cinfo, JERR_BUFFER_SIZE);
|
||||
|
||||
/* Try to allocate new buffer with double size */
|
||||
nextsize = dest->bufsize * 2;
|
||||
nextbuffer = (JOCTET *) malloc(nextsize);
|
||||
|
||||
if (nextbuffer == NULL)
|
||||
ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10);
|
||||
|
||||
MEMCOPY(nextbuffer, dest->buffer, dest->bufsize);
|
||||
|
||||
if (dest->newbuffer != NULL)
|
||||
free(dest->newbuffer);
|
||||
|
||||
dest->newbuffer = nextbuffer;
|
||||
|
||||
dest->pub.next_output_byte = nextbuffer + dest->bufsize;
|
||||
dest->pub.free_in_buffer = dest->bufsize;
|
||||
|
||||
dest->buffer = nextbuffer;
|
||||
dest->bufsize = nextsize;
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Terminate destination --- called by jpeg_finish_compress
|
||||
* after all data has been written. Usually needs to flush buffer.
|
||||
*
|
||||
* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
|
||||
* application must deal with any cleanup that should happen even
|
||||
* for error exit.
|
||||
*/
|
||||
|
||||
METHODDEF(void)
|
||||
term_mem_destination (j_compress_ptr cinfo)
|
||||
{
|
||||
my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest;
|
||||
|
||||
if(dest->alloc) *dest->outbuffer = dest->buffer;
|
||||
*dest->outsize = (unsigned long)(dest->bufsize - dest->pub.free_in_buffer);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Prepare for output to a memory buffer.
|
||||
* The caller may supply an own initial buffer with appropriate size.
|
||||
* Otherwise, or when the actual data output exceeds the given size,
|
||||
* the library adapts the buffer size as necessary.
|
||||
* The standard library functions malloc/free are used for allocating
|
||||
* larger memory, so the buffer is available to the application after
|
||||
* finishing compression, and then the application is responsible for
|
||||
* freeing the requested memory.
|
||||
*/
|
||||
|
||||
GLOBAL(void)
|
||||
jpeg_mem_dest_tj (j_compress_ptr cinfo,
|
||||
unsigned char ** outbuffer, unsigned long * outsize,
|
||||
boolean alloc)
|
||||
{
|
||||
boolean reused = FALSE;
|
||||
my_mem_dest_ptr dest;
|
||||
|
||||
if (outbuffer == NULL || outsize == NULL) /* sanity check */
|
||||
ERREXIT(cinfo, JERR_BUFFER_SIZE);
|
||||
|
||||
/* The destination object is made permanent so that multiple JPEG images
|
||||
* can be written to the same buffer without re-executing jpeg_mem_dest.
|
||||
*/
|
||||
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
|
||||
cinfo->dest = (struct jpeg_destination_mgr *)
|
||||
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
|
||||
sizeof(my_mem_destination_mgr));
|
||||
dest = (my_mem_dest_ptr) cinfo->dest;
|
||||
dest->newbuffer = NULL;
|
||||
dest->buffer = NULL;
|
||||
}
|
||||
|
||||
dest = (my_mem_dest_ptr) cinfo->dest;
|
||||
dest->pub.init_destination = init_mem_destination;
|
||||
dest->pub.empty_output_buffer = empty_mem_output_buffer;
|
||||
dest->pub.term_destination = term_mem_destination;
|
||||
if (dest->buffer == *outbuffer && *outbuffer != NULL && alloc)
|
||||
reused = TRUE;
|
||||
dest->outbuffer = outbuffer;
|
||||
dest->outsize = outsize;
|
||||
dest->alloc = alloc;
|
||||
|
||||
if (*outbuffer == NULL || *outsize == 0) {
|
||||
if (alloc) {
|
||||
/* Allocate initial buffer */
|
||||
dest->newbuffer = *outbuffer = (unsigned char *) malloc(OUTPUT_BUF_SIZE);
|
||||
if (dest->newbuffer == NULL)
|
||||
ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10);
|
||||
*outsize = OUTPUT_BUF_SIZE;
|
||||
}
|
||||
else ERREXIT(cinfo, JERR_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
dest->pub.next_output_byte = dest->buffer = *outbuffer;
|
||||
if (!reused)
|
||||
dest->bufsize = *outsize;
|
||||
dest->pub.free_in_buffer = dest->bufsize;
|
||||
}
|
||||
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user