Compare commits

...
78 Commits
Author SHA1 Message Date
seven332 2092171440 0.6.16 2015-04-30 23:20:22 +08:00
seven332 9ba87db1f0 Keep status bar black for SecretActivity 2015-04-30 23:01:05 +08:00
seven332 447ef9a510 Show suggestion name when add quick search 2015-04-30 22:36:01 +08:00
seven332 23936ff844 Scroll to current downloading gallery 2015-04-30 22:19:40 +08:00
seven332 29f2723919 Update string.xml 2015-04-29 23:26:37 +08:00
seven332 65feff57c0 Add pattern protection 2015-04-29 23:00:24 +08:00
seven332 017ee1c538 Merge pull request #65 from HybridGlucose/dev-AS
Fixes zh-rTW Translation
2015-04-28 08:09:21 +08:00
HybridGlucose 0059edd194 Update strings.xml 2015-04-28 00:26:35 +08:00
HybridGlucose 88a22b8545 修正簡繁用語差異 2015-04-28 00:01:48 +08:00
seven332 024511c249 Merge pull request #63 from fython/dev-AS
Add elevation for ActionBar
2015-04-26 15:01:47 +08:00
fython 7b763a4f2a Add elevation for ActionBar
Signed-off-by: fython <fython@163.com>
2015-04-26 13:32:31 +08:00
seven332 5bfc033d2d Merge remote-tracking branch 'origin/dev-AS' into dev-AS 2015-04-26 02:12:42 +08:00
seven332 101b1cf256 Maybe fix cache issue 2015-04-26 02:12:21 +08:00
seven332 38bd1e1f37 Support library version bump 2015-04-24 10:10:02 +08:00
seven332 58b34a4bb2 What if it crashes when generating crash report 2015-04-21 14:21:58 +08:00
seven332 00b7feab69 0.6.15.2 2015-04-21 14:01:27 +08:00
seven332 c69715d866 Fix torrent name 2015-04-21 13:58:30 +08:00
seven332 c8b347eed2 0.6.15.1 2015-04-21 11:31:24 +08:00
seven332 41b160227f Add current gallery information in crash report 2015-04-21 11:23:50 +08:00
seven332 697e0026c5 Get more information for crash report 2015-04-21 10:01:57 +08:00
seven332 0f9bec5645 Maybe fix NullPointerException for torrent 2015-04-21 10:00:48 +08:00
seven332 40784ea5a5 0.6.15 2015-04-20 12:17:30 +08:00
seven332 6fcbdc284d Remove cache pause 2015-04-19 22:18:26 +08:00
seven332 4084dc26df Clang3.5 for NDK build 2015-04-18 15:03:02 +08:00
seven332 c71a8fc468 Closes #59; fixes year in change_log. 2015-04-18 14:59:54 +08:00
seven332 35df91190a Fix download filename again 2015-04-16 19:02:00 +08:00
seven332 5c44251762 Fix download filename 2015-04-16 17:44:49 +08:00
seven332 4ddf33b4c1 Add keyboard control for gallery 2015-04-15 19:28:28 +08:00
seven332 2d97cd375c Adjust set cookie 2015-04-15 17:55:47 +08:00
seven332 01cf1a8be4 Add login via cookie 2015-04-15 16:18:17 +08:00
seven332 2fdc42acc4 Closes #3; show different icon for different favorite state. 2015-04-14 21:49:34 +08:00
seven332 85ea7550f4 Add gallery favorite status parse 2015-04-14 17:26:36 +08:00
seven332 68d17c3ca8 Update readme 2015-04-13 14:24:45 +08:00
seven332 409e8a093b Add readme 2015-04-13 14:14:31 +08:00
seven332 f7e63ca386 Build *.so from source code 2015-04-13 14:05:24 +08:00
seven332 77403b3032 ' to \' in string.xml 2015-04-13 10:24:14 +08:00
seven332 3b7673c14e Add sharing gallery 2015-04-13 10:19:58 +08:00
seven332 7ecac0db9e Add ic_torrent 2015-04-13 09:28:08 +08:00
seven332 aedadff3a7 Try to adapt to small screen 2015-04-12 22:21:59 +08:00
seven332 7b5cd5df9b Add save torrent, resolve #55 2015-04-12 22:12:05 +08:00
seven332 6918a8776e Remove useless stuff 2015-04-11 22:11:39 +08:00
seven332 9b821e875e Fix miss crash info 2015-04-11 16:02:17 +08:00
seven332 29fadae5ab Fix volume page error 2015-04-11 15:57:31 +08:00
seven332 3d329979d4 Merge remote-tracking branch 'origin/dev-AS' into dev-AS 2015-04-11 15:39:01 +08:00
seven332 2027b806df Page turning via volume key 2015-04-10 16:43:58 +08:00
seven332 b18cdd04ce Avoid IllegalStateException about CookieSyncManager 2015-04-10 13:36:37 +08:00
seven332 281eb12f0c Get url domain name for cookie 2015-04-09 23:48:57 +08:00
seven332 5022ce2b54 Improve crash collection 2015-04-07 14:45:36 +08:00
seven332 063fa658f2 History swipe to dismiss 2015-04-05 01:42:12 +08:00
seven332 59dccfa513 Merge remote-tracking branch 'origin/dev-AS' into dev-AS
Conflicts:
	app/src/main/java/com/hippo/ehviewer/widget/recyclerview/EasyRecyclerView.java
2015-04-05 01:06:40 +08:00
seven332 471919682e Improve EasyRecyclerView item click 2015-04-05 01:05:14 +08:00
seven332 0335e4338b Avoid unknown error in EasyRecyclerView 2015-04-02 19:11:38 +08:00
seven332 857366f8d6 Avoid SparseArray error for multi thread 2015-04-02 19:09:22 +08:00
seven332 3d32fd7bcc Fix omitted 509 url 2015-04-01 09:22:12 +08:00
seven332 f4aae2a027 Remove useless lock in AnyCache 2015-03-30 21:10:21 +08:00
seven332 a69be45099 Fix disk cache key 2015-03-30 18:01:52 +08:00
seven332 4985945dcb Update cache 2015-03-30 17:57:22 +08:00
seven332 e197ce3fe2 0.6.14 2015-03-27 21:42:11 +08:00
seven332 02e1185ebe Fix parsing gallery image url error 2015-03-27 21:13:58 +08:00
seven332 b992602b2d Merge remote-tracking branch 'origin/dev-AS' into dev-AS 2015-03-27 19:01:44 +08:00
seven332 0782469760 Add H@H proxy switch enable 2015-03-27 19:01:19 +08:00
seven332 938c1a2e88 Add warning before cleaning redundancy 2015-03-27 10:42:19 +08:00
seven332 0a2c442b75 Add H@H support 2015-03-26 23:36:23 +08:00
seven332 6b6c50f8cc Enable js in login webview 2015-03-26 19:59:14 +08:00
seven332 fd7ea32942 getAllocationByteCount might fail in kitkat-release 2015-03-26 19:31:22 +08:00
seven332 d02e211ee3 Fix theme.xml syntax 2015-03-26 13:43:06 +08:00
seven332 6d8d16d1f8 Adjust cache 2015-03-25 19:44:50 +08:00
seven332 af8c480588 0.6.13.2 2015-03-22 20:48:22 +08:00
seven332 5d0e035b35 Fix android.content.ActivityNotFoundException when sending email 2015-03-22 20:43:30 +08:00
seven332 f8e51c3ff7 Fix comment parse 2015-03-22 20:00:49 +08:00
seven332 9cb7d20dfc Fix parse 2015-03-22 03:59:05 +08:00
seven332 245bdc14ce Fix parse error 2015-03-22 02:54:32 +08:00
seven332 f29090ee12 Update proguard 2015-03-18 11:04:38 +08:00
seven332 f1d4540558 Move ic_launcher from drawable to mipmap 2015-03-15 02:26:01 +08:00
seven332 497438c0a1 Adjust cache 2015-03-13 22:26:09 +08:00
seven332 b407e38733 Move ic_launcher from mipmap to drawable 2015-03-12 16:30:18 +08:00
seven332 0fd27bf7fa Update Gradle Plugin to 1.1.3 2015-03-12 12:50:30 +08:00
seven332 45a9906731 Update target SDK version to 22 2015-03-12 10:38:14 +08:00
306 changed files with 115220 additions and 3216 deletions

No files matched your search

+4 -3
View File
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" defaultCharsetForPropertiesFiles="UTF-8">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
+2 -2
View File
@@ -5,6 +5,7 @@
<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$" />
@@ -14,5 +15,4 @@
</GradleProjectSettings>
</option>
</component>
</project>
</project>
+25 -2
View File
@@ -3,8 +3,31 @@
<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>
</project>
+3 -3
View File
@@ -1,9 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<module external.linked.project.id="EhViewer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="java-gradle" name="Java-Gradle">
<configuration>
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
<option name="BUILDABLE" value="false" />
</configuration>
</facet>
</component>
@@ -15,5 +16,4 @@
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
</module>
+70
View File
@@ -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)).
+2
View File
@@ -1 +1,3 @@
/build
/src/main/obj
/src/main/libs
+8 -9
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<module 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">
<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>
@@ -12,8 +12,9 @@
<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="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
<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" />
@@ -52,7 +53,6 @@
<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" />
@@ -83,13 +83,12 @@
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="svg-android-2.0.6" level="project" />
<orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />
<orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
<orderEntry type="library" exported="" name="recyclerview-v7-21.0.3" level="project" />
<orderEntry type="library" exported="" name="support-v4-22.1.0" level="project" />
<orderEntry type="library" exported="" name="support-annotations-22.1.0" level="project" />
<orderEntry type="library" exported="" name="recyclerview-v7-22.1.0" level="project" />
</component>
</module>
</module>
+41 -7
View File
@@ -1,15 +1,17 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 21
versionCode 36
versionName "0.6.12"
targetSdkVersion 22
versionCode 44
versionName "0.6.16"
}
buildTypes {
debug {
@@ -21,11 +23,43 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// 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/jni').absolutePath,
'NDK_DEBUG=0',
'NDK_TOOLCHAIN_VERSION=clang3.5',
'-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:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.3'
compile 'com.android.support:support-v4:22.1.0'
compile 'com.android.support:recyclerview-v7:22.1.0'
compile 'com.github.japgolly.android:svg-android:2.0.6'
}
+3
View File
@@ -47,3 +47,6 @@
void set*(***);
*** get*();
}
# I want to track the error in them
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
+23
View File
@@ -135,6 +135,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 +160,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.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.miscellaneous.FavoriteHelper;
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.getInstance(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() {
@@ -19,8 +19,9 @@ package com.hippo.ehviewer;
import android.content.Context;
import android.graphics.Bitmap;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.cache.AnyCache;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.util.BgThread;
import java.util.Stack;
@@ -52,7 +53,7 @@ public class ImageLoader {
private final Context mContext;
private final Stack<LoadTask> mLoadTasks;
private final ImageCache mImageCache;
private final AnyCache<Bitmap> mImageCache;
private final ImageDownloader mImageDownloader;
private ImageLoader(Context context) {
@@ -60,7 +61,7 @@ public class ImageLoader {
mImageDownloader = new ImageDownloader();
mContext = context;
mImageCache = ImageCache.getInstance(mContext);
mImageCache = ImageCache.getImageCache(mContext);
new BgThread(new LoadFromCacheTask()).start();
}
@@ -110,7 +111,7 @@ public class ImageLoader {
int[] state = new int[1];
String key = loadTask.key;
loadTask.bitmap = mImageCache.getCachedBitmap(key, state);
loadTask.bitmap = mImageCache.get(key);
loadTask.state = state[0];
if (loadTask.bitmap != null)
@@ -158,7 +159,7 @@ public class ImageLoader {
// TODO use proxy to get image
loadTask.bitmap = httpHelper.getImage(loadTask.url);
if (loadTask.bitmap != null) {
mImageCache.addBitmapToCache(loadTask.key, loadTask.bitmap);
mImageCache.put(loadTask.key, loadTask.bitmap);
loadTask.state = STATE_FROM_NETWORK;
} else {
loadTask.state = STATE_NONE;
@@ -19,7 +19,6 @@ package com.hippo.ehviewer;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
@@ -28,13 +27,16 @@ 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.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.util.Secret;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.LockPatternUtils;
import com.larvalabs.svgandroid.SVGBuilder;
public class StartActivity extends AbsActivity {
@@ -42,6 +44,8 @@ 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,11 +165,7 @@ public class StartActivity extends AbsActivity {
return true;
}
}).show();
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:ehviewersu@gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "I found a bug in EhViewer !");
i.putExtra(Intent.EXTRA_TEXT, lastCrash + "======== Description ========\n" + et.getText().toString());
startActivity(i);
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:
@@ -200,12 +201,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();
}
}
}
/**
@@ -243,7 +269,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) {
}
}
}
+501
View File
@@ -0,0 +1,501 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import com.hippo.ehviewer.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public abstract class AnyCache<V> {
private static final String TAG = AnyCache.class.getSimpleName();
private LruCache<String, V> mMemoryCache;
private @Nullable DiskCache<V> mDiskCache;
private final boolean mHasMemoryCache;
private final boolean mHasDiskCache;
/**
* Used to temporarily pause the disk cache while scrolling
*/
public boolean mPauseDiskAccess = false;
private final Object mPauseLock = new Object();
private final Object mDiskCacheLock = new Object();
public AnyCache(AnyCacheParams params) {
params.isValid();
mHasMemoryCache = params.hasMemoryCache;
mHasDiskCache = params.hasDiskCache;
if (mHasMemoryCache) {
initMemoryCache(params.memoryCacheMaxSize);
}
if (mHasDiskCache) {
initDiskCache(params.diskCacheDir, params.diskCacheMaxSize);
}
}
private void initMemoryCache(int maxSize) {
mMemoryCache = new MemoryCahce<>(maxSize, this);
}
private void initDiskCache(File cacheDir, int maxSize) {
// Set up disk cache
synchronized (mDiskCacheLock) {
try {
mDiskCache = new DiskCache<>(cacheDir, maxSize, this);
} catch (IOException e) {
Log.e(TAG, "Can't create disk cache", e);
}
}
}
protected abstract int sizeOf(String key, V value);
protected abstract V read(InputStream is);
protected abstract boolean write(OutputStream os, V value);
/**
* Check if have memory cache
*
* @return true if have memory cache
*/
public boolean hasMemoryCache() {
return mHasMemoryCache;
}
/**
* Check if have disk cache
*
* @return true if have disk cache
*/
public boolean hasDiskCache() {
return mHasDiskCache;
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache
*/
public V getFromMemory(String key) {
if (mHasMemoryCache) {
return mMemoryCache.get(key);
} else {
return null;
}
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache or get error
*/
public V getFromDisk(String key) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
return mDiskCache.get(diskKey);
} else {
return null;
}
}
} else {
return null;
}
}
/**
* Get value from memory cache and disk cache. If miss in memory cache and
* get in disk cache, it will put value from disk cache to memory cache.
*
* @param key the key to get value
* @return the value you get
*/
public V get(String key) {
V value = getFromMemory(key);
if (value != null) {
// Get it in memory cache
return value;
}
value = getFromDisk(key);
if (value != null) {
// Get it in disk cache
putToMemory(key, value);
return value;
}
return null;
}
/**
* Put value to memory cache
*
* @param key the key
* @param value the value
* @return false if no memory cache
*/
public boolean putToMemory(String key, V value) {
if (mHasMemoryCache) {
mMemoryCache.put(key, value);
return true;
} else {
return false;
}
}
/**
* Put value to disk cache
*
* @param key the key
* @param value the value
* @return false if no disk cache or get error
*/
public boolean putToDisk(String key, V value) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
mDiskCache.put(diskKey, value);
return true;
} else {
return false;
}
}
} else {
return false;
}
}
/**
* Put value to memory cache and disk cache
*
* @param key the key
* @param value the value
*/
public void put(String key, V value) {
putToMemory(key, value);
putToDisk(key, value);
}
/**
* Used to temporarily pause the disk cache while the user is scrolling to
* improve scrolling.
*
* @param pause True to temporarily pause the disk cache, false otherwise.
*/
public void setPauseDiskCache(final boolean pause) {
synchronized (mPauseLock) {
if (mPauseDiskAccess != pause) {
mPauseDiskAccess = pause;
if (!pause) {
mPauseLock.notify();
}
}
}
}
private void waitUntilUnpaused() {
synchronized (mPauseLock) {
if (Looper.myLooper() != Looper.getMainLooper()) {
while (mPauseDiskAccess) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// ignored, we'll start waiting again
}
}
}
}
}
/**
* Evicts all of the items from the memory cache
*/
public void clearMemory() {
if (mHasMemoryCache) {
mMemoryCache.evictAll();
}
}
/**
* Clear disk cache
*/
public void clearDisk() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null && !mDiskCache.isClosed()) {
try {
mDiskCache.delete();
} catch (IOException e) {
Log.e(TAG, "AnyCache clearCache", e);
}
File cacheDir = mDiskCache.getCacheDir();
int maxSize = mDiskCache.getMaxSize();
mDiskCache = null;
initDiskCache(cacheDir, maxSize);
}
}
}
}
public void flush() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
try {
mDiskCache.flush();
} catch (IOException e) {
Log.e(TAG, "AnyCache flush", e);
}
}
}
}
}
/**
* Evicts all of the items from the memory cache and lets the system know
* now would be a good time to garbage collect
*/
public void clear() {
clearMemory();
clearDisk();
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable
* for using as a disk filename.
*
* @param key The key used to store the file
*/
private static String hashKeyForDisk(final String key) {
String cacheKey;
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(key.getBytes());
cacheKey = bytesToHexString(digest.digest());
} catch (final NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* http://stackoverflow.com/questions/332079
*
* @param bytes The bytes to convert.
* @return A {@link String} converted from the bytes of a hashable key used
* to store a filename on the disk, to hex digits.
*/
private static String bytesToHexString(final byte[] bytes) {
final StringBuilder builder = new StringBuilder();
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
builder.append('0');
}
builder.append(hex);
}
return builder.toString();
}
/**
* A holder class that contains cache parameters.
*/
public static class AnyCacheParams {
public boolean hasMemoryCache = false;
public int memoryCacheMaxSize = 0;
public boolean hasDiskCache = false;
public File diskCacheDir = null;
public int diskCacheMaxSize = 0;
/**
* Check AnyCacheParams is valid
*
* @throws IllegalStateException
*/
public void isValid() throws IllegalStateException {
if (!hasMemoryCache && !hasDiskCache) {
throw new IllegalStateException("No memory cache and no disk cache. What can I do for you?");
}
if (hasMemoryCache && memoryCacheMaxSize <= 0) {
throw new IllegalStateException("Memory cache max size must be bigger than 0.");
}
if (hasDiskCache) {
if (diskCacheDir == null) {
throw new IllegalStateException("Disk cache dir can't be null.");
}
if (diskCacheMaxSize <= 0) {
throw new IllegalStateException("Disk cache max size must be bigger than 0.");
}
}
}
}
public class MemoryCahce<E> extends LruCache<String, E> {
public AnyCache<E> mParent;
public MemoryCahce(int maxSize, AnyCache<E> parent) {
super(maxSize);
mParent = parent;
}
@Override
protected int sizeOf(String key, E value) {
return mParent.sizeOf(key, value);
}
}
public static class DiskCache<E> {
private static final int IO_BUFFER_SIZE = 8 * 1024;
private DiskLruCache mDiskLruCache;
private AnyCache<E> mParent;
private File mCacheDir;
private int mMaxSize;
public DiskCache(File cacheDir, int size, AnyCache<E> parent) throws IOException {
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
mParent = parent;
mCacheDir = cacheDir;
mMaxSize = size;
}
public File getCacheDir() {
return mCacheDir;
}
public int getMaxSize() {
return mMaxSize;
}
public boolean isClosed() {
return mDiskLruCache.isClosed();
}
public void delete() throws IOException {
mDiskLruCache.delete();
}
public void flush() throws IOException {
mDiskLruCache.flush();
}
public E get(String key) {
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskLruCache.get(key);
if ( snapshot == null ) {
// Miss
return null;
}
final InputStream in = snapshot.getInputStream(0);
if (in != null) {
final BufferedInputStream buffIn =
new BufferedInputStream(in, IO_BUFFER_SIZE);
return mParent.read(buffIn);
} else {
// Can't get InputStream
return null;
}
} catch (IOException e) {
// e.printStackTrace();
return null;
} finally {
Util.closeQuietly(snapshot);
}
}
public boolean put(String key, E value) {
DiskLruCache.Editor editor = null;
OutputStream os = null;
boolean completeEdit = false;
try {
editor = mDiskLruCache.edit(key);
if (editor == null) {
// The editor is in progress
return false;
}
os = editor.newOutputStream(0);
if (os != null) {
final BufferedOutputStream buffOut =
new BufferedOutputStream(os, IO_BUFFER_SIZE);
boolean result = mParent.write(buffOut, value);
completeEdit = true;
editor.commit();
return result;
} else {
// Can't get OutputStream
completeEdit = true;
editor.abort();
return false;
}
} catch (IOException e) {
Util.closeQuietly(os);
try {
if (!completeEdit && editor != null) {
editor.abort();
}
} catch (IOException ignored) {
}
return false;
}
}
}
}
File diff suppressed because it is too large. Load diff
+68 -676
View File
@@ -1,560 +1,98 @@
/*
* Copyright (C) 2012 Andrew Neal 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.
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class ImageCache extends AnyCache<Bitmap>{
import com.hippo.ehviewer.util.Utils;
/**
* This class holds the memory and disk bitmap caches.
*/
public final class ImageCache {
private static final String TAG = ImageCache.class.getSimpleName();
private static final String TAG = "ImageCache";
/**
* Default memory cache size as a percent of device memory class
*/
private static final float MEM_CACHE_DIVIDER = 0.25f;
/**
* Default disk cache size 10MB
*/
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10;
/**
* Compression settings when writing images to disk cache
*/
private static final CompressFormat COMPRESS_FORMAT = CompressFormat.JPEG;
/**
* Disk cache index to read from
*/
private static final int DISK_CACHE_INDEX = 0;
private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
/**
* Image compression quality
*/
private static final int COMPRESS_QUALITY = 98;
/**
* LRU cache
*/
private MemoryCache mLruCache;
private static ImageCache sImageCache;
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
if (sImageCache == null) {
final ActivityManager activityManager = (ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
* 1024 * 1024);
AnyCacheParams params = new AnyCacheParams();
params.hasMemoryCache = true;
params.memoryCacheMaxSize = memoryCacheMax;
params.hasDiskCache = true;
params.diskCacheDir = getDiskCacheDir(context, TAG);
params.diskCacheMaxSize = 20 * 1024 * 1024;
sImageCache = new ImageCache(params);
}
return sImageCache;
}
public ImageCache(AnyCacheParams params) {
super(params);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
@Override
protected Bitmap read(InputStream is) {
return BitmapFactory.decodeStream(is);
}
@Override
protected boolean write(OutputStream os, Bitmap value) {
return value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
}
/**
* Disk LRU cache
*/
private DiskLruCache mDiskCache;
private static ImageCache sInstance;
/**
* Used to temporarily pause the disk cache while scrolling
*/
public boolean mPauseDiskAccess = false;
private final Object mPauseLock = new Object();
/**
* Constructor of <code>ImageCache</code>
* Get the external app cache directory
*
* @param context The {@link Context} to use
* @return The external cache directory
*/
public ImageCache(final Context context) {
init(context);
}
/**
* Used to create a singleton of {@link ImageCache}
*
* @param context The {@link Context} to use
* @return A new instance of this class.
*/
public final static ImageCache getInstance(final Context context) {
if (sInstance == null) {
sInstance = new ImageCache(context.getApplicationContext());
}
return sInstance;
}
/**
* Initialize the cache, providing all parameters.
*
* @param context The {@link Context} to use
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(final Context context) {
Utils.execute(false, new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... unused) {
// Initialize the disk cahe in a background thread
initDiskCache(context);
return null;
}
}, (Void[])null);
// Set up the memory cache
initLruCache(context);
}
/**
* Initializes the disk cache. Note that this includes disk access so this
* should not be executed on the main/UI thread. By default an ImageCache
* does not initialize the disk cache when it is created, instead you should
* call initDiskCache() to initialize it on a background thread.
*
* @param context The {@link Context} to use
*/
private synchronized void initDiskCache(final Context context) {
// Set up disk cache
if (mDiskCache == null || mDiskCache.isClosed()) {
File diskCacheDir = getDiskCacheDir(context, TAG);
if (diskCacheDir != null) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdirs();
}
if (getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE) {
try {
mDiskCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE);
} catch (final IOException e) {
diskCacheDir = null;
}
}
}
}
}
/**
* Sets up the Lru cache
*
* @param context The {@link Context} to use
*/
@SuppressLint("NewApi")
public void initLruCache(final Context context) {
final ActivityManager activityManager = (ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
final int lruCacheSize = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
* 1024 * 1024);
mLruCache = new MemoryCache(lruCacheSize);
// Release some memory as needed
context.registerComponentCallbacks(new ComponentCallbacks2() {
/**
* {@inheritDoc}
*/
@Override
public void onTrimMemory(final int level) {
if (level >= TRIM_MEMORY_MODERATE) {
evictAll();
} else if (level >= TRIM_MEMORY_BACKGROUND) {
mLruCache.trimToSize(mLruCache.size() / 2);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onLowMemory() {
// Nothing to do
}
/**
* {@inheritDoc}
*/
@Override
public void onConfigurationChanged(final Configuration newConfig) {
// Nothing to do
}
});
}
/**
* Find and return an existing ImageCache stored in a {@link RetainFragment}
* , if not found a new one is created using the supplied params and saved
* to a {@link RetainFragment}
*
* @param activity The calling {@link FragmentActivity}
* @return An existing retained ImageCache object or a new one if one did
* not exist
*/
public static final ImageCache findOrCreateCache(final Activity activity) {
// Search for, or create an instance of the non-UI RetainFragment
final RetainFragment retainFragment = findOrCreateRetainFragment(
activity.getFragmentManager());
// See if we already have an ImageCache stored in RetainFragment
ImageCache cache = (ImageCache)retainFragment.getObject();
// No existing ImageCache, create one and store it in RetainFragment
if (cache == null) {
cache = getInstance(activity);
retainFragment.setObject(cache);
}
return cache;
}
/**
* Locate an existing instance of this {@link Fragment} or if not found,
* create and add it using {@link FragmentManager}
*
* @param fm The {@link FragmentManager} to use
* @return The existing instance of the {@link Fragment} or the new instance
* if just created
*/
public static final RetainFragment findOrCreateRetainFragment(final FragmentManager fm) {
// Check to see if we have retained the worker fragment
RetainFragment retainFragment = (RetainFragment)fm.findFragmentByTag(TAG);
// If not retained, we need to create and add it
if (retainFragment == null) {
retainFragment = new RetainFragment();
fm.beginTransaction().add(retainFragment, TAG).commit();
}
return retainFragment;
}
/**
* Adds a new image to the memory and disk caches
*
* @param data The key used to store the image
* @param bitmap The {@link Bitmap} to cache
*/
public void addBitmapToCache(final String data, final Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
// Add to memory cache
addBitmapToMemCache(data, bitmap);
// Add to disk cache
if (mDiskCache != null) {
final String key = hashKeyForDisk(data);
OutputStream out = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskCache.get(key);
if (snapshot == null) {
final DiskLruCache.Editor editor = mDiskCache.edit(key);
if (editor != null) {
out = editor.newOutputStream(DISK_CACHE_INDEX);
bitmap.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, out);
editor.commit();
out.close();
flush();
}
} else {
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
} catch (final IOException e) {
Log.e(TAG, "addBitmapToCache - " + e);
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (final IOException e) {
Log.e(TAG, "addBitmapToCache - " + e);
} catch (final IllegalStateException e) {
Log.e(TAG, "addBitmapToCache - " + e);
}
}
}
}
/**
* Called to add a new image to the memory cache
*
* @param data The key identifier
* @param bitmap The {@link Bitmap} to cache
*/
public void addBitmapToMemCache(final String data, final Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
// Add to memory cache
if (getBitmapFromMemCache(data) == null) {
mLruCache.put(data, bitmap);
}
}
/**
* Fetches a cached image from the memory cache
*
* @param data Unique identifier for which item to get
* @return The {@link Bitmap} if found in cache, null otherwise
*/
public final Bitmap getBitmapFromMemCache(final String data) {
if (data == null) {
return null;
}
if (mLruCache != null) {
final Bitmap lruBitmap = mLruCache.get(data);
if (lruBitmap != null) {
return lruBitmap;
}
}
return null;
}
/**
* Fetches a cached image from the disk cache
*
* @param data Unique identifier for which item to get
* @return The {@link Bitmap} if found in cache, null otherwise
*/
public final Bitmap getBitmapFromDiskCache(final String data) {
if (data == null) {
return null;
}
// Check in the memory cache here to avoid going to the disk cache less
// often
if (getBitmapFromMemCache(data) != null) {
return getBitmapFromMemCache(data);
}
waitUntilUnpaused();
final String key = hashKeyForDisk(data);
if (mDiskCache != null) {
InputStream inputStream = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskCache.get(key);
if (snapshot != null) {
inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
if (inputStream != null) {
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap != null) {
return bitmap;
}
}
}
} catch (final IOException e) {
Log.e(TAG, "getBitmapFromDiskCache - " + e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (final IOException e) {
}
}
}
return null;
}
public static final int STATE_NONE = 0;
public static final int STATE_FROM_MEMORY = 1;
public static final int STATE_FROM_DISK = 2;
/**
* Tries to return a cached image from memory cache before fetching from the
* disk cache
*
* @param data Unique identifier for which item to get
* @return The {@link Bitmap} if found in cache, null otherwise
*/
public final Bitmap getCachedBitmap(final String data, int[] state) {
if (data == null) {
return null;
}
Bitmap cachedImage = getBitmapFromMemCache(data);
if (cachedImage == null) {
cachedImage = getBitmapFromDiskCache(data);
if (cachedImage != null) {
addBitmapToMemCache(data, cachedImage);
if (state != null)
state[0] = STATE_FROM_DISK;
} else {
if (state != null)
state[0] = STATE_NONE;
}
} else {
if (state != null)
state[0] = STATE_FROM_MEMORY;
}
return cachedImage;
}
/**
* flush() is called to synchronize up other methods that are accessing the
* cache first
*/
public void flush() {
Utils.execute(false, new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... unused) {
if (mDiskCache != null) {
try {
if (!mDiskCache.isClosed()) {
mDiskCache.flush();
}
} catch (final IOException e) {
Log.e(TAG, "flush - " + e);
}
}
return null;
}
}, (Void[])null);
}
/**
* Clears the disk and memory caches
*/
public void clearCaches() {
Utils.execute(false, new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... unused) {
// Clear the disk cache
try {
if (mDiskCache != null) {
mDiskCache.delete();
mDiskCache = null;
}
} catch (final IOException e) {
Log.e(TAG, "clearCaches - " + e);
}
// Clear the memory cache
evictAll();
return null;
}
}, (Void[])null);
}
/**
* Closes the disk cache associated with this ImageCache object. Note that
* this includes disk access so this should not be executed on the main/UI
* thread.
*/
public void close() {
Utils.execute(false, new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... unused) {
if (mDiskCache != null) {
try {
if (!mDiskCache.isClosed()) {
mDiskCache.close();
mDiskCache = null;
}
} catch (final IOException e) {
Log.e(TAG, "close - " + e);
}
}
return null;
}
}, (Void[])null);
}
/**
* 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 (mLruCache != null) {
mLruCache.evictAll();
}
System.gc();
}
/**
* @param key The key used to identify which cache entries to delete.
*/
public void removeFromCache(final String key) {
if (key == null) {
return;
}
// Remove the Lru entry
if (mLruCache != null) {
mLruCache.remove(key);
}
try {
// Remove the disk entry
if (mDiskCache != null) {
mDiskCache.remove(hashKeyForDisk(key));
}
} catch (final IOException e) {
Log.e(TAG, "remove - " + e);
}
flush();
}
/**
* Used to temporarily pause the disk cache while the user is scrolling to
* improve scrolling.
*
* @param pause True to temporarily pause the disk cache, false otherwise.
*/
public void setPauseDiskCache(final boolean pause) {
synchronized (mPauseLock) {
if (mPauseDiskAccess != pause) {
mPauseDiskAccess = pause;
if (!pause) {
mPauseLock.notify();
}
}
}
}
private void waitUntilUnpaused() {
synchronized (mPauseLock) {
if (Looper.myLooper() != Looper.getMainLooper()) {
while (mPauseDiskAccess) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// ignored, we'll start waiting again
}
}
}
}
}
/**
* @return True if the user is scrolling, false otherwise.
*/
public boolean isDiskCachePaused() {
return mPauseDiskAccess;
private static File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
/**
@@ -565,157 +103,11 @@ public final class ImageCache {
* directory
* @return The cache directory
*/
public static final File getDiskCacheDir(final Context context, final String uniqueName) {
private static File getDiskCacheDir(final Context context, final String uniqueName) {
// getExternalCacheDir(context) returns null if external storage is not ready
final String cachePath = getExternalCacheDir(context) != null
? getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
? getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
return new File(cachePath, uniqueName);
}
/**
* Check if external storage is built-in or removable
*
* @return True if external storage is removable (like an SD card), false
* otherwise
*/
public static final boolean isExternalStorageRemovable() {
return Environment.isExternalStorageRemovable();
}
/**
* Get the external app cache directory
*
* @param context The {@link Context} to use
* @return The external cache directory
*/
public static final File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
/**
* Check how much usable space is available at a given path.
*
* @param path The path to check
* @return The space available in bytes
*/
public static final long getUsableSpace(final File path) {
return path.getUsableSpace();
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable
* for using as a disk filename.
*
* @param key The key used to store the file
*/
public static final String hashKeyForDisk(final String key) {
String cacheKey;
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(key.getBytes());
cacheKey = bytesToHexString(digest.digest());
} catch (final NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* http://stackoverflow.com/questions/332079
*
* @param bytes The bytes to convert.
* @return A {@link String} converted from the bytes of a hashable key used
* to store a filename on the disk, to hex digits.
*/
private static final String bytesToHexString(final byte[] bytes) {
final StringBuilder builder = new StringBuilder();
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
builder.append('0');
}
builder.append(hex);
}
return builder.toString();
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over
* configuration changes. In this sample it will be used to retain an
* {@link ImageCache} object.
*/
public static final class RetainFragment extends Fragment {
/**
* The object to be stored
*/
private Object mObject;
/**
* Empty constructor as per the {@link Fragment} documentation
*/
public RetainFragment() {
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this {@link Fragment}
*
* @param object The object to store
*/
public void setObject(final Object object) {
mObject = object;
}
/**
* Get the stored object
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
/**
* Used to cache images via {@link LruCache}.
*/
public static final class MemoryCache extends LruCache<String, Bitmap> {
/**
* Constructor of <code>MemoryCache</code>
*
* @param maxSize The allowed size of the {@link LruCache}
*/
public MemoryCache(final int maxSize) {
super(maxSize);
}
/**
* Get the size in bytes of a bitmap.
*/
public static final int getBitmapSize(final Bitmap bitmap) {
return bitmap.getByteCount();
}
/**
* {@inheritDoc}
*/
@Override
protected int sizeOf(final String paramString, final Bitmap paramBitmap) {
return getBitmapSize(paramBitmap);
}
}
}
-333
View File
@@ -1,333 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project Licensed under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.hippo.ehviewer.cache;
// NOTE: upstream of this class is android.util.LruCache, changes below
// expose trimToSize() to be called externally.
import android.annotation.SuppressLint;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Static library version of {@link android.util.LruCache}. Used to write apps
* that run on API levels prior to 12. When running on API level 12 or above,
* this implementation is still used; it does not try to switch to the
* framework's implementation. See the framework SDK documentation for a class
* overview.
*/
public class LruCache<K, V> {
private final LinkedHashMap<K, V> map;
private final int maxSize;
/** Size of this cache in units. Not necessarily the number of elements. */
private int size;
private int putCount;
private int createCount;
private int evictionCount;
private int hitCount;
private int missCount;
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other
* caches, this is the maximum sum of the sizes of the entries in
* this cache.
*/
public LruCache(final int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
/**
* Returns the value for {@code key} if it exists in the cache or can be
* created by {@code #create}. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
public final V get(final K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
mapValue = map.get(key);
if (mapValue != null) {
this.hitCount++;
return mapValue;
}
this.missCount++;
}
/*
* Attempt to create a value. This may take a long time, and the map may
* be different when create() returns. If a conflicting value was added
* to the map while create() was working, we leave that value in the map
* and release the created value.
*/
final V createdValue = create(key);
if (createdValue == null) {
return null;
}
synchronized (this) {
this.createCount++;
mapValue = map.put(key, createdValue);
if (mapValue != null) {
/* There was a conflict so undo that last put */
this.map.put(key, mapValue);
} else {
this.size += safeSizeOf(key, createdValue);
}
}
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
trimToSize(maxSize);
return createdValue;
}
}
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/
public final V put(final K key, final V value) {
if (key == null || value == null) {
throw new NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
this.putCount++;
this.size += safeSizeOf(key, value);
previous = this.map.put(key, value);
if (previous != null) {
this.size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
/**
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
public void trimToSize(final int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
if (this.size < 0 || this.map.isEmpty() && size != 0) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
if (this.size <= maxSize || this.map.isEmpty()) {
break;
}
final Map.Entry<K, V> toEvict = this.map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
this.map.remove(key);
this.size -= safeSizeOf(key, value);
this.evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
/**
* Removes the entry for {@code key} if it exists.
*
* @return the previous value mapped by {@code key}.
*/
public final V remove(final K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V previous;
synchronized (this) {
previous = this.map.remove(key);
if (previous != null) {
this.size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, null);
}
return previous;
}
/**
* Called for entries that have been evicted or removed. This method is
* invoked when a value is evicted to make space, removed by a call to
* {@link #remove}, or replaced by a call to {@link #put}. The default
* implementation does nothing.
* <p>
* The method is called without synchronization: other threads may access
* the cache while this method is executing.
*
* @param evicted true if the entry is being removed to make space, false if
* the removal was caused by a {@link #put} or {@link #remove}.
* @param newValue the new value for {@code key}, if it exists. If non-null,
* this removal was caused by a {@link #put}. Otherwise it was
* caused by an eviction or a {@link #remove}.
*/
protected void entryRemoved(final boolean evicted, final K key, final V oldValue,
final V newValue) {
}
/**
* Called after a cache miss to compute a value for the corresponding key.
* Returns the computed value or null if no value can be computed. The
* default implementation returns null.
* <p>
* The method is called without synchronization: other threads may access
* the cache while this method is executing.
* <p>
* If a value for {@code key} exists in the cache when this method returns,
* the created value will be released with {@link #entryRemoved} and
* discarded. This can occur when multiple threads request the same key at
* the same time (causing multiple values to be created), or when one thread
* calls {@link #put} while another is creating a value for the same key.
*/
protected V create(final K key) {
return null;
}
private int safeSizeOf(final K key, final V value) {
final int result = sizeOf(key, value);
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
/**
* Returns the size of the entry for {@code key} and {@code value} in
* user-defined units. The default implementation returns 1 so that size is
* the number of entries and max size is the maximum number of entries.
* <p>
* An entry's size must not change while it is in the cache.
*/
protected int sizeOf(final K key, final V value) {
return 1;
}
/**
* Clear the cache, calling {@link #entryRemoved} on each removed entry.
*/
public final void evictAll() {
trimToSize(-1); // -1 will evict 0-sized elements
}
/**
* For caches that do not override {@link #sizeOf}, this returns the number
* of entries in the cache. For all other caches, this returns the sum of
* the sizes of the entries in this cache.
*/
public synchronized final int size() {
return this.size;
}
/**
* For caches that do not override {@link #sizeOf}, this returns the maximum
* number of entries in the cache. For all other caches, this returns the
* maximum sum of the sizes of the entries in this cache.
*/
public synchronized final int maxSize() {
return this.maxSize;
}
/**
* Returns the number of times {@link #get} returned a value.
*/
public synchronized final int hitCount() {
return this.hitCount;
}
/**
* Returns the number of times {@link #get} returned null or required a new
* value to be created.
*/
public synchronized final int missCount() {
return this.missCount;
}
/**
* Returns the number of times {@link #create(Object)} returned a value.
*/
public synchronized final int createCount() {
return this.createCount;
}
/**
* Returns the number of times {@link #put} was called.
*/
public synchronized final int putCount() {
return this.putCount;
}
/**
* Returns the number of values that have been evicted.
*/
public synchronized final int evictionCount() {
return this.evictionCount;
}
/**
* Returns a copy of the current contents of the cache, ordered from least
* recently accessed to most recently accessed.
*/
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(this.map);
}
@SuppressLint("DefaultLocale")
@Override
public synchronized final String toString() {
final int accesses = this.hitCount + this.missCount;
final int hitPercent = accesses != 0 ? 100 * this.hitCount / accesses : 0;
return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", this.maxSize,
this.hitCount, this.missCount, hitPercent);
}
}
@@ -0,0 +1,196 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* Buffers input from an {@link InputStream} for reading lines.
*
* <p>This class is used for buffered reading of lines. For purposes of this class, a line ends
* with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated
* line at end of input is invalid and will be ignored, the caller may use {@code
* hasUnterminatedLine()} to detect it after catching the {@code EOFException}.
*
* <p>This class is intended for reading input that strictly consists of lines, such as line-based
* cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
* with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
* end-of-input reporting and a more restrictive definition of a line.
*
* <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
* and 10, respectively, and the representation of no other character contains these values.
* We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
* The default charset is US_ASCII.
*/
class StrictLineReader implements Closeable {
private static final byte CR = (byte) '\r';
private static final byte LF = (byte) '\n';
private final InputStream in;
private final Charset charset;
/*
* Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
* and the data in the range [pos, end) is buffered for reading. At end of input, if there is
* an unterminated line, we set end == -1, otherwise end == pos. If the underlying
* {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
*/
private byte[] buf;
private int pos;
private int end;
/**
* Constructs a new {@code LineReader} with the specified charset and the default capacity.
*
* @param in the {@code InputStream} to read data from.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if the specified charset is not supported.
*/
public StrictLineReader(InputStream in, Charset charset) {
this(in, 8192, charset);
}
/**
* Constructs a new {@code LineReader} with the specified capacity and charset.
*
* @param in the {@code InputStream} to read data from.
* @param capacity the capacity of the buffer.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if {@code capacity} is negative or zero
* or the specified charset is not supported.
*/
public StrictLineReader(InputStream in, int capacity, Charset charset) {
if (in == null || charset == null) {
throw new NullPointerException();
}
if (capacity < 0) {
throw new IllegalArgumentException("capacity <= 0");
}
if (!(charset.equals(Util.US_ASCII))) {
throw new IllegalArgumentException("Unsupported encoding");
}
this.in = in;
this.charset = charset;
buf = new byte[capacity];
}
/**
* Closes the reader by closing the underlying {@code InputStream} and
* marking this reader as closed.
*
* @throws IOException for errors when closing the underlying {@code InputStream}.
*/
public void close() throws IOException {
synchronized (in) {
if (buf != null) {
buf = null;
in.close();
}
}
}
/**
* Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
* this end of line marker is not included in the result.
*
* @return the next line from the input.
* @throws IOException for underlying {@code InputStream} errors.
* @throws EOFException for the end of source stream.
*/
public String readLine() throws IOException {
synchronized (in) {
if (buf == null) {
throw new IOException("LineReader is closed");
}
// Read more data if we are at the end of the buffered data.
// Though it's an error to read after an exception, we will let {@code fillBuf()}
// throw again if that happens; thus we need to handle end == -1 as well as end == pos.
if (pos >= end) {
fillBuf();
}
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
String res = new String(buf, pos, lineEnd - pos, charset.name());
pos = i + 1;
return res;
}
}
// Let's anticipate up to 80 characters on top of those already read.
ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
@Override
public String toString() {
int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
try {
return new String(buf, 0, length, charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e); // Since we control the charset this will never happen.
}
}
};
while (true) {
out.write(buf, pos, end - pos);
// Mark unterminated line in case fillBuf throws EOFException or IOException.
end = -1;
fillBuf();
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
if (i != pos) {
out.write(buf, pos, i - pos);
}
pos = i + 1;
return out.toString();
}
}
}
}
}
public boolean hasUnterminatedLine() {
return end == -1;
}
/**
* Reads new input data into the buffer. Call only with pos == end or end == -1,
* depending on the desired outcome if the function throws.
*/
private void fillBuf() throws IOException {
int result = in.read(buf, 0, buf.length);
if (result == -1) {
throw new EOFException();
}
pos = 0;
end = result;
}
}
+77
View File
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
/** Junk drawer of utility methods. */
final class Util {
static final Charset US_ASCII = Charset.forName("US-ASCII");
static final Charset UTF_8 = Charset.forName("UTF-8");
private Util() {
}
static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
/**
* Deletes the contents of {@code dir}. Throws an IOException if any file
* could not be deleted, or if {@code dir} is not a readable directory.
*/
static void deleteContents(File dir) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IOException("not a readable directory: " + dir);
}
for (File file : files) {
if (file.isDirectory()) {
deleteContents(file);
}
if (!file.delete()) {
throw new IOException("failed to delete file: " + file);
}
}
}
static void closeQuietly(/*Auto*/Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
}
@@ -0,0 +1,73 @@
package com.hippo.ehviewer.content;
import android.util.SparseArray;
import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.util.IntIdGenerator;
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(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 Object obj);
}
}
@@ -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,13 +16,6 @@
package com.hippo.ehviewer.ehclient;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.hippo.ehviewer.data.Comment;
import com.hippo.ehviewer.data.LargePreviewList;
import com.hippo.ehviewer.data.NormalPreviewList;
@@ -30,6 +23,13 @@ import com.hippo.ehviewer.data.PreviewList;
import com.hippo.ehviewer.util.EhUtils;
import com.hippo.ehviewer.util.Utils;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DetailParser {
private static final String OFFENSIVE_STRING =
@@ -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,27 +130,34 @@ public class DetailParser {
// Get detail
if ((mode & DETAIL) != 0) {
p = Pattern
.compile("<div id=\"gd1\"><img src=\"([^\"]+)\"[^<>]+/></div>" // thumb
.compile("<div id=\"gd1\"><img src=\"([^\"]+)\"[^<>]+></div>" // thumb
+ "</div>"
+ "<div id=\"gd2\">"
+ "<h1 id=\"gn\">([^<>]+)</h1>" // title
+ "<h1 id=\"gj\">([^<>]*)</h1>" // title_jpn might be empty string
+ "</div>"
+ ".+"
+ "<div id=\"gdc\"><a[^<>]+><[^<>]*alt=\"([\\w|\\-]+)\"[^<>]*/></a></div>" // category
+ ".+?"
+ "<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>"
+ ".+?"
+ "<div id=\"gdc\"><a[^<>]+><[^<>]*alt=\"([\\w|\\-]+)\"[^<>]*></a></div>" // category
+ "<div id=\"gdn\"><a[^<>]+>([^<>]+)</a>" // uploader
+ ".+"
+ ".+?"
+ "<tr><td[^<>]*>Posted:</td><td[^<>]*>([\\w|\\-|\\s|:]+)</td></tr>" // posted
+ "<tr><td[^<>]*>Images:</td><td[^<>]*>([\\d]+) @ ([\\w|\\.|\\s]+)</td></tr>" // pages and size
+ "<tr><td[^<>]*>Resized:</td><td[^<>]*>([^<>]+)</td></tr>" // resized
//+ "<tr><td[^<>]*>Images:</td><td[^<>]*>([\\d]+) @ ([\\w|\\.|\\s]+)</td></tr>" // pages and size
//+ "<tr><td[^<>]*>Resized:</td><td[^<>]*>([^<>]+)</td></tr>" // resized
+ "<tr><td[^<>]*>Parent:</td><td[^<>]*>(?:<a[^<>]*>)?([^<>]+)(?:</a>)?</td></tr>" // parent
+ "<tr><td[^<>]*>Visible:</td><td[^<>]*>([^<>]+)</td></tr>" // visible
+ "<tr><td[^<>]*>Language:</td><td[^<>]*>([^<>]+)</td></tr>" // language
+ ".+"
+ "<td id=\"grt3\">\\(<span id=\"rating_count\">([\\d|,]+)</span>\\)</td>" // people
+ "<tr><td[^<>]*>Language:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>[^<>]*</span>)?</td></tr>" // language
+ "<tr><td[^<>]*>File Size:</td><td[^<>]*>([^<>]+)(?:<span[^<>]*>([^<>]+)</span>)?</td></tr>" // File size and resize
+ "<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d|,]+) pages</td></tr>" // pages
+ "<tr><td[^<>]*>Favorited:</td><[^<>]*>([^<>]+)</td></tr>" // Favorite times ([\d|,]+) times or Never
+ ".+?"
+ "<td id=\"grt3\"><span id=\"rating_count\">([\\d|,]+)</span></td>" // people
+ "</tr>"
+ "<tr><td[^<>]*>([^<>]+)</td>" // rating
+ ".+"
+ ".+?"
+ "<a id=\"favoritelink\"[^<>]*>(.+?)</a>"
+ ".+?"
+ "<div id=\"gdt\"><div[^<>]*>(?:<div[^<>]*>)?<a[^<>]*href=\"([^<>\"]+)\"[^<>]*>"); // get firstPage
m = p.matcher(body);
if (m.find()) {
@@ -154,30 +166,35 @@ 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);
pages = Integer.parseInt(m.group(7));
size = m.group(8);
resized = m.group(9);
parent = m.group(10);
visible = m.group(11);
language = m.group(12);
people = Integer.parseInt(m.group(13).replace(",", ""));
torrentUrl = Utils.unescapeXml(m.group(4));
torrentNumber = Utils.parseIntSafely(m.group(5), 0);
category = EhUtils.getCategory(m.group(6));
uploader = m.group(7);
posted = m.group(8);
parent = m.group(9);
visible = m.group(10);
language = Utils.unescapeXml(m.group(11)).trim();
size = Utils.unescapeXml(m.group(12)).trim();
resized = m.group(13);
pages = Integer.parseInt(m.group(14).replace(",", ""));
// favoriteTimes = m.group(15)
people = Integer.parseInt(m.group(16).replace(",", ""));
Pattern pattern = Pattern.compile("([\\d|\\.]+)");
Matcher matcher = pattern.matcher(m.group(14));
Matcher matcher = pattern.matcher(m.group(17));
if (matcher.find())
rating = Float.parseFloat(matcher.group(1));
else
rating = Float.NaN;
firstPage = m.group(15);
isFavorite = "Favorite Gallery".equals(m.group(18));
firstPage = m.group(19);
}
}
// Get tag
if ((mode & TAG) != 0) {
tags = new LinkedHashMap<String, LinkedList<String>>();
tags = new LinkedHashMap<>();
p = Pattern
.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
m = p.matcher(body);
@@ -232,7 +249,7 @@ public class DetailParser {
// Get comment
if ((mode & COMMENT) != 0) {
p = Pattern
.compile("<div class=\"c3\">Posted on ([^<>]+) by <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
.compile("<div class=\"c3\">Posted on ([^<>]+) by: &nbsp; <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
m = p.matcher(body);
comments = new LinkedList<Comment>();
while (m.find()) {
@@ -16,13 +16,13 @@
package com.hippo.ehviewer.ehclient;
import com.hippo.ehviewer.util.Log;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.hippo.ehviewer.util.Log;
public class EdDetailParser {
int previewPageNum;
@@ -80,7 +80,7 @@ public class EdDetailParser {
return false;
}
p = Pattern.compile("<td class=\"gdt1\">Images:</td><td class=\"gdt2\">([\\d,]+) ");
p = Pattern.compile("<tr><td[^<>]*>Length:</td><td[^<>]*>([\\d|,]+) pages</td></tr>");
m = p.matcher(body);
if (m.find())
imageNum = Integer.valueOf(m.group(1).replace(",", ""));
@@ -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;
@@ -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
@@ -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);
@@ -21,9 +21,11 @@ import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.MathUtils;
import com.hippo.ehviewer.util.Utils;
import com.larvalabs.svgandroid.SVGBuilder;
@@ -34,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;
/**
@@ -51,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;
@@ -76,6 +79,12 @@ public class EhInfo {
private String mPreviewMode;
private int mExculdeTagGroup;
private String mExculdeLanguage;
private boolean mHAHProxy;
private String mHAHIp;
private String mHAHPort;
private String mHAHPasskey;
private static EhInfo sInstance;
private BitmapDrawable getAvatarFromFile() {
@@ -110,28 +119,65 @@ public class EhInfo {
mPreviewMode = Config.getPreviewMode();
mExculdeTagGroup = Config.getExculdeTagGroup();
mExculdeLanguage = Config.getExculdeLanguage();
mHAHProxy = Config.getHAHProxy();
mHAHIp = Config.getHAHIp();
mHAHPort = Config.getHAHPort();
mHAHPasskey = Config.getHAHPasskey();
updateUconfig();
};
}
private String getUconfigString(String previewMode) {
return new StringBuilder().append("cats_").append(mDefaultCat)
.append("-ts_").append(previewMode == null ? mPreviewMode : previewMode)
.append("-xns_").append(mExculdeTagGroup)
.append("-xl_").append(mExculdeLanguage)
.append("-tl_m-uh_y-tr_2-prn_n-dm_l-ar_0-rc_0-rx_0-ry_0-sa_y-oi_n-qb_n-tf_n-hp_-hk_-ms_n-mt_n")
.toString();
String proxy;
if (!mHAHProxy || TextUtils.isEmpty(mHAHIp) || TextUtils.isEmpty(mHAHPort)) {
proxy = "";
} else {
proxy = mHAHIp + "%3A" + mHAHPort;
}
return "cats_" + mDefaultCat
+ "-ts_" + (previewMode == null ? mPreviewMode : previewMode)
+ "-xns_" + mExculdeTagGroup
+ "-xl_" + mExculdeLanguage
+ "-hp_" + proxy
+ "-hk_" + mHAHPasskey
+ "-prn_" + (TextUtils.isEmpty(proxy) ? "n" : "y")
+ "-tl_m-uh_y-tr_2-dm_l-ar_0-rc_0-rx_0-ry_0-sa_y-oi_n-qb_n-tf_n-ms_n-mt_n";
}
private void updateUconfig() {
mUconfig = getUconfigString(null);
}
public final static EhInfo getInstance(final Context context) {
public static EhInfo getInstance(final Context context) {
if (sInstance == null)
sInstance = new EhInfo(context.getApplicationContext());
return sInstance;
}
public static boolean isEhSite(URL url) {
String host = url.getHost();
int length = host.length();
int dotCount = 0;
int i = length;
while(i-- != 0) {
char ch = host.charAt(i);
if (ch == '.') {
dotCount++;
}
if (dotCount == 2) {
// Get it
break;
}
}
String site = host.substring(MathUtils.clamp(i+1, 0, length));
for (String h : EhInfo.COOKIABLE_SITE_ARRAY) {
if (h.equals(site))
return true;
}
return false;
}
private String getCookie(String cookieStr, String key) {
String value = null;
int index1 = -1;
@@ -186,6 +232,7 @@ public class EhInfo {
// Fake
sb.append("; igneous=");
sb.append("; lv=");
conn.setRequestProperty("Cookie", sb.toString());
}
@@ -266,4 +313,16 @@ public class EhInfo {
mExculdeLanguage = exculdeLanguage;
updateUconfig();
}
public void setHAHProxy(boolean hahProxy) {
mHAHProxy = hahProxy;
updateUconfig();
}
public void setHAHProxy(String ip, String port, String passkey) {
mHAHIp = ip;
mHAHPort = port;
mHAHPasskey = passkey;
updateUconfig();
}
}
@@ -16,20 +16,6 @@
package com.hippo.ehviewer.ehclient;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Process;
@@ -44,6 +30,20 @@ import com.hippo.ehviewer.util.EhUtils;
import com.hippo.ehviewer.util.Log;
import com.hippo.ehviewer.util.Utils;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
// TODO what a mess
public final class ExDownloader implements Runnable {
@@ -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;
@@ -106,7 +104,7 @@ public final class ExDownloader implements Runnable {
private volatile long mLastUpdateSpeedTime = 0;
private volatile long mAccumulateSize;
private volatile HashSet<Integer> mDownloadIndexSet;
private volatile Object mDownloadLock = new Object();
private final Object mDownloadLock = new Object();
private int mCurReadIndex = 0;
@@ -476,7 +474,7 @@ public final class ExDownloader implements Runnable {
if (edp.isLastPage) {
mPreviewPageNum = pageIndex + 1;
mImageNum = pageIndex * mPreviewPerPage + pageTokenArray.size();
} else if (!edp.isLastPage && mPreviewPageNum == -1) {
} else if (mPreviewPageNum == -1) {
mCurMaxPreviewPage = Math.max(mCurMaxPreviewPage, pageIndex + 1);
}
} else {
@@ -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) {
}
}
}
@@ -16,11 +16,11 @@
package com.hippo.ehviewer.ehclient;
import com.hippo.ehviewer.util.Utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.hippo.ehviewer.util.Utils;
public class ImagePageParser {
public String imageUrl;
@@ -61,9 +61,10 @@ public class ImagePageParser {
}
} else {
p = Pattern.compile("<div id=\"i3\">.+?<img id=\"img\" src=\"(.+?)\""
+ ".+?"
+ "<div id=\"i5\"><div class=\"sb\"><a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)");
p = Pattern.compile(
"<(?:/iframe|div id=\"i3\")[^>]*><a[^>]*><img[^>]*src=\"(.+?)\"" +
".+?" +
"<div class=\"sb\"><a href=\"(?:http|https)://.+?/g/(\\d+)/(\\w+)");
m = p.matcher(body);
if (m.find()) {
imageUrl = Utils.unescapeXml(m.group(1));
@@ -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\"> &nbsp; <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() {
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.miscellaneous;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.widget.MaterialToast;
public final class ActivityHelper {
public static boolean sendEmail(@NonNull Activity from, @NonNull String address,
@Nullable String subject, @Nullable String text) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:" + address));
if (subject != null) {
i.putExtra(Intent.EXTRA_SUBJECT, subject);
}
if (text != null) {
i.putExtra(Intent.EXTRA_TEXT, text);
}
try {
from.startActivity(i);
return true;
} catch (ActivityNotFoundException e) {
MaterialToast.showToast(R.string.em_cant_find_activity);
return false;
}
}
public static boolean share(@NonNull Activity from, String text) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.setType("text/plain");
try {
from.startActivity(sendIntent);
return true;
} catch (ActivityNotFoundException e) {
MaterialToast.showToast(R.string.em_cant_find_activity);
return false;
}
}
}
@@ -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;
}
}
@@ -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)
@@ -32,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();
@@ -46,7 +53,5 @@ public abstract class AbsActivity extends Activity {
if (Config.getAllowAnalyics())
EasyTracker.getInstance(this).activityStop(this);
ImageCache.getInstance(this).flush();
}
}
@@ -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, Long.MAX_VALUE);
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;
@@ -39,6 +39,7 @@ import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.DirSelectDialog;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.content.Messenger;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.data.GalleryInfo;
import com.hippo.ehviewer.ehclient.ExDownloader;
@@ -53,11 +54,13 @@ import com.hippo.ehviewer.widget.ColorView;
import com.hippo.ehviewer.widget.MaterialToast;
import com.hippo.ehviewer.widget.SlidingLayout;
import java.io.File;
public class GalleryActivity extends AbsActivity
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(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;
@@ -33,8 +34,11 @@ 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;
@@ -44,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;
@@ -56,7 +63,6 @@ import com.hippo.ehviewer.AppContext;
import com.hippo.ehviewer.ImageLoader;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.data.ApiGalleryDetail;
import com.hippo.ehviewer.data.Comment;
import com.hippo.ehviewer.data.Data;
@@ -75,11 +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.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;
@@ -97,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;
@@ -109,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;
@@ -135,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;
@@ -171,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;
@@ -185,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++)
@@ -208,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())) {
@@ -227,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);
@@ -269,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
@@ -284,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));
@@ -291,6 +327,7 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
mClient = EhClient.getInstance();
mWindowsAnimate = new WindowsAnimate();
mWindowsAnimate.init(this);
mData = Data.getInstance();
mResources = getResources();
@@ -329,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);
@@ -353,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);
@@ -395,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);
@@ -600,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
@@ -632,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();
@@ -665,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")
@@ -684,6 +757,8 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
// TODO
}
updateFavoriteButton();
// Rate
mDividerMR.setVisibility(View.VISIBLE);
mDetailRate.setVisibility(View.VISIBLE);
@@ -861,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);
@@ -869,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);
@@ -1008,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) {
@@ -1159,14 +1349,28 @@ public class GalleryDetailActivity extends AbsTranslucentActivity
@Override
public void onScrollStateChanged(ResponedScrollView view, int state) {
if (view == mDetailScroll) {
ImageCache imageCache = ImageCache.getInstance(this);
/*
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
@@ -1260,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;
@@ -1269,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
@@ -1284,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);
@@ -1293,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)
@@ -1304,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;
@@ -550,16 +550,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;
}
@@ -1416,8 +1416,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 +1478,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;
@@ -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);
@@ -16,15 +16,6 @@
package com.hippo.ehviewer.ui;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
@@ -41,6 +32,7 @@ import android.os.SystemClock;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.provider.SearchRecentSuggestions;
import android.text.util.Linkify;
import android.view.MenuItem;
@@ -58,6 +50,7 @@ import com.hippo.ehviewer.UpdateHelper;
import com.hippo.ehviewer.app.DirSelectDialog;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.app.MaterialProgressDialog;
import com.hippo.ehviewer.content.Messenger;
import com.hippo.ehviewer.data.ApiGalleryInfo;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.data.DownloadInfo;
@@ -67,11 +60,12 @@ import com.hippo.ehviewer.ehclient.EhClient;
import com.hippo.ehviewer.ehclient.EhInfo;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.preference.ListPreference;
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
import com.hippo.ehviewer.util.BgThread;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.DialogUtils;
import com.hippo.ehviewer.util.EhUtils;
import com.hippo.ehviewer.util.Favorite;
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
import com.hippo.ehviewer.util.Secret;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.Utils;
@@ -80,6 +74,15 @@ import com.hippo.ehviewer.widget.CategoryTable;
import com.hippo.ehviewer.widget.MaterialToast;
import com.hippo.ehviewer.widget.SuggestionHelper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SettingsActivity extends AbsPreferenceActivity {
@SuppressWarnings("unused")
private static String TAG = SettingsActivity.class.getSimpleName();
@@ -197,6 +200,8 @@ public class SettingsActivity extends AbsPreferenceActivity {
private static final String KEY_CLEAR_SUGGESTIONS = "clear_suggestions";
private static final String KEY_PREVIEW_MODE = "preview_mode";
private static final String KEY_DEFAULT_FAVORITE = "default_favorite";
private static final String KEY_HAH_PROXY = "hah_proxy";
private static final String KEY_HAH_PROXY_CONFIG = "hah_proxy_config";
private Preference mListDefaultCategory;
private Preference mExculdeTagGroup;
@@ -204,6 +209,8 @@ public class SettingsActivity extends AbsPreferenceActivity {
private Preference mClearSuggestions;
private ListPreference mPreviewMode;
private ListPreference mDefaultFavorite;
private SwitchPreference mHAHProxy;
private Preference mHAHProxyConfig;
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -221,11 +228,15 @@ public class SettingsActivity extends AbsPreferenceActivity {
mPreviewMode = (ListPreference) findPreference(KEY_PREVIEW_MODE);
mPreviewMode.setOnPreferenceChangeListener(this);
mDefaultFavorite = (ListPreference) findPreference(KEY_DEFAULT_FAVORITE);
mHAHProxy = (SwitchPreference) findPreference(KEY_HAH_PROXY);
mHAHProxy.setOnPreferenceChangeListener(this);
mHAHProxyConfig = findPreference(KEY_HAH_PROXY_CONFIG);
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);
}
@@ -236,6 +247,9 @@ public class SettingsActivity extends AbsPreferenceActivity {
if (KEY_PREVIEW_MODE.equals(key)) {
String newPreviewMode = (String) newValue;
EhInfo.getInstance(getActivity()).setPreviewMode(newPreviewMode);
} else if (KEY_HAH_PROXY.equals(key)) {
boolean hahProxy = (Boolean) newValue;
EhInfo.getInstance(getActivity()).setHAHProxy(hahProxy);
}
return true;
}
@@ -273,9 +287,11 @@ public class SettingsActivity extends AbsPreferenceActivity {
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
int newValue = getExculdeTagGroup(tl);
Config.setExculdeTagGroup(newValue);
EhInfo.getInstance(getActivity()).setExculdeTagGroup(newValue);
if (which == MaterialAlertDialog.POSITIVE) {
int newValue = getExculdeTagGroup(tl);
Config.setExculdeTagGroup(newValue);
EhInfo.getInstance(getActivity()).setExculdeTagGroup(newValue);
}
return true;
}
}).show();
@@ -289,9 +305,11 @@ public class SettingsActivity extends AbsPreferenceActivity {
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
String newValue = getExculdeLanguage(tl);
Config.setExculdeLanguage(newValue);
EhInfo.getInstance(getActivity()).setExculdeLanguage(newValue);
if (which == MaterialAlertDialog.POSITIVE) {
String newValue = getExculdeLanguage(tl);
Config.setExculdeLanguage(newValue);
EhInfo.getInstance(getActivity()).setExculdeLanguage(newValue);
}
return true;
}
}).show();
@@ -300,6 +318,34 @@ public class SettingsActivity extends AbsPreferenceActivity {
SearchRecentSuggestions suggestions = SuggestionHelper.getInstance(getActivity(),
SimpleSuggestionProvider.AUTHORITY, SimpleSuggestionProvider.MODE);
suggestions.clearHistory();
} else if (KEY_HAH_PROXY_CONFIG.equals(key)) {
LinearLayout ll = (LinearLayout) ViewUtils.inflateDialogView(R.layout.hah_proxy_config, false);
final EditText hahIp = (EditText) ll.findViewById(R.id.hah_ip);
final EditText hahPort = (EditText) ll.findViewById(R.id.hah_port);
final EditText hahPasskey = (EditText) ll.findViewById(R.id.hah_passkey);
hahIp.setText(Config.getHAHIp());
hahPort.setText(Config.getHAHPort());
hahPasskey.setText(Config.getHAHPasskey());
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.hah_proxy_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 ip = hahIp.getText().toString();
String port = hahPort.getText().toString();
String passkey = hahPasskey.getText().toString();
Config.setHAHIp(ip);
Config.setHAHPort(port);
Config.setHAHPasskey(passkey);
EhInfo.getInstance(getActivity()).setHAHProxy(ip, port, passkey);
}
return true;
}
}).show();
}
return true;
}
@@ -355,11 +401,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;
@@ -370,6 +418,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);
@@ -383,6 +433,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)))
@@ -441,56 +502,71 @@ public class SettingsActivity extends AbsPreferenceActivity {
public boolean onPreferenceClick(Preference preference) {
final String key = preference.getKey();
if (KEY_CLEAN_REDUNDANCY.equals(key)) {
// Create a thread to do clean task
new BgThread() {
@Override
public void run() {
Data data = Data.getInstance();
List<DownloadInfo> diList = data.getAllDownloads();
File downloadDir = new File(Config.getDownloadPath());
String[] files = downloadDir.list();
Handler handler = AppHandler.getInstance();
List<File> targetDirList = new ArrayList<File>();
if (files == null) {
// Check files null
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
return;
}
for (String filename : files) {
// If in download list, just continue
if (isInDownloadList(diList, filename))
continue;
File dir = new File(downloadDir, filename);
// If there is no tag file, just continue
if (!new File(dir, EhUtils.EH_DOWNLOAD_FILENAME).exists())
continue;
// Add to list
targetDirList.add(dir);
}
if (targetDirList.isEmpty()) {
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
return;
} else {
handler.post(new CleanResponder(CleanResponder.STATE_START, 0, 0));
}
// Do delete
for (int i = 0; i < targetDirList.size(); i++) {
File dir = targetDirList.get(i);
Utils.deleteFile(dir);
handler.post(new CleanResponder(CleanResponder.STATE_DOING, targetDirList.size(), i + 1));
}
// Close windows
handler.post(new CleanResponder(CleanResponder.STATE_DONE, targetDirList.size(), targetDirList
.size()));
}
}.start();
new MaterialAlertDialog.Builder(getActivity()).setTitle(R.string.warning)
.setMessage(R.string.clean_redundancy_mesg)
.setPositiveButton(R.string.are_you_sure_sure)
.setNegativeButton(R.string.are_you_sure_no)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
if (which == MaterialAlertDialog.POSITIVE) {
cleanRedundancy();
} return true;
}
}).show();
}
return true;
}
private void cleanRedundancy() {
// Create a thread to do clean task
new BgThread() {
@Override
public void run() {
Data data = Data.getInstance();
List<DownloadInfo> diList = data.getAllDownloads();
File downloadDir = new File(Config.getDownloadPath());
String[] files = downloadDir.list();
Handler handler = AppHandler.getInstance();
List<File> targetDirList = new ArrayList<File>();
if (files == null) {
// Check files null
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
return;
}
for (String filename : files) {
// If in download list, just continue
if (isInDownloadList(diList, filename))
continue;
File dir = new File(downloadDir, filename);
// If there is no tag file, just continue
if (!new File(dir, EhUtils.EH_DOWNLOAD_FILENAME).exists())
continue;
// Add to list
targetDirList.add(dir);
}
if (targetDirList.isEmpty()) {
handler.post(new CleanResponder(CleanResponder.STATE_NONE, 0, 0));
return;
} else {
handler.post(new CleanResponder(CleanResponder.STATE_START, 0, 0));
}
// Do delete
for (int i = 0; i < targetDirList.size(); i++) {
File dir = targetDirList.get(i);
Utils.deleteFile(dir);
handler.post(new CleanResponder(CleanResponder.STATE_DOING, targetDirList.size(), i + 1));
}
// Close windows
handler.post(new CleanResponder(CleanResponder.STATE_DONE, targetDirList.size(), targetDirList
.size()));
}
}.start();
}
}
public static class DownloadFragment extends PreferenceFragment implements
@@ -611,8 +687,12 @@ public class SettingsActivity extends AbsPreferenceActivity {
Preference.OnPreferenceClickListener {
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 Preference mFixDirname;
private Preference mLoginViaCookie;
private Preference mPatternProtection;
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -621,6 +701,10 @@ 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);
}
@Override
@@ -719,6 +803,30 @@ 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;
}
@@ -805,10 +913,7 @@ public class SettingsActivity extends AbsPreferenceActivity {
}
} else if (KEY_AUTHOR.equals(key)) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:ehviewersu@gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "About EhViewer");
startActivity(i);
ActivityHelper.sendEmail(getActivity(), "ehviewersu@gmail.com", "About EhViewer", null);
} else if (KEY_TWITTER.equals(key)) {
new MaterialAlertDialog.Builder(getActivity())
@@ -879,7 +984,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;
@@ -1,5 +1,22 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebView;
@@ -14,12 +31,13 @@ public class WebViewLoginActivity extends AbsActivity {
public static final String KEY_ERROR = "error";
@SuppressLint("SetJavaScriptEnabled")
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);
setContentView(wv);
@@ -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);
}
}
@@ -22,6 +22,7 @@ import android.content.pm.ActivityInfo;
import android.os.Environment;
import android.preference.PreferenceManager;
import com.hippo.ehviewer.content.Messenger;
import com.hippo.ehviewer.data.ListUrls;
import com.hippo.ehviewer.ehclient.EhClient;
@@ -41,9 +42,16 @@ public final class Config {
private static boolean mInit = false;
private static Context mContext;
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
*
@@ -54,8 +62,7 @@ public final class Config {
return;
mInit = true;
mContext = context;
mConfigPre = PreferenceManager.getDefaultSharedPreferences(mContext);
mConfigPre = PreferenceManager.getDefaultSharedPreferences(context);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
sExternalDir = new File(Environment.getExternalStorageDirectory(), EXTERANL_DIR_NAME);
@@ -89,6 +96,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);
}
@@ -253,6 +268,18 @@ public final class Config {
private static final String KEY_MAX_HISTORY_COUNT = "max_history_count";
private static final int DEFAULT_MAX_HISTORY_COUNT = 100;
private static final String KEY_HAH_PROXY = "hah_proxy";
private static final boolean DEFAULT_HAH_PROXY = false;
private static final String KEY_HAH_IP = "hah_ip";
private static final String DEFAULT_HAH_IP = "";
private static final String KEY_HAH_PORT = "hah_port";
private static final String DEFAULT_HAH_PORT = "";
private static final String KEY_HAH_PASSKEY = "hah_passkey";
private static final String DEFAULT_HAH_PASSKEY = "";
public static int getDefaultCat() {
return getInt(KEY_DEFAULT_CAT, DEFAULT_DEFAULT_CAT);
}
@@ -293,6 +320,34 @@ public final class Config {
return getIntFromStr(KEY_MAX_HISTORY_COUNT, DEFAULT_MAX_HISTORY_COUNT);
}
public static boolean getHAHProxy() {
return getBoolean(KEY_HAH_PROXY, DEFAULT_HAH_PROXY);
}
public static void setHAHIp(String hahIp) {
setString(KEY_HAH_IP, hahIp);
}
public static String getHAHIp() {
return getString(KEY_HAH_IP, DEFAULT_HAH_IP);
}
public static void setHAHPort(String hahPort) {
setString(KEY_HAH_PORT, hahPort);
}
public static String getHAHPort() {
return getString(KEY_HAH_PORT, DEFAULT_HAH_PORT);
}
public static void setHAHPasskey(String hahPasskey) {
setString(KEY_HAH_PASSKEY, hahPasskey);
}
public static String getHAHPasskey() {
return getString(KEY_HAH_PASSKEY, DEFAULT_HAH_PASSKEY);
}
/****** Read ******/
@@ -305,6 +360,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;
@@ -357,6 +415,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);
}
@@ -504,6 +571,9 @@ 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 = "";
public static int getHttpRetry() {
return getIntFromStr(KEY_HTTP_RETRY, DEFAULT_HTTP_RETRY);
}
@@ -520,6 +590,14 @@ 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);
}
/****** About ******/
@@ -24,8 +24,6 @@ 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;
@@ -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);
@@ -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);
@@ -16,17 +16,15 @@
package com.hippo.ehviewer.util;
import android.text.format.DateFormat;
public final class DateUtils {
@SuppressWarnings("deprecation")
public static final char QUOTE = '\'';
public static final char SECONDS = 's';
public static boolean hasSeconds(CharSequence inFormat) {
return hasDesignator(inFormat, DateFormat.SECONDS);
return hasDesignator(inFormat, SECONDS);
}
@SuppressWarnings("deprecation")
public static boolean hasDesignator(CharSequence inFormat, char designator) {
if (inFormat == null) return false;
@@ -39,7 +37,7 @@ public final class DateUtils {
count = 1;
c = inFormat.charAt(i);
if (c == DateFormat.QUOTE) {
if (c == QUOTE) {
count = skipQuotedText(inFormat, i, length);
} else if (c == designator) {
return true;
@@ -49,9 +47,8 @@ public final class DateUtils {
return false;
}
@SuppressWarnings("deprecation")
private static int skipQuotedText(CharSequence s, int i, int len) {
if (i + 1 < len && s.charAt(i + 1) == DateFormat.QUOTE) {
if (i + 1 < len && s.charAt(i + 1) == QUOTE) {
return 2;
}
@@ -62,10 +59,10 @@ public final class DateUtils {
while (i < len) {
char c = s.charAt(i);
if (c == DateFormat.QUOTE) {
if (c == QUOTE) {
count++;
// QUOTEQUOTE -> QUOTE
if (i + 1 < len && s.charAt(i + 1) == DateFormat.QUOTE) {
if (i + 1 < len && s.charAt(i + 1) == QUOTE) {
i++;
} else {
break;
@@ -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,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;
}
@@ -371,6 +371,7 @@ public class Ui {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(d);
actionBar.setIcon(null);
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();
@@ -281,21 +284,23 @@ public final class Utils {
}
private static final String[] ESCAPE_CHARATER_LIST = {
"&amp;",
"&lt;",
"&gt;",
"&quot;",
"&#039;",
"&times;"
"&amp;",
"&lt;",
"&gt;",
"&quot;",
"&#039;",
"&times;",
"&nbsp;"
};
private static final String[] UNESCAPE_CHARATER_LIST = {
"&",
"<",
">",
"\"",
"'",
"×"
"&",
"<",
">",
"\"",
"'",
"×",
" "
};
/**
@@ -740,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();
}
}
@@ -16,12 +16,10 @@
package com.hippo.ehviewer.widget;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
@@ -45,10 +43,13 @@ 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.MarginItemDecoration;
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView.FooterAdapter;
import com.hippo.ehviewer.widget.refreshlayout.RefreshLayout;
public class GalleryListView extends FrameLayout implements RefreshLayout.OnFooterRefreshListener,
RefreshLayout.OnRefreshListener {
import java.util.ArrayList;
import java.util.List;
public class GalleryListView extends FrameLayout implements RefreshLayout.OnHeaderRefreshListener,
RefreshLayout.OnFooterRefreshListener {
private static final String TAG = GalleryListView.class.getSimpleName();
@@ -112,6 +113,8 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
private int mListDetailThumbWidth;
private int mListDetailThumbHeight;
private int mOldPaddingBottom;
public GalleryListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
@@ -130,13 +133,13 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
mContext = context;
mGiList = new ArrayList<GalleryInfo>();
mGiList = new ArrayList<>();
mListener = new OnGetGalleryListListener();
LayoutInflater.from(mContext).inflate(R.layout.gallery_list_view, this);
mRefreshLayout = (RefreshLayout) findViewById(R.id.refresh_layout);
mEasyRecyclerView = mRefreshLayout.getEasyRecyclerView();
mEasyRecyclerView = (EasyRecyclerView) mRefreshLayout.findViewById(R.id.easy_recycler_view);
mRefreshTextView = (RefreshTextView) findViewById(R.id.refresh_text);
mAdapter = new GalleryAdapter(mContext, mGiList);
@@ -158,18 +161,24 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
});
mRefreshLayout.setColorSchemeResources(
mRefreshLayout.setHeaderEnable(true);
mRefreshLayout.setFooterEnable(true);
mRefreshLayout.setHeaderColorSchemeResources(
R.color.refresh_color_1,
R.color.refresh_color_2,
R.color.refresh_color_3,
R.color.refresh_color_4);
R.color.refresh_color_4
);
mRefreshLayout.setFooterColorSchemeResources(
R.color.refresh_color_1,
R.color.refresh_color_2,
R.color.refresh_color_3,
R.color.refresh_color_4
);
mRefreshLayout.setOnHeaderRefreshListener(this);
mRefreshLayout.setOnFooterRefreshListener(this);
mRefreshLayout.setFooterString(
mContext.getString(R.string.footer_loading),
mContext.getString(R.string.footer_loaded),
mContext.getString(R.string.footer_fail));
mRefreshLayout.addFooterView();
mOldPaddingBottom = mEasyRecyclerView.getPaddingBottom();
// Caculate gallery detail height
mInflater = LayoutInflater.from(mContext);
@@ -219,6 +228,14 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
}
public EasyRecyclerView getEasyRecyclerView() {
return mEasyRecyclerView;
}
public GalleryAdapter getGalleryAdapter() {
return mAdapter;
}
public void setGalleryListViewHelper(GalleryListViewHelper h) {
mHelper = h;
}
@@ -226,7 +243,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
public void setPaddingTopAndBottom(int top, int bottom) {
setPadding(getPaddingLeft(), top, getPaddingRight(), getPaddingBottom());
mEasyRecyclerView.setPadding(mEasyRecyclerView.getPaddingLeft(), mEasyRecyclerView.getPaddingTop(),
mEasyRecyclerView.getPaddingRight(), mEasyRecyclerView.getPaddingBottom() + bottom);
mEasyRecyclerView.getPaddingRight(), mOldPaddingBottom + bottom);
}
private void setItemMargin(int margin) {
@@ -237,15 +254,15 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
public void setEnabledHeader(boolean enabled) {
mRefreshLayout.setEnabledHeader(enabled);
mRefreshLayout.setHeaderEnable(enabled);
}
public void setEnabledFooter(boolean enabled) {
mRefreshLayout.setEnabledFooter(enabled);
mRefreshLayout.setFooterEnable(enabled);
}
public void setHeaderRefreshing(boolean refreshing) {
mRefreshLayout.setRefreshing(refreshing);
mRefreshLayout.setHeaderRefreshing(refreshing);
}
public void setOnItemClickListener(EasyRecyclerView.OnItemClickListener l) {
@@ -264,6 +281,10 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
mEasyRecyclerView.setMultiChoiceModeListener(listener);
}
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mEasyRecyclerView.addOnItemTouchListener(listener);
}
public void notifyDataSetChanged() {
mAdapter.notifyDataSetChanged();
}
@@ -294,7 +315,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
@Override
public void onRefresh() {
public void onHeaderRefresh() {
// It is invokened by user pull, so no need to
if (mFirstPage > 0) {
getPrePage(true);
@@ -327,7 +348,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
private void setGallerysLayout() {
if (mRefreshLayout.getVisibility() == View.VISIBLE) {
if (!isFootRefresh)
mRefreshLayout.setRefreshing(true);
mRefreshLayout.setHeaderRefreshing(true);
mRefreshTextView.setVisibility(View.GONE);
} else {
mRefreshLayout.setVisibility(View.GONE);
@@ -437,6 +458,10 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
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);
@@ -541,7 +566,8 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
}
mRefreshLayout.setAnyRefreshComplete(true);
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
@Override
@@ -572,7 +598,8 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
mRefreshTextView.setVisibility(View.GONE);
MaterialToast.showToast(eMsg);
}
mRefreshLayout.setAnyRefreshComplete(false);
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
}
@@ -600,19 +627,21 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
/*
switch (newState) {
case RecyclerView.SCROLL_STATE_DRAGGING:
ImageCache.getInstance(mContext).setPauseDiskCache(true);
ImageCache.getImageCache(mContext).setPauseDiskCache(true);
break;
case RecyclerView.SCROLL_STATE_IDLE:
ImageCache.getInstance(mContext).setPauseDiskCache(false);
ImageCache.getImageCache(mContext).setPauseDiskCache(false);
break;
}
*/
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
mRefreshLayout.onScrolled(recyclerView, dx, dy);
// mRefreshLayout.onScrolled(recyclerView, dx, dy);
int itemCount = mLayoutManager.getChildCount();
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPositions(mFirstPositionTemp)[0];
@@ -692,7 +721,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
}
public class GalleryAdapter extends EasyRecyclerView.FooterAdapter<GalleryViewHolder> {
public class GalleryAdapter extends RecyclerView.Adapter<GalleryViewHolder> {
private final Context mContext;
private final List<GalleryInfo> mGiList;
@@ -706,13 +735,7 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
@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)
@@ -729,16 +752,24 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
@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;
if (!String.valueOf(gi.gid).equals(thumb.getKey())) {
final String key = String.valueOf(gi.gid);
if (!key.equals(thumb.getKey())) {
// Set new thumb
thumb.setImageDrawable(null);
thumb.setLoadInfo(gi.thumb, String.valueOf(gi.gid));
mImageLoader.add(gi.thumb, String.valueOf(gi.gid),
new LoadImageView.SimpleImageGetListener(thumb).setFixScaleType(true));
thumb.setLoadInfo(gi.thumb, key);
Bitmap b = ImageCache.getImageCache(getContext()).getFromMemory(key);
if (b != null) {
thumb.setContextImage(b, true, false);
} else {
mImageLoader.add(gi.thumb, String.valueOf(gi.gid),
new LoadImageView.SimpleImageGetListener(thumb).setFixScaleType(true));
}
}
// Set simple language
TextView simpleLanguage = holder.simpleLanguage;
@@ -783,12 +814,12 @@ public class GalleryListView extends FrameLayout implements RefreshLayout.OnFoot
}
@Override
public int getItemViewTypeActual(int position) {
public int getItemViewType(int position) {
return mListMode;
}
@Override
public int getItemCountActual() {
public int getItemCount() {
return mGiList.size();
}
}
@@ -96,9 +96,19 @@ public class LoadImageView extends FixedAspectImageView {
* Load target bmp, set progressive animation
* @param bmp
*/
public void setContextImage(Bitmap bmp, int state) {
public void setContextImage(Bitmap bmp, boolean fixScaleType, boolean transit) {
if (fixScaleType) {
float aspectRatio = (float)bmp.getHeight() / bmp.getWidth();
if (aspectRatio < 1.7 && aspectRatio > 1.3)
setScaleType(ImageView.ScaleType.CENTER_CROP);
else
setScaleType(ImageView.ScaleType.FIT_CENTER);
} else {
setScaleType(ImageView.ScaleType.FIT_CENTER);
}
setImageBitmap(bmp);
if (state != ImageLoader.STATE_FROM_MEMORY) {
if (transit) {
final Drawable drawable = getDrawable();
DrawableTransition.transit(drawable, false, 1000);
}
@@ -134,16 +144,8 @@ public class LoadImageView extends FixedAspectImageView {
public void onGetImage(String key, Bitmap bmp, int state) {
if (isVaild(key) && mLiv.getState() == LoadImageView.LOADING) {
if (bmp != null) {
if (mFixScaleType) {
float aspectRatio = (float)bmp.getHeight() / bmp.getWidth();
if (aspectRatio < 1.7 && aspectRatio > 1.3)
mLiv.setScaleType(ImageView.ScaleType.CENTER_CROP);
else
mLiv.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
if (mTransitabled)
mLiv.setContextImage(bmp, state);
mLiv.setContextImage(bmp, mFixScaleType, true);
else
mLiv.setImageBitmap(bmp);
mLiv.setState(LoadImageView.LOADED);
@@ -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
@@ -1,238 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
public class RefreshLayout extends SwipeRefreshLayout {
private final static int FOOTER_REFRESHING = 0;
private final static int FOOTER_SUCCESS = 1;
private final static int FOOTER_FAIL = 2;
private EasyRecyclerView mEasyRecyclerView;
private View mFooterView;
private TextView mFooterTipTextView;
private View mFooterProgressBar;
private int mFooterState = FOOTER_SUCCESS;
private OnFooterRefreshListener mFooterRefreshListener;
// Footer String to show
private String mFooterRefreshStr;
private String mFooterSuccessStr;
private String mFooterFailStr;
private boolean mIsEnabledHeader = true;
private boolean mIsEnabledFooter = true;
public RefreshLayout(Context context) {
super(context);
init(context, null);
}
public RefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (attrs == null)
mEasyRecyclerView = new EasyRecyclerView(context);
else
mEasyRecyclerView = new EasyRecyclerView(context, attrs);
mEasyRecyclerView.setId(R.id.easy_recycler_view);
addView(mEasyRecyclerView);
// Footer view
mFooterView = LayoutInflater.from(context).inflate(R.layout.pull_list_view_footer, null);
mFooterTipTextView = (TextView) mFooterView.findViewById(R.id.footer_tip_text);
mFooterProgressBar = mFooterView.findViewById(R.id.footer_progressBar);
mFooterView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isRefreshing() && mFooterState == FOOTER_FAIL)
footerRefresh();
}
});
}
public EasyRecyclerView getEasyRecyclerView() {
return mEasyRecyclerView;
}
public void addFooterView() {
((EasyRecyclerView.FooterAdapter<?>) mEasyRecyclerView.getAdapter()).setFooterView(mFooterView);
}
public void removeFooterView() {
((EasyRecyclerView.FooterAdapter<?>) mEasyRecyclerView.getAdapter()).setFooterView(null);
}
public void setOnHeaderRefreshListener(OnRefreshListener l) {
super.setOnRefreshListener(l);
}
public void setOnFooterRefreshListener(OnFooterRefreshListener l) {
mFooterRefreshListener = l;
}
private void footerRefresh() {
if (mFooterRefreshListener.onFooterRefresh()) {
mFooterState = FOOTER_REFRESHING;
changeFooterViewByState();
// Disable header refresh
if (mIsEnabledHeader)
setEnabled(false);
}
}
/**
* Set footer UI String
*
* @param refreshStr
* @param successStr
* @param failStr
*/
public void setFooterString(String refreshStr, String successStr, String failStr) {
mFooterRefreshStr = refreshStr;
mFooterSuccessStr = successStr;
mFooterFailStr = failStr;
switch (mFooterState) {
case FOOTER_REFRESHING:
mFooterTipTextView.setText(mFooterRefreshStr);
break;
case FOOTER_SUCCESS:
mFooterTipTextView.setText(mFooterSuccessStr);
break;
case FOOTER_FAIL:
mFooterTipTextView.setText(mFooterFailStr);
break;
}
}
/**
* Refresh footer UI
*/
private void changeFooterViewByState() {
switch (mFooterState) {
case FOOTER_REFRESHING:
mFooterTipTextView.setText(mFooterRefreshStr);
mFooterProgressBar.setVisibility(View.VISIBLE);
break;
case FOOTER_SUCCESS:
mFooterTipTextView.setText(mFooterSuccessStr);
mFooterProgressBar.setVisibility(View.GONE);
break;
case FOOTER_FAIL:
mFooterTipTextView.setText(mFooterFailStr);
mFooterProgressBar.setVisibility(View.GONE);
break;
}
}
public void setHeaderRefreshComplete() {
super.setRefreshing(false);
}
public void setFooterRefreshComplete(boolean isSuccess) {
if (isSuccess)
mFooterState = FOOTER_SUCCESS;
else
mFooterState = FOOTER_FAIL;
changeFooterViewByState();
// enable header refresh
if (mIsEnabledHeader)
setEnabled(true);
}
public void setAnyRefreshComplete() {
setAnyRefreshComplete(true);
}
public void setAnyRefreshComplete(boolean isSuccess) {
setHeaderRefreshComplete();
setFooterRefreshComplete(isSuccess);
}
/**
* @return True if actionbar is refreshing
*/
public boolean isHeaderRefreshing() {
return super.isRefreshing();
}
/**
* @return True if footer is refreshing
*/
public boolean isFooterRefreshing() {
return mFooterState == FOOTER_REFRESHING;
}
/**
* @return True if actionbar or footer is refreshing
*/
@Override
public boolean isRefreshing() {
return (mIsEnabledHeader ? isHeaderRefreshing() : false)
| (mIsEnabledFooter ? isFooterRefreshing() : false);
}
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (mIsEnabledFooter && mFooterView.isShown() && mFooterState != FOOTER_FAIL)
footerRefresh();
}
public void setEnabledHeader(boolean enabled) {
if (mIsEnabledHeader == enabled)
return;
mIsEnabledHeader = enabled;
setEnabled(enabled);
}
public void setEnabledFooter(boolean enabled) {
if (mIsEnabledFooter == enabled)
return;
if (mIsEnabledFooter = enabled)
addFooterView();
else
removeFooterView();
}
public interface OnFooterRefreshListener {
/**
* @return True if this refresh action is vaild
*/
boolean onFooterRefresh();
}
}
@@ -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();
}
}
@@ -0,0 +1,372 @@
/*
* 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 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,84 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.view.animation.Interpolator;
/**
* A pre-baked bezier-curved interpolator for indeterminate progress animations.
*/
final class BakedBezierInterpolator implements Interpolator {
private static final BakedBezierInterpolator INSTANCE = new BakedBezierInterpolator();
public final static BakedBezierInterpolator getInstance() {
return INSTANCE;
}
/**
* Use getInstance instead of instantiating.
*/
private BakedBezierInterpolator() {
super();
}
/**
* Lookup table values.
* Generated using a Bezier curve from (0,0) to (1,1) with control points:
* P0 (0,0)
* P1 (0.4, 0)
* P2 (0.2, 1.0)
* P3 (1.0, 1.0)
*
* Values sampled with x at regular intervals between 0 and 1.
*/
private static final float[] VALUES = new float[] {
0.0f, 0.0002f, 0.0009f, 0.0019f, 0.0036f, 0.0059f, 0.0086f, 0.0119f, 0.0157f, 0.0209f,
0.0257f, 0.0321f, 0.0392f, 0.0469f, 0.0566f, 0.0656f, 0.0768f, 0.0887f, 0.1033f, 0.1186f,
0.1349f, 0.1519f, 0.1696f, 0.1928f, 0.2121f, 0.237f, 0.2627f, 0.2892f, 0.3109f, 0.3386f,
0.3667f, 0.3952f, 0.4241f, 0.4474f, 0.4766f, 0.5f, 0.5234f, 0.5468f, 0.5701f, 0.5933f,
0.6134f, 0.6333f, 0.6531f, 0.6698f, 0.6891f, 0.7054f, 0.7214f, 0.7346f, 0.7502f, 0.763f,
0.7756f, 0.7879f, 0.8f, 0.8107f, 0.8212f, 0.8326f, 0.8415f, 0.8503f, 0.8588f, 0.8672f,
0.8754f, 0.8833f, 0.8911f, 0.8977f, 0.9041f, 0.9113f, 0.9165f, 0.9232f, 0.9281f, 0.9328f,
0.9382f, 0.9434f, 0.9476f, 0.9518f, 0.9557f, 0.9596f, 0.9632f, 0.9662f, 0.9695f, 0.9722f,
0.9753f, 0.9777f, 0.9805f, 0.9826f, 0.9847f, 0.9866f, 0.9884f, 0.9901f, 0.9917f, 0.9931f,
0.9944f, 0.9955f, 0.9964f, 0.9973f, 0.9981f, 0.9986f, 0.9992f, 0.9995f, 0.9998f, 1.0f, 1.0f
};
private static final float STEP_SIZE = 1.0f / (VALUES.length - 1);
@Override
public float getInterpolation(float input) {
if (input >= 1.0f) {
return 1.0f;
}
if (input <= 0f) {
return 0f;
}
int position = Math.min(
(int)(input * (VALUES.length - 1)),
VALUES.length - 2);
float quantized = position * STEP_SIZE;
float difference = input - quantized;
float weight = difference / STEP_SIZE;
return VALUES[position] + weight * (VALUES[position + 1] - VALUES[position]);
}
}
@@ -0,0 +1,154 @@
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.v4.view.ViewCompat;
import android.view.animation.Animation;
import android.widget.ImageView;
/**
* Private class created to work around issues with AnimationListeners being
* called before the animation is actually complete and support shadows on older
* platforms.
*
* @hide
*/
class CircleImageView extends ImageView {
private static final int KEY_SHADOW_COLOR = 0x1E000000;
private static final int FILL_SHADOW_COLOR = 0x3D000000;
// PX
private static final float X_OFFSET = 0f;
private static final float Y_OFFSET = 1.75f;
private static final float SHADOW_RADIUS = 3.5f;
private static final int SHADOW_ELEVATION = 4;
private Animation.AnimationListener mListener;
private int mShadowRadius;
public CircleImageView(Context context, int color, final float radius) {
super(context);
final float density = getContext().getResources().getDisplayMetrics().density;
final int diameter = (int) (radius * density * 2);
final int shadowYOffset = (int) (density * Y_OFFSET);
final int shadowXOffset = (int) (density * X_OFFSET);
mShadowRadius = (int) (density * SHADOW_RADIUS);
ShapeDrawable circle;
if (elevationSupported()) {
circle = new ShapeDrawable(new OvalShape());
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
} else {
OvalShape oval = new OvalShadow(mShadowRadius, diameter);
circle = new ShapeDrawable(oval);
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint());
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
KEY_SHADOW_COLOR);
final int padding = mShadowRadius;
// set padding so the inner image sits correctly within the shadow.
setPadding(padding, padding, padding, padding);
}
circle.getPaint().setColor(color);
setBackgroundDrawable(circle);
}
private boolean elevationSupported() {
return android.os.Build.VERSION.SDK_INT >= 21;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!elevationSupported()) {
setMeasuredDimension(getMeasuredWidth() + mShadowRadius*2, getMeasuredHeight()
+ mShadowRadius*2);
}
}
public void setAnimationListener(Animation.AnimationListener listener) {
mListener = listener;
}
@Override
public void onAnimationStart() {
super.onAnimationStart();
if (mListener != null) {
mListener.onAnimationStart(getAnimation());
}
}
@Override
public void onAnimationEnd() {
super.onAnimationEnd();
if (mListener != null) {
mListener.onAnimationEnd(getAnimation());
}
}
/**
* Update the background color of the circle image view.
*
* @param colorRes Id of a color resource.
*/
public void setBackgroundColorRes(int colorRes) {
setBackgroundColor(getContext().getResources().getColor(colorRes));
}
@Override
public void setBackgroundColor(int color) {
if (getBackground() instanceof ShapeDrawable) {
((ShapeDrawable) getBackground()).getPaint().setColor(color);
}
}
private class OvalShadow extends OvalShape {
private RadialGradient mRadialGradient;
private int mShadowRadius;
private Paint mShadowPaint;
private int mCircleDiameter;
public OvalShadow(int shadowRadius, int circleDiameter) {
super();
mShadowPaint = new Paint();
mShadowRadius = shadowRadius;
mCircleDiameter = circleDiameter;
mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2,
mShadowRadius, new int[] {
FILL_SHADOW_COLOR, Color.TRANSPARENT
}, null, Shader.TileMode.CLAMP);
mShadowPaint.setShader(mRadialGradient);
}
@Override
public void draw(Canvas canvas, Paint paint) {
final int viewWidth = CircleImageView.this.getWidth();
final int viewHeight = CircleImageView.this.getHeight();
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
mShadowPaint);
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
}
}
}
@@ -0,0 +1,714 @@
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
* Fancy progress indicator for Material theme.
*
* @hide
*/
class MaterialProgressDrawable extends Drawable implements Animatable {
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator END_CURVE_INTERPOLATOR = new EndCurveInterpolator();
private static final Interpolator START_CURVE_INTERPOLATOR = new StartCurveInterpolator();
private static final Interpolator EASE_INTERPOLATOR = new AccelerateDecelerateInterpolator();
@Retention(RetentionPolicy.CLASS)
@IntDef({LARGE, DEFAULT})
public @interface ProgressDrawableSize {}
// Maps to ProgressBar.Large style
static final int LARGE = 0;
// Maps to ProgressBar default style
static final int DEFAULT = 1;
// Maps to ProgressBar default style
private static final int CIRCLE_DIAMETER = 40;
private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
private static final float STROKE_WIDTH = 2.5f;
// Maps to ProgressBar.Large style
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float CENTER_RADIUS_LARGE = 12.5f;
private static final float STROKE_WIDTH_LARGE = 3f;
private final int[] COLORS = new int[] {
Color.BLACK
};
/** The duration of a single progress spin in milliseconds. */
private static final int ANIMATION_DURATION = 1000 * 80 / 60;
/** The number of points in the progress "star". */
private static final float NUM_POINTS = 5f;
/** The list of animators operating on this drawable. */
private final ArrayList<Animation> mAnimators = new ArrayList<Animation>();
/** The indicator ring, used to manage animation state. */
private final Ring mRing;
/** Canvas rotation in degrees. */
private float mRotation;
/** Layout info for the arrowhead in dp */
private static final int ARROW_WIDTH = 10;
private static final int ARROW_HEIGHT = 5;
private static final float ARROW_OFFSET_ANGLE = 5;
/** Layout info for the arrowhead for the large spinner in dp */
private static final int ARROW_WIDTH_LARGE = 12;
private static final int ARROW_HEIGHT_LARGE = 6;
private static final float MAX_PROGRESS_ARC = .8f;
private Resources mResources;
private View mParent;
private Animation mAnimation;
private float mRotationCount;
private double mWidth;
private double mHeight;
boolean mFinishing;
public MaterialProgressDrawable(Context context, View parent) {
mParent = parent;
mResources = context.getResources();
mRing = new Ring(mCallback);
mRing.setColors(COLORS);
updateSizes(DEFAULT);
setupAnimators();
}
private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) {
final Ring ring = mRing;
final DisplayMetrics metrics = mResources.getDisplayMetrics();
final float screenDensity = metrics.density;
mWidth = progressCircleWidth * screenDensity;
mHeight = progressCircleHeight * screenDensity;
ring.setStrokeWidth((float) strokeWidth * screenDensity);
ring.setCenterRadius(centerRadius * screenDensity);
ring.setColorIndex(0);
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
ring.setInsets((int) mWidth, (int) mHeight);
}
/**
* Set the overall size for the progress spinner. This updates the radius
* and stroke width of the ring.
*
* @param size One of {@link #LARGE} or
* {@link #DEFAULT}
*/
public void updateSizes(@ProgressDrawableSize int size) {
if (size == LARGE) {
setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
} else {
setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
ARROW_WIDTH, ARROW_HEIGHT);
}
}
/**
* @param show Set to true to display the arrowhead on the progress spinner.
*/
public void showArrow(boolean show) {
mRing.setShowArrow(show);
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
mRing.setArrowScale(scale);
}
/**
* Set the start and end trim for the progress spinner arc.
*
* @param startAngle start angle
* @param endAngle end angle
*/
public void setStartEndTrim(float startAngle, float endAngle) {
mRing.setStartTrim(startAngle);
mRing.setEndTrim(endAngle);
}
/**
* Set the amount of rotation to apply to the progress spinner.
*
* @param rotation Rotation is from [0..1]
*/
public void setProgressRotation(float rotation) {
mRing.setRotation(rotation);
}
/**
* Update the background color of the circle image view.
*/
public void setBackgroundColor(int color) {
mRing.setBackgroundColor(color);
}
/**
* Set the colors used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
mRing.setColors(colors);
mRing.setColorIndex(0);
}
@Override
public int getIntrinsicHeight() {
return (int) mHeight;
}
@Override
public int getIntrinsicWidth() {
return (int) mWidth;
}
@Override
public void draw(Canvas c) {
final Rect bounds = getBounds();
final int saveCount = c.save();
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
mRing.draw(c, bounds);
c.restoreToCount(saveCount);
}
@Override
public void setAlpha(int alpha) {
mRing.setAlpha(alpha);
}
public int getAlpha() {
return mRing.getAlpha();
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mRing.setColorFilter(colorFilter);
}
@SuppressWarnings("unused")
void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
private float getRotation() {
return mRotation;
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public boolean isRunning() {
final ArrayList<Animation> animators = mAnimators;
final int N = animators.size();
for (int i = 0; i < N; i++) {
final Animation animator = animators.get(i);
if (animator.hasStarted() && !animator.hasEnded()) {
return true;
}
}
return false;
}
@Override
public void start() {
mAnimation.reset();
mRing.storeOriginals();
// Already showing some part of the ring
if (mRing.getEndTrim() != mRing.getStartTrim()) {
mFinishing = true;
mAnimation.setDuration(ANIMATION_DURATION/2);
mParent.startAnimation(mAnimation);
} else {
mRing.setColorIndex(0);
mRing.resetOriginals();
mAnimation.setDuration(ANIMATION_DURATION);
mParent.startAnimation(mAnimation);
}
}
@Override
public void stop() {
mParent.clearAnimation();
setRotation(0);
mRing.setShowArrow(false);
mRing.setColorIndex(0);
mRing.resetOriginals();
}
private void applyFinishTranslation(float interpolatedTime, Ring ring) {
// shrink back down and complete a full rotation before
// starting other circles
// Rotation goes between [0..1].
float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
+ 1f);
final float startTrim = ring.getStartingStartTrim()
+ (ring.getStartingEndTrim() - ring.getStartingStartTrim()) * interpolatedTime;
ring.setStartTrim(startTrim);
final float rotation = ring.getStartingRotation()
+ ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
ring.setRotation(rotation);
}
private void setupAnimators() {
final Ring ring = mRing;
final Animation animation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
if (mFinishing) {
applyFinishTranslation(interpolatedTime, ring);
} else {
// The minProgressArc is calculated from 0 to create an
// angle that
// matches the stroke width.
final float minProgressArc = (float) Math.toRadians(
ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
final float startingEndTrim = ring.getStartingEndTrim();
final float startingTrim = ring.getStartingStartTrim();
final float startingRotation = ring.getStartingRotation();
// Offset the minProgressArc to where the endTrim is
// located.
final float minArc = MAX_PROGRESS_ARC - minProgressArc;
final float endTrim = startingEndTrim + (minArc
* START_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
ring.setEndTrim(endTrim);
final float startTrim = startingTrim + (MAX_PROGRESS_ARC
* END_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
ring.setStartTrim(startTrim);
final float rotation = startingRotation + (0.25f * interpolatedTime);
ring.setRotation(rotation);
float groupRotation = ((720.0f / NUM_POINTS) * interpolatedTime)
+ (720.0f * (mRotationCount / NUM_POINTS));
setRotation(groupRotation);
}
}
};
animation.setRepeatCount(Animation.INFINITE);
animation.setRepeatMode(Animation.RESTART);
animation.setInterpolator(LINEAR_INTERPOLATOR);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mRotationCount = 0;
}
@Override
public void onAnimationEnd(Animation animation) {
// do nothing
}
@Override
public void onAnimationRepeat(Animation animation) {
ring.storeOriginals();
ring.goToNextColor();
ring.setStartTrim(ring.getEndTrim());
if (mFinishing) {
// finished closing the last ring from the swipe gesture; go
// into progress mode
mFinishing = false;
animation.setDuration(ANIMATION_DURATION);
ring.setShowArrow(false);
} else {
mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
}
}
});
mAnimation = animation;
}
private final Callback mCallback = new Callback() {
@Override
public void invalidateDrawable(Drawable d) {
invalidateSelf();
}
@Override
public void scheduleDrawable(Drawable d, Runnable what, long when) {
scheduleSelf(what, when);
}
@Override
public void unscheduleDrawable(Drawable d, Runnable what) {
unscheduleSelf(what);
}
};
private static class Ring {
private final RectF mTempBounds = new RectF();
private final Paint mPaint = new Paint();
private final Paint mArrowPaint = new Paint();
private final Callback mCallback;
private float mStartTrim = 0.0f;
private float mEndTrim = 0.0f;
private float mRotation = 0.0f;
private float mStrokeWidth = 5.0f;
private float mStrokeInset = 2.5f;
private int[] mColors;
// mColorIndex represents the offset into the available mColors that the
// progress circle should currently display. As the progress circle is
// animating, the mColorIndex moves by one to the next available color.
private int mColorIndex;
private float mStartingStartTrim;
private float mStartingEndTrim;
private float mStartingRotation;
private boolean mShowArrow;
private Path mArrow;
private float mArrowScale;
private double mRingCenterRadius;
private int mArrowWidth;
private int mArrowHeight;
private int mAlpha;
private final Paint mCirclePaint = new Paint();
private int mBackgroundColor;
public Ring(Callback callback) {
mCallback = callback;
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setAntiAlias(true);
mPaint.setStyle(Style.STROKE);
mArrowPaint.setStyle(Style.FILL);
mArrowPaint.setAntiAlias(true);
}
public void setBackgroundColor(int color) {
mBackgroundColor = color;
}
/**
* Set the dimensions of the arrowhead.
*
* @param width Width of the hypotenuse of the arrow head
* @param height Height of the arrow point
*/
public void setArrowDimensions(float width, float height) {
mArrowWidth = (int) width;
mArrowHeight = (int) height;
}
/**
* Draw the progress spinner
*/
public void draw(Canvas c, Rect bounds) {
final RectF arcBounds = mTempBounds;
arcBounds.set(bounds);
arcBounds.inset(mStrokeInset, mStrokeInset);
final float startAngle = (mStartTrim + mRotation) * 360;
final float endAngle = (mEndTrim + mRotation) * 360;
float sweepAngle = endAngle - startAngle;
mPaint.setColor(mColors[mColorIndex]);
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
drawTriangle(c, startAngle, sweepAngle, bounds);
if (mAlpha < 255) {
mCirclePaint.setColor(mBackgroundColor);
mCirclePaint.setAlpha(255 - mAlpha);
c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2,
mCirclePaint);
}
}
private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
if (mShowArrow) {
if (mArrow == null) {
mArrow = new Path();
mArrow.setFillType(Path.FillType.EVEN_ODD);
} else {
mArrow.reset();
}
// Adjust the position of the triangle so that it is inset as
// much as the arc, but also centered on the arc.
float inset = (int) mStrokeInset / 2 * mArrowScale;
float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());
// Update the path each time. This works around an issue in SKIA
// where concatenating a rotation matrix to a scale matrix
// ignored a starting negative rotation. This appears to have
// been fixed as of API 21.
mArrow.moveTo(0, 0);
mArrow.lineTo(mArrowWidth * mArrowScale, 0);
mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
* mArrowScale));
mArrow.offset(x - inset, y);
mArrow.close();
// draw a triangle
mArrowPaint.setColor(mColors[mColorIndex]);
c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
bounds.exactCenterY());
c.drawPath(mArrow, mArrowPaint);
}
}
/**
* Set the colors the progress spinner alternates between.
*
* @param colors Array of integers describing the colors. Must be non-<code>null</code>.
*/
public void setColors(@NonNull int[] colors) {
mColors = colors;
// if colors are reset, make sure to reset the color index as well
setColorIndex(0);
}
/**
* @param index Index into the color array of the color to display in
* the progress spinner.
*/
public void setColorIndex(int index) {
mColorIndex = index;
}
/**
* Proceed to the next available ring color. This will automatically
* wrap back to the beginning of colors.
*/
public void goToNextColor() {
mColorIndex = (mColorIndex + 1) % (mColors.length);
}
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
invalidateSelf();
}
/**
* @param alpha Set the alpha of the progress spinner and associated arrowhead.
*/
public void setAlpha(int alpha) {
mAlpha = alpha;
}
/**
* @return Current alpha of the progress spinner and arrowhead.
*/
public int getAlpha() {
return mAlpha;
}
/**
* @param strokeWidth Set the stroke width of the progress spinner in pixels.
*/
public void setStrokeWidth(float strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(strokeWidth);
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStrokeWidth() {
return mStrokeWidth;
}
@SuppressWarnings("unused")
public void setStartTrim(float startTrim) {
mStartTrim = startTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStartTrim() {
return mStartTrim;
}
public float getStartingStartTrim() {
return mStartingStartTrim;
}
public float getStartingEndTrim() {
return mStartingEndTrim;
}
@SuppressWarnings("unused")
public void setEndTrim(float endTrim) {
mEndTrim = endTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getEndTrim() {
return mEndTrim;
}
@SuppressWarnings("unused")
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getRotation() {
return mRotation;
}
public void setInsets(int width, int height) {
final float minEdge = (float) Math.min(width, height);
float insets;
if (mRingCenterRadius <= 0 || minEdge < 0) {
insets = (float) Math.ceil(mStrokeWidth / 2.0f);
} else {
insets = (float) (minEdge / 2.0f - mRingCenterRadius);
}
mStrokeInset = insets;
}
@SuppressWarnings("unused")
public float getInsets() {
return mStrokeInset;
}
/**
* @param centerRadius Inner radius in px of the circle the progress
* spinner arc traces.
*/
public void setCenterRadius(double centerRadius) {
mRingCenterRadius = centerRadius;
}
public double getCenterRadius() {
return mRingCenterRadius;
}
/**
* @param show Set to true to show the arrow head on the progress spinner.
*/
public void setShowArrow(boolean show) {
if (mShowArrow != show) {
mShowArrow = show;
invalidateSelf();
}
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
if (scale != mArrowScale) {
mArrowScale = scale;
invalidateSelf();
}
}
/**
* @return The amount the progress spinner is currently rotated, between [0..1].
*/
public float getStartingRotation() {
return mStartingRotation;
}
/**
* If the start / end trim are offset to begin with, store them so that
* animation starts from that offset.
*/
public void storeOriginals() {
mStartingStartTrim = mStartTrim;
mStartingEndTrim = mEndTrim;
mStartingRotation = mRotation;
}
/**
* Reset the progress spinner to default rotation, start and end angles.
*/
public void resetOriginals() {
mStartingStartTrim = 0;
mStartingEndTrim = 0;
mStartingRotation = 0;
setStartTrim(0);
setEndTrim(0);
setRotation(0);
}
private void invalidateSelf() {
mCallback.invalidateDrawable(null);
}
}
/**
* Squishes the interpolation curve into the second half of the animation.
*/
private static class EndCurveInterpolator extends AccelerateDecelerateInterpolator {
@Override
public float getInterpolation(float input) {
return super.getInterpolation(Math.max(0, (input - 0.5f) * 2.0f));
}
}
/**
* Squishes the interpolation curve into the first half of the animation.
*/
private static class StartCurveInterpolator extends AccelerateDecelerateInterpolator {
@Override
public float getInterpolation(float input) {
return super.getInterpolation(Math.min(1, input * 2.0f));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,276 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
/**
* Custom progress bar that shows a cycle of colors as widening circles that
* overdraw each other. When finished, the bar is cleared from the inside out as
* the main cycle continues. Before running, this can also indicate how close
* the user is to triggering something (e.g. how far they need to pull down to
* trigger a refresh).
*/
final class SwipeProgressBar {
// Default progress animation colors are grays.
private final static int COLOR1 = 0xB3000000;
private final static int COLOR2 = 0x80000000;
private final static int COLOR3 = 0x4d000000;
private final static int COLOR4 = 0x1a000000;
// The duration of the animation cycle.
private static final int ANIMATION_DURATION_MS = 2000;
// The duration of the animation to clear the bar.
private static final int FINISH_ANIMATION_DURATION_MS = 1000;
// Interpolator for varying the speed of the animation.
private static final Interpolator INTERPOLATOR = BakedBezierInterpolator.getInstance();
private final Paint mPaint = new Paint();
private final RectF mClipRect = new RectF();
private float mTriggerPercentage;
private long mStartTime;
private long mFinishTime;
private boolean mRunning;
// Colors used when rendering the animation,
private int mColor1;
private int mColor2;
private int mColor3;
private int mColor4;
private View mParent;
private Rect mBounds = new Rect();
public SwipeProgressBar(View parent) {
mParent = parent;
mColor1 = COLOR1;
mColor2 = COLOR2;
mColor3 = COLOR3;
mColor4 = COLOR4;
}
/**
* Set the four colors used in the progress animation. The first color will
* also be the color of the bar that grows in response to a user swipe
* gesture.
*
* @param color1 Integer representation of a color.
* @param color2 Integer representation of a color.
* @param color3 Integer representation of a color.
* @param color4 Integer representation of a color.
*/
void setColorScheme(int color1, int color2, int color3, int color4) {
mColor1 = color1;
mColor2 = color2;
mColor3 = color3;
mColor4 = color4;
}
/**
* Update the progress the user has made toward triggering the swipe
* gesture. and use this value to update the percentage of the trigger that
* is shown.
*/
void setTriggerPercentage(float triggerPercentage) {
mTriggerPercentage = triggerPercentage;
mStartTime = 0;
ViewCompat.postInvalidateOnAnimation(
mParent, mBounds.left, mBounds.top, mBounds.right, mBounds.bottom);
}
/**
* Start showing the progress animation.
*/
void start() {
if (!mRunning) {
mTriggerPercentage = 0;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = true;
mParent.postInvalidate();
}
}
/**
* Stop showing the progress animation.
*/
void stop() {
if (mRunning) {
mTriggerPercentage = 0;
mFinishTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = false;
mParent.postInvalidate();
}
}
/**
* @return Return whether the progress animation is currently running.
*/
boolean isRunning() {
return mRunning || mFinishTime > 0;
}
void draw(Canvas canvas) {
final int width = mBounds.width();
final int height = mBounds.height();
final int cx = width / 2;
final int cy = height / 2;
boolean drawTriggerWhileFinishing = false;
int restoreCount = canvas.save();
canvas.clipRect(mBounds);
if (mRunning || (mFinishTime > 0)) {
long now = AnimationUtils.currentAnimationTimeMillis();
long elapsed = (now - mStartTime) % ANIMATION_DURATION_MS;
long iterations = (now - mStartTime) / ANIMATION_DURATION_MS;
float rawProgress = (elapsed / (ANIMATION_DURATION_MS / 100f));
// If we're not running anymore, that means we're running through
// the finish animation.
if (!mRunning) {
// If the finish animation is done, don't draw anything, and
// don't repost.
if ((now - mFinishTime) >= FINISH_ANIMATION_DURATION_MS) {
mFinishTime = 0;
return;
}
// Otherwise, use a 0 opacity alpha layer to clear the animation
// from the inside out. This layer will prevent the circles from
// drawing within its bounds.
long finishElapsed = (now - mFinishTime) % FINISH_ANIMATION_DURATION_MS;
float finishProgress = (finishElapsed / (FINISH_ANIMATION_DURATION_MS / 100f));
float pct = (finishProgress / 100f);
// Radius of the circle is half of the screen.
float clearRadius = width / 2 * INTERPOLATOR.getInterpolation(pct);
mClipRect.set(cx - clearRadius, 0, cx + clearRadius, height);
canvas.saveLayerAlpha(mClipRect, 0, 0);
// Only draw the trigger if there is a space in the center of
// this refreshing view that needs to be filled in by the
// trigger. If the progress view is just still animating, let it
// continue animating.
drawTriggerWhileFinishing = true;
}
// First fill in with the last color that would have finished drawing.
if (iterations == 0) {
canvas.drawColor(mColor1);
} else {
if (rawProgress >= 0 && rawProgress < 25) {
canvas.drawColor(mColor4);
} else if (rawProgress >= 25 && rawProgress < 50) {
canvas.drawColor(mColor1);
} else if (rawProgress >= 50 && rawProgress < 75) {
canvas.drawColor(mColor2);
} else {
canvas.drawColor(mColor3);
}
}
// Then draw up to 4 overlapping concentric circles of varying radii, based on how far
// along we are in the cycle.
// progress 0-50 draw mColor2
// progress 25-75 draw mColor3
// progress 50-100 draw mColor4
// progress 75 (wrap to 25) draw mColor1
if ((rawProgress >= 0 && rawProgress <= 25)) {
float pct = (((rawProgress + 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (rawProgress >= 0 && rawProgress <= 50) {
float pct = ((rawProgress * 2) / 100f);
drawCircle(canvas, cx, cy, mColor2, pct);
}
if (rawProgress >= 25 && rawProgress <= 75) {
float pct = (((rawProgress - 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor3, pct);
}
if (rawProgress >= 50 && rawProgress <= 100) {
float pct = (((rawProgress - 50) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor4, pct);
}
if ((rawProgress >= 75 && rawProgress <= 100)) {
float pct = (((rawProgress - 75) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (mTriggerPercentage > 0 && drawTriggerWhileFinishing) {
// There is some portion of trigger to draw. Restore the canvas,
// then draw the trigger. Otherwise, the trigger does not appear
// until after the bar has finished animating and appears to
// just jump in at a larger width than expected.
canvas.restoreToCount(restoreCount);
restoreCount = canvas.save();
canvas.clipRect(mBounds);
drawTrigger(canvas, cx, cy);
}
// Keep running until we finish out the last cycle.
ViewCompat.postInvalidateOnAnimation(
mParent, mBounds.left, mBounds.top, mBounds.right, mBounds.bottom);
} else {
// Otherwise if we're in the middle of a trigger, draw that.
if (mTriggerPercentage > 0 && mTriggerPercentage <= 1.0) {
drawTrigger(canvas, cx, cy);
}
}
canvas.restoreToCount(restoreCount);
}
private void drawTrigger(Canvas canvas, int cx, int cy) {
mPaint.setColor(mColor1);
canvas.drawCircle(cx, cy, cx * mTriggerPercentage, mPaint);
}
/**
* Draws a circle centered in the view.
*
* @param canvas the canvas to draw on
* @param cx the center x coordinate
* @param cy the center y coordinate
* @param color the color to draw
* @param pct the percentage of the view that the circle should cover
*/
private void drawCircle(Canvas canvas, float cx, float cy, int color, float pct) {
mPaint.setColor(color);
canvas.save();
// Go to bottom
canvas.translate(cx, mParent.getHeight() - cy);
float radiusScale = INTERPOLATOR.getInterpolation(pct);
canvas.scale(radiusScale, radiusScale);
canvas.drawCircle(0, 0, cx, mPaint);
canvas.restore();
}
/**
* Set the drawing bounds of this SwipeProgressBar.
*/
void setBounds(int left, int top, int right, int bottom) {
mBounds.left = left;
mBounds.top = top;
mBounds.right = right;
mBounds.bottom = bottom;
}
}
+232
View File
@@ -0,0 +1,232 @@
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_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_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)
+3
View File
@@ -0,0 +1,3 @@
APP_ABI := armeabi armeabi-v7a x86
APP_PLATFORM := android-7
APP_OPTIM := release
+574
View File
@@ -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);
}
+27
View File
@@ -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_ */
+72
View File
@@ -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
+132
View File
@@ -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 */
+39
View File
@@ -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 */
+309
View File
@@ -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 */
+59
View File
@@ -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 */
+411
View File
@@ -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 */
+176
View File
@@ -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) {
}
+75
View File
@@ -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_ */
+147
View File
@@ -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);
}
+20
View File
@@ -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_ */
+10
View File
@@ -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
+145
View File
@@ -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 */
+153
View File
@@ -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 )
};
+108
View File
@@ -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;
}
+71
View File
@@ -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"
+397
View File
@@ -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;
}
+278
View File
@@ -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 */
+763
View File
@@ -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 306 files, more files were not shown because too many files have changed in this diff. Show more