Compare commits

...
18 Commits
Author SHA1 Message Date
seven332 37043c1284 WrongCall 警告 2014-04-01 11:10:55 +08:00
seven332 7f693f4e1d 0.4.0 2014-04-01 11:09:00 +08:00
seven332 529ed71ebe 修正下载阅读文字提示错误 2014-04-01 11:07:20 +08:00
seven332 644d3d6402 检测已存在磁盘中的图片,删除页面缓存 2014-04-01 00:43:42 +08:00
seven332 83395619e7 阅读界面在非下载界面的使用 2014-03-31 23:59:51 +08:00
seven332 cde6904e3f 完成开页方向,单点触控 2014-03-31 00:32:12 +08:00
seven332 74dcbae3dd 初步完成阅读界面 2014-03-30 10:59:41 +08:00
seven332 70f6a2fa78 开启硬件加速 2014-03-29 00:58:41 +08:00
seven332 567b0a2c19 自动更新改为每日检查,user-agent使用默认值 2014-03-28 19:25:54 +08:00
seven332 5e28481684 修正获取网页 2014-03-28 14:38:11 +08:00
seven332 90ed3d40f3 添加注释 2014-03-27 19:59:49 +08:00
seven332 366285f625 修正未判断下载服务获取DownloadInfo为空的错误 2014-03-25 13:11:59 +08:00
seven332 7945b0facd 添加 AutoWrapLayout 每行 baseLine top, center, bottom 功能
修正预览图下沿对齐
2014-03-25 11:50:42 +08:00
seven332 556429a4d6 显示漫画标签组名 2014-03-25 00:14:39 +08:00
seven332 601d426721 完善 AutoWrapLayout onMeasure 函数,图片内存缓存设为 8MB 2014-03-24 23:52:07 +08:00
seven332 aa3d3ca57c update changelog 2014-03-23 23:49:49 +08:00
seven332 471cf5df85 修正更新显示主机错误 2014-03-23 23:48:34 +08:00
seven332 177920a1eb 提升版本号,仅供自动更新测试 2014-03-23 23:27:04 +08:00
87 changed files with 15113 additions and 5820 deletions

No files matched your search

+3 -3
View File
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer"
android:versionCode="7"
android:versionName="0.3.2" >
android:versionCode="10"
android:versionName="0.4.0" >
<uses-sdk
android:minSdkVersion="14"
@@ -16,7 +16,7 @@
android:name=".CrashApplication"
android:allowBackup="true"
android:largeHeap="false"
android:hardwareAccelerated="false"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
+3 -3
View File
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer"
android:versionCode="7"
android:versionName="0.3.2" >
android:versionCode="10"
android:versionName="0.4.0" >
<uses-sdk
android:minSdkVersion="14"
@@ -16,7 +16,7 @@
android:name=".CrashApplication"
android:allowBackup="true"
android:largeHeap="false"
android:hardwareAccelerated="false"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

BIN
View File
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

+68 -68
View File
@@ -1,69 +1,69 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true" >
<ScrollView
android:id="@+id/manga_detail_scrollview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="vertical"
android:scrollbars="vertical" >
<LinearLayout
android:id="@+id/manga_detail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<com.hippo.ehviewer.view.OlImageView
android:id="@+id/detail_cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" />
<TextView
android:id="@+id/detail_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp" />
<include
android:id="@+id/manga_detail_normal"
layout="@layout/detail_normal"
android:visibility="gone" />
<include
android:id="@+id/manga_detail_offensive"
layout="@layout/detail_offensive"
android:visibility="gone" />
<include
android:id="@+id/manga_detail_pining"
layout="@layout/detail_pining"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
<ProgressBar
android:id="@+id/detail_wait"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="@+id/detail_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="buttonRefresh"
android:text="@string/refresh"
android:visibility="gone" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true" >
<ScrollView
android:id="@+id/manga_detail_scrollview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="vertical"
android:scrollbars="vertical" >
<LinearLayout
android:id="@+id/manga_detail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<com.hippo.ehviewer.view.OlImageView
android:id="@+id/detail_cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" />
<TextView
android:id="@+id/detail_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp" />
<include
android:id="@+id/manga_detail_normal"
layout="@layout/detail_normal"
android:visibility="gone" />
<include
android:id="@+id/manga_detail_offensive"
layout="@layout/detail_offensive"
android:visibility="gone" />
<include
android:id="@+id/manga_detail_pining"
layout="@layout/detail_pining"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
<ProgressBar
android:id="@+id/detail_wait"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="@+id/detail_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="buttonRefresh"
android:text="@string/refresh"
android:visibility="gone" />
</RelativeLayout>
+85 -85
View File
@@ -1,86 +1,86 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal" >
<ImageView
android:id="@+id/detail_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_uploader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_posted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_pages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_language"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<LinearLayout
android:id="@+id/detail_rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation = "horizontal"
android:layout_marginBottom="8dp" >
</LinearLayout>
<TextView
android:id="@+id/detail_average"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_people"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<LinearLayout
android:id="@+id/tags_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation = "vertical"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginBottom="8dp" >
</LinearLayout>
<Button
android:id="@+id/button_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:text="@string/detail_button_read"
android:onClick="buttonRead" />
<include
layout="@layout/page_list"
android:id="@+id/page_list"
android:visibility="gone" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal" >
<ImageView
android:id="@+id/detail_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_uploader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_posted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_pages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_language"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<LinearLayout
android:id="@+id/detail_rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation = "horizontal"
android:layout_marginBottom="8dp" >
</LinearLayout>
<TextView
android:id="@+id/detail_average"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/detail_people"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<LinearLayout
android:id="@+id/tags_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation = "vertical"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
android:layout_marginBottom="8dp" >
</LinearLayout>
<Button
android:id="@+id/button_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:text="@string/read"
android:onClick="buttonRead" />
<include
layout="@layout/page_list"
android:id="@+id/page_list"
android:visibility="gone" />
</LinearLayout>
+18
View File
@@ -0,0 +1,18 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.hippo.ehviewer.gallery.ui.GLRootView
android:id="@+id/gl_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
View android:id="@+id/gl_root_cover"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff888888"/
-->
</RelativeLayout>
+3 -1
View File
@@ -1,4 +1,5 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:auto="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="12dp"
@@ -13,7 +14,8 @@
android:id="@+id/paper_list_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
android:layout_gravity="center"
auto:baseLine="bottom">
</com.hippo.ehviewer.widget.AutoWrapLayout>
<ProgressBar
+88 -71
View File
@@ -1,71 +1,88 @@
Version 0.3.2 (2014-03-23)
* 添加启动界面
* 添加自动更新功能
* 添加检测登陆状态按钮
* 添加漫画标签显示
* 优化下拉控件
* 优化侧边栏
* 优化漫画列表
* 优化预览列表,屏幕颠倒可重新布局
* 列表标题显示内容
* 后台检查登陆状态
* 设置中添加移除所有应用通知项
* 修正清除缓存错误
* 修正 game 拼写为 gmae 错误
* 修正其他问题
Version 0.3.1 (2014-03-14)
* 修正有时点击通知栏无法进入下载界面
Version 0.3.0 (2014-03-14)
* 完成搜索标签功能
* 初步完成下载功能
* 修正由收藏进入漫画详情无封面显示
* 修正漫画详情无标题显示
* 修正匹配宽度 y 轴偏移错误
* 加强列表显示稳定性
* 优化列表流畅度
* 微调界面
* 修正其他问题
Version 0.2.2 (2014-03-06)
* 放弃 4.0 以下系统
* 修复多个关键字搜索错误
* 修复列表跳转功能
* 添加状态栏简易搜索
* 微调界面
* 更改筛选为搜索
* 漫画详情页标题改为该漫画的 gid
* 漫画详情页添加收藏按钮
* 修正页面默认缩放错误
* 修正其他问题
Version 0.2.1 (2014-03-02)
* 漫画详情页添加类型与上传者信息
Version 0.2 (2014-03-02)
* 优化网络连接
* 添加网络状态检查
* 添加是否能连接到主机检查
* 添加屏幕方向设置
* 添加警告提示
* 添加作者联系入口
* 添加感谢信息
* 添加双击返回键退出功能
* 添加 exhentai 选项
* 添加漫画详情页面缓存
* 移除容易大量产生的 Toast
* 改善列表显示
* 完善列表跳页功能
* 替换未授权资源
* 更改过滤为筛选
* 修正预览导航栏
* 修正平均得分显示错误
* 修正中文搜索失败
* 修正屏幕重新亮起后页面纯白问题
* 修正从中间读取页面无法查看上一页问题
* 修正页面无限重试问题
* 修正其他问题
Version 0.1 (2014-02-24)
* 公开
Version 0.4.0 (2014-04-01)
* 全新的阅读界面
* 优化内存
* 修正清除缓存可能出现的问题
* 更新使用国内服务
* 修正其他问题
Version 0.3.4 (2014-03-28)
* 完善用于显示预览图的控件
* 显示漫画标签组名
* 自动更新改为每日检查
* 修正其他问题
Version 0.3.3 (2014-03-23)
* 测试自动更新
* 修正没有时更新显示主机错误问题
Version 0.3.2 (2014-03-23)
* 添加启动界面
* 添加自动更新功能
* 添加检测登陆状态按钮
* 添加漫画标签显示
* 优化下拉控件
* 优化侧边栏
* 优化漫画列表
* 优化预览列表,屏幕颠倒可重新布局
* 列表标题显示内容
* 后台检查登陆状态
* 设置中添加移除所有应用通知项
* 修正清除缓存错误
* 修正 game 拼写为 gmae 错误
* 修正其他问题
Version 0.3.1 (2014-03-14)
* 修正有时点击通知栏无法进入下载界面
Version 0.3.0 (2014-03-14)
* 完成搜索标签功能
* 初步完成下载功能
* 修正由收藏进入漫画详情无封面显示
* 修正漫画详情无标题显示
* 修正匹配宽度 y 轴偏移错误
* 加强列表显示稳定性
* 优化列表流畅度
* 微调界面
* 修正其他问题
Version 0.2.2 (2014-03-06)
* 放弃 4.0 以下系统
* 修复多个关键字搜索错误
* 修复列表跳转功能
* 添加状态栏简易搜索
* 微调界面
* 更改筛选为搜索
* 漫画详情页标题改为该漫画的 gid
* 漫画详情页添加收藏按钮
* 修正页面默认缩放错误
* 修正其他问题
Version 0.2.1 (2014-03-02)
* 漫画详情页添加类型与上传者信息
Version 0.2 (2014-03-02)
* 优化网络连接
* 添加网络状态检查
* 添加是否能连接到主机检查
* 添加屏幕方向设置
* 添加警告提示
* 添加作者联系入口
* 添加感谢信息
* 添加双击返回键退出功能
* 添加 exhentai 选项
* 添加漫画详情页面缓存
* 移除容易大量产生的 Toast
* 改善列表显示
* 完善列表跳页功能
* 替换未授权资源
* 更改过滤为筛选
* 修正预览导航栏
* 修正平均得分显示错误
* 修正中文搜索失败
* 修正屏幕重新亮起后页面纯白问题
* 修正从中间读取页面无法查看上一页问题
* 修正页面无限重试问题
* 修正其他问题
Version 0.1 (2014-02-24)
* 公开
+16 -1
View File
@@ -76,7 +76,6 @@
<string name="detail_people">投票人数:%s</string>
<string name="detail_offensive_title">内容警告</string>
<string name="detail_offensive">这个本子被所有人标记为瞎眼。所以任何人都不应该看。\n\n(如果你忽略了这个警告,你就失去了抱怨的权利。)</string>
<string name="detail_button_read">阅读</string>
<string name="detail_button_cancel">算了,不看了</string>
<string name="detail_button_once">就看这一次</string>
<string name="detail_button_every">别再烦我了</string>
@@ -126,6 +125,7 @@
<string name="landscape">横屏</string>
<string name="preference_page_scaling">页面缩放</string>
<string name="preference_start_position">开页位置</string>
<string name="preference_settings_title">设置</string>
<string name="preference_category_cache">缓存</string>
@@ -188,7 +188,15 @@
<string name="not_started">未启动</string>
<string name="waiting">等待中</string>
<!-- GalleryView -->
<string name="pre_page">上一页</string>
<string name="next_page">下一页</string>
<string name="zoom_in">放大</string>
<string name="zoom_out">缩小</string>
<string name="menu">菜单</string>
<!-- Util -->
<string name="read">阅读</string>
<string name="last_page">最后一页!</string>
<string name="unfinished">未完成的功能</string>
<string name="period">。</string>
@@ -219,6 +227,13 @@
<string name="fit_to_width">匹配宽度</string>
<string name="fit_to_height">匹配长度</string>
<string name="fit_to_screen">匹配屏幕</string>
<string name="fixed_scale">固定缩放</string>
<string name="top_left">左上角</string>
<string name="top_right">右上角</string>
<string name="bottom_left">左下角</string>
<string name="bottom_right">右下角</string>
<string name="center">中心</string>
<string name="add_to_favourite">收藏</string>
<string name="remove">移除</string>
+19
View File
@@ -20,6 +20,7 @@
<item>@string/fit_to_width</item>
<item>@string/fit_to_height</item>
<item>@string/fit_to_screen</item>
<item>@string/fixed_scale</item>
</string-array>
<string-array name="page_scaling_entry_values" translatable="false">
@@ -27,6 +28,23 @@
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
<string-array name="start_position_entries">
<item>@string/top_left</item>
<item>@string/top_right</item>
<item>@string/bottom_left</item>
<item>@string/bottom_right</item>
<item>@string/center</item>
</string-array>
<string-array name="start_position_values" translatable="false">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
<string-array name="list_item_long_click">
@@ -42,6 +60,7 @@
<string-array name="download_item_long_click">
<item>@string/remove</item>
<item>@string/remove_info_data</item>
<item>@string/read</item>
</string-array>
<string-array name="preference_screen_ori_entries">
+9 -3
View File
@@ -1,14 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SuperImageView">
<declare-styleable name="SuperImageView">
<!-- Sets a drawable as the content of this ImageView. -->
<attr name="src" format="reference|color" />
<!-- Controls how the image should be resized or moved to match the size
of this ImageView. -->
<attr name="scaleType">
<enum name="matrix" value="0" />
<enum name="fitXY" value="1" /> <!-- error -->
<enum name="fitXY" value="1" />
<enum name="fitStart" value="2" />
<enum name="fitCenter" value="3" />
<enum name="fitEnd" value="4" />
@@ -44,6 +44,12 @@
<attr name="mask" format="reference" />
</declare-styleable>
<declare-styleable name="AutoWrapLayout">
<attr name="baseLine">
<enum name="top" value="0" />
<enum name="center" value="1" />
<enum name="bottom" value="2" />
</attr>
</declare-styleable>
</resources>
+16 -1
View File
@@ -79,7 +79,6 @@
<string name="detail_people">Number of voters: %s</string>
<string name="detail_offensive_title">Content Warning</string>
<string name="detail_offensive">This gallery has been flagged as Offensive For Everyone. Due to its content, it should not be viewed by anyone.\n\n(And if you choose to ignore this warning, you lose all rights to complain about it in the future.)</string>
<string name="detail_button_read">Read</string>
<string name="detail_button_cancel">I would not read it</string>
<string name="detail_button_once">Just this time</string>
<string name="detail_button_every">Do not trouble me</string>
@@ -130,6 +129,7 @@
<string name="portrait">Portrait</string>
<string name="landscape">Landscape</string>
<string name="preference_page_scaling">Page scaling</string>
<string name="preference_start_position">Start position</string>
<string name="preference_settings_title">Settings</string>
<string name="preference_category_cache">Cache</string>
@@ -195,7 +195,15 @@
<string name="not_started">Not started</string>
<string name="waiting">Waiting</string>
<!-- GalleryView -->
<string name="pre_page">Previous page</string>
<string name="next_page">Next page</string>
<string name="zoom_in">Zoom in</string>
<string name="zoom_out">Zoom out</string>
<string name="menu">Menu</string>
<!-- Util -->
<string name="read">Read</string>
<string name="last_page">Last page !</string>
<string name="sadpanda" translatable="false">Sad Panda</string>
<string name="unfinished">Unfinished</string>
@@ -227,6 +235,13 @@
<string name="fit_to_width">Fit to width</string>
<string name="fit_to_height">Fit to height</string>
<string name="fit_to_screen">Fit to screen</string>
<string name="fixed_scale">Fixed</string>
<string name="top_left">Top left</string>
<string name="top_right">Top right</string>
<string name="bottom_left">Bottom left</string>
<string name="bottom_right">Bottom right</string>
<string name="center">Center</string>
<string name="add_to_favourite">Add to favourite</string>
<string name="remove">Remove</string>
+8 -17
View File
@@ -17,6 +17,14 @@
android:key="preference_page_scaling"
android:summary="%s"
android:title="@string/preference_page_scaling" />
<com.hippo.ehviewer.preference.AutoListPreference
android:defaultValue="1"
android:entries="@array/start_position_entries"
android:entryValues="@array/start_position_values"
android:key="preference_start_position"
android:summary="%s"
android:title="@string/preference_page_scaling" />
</PreferenceCategory>
<PreferenceCategory android:title="@string/preference_category_cache" >
@@ -30,23 +38,6 @@
android:key="preference_clear_cp_cache"
android:title="@string/preference_clear_cp_cache" />
<EditTextPreference
android:defaultValue="256"
android:inputType="number"
android:key="preference_page_cache"
android:title="@string/preference_page_cache" />
<Preference
android:key="preference_clear_page_cache"
android:title="@string/preference_clear_page_cache" />
<CheckBoxPreference
android:defaultValue="false"
android:key="preference_auto_page_cache"
android:summaryOff="@string/preference_auto_page_cache_summary_off"
android:summaryOn="@string/preference_auto_page_cache_summary_on"
android:title="@string/preference_auto_page_cache" />
</PreferenceCategory>
<!--
+15 -1
View File
@@ -5,7 +5,7 @@ import com.hippo.ehviewer.dialog.DialogBuilder;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.view.AlertButton;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
@@ -20,6 +20,7 @@ import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class StartActivity extends Activity {
@@ -116,12 +117,25 @@ public class StartActivity extends Activity {
}).create();
}
@SuppressLint("InlinedApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
LinearLayout wellcome = (LinearLayout)findViewById(R.id.app_start_view);
// For fullscreen
if (Build.VERSION.SDK_INT >= 19) {
wellcome.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
// Show welcome in progress
AlphaAnimation aa = new AlphaAnimation(0.3f,1.0f);
aa.setDuration(2000);
+36 -9
View File
@@ -17,22 +17,37 @@ import com.hippo.ehviewer.dialog.DialogBuilder;
import com.hippo.ehviewer.network.Downloader;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.EhClient;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.AlertButton;
public class UpdateHelper {
private static final String TAG = "UpdateHelper";
// Update host
private static final int GOOGLE = 0;
private static final int QINIU = 1;
private Activity mActivity;
private String updateFileName;
private OnCheckUpdateListener listener;
private int downloadHost = QINIU;
public UpdateHelper(Activity activity) {
mActivity = activity;
}
public void autoCheckUpdate() {
if (Config.getUpdateDate() < Util.getDate())
checkUpdate();
}
public void checkUpdate() {
EhClient.checkUpdate(new EhClient.OnCheckUpdateListener() {
@Override
public void onSuccess(String pageContext) {
Config.setUpdateDate();
String[] items = pageContext.split("\n");
if (items.length > 3) {
@@ -40,7 +55,17 @@ public class UpdateHelper {
listener.onSuccess(pageContext);
String newVer = items[0];
final String url = EhClient.UPDATE_URL + items[1];
String tempUrl = "";
switch (downloadHost) {
case GOOGLE:
tempUrl = EhClient.UPDATE_URL + items[1];
break;
case QINIU:
tempUrl = EhClient.UPDATE_URI_QINIU + Util.getFileForUrl(items[1]);
break;
}
final String url = tempUrl;
final String name = url.substring(url.lastIndexOf('/')+1);
updateFileName = name;
String size = items[2];
@@ -69,15 +94,17 @@ public class UpdateHelper {
}).create();
if (!mActivity.isFinishing())
dialog.show();
} else if(pageContext.equals("none")) {
if (listener != null)
listener.onNoUpdate();
} else if(pageContext.equals("error")){
if (listener != null)
listener.onFailure(R.string.em_request_error);
} else {
if (listener != null)
listener.onFailure(R.string.em_host_error);
if(pageContext.equals("none")) {
if (listener != null)
listener.onNoUpdate();
} else if(pageContext.equals("error")){
if (listener != null)
listener.onFailure(R.string.em_request_error);
} else {
if (listener != null)
listener.onFailure(R.string.em_host_error);
}
}
}
@@ -1,388 +1,399 @@
package com.hippo.ehviewer.activity;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.hippo.ehviewer.BeautifyScreen;
import com.hippo.ehviewer.DownloadInfo;
import com.hippo.ehviewer.ListMangaDetail;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dialog.DialogBuilder;
import com.hippo.ehviewer.service.DownloadService;
import com.hippo.ehviewer.service.DownloadServiceConnection;
import com.hippo.ehviewer.util.Cache;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Download;
import com.hippo.ehviewer.util.EhClient;
import com.hippo.ehviewer.util.Favourite;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.AlertButton;
import com.hippo.ehviewer.view.DownloadItemLayout;
import com.hippo.ehviewer.view.OlImageView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class DownloadActivity extends Activity {
private static final String TAG = "DownloadActivity";
private static final String ACTION_UPDATE = "com.hippo.ehviewer.service.UPDATE";
private DownloadServiceConnection mServiceConn = new DownloadServiceConnection();
private List<DownloadInfo> mDownloadInfos;
private DlAdapter mDlAdapter;
private int longClickItemIndex;
private AlertDialog longClickDialog;
private AlertDialog setLongClickDialog() {
return new DialogBuilder(this).setTitle(R.string.what_to_do)
.setItems(R.array.download_item_long_click, new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0: // Remove info item
mServiceConn.getService().cancel(Download.getKey(longClickItemIndex));
Download.remove(longClickItemIndex);
mDlAdapter.notifyDataSetChanged();
break;
case 1: // Remove info item
mServiceConn.getService().cancel(Download.getKey(longClickItemIndex));
mDlAdapter.notifyDataSetChanged();
File dir = new File(Config.getDownloadPath(), Download.get(longClickItemIndex).title);
try {
Util.deleteContents(dir);
} catch (IOException e) {
e.printStackTrace();
}
dir.delete();
Download.remove(longClickItemIndex);
break;
default:
break;
}
longClickDialog.cancel();
}
}).setNegativeButton(android.R.string.cancel, new View.OnClickListener() {
@Override
public void onClick(View v) {
((AlertButton)v).dialog.dismiss();
}
}).create();
}
private class DlAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public DlAdapter() {
mInflater = LayoutInflater.from(DownloadActivity.this);
}
@Override
public int getCount() {
return mDownloadInfos.size();
}
@Override
public Object getItem(int arg0) {
return mDownloadInfos.get(arg0);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
DownloadInfo di= mDownloadInfos.get(position);
if (convertView != null) {
DownloadItemLayout view = (DownloadItemLayout)convertView;
if (!view.gid.equals(di.gid)) {
view.gid = di.gid;
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
OlImageView thumb = (OlImageView)view
.findViewById(R.id.thumb);
thumb.setUrl(di.thumb);
thumb.setKey(String.valueOf(di.gid));
thumb.setCache(Cache.memoryCache, Cache.cpCache);
thumb.loadImage(true);
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(di.title);
setDownloadInfo(view, di);
} else if (view.status != di.status || view.isWait) {
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
setDownloadInfo(view, di);
} else if (view.status == DownloadInfo.DOWNLOADING &&
(view.type != di.type
|| view.lastStartIndex != di.lastStartIndex
|| view.downloadSize != di.downloadSize)) {
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
ProgressBar pb = (ProgressBar)view.findViewById(R.id.progressBar);
TextView info = (TextView)view.findViewById(R.id.info);
if (di.type == DownloadInfo.DETAIL_URL) {
pb.setIndeterminate(true);
info.setText(R.string.downloading);
} else {
pb.setIndeterminate(false);
pb.setMax(di.pageSum);
pb.setProgress(di.lastStartIndex-1);
StringBuilder sb = new StringBuilder(getString(R.string.downloading));
sb.append(" ").append(di.lastStartIndex-1).append(" / ").append(di.pageSum).append("\n");
if (di.totalSize != 0)
sb.append(String.format("%.2f", di.downloadSize))
.append(" / ").append(String.format("%.2f", di.totalSize)).append(" KB");
info.setText(sb.toString());
}
}
return view;
}
DownloadItemLayout view = (DownloadItemLayout)mInflater.inflate(R.layout.download_item, null);
view.gid = di.gid;
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
OlImageView thumb = (OlImageView)view
.findViewById(R.id.thumb);
thumb.setUrl(di.thumb);
thumb.setKey(String.valueOf(di.gid));
thumb.setCache(Cache.memoryCache, Cache.cpCache);
thumb.loadImage(true);
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(di.title);
setDownloadInfo(view, di);
return view;
}
/**
* For clickable button, when click change message to "Please wait", then when action over change message
*
* @param view
* @param di
* @param position
*/
private void setDownloadInfo(final DownloadItemLayout view, final DownloadInfo di) {
final ProgressBar pb = (ProgressBar)view.findViewById(R.id.progressBar);
final TextView info = (TextView)view.findViewById(R.id.info);
final ImageView action = (ImageView)view.findViewById(R.id.action);
if (di.status == DownloadInfo.STOP) {
pb.setVisibility(View.GONE);
String meg = getString(R.string.not_started) + (di.type == DownloadInfo.DETAIL_URL ? ""
: (" " + (di.lastStartIndex-1) + " / " + di.pageSum));
info.setText(meg);
action.setImageResource(R.drawable.ic_action_start);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
startService(it);
mServiceConn.getService().add(di);
}
});
} else if (di.status == DownloadInfo.DOWNLOADING) {
pb.setVisibility(View.VISIBLE);
if (di.type == DownloadInfo.DETAIL_URL) {
pb.setIndeterminate(true);
info.setText(R.string.downloading);
} else {
pb.setIndeterminate(false);
pb.setMax(di.pageSum);
pb.setProgress(di.lastStartIndex-1);
StringBuilder sb = new StringBuilder(getString(R.string.downloading));
sb.append(" ").append(di.lastStartIndex-1).append(" / ").append(di.pageSum).append("\n");
if (di.totalSize != 0)
sb.append(String.format("%.2f", di.downloadSize))
.append(" / ").append(String.format("%.2f", di.totalSize)).append(" KB");
info.setText(sb.toString());
}
action.setImageResource(R.drawable.ic_action_pause);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
mServiceConn.getService().cancel(di.gid);
}
});
} else if (di.status == DownloadInfo.WAITING) {
pb.setVisibility(View.GONE);
info.setText(R.string.waiting);
action.setImageResource(R.drawable.ic_action_pause);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
mServiceConn.getService().cancel(di.gid);
}
});
} else if (di.status == DownloadInfo.COMPLETED) {
pb.setVisibility(View.GONE);
info.setText(R.string.download_successfully);
action.setImageResource(R.drawable.ic_action_completed);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DownloadActivity.this,
MangaDownloadActivity.class);
intent.putExtra("title", di.title);
startActivity(intent);
}
});
} else if (di.status == DownloadInfo.FAILED) {
pb.setVisibility(View.GONE);
String meg = getString(R.string.download_unsuccessfully) + (di.type == DownloadInfo.DETAIL_URL ? ""
: (" " + (di.lastStartIndex-1) + " / " + di.pageSum));
info.setText(meg);
action.setImageResource(R.drawable.ic_action_start);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
startService(it);
mServiceConn.getService().add(di);
}
});
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.fixColour(this);
}
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
unbindService(mServiceConn);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
// Download service
Intent it = new Intent(this, DownloadService.class);
bindService(it, mServiceConn, BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_UPDATE);
registerReceiver(mReceiver, filter);
longClickDialog = setLongClickDialog();
// For colourfy the activity
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.ColourfyScreen(this);
}
mDownloadInfos = Download.getDownloadInfoList();
ListView listView = (ListView)findViewById(R.id.download);
mDlAdapter = new DlAdapter();
listView.setAdapter(mDlAdapter);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
longClickItemIndex = position;
longClickDialog.show();
return true;
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION_UPDATE))
mDlAdapter.notifyDataSetChanged();
}
};
}
package com.hippo.ehviewer.activity;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.hippo.ehviewer.BeautifyScreen;
import com.hippo.ehviewer.DownloadInfo;
import com.hippo.ehviewer.ListMangaDetail;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dialog.DialogBuilder;
import com.hippo.ehviewer.service.DownloadService;
import com.hippo.ehviewer.service.DownloadServiceConnection;
import com.hippo.ehviewer.util.Cache;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Download;
import com.hippo.ehviewer.util.EhClient;
import com.hippo.ehviewer.util.Favourite;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.AlertButton;
import com.hippo.ehviewer.view.DownloadItemLayout;
import com.hippo.ehviewer.view.OlImageView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class DownloadActivity extends Activity {
private static final String TAG = "DownloadActivity";
private DownloadServiceConnection mServiceConn = new DownloadServiceConnection();
private List<DownloadInfo> mDownloadInfos;
private DlAdapter mDlAdapter;
private int longClickItemIndex;
private AlertDialog longClickDialog;
private AlertDialog setLongClickDialog() {
return new DialogBuilder(this).setTitle(R.string.what_to_do)
.setItems(R.array.download_item_long_click, new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0: // Remove info item
mServiceConn.getService().cancel(Download.getKey(longClickItemIndex));
Download.remove(longClickItemIndex);
mDlAdapter.notifyDataSetChanged();
break;
case 1: // Remove info item
mServiceConn.getService().cancel(Download.getKey(longClickItemIndex));
mDlAdapter.notifyDataSetChanged();
// TODO 有人反馈 Download.get(longClickItemIndex).title 为空,看来很有必要在正则抓取时检查是否为空
File dir = new File(Config.getDownloadPath(), Download.get(longClickItemIndex).title);
try {
Util.deleteContents(dir);
} catch (IOException e) {
e.printStackTrace();
}
dir.delete();
Download.remove(longClickItemIndex);
break;
case 2:
DownloadInfo di= mDownloadInfos.get(longClickItemIndex);
Intent intent = new Intent(DownloadActivity.this,
MangaDownloadActivity.class);
intent.putExtra(MangaDownloadActivity.KEY_TITLE, di.title);
intent.putExtra(MangaDownloadActivity.KEY_SIZE, di.pageSum);
intent.putExtra(MangaDownloadActivity.KEY_GID, di.gid);
intent.putExtra(MangaDownloadActivity.KEY_END_INDEX, di.lastStartIndex);
startActivity(intent);
default:
break;
}
longClickDialog.cancel();
}
}).setNegativeButton(android.R.string.cancel, new View.OnClickListener() {
@Override
public void onClick(View v) {
((AlertButton)v).dialog.dismiss();
}
}).create();
}
private class DlAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public DlAdapter() {
mInflater = LayoutInflater.from(DownloadActivity.this);
}
@Override
public int getCount() {
return mDownloadInfos.size();
}
@Override
public Object getItem(int arg0) {
return mDownloadInfos.get(arg0);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
DownloadInfo di= mDownloadInfos.get(position);
if (convertView != null) {
DownloadItemLayout view = (DownloadItemLayout)convertView;
if (!view.gid.equals(di.gid)) {
view.gid = di.gid;
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
OlImageView thumb = (OlImageView)view
.findViewById(R.id.thumb);
thumb.setUrl(di.thumb);
thumb.setKey(String.valueOf(di.gid));
thumb.setCache(Cache.memoryCache, Cache.cpCache);
thumb.loadImage(true);
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(di.title);
setDownloadInfo(view, di);
} else if (view.status != di.status || view.isWait) {
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
setDownloadInfo(view, di);
} else if (view.status == DownloadInfo.DOWNLOADING &&
(view.type != di.type
|| view.lastStartIndex != di.lastStartIndex
|| view.downloadSize != di.downloadSize)) {
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
ProgressBar pb = (ProgressBar)view.findViewById(R.id.progressBar);
TextView info = (TextView)view.findViewById(R.id.info);
if (di.type == DownloadInfo.DETAIL_URL) {
pb.setIndeterminate(true);
info.setText(R.string.downloading);
} else {
pb.setIndeterminate(false);
pb.setMax(di.pageSum);
pb.setProgress(di.lastStartIndex);
StringBuilder sb = new StringBuilder(getString(R.string.downloading));
sb.append(" ").append(di.lastStartIndex).append(" / ").append(di.pageSum).append("\n");
if (di.totalSize != 0)
sb.append(String.format("%.2f", di.downloadSize))
.append(" / ").append(String.format("%.2f", di.totalSize)).append(" KB");
info.setText(sb.toString());
}
}
return view;
}
DownloadItemLayout view = (DownloadItemLayout)mInflater.inflate(R.layout.download_item, null);
view.gid = di.gid;
view.status = di.status;
view.type = di.type;
view.lastStartIndex = di.lastStartIndex;
view.downloadSize = di.downloadSize;
view.isWait = false;
OlImageView thumb = (OlImageView)view
.findViewById(R.id.thumb);
thumb.setUrl(di.thumb);
thumb.setKey(String.valueOf(di.gid));
thumb.setCache(Cache.memoryCache, Cache.cpCache);
thumb.loadImage(true);
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(di.title);
setDownloadInfo(view, di);
return view;
}
/**
* For clickable button, when click change message to "Please wait", then when action over change message
*
* @param view
* @param di
* @param position
*/
private void setDownloadInfo(final DownloadItemLayout view, final DownloadInfo di) {
final ProgressBar pb = (ProgressBar)view.findViewById(R.id.progressBar);
final TextView info = (TextView)view.findViewById(R.id.info);
final ImageView action = (ImageView)view.findViewById(R.id.action);
if (di.status == DownloadInfo.STOP) {
pb.setVisibility(View.GONE);
String meg = getString(R.string.not_started) + (di.type == DownloadInfo.DETAIL_URL ? ""
: (" " + (di.lastStartIndex) + " / " + di.pageSum));
info.setText(meg);
action.setImageResource(R.drawable.ic_action_start);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
startService(it);
mServiceConn.getService().add(di);
}
});
} else if (di.status == DownloadInfo.DOWNLOADING) {
pb.setVisibility(View.VISIBLE);
if (di.type == DownloadInfo.DETAIL_URL) {
pb.setIndeterminate(true);
info.setText(R.string.downloading);
} else {
pb.setIndeterminate(false);
pb.setMax(di.pageSum);
pb.setProgress(di.lastStartIndex);
StringBuilder sb = new StringBuilder(getString(R.string.downloading));
sb.append(" ").append(di.lastStartIndex).append(" / ").append(di.pageSum).append("\n");
if (di.totalSize != 0)
sb.append(String.format("%.2f", di.downloadSize))
.append(" / ").append(String.format("%.2f", di.totalSize)).append(" KB");
info.setText(sb.toString());
}
action.setImageResource(R.drawable.ic_action_pause);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
mServiceConn.getService().cancel(di.gid);
}
});
} else if (di.status == DownloadInfo.WAITING) {
pb.setVisibility(View.GONE);
info.setText(R.string.waiting);
action.setImageResource(R.drawable.ic_action_pause);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
mServiceConn.getService().cancel(di.gid);
}
});
} else if (di.status == DownloadInfo.COMPLETED) {
pb.setVisibility(View.GONE);
info.setText(R.string.download_successfully);
action.setImageResource(R.drawable.ic_action_completed);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DownloadActivity.this,
MangaDownloadActivity.class);
intent.putExtra(MangaDownloadActivity.KEY_TITLE, di.title);
intent.putExtra(MangaDownloadActivity.KEY_SIZE, di.pageSum);
intent.putExtra(MangaDownloadActivity.KEY_GID, di.gid);
intent.putExtra(MangaDownloadActivity.KEY_END_INDEX, di.lastStartIndex);
startActivity(intent);
}
});
} else if (di.status == DownloadInfo.FAILED) {
pb.setVisibility(View.GONE);
String meg = getString(R.string.download_unsuccessfully) + (di.type == DownloadInfo.DETAIL_URL ? ""
: (" " + (di.lastStartIndex) + " / " + di.pageSum));
info.setText(meg);
action.setImageResource(R.drawable.ic_action_start);
action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pb.setVisibility(View.GONE);
info.setText(R.string.wait);
action.setClickable(false);
view.isWait = true;
Intent it = new Intent(DownloadActivity.this, DownloadService.class);
startService(it);
mServiceConn.getService().add(di);
}
});
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.fixColour(this);
}
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
unbindService(mServiceConn);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
// Download service
Intent it = new Intent(this, DownloadService.class);
bindService(it, mServiceConn, BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter();
filter.addAction(DownloadService.ACTION_UPDATE);
registerReceiver(mReceiver, filter);
longClickDialog = setLongClickDialog();
// For colourfy the activity
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.ColourfyScreen(this);
}
mDownloadInfos = Download.getDownloadInfoList();
ListView listView = (ListView)findViewById(R.id.download);
mDlAdapter = new DlAdapter();
listView.setAdapter(mDlAdapter);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
longClickItemIndex = position;
longClickDialog.show();
return true;
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadService.ACTION_UPDATE))
mDlAdapter.notifyDataSetChanged();
}
};
}
+357 -375
View File
@@ -1,375 +1,357 @@
package com.hippo.ehviewer.activity;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.hippo.ehviewer.BeautifyScreen;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.R.id;
import com.hippo.ehviewer.R.layout;
import com.hippo.ehviewer.R.string;
import com.hippo.ehviewer.util.Cache;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.EhClient;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.MangaImage;
import com.hippo.ehviewer.view.MangaViewPager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
// Add load front page
public class MangaActivity extends Activity {
private String TAG = "MangaActivity";
//private String nextPageUrl;
private MangaAdapter ma;
private ArrayList<String[]> imageList;
private MangaViewPager mvp;
private String gid;
private int retryTimes = 0;
private static final int maxRetry = 3;
private boolean stopFlag = false;
private int pageSum;
private int firstPage;
private int lastPage;
private String allPrePageUrl;
private String allNextPageUrl;
private boolean getPrePage = false;
private boolean mStop = false;
private class MangaUrlGetListener implements EhClient.OnGetManagaUrlListener {
@Override
public void onSuccess(Object checkFlag, String[] arg) {
if (stopFlag) {
Log.d(TAG, "Stop by stop flag");
return;
}
retryTimes = 0;
final int targetPage = (Integer)checkFlag;
//
final String key = getKey(targetPage);
final String prePageUrl = arg[0];
final String nextPageUrl = arg[1];
final String imageUrl = arg[2];
if (targetPage == firstPage)
allPrePageUrl = prePageUrl;
if (targetPage == lastPage)
allNextPageUrl = nextPageUrl;
if (targetPage != firstPage && targetPage != lastPage) {
Log.e(TAG, "targetPage != firstPage && targetPage != lastPage");
}
EhClient.getImage(imageUrl, key, Util.getResourcesType(imageUrl), null, Cache.pageCache,
null, new EhClient.OnGetImageListener() {
@Override
public void onSuccess(Object checkFlag, Object res) {
if (res instanceof Bitmap)
((Bitmap)res).recycle();
res = null;
System.gc();
onFinish();
}
@Override
public void onFailure(int errorMessageId) {
Toast.makeText(MangaActivity.this, getString(errorMessageId), Toast.LENGTH_SHORT).show();
onFinish();
}
private void onFinish() {
// Put Image info into imageList
int index = targetPage - firstPage;
if (index >= imageList.size() || index < 0) {
Log.e(TAG, "index is " + index);
index = imageList.size() - 1;
}
String[] imageInfo = imageList.get(index);
imageInfo[0] = imageUrl;
imageInfo[1] = key;
// Read other page or not
if (targetPage == firstPage &&
getPrePage == true) { // If get prePage
getPrePage = false;
} else if (nextPageUrl != "last") { // If get nextPage
EhClient.getManagaUrl(nextPageUrl, targetPage + 1, new MangaUrlGetListener());
imageList.add(new String[]{"wait", null});
lastPage++;
}
ma.notifyDataSetChanged();
}
});
}
@Override
public void onFailure(Object checkFlag, int errorMessageId) {
if (stopFlag) {
Log.d(TAG, "Stop by stop flag");
return;
}
retryTimes++;
int targetPage = (Integer)checkFlag;
if (retryTimes < maxRetry) {
Toast.makeText(MangaActivity.this, getString(errorMessageId) + " " +
String.format(getString(R.string.em_retry_times), retryTimes),
Toast.LENGTH_SHORT).show();
if (targetPage == firstPage &&
getPrePage == true)
EhClient.getManagaUrl(allPrePageUrl, targetPage, new MangaUrlGetListener());
else
EhClient.getManagaUrl(allNextPageUrl, targetPage, new MangaUrlGetListener());
} else {
retryTimes = 0;
if (targetPage == firstPage &&
getPrePage == true) {
getPrePage = false;
Toast.makeText(MangaActivity.this,
getString(R.string.retry_max_pre), Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MangaActivity.this,
getString(R.string.retry_max_next), Toast.LENGTH_SHORT).show();
mStop = true;
}
}
}
}
private String getKey(int targePage) {
// Start from 1
return gid + "-image-" + (targePage + 1);
}
public class MangaAdapter extends PagerAdapter {
@Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View)view);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
String[] imageUrl = imageList.get(position);
MangaImage oiv = new MangaImage(MangaActivity.this);
if (imageUrl[0].equals("wait")) {
oiv.setWaitMovie();
} else {
oiv.setUrl(imageUrl[0]);
oiv.setKey(imageUrl[1]);
oiv.setCache(null, Cache.pageCache);
oiv.loadImage(false);
}
container.addView(oiv, null);
return oiv;
}
@Override
public int getCount() {
return imageList.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public int getItemPosition(Object view) {
MangaImage ovi = (MangaImage)view;
for (int i = 0; i < imageList.size(); i++)
if (imageList.get(i)[0].equals(ovi.getUrl()))
return i;
return POSITION_NONE;
}
}
private class MangaListener implements ViewPager.OnPageChangeListener {
int currentPage = 0;
int oldPage = 0;
@Override
public void onPageScrollStateChanged(int arg0) {
if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
oldPage = currentPage;
currentPage = mvp.getCurrentItem();
if (mvp.distanceX < 0 && oldPage == 0 && currentPage == oldPage) { // First page and attemp to
if ((firstPage > 0 || (imageList.get(0)[0].equals("wait")))
&& allPrePageUrl != null && !allPrePageUrl.equals("first")
&& !getPrePage) {// Try to load pre page
getPrePage = true;
// If last get pre page dose not fail
if (imageList.size() == 1 ||
!imageList.get(0)[0].equals("wait")) {
firstPage--;
imageList.add(0, new String[]{"wait", null});
ma.notifyDataSetChanged();
mvp.setCurrentItem(1);
currentPage++;
oldPage++;
}
EhClient.getManagaUrl(allPrePageUrl, firstPage, new MangaUrlGetListener());
Toast.makeText(MangaActivity.this,
getString(R.string.load_pre), Toast.LENGTH_SHORT).show();
} else if (allPrePageUrl != null
&& allPrePageUrl.equals("first"))
Toast.makeText(MangaActivity.this,
getString(R.string.first_page), Toast.LENGTH_SHORT).show();
else
Toast.makeText(MangaActivity.this, getString(R.string.wait), Toast.LENGTH_SHORT).show();
} else if (mvp.distanceX > 0 && oldPage == imageList.size() - 1 && currentPage == oldPage) { // last page
if (mStop) { // If stop get next page
mStop = false;
EhClient.getManagaUrl(allNextPageUrl, lastPage, new MangaUrlGetListener());
Toast.makeText(MangaActivity.this,
getString(R.string.start_reloading), Toast.LENGTH_SHORT).show();
} else if (allNextPageUrl.equals("last")) {
Toast.makeText(MangaActivity.this,
getString(R.string.last_page), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MangaActivity.this, getString(R.string.wait), Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
@Override
public void onPageSelected(int arg0) {}
}
@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (Build.VERSION.SDK_INT >= 19 && hasFocus && mvp != null) {
mvp.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.fixColour(this);
}
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
// If I do not do it page load when screen is off, will be white
if (mvp != null) {
int childCount = mvp.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = mvp.getChildAt(i);
if (view instanceof MangaImage)
((MangaImage)view).reloadImage();
}
}
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manga);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
getActionBar().hide();
// For API < 16 Fullscreen
if (Build.VERSION.SDK_INT < 19) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Intent intent = getIntent();
firstPage = intent.getIntExtra("firstPage", 0);
lastPage = firstPage;
pageSum = Integer.parseInt(intent.getStringExtra("pageSum"));
String url = intent.getStringExtra("url");
allNextPageUrl = url;
allPrePageUrl = null;
if (firstPage == 0)
allPrePageUrl = "first";
if (firstPage == pageSum - 1)
allNextPageUrl = "last";
gid = intent.getStringExtra("gid");
imageList = new ArrayList<String[]>(pageSum);
mvp = (MangaViewPager)findViewById(R.id.pager);
// For fullscreen
if (Build.VERSION.SDK_INT >= 19) {
mvp.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
ma = new MangaAdapter();
mvp.setAdapter(ma);
MangaListener ml = new MangaListener();
mvp.setOnPageChangeListener(ml);
// Get image and next page
MangaUrlGetListener listener = new MangaUrlGetListener();
EhClient.getManagaUrl(url, firstPage, listener);
// Add progress bar to ViewPager
imageList.add(new String[]{"wait", null});
ma.notifyDataSetChanged();
}
@Override
protected void onDestroy () {
stopFlag = true;
super.onDestroy();
}
}
package com.hippo.ehviewer.activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.hippo.ehviewer.BeautifyScreen;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.R.id;
import com.hippo.ehviewer.R.layout;
import com.hippo.ehviewer.R.string;
import com.hippo.ehviewer.gallery.GalleryView;
import com.hippo.ehviewer.gallery.data.ImageSet;
import com.hippo.ehviewer.gallery.ui.GLRootView;
import com.hippo.ehviewer.network.Downloader;
import com.hippo.ehviewer.util.Cache;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.EhClient;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.MangaImage;
import com.hippo.ehviewer.view.MangaViewPager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
// Add load front page
public class MangaActivity extends Activity {
private String TAG = "MangaActivity";
private RelativeLayout mainView;
private String gid;
private String title;
private int retryTimes = 0;
private static final int maxRetry = 3;
private boolean stopFlag = false;
// [firstPage, lastPage)
// last 是目前已下载的最后一页的 index + 1
private int pageSum;
private int firstPage;
private int lastPage;
private String allPrePageUrl;
private String allNextPageUrl;
private boolean getPrePage = false;
private boolean mStop = false;
private File mFolder;
private ImageSet mImageSet;
private Downloader mDownloader;
// two element, first is web url, second is image url
private ArrayList<String[]> imagesUrl;
private class MangaUrlGetListener implements EhClient.OnGetManagaUrlListener {
@Override
public void onSuccess(Object checkFlag, String[] arg) {
if (stopFlag) {
Log.d(TAG, "Stop by stop flag");
return;
}
retryTimes = 0;
final int index = (Integer)checkFlag;
final String prePageUrl = arg[0];
final String nextPageUrl = arg[1];
final String imageUrl = arg[2];
String[] urls = imagesUrl.get(index);
if (urls == null) {
imagesUrl.add(index, urls = new String[2]);
}
urls[1] = imageUrl;
if (index == firstPage - 1 || (index == firstPage && allPrePageUrl == null)) {
allPrePageUrl = prePageUrl;
if (index > 0)
imagesUrl.add(index - 1, new String[]{allPrePageUrl, null});
}
if (index == lastPage) {
allNextPageUrl = nextPageUrl;
if (index < pageSum - 1)
imagesUrl.add(index + 1, new String[]{allNextPageUrl, null});
}
if (index != firstPage - 1 && (index == firstPage && allPrePageUrl == null) && index != lastPage) {
Log.e(TAG, "targetPage != firstPage - 1 && (targetPage == firstPage && allPrePageUrl == null) && targetPage != lastPage");
}
final String imageName = String.format("%05d", index + 1) + "." + Util.getExtension(imageUrl);
try {
mDownloader.resetData(mFolder.getPath(),
imageName,
imageUrl);
} catch (MalformedURLException e) {
onFailure(checkFlag, R.string.em_url_format_error);
e.printStackTrace();
}
// TODO threadpool
new Thread() {
@Override
public void run() {
// First check is it in disk and ok
if (testImage(mFolder.getPath(), imageName)) {
onGetImage(index, Downloader.COMPLETED, nextPageUrl);
} else {
mDownloader.run();
onGetImage(index, mDownloader.getStatus(), nextPageUrl);
}
}
}.start();
}
// TODO only test bitmap here
private boolean testImage(String path, String name) {
boolean isImage = false;
File file = new File(path, name);
FileInputStream fis = null;
try {
// Just test bound might error
fis = new FileInputStream(file);
Bitmap bmp = BitmapFactory.decodeStream(fis);
if (bmp != null) {
bmp.recycle();
isImage = true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null)
Util.closeStreamQuietly(fis);
}
return isImage;
}
private void onGetImage(int index, int state, String nextPageUrl) {
if (state == Downloader.COMPLETED) {
mImageSet.changeState(index, ImageSet.STATE_LOADED);
} else {
mImageSet.changeState(index, ImageSet.STATE_FAIL);
}
if (index == firstPage - 1 &&
getPrePage == true) { // If get prePage
firstPage--;
getPrePage = false;
} else if (index == lastPage && nextPageUrl != "last") { // If get nextPage
lastPage++;
EhClient.getManagaUrl(nextPageUrl, lastPage, new MangaUrlGetListener());
mImageSet.changeState(lastPage, ImageSet.STATE_LOADING);
}
}
@Override
public void onFailure(Object checkFlag, int errorMessageId) {
if (stopFlag) {
Log.d(TAG, "Stop by stop flag");
return;
}
retryTimes++;
int targetPage = (Integer)checkFlag;
if (retryTimes < maxRetry) {
Toast.makeText(MangaActivity.this, getString(errorMessageId) + " " +
String.format(getString(R.string.em_retry_times), retryTimes),
Toast.LENGTH_SHORT).show();
if (targetPage == firstPage - 1 &&
getPrePage == true) {
EhClient.getManagaUrl(allPrePageUrl, targetPage, new MangaUrlGetListener());
}
else {
EhClient.getManagaUrl(allNextPageUrl, targetPage, new MangaUrlGetListener());
}
mImageSet.changeState(targetPage, ImageSet.STATE_LOADING);
} else {
retryTimes = 0;
if (targetPage == firstPage - 1 &&
getPrePage == true) {
getPrePage = false;
Toast.makeText(MangaActivity.this,
getString(R.string.retry_max_pre), Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MangaActivity.this,
getString(R.string.retry_max_next), Toast.LENGTH_SHORT).show();
mStop = true;
}
mImageSet.changeState(targetPage, ImageSet.STATE_FAIL);
}
}
}
@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (Build.VERSION.SDK_INT >= 19 && hasFocus && mainView != null) {
mainView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= 19) {
BeautifyScreen.fixColour(this);
}
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gl_root_group);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
getActionBar().hide();
// For API < 16 Fullscreen
if (Build.VERSION.SDK_INT < 19) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
mainView = (RelativeLayout)findViewById(R.id.main);
// For fullscreen
if (Build.VERSION.SDK_INT >= 19) {
mainView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
Intent intent = getIntent();
firstPage = intent.getIntExtra("firstPage", 0);
lastPage = firstPage;
gid = intent.getStringExtra("gid");
title = intent.getStringExtra("title");
mFolder = new File(Config.getDownloadPath(), title);
if (mFolder.isFile())
mFolder.delete();
mFolder.mkdirs();
pageSum = Integer.parseInt(intent.getStringExtra("pageSum"));
mImageSet = new ImageSet(this, gid, mFolder, pageSum, firstPage, lastPage, null);
GalleryView isv = new GalleryView(getApplicationContext(), mImageSet, firstPage);
isv.setOnEdgeListener(new GalleryView.OnEdgeListener() {
@Override
public void onLastPageEdge() {
Toast.makeText(MangaActivity.this, getString(R.string.last_page), Toast.LENGTH_SHORT).show();
}
@Override
public void onFirstPageEdge() {
Toast.makeText(MangaActivity.this, getString(R.string.first_page), Toast.LENGTH_SHORT).show();
}
});
isv.setOnTapTextListener(new GalleryView.OnTapTextListener() {
@Override
public void onTapText(int index) {
if (mStop && index == lastPage) {
mStop = false;
MangaUrlGetListener listener = new MangaUrlGetListener();
EhClient.getManagaUrl(allNextPageUrl, lastPage, listener);
mImageSet.changeState(lastPage, ImageSet.STATE_LOADING);
}
}
});
isv.setOnScrollPageListener(new GalleryView.OnScrollPageListener() {
@Override
public void onScrollPage(int index) {
if (mStop && index == lastPage) {
mStop = false;
EhClient.getManagaUrl(allNextPageUrl, lastPage, new MangaUrlGetListener());
mImageSet.changeState(lastPage, ImageSet.STATE_LOADING);
}
if (!getPrePage && allPrePageUrl != null
&& !allPrePageUrl.equals("first")
&& index == firstPage - 1) {
getPrePage = true;
EhClient.getManagaUrl(allPrePageUrl, firstPage - 1, new MangaUrlGetListener());
mImageSet.changeState(firstPage - 1, ImageSet.STATE_LOADING);
}
}
});
GLRootView glrv= (GLRootView)findViewById(R.id.gl_root_view);
glrv.setContentPane(isv);
// Start download
mDownloader = new Downloader();
String url = intent.getStringExtra("url");
allNextPageUrl = url;
allPrePageUrl = null;
if (firstPage == 0)
allPrePageUrl = "first";
if (firstPage == pageSum - 1)
allNextPageUrl = "last";
imagesUrl = new ArrayList<String[]>(pageSum);
imagesUrl.add(lastPage, new String[]{url, null});
// Get image and next page
EhClient.getManagaUrl(url, lastPage, new MangaUrlGetListener());
mImageSet.changeState(lastPage, ImageSet.STATE_LOADING);
}
@Override
protected void onDestroy () {
stopFlag = true;
super.onDestroy();
}
}
File diff suppressed because it is too large. Load diff
@@ -1,150 +1,136 @@
package com.hippo.ehviewer.activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.MangaImage;
import com.hippo.ehviewer.view.MangaViewPager;
import android.R.color;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
public class MangaDownloadActivity extends Activity {
private static final String TAG = "MangaDownloadActivity";
private MangaViewPager pageView;
private File dir;
private ArrayList<String> fileList;
class ImageLoadPackage {
public MangaImage mMangaImage;
public Bitmap mBitmap;
public ImageLoadPackage(MangaImage mangaImage, Bitmap bitmap) {
mMangaImage = mangaImage;
mBitmap = bitmap;
}
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
getActionBar().hide();
// For API < 16 Fullscreen
if (Build.VERSION.SDK_INT < 19) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Intent intent = getIntent();
String title = intent.getStringExtra("title");
if (title == null) {
finish();
return;
}
dir = new File(Config.getDownloadPath(), title);
String[] files;
if (!dir.isDirectory() || (files = dir.list()) == null) {
finish();
return;
}
fileList = new ArrayList<String>();
for (String fileName : files) {
String name = Util.getName(fileName);
if (Util.isNumber(name))
fileList.add(fileName);
}
// TODO do it you self
Collections.sort(fileList);
pageView = new MangaViewPager(this);
pageView.setBackgroundColor(color.darker_gray);
// For fullscreen
if (Build.VERSION.SDK_INT >= 19) {
pageView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
pageView.setAdapter(new PagerAdapter() {
@Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View)view);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
final String imageName = fileList.get(position);
MangaImage oiv = new MangaImage(MangaDownloadActivity.this);
Bitmap bitmap = BitmapFactory.decodeFile(dir.toString() + "/" + imageName);
oiv.setImageBitmap(bitmap);
//oiv.enableZoomMove(true);
container.addView(oiv);
return oiv;
}
@Override
public int getCount() {
return fileList.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
});
setContentView(pageView);
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
}
@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (Build.VERSION.SDK_INT >= 19 && hasFocus && pageView != null) {
pageView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
}
package com.hippo.ehviewer.activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.GalleryView;
import com.hippo.ehviewer.gallery.data.DownloadImageSet;
import com.hippo.ehviewer.gallery.data.ImageSet;
import com.hippo.ehviewer.gallery.ui.GLRootView;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Util;
import com.hippo.ehviewer.view.MangaImage;
import com.hippo.ehviewer.view.MangaViewPager;
import android.R.color;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MangaDownloadActivity extends Activity {
private static final String TAG = "MangaDownloadActivity";
public static final String KEY_TITLE = "title";
public static final String KEY_GID= "gid";
public static final String KEY_SIZE = "size";
public static final String KEY_END_INDEX = "endIndex";
private RelativeLayout mainView;
private DownloadImageSet mDownloadImageSet;
class ImageLoadPackage {
public MangaImage mMangaImage;
public Bitmap mBitmap;
public ImageLoadPackage(MangaImage mangaImage, Bitmap bitmap) {
mMangaImage = mangaImage;
mBitmap = bitmap;
}
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gl_root_group);
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
getActionBar().hide();
// For API < 16 Fullscreen
if (Build.VERSION.SDK_INT < 19) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
mainView = (RelativeLayout)findViewById(R.id.main);
// For fullscreen
if (Build.VERSION.SDK_INT >= 19) {
mainView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
Intent intent = getIntent();
String title = intent.getStringExtra(KEY_TITLE);
String gid = intent.getStringExtra(KEY_GID);
int size = intent.getIntExtra(KEY_SIZE, 1);
int endIndex = intent.getIntExtra(KEY_END_INDEX, 0);
GLRootView glrv= (GLRootView)findViewById(R.id.gl_root_view);
mDownloadImageSet = new DownloadImageSet(this, gid, new File(Config.getDownloadPath(), title), size, 0, endIndex, null);
GalleryView isv = new GalleryView(getApplicationContext(), mDownloadImageSet, 0);
isv.setOnEdgeListener(new GalleryView.OnEdgeListener() {
@Override
public void onLastPageEdge() {
Toast.makeText(MangaDownloadActivity.this, getString(R.string.last_page), Toast.LENGTH_SHORT).show();
}
@Override
public void onFirstPageEdge() {
Toast.makeText(MangaDownloadActivity.this, getString(R.string.first_page), Toast.LENGTH_SHORT).show();
}
});
glrv.setContentPane(isv);
}
@Override
protected void onResume() {
super.onResume();
int screenOri = Config.getScreenOriMode();
if (screenOri != getRequestedOrientation())
setRequestedOrientation(screenOri);
}
@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (Build.VERSION.SDK_INT >= 19 && hasFocus && mainView != null) {
mainView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
@Override
public void onDestroy() {
super.onDestroy();
mDownloadImageSet.unregisterReceiver();
}
}
File diff suppressed because it is too large. Load diff
@@ -32,7 +32,6 @@ import android.support.v4.util.LruCache;
import android.webkit.WebView;
import android.widget.Toast;
//TODO Add thanks
public class SettingsActivity extends PreferenceActivity {
@SuppressWarnings("unused")
private static String TAG = "Settings";
@@ -41,17 +40,15 @@ public class SettingsActivity extends PreferenceActivity {
public LruCache<String, Bitmap> memoryCache;
private String CP_CACHE = "preference_cp_cache";
private String CLEAR_CP_CACHE = "preference_clear_cp_cache";
private String PAGE_CACHE = "preference_page_cache";
private String CLEAR_PAGE_CACHE = "preference_clear_page_cache";
private String PAGE_SCALING = "preference_page_scaling";
private String AUTHOR = "preference_author";
private String SCREEN_ORI = "preference_screen_ori";
private String CHANGELOG = "preference_changelog";
private String THANKS = "preference_thanks";
private String UPDATE = "preference_update";
private String RAN = "preference_remove_all_noification";
private static final String CP_CACHE = "preference_cp_cache";
private static final String CLEAR_CP_CACHE = "preference_clear_cp_cache";
private static final String PAGE_SCALING = "preference_page_scaling";
private static final String AUTHOR = "preference_author";
private static final String SCREEN_ORI = "preference_screen_ori";
private static final String CHANGELOG = "preference_changelog";
private static final String THANKS = "preference_thanks";
private static final String UPDATE = "preference_update";
private static final String RAN = "preference_remove_all_noification";
private EditTextPreference cpCachePre;
private Preference clearCpCachePre;
@@ -157,65 +154,6 @@ public class SettingsActivity extends PreferenceActivity {
}
});
pageCachePre = (EditTextPreference) screen.findPreference(PAGE_CACHE);
pageCachePre
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int pageCacheSize = 0;
try {
int pageCacheSizeInMB = Integer
.parseInt((String) newValue);
if (pageCacheSizeInMB > 1024) {
Toast.makeText(mContext,
getString(R.string.cache_large),
Toast.LENGTH_SHORT).show();
return false;
}
pageCacheSize = pageCacheSizeInMB * 1024 * 1024;
} catch (Exception e) {
Toast.makeText(mContext,
getString(R.string.input_error),
Toast.LENGTH_SHORT).show();
return false;
}
if (pageCacheSize <= 0 && Cache.pageCache != null) {
Cache.pageCache.clear();
Cache.pageCache.close();
Cache.pageCache = null;
} else if (Cache.pageCache == null) {
try {
Cache.pageCache = new DiskCache(
SettingsActivity.this.getApplication()
.getApplicationContext(),
Cache.pageCachePath, pageCacheSize);
} catch (Exception e) {
Toast.makeText(mContext,
getString(R.string.create_cache_error),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else
Cache.pageCache.setMaxSize(pageCacheSize);
updatePageCacheSummary();
return true;
}
});
clearPageCachePre = (Preference) screen
.findPreference(CLEAR_PAGE_CACHE);
updatePageCacheSummary();
clearPageCachePre
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Cache.pageCache.clear();
updatePageCacheSummary();
return true;
}
});
pageScalingListPre = (AutoListPreference) screen
.findPreference(PAGE_SCALING);
pageScalingListPre
@@ -227,7 +165,20 @@ public class SettingsActivity extends PreferenceActivity {
return true;
}
});
/*
final AutoListPreference start_position =
(AutoListPreference)screen.findPreference(START_POSITION);
start_position.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
// TODO Auto-generated method stub
return false;
}
});*/
// Connect me !
authorPer = screen.findPreference(AUTHOR);
authorPer.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@@ -262,7 +213,7 @@ public class SettingsActivity extends PreferenceActivity {
InputStream is = SettingsActivity.this.getResources()
.openRawResource(R.raw.change_log);
new DialogBuilder(SettingsActivity.this).setTitle(R.string.changelog)
.setLongMessage(Util.InputStream2String(is)).create().show();
.setLongMessage(Util.InputStream2String(is, "utf-8")).create().show();
return true;
}
});
@@ -275,7 +226,7 @@ public class SettingsActivity extends PreferenceActivity {
InputStream is = SettingsActivity.this.getResources()
.openRawResource(R.raw.thanks);
final WebView webView = new WebView(SettingsActivity.this);
webView.loadData(Util.InputStream2String(is), "text/html; charset=UTF-8", null);
webView.loadData(Util.InputStream2String(is, "utf-8"), "text/html; charset=UTF-8", null);
new DialogBuilder(SettingsActivity.this).setTitle(R.string.thanks)
.setView(webView, false).create().show();
return true;
@@ -335,18 +286,4 @@ public class SettingsActivity extends PreferenceActivity {
clearCpCachePre.setEnabled(false);
}
}
private void updatePageCacheSummary() {
if (Cache.pageCache != null) {
clearPageCachePre.setSummary(String.format(
getString(R.string.preference_cache_summary),
Cache.pageCache.size() / 1024 / 1024f,
Cache.pageCache.maxSize() / 1024 / 1024));
clearPageCachePre.setEnabled(true);
} else {
clearPageCachePre
.setSummary(getString(R.string.preference_cache_summary_no));
clearPageCachePre.setEnabled(false);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.anim;
import com.hippo.ehviewer.gallery.common.Utils;
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
public class AlphaAnimation extends CanvasAnimation {
private final float mStartAlpha;
private final float mEndAlpha;
private float mCurrentAlpha;
public AlphaAnimation(float from, float to) {
mStartAlpha = from;
mEndAlpha = to;
mCurrentAlpha = from;
}
@Override
public void apply(GLCanvas canvas) {
canvas.multiplyAlpha(mCurrentAlpha);
}
@Override
public int getCanvasSaveFlags() {
return GLCanvas.SAVE_FLAG_ALPHA;
}
@Override
protected void onCalculate(float progress) {
mCurrentAlpha = Utils.clamp(mStartAlpha
+ (mEndAlpha - mStartAlpha) * progress, 0f, 1f);
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.anim;
import android.view.animation.Interpolator;
import com.hippo.ehviewer.gallery.common.Utils;
// Animation calculates a value according to the current input time.
//
// 1. First we need to use setDuration(int) to set the duration of the
// animation. The duration is in milliseconds.
// 2. Then we should call start(). The actual start time is the first value
// passed to calculate(long).
// 3. Each time we want to get an animation value, we call
// calculate(long currentTimeMillis) to ask the Animation to calculate it.
// The parameter passed to calculate(long) should be nonnegative.
// 4. Use get() to get that value.
//
// In step 3, onCalculate(float progress) is called so subclasses can calculate
// the value according to progress (progress is a value in [0,1]).
//
// Before onCalculate(float) is called, There is an optional interpolator which
// can change the progress value. The interpolator can be set by
// setInterpolator(Interpolator). If the interpolator is used, the value passed
// to onCalculate may be (for example, the overshoot effect).
//
// The isActive() method returns true after the animation start() is called and
// before calculate is passed a value which reaches the duration of the
// animation.
//
// The start() method can be called again to restart the Animation.
//
abstract public class Animation {
private static final long ANIMATION_START = -1;
private static final long NO_ANIMATION = -2;
private long mStartTime = NO_ANIMATION;
private int mDuration;
private Interpolator mInterpolator;
public void setInterpolator(Interpolator interpolator) {
mInterpolator = interpolator;
}
public void setDuration(int duration) {
mDuration = duration;
}
public void start() {
mStartTime = ANIMATION_START;
}
public void setStartTime(long time) {
mStartTime = time;
}
public boolean isActive() {
return mStartTime != NO_ANIMATION;
}
public void forceStop() {
mStartTime = NO_ANIMATION;
}
public boolean calculate(long currentTimeMillis) {
if (mStartTime == NO_ANIMATION) return false;
if (mStartTime == ANIMATION_START) mStartTime = currentTimeMillis;
int elapse = (int) (currentTimeMillis - mStartTime);
float x = Utils.clamp((float) elapse / mDuration, 0f, 1f);
Interpolator i = mInterpolator;
onCalculate(i != null ? i.getInterpolation(x) : x);
if (elapse >= mDuration) mStartTime = NO_ANIMATION;
return mStartTime != NO_ANIMATION;
}
abstract protected void onCalculate(float progress);
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.anim;
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
public abstract class CanvasAnimation extends Animation {
public abstract int getCanvasSaveFlags();
public abstract void apply(GLCanvas canvas);
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.anim;
public class FloatAnimation extends Animation {
private final float mFrom;
private final float mTo;
private float mCurrent;
public FloatAnimation(float from, float to, int duration) {
mFrom = from;
mTo = to;
mCurrent = from;
setDuration(duration);
}
@Override
protected void onCalculate(float progress) {
mCurrent = mFrom + (mTo - mFrom) * progress;
}
public float get() {
return mCurrent;
}
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.common;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.hardware.Camera;
import android.os.Build;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.view.WindowManager;
import java.lang.reflect.Field;
public class ApiHelper {
public static interface VERSION_CODES {
// These value are copied from Build.VERSION_CODES
public static final int GINGERBREAD_MR1 = 10;
public static final int HONEYCOMB = 11;
public static final int HONEYCOMB_MR1 = 12;
public static final int HONEYCOMB_MR2 = 13;
public static final int ICE_CREAM_SANDWICH = 14;
public static final int ICE_CREAM_SANDWICH_MR1 = 15;
public static final int JELLY_BEAN = 16;
public static final int JELLY_BEAN_MR1 = 17;
public static final int JELLY_BEAN_MR2 = 18;
}
public static final boolean AT_LEAST_16 = Build.VERSION.SDK_INT >= 16;
public static final boolean USE_888_PIXEL_FORMAT =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean ENABLE_PHOTO_EDITOR =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE =
hasField(View.class, "SYSTEM_UI_FLAG_LAYOUT_STABLE");
public static final boolean HAS_VIEW_SYSTEM_UI_FLAG_HIDE_NAVIGATION =
hasField(View.class, "SYSTEM_UI_FLAG_HIDE_NAVIGATION");
public static final boolean HAS_MEDIA_COLUMNS_WIDTH_AND_HEIGHT =
hasField(MediaColumns.class, "WIDTH");
public static final boolean HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_REUSING_BITMAP_IN_BITMAP_FACTORY =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_SET_BEAM_PUSH_URIS =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_SET_DEFALT_BUFFER_SIZE = hasMethod(
"android.graphics.SurfaceTexture", "setDefaultBufferSize",
int.class, int.class);
public static final boolean HAS_RELEASE_SURFACE_TEXTURE = hasMethod(
"android.graphics.SurfaceTexture", "release");
public static final boolean HAS_SURFACE_TEXTURE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_MTP =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1;
public static final boolean HAS_AUTO_FOCUS_MOVE_CALLBACK =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_REMOTE_VIEWS_SERVICE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_INTENT_EXTRA_LOCAL_ONLY =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_SET_SYSTEM_UI_VISIBILITY =
hasMethod(View.class, "setSystemUiVisibility", int.class);
public static final boolean HAS_FACE_DETECTION;
static {
boolean hasFaceDetection = false;
try {
Class<?> listenerClass = Class.forName(
"android.hardware.Camera$FaceDetectionListener");
hasFaceDetection =
hasMethod(Camera.class, "setFaceDetectionListener", listenerClass) &&
hasMethod(Camera.class, "startFaceDetection") &&
hasMethod(Camera.class, "stopFaceDetection") &&
hasMethod(Camera.Parameters.class, "getMaxNumDetectedFaces");
} catch (Throwable t) {
}
HAS_FACE_DETECTION = hasFaceDetection;
}
public static final boolean HAS_GET_CAMERA_DISABLED =
hasMethod(DevicePolicyManager.class, "getCameraDisabled", ComponentName.class);
public static final boolean HAS_MEDIA_ACTION_SOUND =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_OLD_PANORAMA =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_TIME_LAPSE_RECORDING =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_ZOOM_WHEN_RECORDING =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_CAMERA_FOCUS_AREA =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_CAMERA_METERING_AREA =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_FINE_RESOLUTION_QUALITY_LEVELS =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_MOTION_EVENT_TRANSFORM =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_EFFECTS_RECORDING = false;
// "Background" filter does not have "context" input port in jelly bean.
public static final boolean HAS_EFFECTS_RECORDING_CONTEXT_INPUT =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1;
public static final boolean HAS_GET_SUPPORTED_VIDEO_SIZE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_SET_ICON_ATTRIBUTE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_MEDIA_PROVIDER_FILES_TABLE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_SURFACE_TEXTURE_RECORDING =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_ACTION_BAR =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
// Ex: View.setTranslationX.
public static final boolean HAS_VIEW_TRANSFORM_PROPERTIES =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_CAMERA_HDR =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1;
public static final boolean HAS_OPTIONS_IN_MUTABLE =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean CAN_START_PREVIEW_IN_JPEG_CALLBACK =
Build.VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
public static final boolean HAS_VIEW_PROPERTY_ANIMATOR =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1;
public static final boolean HAS_POST_ON_ANIMATION =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_ANNOUNCE_FOR_ACCESSIBILITY =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_OBJECT_ANIMATION =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_GLES20_REQUIRED =
Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
public static final boolean HAS_ROTATION_ANIMATION =
hasField(WindowManager.LayoutParams.class, "rotationAnimation");
public static final boolean HAS_ORIENTATION_LOCK =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2;
public static final boolean HAS_CANCELLATION_SIGNAL =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
public static final boolean HAS_MEDIA_MUXER =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2;
public static final boolean HAS_DISPLAY_LISTENER =
Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1;
public static int getIntFieldIfExists(Class<?> klass, String fieldName,
Class<?> obj, int defaultVal) {
try {
Field f = klass.getDeclaredField(fieldName);
return f.getInt(obj);
} catch (Exception e) {
return defaultVal;
}
}
private static boolean hasField(Class<?> klass, String fieldName) {
try {
klass.getDeclaredField(fieldName);
return true;
} catch (NoSuchFieldException e) {
return false;
}
}
private static boolean hasMethod(String className, String methodName,
Class<?>... parameterTypes) {
try {
Class<?> klass = Class.forName(className);
klass.getDeclaredMethod(methodName, parameterTypes);
return true;
} catch (Throwable th) {
return false;
}
}
private static boolean hasMethod(
Class<?> klass, String methodName, Class<?> ... paramTypes) {
try {
klass.getDeclaredMethod(methodName, paramTypes);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
}
@@ -0,0 +1,340 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.common;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.util.Log;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
public class Utils {
private static final String TAG = "Utils";
private static final String DEBUG_TAG = "GalleryDebug";
private static final long POLY64REV = 0x95AC9329AC4BC9B5L;
private static final long INITIALCRC = 0xFFFFFFFFFFFFFFFFL;
private static long[] sCrcTable = new long[256];
private static final boolean IS_DEBUG_BUILD =
Build.TYPE.equals("eng") || Build.TYPE.equals("userdebug");
private static final String MASK_STRING = "********************************";
// Throws AssertionError if the input is false.
public static void assertTrue(boolean cond) {
if (!cond) {
throw new AssertionError();
}
}
// Throws AssertionError with the message. We had a method having the form
// assertTrue(boolean cond, String message, Object ... args);
// However a call to that method will cause memory allocation even if the
// condition is false (due to autoboxing generated by "Object ... args"),
// so we don't use that anymore.
public static void fail(String message, Object ... args) {
throw new AssertionError(
args.length == 0 ? message : String.format(message, args));
}
// Throws NullPointerException if the input is null.
public static <T> T checkNotNull(T object) {
if (object == null) throw new NullPointerException();
return object;
}
// Returns true if two input Object are both null or equal
// to each other.
public static boolean equals(Object a, Object b) {
return (a == b) || (a == null ? false : a.equals(b));
}
// Returns the next power of two.
// Returns the input if it is already power of 2.
// Throws IllegalArgumentException if the input is <= 0 or
// the answer overflows.
public static int nextPowerOf2(int n) {
if (n <= 0 || n > (1 << 30)) throw new IllegalArgumentException("n is invalid: " + n);
n -= 1;
n |= n >> 16;
n |= n >> 8;
n |= n >> 4;
n |= n >> 2;
n |= n >> 1;
return n + 1;
}
// Returns the previous power of two.
// Returns the input if it is already power of 2.
// Throws IllegalArgumentException if the input is <= 0
public static int prevPowerOf2(int n) {
if (n <= 0) throw new IllegalArgumentException();
return Integer.highestOneBit(n);
}
// Returns the input value x clamped to the range [min, max].
public static int clamp(int x, int min, int max) {
if (x > max) return max;
if (x < min) return min;
return x;
}
// Returns the input value x clamped to the range [min, max].
public static float clamp(float x, float min, float max) {
if (x > max) return max;
if (x < min) return min;
return x;
}
// Returns the input value x clamped to the range [min, max].
public static long clamp(long x, long min, long max) {
if (x > max) return max;
if (x < min) return min;
return x;
}
public static boolean isOpaque(int color) {
return color >>> 24 == 0xFF;
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
* A function thats returns a 64-bit crc for string
*
* @param in input string
* @return a 64-bit crc value
*/
public static final long crc64Long(String in) {
if (in == null || in.length() == 0) {
return 0;
}
return crc64Long(getBytes(in));
}
static {
// http://bioinf.cs.ucl.ac.uk/downloads/crc64/crc64.c
long part;
for (int i = 0; i < 256; i++) {
part = i;
for (int j = 0; j < 8; j++) {
long x = ((int) part & 1) != 0 ? POLY64REV : 0;
part = (part >> 1) ^ x;
}
sCrcTable[i] = part;
}
}
public static final long crc64Long(byte[] buffer) {
long crc = INITIALCRC;
for (int k = 0, n = buffer.length; k < n; ++k) {
crc = sCrcTable[(((int) crc) ^ buffer[k]) & 0xff] ^ (crc >> 8);
}
return crc;
}
public static byte[] getBytes(String in) {
byte[] result = new byte[in.length() * 2];
int output = 0;
for (char ch : in.toCharArray()) {
result[output++] = (byte) (ch & 0xFF);
result[output++] = (byte) (ch >> 8);
}
return result;
}
public static void closeSilently(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException t) {
Log.w(TAG, "close fail ", t);
}
}
public static int compare(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
public static int ceilLog2(float value) {
int i;
for (i = 0; i < 31; i++) {
if ((1 << i) >= value) break;
}
return i;
}
public static int floorLog2(float value) {
int i;
for (i = 0; i < 31; i++) {
if ((1 << i) > value) break;
}
return i - 1;
}
public static void closeSilently(ParcelFileDescriptor fd) {
try {
if (fd != null) fd.close();
} catch (Throwable t) {
Log.w(TAG, "fail to close", t);
}
}
public static void closeSilently(Cursor cursor) {
try {
if (cursor != null) cursor.close();
} catch (Throwable t) {
Log.w(TAG, "fail to close", t);
}
}
public static float interpolateAngle(
float source, float target, float progress) {
// interpolate the angle from source to target
// We make the difference in the range of [-179, 180], this is the
// shortest path to change source to target.
float diff = target - source;
if (diff < 0) diff += 360f;
if (diff > 180) diff -= 360f;
float result = source + diff * progress;
return result < 0 ? result + 360f : result;
}
public static float interpolateScale(
float source, float target, float progress) {
return source + progress * (target - source);
}
public static String ensureNotNull(String value) {
return value == null ? "" : value;
}
public static float parseFloatSafely(String content, float defaultValue) {
if (content == null) return defaultValue;
try {
return Float.parseFloat(content);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static int parseIntSafely(String content, int defaultValue) {
if (content == null) return defaultValue;
try {
return Integer.parseInt(content);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static boolean isNullOrEmpty(String exifMake) {
return TextUtils.isEmpty(exifMake);
}
public static void waitWithoutInterrupt(Object object) {
try {
object.wait();
} catch (InterruptedException e) {
Log.w(TAG, "unexpected interrupt: " + object);
}
}
public static boolean handleInterrruptedException(Throwable e) {
// A helper to deal with the interrupt exception
// If an interrupt detected, we will setup the bit again.
if (e instanceof InterruptedIOException
|| e instanceof InterruptedException) {
Thread.currentThread().interrupt();
return true;
}
return false;
}
/**
* @return String with special XML characters escaped.
*/
public static String escapeXml(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = s.length(); i < len; ++i) {
char c = s.charAt(i);
switch (c) {
case '<': sb.append("&lt;"); break;
case '>': sb.append("&gt;"); break;
case '\"': sb.append("&quot;"); break;
case '\'': sb.append("&#039;"); break;
case '&': sb.append("&amp;"); break;
default: sb.append(c);
}
}
return sb.toString();
}
public static String getUserAgent(Context context) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
} catch (NameNotFoundException e) {
throw new IllegalStateException("getPackageInfo failed");
}
return String.format("%s/%s; %s/%s/%s/%s; %s/%s/%s",
packageInfo.packageName,
packageInfo.versionName,
Build.BRAND,
Build.DEVICE,
Build.MODEL,
Build.ID,
Build.VERSION.SDK_INT,
Build.VERSION.RELEASE,
Build.VERSION.INCREMENTAL);
}
public static String[] copyOf(String[] source, int newSize) {
String[] result = new String[newSize];
newSize = Math.min(source.length, newSize);
System.arraycopy(source, 0, result, 0, newSize);
return result;
}
// Mask information for debugging only. It returns <code>info.toString()</code> directly
// for debugging build (i.e., 'eng' and 'userdebug') and returns a mask ("****")
// in release build to protect the information (e.g. for privacy issue).
public static String maskDebugInfo(Object info) {
if (info == null) return null;
String s = info.toString();
int length = Math.min(s.length(), MASK_STRING.length());
return IS_DEBUG_BUILD ? s : MASK_STRING.substring(0, length);
}
// This method should be ONLY used for debugging.
public static void debug(String message, Object ... args) {
Log.v(DEBUG_TAG, String.format(message, args));
}
}
@@ -0,0 +1,46 @@
package com.hippo.ehviewer.gallery.data;
import java.io.File;
import java.util.Set;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.hippo.ehviewer.service.DownloadService;
public class DownloadImageSet extends ImageSet {
public DownloadImageSet(Context context, String gid, File folder, int size,
int startIndex, int endIndex, Set<Integer> failIndexSet) {
super(context, gid, folder, size, startIndex, endIndex, failIndexSet);
IntentFilter filter = new IntentFilter();
filter.addAction(DownloadService.ACTION_UPDATE);
mContext.registerReceiver(mReceiver, filter);
}
public void unregisterReceiver() {
mContext.unregisterReceiver(mReceiver);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String gid;
if(intent.getAction().equals(DownloadService.ACTION_UPDATE)
&& (gid = intent.getStringExtra(DownloadService.KEY_GID)) != null
&& gid.equals(mGid)) {
int index = intent.getIntExtra(DownloadService.KEY_INDEX, -1);
int state = intent.getIntExtra(DownloadService.KEY_STATE, -1);
if (index != -1 && state != -1) {
changeState(index, state);
}
}
}
};
}
@@ -0,0 +1,197 @@
package com.hippo.ehviewer.gallery.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;
import com.hippo.ehviewer.util.Future;
import com.hippo.ehviewer.util.FutureListener;
import com.hippo.ehviewer.util.ThreadPool;
import com.hippo.ehviewer.util.ThreadPool.Job;
import com.hippo.ehviewer.util.ThreadPool.JobContext;
import com.hippo.ehviewer.util.Util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.util.SparseArray;
/**
* @author Hippo
*
* ImageSet 用于记录漫画的下载信息
* 对于已完成下载的则无特殊之处。
* 对于未完成下载的要记录,开始下载之处,目前下载截止之处,
* 以及下载失败之处。
* 同时拥有检查该目录识别图片文件。
*/
public class ImageSet {
private static final String TAG = "ImageSet";
public static final int INVALID_ID = -1;
public static final int STATE_NONE = 0;
public static final int STATE_LOADING = 1;
public static final int STATE_LOADED = 2;
public static final int STATE_FAIL = 3;
protected Context mContext;
protected String mGid;
protected File mFolder;
protected int mSize;
private SparseArray<ImageData> mImagesDate;
private ThreadPool mThreadPool;
private OnStateChangeListener mOnStateChangeListener;
public interface OnStateChangeListener {
void onStateChange(int index, int state);
}
public interface OnDecodeOverListener {
void onDecodeOver(Bitmap bmp, int index);
}
private class ImageData {
int state;
String fileName;
public ImageData() {
state = STATE_NONE;
fileName = null;
}
}
// [startIndex, endIndex)
public ImageSet(Context context, String gid, File folder, int size, int startIndex, int endIndex,
Set<Integer> failIndexSet) {
if (folder == null || !folder.isDirectory())
throw new IllegalArgumentException("Folder is null or not directory");
if (size < 0 || startIndex < 0
|| startIndex > endIndex || endIndex > size)
throw new IllegalArgumentException("size or index value error");
mContext = context;
mGid = gid;
mFolder = folder;
mSize = size;
// TODO sometimes size is too large
mImagesDate = new SparseArray<ImageData>(mSize);
int i = 0;
for (; i < startIndex; i++) {
mImagesDate.append(i, new ImageData());
}
for (; i < endIndex; i++) {
if (failIndexSet != null && failIndexSet.contains(i)) {
ImageData imageData = new ImageData();
imageData.state = STATE_FAIL;
mImagesDate.append(i, imageData);
}
else {
// Get file name only when you need it
ImageData imageData = new ImageData();
imageData.state = STATE_LOADED;
mImagesDate.append(i, imageData);
}
}
for (; i < size; i++) {
mImagesDate.append(i, new ImageData());
}
mThreadPool = new ThreadPool(1, 1);
}
public int getSize() {
return mSize;
}
public void setOnStateChangeListener(OnStateChangeListener l) {
mOnStateChangeListener = l;
}
public int getImage(final int index, final OnDecodeOverListener listener) {
final ImageData imageData = mImagesDate.get(index);
int state;
if (imageData == null)
state = INVALID_ID;
else
state = imageData.state;
if (state == STATE_LOADED && listener != null) {
mThreadPool.submit(new Job<Bitmap>() {
@Override
public Bitmap run(JobContext jc) {
Bitmap bmp = null;
if (imageData.fileName == null) {
imageData.fileName = getFileForName(getFileNameForIndex(index));
}
if (imageData.fileName == null)
return null;
Log.d(TAG, imageData.fileName);
File file = new File(mFolder, imageData.fileName);
FileInputStream fis = null;
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
fis = new FileInputStream(file);
bmp = BitmapFactory.decodeStream(fis, null, opt);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null)
Util.closeStreamQuietly(fis);
}
return bmp;
}
}, new FutureListener<Bitmap>() {
@Override
public void onFutureDone(Future<Bitmap> future) {
listener.onDecodeOver(future.get(), index);
}
});
}
return state;
}
@SuppressLint("DefaultLocale")
public String getFileNameForIndex(int index) {
return String.format("%05d", index + 1);
}
public String getFileForName(String name) {
String[] list = mFolder.list();
for (String item : list) {
if(name.equals(Util.getName(item)))
return item;
}
return null;
}
public void changeState(int index, int state) {
final ImageData imageData = mImagesDate.get(index);
if(imageData != null) {
imageData.state = state;
if (mOnStateChangeListener != null) {
mOnStateChangeListener.onStateChange(index, state);
}
}
}
/**
* mSize is faithful
*
*/
public void scan() {
String[] fileList = mFolder.list();
}
}
@@ -0,0 +1,217 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.RectF;
import android.util.Log;
import com.hippo.ehviewer.gallery.common.Utils;
import java.util.WeakHashMap;
// BasicTexture is a Texture corresponds to a real GL texture.
// The state of a BasicTexture indicates whether its data is loaded to GL memory.
// If a BasicTexture is loaded into GL memory, it has a GL texture id.
public abstract class BasicTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "BasicTexture";
protected static final int UNSPECIFIED = -1;
protected static final int STATE_UNLOADED = 0;
protected static final int STATE_LOADED = 1;
protected static final int STATE_ERROR = -1;
// Log a warning if a texture is larger along a dimension
private static final int MAX_TEXTURE_SIZE = 4096;
protected int mId = -1;
protected int mState;
protected int mWidth = UNSPECIFIED;
protected int mHeight = UNSPECIFIED;
protected int mTextureWidth;
protected int mTextureHeight;
private boolean mHasBorder;
protected GLCanvas mCanvasRef = null;
private static WeakHashMap<BasicTexture, Object> sAllTextures
= new WeakHashMap<BasicTexture, Object>();
private static ThreadLocal sInFinalizer = new ThreadLocal();
protected BasicTexture(GLCanvas canvas, int id, int state) {
setAssociatedCanvas(canvas);
mId = id;
mState = state;
synchronized (sAllTextures) {
sAllTextures.put(this, null);
}
}
protected BasicTexture() {
this(null, 0, STATE_UNLOADED);
}
protected void setAssociatedCanvas(GLCanvas canvas) {
mCanvasRef = canvas;
}
/**
* Sets the content size of this texture. In OpenGL, the actual texture
* size must be of power of 2, the size of the content may be smaller.
*/
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
mTextureWidth = width > 0 ? Utils.nextPowerOf2(width) : 0;
mTextureHeight = height > 0 ? Utils.nextPowerOf2(height) : 0;
if (mTextureWidth > MAX_TEXTURE_SIZE || mTextureHeight > MAX_TEXTURE_SIZE) {
Log.w(TAG, String.format("texture is too large: %d x %d",
mTextureWidth, mTextureHeight), new Exception());
}
}
public boolean isFlippedVertically() {
return false;
}
public int getId() {
return mId;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
// Returns the width rounded to the next power of 2.
public int getTextureWidth() {
return mTextureWidth;
}
// Returns the height rounded to the next power of 2.
public int getTextureHeight() {
return mTextureHeight;
}
// Returns true if the texture has one pixel transparent border around the
// actual content. This is used to avoid jigged edges.
//
// The jigged edges appear because we use GL_CLAMP_TO_EDGE for texture wrap
// mode (GL_CLAMP is not available in OpenGL ES), so a pixel partially
// covered by the texture will use the color of the edge texel. If we add
// the transparent border, the color of the edge texel will be mixed with
// appropriate amount of transparent.
//
// Currently our background is black, so we can draw the thumbnails without
// enabling blending.
public boolean hasBorder() {
return mHasBorder;
}
protected void setBorder(boolean hasBorder) {
mHasBorder = hasBorder;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
canvas.drawTexture(this, x, y, getWidth(), getHeight());
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.drawTexture(this, x, y, w, h);
}
public void draw(GLCanvas canvas, RectF source, RectF target) {
canvas.drawTexture(this, source, target);
}
// onBind is called before GLCanvas binds this texture.
// It should make sure the data is uploaded to GL memory.
abstract protected boolean onBind(GLCanvas canvas);
// Returns the GL texture target for this texture (e.g. GL_TEXTURE_2D).
abstract protected int getTarget();
public boolean isLoaded() {
return mState == STATE_LOADED;
}
// recycle() is called when the texture will never be used again,
// so it can free all resources.
public void recycle() {
freeResource();
}
// yield() is called when the texture will not be used temporarily,
// so it can free some resources.
// The default implementation unloads the texture from GL memory, so
// the subclass should make sure it can reload the texture to GL memory
// later, or it will have to override this method.
public void yield() {
freeResource();
}
private void freeResource() {
GLCanvas canvas = mCanvasRef;
if (canvas != null && mId != -1) {
canvas.unloadTexture(this);
mId = -1; // Don't free it again.
}
mState = STATE_UNLOADED;
setAssociatedCanvas(null);
}
@Override
protected void finalize() {
sInFinalizer.set(BasicTexture.class);
recycle();
sInFinalizer.set(null);
}
// This is for deciding if we can call Bitmap's recycle().
// We cannot call Bitmap's recycle() in finalizer because at that point
// the finalizer of Bitmap may already be called so recycle() will crash.
public static boolean inFinalizer() {
return sInFinalizer.get() != null;
}
public static void yieldAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.yield();
}
}
}
public static void invalidateAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.mState = STATE_UNLOADED;
t.setAssociatedCanvas(null);
}
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import junit.framework.Assert;
// BitmapTexture is a texture whose content is specified by a fixed Bitmap.
//
// The texture does not own the Bitmap. The user should make sure the Bitmap
// is valid during the texture's lifetime. When the texture is recycled, it
// does not free the Bitmap.
public class BitmapTexture extends UploadedTexture {
protected Bitmap mContentBitmap;
public BitmapTexture(Bitmap bitmap) {
this(bitmap, false);
}
public BitmapTexture(Bitmap bitmap, boolean hasBorder) {
super(hasBorder);
Assert.assertTrue(bitmap != null && !bitmap.isRecycled());
mContentBitmap = bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
// Do nothing.
}
@Override
protected Bitmap onGetBitmap() {
return mContentBitmap;
}
public Bitmap getBitmap() {
return mContentBitmap;
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
// CanvasTexture is a texture whose content is the drawing on a Canvas.
// The subclasses should override onDraw() to draw on the bitmap.
// By default CanvasTexture is not opaque.
abstract class CanvasTexture extends UploadedTexture {
protected Canvas mCanvas;
private final Config mConfig;
public CanvasTexture(int width, int height) {
mConfig = Config.ARGB_8888;
setSize(width, height);
setOpaque(false);
}
@SuppressLint("WrongCall")
@Override
protected Bitmap onGetBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, mConfig);
mCanvas = new Canvas(bitmap);
onDraw(mCanvas, bitmap);
return bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
if (!inFinalizer()) {
bitmap.recycle();
}
}
abstract protected void onDraw(Canvas canvas, Bitmap backing);
}
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import com.hippo.ehviewer.gallery.common.Utils;
// ColorTexture is a texture which fills the rectangle with the specified color.
public class ColorTexture implements Texture {
private final int mColor;
private int mWidth;
private int mHeight;
public ColorTexture(int color) {
mColor = color;
mWidth = 1;
mHeight = 1;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.fillRect(x, y, w, h, mColor);
}
@Override
public boolean isOpaque() {
return Utils.isOpaque(mColor);
}
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
// ExtTexture is a texture whose content comes from a external texture.
// Before drawing, setSize() should be called.
public class ExtTexture extends BasicTexture {
private int mTarget;
public ExtTexture(GLCanvas canvas, int target) {
GLId glId = canvas.getGLId();
mId = glId.generateTexture();
mTarget = target;
}
private void uploadToCanvas(GLCanvas canvas) {
canvas.setTextureParameters(this);
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
}
@Override
protected boolean onBind(GLCanvas canvas) {
if (!isLoaded()) {
uploadToCanvas(canvas);
}
return true;
}
@Override
public int getTarget() {
return mTarget;
}
@Override
public boolean isOpaque() {
return true;
}
@Override
public void yield() {
// we cannot free the texture because we have no backup.
}
}
@@ -0,0 +1,43 @@
/*
* 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.gallery.glrenderer;
// FadeInTexture is a texture which begins with a color, then gradually animates
// into a given texture.
public class FadeInTexture extends FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeInTexture";
private final int mColor;
private final TiledTexture mTexture;
public FadeInTexture(int color, TiledTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mColor = color;
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
mTexture.drawMixed(canvas, mColor, getRatio(), x, y, w, h);
} else {
mTexture.draw(canvas, x, y, w, h);
}
}
}
@@ -0,0 +1,42 @@
/*
* 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.gallery.glrenderer;
// FadeOutTexture is a texture which begins with a given texture, then gradually animates
// into fading out totally.
public class FadeOutTexture extends FadeTexture {
@SuppressWarnings("unused")
private static final String TAG = "FadeOutTexture";
private final BasicTexture mTexture;
public FadeOutTexture(BasicTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
canvas.save(GLCanvas.SAVE_FLAG_ALPHA);
canvas.setAlpha(getRatio());
mTexture.draw(canvas, x, y, w, h);
canvas.restore();
}
}
}
@@ -0,0 +1,81 @@
/*
* 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.gallery.glrenderer;
import com.hippo.ehviewer.gallery.common.Utils;
import com.hippo.ehviewer.gallery.ui.AnimationTime;
// FadeTexture is a texture which fades the given texture along the time.
public abstract class FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeTexture";
// The duration of the fading animation in milliseconds
public static final int DURATION = 180;
private final long mStartTime;
private final int mWidth;
private final int mHeight;
private final boolean mIsOpaque;
private boolean mIsAnimating;
public FadeTexture(int width, int height, boolean opaque) {
mWidth = width;
mHeight = height;
mIsOpaque = opaque;
mStartTime = now();
mIsAnimating = true;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public boolean isOpaque() {
return mIsOpaque;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
public boolean isAnimating() {
if (mIsAnimating) {
if (now() - mStartTime >= DURATION) {
mIsAnimating = false;
}
}
return mIsAnimating;
}
protected float getRatio() {
float r = (float)(now() - mStartTime) / DURATION;
return Utils.clamp(1.0f - r, 0.0f, 1.0f);
}
private long now() {
return AnimationTime.get();
}
}
@@ -0,0 +1,217 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import javax.microedition.khronos.opengles.GL11;
//
// GLCanvas gives a convenient interface to draw using OpenGL.
//
// When a rectangle is specified in this interface, it means the region
// [x, x+width) * [y, y+height)
//
public interface GLCanvas {
public GLId getGLId();
// Tells GLCanvas the size of the underlying GL surface. This should be
// called before first drawing and when the size of GL surface is changed.
// This is called by GLRoot and should not be called by the clients
// who only want to draw on the GLCanvas. Both width and height must be
// nonnegative.
public abstract void setSize(int width, int height);
// Clear the drawing buffers. This should only be used by GLRoot.
public abstract void clearBuffer();
public abstract void clearBuffer(float[] argb);
// Sets and gets the current alpha, alpha must be in [0, 1].
public abstract void setAlpha(float alpha);
public abstract float getAlpha();
// (current alpha) = (current alpha) * alpha
public abstract void multiplyAlpha(float alpha);
// Change the current transform matrix.
public abstract void translate(float x, float y, float z);
public abstract void translate(float x, float y);
public abstract void scale(float sx, float sy, float sz);
public abstract void rotate(float angle, float x, float y, float z);
public abstract void multiplyMatrix(float[] mMatrix, int offset);
// Pushes the configuration state (matrix, and alpha) onto
// a private stack.
public abstract void save();
// Same as save(), but only save those specified in saveFlags.
public abstract void save(int saveFlags);
public static final int SAVE_FLAG_ALL = 0xFFFFFFFF;
public static final int SAVE_FLAG_ALPHA = 0x01;
public static final int SAVE_FLAG_MATRIX = 0x02;
// Pops from the top of the stack as current configuration state (matrix,
// alpha, and clip). This call balances a previous call to save(), and is
// used to remove all modifications to the configuration state since the
// last save call.
public abstract void restore();
// Draws a line using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
public abstract void drawLine(float x1, float y1, float x2, float y2, GLPaint paint);
// Draws a rectangle using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
public abstract void drawRect(float x1, float y1, float x2, float y2, GLPaint paint);
// Fills the specified rectangle with the specified color.
public abstract void fillRect(float x, float y, float width, float height, int color);
// Draws a texture to the specified rectangle.
public abstract void drawTexture(
BasicTexture texture, int x, int y, int width, int height);
public abstract void drawMesh(BasicTexture tex, int x, int y, int xyBuffer,
int uvBuffer, int indexBuffer, int indexCount);
// Draws the source rectangle part of the texture to the target rectangle.
public abstract void drawTexture(BasicTexture texture, RectF source, RectF target);
// Draw a texture with a specified texture transform.
public abstract void drawTexture(BasicTexture texture, float[] mTextureTransform,
int x, int y, int w, int h);
// Draw two textures to the specified rectangle. The actual texture used is
// from * (1 - ratio) + to * ratio
// The two textures must have the same size.
public abstract void drawMixed(BasicTexture from, int toColor,
float ratio, int x, int y, int w, int h);
// Draw a region of a texture and a specified color to the specified
// rectangle. The actual color used is from * (1 - ratio) + to * ratio.
// The region of the texture is defined by parameter "src". The target
// rectangle is specified by parameter "target".
public abstract void drawMixed(BasicTexture from, int toColor,
float ratio, RectF src, RectF target);
// Unloads the specified texture from the canvas. The resource allocated
// to draw the texture will be released. The specified texture will return
// to the unloaded state. This function should be called only from
// BasicTexture or its descendant
public abstract boolean unloadTexture(BasicTexture texture);
// Delete the specified buffer object, similar to unloadTexture.
public abstract void deleteBuffer(int bufferId);
// Delete the textures and buffers in GL side. This function should only be
// called in the GL thread.
public abstract void deleteRecycledResources();
// Dump statistics information and clear the counters. For debug only.
public abstract void dumpStatisticsAndClear();
public abstract void beginRenderTarget(RawTexture texture);
public abstract void endRenderTarget();
/**
* Sets texture parameters to use GL_CLAMP_TO_EDGE for both
* GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T. Sets texture parameters to be
* GL_LINEAR for GL_TEXTURE_MIN_FILTER and GL_TEXTURE_MAG_FILTER.
* bindTexture() must be called prior to this.
*
* @param texture The texture to set parameters on.
*/
public abstract void setTextureParameters(BasicTexture texture);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
public abstract void initializeTextureSize(BasicTexture texture, int format, int type);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param bitmap The bitmap to initialize the bitmap with.
*/
public abstract void initializeTexture(BasicTexture texture, Bitmap bitmap);
/**
* Calls glTexSubImage2D to upload a bitmap to the texture.
*
* @param texture The target texture to write to.
* @param xOffset Specifies a texel offset in the x direction within the
* texture array.
* @param yOffset Specifies a texel offset in the y direction within the
* texture array.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
public abstract void texSubImage2D(BasicTexture texture, int xOffset, int yOffset,
Bitmap bitmap,
int format, int type);
/**
* Generates buffers and uploads the buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
public abstract int uploadBuffer(java.nio.FloatBuffer buffer);
/**
* Generates buffers and uploads the element array buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
public abstract int uploadBuffer(java.nio.ByteBuffer buffer);
/**
* After LightCycle makes GL calls, this method is called to restore the GL
* configuration to the one expected by GLCanvas.
*/
public abstract void recoverFromLightCycle();
/**
* Gets the bounds given by x, y, width, and height as well as the internal
* matrix state. There is no special handling for non-90-degree rotations.
* It only considers the lower-left and upper-right corners as the bounds.
*
* @param bounds The output bounds to write to.
* @param x The left side of the input rectangle.
* @param y The bottom of the input rectangle.
* @param width The width of the input rectangle.
* @param height The height of the input rectangle.
*/
public abstract void getBounds(Rect bounds, int x, int y, int width, int height);
}
@@ -0,0 +1,997 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.util.Log;
import com.hippo.ehviewer.gallery.common.Utils;
import com.hippo.ehviewer.util.IntArray;
import junit.framework.Assert;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
public class GLES11Canvas implements GLCanvas {
@SuppressWarnings("unused")
private static final String TAG = "GLCanvasImp";
private static final float OPAQUE_ALPHA = 0.95f;
private static final int OFFSET_FILL_RECT = 0;
private static final int OFFSET_DRAW_LINE = 4;
private static final int OFFSET_DRAW_RECT = 6;
private static final float[] BOX_COORDINATES = {
0, 0, 1, 0, 0, 1, 1, 1, // used for filling a rectangle
0, 0, 1, 1, // used for drawing a line
0, 0, 0, 1, 1, 1, 1, 0}; // used for drawing the outline of a rectangle
private GL11 mGL;
private final float mMatrixValues[] = new float[16];
private final float mTextureMatrixValues[] = new float[16];
// The results of mapPoints are stored in this buffer, and the order is
// x1, y1, x2, y2.
private final float mMapPointsBuffer[] = new float[4];
private final float mTextureColor[] = new float[4];
private int mBoxCoords;
private GLState mGLState;
private final ArrayList<RawTexture> mTargetStack = new ArrayList<RawTexture>();
private float mAlpha;
private final ArrayList<ConfigState> mRestoreStack = new ArrayList<ConfigState>();
private ConfigState mRecycledRestoreAction;
private final RectF mDrawTextureSourceRect = new RectF();
private final RectF mDrawTextureTargetRect = new RectF();
private final float[] mTempMatrix = new float[32];
private final IntArray mUnboundTextures = new IntArray();
private final IntArray mDeleteBuffers = new IntArray();
private int mScreenWidth;
private int mScreenHeight;
private boolean mBlendEnabled = true;
private int mFrameBuffer[] = new int[1];
private static float[] sCropRect = new float[4];
private RawTexture mTargetTexture;
// Drawing statistics
int mCountDrawLine;
int mCountFillRect;
int mCountDrawMesh;
int mCountTextureRect;
int mCountTextureOES;
private static GLId mGLId = new GLES11IdImpl();
public GLES11Canvas(GL11 gl) {
mGL = gl;
mGLState = new GLState(gl);
// First create an nio buffer, then create a VBO from it.
int size = BOX_COORDINATES.length * Float.SIZE / Byte.SIZE;
FloatBuffer xyBuffer = allocateDirectNativeOrderBuffer(size).asFloatBuffer();
xyBuffer.put(BOX_COORDINATES, 0, BOX_COORDINATES.length).position(0);
int[] name = new int[1];
mGLId.glGenBuffers(1, name, 0);
mBoxCoords = name[0];
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, mBoxCoords);
gl.glBufferData(GL11.GL_ARRAY_BUFFER, xyBuffer.capacity() * (Float.SIZE / Byte.SIZE),
xyBuffer, GL11.GL_STATIC_DRAW);
gl.glVertexPointer(2, GL11.GL_FLOAT, 0, 0);
gl.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
// Enable the texture coordinate array for Texture 1
gl.glClientActiveTexture(GL11.GL_TEXTURE1);
gl.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
gl.glClientActiveTexture(GL11.GL_TEXTURE0);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// mMatrixValues and mAlpha will be initialized in setSize()
}
@Override
public void setSize(int width, int height) {
Assert.assertTrue(width >= 0 && height >= 0);
if (mTargetTexture == null) {
mScreenWidth = width;
mScreenHeight = height;
}
mAlpha = 1.0f;
GL11 gl = mGL;
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL11.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, width, 0, height);
gl.glMatrixMode(GL11.GL_MODELVIEW);
gl.glLoadIdentity();
float matrix[] = mMatrixValues;
Matrix.setIdentityM(matrix, 0);
// to match the graphic coordinate system in android, we flip it vertically.
if (mTargetTexture == null) {
Matrix.translateM(matrix, 0, 0, height, 0);
Matrix.scaleM(matrix, 0, 1, -1, 1);
}
}
@Override
public void setAlpha(float alpha) {
Assert.assertTrue(alpha >= 0 && alpha <= 1);
mAlpha = alpha;
}
@Override
public float getAlpha() {
return mAlpha;
}
@Override
public void multiplyAlpha(float alpha) {
Assert.assertTrue(alpha >= 0 && alpha <= 1);
mAlpha *= alpha;
}
private static ByteBuffer allocateDirectNativeOrderBuffer(int size) {
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
@Override
public void drawRect(float x, float y, float width, float height, GLPaint paint) {
GL11 gl = mGL;
mGLState.setColorMode(paint.getColor(), mAlpha);
mGLState.setLineWidth(paint.getLineWidth());
saveTransform();
translate(x, y);
scale(width, height, 1);
gl.glLoadMatrixf(mMatrixValues, 0);
gl.glDrawArrays(GL11.GL_LINE_LOOP, OFFSET_DRAW_RECT, 4);
restoreTransform();
mCountDrawLine++;
}
@Override
public void drawLine(float x1, float y1, float x2, float y2, GLPaint paint) {
GL11 gl = mGL;
mGLState.setColorMode(paint.getColor(), mAlpha);
mGLState.setLineWidth(paint.getLineWidth());
saveTransform();
translate(x1, y1);
scale(x2 - x1, y2 - y1, 1);
gl.glLoadMatrixf(mMatrixValues, 0);
gl.glDrawArrays(GL11.GL_LINE_STRIP, OFFSET_DRAW_LINE, 2);
restoreTransform();
mCountDrawLine++;
}
@Override
public void fillRect(float x, float y, float width, float height, int color) {
mGLState.setColorMode(color, mAlpha);
GL11 gl = mGL;
saveTransform();
translate(x, y);
scale(width, height, 1);
gl.glLoadMatrixf(mMatrixValues, 0);
gl.glDrawArrays(GL11.GL_TRIANGLE_STRIP, OFFSET_FILL_RECT, 4);
restoreTransform();
mCountFillRect++;
}
@Override
public void translate(float x, float y, float z) {
Matrix.translateM(mMatrixValues, 0, x, y, z);
}
// This is a faster version of translate(x, y, z) because
// (1) we knows z = 0, (2) we inline the Matrix.translateM call,
// (3) we unroll the loop
@Override
public void translate(float x, float y) {
float[] m = mMatrixValues;
m[12] += m[0] * x + m[4] * y;
m[13] += m[1] * x + m[5] * y;
m[14] += m[2] * x + m[6] * y;
m[15] += m[3] * x + m[7] * y;
}
@Override
public void scale(float sx, float sy, float sz) {
Matrix.scaleM(mMatrixValues, 0, sx, sy, sz);
}
@Override
public void rotate(float angle, float x, float y, float z) {
if (angle == 0) return;
float[] temp = mTempMatrix;
Matrix.setRotateM(temp, 0, angle, x, y, z);
Matrix.multiplyMM(temp, 16, mMatrixValues, 0, temp, 0);
System.arraycopy(temp, 16, mMatrixValues, 0, 16);
}
@Override
public void multiplyMatrix(float matrix[], int offset) {
float[] temp = mTempMatrix;
Matrix.multiplyMM(temp, 0, mMatrixValues, 0, matrix, offset);
System.arraycopy(temp, 0, mMatrixValues, 0, 16);
}
private void textureRect(float x, float y, float width, float height) {
GL11 gl = mGL;
saveTransform();
translate(x, y);
scale(width, height, 1);
gl.glLoadMatrixf(mMatrixValues, 0);
gl.glDrawArrays(GL11.GL_TRIANGLE_STRIP, OFFSET_FILL_RECT, 4);
restoreTransform();
mCountTextureRect++;
}
@Override
public void drawMesh(BasicTexture tex, int x, int y, int xyBuffer,
int uvBuffer, int indexBuffer, int indexCount) {
float alpha = mAlpha;
if (!bindTexture(tex)) return;
mGLState.setBlendEnabled(mBlendEnabled
&& (!tex.isOpaque() || alpha < OPAQUE_ALPHA));
mGLState.setTextureAlpha(alpha);
// Reset the texture matrix. We will set our own texture coordinates
// below.
setTextureCoords(0, 0, 1, 1);
saveTransform();
translate(x, y);
mGL.glLoadMatrixf(mMatrixValues, 0);
mGL.glBindBuffer(GL11.GL_ARRAY_BUFFER, xyBuffer);
mGL.glVertexPointer(2, GL11.GL_FLOAT, 0, 0);
mGL.glBindBuffer(GL11.GL_ARRAY_BUFFER, uvBuffer);
mGL.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
mGL.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
mGL.glDrawElements(GL11.GL_TRIANGLE_STRIP,
indexCount, GL11.GL_UNSIGNED_BYTE, 0);
mGL.glBindBuffer(GL11.GL_ARRAY_BUFFER, mBoxCoords);
mGL.glVertexPointer(2, GL11.GL_FLOAT, 0, 0);
mGL.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
restoreTransform();
mCountDrawMesh++;
}
// Transforms two points by the given matrix m. The result
// {x1', y1', x2', y2'} are stored in mMapPointsBuffer and also returned.
private float[] mapPoints(float m[], int x1, int y1, int x2, int y2) {
float[] r = mMapPointsBuffer;
// Multiply m and (x1 y1 0 1) to produce (x3 y3 z3 w3). z3 is unused.
float x3 = m[0] * x1 + m[4] * y1 + m[12];
float y3 = m[1] * x1 + m[5] * y1 + m[13];
float w3 = m[3] * x1 + m[7] * y1 + m[15];
r[0] = x3 / w3;
r[1] = y3 / w3;
// Same for x2 y2.
float x4 = m[0] * x2 + m[4] * y2 + m[12];
float y4 = m[1] * x2 + m[5] * y2 + m[13];
float w4 = m[3] * x2 + m[7] * y2 + m[15];
r[2] = x4 / w4;
r[3] = y4 / w4;
return r;
}
private void drawBoundTexture(
BasicTexture texture, int x, int y, int width, int height) {
// Test whether it has been rotated or flipped, if so, glDrawTexiOES
// won't work
if (isMatrixRotatedOrFlipped(mMatrixValues)) {
if (texture.hasBorder()) {
setTextureCoords(
1.0f / texture.getTextureWidth(),
1.0f / texture.getTextureHeight(),
(texture.getWidth() - 1.0f) / texture.getTextureWidth(),
(texture.getHeight() - 1.0f) / texture.getTextureHeight());
} else {
setTextureCoords(0, 0,
(float) texture.getWidth() / texture.getTextureWidth(),
(float) texture.getHeight() / texture.getTextureHeight());
}
textureRect(x, y, width, height);
} else {
// draw the rect from bottom-left to top-right
float points[] = mapPoints(
mMatrixValues, x, y + height, x + width, y);
x = (int) (points[0] + 0.5f);
y = (int) (points[1] + 0.5f);
width = (int) (points[2] + 0.5f) - x;
height = (int) (points[3] + 0.5f) - y;
if (width > 0 && height > 0) {
((GL11Ext) mGL).glDrawTexiOES(x, y, 0, width, height);
mCountTextureOES++;
}
}
}
@Override
public void drawTexture(
BasicTexture texture, int x, int y, int width, int height) {
drawTexture(texture, x, y, width, height, mAlpha);
}
private void drawTexture(BasicTexture texture,
int x, int y, int width, int height, float alpha) {
if (width <= 0 || height <= 0) return;
mGLState.setBlendEnabled(mBlendEnabled
&& (!texture.isOpaque() || alpha < OPAQUE_ALPHA));
if (!bindTexture(texture)) return;
mGLState.setTextureAlpha(alpha);
drawBoundTexture(texture, x, y, width, height);
}
@Override
public void drawTexture(BasicTexture texture, RectF source, RectF target) {
if (target.width() <= 0 || target.height() <= 0) return;
// Copy the input to avoid changing it.
mDrawTextureSourceRect.set(source);
mDrawTextureTargetRect.set(target);
source = mDrawTextureSourceRect;
target = mDrawTextureTargetRect;
mGLState.setBlendEnabled(mBlendEnabled
&& (!texture.isOpaque() || mAlpha < OPAQUE_ALPHA));
if (!bindTexture(texture)) return;
convertCoordinate(source, target, texture);
setTextureCoords(source);
mGLState.setTextureAlpha(mAlpha);
textureRect(target.left, target.top, target.width(), target.height());
}
@Override
public void drawTexture(BasicTexture texture, float[] mTextureTransform,
int x, int y, int w, int h) {
mGLState.setBlendEnabled(mBlendEnabled
&& (!texture.isOpaque() || mAlpha < OPAQUE_ALPHA));
if (!bindTexture(texture)) return;
setTextureCoords(mTextureTransform);
mGLState.setTextureAlpha(mAlpha);
textureRect(x, y, w, h);
}
// This function changes the source coordinate to the texture coordinates.
// It also clips the source and target coordinates if it is beyond the
// bound of the texture.
private static void convertCoordinate(RectF source, RectF target,
BasicTexture texture) {
int width = texture.getWidth();
int height = texture.getHeight();
int texWidth = texture.getTextureWidth();
int texHeight = texture.getTextureHeight();
// Convert to texture coordinates
source.left /= texWidth;
source.right /= texWidth;
source.top /= texHeight;
source.bottom /= texHeight;
// Clip if the rendering range is beyond the bound of the texture.
float xBound = (float) width / texWidth;
if (source.right > xBound) {
target.right = target.left + target.width() *
(xBound - source.left) / source.width();
source.right = xBound;
}
float yBound = (float) height / texHeight;
if (source.bottom > yBound) {
target.bottom = target.top + target.height() *
(yBound - source.top) / source.height();
source.bottom = yBound;
}
}
@Override
public void drawMixed(BasicTexture from,
int toColor, float ratio, int x, int y, int w, int h) {
drawMixed(from, toColor, ratio, x, y, w, h, mAlpha);
}
private boolean bindTexture(BasicTexture texture) {
if (!texture.onBind(this)) return false;
int target = texture.getTarget();
mGLState.setTextureTarget(target);
mGL.glBindTexture(target, texture.getId());
return true;
}
private void setTextureColor(float r, float g, float b, float alpha) {
float[] color = mTextureColor;
color[0] = r;
color[1] = g;
color[2] = b;
color[3] = alpha;
}
private void setMixedColor(int toColor, float ratio, float alpha) {
//
// The formula we want:
// alpha * ((1 - ratio) * from + ratio * to)
//
// The formula that GL supports is in the form of:
// combo * from + (1 - combo) * to * scale
//
// So, we have combo = alpha * (1 - ratio)
// and scale = alpha * ratio / (1 - combo)
//
float combo = alpha * (1 - ratio);
float scale = alpha * ratio / (1 - combo);
// Specify the interpolation factor via the alpha component of
// GL_TEXTURE_ENV_COLORs.
// RGB component are get from toColor and will used as SRC1
float colorScale = scale * (toColor >>> 24) / (0xff * 0xff);
setTextureColor(((toColor >>> 16) & 0xff) * colorScale,
((toColor >>> 8) & 0xff) * colorScale,
(toColor & 0xff) * colorScale, combo);
GL11 gl = mGL;
gl.glTexEnvfv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR, mTextureColor, 0);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB, GL11.GL_INTERPOLATE);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_COMBINE_ALPHA, GL11.GL_INTERPOLATE);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_CONSTANT);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_OPERAND1_RGB, GL11.GL_SRC_COLOR);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_ALPHA, GL11.GL_CONSTANT);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_OPERAND1_ALPHA, GL11.GL_SRC_ALPHA);
// Wire up the interpolation factor for RGB.
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_SRC2_RGB, GL11.GL_CONSTANT);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_OPERAND2_RGB, GL11.GL_SRC_ALPHA);
// Wire up the interpolation factor for alpha.
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_SRC2_ALPHA, GL11.GL_CONSTANT);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_OPERAND2_ALPHA, GL11.GL_SRC_ALPHA);
}
@Override
public void drawMixed(BasicTexture from, int toColor, float ratio,
RectF source, RectF target) {
if (target.width() <= 0 || target.height() <= 0) return;
if (ratio <= 0.01f) {
drawTexture(from, source, target);
return;
} else if (ratio >= 1) {
fillRect(target.left, target.top, target.width(), target.height(), toColor);
return;
}
float alpha = mAlpha;
// Copy the input to avoid changing it.
mDrawTextureSourceRect.set(source);
mDrawTextureTargetRect.set(target);
source = mDrawTextureSourceRect;
target = mDrawTextureTargetRect;
mGLState.setBlendEnabled(mBlendEnabled && (!from.isOpaque()
|| !Utils.isOpaque(toColor) || alpha < OPAQUE_ALPHA));
if (!bindTexture(from)) return;
// Interpolate the RGB and alpha values between both textures.
mGLState.setTexEnvMode(GL11.GL_COMBINE);
setMixedColor(toColor, ratio, alpha);
convertCoordinate(source, target, from);
setTextureCoords(source);
textureRect(target.left, target.top, target.width(), target.height());
mGLState.setTexEnvMode(GL11.GL_REPLACE);
}
private void drawMixed(BasicTexture from, int toColor,
float ratio, int x, int y, int width, int height, float alpha) {
// change from 0 to 0.01f to prevent getting divided by zero below
if (ratio <= 0.01f) {
drawTexture(from, x, y, width, height, alpha);
return;
} else if (ratio >= 1) {
fillRect(x, y, width, height, toColor);
return;
}
mGLState.setBlendEnabled(mBlendEnabled && (!from.isOpaque()
|| !Utils.isOpaque(toColor) || alpha < OPAQUE_ALPHA));
final GL11 gl = mGL;
if (!bindTexture(from)) return;
// Interpolate the RGB and alpha values between both textures.
mGLState.setTexEnvMode(GL11.GL_COMBINE);
setMixedColor(toColor, ratio, alpha);
drawBoundTexture(from, x, y, width, height);
mGLState.setTexEnvMode(GL11.GL_REPLACE);
}
// TODO: the code only work for 2D should get fixed for 3D or removed
private static final int MSKEW_X = 4;
private static final int MSKEW_Y = 1;
private static final int MSCALE_X = 0;
private static final int MSCALE_Y = 5;
private static boolean isMatrixRotatedOrFlipped(float matrix[]) {
final float eps = 1e-5f;
return Math.abs(matrix[MSKEW_X]) > eps
|| Math.abs(matrix[MSKEW_Y]) > eps
|| matrix[MSCALE_X] < -eps
|| matrix[MSCALE_Y] > eps;
}
private static class GLState {
private final GL11 mGL;
private int mTexEnvMode = GL11.GL_REPLACE;
private float mTextureAlpha = 1.0f;
private int mTextureTarget = GL11.GL_TEXTURE_2D;
private boolean mBlendEnabled = true;
private float mLineWidth = 1.0f;
private boolean mLineSmooth = false;
public GLState(GL11 gl) {
mGL = gl;
// Disable unused state
gl.glDisable(GL11.GL_LIGHTING);
// Enable used features
gl.glEnable(GL11.GL_DITHER);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL11.GL_TEXTURE_2D);
gl.glTexEnvf(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, GL11.GL_REPLACE);
// Set the background color
gl.glClearColor(0f, 0f, 0f, 0f);
gl.glEnable(GL11.GL_BLEND);
gl.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
// We use 565 or 8888 format, so set the alignment to 2 bytes/pixel.
gl.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 2);
}
public void setTexEnvMode(int mode) {
if (mTexEnvMode == mode) return;
mTexEnvMode = mode;
mGL.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, mode);
}
public void setLineWidth(float width) {
if (mLineWidth == width) return;
mLineWidth = width;
mGL.glLineWidth(width);
}
public void setTextureAlpha(float alpha) {
if (mTextureAlpha == alpha) return;
mTextureAlpha = alpha;
if (alpha >= OPAQUE_ALPHA) {
// The alpha is need for those texture without alpha channel
mGL.glColor4f(1, 1, 1, 1);
setTexEnvMode(GL11.GL_REPLACE);
} else {
mGL.glColor4f(alpha, alpha, alpha, alpha);
setTexEnvMode(GL11.GL_MODULATE);
}
}
public void setColorMode(int color, float alpha) {
setBlendEnabled(!Utils.isOpaque(color) || alpha < OPAQUE_ALPHA);
// Set mTextureAlpha to an invalid value, so that it will reset
// again in setTextureAlpha(float) later.
mTextureAlpha = -1.0f;
setTextureTarget(0);
float prealpha = (color >>> 24) * alpha * 65535f / 255f / 255f;
mGL.glColor4x(
Math.round(((color >> 16) & 0xFF) * prealpha),
Math.round(((color >> 8) & 0xFF) * prealpha),
Math.round((color & 0xFF) * prealpha),
Math.round(255 * prealpha));
}
// target is a value like GL_TEXTURE_2D. If target = 0, texturing is disabled.
public void setTextureTarget(int target) {
if (mTextureTarget == target) return;
if (mTextureTarget != 0) {
mGL.glDisable(mTextureTarget);
}
mTextureTarget = target;
if (mTextureTarget != 0) {
mGL.glEnable(mTextureTarget);
}
}
public void setBlendEnabled(boolean enabled) {
if (mBlendEnabled == enabled) return;
mBlendEnabled = enabled;
if (enabled) {
mGL.glEnable(GL11.GL_BLEND);
} else {
mGL.glDisable(GL11.GL_BLEND);
}
}
}
@Override
public void clearBuffer(float[] argb) {
if(argb != null && argb.length == 4) {
mGL.glClearColor(argb[1], argb[2], argb[3], argb[0]);
} else {
mGL.glClearColor(0, 0, 0, 1);
}
mGL.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
@Override
public void clearBuffer() {
clearBuffer(null);
}
private void setTextureCoords(RectF source) {
setTextureCoords(source.left, source.top, source.right, source.bottom);
}
private void setTextureCoords(float left, float top,
float right, float bottom) {
mGL.glMatrixMode(GL11.GL_TEXTURE);
mTextureMatrixValues[0] = right - left;
mTextureMatrixValues[5] = bottom - top;
mTextureMatrixValues[10] = 1;
mTextureMatrixValues[12] = left;
mTextureMatrixValues[13] = top;
mTextureMatrixValues[15] = 1;
mGL.glLoadMatrixf(mTextureMatrixValues, 0);
mGL.glMatrixMode(GL11.GL_MODELVIEW);
}
private void setTextureCoords(float[] mTextureTransform) {
mGL.glMatrixMode(GL11.GL_TEXTURE);
mGL.glLoadMatrixf(mTextureTransform, 0);
mGL.glMatrixMode(GL11.GL_MODELVIEW);
}
// unloadTexture and deleteBuffer can be called from the finalizer thread,
// so we synchronized on the mUnboundTextures object.
@Override
public boolean unloadTexture(BasicTexture t) {
synchronized (mUnboundTextures) {
if (!t.isLoaded()) return false;
mUnboundTextures.add(t.mId);
return true;
}
}
@Override
public void deleteBuffer(int bufferId) {
synchronized (mUnboundTextures) {
mDeleteBuffers.add(bufferId);
}
}
@Override
public void deleteRecycledResources() {
synchronized (mUnboundTextures) {
IntArray ids = mUnboundTextures;
if (ids.size() > 0) {
mGLId.glDeleteTextures(mGL, ids.size(), ids.getInternalArray(), 0);
ids.clear();
}
ids = mDeleteBuffers;
if (ids.size() > 0) {
mGLId.glDeleteBuffers(mGL, ids.size(), ids.getInternalArray(), 0);
ids.clear();
}
}
}
@Override
public void save() {
save(SAVE_FLAG_ALL);
}
@Override
public void save(int saveFlags) {
ConfigState config = obtainRestoreConfig();
if ((saveFlags & SAVE_FLAG_ALPHA) != 0) {
config.mAlpha = mAlpha;
} else {
config.mAlpha = -1;
}
if ((saveFlags & SAVE_FLAG_MATRIX) != 0) {
System.arraycopy(mMatrixValues, 0, config.mMatrix, 0, 16);
} else {
config.mMatrix[0] = Float.NEGATIVE_INFINITY;
}
mRestoreStack.add(config);
}
@Override
public void restore() {
if (mRestoreStack.isEmpty()) throw new IllegalStateException();
ConfigState config = mRestoreStack.remove(mRestoreStack.size() - 1);
config.restore(this);
freeRestoreConfig(config);
}
private void freeRestoreConfig(ConfigState action) {
action.mNextFree = mRecycledRestoreAction;
mRecycledRestoreAction = action;
}
private ConfigState obtainRestoreConfig() {
if (mRecycledRestoreAction != null) {
ConfigState result = mRecycledRestoreAction;
mRecycledRestoreAction = result.mNextFree;
return result;
}
return new ConfigState();
}
private static class ConfigState {
float mAlpha;
float mMatrix[] = new float[16];
ConfigState mNextFree;
public void restore(GLES11Canvas canvas) {
if (mAlpha >= 0) canvas.setAlpha(mAlpha);
if (mMatrix[0] != Float.NEGATIVE_INFINITY) {
System.arraycopy(mMatrix, 0, canvas.mMatrixValues, 0, 16);
}
}
}
@Override
public void dumpStatisticsAndClear() {
String line = String.format(
"MESH:%d, TEX_OES:%d, TEX_RECT:%d, FILL_RECT:%d, LINE:%d",
mCountDrawMesh, mCountTextureRect, mCountTextureOES,
mCountFillRect, mCountDrawLine);
mCountDrawMesh = 0;
mCountTextureRect = 0;
mCountTextureOES = 0;
mCountFillRect = 0;
mCountDrawLine = 0;
Log.d(TAG, line);
}
private void saveTransform() {
System.arraycopy(mMatrixValues, 0, mTempMatrix, 0, 16);
}
private void restoreTransform() {
System.arraycopy(mTempMatrix, 0, mMatrixValues, 0, 16);
}
private void setRenderTarget(RawTexture texture) {
GL11ExtensionPack gl11ep = (GL11ExtensionPack) mGL;
if (mTargetTexture == null && texture != null) {
mGLId.glGenBuffers(1, mFrameBuffer, 0);
gl11ep.glBindFramebufferOES(
GL11ExtensionPack.GL_FRAMEBUFFER_OES, mFrameBuffer[0]);
}
if (mTargetTexture != null && texture == null) {
gl11ep.glBindFramebufferOES(GL11ExtensionPack.GL_FRAMEBUFFER_OES, 0);
gl11ep.glDeleteFramebuffersOES(1, mFrameBuffer, 0);
}
mTargetTexture = texture;
if (texture == null) {
setSize(mScreenWidth, mScreenHeight);
} else {
setSize(texture.getWidth(), texture.getHeight());
if (!texture.isLoaded()) texture.prepare(this);
gl11ep.glFramebufferTexture2DOES(
GL11ExtensionPack.GL_FRAMEBUFFER_OES,
GL11ExtensionPack.GL_COLOR_ATTACHMENT0_OES,
GL11.GL_TEXTURE_2D, texture.getId(), 0);
checkFramebufferStatus(gl11ep);
}
}
@Override
public void endRenderTarget() {
RawTexture texture = mTargetStack.remove(mTargetStack.size() - 1);
setRenderTarget(texture);
restore(); // restore matrix and alpha
}
@Override
public void beginRenderTarget(RawTexture texture) {
save(); // save matrix and alpha
mTargetStack.add(mTargetTexture);
setRenderTarget(texture);
}
private static void checkFramebufferStatus(GL11ExtensionPack gl11ep) {
int status = gl11ep.glCheckFramebufferStatusOES(GL11ExtensionPack.GL_FRAMEBUFFER_OES);
if (status != GL11ExtensionPack.GL_FRAMEBUFFER_COMPLETE_OES) {
String msg = "";
switch (status) {
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES:
msg = "FRAMEBUFFER_FORMATS";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES:
msg = "FRAMEBUFFER_ATTACHMENT";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES:
msg = "FRAMEBUFFER_MISSING_ATTACHMENT";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_OES:
msg = "FRAMEBUFFER_DRAW_BUFFER";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_OES:
msg = "FRAMEBUFFER_READ_BUFFER";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_UNSUPPORTED_OES:
msg = "FRAMEBUFFER_UNSUPPORTED";
break;
case GL11ExtensionPack.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES:
msg = "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
break;
}
throw new RuntimeException(msg + ":" + Integer.toHexString(status));
}
}
@Override
public void setTextureParameters(BasicTexture texture) {
int width = texture.getWidth();
int height = texture.getHeight();
// Define a vertically flipped crop rectangle for OES_draw_texture.
// The four values in sCropRect are: left, bottom, width, and
// height. Negative value of width or height means flip.
sCropRect[0] = 0;
sCropRect[1] = height;
sCropRect[2] = width;
sCropRect[3] = -height;
// Set texture parameters.
int target = texture.getTarget();
mGL.glBindTexture(target, texture.getId());
mGL.glTexParameterfv(target, GL11Ext.GL_TEXTURE_CROP_RECT_OES, sCropRect, 0);
mGL.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP_TO_EDGE);
mGL.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP_TO_EDGE);
mGL.glTexParameterf(target, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
mGL.glTexParameterf(target, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
}
@Override
public void initializeTextureSize(BasicTexture texture, int format, int type) {
int target = texture.getTarget();
mGL.glBindTexture(target, texture.getId());
int width = texture.getTextureWidth();
int height = texture.getTextureHeight();
mGL.glTexImage2D(target, 0, format, width, height, 0, format, type, null);
}
@Override
public void initializeTexture(BasicTexture texture, Bitmap bitmap) {
int target = texture.getTarget();
mGL.glBindTexture(target, texture.getId());
GLUtils.texImage2D(target, 0, bitmap, 0);
}
@Override
public void texSubImage2D(BasicTexture texture, int xOffset, int yOffset, Bitmap bitmap,
int format, int type) {
int target = texture.getTarget();
mGL.glBindTexture(target, texture.getId());
GLUtils.texSubImage2D(target, 0, xOffset, yOffset, bitmap, format, type);
}
@Override
public int uploadBuffer(FloatBuffer buf) {
return uploadBuffer(buf, Float.SIZE / Byte.SIZE);
}
@Override
public int uploadBuffer(ByteBuffer buf) {
return uploadBuffer(buf, 1);
}
private int uploadBuffer(Buffer buf, int elementSize) {
int[] bufferIds = new int[1];
mGLId.glGenBuffers(bufferIds.length, bufferIds, 0);
int bufferId = bufferIds[0];
mGL.glBindBuffer(GL11.GL_ARRAY_BUFFER, bufferId);
mGL.glBufferData(GL11.GL_ARRAY_BUFFER, buf.capacity() * elementSize, buf,
GL11.GL_STATIC_DRAW);
return bufferId;
}
@Override
public void recoverFromLightCycle() {
// This is only required for GLES20
}
@Override
public void getBounds(Rect bounds, int x, int y, int width, int height) {
// This is only required for GLES20
}
@Override
public GLId getGLId() {
return mGLId;
}
}
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
/**
* Open GL ES 1.1 implementation for generating and destroying texture IDs and
* buffer IDs
*/
public class GLES11IdImpl implements GLId {
private static int sNextId = 1;
// Mutex for sNextId
private static Object sLock = new Object();
@Override
public int generateTexture() {
synchronized (sLock) {
return sNextId++;
}
}
@Override
public void glGenBuffers(int n, int[] buffers, int offset) {
synchronized (sLock) {
while (n-- > 0) {
buffers[offset + n] = sNextId++;
}
}
}
@Override
public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset) {
synchronized (sLock) {
gl.glDeleteTextures(n, textures, offset);
}
}
@Override
public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset) {
synchronized (sLock) {
gl.glDeleteBuffers(n, buffers, offset);
}
}
@Override
public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset) {
synchronized (sLock) {
gl11ep.glDeleteFramebuffersOES(n, buffers, offset);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,42 @@
package com.hippo.ehviewer.gallery.glrenderer;
import android.opengl.GLES20;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
public class GLES20IdImpl implements GLId {
private final int[] mTempIntArray = new int[1];
@Override
public int generateTexture() {
GLES20.glGenTextures(1, mTempIntArray, 0);
GLES20Canvas.checkError();
return mTempIntArray[0];
}
@Override
public void glGenBuffers(int n, int[] buffers, int offset) {
GLES20.glGenBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset) {
GLES20.glDeleteTextures(n, textures, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset) {
GLES20.glDeleteBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset) {
GLES20.glDeleteFramebuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
}
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
// This mimics corresponding GL functions.
public interface GLId {
public int generateTexture();
public void glGenBuffers(int n, int[] buffers, int offset);
public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset);
public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset);
public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset);
}
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import junit.framework.Assert;
public class GLPaint {
private float mLineWidth = 1f;
private int mColor = 0;
public GLPaint() {}
public GLPaint(int color, float width) {
setColor(color);
setLineWidth(width);
}
public void setColor(int color) {
mColor = color;
}
public int getColor() {
return mColor;
}
public void setLineWidth(float width) {
Assert.assertTrue(width >= 0);
mLineWidth = width;
}
public float getLineWidth() {
return mLineWidth;
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
// MultiLineTexture is a texture shows the content of a specified String.
//
// To create a MultiLineTexture, use the newInstance() method and specify
// the String, the font size, and the color.
class MultiLineTexture extends CanvasTexture {
private final Layout mLayout;
private MultiLineTexture(Layout layout) {
super(layout.getWidth(), layout.getHeight());
mLayout = layout;
}
public static MultiLineTexture newInstance(
String text, int maxWidth, float textSize, int color,
Layout.Alignment alignment) {
TextPaint paint = StringTexture.getDefaultPaint(textSize, color);
Layout layout = new StaticLayout(text, 0, text.length(), paint,
maxWidth, alignment, 1, 0, true, null, 0);
return new MultiLineTexture(layout);
}
@Override
protected void onDraw(Canvas canvas, Bitmap backing) {
mLayout.draw(canvas);
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Rect;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
// See "frameworks/base/include/utils/ResourceTypes.h" for the format of
// NinePatch chunk.
class NinePatchChunk {
public static final int NO_COLOR = 0x00000001;
public static final int TRANSPARENT_COLOR = 0x00000000;
public Rect mPaddings = new Rect();
public int mDivX[];
public int mDivY[];
public int mColor[];
private static void readIntArray(int[] data, ByteBuffer buffer) {
for (int i = 0, n = data.length; i < n; ++i) {
data[i] = buffer.getInt();
}
}
private static void checkDivCount(int length) {
if (length == 0 || (length & 0x01) != 0) {
throw new RuntimeException("invalid nine-patch: " + length);
}
}
public static NinePatchChunk deserialize(byte[] data) {
ByteBuffer byteBuffer =
ByteBuffer.wrap(data).order(ByteOrder.nativeOrder());
byte wasSerialized = byteBuffer.get();
if (wasSerialized == 0) return null;
NinePatchChunk chunk = new NinePatchChunk();
chunk.mDivX = new int[byteBuffer.get()];
chunk.mDivY = new int[byteBuffer.get()];
chunk.mColor = new int[byteBuffer.get()];
checkDivCount(chunk.mDivX.length);
checkDivCount(chunk.mDivY.length);
// skip 8 bytes
byteBuffer.getInt();
byteBuffer.getInt();
chunk.mPaddings.left = byteBuffer.getInt();
chunk.mPaddings.right = byteBuffer.getInt();
chunk.mPaddings.top = byteBuffer.getInt();
chunk.mPaddings.bottom = byteBuffer.getInt();
// skip 4 bytes
byteBuffer.getInt();
readIntArray(chunk.mDivX, byteBuffer);
readIntArray(chunk.mDivY, byteBuffer);
readIntArray(chunk.mColor, byteBuffer);
return chunk;
}
}
@@ -0,0 +1,424 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import com.hippo.ehviewer.gallery.common.Utils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
// NinePatchTexture is a texture backed by a NinePatch resource.
//
// getPaddings() returns paddings specified in the NinePatch.
// getNinePatchChunk() returns the layout data specified in the NinePatch.
//
public class NinePatchTexture extends ResourceTexture {
@SuppressWarnings("unused")
private static final String TAG = "NinePatchTexture";
private NinePatchChunk mChunk;
private SmallCache<NinePatchInstance> mInstanceCache
= new SmallCache<NinePatchInstance>();
public NinePatchTexture(Context context, int resId) {
super(context, resId);
}
@Override
protected Bitmap onGetBitmap() {
if (mBitmap != null) return mBitmap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
mBitmap = bitmap;
setSize(bitmap.getWidth(), bitmap.getHeight());
byte[] chunkData = bitmap.getNinePatchChunk();
mChunk = chunkData == null
? null
: NinePatchChunk.deserialize(bitmap.getNinePatchChunk());
if (mChunk == null) {
throw new RuntimeException("invalid nine-patch image: " + mResId);
}
return bitmap;
}
public Rect getPaddings() {
// get the paddings from nine patch
if (mChunk == null) onGetBitmap();
return mChunk.mPaddings;
}
public NinePatchChunk getNinePatchChunk() {
if (mChunk == null) onGetBitmap();
return mChunk;
}
// This is a simple cache for a small number of things. Linear search
// is used because the cache is small. It also tries to remove less used
// item when the cache is full by moving the often-used items to the front.
private static class SmallCache<V> {
private static final int CACHE_SIZE = 16;
private static final int CACHE_SIZE_START_MOVE = CACHE_SIZE / 2;
private int[] mKey = new int[CACHE_SIZE];
private V[] mValue = (V[]) new Object[CACHE_SIZE];
private int mCount; // number of items in this cache
// Puts a value into the cache. If the cache is full, also returns
// a less used item, otherwise returns null.
public V put(int key, V value) {
if (mCount == CACHE_SIZE) {
V old = mValue[CACHE_SIZE - 1]; // remove the last item
mKey[CACHE_SIZE - 1] = key;
mValue[CACHE_SIZE - 1] = value;
return old;
} else {
mKey[mCount] = key;
mValue[mCount] = value;
mCount++;
return null;
}
}
public V get(int key) {
for (int i = 0; i < mCount; i++) {
if (mKey[i] == key) {
// Move the accessed item one position to the front, so it
// will less likely to be removed when cache is full. Only
// do this if the cache is starting to get full.
if (mCount > CACHE_SIZE_START_MOVE && i > 0) {
int tmpKey = mKey[i];
mKey[i] = mKey[i - 1];
mKey[i - 1] = tmpKey;
V tmpValue = mValue[i];
mValue[i] = mValue[i - 1];
mValue[i - 1] = tmpValue;
}
return mValue[i];
}
}
return null;
}
public void clear() {
for (int i = 0; i < mCount; i++) {
mValue[i] = null; // make sure it's can be garbage-collected.
}
mCount = 0;
}
public int size() {
return mCount;
}
public V valueAt(int i) {
return mValue[i];
}
}
private NinePatchInstance findInstance(GLCanvas canvas, int w, int h) {
int key = w;
key = (key << 16) | h;
NinePatchInstance instance = mInstanceCache.get(key);
if (instance == null) {
instance = new NinePatchInstance(this, w, h);
NinePatchInstance removed = mInstanceCache.put(key, instance);
if (removed != null) {
removed.recycle(canvas);
}
}
return instance;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (!isLoaded()) {
mInstanceCache.clear();
}
if (w != 0 && h != 0) {
findInstance(canvas, w, h).draw(canvas, this, x, y);
}
}
@Override
public void recycle() {
super.recycle();
GLCanvas canvas = mCanvasRef;
if (canvas == null) return;
int n = mInstanceCache.size();
for (int i = 0; i < n; i++) {
NinePatchInstance instance = mInstanceCache.valueAt(i);
instance.recycle(canvas);
}
mInstanceCache.clear();
}
}
// This keeps data for a specialization of NinePatchTexture with the size
// (width, height). We pre-compute the coordinates for efficiency.
class NinePatchInstance {
@SuppressWarnings("unused")
private static final String TAG = "NinePatchInstance";
// We need 16 vertices for a normal nine-patch image (the 4x4 vertices)
private static final int VERTEX_BUFFER_SIZE = 16 * 2;
// We need 22 indices for a normal nine-patch image, plus 2 for each
// transparent region. Current there are at most 1 transparent region.
private static final int INDEX_BUFFER_SIZE = 22 + 2;
private FloatBuffer mXyBuffer;
private FloatBuffer mUvBuffer;
private ByteBuffer mIndexBuffer;
// Names for buffer names: xy, uv, index.
private int mXyBufferName = -1;
private int mUvBufferName;
private int mIndexBufferName;
private int mIdxCount;
public NinePatchInstance(NinePatchTexture tex, int width, int height) {
NinePatchChunk chunk = tex.getNinePatchChunk();
if (width <= 0 || height <= 0) {
throw new RuntimeException("invalid dimension");
}
// The code should be easily extended to handle the general cases by
// allocating more space for buffers. But let's just handle the only
// use case.
if (chunk.mDivX.length != 2 || chunk.mDivY.length != 2) {
throw new RuntimeException("unsupported nine patch");
}
float divX[] = new float[4];
float divY[] = new float[4];
float divU[] = new float[4];
float divV[] = new float[4];
int nx = stretch(divX, divU, chunk.mDivX, tex.getWidth(), width);
int ny = stretch(divY, divV, chunk.mDivY, tex.getHeight(), height);
prepareVertexData(divX, divY, divU, divV, nx, ny, chunk.mColor);
}
/**
* Stretches the texture according to the nine-patch rules. It will
* linearly distribute the strechy parts defined in the nine-patch chunk to
* the target area.
*
* <pre>
* source
* /--------------^---------------\
* u0 u1 u2 u3 u4 u5
* div ---> |fffff|ssssssss|fff|ssssss|ffff| ---> u
* | div0 div1 div2 div3 |
* | | / / / /
* | | / / / /
* | | / / / /
* |fffff|ssss|fff|sss|ffff| ---> x
* x0 x1 x2 x3 x4 x5
* \----------v------------/
* target
*
* f: fixed segment
* s: stretchy segment
* </pre>
*
* @param div the stretch parts defined in nine-patch chunk
* @param source the length of the texture
* @param target the length on the drawing plan
* @param u output, the positions of these dividers in the texture
* coordinate
* @param x output, the corresponding position of these dividers on the
* drawing plan
* @return the number of these dividers.
*/
private static int stretch(
float x[], float u[], int div[], int source, int target) {
int textureSize = Utils.nextPowerOf2(source);
float textureBound = (float) source / textureSize;
float stretch = 0;
for (int i = 0, n = div.length; i < n; i += 2) {
stretch += div[i + 1] - div[i];
}
float remaining = target - source + stretch;
float lastX = 0;
float lastU = 0;
x[0] = 0;
u[0] = 0;
for (int i = 0, n = div.length; i < n; i += 2) {
// Make the stretchy segment a little smaller to prevent sampling
// on neighboring fixed segments.
// fixed segment
x[i + 1] = lastX + (div[i] - lastU) + 0.5f;
u[i + 1] = Math.min((div[i] + 0.5f) / textureSize, textureBound);
// stretchy segment
float partU = div[i + 1] - div[i];
float partX = remaining * partU / stretch;
remaining -= partX;
stretch -= partU;
lastX = x[i + 1] + partX;
lastU = div[i + 1];
x[i + 2] = lastX - 0.5f;
u[i + 2] = Math.min((lastU - 0.5f)/ textureSize, textureBound);
}
// the last fixed segment
x[div.length + 1] = target;
u[div.length + 1] = textureBound;
// remove segments with length 0.
int last = 0;
for (int i = 1, n = div.length + 2; i < n; ++i) {
if ((x[i] - x[last]) < 1f) continue;
x[++last] = x[i];
u[last] = u[i];
}
return last + 1;
}
private void prepareVertexData(float x[], float y[], float u[], float v[],
int nx, int ny, int[] color) {
/*
* Given a 3x3 nine-patch image, the vertex order is defined as the
* following graph:
*
* (0) (1) (2) (3)
* | /| /| /|
* | / | / | / |
* (4) (5) (6) (7)
* | \ | \ | \ |
* | \| \| \|
* (8) (9) (A) (B)
* | /| /| /|
* | / | / | / |
* (C) (D) (E) (F)
*
* And we draw the triangle strip in the following index order:
*
* index: 04152637B6A5948C9DAEBF
*/
int pntCount = 0;
float xy[] = new float[VERTEX_BUFFER_SIZE];
float uv[] = new float[VERTEX_BUFFER_SIZE];
for (int j = 0; j < ny; ++j) {
for (int i = 0; i < nx; ++i) {
int xIndex = (pntCount++) << 1;
int yIndex = xIndex + 1;
xy[xIndex] = x[i];
xy[yIndex] = y[j];
uv[xIndex] = u[i];
uv[yIndex] = v[j];
}
}
int idxCount = 1;
boolean isForward = false;
byte index[] = new byte[INDEX_BUFFER_SIZE];
for (int row = 0; row < ny - 1; row++) {
--idxCount;
isForward = !isForward;
int start, end, inc;
if (isForward) {
start = 0;
end = nx;
inc = 1;
} else {
start = nx - 1;
end = -1;
inc = -1;
}
for (int col = start; col != end; col += inc) {
int k = row * nx + col;
if (col != start) {
int colorIdx = row * (nx - 1) + col;
if (isForward) colorIdx--;
if (color[colorIdx] == NinePatchChunk.TRANSPARENT_COLOR) {
index[idxCount] = index[idxCount - 1];
++idxCount;
index[idxCount++] = (byte) k;
}
}
index[idxCount++] = (byte) k;
index[idxCount++] = (byte) (k + nx);
}
}
mIdxCount = idxCount;
int size = (pntCount * 2) * (Float.SIZE / Byte.SIZE);
mXyBuffer = allocateDirectNativeOrderBuffer(size).asFloatBuffer();
mUvBuffer = allocateDirectNativeOrderBuffer(size).asFloatBuffer();
mIndexBuffer = allocateDirectNativeOrderBuffer(mIdxCount);
mXyBuffer.put(xy, 0, pntCount * 2).position(0);
mUvBuffer.put(uv, 0, pntCount * 2).position(0);
mIndexBuffer.put(index, 0, idxCount).position(0);
}
private static ByteBuffer allocateDirectNativeOrderBuffer(int size) {
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
private void prepareBuffers(GLCanvas canvas) {
mXyBufferName = canvas.uploadBuffer(mXyBuffer);
mUvBufferName = canvas.uploadBuffer(mUvBuffer);
mIndexBufferName = canvas.uploadBuffer(mIndexBuffer);
// These buffers are never used again.
mXyBuffer = null;
mUvBuffer = null;
mIndexBuffer = null;
}
public void draw(GLCanvas canvas, NinePatchTexture tex, int x, int y) {
if (mXyBufferName == -1) {
prepareBuffers(canvas);
}
canvas.drawMesh(tex, x, y, mXyBufferName, mUvBufferName, mIndexBufferName, mIdxCount);
}
public void recycle(GLCanvas canvas) {
if (mXyBuffer == null) {
canvas.deleteBuffer(mXyBufferName);
canvas.deleteBuffer(mUvBufferName);
canvas.deleteBuffer(mIndexBufferName);
mXyBufferName = -1;
}
}
}
@@ -0,0 +1,73 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.util.Log;
import javax.microedition.khronos.opengles.GL11;
public class RawTexture extends BasicTexture {
private static final String TAG = "RawTexture";
private final boolean mOpaque;
private boolean mIsFlipped;
public RawTexture(int width, int height, boolean opaque) {
mOpaque = opaque;
setSize(width, height);
}
@Override
public boolean isOpaque() {
return mOpaque;
}
@Override
public boolean isFlippedVertically() {
return mIsFlipped;
}
public void setIsFlippedVertically(boolean isFlipped) {
mIsFlipped = isFlipped;
}
protected void prepare(GLCanvas canvas) {
GLId glId = canvas.getGLId();
mId = glId.generateTexture();
canvas.initializeTextureSize(this, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE);
canvas.setTextureParameters(this);
mState = STATE_LOADED;
setAssociatedCanvas(canvas);
}
@Override
protected boolean onBind(GLCanvas canvas) {
if (isLoaded()) return true;
Log.w(TAG, "lost the content due to context change");
return false;
}
@Override
public void yield() {
// we cannot free the texture because we have no backup.
}
@Override
protected int getTarget() {
return GL11.GL_TEXTURE_2D;
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import junit.framework.Assert;
// ResourceTexture is a texture whose Bitmap is decoded from a resource.
// By default ResourceTexture is not opaque.
public class ResourceTexture extends UploadedTexture {
protected final Context mContext;
protected final int mResId;
public ResourceTexture(Context context, int resId) {
Assert.assertNotNull(context);
mContext = context;
mResId = resId;
setOpaque(false);
}
@Override
protected Bitmap onGetBitmap() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
if (!inFinalizer()) {
bitmap.recycle();
}
}
}
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.FloatMath;
// StringTexture is a texture shows the content of a specified String.
//
// To create a StringTexture, use the newInstance() method and specify
// the String, the font size, and the color.
public class StringTexture extends CanvasTexture {
private final String mText;
private final TextPaint mPaint;
private final FontMetricsInt mMetrics;
private StringTexture(String text, TextPaint paint,
FontMetricsInt metrics, int width, int height) {
super(width, height);
mText = text;
mPaint = paint;
mMetrics = metrics;
}
public static TextPaint getDefaultPaint(float textSize, int color) {
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);
paint.setAntiAlias(true);
paint.setColor(color);
paint.setShadowLayer(2f, 0f, 0f, Color.BLACK);
return paint;
}
public static StringTexture newInstance(
String text, float textSize, int color) {
return newInstance(text, getDefaultPaint(textSize, color));
}
public static StringTexture newInstance(
String text, float textSize, int color,
float lengthLimit, boolean isBold) {
TextPaint paint = getDefaultPaint(textSize, color);
if (isBold) {
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}
if (lengthLimit > 0) {
text = TextUtils.ellipsize(
text, paint, lengthLimit, TextUtils.TruncateAt.END).toString();
}
return newInstance(text, paint);
}
private static StringTexture newInstance(String text, TextPaint paint) {
FontMetricsInt metrics = paint.getFontMetricsInt();
int width = (int) FloatMath.ceil(paint.measureText(text));
int height = metrics.bottom - metrics.top;
// The texture size needs to be at least 1x1.
if (width <= 0) width = 1;
if (height <= 0) height = 1;
return new StringTexture(text, paint, metrics, width, height);
}
@Override
protected void onDraw(Canvas canvas, Bitmap backing) {
canvas.translate(0, -mMetrics.ascent);
canvas.drawText(mText, 0, 0, mPaint);
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
// Texture is a rectangular image which can be drawn on GLCanvas.
// The isOpaque() function gives a hint about whether the texture is opaque,
// so the drawing can be done faster.
//
// This is the current texture hierarchy:
//
// Texture
// -- ColorTexture
// -- FadeInTexture
// -- BasicTexture
// -- UploadedTexture
// -- BitmapTexture
// -- Tile
// -- ResourceTexture
// -- NinePatchTexture
// -- CanvasTexture
// -- StringTexture
//
public interface Texture {
public int getWidth();
public int getHeight();
public void draw(GLCanvas canvas, int x, int y);
public void draw(GLCanvas canvas, int x, int y, int w, int h);
public boolean isOpaque();
}
@@ -0,0 +1,105 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import com.hippo.ehviewer.gallery.ui.GLRoot;
import com.hippo.ehviewer.gallery.ui.GLRoot.OnGLIdleListener;
import java.util.ArrayDeque;
public class TextureUploader implements OnGLIdleListener {
private static final int INIT_CAPACITY = 64;
private static final int QUOTA_PER_FRAME = 1;
private final ArrayDeque<UploadedTexture> mFgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
private final ArrayDeque<UploadedTexture> mBgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
private final GLRoot mGLRoot;
private volatile boolean mIsQueued = false;
public TextureUploader(GLRoot root) {
mGLRoot = root;
}
public synchronized void clear() {
while (!mFgTextures.isEmpty()) {
mFgTextures.pop().setIsUploading(false);
}
while (!mBgTextures.isEmpty()) {
mBgTextures.pop().setIsUploading(false);
}
}
// caller should hold synchronized on "this"
private void queueSelfIfNeed() {
if (mIsQueued) return;
mIsQueued = true;
mGLRoot.addOnGLIdleListener(this);
}
public synchronized void addBgTexture(UploadedTexture t) {
if (t.isContentValid()) return;
mBgTextures.addLast(t);
t.setIsUploading(true);
queueSelfIfNeed();
}
public synchronized void addFgTexture(UploadedTexture t) {
if (t.isContentValid()) return;
mFgTextures.addLast(t);
t.setIsUploading(true);
queueSelfIfNeed();
}
private int upload(GLCanvas canvas, ArrayDeque<UploadedTexture> deque,
int uploadQuota, boolean isBackground) {
while (uploadQuota > 0) {
UploadedTexture t;
synchronized (this) {
if (deque.isEmpty()) break;
t = deque.removeFirst();
t.setIsUploading(false);
if (t.isContentValid()) continue;
// this has to be protected by the synchronized block
// to prevent the inner bitmap get recycled
t.updateContent(canvas);
}
// It will took some more time for a texture to be drawn for
// the first time.
// Thus, when scrolling, if a new column appears on screen,
// it may cause a UI jank even these textures are uploaded.
if (isBackground) t.draw(canvas, 0, 0);
--uploadQuota;
}
return uploadQuota;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
int uploadQuota = QUOTA_PER_FRAME;
uploadQuota = upload(canvas, mFgTextures, uploadQuota, false);
if (uploadQuota < QUOTA_PER_FRAME) mGLRoot.requestRender();
upload(canvas, mBgTextures, uploadQuota, true);
synchronized (this) {
mIsQueued = !mFgTextures.isEmpty() || !mBgTextures.isEmpty();
return mIsQueued;
}
}
}
@@ -0,0 +1,349 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.SystemClock;
import com.hippo.ehviewer.gallery.ui.GLRoot;
import com.hippo.ehviewer.gallery.ui.GLRoot.OnGLIdleListener;
import java.util.ArrayDeque;
import java.util.ArrayList;
// This class is similar to BitmapTexture, except the bitmap is
// split into tiles. By doing so, we may increase the time required to
// upload the whole bitmap but we reduce the time of uploading each tile
// so it make the animation more smooth and prevents jank.
public class TiledTexture implements Texture {
private static final int CONTENT_SIZE = 254;
private static final int BORDER_SIZE = 1;
private static final int TILE_SIZE = CONTENT_SIZE + 2 * BORDER_SIZE;
private static final int INIT_CAPACITY = 8;
// We are targeting at 60fps, so we have 16ms for each frame.
// In this 16ms, we use about 4~8 ms to upload tiles.
private static final long UPLOAD_TILE_LIMIT = 4; // ms
private static Tile sFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private static Bitmap sUploadBitmap;
private static Canvas sCanvas;
private static Paint sBitmapPaint;
private static Paint sPaint;
private int mUploadIndex = 0;
private final Tile[] mTiles; // Can be modified in different threads.
// Should be protected by "synchronized."
private final int mWidth;
private final int mHeight;
private final RectF mSrcRect = new RectF();
private final RectF mDestRect = new RectF();
public static class Uploader implements OnGLIdleListener {
private final ArrayDeque<TiledTexture> mTextures =
new ArrayDeque<TiledTexture>(INIT_CAPACITY);
private final GLRoot mGlRoot;
private boolean mIsQueued = false;
public Uploader(GLRoot glRoot) {
mGlRoot = glRoot;
}
public synchronized void clear() {
mTextures.clear();
}
public synchronized void addTexture(TiledTexture t) {
if (t.isReady()) return;
mTextures.addLast(t);
if (mIsQueued) return;
mIsQueued = true;
mGlRoot.addOnGLIdleListener(this);
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
ArrayDeque<TiledTexture> deque = mTextures;
synchronized (this) {
long now = SystemClock.uptimeMillis();
long dueTime = now + UPLOAD_TILE_LIMIT;
while (now < dueTime && !deque.isEmpty()) {
TiledTexture t = deque.peekFirst();
if (t.uploadNextTile(canvas)) {
deque.removeFirst();
mGlRoot.requestRender();
}
now = SystemClock.uptimeMillis();
}
mIsQueued = !mTextures.isEmpty();
// return true to keep this listener in the queue
return mIsQueued;
}
}
}
private static class Tile extends UploadedTexture {
public int offsetX;
public int offsetY;
public Bitmap bitmap;
public Tile nextFreeTile;
public int contentWidth;
public int contentHeight;
@Override
public void setSize(int width, int height) {
contentWidth = width;
contentHeight = height;
mWidth = width + 2 * BORDER_SIZE;
mHeight = height + 2 * BORDER_SIZE;
mTextureWidth = TILE_SIZE;
mTextureHeight = TILE_SIZE;
}
@Override
protected Bitmap onGetBitmap() {
int x = BORDER_SIZE - offsetX;
int y = BORDER_SIZE - offsetY;
int r = bitmap.getWidth() + x;
int b = bitmap.getHeight() + y;
sCanvas.drawBitmap(bitmap, x, y, sBitmapPaint);
bitmap = null;
// draw borders if need
if (x > 0) sCanvas.drawLine(x - 1, 0, x - 1, TILE_SIZE, sPaint);
if (y > 0) sCanvas.drawLine(0, y - 1, TILE_SIZE, y - 1, sPaint);
if (r < CONTENT_SIZE) sCanvas.drawLine(r, 0, r, TILE_SIZE, sPaint);
if (b < CONTENT_SIZE) sCanvas.drawLine(0, b, TILE_SIZE, b, sPaint);
return sUploadBitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
// do nothing
}
}
private static void freeTile(Tile tile) {
tile.invalidateContent();
tile.bitmap = null;
synchronized (sFreeTileLock) {
tile.nextFreeTile = sFreeTileHead;
sFreeTileHead = tile;
}
}
private static Tile obtainTile() {
synchronized (sFreeTileLock) {
Tile result = sFreeTileHead;
if (result == null) return new Tile();
sFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
return result;
}
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
synchronized (mTiles) {
Tile next = mTiles[mUploadIndex++];
// Make sure tile has not already been recycled by the time
// this is called (race condition in onGLIdle)
if (next.bitmap != null) {
boolean hasBeenLoad = next.isLoaded();
next.updateContent(canvas);
// It will take some time for a texture to be drawn for the first
// time. When scrolling, we need to draw several tiles on the screen
// at the same time. It may cause a UI jank even these textures has
// been uploaded.
if (!hasBeenLoad) next.draw(canvas, 0, 0);
}
}
return mUploadIndex == mTiles.length;
}
public TiledTexture(Bitmap bitmap) {
mWidth = bitmap.getWidth();
mHeight = bitmap.getHeight();
ArrayList<Tile> list = new ArrayList<Tile>();
for (int x = 0, w = mWidth; x < w; x += CONTENT_SIZE) {
for (int y = 0, h = mHeight; y < h; y += CONTENT_SIZE) {
Tile tile = obtainTile();
tile.offsetX = x;
tile.offsetY = y;
tile.bitmap = bitmap;
tile.setSize(
Math.min(CONTENT_SIZE, mWidth - x),
Math.min(CONTENT_SIZE, mHeight - y));
list.add(tile);
}
}
mTiles = list.toArray(new Tile[list.size()]);
}
public boolean isReady() {
return mUploadIndex == mTiles.length;
}
// Can be called in UI thread.
public void recycle() {
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
freeTile(mTiles[i]);
}
}
}
public static void freeResources() {
sUploadBitmap = null;
sCanvas = null;
sBitmapPaint = null;
sPaint = null;
}
public static void prepareResources() {
sUploadBitmap = Bitmap.createBitmap(TILE_SIZE, TILE_SIZE, Config.ARGB_8888);
sCanvas = new Canvas(sUploadBitmap);
sBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
sBitmapPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
sPaint = new Paint();
sPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
sPaint.setColor(Color.TRANSPARENT);
}
// We want to draw the "source" on the "target".
// This method is to find the "output" rectangle which is
// the corresponding area of the "src".
// (x,y) target
// (x0,y0) source +---------------+
// +----------+ | |
// | src | | output |
// | +--+ | linear map | +----+ |
// | +--+ | ----------> | | | |
// | | by (scaleX, scaleY) | +----+ |
// +----------+ | |
// Texture +---------------+
// Canvas
private static void mapRect(RectF output,
RectF src, float x0, float y0, float x, float y, float scaleX,
float scaleY) {
output.set(x + (src.left - x0) * scaleX,
y + (src.top - y0) * scaleY,
x + (src.right - x0) * scaleX,
y + (src.bottom - y0) * scaleY);
}
// Draws a mixed color of this texture and a specified color onto the
// a rectangle. The used color is: from * (1 - ratio) + to * ratio.
public void drawMixed(GLCanvas canvas, int color, float ratio,
int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawMixed(t, color, ratio, mSrcRect, mDestRect);
}
}
}
// Draws the texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawTexture(t, mSrcRect, mDestRect);
}
}
}
// Draws a sub region of this texture on to the specified rectangle.
public void draw(GLCanvas canvas, RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) continue;
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public boolean isOpaque() {
return false;
}
}
@@ -0,0 +1,298 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.opengl.GLUtils;
import junit.framework.Assert;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL11;
// UploadedTextures use a Bitmap for the content of the texture.
//
// Subclasses should implement onGetBitmap() to provide the Bitmap and
// implement onFreeBitmap(mBitmap) which will be called when the Bitmap
// is not needed anymore.
//
// isContentValid() is meaningful only when the isLoaded() returns true.
// It means whether the content needs to be updated.
//
// The user of this class should call recycle() when the texture is not
// needed anymore.
//
// By default an UploadedTexture is opaque (so it can be drawn faster without
// blending). The user or subclass can override it using setOpaque().
public abstract class UploadedTexture extends BasicTexture {
// To prevent keeping allocation the borders, we store those used borders here.
// Since the length will be power of two, it won't use too much memory.
private static HashMap<BorderKey, Bitmap> sBorderLines =
new HashMap<BorderKey, Bitmap>();
private static BorderKey sBorderKey = new BorderKey();
@SuppressWarnings("unused")
private static final String TAG = "Texture";
private boolean mContentValid = true;
// indicate this textures is being uploaded in background
private boolean mIsUploading = false;
private boolean mOpaque = true;
private boolean mThrottled = false;
private static int sUploadedCount;
private static final int UPLOAD_LIMIT = 100;
protected Bitmap mBitmap;
private int mBorder;
protected UploadedTexture() {
this(false);
}
protected UploadedTexture(boolean hasBorder) {
super(null, 0, STATE_UNLOADED);
if (hasBorder) {
setBorder(true);
mBorder = 1;
}
}
protected void setIsUploading(boolean uploading) {
mIsUploading = uploading;
}
public boolean isUploading() {
return mIsUploading;
}
private static class BorderKey implements Cloneable {
public boolean vertical;
public Config config;
public int length;
@Override
public int hashCode() {
int x = config.hashCode() ^ length;
return vertical ? x : -x;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof BorderKey)) return false;
BorderKey o = (BorderKey) object;
return vertical == o.vertical
&& config == o.config && length == o.length;
}
@Override
public BorderKey clone() {
try {
return (BorderKey) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
protected void setThrottled(boolean throttled) {
mThrottled = throttled;
}
private static Bitmap getBorderLine(
boolean vertical, Config config, int length) {
BorderKey key = sBorderKey;
key.vertical = vertical;
key.config = config;
key.length = length;
Bitmap bitmap = sBorderLines.get(key);
if (bitmap == null) {
bitmap = vertical
? Bitmap.createBitmap(1, length, config)
: Bitmap.createBitmap(length, 1, config);
sBorderLines.put(key.clone(), bitmap);
}
return bitmap;
}
private Bitmap getBitmap() {
if (mBitmap == null) {
mBitmap = onGetBitmap();
int w = mBitmap.getWidth() + mBorder * 2;
int h = mBitmap.getHeight() + mBorder * 2;
if (mWidth == UNSPECIFIED) {
setSize(w, h);
}
}
return mBitmap;
}
private void freeBitmap() {
Assert.assertTrue(mBitmap != null);
onFreeBitmap(mBitmap);
mBitmap = null;
}
@Override
public int getWidth() {
if (mWidth == UNSPECIFIED) getBitmap();
return mWidth;
}
@Override
public int getHeight() {
if (mWidth == UNSPECIFIED) getBitmap();
return mHeight;
}
protected abstract Bitmap onGetBitmap();
protected abstract void onFreeBitmap(Bitmap bitmap);
protected void invalidateContent() {
if (mBitmap != null) freeBitmap();
mContentValid = false;
mWidth = UNSPECIFIED;
mHeight = UNSPECIFIED;
}
/**
* Whether the content on GPU is valid.
*/
public boolean isContentValid() {
return isLoaded() && mContentValid;
}
/**
* Updates the content on GPU's memory.
* @param canvas
*/
public void updateContent(GLCanvas canvas) {
if (!isLoaded()) {
if (mThrottled && ++sUploadedCount > UPLOAD_LIMIT) {
return;
}
uploadToCanvas(canvas);
} else if (!mContentValid) {
Bitmap bitmap = getBitmap();
int format = GLUtils.getInternalFormat(bitmap);
int type = GLUtils.getType(bitmap);
canvas.texSubImage2D(this, mBorder, mBorder, bitmap, format, type);
freeBitmap();
mContentValid = true;
}
}
public static void resetUploadLimit() {
sUploadedCount = 0;
}
public static boolean uploadLimitReached() {
return sUploadedCount > UPLOAD_LIMIT;
}
private void uploadToCanvas(GLCanvas canvas) {
Bitmap bitmap = getBitmap();
if (bitmap != null) {
try {
int bWidth = bitmap.getWidth();
int bHeight = bitmap.getHeight();
int width = bWidth + mBorder * 2;
int height = bHeight + mBorder * 2;
int texWidth = getTextureWidth();
int texHeight = getTextureHeight();
Assert.assertTrue(bWidth <= texWidth && bHeight <= texHeight);
// Upload the bitmap to a new texture.
mId = canvas.getGLId().generateTexture();
canvas.setTextureParameters(this);
if (bWidth == texWidth && bHeight == texHeight) {
canvas.initializeTexture(this, bitmap);
} else {
int format = GLUtils.getInternalFormat(bitmap);
int type = GLUtils.getType(bitmap);
Config config = bitmap.getConfig();
canvas.initializeTextureSize(this, format, type);
canvas.texSubImage2D(this, mBorder, mBorder, bitmap, format, type);
if (mBorder > 0) {
// Left border
Bitmap line = getBorderLine(true, config, texHeight);
canvas.texSubImage2D(this, 0, 0, line, format, type);
// Top border
line = getBorderLine(false, config, texWidth);
canvas.texSubImage2D(this, 0, 0, line, format, type);
}
// Right border
if (mBorder + bWidth < texWidth) {
Bitmap line = getBorderLine(true, config, texHeight);
canvas.texSubImage2D(this, mBorder + bWidth, 0, line, format, type);
}
// Bottom border
if (mBorder + bHeight < texHeight) {
Bitmap line = getBorderLine(false, config, texWidth);
canvas.texSubImage2D(this, 0, mBorder + bHeight, line, format, type);
}
}
} finally {
freeBitmap();
}
// Update texture state.
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
mContentValid = true;
} else {
mState = STATE_ERROR;
throw new RuntimeException("Texture load fail, no bitmap");
}
}
@Override
protected boolean onBind(GLCanvas canvas) {
updateContent(canvas);
return isContentValid();
}
@Override
protected int getTarget() {
return GL11.GL_TEXTURE_2D;
}
public void setOpaque(boolean isOpaque) {
mOpaque = isOpaque;
}
@Override
public boolean isOpaque() {
return mOpaque;
}
@Override
public void recycle() {
super.recycle();
if (mBitmap != null) freeBitmap();
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.os.SystemClock;
//
// The animation time should ideally be the vsync time the frame will be
// displayed, but that is an unknown time in the future. So we use the system
// time just after eglSwapBuffers (when GLSurfaceView.onDrawFrame is called)
// as a approximation.
//
public class AnimationTime {
private static volatile long sTime;
// Sets current time as the animation time.
public static void update() {
sTime = SystemClock.uptimeMillis();
}
// Returns the animation time.
public static long get() {
return sTime;
}
public static long startTime() {
sTime = SystemClock.uptimeMillis();
return sTime;
}
}
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.view.MotionEvent;
public class DownUpDetector {
public interface DownUpListener {
void onDown(MotionEvent e);
void onUp(MotionEvent e);
}
private boolean mStillDown;
private DownUpListener mListener;
public DownUpDetector(DownUpListener listener) {
mListener = listener;
}
private void setState(boolean down, MotionEvent e) {
if (down == mStillDown) return;
mStillDown = down;
if (down) {
mListener.onDown(e);
} else {
mListener.onUp(e);
}
}
public void onTouchEvent(MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
setState(true, ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_POINTER_DOWN: // Multitouch event - abort.
setState(false, ev);
break;
}
}
public boolean isDown() {
return mStillDown;
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.content.Context;
import android.graphics.Matrix;
import com.hippo.ehviewer.gallery.anim.CanvasAnimation;
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
public interface GLRoot {
// Listener will be called when GL is idle AND before each frame.
// Mainly used for uploading textures.
public static interface OnGLIdleListener {
public boolean onGLIdle(
GLCanvas canvas, boolean renderRequested);
}
public void addOnGLIdleListener(OnGLIdleListener listener);
public void registerLaunchedAnimation(CanvasAnimation animation);
public void requestRenderForced();
public void requestRender();
public void requestLayoutContentPane();
public void lockRenderThread();
public void unlockRenderThread();
public void setContentPane(GLView content);
public void setOrientationSource(OrientationSource source);
public int getDisplayRotation();
public int getCompensation();
public Matrix getCompensationMatrix();
public void freeze();
public void unfreeze();
public void setLightsOutMode(boolean enabled);
public Context getContext();
}
@@ -0,0 +1,599 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Process;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.anim.CanvasAnimation;
import com.hippo.ehviewer.gallery.common.ApiHelper;
import com.hippo.ehviewer.gallery.common.Utils;
import com.hippo.ehviewer.gallery.glrenderer.BasicTexture;
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
import com.hippo.ehviewer.gallery.glrenderer.GLES11Canvas;
import com.hippo.ehviewer.gallery.glrenderer.GLES20Canvas;
import com.hippo.ehviewer.gallery.glrenderer.UploadedTexture;
import com.hippo.ehviewer.gallery.util.GalleryUtils;
import com.hippo.ehviewer.gallery.util.MotionEventHelper;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
// The root component of all <code>GLView</code>s. The rendering is done in GL
// thread while the event handling is done in the main thread. To synchronize
// the two threads, the entry points of this package need to synchronize on the
// <code>GLRootView</code> instance unless it can be proved that the rendering
// thread won't access the same thing as the method. The entry points include:
// (1) The public methods of HeadUpDisplay
// (2) The public methods of CameraHeadUpDisplay
// (3) The overridden methods in GLRootView.
public class GLRootView extends GLSurfaceView
implements GLSurfaceView.Renderer, GLRoot {
private static final String TAG = "GLRootView";
private static final boolean DEBUG_FPS = false;
private int mFrameCount = 0;
private long mFrameCountingStart = 0;
private static final boolean DEBUG_INVALIDATE = false;
private int mInvalidateColor = 0;
private static final boolean DEBUG_DRAWING_STAT = false;
private static final boolean DEBUG_PROFILE = false;
private static final boolean DEBUG_PROFILE_SLOW_ONLY = false;
private static final int FLAG_INITIALIZED = 1;
private static final int FLAG_NEED_LAYOUT = 2;
private GL11 mGL;
private GLCanvas mCanvas;
private GLView mContentView;
private OrientationSource mOrientationSource;
// mCompensation is the difference between the UI orientation on GLCanvas
// and the framework orientation. See OrientationManager for details.
private int mCompensation;
// mCompensationMatrix maps the coordinates of touch events. It is kept sync
// with mCompensation.
private Matrix mCompensationMatrix = new Matrix();
private int mDisplayRotation;
private int mFlags = FLAG_NEED_LAYOUT;
private volatile boolean mRenderRequested = false;
private final ArrayList<CanvasAnimation> mAnimations =
new ArrayList<CanvasAnimation>();
private final ArrayDeque<OnGLIdleListener> mIdleListeners =
new ArrayDeque<OnGLIdleListener>();
private final IdleRunner mIdleRunner = new IdleRunner();
private final ReentrantLock mRenderLock = new ReentrantLock();
private final Condition mFreezeCondition =
mRenderLock.newCondition();
private boolean mFreeze;
private long mLastDrawFinishTime;
private boolean mInDownState = false;
//private boolean mFirstDraw = true;
public GLRootView(Context context) {
this(context, null);
}
public GLRootView(Context context, AttributeSet attrs) {
super(context, attrs);
mFlags |= FLAG_INITIALIZED;
setBackgroundDrawable(null);
setEGLContextClientVersion(ApiHelper.HAS_GLES20_REQUIRED ? 2 : 1);
if (ApiHelper.USE_888_PIXEL_FORMAT) {
setEGLConfigChooser(8, 8, 8, 0, 0, 0);
} else {
setEGLConfigChooser(5, 6, 5, 0, 0, 0);
}
setRenderer(this);
if (ApiHelper.USE_888_PIXEL_FORMAT) {
getHolder().setFormat(PixelFormat.RGB_888);
} else {
getHolder().setFormat(PixelFormat.RGB_565);
}
// Uncomment this to enable gl error check.
// setDebugFlags(DEBUG_CHECK_GL_ERROR);
}
@Override
public void registerLaunchedAnimation(CanvasAnimation animation) {
// Register the newly launched animation so that we can set the start
// time more precisely. (Usually, it takes much longer for first
// rendering, so we set the animation start time as the time we
// complete rendering)
mAnimations.add(animation);
}
@Override
public void addOnGLIdleListener(OnGLIdleListener listener) {
synchronized (mIdleListeners) {
mIdleListeners.addLast(listener);
mIdleRunner.enable();
}
}
@Override
public void setContentPane(GLView content) {
if (mContentView == content) return;
if (mContentView != null) {
if (mInDownState) {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mContentView.dispatchTouchEvent(cancelEvent);
cancelEvent.recycle();
mInDownState = false;
}
mContentView.detachFromRoot();
BasicTexture.yieldAllTextures();
}
mContentView = content;
if (content != null) {
content.attachToRoot(this);
requestLayoutContentPane();
}
}
@Override
public void requestRenderForced() {
superRequestRender();
}
@SuppressLint("NewApi")
@Override
public void requestRender() {
if (DEBUG_INVALIDATE) {
StackTraceElement e = Thread.currentThread().getStackTrace()[4];
String caller = e.getFileName() + ":" + e.getLineNumber() + " ";
Log.d(TAG, "invalidate: " + caller);
}
if (mRenderRequested) return;
mRenderRequested = true;
if (ApiHelper.HAS_POST_ON_ANIMATION) {
postOnAnimation(mRequestRenderOnAnimationFrame);
} else {
super.requestRender();
}
}
private Runnable mRequestRenderOnAnimationFrame = new Runnable() {
@Override
public void run() {
superRequestRender();
}
};
private void superRequestRender() {
super.requestRender();
}
@Override
public void requestLayoutContentPane() {
mRenderLock.lock();
try {
if (mContentView == null || (mFlags & FLAG_NEED_LAYOUT) != 0) return;
// "View" system will invoke onLayout() for initialization(bug ?), we
// have to ignore it since the GLThread is not ready yet.
if ((mFlags & FLAG_INITIALIZED) == 0) return;
mFlags |= FLAG_NEED_LAYOUT;
requestRender();
} finally {
mRenderLock.unlock();
}
}
private void layoutContentPane() {
mFlags &= ~FLAG_NEED_LAYOUT;
int w = getWidth();
int h = getHeight();
int displayRotation = 0;
int compensation = 0;
// Get the new orientation values
if (mOrientationSource != null) {
displayRotation = mOrientationSource.getDisplayRotation();
compensation = mOrientationSource.getCompensation();
} else {
displayRotation = 0;
compensation = 0;
}
if (mCompensation != compensation) {
mCompensation = compensation;
if (mCompensation % 180 != 0) {
mCompensationMatrix.setRotate(mCompensation);
// move center to origin before rotation
mCompensationMatrix.preTranslate(-w / 2, -h / 2);
// align with the new origin after rotation
mCompensationMatrix.postTranslate(h / 2, w / 2);
} else {
mCompensationMatrix.setRotate(mCompensation, w / 2, h / 2);
}
}
mDisplayRotation = displayRotation;
// Do the actual layout.
if (mCompensation % 180 != 0) {
int tmp = w;
w = h;
h = tmp;
}
Log.i(TAG, "layout content pane " + w + "x" + h
+ " (compensation " + mCompensation + ")");
if (mContentView != null && w != 0 && h != 0) {
mContentView.layout(0, 0, w, h);
}
// Uncomment this to dump the view hierarchy.
//mContentView.dumpTree("");
}
@Override
protected void onLayout(
boolean changed, int left, int top, int right, int bottom) {
if (changed) requestLayoutContentPane();
}
/**
* Called when the context is created, possibly after automatic destruction.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceCreated(GL10 gl1, EGLConfig config) {
GL11 gl = (GL11) gl1;
if (mGL != null) {
// The GL Object has changed
Log.i(TAG, "GLObject has changed from " + mGL + " to " + gl);
}
mRenderLock.lock();
try {
mGL = gl;
mCanvas = ApiHelper.HAS_GLES20_REQUIRED ? new GLES20Canvas() : new GLES11Canvas(gl);
BasicTexture.invalidateAllTextures();
} finally {
mRenderLock.unlock();
}
if (DEBUG_FPS || DEBUG_PROFILE) {
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
} else {
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
}
/**
* Called when the OpenGL surface is recreated without destroying the
* context.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceChanged(GL10 gl1, int width, int height) {
Log.i(TAG, "onSurfaceChanged: " + width + "x" + height
+ ", gl10: " + gl1.toString());
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
GalleryUtils.setRenderThread();
GL11 gl = (GL11) gl1;
Utils.assertTrue(mGL == gl);
mCanvas.setSize(width, height);
}
private void outputFps() {
long now = System.nanoTime();
if (mFrameCountingStart == 0) {
mFrameCountingStart = now;
} else if ((now - mFrameCountingStart) > 1000000000) {
Log.d(TAG, "fps: " + (double) mFrameCount
* 1000000000 / (now - mFrameCountingStart));
mFrameCountingStart = now;
mFrameCount = 0;
}
++mFrameCount;
}
@Override
public void onDrawFrame(GL10 gl) {
AnimationTime.update();
mRenderLock.lock();
while (mFreeze) {
mFreezeCondition.awaitUninterruptibly();
}
try {
onDrawFrameLocked(gl);
} finally {
mRenderLock.unlock();
}
/*
// We put a black cover View in front of the SurfaceView and hide it
// after the first draw. This prevents the SurfaceView being transparent
// before the first draw.
if (mFirstDraw) {
mFirstDraw = false;
post(new Runnable() {
@Override
public void run() {
View root = getRootView();
View cover = root.findViewById(R.id.gl_root_cover);
cover.setVisibility(GONE);
}
});
}*/
}
private void onDrawFrameLocked(GL10 gl) {
if (DEBUG_FPS) outputFps();
// release the unbound textures and deleted buffers.
mCanvas.deleteRecycledResources();
// reset texture upload limit
UploadedTexture.resetUploadLimit();
mRenderRequested = false;
if ((mOrientationSource != null
&& mDisplayRotation != mOrientationSource.getDisplayRotation())
|| (mFlags & FLAG_NEED_LAYOUT) != 0) {
layoutContentPane();
}
mCanvas.save(GLCanvas.SAVE_FLAG_ALL);
rotateCanvas(-mCompensation);
if (mContentView != null) {
mContentView.render(mCanvas);
}
mCanvas.restore();
if (!mAnimations.isEmpty()) {
long now = AnimationTime.get();
for (int i = 0, n = mAnimations.size(); i < n; i++) {
mAnimations.get(i).setStartTime(now);
}
mAnimations.clear();
}
if (UploadedTexture.uploadLimitReached()) {
requestRender();
}
synchronized (mIdleListeners) {
if (!mIdleListeners.isEmpty()) mIdleRunner.enable();
}
if (DEBUG_INVALIDATE) {
mCanvas.fillRect(10, 10, 5, 5, mInvalidateColor);
mInvalidateColor = ~mInvalidateColor;
}
if (DEBUG_DRAWING_STAT) {
mCanvas.dumpStatisticsAndClear();
}
}
private void rotateCanvas(int degrees) {
if (degrees == 0) return;
int w = getWidth();
int h = getHeight();
int cx = w / 2;
int cy = h / 2;
mCanvas.translate(cx, cy);
mCanvas.rotate(degrees, 0, 0, 1);
if (degrees % 180 != 0) {
mCanvas.translate(-cy, -cx);
} else {
mCanvas.translate(-cx, -cy);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (!isEnabled()) return false;
int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_UP) {
mInDownState = false;
} else if (!mInDownState && action != MotionEvent.ACTION_DOWN) {
return false;
}
if (mCompensation != 0) {
event = MotionEventHelper.transformEvent(event, mCompensationMatrix);
}
mRenderLock.lock();
try {
// If this has been detached from root, we don't need to handle event
boolean handled = mContentView != null
&& mContentView.dispatchTouchEvent(event);
if (action == MotionEvent.ACTION_DOWN && handled) {
mInDownState = true;
}
return handled;
} finally {
mRenderLock.unlock();
}
}
private class IdleRunner implements Runnable {
// true if the idle runner is in the queue
private boolean mActive = false;
@Override
public void run() {
OnGLIdleListener listener;
synchronized (mIdleListeners) {
mActive = false;
if (mIdleListeners.isEmpty()) return;
listener = mIdleListeners.removeFirst();
}
mRenderLock.lock();
boolean keepInQueue;
try {
keepInQueue = listener.onGLIdle(mCanvas, mRenderRequested);
} finally {
mRenderLock.unlock();
}
synchronized (mIdleListeners) {
if (keepInQueue) mIdleListeners.addLast(listener);
if (!mRenderRequested && !mIdleListeners.isEmpty()) enable();
}
}
public void enable() {
// Who gets the flag can add it to the queue
if (mActive) return;
mActive = true;
queueEvent(this);
}
}
@Override
public void lockRenderThread() {
mRenderLock.lock();
}
@Override
public void unlockRenderThread() {
mRenderLock.unlock();
}
@Override
public void onPause() {
unfreeze();
super.onPause();
}
@Override
public void setOrientationSource(OrientationSource source) {
mOrientationSource = source;
}
@Override
public int getDisplayRotation() {
return mDisplayRotation;
}
@Override
public int getCompensation() {
return mCompensation;
}
@Override
public Matrix getCompensationMatrix() {
return mCompensationMatrix;
}
@Override
public void freeze() {
mRenderLock.lock();
mFreeze = true;
mRenderLock.unlock();
}
@Override
public void unfreeze() {
mRenderLock.lock();
mFreeze = false;
mFreezeCondition.signalAll();
mRenderLock.unlock();
}
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setLightsOutMode(boolean enabled) {
if (!ApiHelper.HAS_SET_SYSTEM_UI_VISIBILITY) return;
int flags = 0;
if (enabled) {
flags = STATUS_BAR_HIDDEN;
if (ApiHelper.HAS_VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE) {
flags |= (SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
}
setSystemUiVisibility(flags);
}
// We need to unfreeze in the following methods and in onPause().
// These methods will wait on GLThread. If we have freezed the GLRootView,
// the GLThread will wait on main thread to call unfreeze and cause dead
// lock.
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
unfreeze();
super.surfaceChanged(holder, format, w, h);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
unfreeze();
super.surfaceCreated(holder);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
unfreeze();
super.surfaceDestroyed(holder);
}
@Override
protected void onDetachedFromWindow() {
unfreeze();
super.onDetachedFromWindow();
}
@Override
protected void finalize() throws Throwable {
try {
unfreeze();
} finally {
super.finalize();
}
}
}
@@ -0,0 +1,447 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import com.hippo.ehviewer.gallery.anim.CanvasAnimation;
import com.hippo.ehviewer.gallery.common.Utils;
import com.hippo.ehviewer.gallery.glrenderer.GLCanvas;
import java.util.ArrayList;
// GLView is a UI component. It can render to a GLCanvas and accept touch
// events. A GLView may have zero or more child GLView and they form a tree
// structure. The rendering and event handling will pass through the tree
// structure.
//
// A GLView tree should be attached to a GLRoot before event dispatching and
// rendering happens. GLView asks GLRoot to re-render or re-layout the
// GLView hierarchy using requestRender() and requestLayoutContentPane().
//
// The render() method is called in a separate thread. Before calling
// dispatchTouchEvent() and layout(), GLRoot acquires a lock to avoid the
// rendering thread running at the same time. If there are other entry points
// from main thread (like a Handler) in your GLView, you need to call
// lockRendering() if the rendering thread should not run at the same time.
//
public class GLView {
private static final String TAG = "GLView";
public static final int VISIBLE = 0;
public static final int INVISIBLE = 1;
private static final int FLAG_INVISIBLE = 1;
private static final int FLAG_SET_MEASURED_SIZE = 2;
private static final int FLAG_LAYOUT_REQUESTED = 4;
public interface OnClickListener {
void onClick(GLView v);
}
protected final Rect mBounds = new Rect();
protected final Rect mPaddings = new Rect();
private GLRoot mRoot;
protected GLView mParent;
private ArrayList<GLView> mComponents;
private GLView mMotionTarget;
private CanvasAnimation mAnimation;
private int mViewFlags = 0;
protected int mMeasuredWidth = 0;
protected int mMeasuredHeight = 0;
private int mLastWidthSpec = -1;
private int mLastHeightSpec = -1;
protected int mScrollY = 0;
protected int mScrollX = 0;
protected int mScrollHeight = 0;
protected int mScrollWidth = 0;
private float [] mBackgroundColor;
public void startAnimation(CanvasAnimation animation) {
GLRoot root = getGLRoot();
if (root == null) throw new IllegalStateException();
mAnimation = animation;
if (mAnimation != null) {
mAnimation.start();
root.registerLaunchedAnimation(mAnimation);
}
invalidate();
}
// Sets the visiblity of this GLView (either GLView.VISIBLE or
// GLView.INVISIBLE).
public void setVisibility(int visibility) {
if (visibility == getVisibility()) return;
if (visibility == VISIBLE) {
mViewFlags &= ~FLAG_INVISIBLE;
} else {
mViewFlags |= FLAG_INVISIBLE;
}
onVisibilityChanged(visibility);
invalidate();
}
// Returns GLView.VISIBLE or GLView.INVISIBLE
public int getVisibility() {
return (mViewFlags & FLAG_INVISIBLE) == 0 ? VISIBLE : INVISIBLE;
}
// This should only be called on the content pane (the topmost GLView).
public void attachToRoot(GLRoot root) {
Utils.assertTrue(mParent == null && mRoot == null);
onAttachToRoot(root);
}
// This should only be called on the content pane (the topmost GLView).
public void detachFromRoot() {
Utils.assertTrue(mParent == null && mRoot != null);
onDetachFromRoot();
}
// Returns the number of children of the GLView.
public int getComponentCount() {
return mComponents == null ? 0 : mComponents.size();
}
// Returns the children for the given index.
public GLView getComponent(int index) {
if (mComponents == null) {
throw new ArrayIndexOutOfBoundsException(index);
}
return mComponents.get(index);
}
// Adds a child to this GLView.
public void addComponent(GLView component) {
// Make sure the component doesn't have a parent currently.
if (component.mParent != null) throw new IllegalStateException();
// Build parent-child links
if (mComponents == null) {
mComponents = new ArrayList<GLView>();
}
mComponents.add(component);
component.mParent = this;
// If this is added after we have a root, tell the component.
if (mRoot != null) {
component.onAttachToRoot(mRoot);
}
}
// Removes a child from this GLView.
public boolean removeComponent(GLView component) {
if (mComponents == null) return false;
if (mComponents.remove(component)) {
removeOneComponent(component);
return true;
}
return false;
}
// Removes all children of this GLView.
public void removeAllComponents() {
for (int i = 0, n = mComponents.size(); i < n; ++i) {
removeOneComponent(mComponents.get(i));
}
mComponents.clear();
}
private void removeOneComponent(GLView component) {
if (mMotionTarget == component) {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
dispatchTouchEvent(cancelEvent);
cancelEvent.recycle();
}
component.onDetachFromRoot();
component.mParent = null;
}
public Rect bounds() {
return mBounds;
}
public int getWidth() {
return mBounds.right - mBounds.left;
}
public int getHeight() {
return mBounds.bottom - mBounds.top;
}
public GLRoot getGLRoot() {
return mRoot;
}
// Request re-rendering of the view hierarchy.
// This is used for animation or when the contents changed.
public void invalidate() {
GLRoot root = getGLRoot();
if (root != null) root.requestRender();
}
// Request re-layout of the view hierarchy.
public void requestLayout() {
mViewFlags |= FLAG_LAYOUT_REQUESTED;
mLastHeightSpec = -1;
mLastWidthSpec = -1;
if (mParent != null) {
mParent.requestLayout();
} else {
// Is this a content pane ?
GLRoot root = getGLRoot();
if (root != null) root.requestLayoutContentPane();
}
}
protected void render(GLCanvas canvas) {
renderBackground(canvas);
canvas.save();
for (int i = 0, n = getComponentCount(); i < n; ++i) {
renderChild(canvas, getComponent(i));
}
canvas.restore();
}
public float [] getBackgroundColor() {
return mBackgroundColor;
}
public void setBackgroundColor(float [] color) {
mBackgroundColor = color;
}
protected void renderBackground(GLCanvas view) {
if (mBackgroundColor != null) {
view.clearBuffer(mBackgroundColor);
}
}
protected void renderChild(GLCanvas canvas, GLView component) {
if (component.getVisibility() != GLView.VISIBLE
&& component.mAnimation == null) return;
int xoffset = component.mBounds.left - mScrollX;
int yoffset = component.mBounds.top - mScrollY;
canvas.translate(xoffset, yoffset);
CanvasAnimation anim = component.mAnimation;
if (anim != null) {
canvas.save(anim.getCanvasSaveFlags());
if (anim.calculate(AnimationTime.get())) {
invalidate();
} else {
component.mAnimation = null;
}
anim.apply(canvas);
}
component.render(canvas);
if (anim != null) canvas.restore();
canvas.translate(-xoffset, -yoffset);
}
protected boolean onTouch(MotionEvent event) {
return false;
}
protected boolean dispatchTouchEvent(MotionEvent event,
int x, int y, GLView component, boolean checkBounds) {
Rect rect = component.mBounds;
int left = rect.left;
int top = rect.top;
if (!checkBounds || rect.contains(x, y)) {
event.offsetLocation(-left, -top);
if (component.dispatchTouchEvent(event)) {
event.offsetLocation(left, top);
return true;
}
event.offsetLocation(left, top);
}
return false;
}
protected boolean dispatchTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int action = event.getAction();
if (mMotionTarget != null) {
if (action == MotionEvent.ACTION_DOWN) {
MotionEvent cancel = MotionEvent.obtain(event);
cancel.setAction(MotionEvent.ACTION_CANCEL);
dispatchTouchEvent(cancel, x, y, mMotionTarget, false);
mMotionTarget = null;
} else {
dispatchTouchEvent(event, x, y, mMotionTarget, false);
if (action == MotionEvent.ACTION_CANCEL
|| action == MotionEvent.ACTION_UP) {
mMotionTarget = null;
}
return true;
}
}
if (action == MotionEvent.ACTION_DOWN) {
// in the reverse rendering order
for (int i = getComponentCount() - 1; i >= 0; --i) {
GLView component = getComponent(i);
if (component.getVisibility() != GLView.VISIBLE) continue;
if (dispatchTouchEvent(event, x, y, component, true)) {
mMotionTarget = component;
return true;
}
}
}
return onTouch(event);
}
public Rect getPaddings() {
return mPaddings;
}
@SuppressLint("WrongCall")
public void layout(int left, int top, int right, int bottom) {
boolean sizeChanged = setBounds(left, top, right, bottom);
mViewFlags &= ~FLAG_LAYOUT_REQUESTED;
// We call onLayout no matter sizeChanged is true or not because the
// orientation may change without changing the size of the View (for
// example, rotate the device by 180 degrees), and we want to handle
// orientation change in onLayout.
onLayout(sizeChanged, left, top, right, bottom);
}
private boolean setBounds(int left, int top, int right, int bottom) {
boolean sizeChanged = (right - left) != (mBounds.right - mBounds.left)
|| (bottom - top) != (mBounds.bottom - mBounds.top);
mBounds.set(left, top, right, bottom);
return sizeChanged;
}
@SuppressLint("WrongCall")
public void measure(int widthSpec, int heightSpec) {
if (widthSpec == mLastWidthSpec && heightSpec == mLastHeightSpec
&& (mViewFlags & FLAG_LAYOUT_REQUESTED) == 0) {
return;
}
mLastWidthSpec = widthSpec;
mLastHeightSpec = heightSpec;
mViewFlags &= ~FLAG_SET_MEASURED_SIZE;
onMeasure(widthSpec, heightSpec);
if ((mViewFlags & FLAG_SET_MEASURED_SIZE) == 0) {
throw new IllegalStateException(getClass().getName()
+ " should call setMeasuredSize() in onMeasure()");
}
}
protected void onMeasure(int widthSpec, int heightSpec) {
}
protected void setMeasuredSize(int width, int height) {
mViewFlags |= FLAG_SET_MEASURED_SIZE;
mMeasuredWidth = width;
mMeasuredHeight = height;
}
public int getMeasuredWidth() {
return mMeasuredWidth;
}
public int getMeasuredHeight() {
return mMeasuredHeight;
}
protected void onLayout(
boolean changeSize, int left, int top, int right, int bottom) {
}
/**
* Gets the bounds of the given descendant that relative to this view.
*/
public boolean getBoundsOf(GLView descendant, Rect out) {
int xoffset = 0;
int yoffset = 0;
GLView view = descendant;
while (view != this) {
if (view == null) return false;
Rect bounds = view.mBounds;
xoffset += bounds.left;
yoffset += bounds.top;
view = view.mParent;
}
out.set(xoffset, yoffset, xoffset + descendant.getWidth(),
yoffset + descendant.getHeight());
return true;
}
protected void onVisibilityChanged(int visibility) {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
GLView child = getComponent(i);
if (child.getVisibility() == GLView.VISIBLE) {
child.onVisibilityChanged(visibility);
}
}
}
protected void onAttachToRoot(GLRoot root) {
mRoot = root;
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onAttachToRoot(root);
}
}
protected void onDetachFromRoot() {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onDetachFromRoot();
}
mRoot = null;
}
public void lockRendering() {
if (mRoot != null) {
mRoot.lockRenderThread();
}
}
public void unlockRendering() {
if (mRoot != null) {
mRoot.unlockRenderThread();
}
}
// This is for debugging only.
// Dump the view hierarchy into log.
void dumpTree(String prefix) {
Log.d(TAG, prefix + getClass().getSimpleName());
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).dumpTree(prefix + "....");
}
}
}
@@ -0,0 +1,150 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.content.Context;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
// This class aggregates three gesture detectors: GestureDetector,
// ScaleGestureDetector, and DownUpDetector.
public class GestureRecognizer {
@SuppressWarnings("unused")
private static final String TAG = "GestureRecognizer";
public interface Listener {
boolean onSingleTapUp(float x, float y);
boolean onDoubleTap(float x, float y);
boolean onScrollBegin(float dx, float dy, float totalX, float totalY);
boolean onScroll(float dx, float dy, float totalX, float totalY);
boolean onScrollEnd();
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
boolean onScaleBegin(float focusX, float focusY);
boolean onScale(float focusX, float focusY, float scale);
void onScaleEnd();
void onDown(float x, float y);
void onUp();
}
private final GestureDetector mGestureDetector;
private final ScaleGestureDetector mScaleDetector;
private final DownUpDetector mDownUpDetector;
private final Listener mListener;
private boolean mStillScroll = false;
public GestureRecognizer(Context context, Listener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new MyGestureListener(),
null, true /* ignoreMultitouch */);
mScaleDetector = new ScaleGestureDetector(
context, new MyScaleListener());
mDownUpDetector = new DownUpDetector(new MyDownUpListener());
}
public void onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
mScaleDetector.onTouchEvent(event);
mDownUpDetector.onTouchEvent(event);
}
public boolean isDown() {
return mDownUpDetector.isDown();
}
public void cancelScale() {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mScaleDetector.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
private class MyGestureListener
extends GestureDetector.SimpleOnGestureListener {
float firstX = 0;
float firstY = 0;
@Override
public boolean onSingleTapUp(MotionEvent e) {
return mListener.onSingleTapUp(e.getX(), e.getY());
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return mListener.onDoubleTap(e.getX(), e.getY());
}
@Override
public boolean onScroll(
MotionEvent e1, MotionEvent e2, float dx, float dy) {
if (e1.getX() != firstX || e1.getY() != firstY) {
mStillScroll = true;
firstX = e1.getX();
firstY = e1.getY();
return mListener.onScrollBegin(
dx, dy, e2.getX() - e1.getX(), e2.getY() - e1.getY());
}
else
return mListener.onScroll(
dx, dy, e2.getX() - e1.getX(), e2.getY() - e1.getY());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return mListener.onFling(e1, e2, velocityX, velocityY);
}
}
private class MyScaleListener
extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return mListener.onScaleBegin(
detector.getFocusX(), detector.getFocusY());
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
return mListener.onScale(detector.getFocusX(),
detector.getFocusY(), detector.getScaleFactor());
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mListener.onScaleEnd();
}
}
private class MyDownUpListener implements DownUpDetector.DownUpListener {
@Override
public void onDown(MotionEvent e) {
mListener.onDown(e.getX(), e.getY());
}
@Override
public void onUp(MotionEvent e) {
mListener.onUp();
if (mStillScroll) {
mStillScroll = false;
mListener.onScrollEnd();
}
}
}
}
@@ -0,0 +1,22 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
public interface OrientationSource {
public int getDisplayRotation();
public int getCompensation();
}
@@ -0,0 +1,253 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.util;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.ConditionVariable;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import com.hippo.ehviewer.util.ThreadPool.CancelListener;
import com.hippo.ehviewer.util.ThreadPool.JobContext;
import java.io.File;
import java.util.Arrays;
import java.util.Locale;
public class GalleryUtils {
private static final String TAG = "GalleryUtils";
private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_PANORAMA360 = "application/vnd.google.panorama360+jpg";
public static final String MIME_TYPE_ALL = "*/*";
private static float sPixelDensity = -1f;
public static void initialize(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager)
context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
sPixelDensity = metrics.density;
}
public static float[] intColorToFloatARGBArray(int from) {
return new float[] {
Color.alpha(from) / 255f,
Color.red(from) / 255f,
Color.green(from) / 255f,
Color.blue(from) / 255f
};
}
public static float dpToPixel(float dp) {
return sPixelDensity * dp;
}
public static int dpToPixel(int dp) {
return Math.round(dpToPixel((float) dp));
}
public static int meterToPixel(float meter) {
// 1 meter = 39.37 inches, 1 inch = 160 dp.
return Math.round(dpToPixel(meter * 39.37f * 160));
}
public static byte[] getBytes(String in) {
byte[] result = new byte[in.length() * 2];
int output = 0;
for (char ch : in.toCharArray()) {
result[output++] = (byte) (ch & 0xFF);
result[output++] = (byte) (ch >> 8);
}
return result;
}
// Below are used the detect using database in the render thread. It only
// works most of the time, but that's ok because it's for debugging only.
private static volatile Thread sCurrentThread;
private static volatile boolean sWarned;
public static void setRenderThread() {
sCurrentThread = Thread.currentThread();
}
public static void assertNotInRenderThread() {
if (!sWarned) {
if (Thread.currentThread() == sCurrentThread) {
sWarned = true;
Log.w(TAG, new Throwable("Should not do this in render thread"));
}
}
}
private static final double RAD_PER_DEG = Math.PI / 180.0;
private static final double EARTH_RADIUS_METERS = 6367000.0;
public static double fastDistanceMeters(double latRad1, double lngRad1,
double latRad2, double lngRad2) {
if ((Math.abs(latRad1 - latRad2) > RAD_PER_DEG)
|| (Math.abs(lngRad1 - lngRad2) > RAD_PER_DEG)) {
return accurateDistanceMeters(latRad1, lngRad1, latRad2, lngRad2);
}
// Approximate sin(x) = x.
double sineLat = (latRad1 - latRad2);
// Approximate sin(x) = x.
double sineLng = (lngRad1 - lngRad2);
// Approximate cos(lat1) * cos(lat2) using
// cos((lat1 + lat2)/2) ^ 2
double cosTerms = Math.cos((latRad1 + latRad2) / 2.0);
cosTerms = cosTerms * cosTerms;
double trigTerm = sineLat * sineLat + cosTerms * sineLng * sineLng;
trigTerm = Math.sqrt(trigTerm);
// Approximate arcsin(x) = x
return EARTH_RADIUS_METERS * trigTerm;
}
public static double accurateDistanceMeters(double lat1, double lng1,
double lat2, double lng2) {
double dlat = Math.sin(0.5 * (lat2 - lat1));
double dlng = Math.sin(0.5 * (lng2 - lng1));
double x = dlat * dlat + dlng * dlng * Math.cos(lat1) * Math.cos(lat2);
return (2 * Math.atan2(Math.sqrt(x), Math.sqrt(Math.max(0.0,
1.0 - x)))) * EARTH_RADIUS_METERS;
}
public static final double toMile(double meter) {
return meter / 1609;
}
// For debugging, it will block the caller for timeout millis.
public static void fakeBusy(JobContext jc, int timeout) {
final ConditionVariable cv = new ConditionVariable();
jc.setCancelListener(new CancelListener() {
@Override
public void onCancel() {
cv.open();
}
});
cv.block(timeout);
jc.setCancelListener(null);
}
public static void startCameraActivity(Context context) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static String formatLatitudeLongitude(String format, double latitude,
double longitude) {
// We need to specify the locale otherwise it may go wrong in some language
// (e.g. Locale.FRENCH)
return String.format(Locale.ENGLISH, format, latitude, longitude);
}
public static void showOnMap(Context context, double latitude, double longitude) {
try {
// We don't use "geo:latitude,longitude" because it only centers
// the MapView to the specified location, but we need a marker
// for further operations (routing to/from).
// The q=(lat, lng) syntax is suggested by geo-team.
String uri = formatLatitudeLongitude("http://maps.google.com/maps?f=q&q=(%f,%f)",
latitude, longitude);
ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
MAPS_CLASS_NAME);
Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(uri)).setComponent(compName);
context.startActivity(mapsIntent);
} catch (ActivityNotFoundException e) {
// Use the "geo intent" if no GMM is installed
Log.e(TAG, "GMM activity not found!", e);
String url = formatLatitudeLongitude("geo:%f,%f", latitude, longitude);
Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(mapsIntent);
}
}
public static void setViewPointMatrix(
float matrix[], float x, float y, float z) {
// The matrix is
// -z, 0, x, 0
// 0, -z, y, 0
// 0, 0, 1, 0
// 0, 0, 1, -z
Arrays.fill(matrix, 0, 16, 0);
matrix[0] = matrix[5] = matrix[15] = -z;
matrix[8] = x;
matrix[9] = y;
matrix[10] = matrix[11] = 1;
}
public static int getBucketId(String path) {
return path.toLowerCase().hashCode();
}
// Return the local path that matches the given bucketId. If no match is
// found, return null
public static String searchDirForPath(File dir, int bucketId) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
String path = file.getAbsolutePath();
if (GalleryUtils.getBucketId(path) == bucketId) {
return path;
} else {
path = searchDirForPath(file, bucketId);
if (path != null) return path;
}
}
}
}
return null;
}
public static boolean hasSpaceForSize(long size) {
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
return false;
}
String path = Environment.getExternalStorageDirectory().getPath();
try {
StatFs stat = new StatFs(path);
return stat.getAvailableBlocks() * (long) stat.getBlockSize() > size;
} catch (Exception e) {
Log.i(TAG, "Fail to access external storage", e);
}
return false;
}
}
@@ -0,0 +1,120 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.util;
import android.annotation.TargetApi;
import android.graphics.Matrix;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.MotionEvent.PointerCoords;
import com.hippo.ehviewer.gallery.common.ApiHelper;
public final class MotionEventHelper {
private MotionEventHelper() {}
public static MotionEvent transformEvent(MotionEvent e, Matrix m) {
// We try to use the new transform method if possible because it uses
// less memory.
if (ApiHelper.HAS_MOTION_EVENT_TRANSFORM) {
return transformEventNew(e, m);
} else {
return transformEventOld(e, m);
}
}
@TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
private static MotionEvent transformEventNew(MotionEvent e, Matrix m) {
MotionEvent newEvent = MotionEvent.obtain(e);
newEvent.transform(m);
return newEvent;
}
// This is copied from Input.cpp in the android framework.
private static MotionEvent transformEventOld(MotionEvent e, Matrix m) {
long downTime = e.getDownTime();
long eventTime = e.getEventTime();
int action = e.getAction();
int pointerCount = e.getPointerCount();
int[] pointerIds = getPointerIds(e);
PointerCoords[] pointerCoords = getPointerCoords(e);
int metaState = e.getMetaState();
float xPrecision = e.getXPrecision();
float yPrecision = e.getYPrecision();
int deviceId = e.getDeviceId();
int edgeFlags = e.getEdgeFlags();
int source = e.getSource();
int flags = e.getFlags();
// Copy the x and y coordinates into an array, map them, and copy back.
float[] xy = new float[pointerCoords.length * 2];
for (int i = 0; i < pointerCount;i++) {
xy[2 * i] = pointerCoords[i].x;
xy[2 * i + 1] = pointerCoords[i].y;
}
m.mapPoints(xy);
for (int i = 0; i < pointerCount;i++) {
pointerCoords[i].x = xy[2 * i];
pointerCoords[i].y = xy[2 * i + 1];
pointerCoords[i].orientation = transformAngle(
m, pointerCoords[i].orientation);
}
MotionEvent n = MotionEvent.obtain(downTime, eventTime, action,
pointerCount, pointerIds, pointerCoords, metaState, xPrecision,
yPrecision, deviceId, edgeFlags, source, flags);
return n;
}
private static int[] getPointerIds(MotionEvent e) {
int n = e.getPointerCount();
int[] r = new int[n];
for (int i = 0; i < n; i++) {
r[i] = e.getPointerId(i);
}
return r;
}
private static PointerCoords[] getPointerCoords(MotionEvent e) {
int n = e.getPointerCount();
PointerCoords[] r = new PointerCoords[n];
for (int i = 0; i < n; i++) {
r[i] = new PointerCoords();
e.getPointerCoords(i, r[i]);
}
return r;
}
private static float transformAngle(Matrix m, float angleRadians) {
// Construct and transform a vector oriented at the specified clockwise
// angle from vertical. Coordinate system: down is increasing Y, right is
// increasing X.
float[] v = new float[2];
v[0] = FloatMath.sin(angleRadians);
v[1] = -FloatMath.cos(angleRadians);
m.mapVectors(v);
// Derive the transformed vector's clockwise angle from vertical.
float result = (float) Math.atan2(v[0], -v[1]);
if (result < -Math.PI / 2) {
result += Math.PI;
} else if (result > Math.PI / 2) {
result -= Math.PI;
}
return result;
}
}
@@ -22,7 +22,10 @@ import android.util.Log;
public class DownloadService extends Service {
private static final int DOWNLOAD_NOTIFY_ID = -1;
private static final String TAG = "DownloadService";
private static final String ACTION_UPDATE = "com.hippo.ehviewer.service.UPDATE";
public static final String ACTION_UPDATE = "com.hippo.ehviewer.service.DownloadService";
public static final String KEY_GID = "gid";
public static final String KEY_INDEX = "index";
public static final String KEY_STATE = "state";
private ServiceBinder mBinder = null;
@@ -63,21 +66,31 @@ public class DownloadService extends Service {
@Override
public void onDownloadMangaStart(String id) {
mBuilder.setContentTitle(getString(R.string.downloading)
+ " " + Download.get(id).title)
DownloadInfo di = Download.get(id);
if (di == null)
mNotifyManager.cancel(DOWNLOAD_NOTIFY_ID);
else {
mBuilder.setContentTitle(getString(R.string.downloading)
+ " " + di.title)
.setContentText(null)
.setProgress(0, 0, true).setOngoing(true).setAutoCancel(false);;
mNotifyManager.notify(DOWNLOAD_NOTIFY_ID, mBuilder.build());
}
}
@Override
public void onDownloadMangaStart(String id, int pageSum, int startIndex) {
mBuilder.setContentTitle(getString(R.string.downloading)
+ " " + Download.get(id).title)
.setContentText(startIndex + " / " + pageSum)
.setProgress(pageSum, startIndex, false).setOngoing(true)
.setAutoCancel(false);
mNotifyManager.notify(DOWNLOAD_NOTIFY_ID, mBuilder.build());
DownloadInfo di = Download.get(id);
if (di == null)
mNotifyManager.cancel(DOWNLOAD_NOTIFY_ID);
else {
mBuilder.setContentTitle(getString(R.string.downloading)
+ " " + di.title)
.setContentText(startIndex + " / " + pageSum)
.setProgress(pageSum, startIndex, false).setOngoing(true)
.setAutoCancel(false);
mNotifyManager.notify(DOWNLOAD_NOTIFY_ID, mBuilder.build());
}
}
@Override
@@ -199,6 +212,14 @@ public class DownloadService extends Service {
sendBroadcast(it);
}
public void notifyUpdate(String gid, int index, int state){
Intent it = new Intent(ACTION_UPDATE);
it.putExtra(KEY_GID, gid);
it.putExtra(KEY_INDEX, index);
it.putExtra(KEY_STATE, state);
sendBroadcast(it);
}
public class ServiceBinder extends Binder{
public DownloadService getService(){
return DownloadService.this;
+4 -17
View File
@@ -17,9 +17,7 @@ public class Cache {
private static Context mContext;
public static final String cpCachePath = "/EhViewer/cache/cover";
public static final String pageCachePath = "/EhViewer/cache/page";
public static DiskCache cpCache = null;
public static DiskCache pageCache = null;
public static LruCache<String, Bitmap> memoryCache = null;
public static LruCache<String, MangaDetail> mdCache = null;
@@ -49,29 +47,18 @@ public class Cache {
} catch (Exception e) {
e.printStackTrace();
}
try {
int pageCacheSize = Config.getPageDiskCacheSize() * 1024 * 1024;
if (pageCacheSize <= 0)
pageCache = null;
else
pageCache = new DiskCache(mContext, pageCachePath,
pageCacheSize);
} catch (Exception e) {
e.printStackTrace();
}
}
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 24;
//final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = 8 * 1024 * 1024; // 8MB, can store 80 thumb
memoryCache = new LruCache<String, Bitmap>(cacheSize) {
@SuppressLint("NewApi")
@Override
protected int sizeOf(String key, Bitmap bitmap) {
if (Build.VERSION.SDK_INT < 19)
return bitmap.getByteCount() / 1024;
return bitmap.getByteCount();
else
return bitmap.getAllocationByteCount() / 1024;
return bitmap.getAllocationByteCount();
}
};
+198 -218
View File
@@ -1,218 +1,198 @@
package com.hippo.ehviewer.util;
import java.util.HashSet;
import java.util.Set;
import com.hippo.ehviewer.view.MangaImage;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.Environment;
import android.preference.PreferenceManager;
public class Config {
private static final String TAG = "Config";
private static final String KEY_ALLOWED = "allowed";
private static final String KEY_FIRST = "first_time";
private static final String KEY_LOGIN = "login";
private static final String KEY_IS_EXHENTAI = "is_exhentai";
private static final String CP_CACHE = "preference_cp_cache";
private static final String CP_CACHE_DEFAULT = "25";
private static final String PAGE_CACHE = "preference_page_cache";
private static final String PAGE_CACHE_DEFAULT = "256";
private static final String AUTO_PAGE_CACHE = "preference_auto_page_cache";
private static final String PAGE_SCALING = "preference_page_scaling";
private static final String PAGE_SCALING_DEFAULT = "3";
private static final String SCREEN_ORI = "preference_screen_ori";
private static final String SCREEN_ORI_DEFAULT = "0";
private static final String DOWNLOAD_PATH = "preference_download_path";
private static final String DOWNLOAD_PATH_DEFAULT = Environment.getExternalStorageDirectory() + "/EhViewer/download/";
private static boolean mInit = false;
private static Context mContext;
private static SharedPreferences mConfigPre;
private static final String EMSG = "Please init Config first.";
/**
* Init Config
*
* @param context Application context
*/
public static void init(Context context) {
if (mInit)
return;
mInit = true;
mContext = context;
mConfigPre = PreferenceManager.getDefaultSharedPreferences(mContext);
// Init what in config
MangaImage.setMode(getPageScalingMode());
}
/**
* Is init
* @return True if init
*/
public static boolean isInit() {
return mInit;
}
/**
* Get is it allowed to launch
*
* @return True if allowed
*/
public static boolean isAllowed() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
return mConfigPre.getBoolean(KEY_ALLOWED, false);
}
/**
* Allowed the appliation to launch
*/
public static void allowed() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
mConfigPre.edit().putBoolean(KEY_ALLOWED, true).apply();
}
/**
* Check is it first time to launch the application
*
* @return
*/
public static boolean isFirstTime() {
if (!mInit) {
throw new IllegalStateException();
}
return mConfigPre.getBoolean(KEY_FIRST, true);
}
/**
* It is first time to launch the application
*/
public static void firstTime() {
mConfigPre.edit().putBoolean(KEY_FIRST, false).apply();
}
/**
* Is login last time ?
*
* @return
*/
public static boolean isLogin() {
return mConfigPre.getBoolean(KEY_LOGIN, false);
}
public static void loginNow() {
mConfigPre.edit().putBoolean(KEY_LOGIN, true).apply();
}
public static void logoutNow() {
mConfigPre.edit().putBoolean(KEY_LOGIN, false).apply();
}
public static String getDownloadPath() {
return mConfigPre.getString(DOWNLOAD_PATH, DOWNLOAD_PATH_DEFAULT);
}
/**
* Get cover cache size in MB
*
* @return
*/
public static int getCoverDiskCacheSize() {
try {
return Integer.parseInt(mConfigPre.getString(CP_CACHE, CP_CACHE_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(CP_CACHE, CP_CACHE_DEFAULT).apply();
return 25;
}
}
/**
* Get page cache size in MB
*
* @return
*/
public static int getPageDiskCacheSize() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
try {
return Integer.parseInt(mConfigPre.getString(PAGE_CACHE, PAGE_CACHE_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(PAGE_CACHE, PAGE_CACHE_DEFAULT).apply();
return 256;
}
}
public static boolean isAutoPageCache() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
return mConfigPre.getBoolean(AUTO_PAGE_CACHE, false);
}
public static int getPageScalingMode() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
int pageScalingMode = 3;
try {
pageScalingMode = Integer.parseInt(mConfigPre.getString(
PAGE_SCALING, PAGE_SCALING_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(PAGE_SCALING, PAGE_SCALING_DEFAULT)
.apply();
}
return pageScalingMode;
}
public static int getScreenOriMode() {
if (!mInit) {
throw new IllegalStateException(EMSG);
}
int screenOriMode = 0;
try {
screenOriMode = Integer.parseInt(mConfigPre.getString(
SCREEN_ORI, SCREEN_ORI_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(SCREEN_ORI, SCREEN_ORI_DEFAULT)
.apply();
}
return screenOriPre2Value(screenOriMode);
}
public static int screenOriPre2Value(int screenOriModePre) {
switch (screenOriModePre) {
case 0:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
case 1:
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
case 2:
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
default:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}
public static boolean isExhentai() {
return mConfigPre.getBoolean(KEY_IS_EXHENTAI, false);
}
public static void exhentai(boolean isExhentai) {
mConfigPre.edit().putBoolean(KEY_IS_EXHENTAI, isExhentai).apply();
}
}
package com.hippo.ehviewer.util;
import com.hippo.ehviewer.view.MangaImage;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Environment;
import android.preference.PreferenceManager;
public class Config {
@SuppressWarnings("unused")
private static final String TAG = "Config";
private static final String KEY_ALLOWED = "allowed";
private static final String KEY_FIRST = "first_time";
private static final String KEY_LOGIN = "login";
private static final String KEY_IS_EXHENTAI = "is_exhentai";
private static final String KEY_UPDATE_DATE = "update_date";
private static final String CP_CACHE = "preference_cp_cache";
private static final String CP_CACHE_DEFAULT = "25";
private static final String PAGE_SCALING = "preference_page_scaling";
private static final String PAGE_SCALING_DEFAULT = "3";
private static final String START_POSITION = "preference_start_position";
private static final String START_POSITION_DEFAULT = "1";
private static final String SCREEN_ORI = "preference_screen_ori";
private static final String SCREEN_ORI_DEFAULT = "0";
private static final String DOWNLOAD_PATH = "preference_download_path";
private static final String DOWNLOAD_PATH_DEFAULT = Environment.getExternalStorageDirectory() + "/EhViewer/download/";
private static boolean mInit = false;
private static Context mContext;
private static SharedPreferences mConfigPre;
/**
* Init Config
*
* @param context Application context
*/
public static void init(Context context) {
if (mInit)
return;
mInit = true;
mContext = context;
mConfigPre = PreferenceManager.getDefaultSharedPreferences(mContext);
// Init what in config
MangaImage.setMode(getPageScalingMode());
}
/**
* Is init
* @return True if init
*/
public static boolean isInit() {
return mInit;
}
/**
* Get is it allowed to launch
*
* @return True if allowed
*/
public static boolean isAllowed() {
return mConfigPre.getBoolean(KEY_ALLOWED, false);
}
/**
* Allowed the appliation to launch
*/
public static void allowed() {
mConfigPre.edit().putBoolean(KEY_ALLOWED, true).apply();
}
/**
* Check is it first time to launch the application
*
* @return
*/
public static boolean isFirstTime() {
return mConfigPre.getBoolean(KEY_FIRST, true);
}
/**
* It is first time to launch the application
*/
public static void firstTime() {
mConfigPre.edit().putBoolean(KEY_FIRST, false).apply();
}
/**
* Is login last time ?
*
* @return
*/
public static boolean isLogin() {
return mConfigPre.getBoolean(KEY_LOGIN, false);
}
public static void loginNow() {
mConfigPre.edit().putBoolean(KEY_LOGIN, true).apply();
}
public static void logoutNow() {
mConfigPre.edit().putBoolean(KEY_LOGIN, false).apply();
}
public static String getDownloadPath() {
return mConfigPre.getString(DOWNLOAD_PATH, DOWNLOAD_PATH_DEFAULT);
}
/**
* Get cover cache size in MB
*
* @return
*/
public static int getCoverDiskCacheSize() {
try {
return Integer.parseInt(mConfigPre.getString(CP_CACHE, CP_CACHE_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(CP_CACHE, CP_CACHE_DEFAULT).apply();
return 25;
}
}
public static int getPageScalingMode() {
int pageScalingMode = 3;
try {
pageScalingMode = Integer.parseInt(mConfigPre.getString(
PAGE_SCALING, PAGE_SCALING_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(PAGE_SCALING, PAGE_SCALING_DEFAULT)
.apply();
}
return pageScalingMode;
}
public static int getStartPosition() {
int startPosition = 1;
try {
startPosition = Integer.parseInt(mConfigPre.getString(
START_POSITION, START_POSITION_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(START_POSITION, START_POSITION_DEFAULT)
.apply();
}
return startPosition;
}
public static int getScreenOriMode() {
int screenOriMode = 0;
try {
screenOriMode = Integer.parseInt(mConfigPre.getString(
SCREEN_ORI, SCREEN_ORI_DEFAULT));
} catch (Exception e) {
mConfigPre.edit().putString(SCREEN_ORI, SCREEN_ORI_DEFAULT)
.apply();
}
return screenOriPre2Value(screenOriMode);
}
public static int screenOriPre2Value(int screenOriModePre) {
switch (screenOriModePre) {
case 0:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
case 1:
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
case 2:
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
default:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}
public static boolean isExhentai() {
return mConfigPre.getBoolean(KEY_IS_EXHENTAI, false);
}
public static void exhentai(boolean isExhentai) {
mConfigPre.edit().putBoolean(KEY_IS_EXHENTAI, isExhentai).apply();
}
public static int getUpdateDate() {
return mConfigPre.getInt(KEY_UPDATE_DATE, 0);
}
public static void setUpdateDate() {
setUpdateDate(Util.getDate());
}
public static void setUpdateDate(int date) {
mConfigPre.edit().putInt(KEY_UPDATE_DATE, date).apply();
}
}
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
/*
* 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.util;
// This Future differs from the java.util.concurrent.Future in these aspects:
//
// - Once cancel() is called, isCancelled() always returns true. It is a sticky
// flag used to communicate to the implementation. The implmentation may
// ignore that flag. Regardless whether the Future is cancelled, a return
// value will be provided to get(). The implementation may choose to return
// null if it finds the Future is cancelled.
//
// - get() does not throw exceptions.
//
public interface Future<T> {
public void cancel();
public boolean isCancelled();
public boolean isDone();
public T get();
public void waitDone();
}
@@ -0,0 +1,21 @@
/*
* 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.util;
public interface FutureListener<T> {
public void onFutureDone(Future<T> future);
}
+60
View File
@@ -0,0 +1,60 @@
/*
* 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.util;
public class IntArray {
private static final int INIT_CAPACITY = 8;
private int mData[] = new int[INIT_CAPACITY];
private int mSize = 0;
public void add(int value) {
if (mData.length == mSize) {
int temp[] = new int[mSize + mSize];
System.arraycopy(mData, 0, temp, 0, mSize);
mData = temp;
}
mData[mSize++] = value;
}
public int removeLast() {
mSize--;
return mData[mSize];
}
public int size() {
return mSize;
}
// For testing only
public int[] toArray(int[] result) {
if (result == null || result.length < mSize) {
result = new int[mSize];
}
System.arraycopy(mData, 0, result, 0, mSize);
return result;
}
public int[] getInternalArray() {
return mData;
}
public void clear() {
mSize = 0;
if (mData.length != INIT_CAPACITY) mData = new int[INIT_CAPACITY];
}
}
@@ -0,0 +1,49 @@
/*
* 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.util;
import android.os.Process;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A thread factory that creates threads with a given thread priority.
*/
public class PriorityThreadFactory implements ThreadFactory {
private final int mPriority;
private final AtomicInteger mNumber = new AtomicInteger();
private final String mName;
public PriorityThreadFactory(String name, int priority) {
mName = name;
mPriority = priority;
}
@Override
public Thread newThread(Runnable r) {
return new Thread(r, mName + '-' + mNumber.getAndIncrement()) {
@Override
public void run() {
Process.setThreadPriority(mPriority);
super.run();
}
};
}
}
+268
View File
@@ -0,0 +1,268 @@
/*
* 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.util;
import android.util.Log;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
@SuppressWarnings("unused")
private static final String TAG = "ThreadPool";
private static final int CORE_POOL_SIZE = 4;
private static final int MAX_POOL_SIZE = 8;
private static final int KEEP_ALIVE_TIME = 10; // 10 seconds
// Resource type
public static final int MODE_NONE = 0;
public static final int MODE_CPU = 1;
public static final int MODE_NETWORK = 2;
public static final JobContext JOB_CONTEXT_STUB = new JobContextStub();
ResourceCounter mCpuCounter = new ResourceCounter(2);
ResourceCounter mNetworkCounter = new ResourceCounter(2);
// A Job is like a Callable, but it has an addition JobContext parameter.
public interface Job<T> {
public T run(JobContext jc);
}
public interface JobContext {
boolean isCancelled();
void setCancelListener(CancelListener listener);
boolean setMode(int mode);
}
private static class JobContextStub implements JobContext {
@Override
public boolean isCancelled() {
return false;
}
@Override
public void setCancelListener(CancelListener listener) {
}
@Override
public boolean setMode(int mode) {
return true;
}
}
public interface CancelListener {
public void onCancel();
}
private static class ResourceCounter {
public int value;
public ResourceCounter(int v) {
value = v;
}
}
private final Executor mExecutor;
public ThreadPool() {
this(CORE_POOL_SIZE, MAX_POOL_SIZE);
}
public ThreadPool(int initPoolSize, int maxPoolSize) {
mExecutor = new ThreadPoolExecutor(
initPoolSize, maxPoolSize, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
new PriorityThreadFactory("thread-pool",
android.os.Process.THREAD_PRIORITY_BACKGROUND));
}
// Submit a job to the thread pool. The listener will be called when the
// job is finished (or cancelled).
public <T> Future<T> submit(Job<T> job, FutureListener<T> listener) {
Worker<T> w = new Worker<T>(job, listener);
mExecutor.execute(w);
return w;
}
public <T> Future<T> submit(Job<T> job) {
return submit(job, null);
}
private class Worker<T> implements Runnable, Future<T>, JobContext {
@SuppressWarnings("hiding")
private static final String TAG = "Worker";
private Job<T> mJob;
private FutureListener<T> mListener;
private CancelListener mCancelListener;
private ResourceCounter mWaitOnResource;
private volatile boolean mIsCancelled;
private boolean mIsDone;
private T mResult;
private int mMode;
public Worker(Job<T> job, FutureListener<T> listener) {
mJob = job;
mListener = listener;
}
// This is called by a thread in the thread pool.
@Override
public void run() {
T result = null;
// A job is in CPU mode by default. setMode returns false
// if the job is cancelled.
if (setMode(MODE_CPU)) {
try {
result = mJob.run(this);
} catch (Throwable ex) {
Log.w(TAG, "Exception in running a job", ex);
}
}
synchronized(this) {
setMode(MODE_NONE);
mResult = result;
mIsDone = true;
notifyAll();
}
if (mListener != null) mListener.onFutureDone(this);
}
// Below are the methods for Future.
@Override
public synchronized void cancel() {
if (mIsCancelled) return;
mIsCancelled = true;
if (mWaitOnResource != null) {
synchronized (mWaitOnResource) {
mWaitOnResource.notifyAll();
}
}
if (mCancelListener != null) {
mCancelListener.onCancel();
}
}
@Override
public boolean isCancelled() {
return mIsCancelled;
}
@Override
public synchronized boolean isDone() {
return mIsDone;
}
@Override
public synchronized T get() {
while (!mIsDone) {
try {
wait();
} catch (Exception ex) {
Log.w(TAG, "ingore exception", ex);
// ignore.
}
}
return mResult;
}
@Override
public void waitDone() {
get();
}
// Below are the methods for JobContext (only called from the
// thread running the job)
@Override
public synchronized void setCancelListener(CancelListener listener) {
mCancelListener = listener;
if (mIsCancelled && mCancelListener != null) {
mCancelListener.onCancel();
}
}
@Override
public boolean setMode(int mode) {
// Release old resource
ResourceCounter rc = modeToCounter(mMode);
if (rc != null) releaseResource(rc);
mMode = MODE_NONE;
// Acquire new resource
rc = modeToCounter(mode);
if (rc != null) {
if (!acquireResource(rc)) {
return false;
}
mMode = mode;
}
return true;
}
private ResourceCounter modeToCounter(int mode) {
if (mode == MODE_CPU) {
return mCpuCounter;
} else if (mode == MODE_NETWORK) {
return mNetworkCounter;
} else {
return null;
}
}
private boolean acquireResource(ResourceCounter counter) {
while (true) {
synchronized (this) {
if (mIsCancelled) {
mWaitOnResource = null;
return false;
}
mWaitOnResource = counter;
}
synchronized (counter) {
if (counter.value > 0) {
counter.value--;
break;
} else {
try {
counter.wait();
} catch (InterruptedException ex) {
// ignore.
}
}
}
}
synchronized (this) {
mWaitOnResource = null;
}
return true;
}
private void releaseResource(ResourceCounter counter) {
synchronized (counter) {
counter.value++;
counter.notifyAll();
}
}
}
}
+119
View File
@@ -0,0 +1,119 @@
package com.hippo.ehviewer.util;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
public abstract class TimeRunner {
private static final int INTERVAL = 5;
private static final int RUNNING = 0;
private static final int START = 1;
private static final int END = 2;
private boolean mRunInThread = true;
private boolean mListenerInThread = true;
private OnTimeListener mListener;
public interface OnTimeListener {
public void onStart();
public void onEnd();
}
// TODO
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RUNNING:
run((Float)msg.obj, msg.arg1);
break;
case START:
mListener.onStart();
break;
case END:
mListener.onEnd();
break;
}
}
};
private int mDuration = 0;
private int mDelay = 0;
public void setOnTimerListener(OnTimeListener listener) {
mListener = listener;
}
public void setDuration(int duration) {
mDuration = duration;
}
public void setRunInThread(boolean runInThread) {
mRunInThread = runInThread;
}
public void setListenerInThread(boolean listenerInThread) {
mListenerInThread = listenerInThread;
}
public void start() {
start(0);
}
public void start(int delay) {
mDelay = delay;
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(mDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mListener != null) {
if (mListenerInThread) {
mListener.onStart();
} else {
Message msg = new Message();
msg.what = START;
mHandler.sendMessage(msg);
}
}
long startTime = System.currentTimeMillis();
for (int runningTime = 0; runningTime < mDuration; runningTime = (int)(System.currentTimeMillis() - startTime)) {
if (mRunInThread) {
TimeRunner.this.run(runningTime/(float)mDuration, runningTime);
} else {
Message msg = new Message();
msg.what = RUNNING;
msg.obj = runningTime/(float)mDuration;
msg.arg1 = runningTime;
mHandler.sendMessage(msg);
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (mListener != null) {
if (mListenerInThread) {
mListener.onEnd();
} else {
Message msg = new Message();
msg.what = END;
mHandler.sendMessage(msg);
}
}
}
}).start();
}
protected abstract void run(float interpolatedTime, int runningTime);
}
+217 -187
View File
@@ -1,187 +1,217 @@
package com.hippo.ehviewer.util;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.hippo.ehviewer.DiskCache;
import com.hippo.ehviewer.ListUrls;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.view.OlImageView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Movie;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
public class Util {
private static String TAG = "Util";
/**
* Put InputStream to File, default bufferSize is 512 * 1024
*
* @param is
* @param file
* @throws IOException
*/
public static void inputStream2File(InputStream is, File file) throws IOException {
OutputStream os = new FileOutputStream(file);
copy(is, os);
}
public static void copy(InputStream is, OutputStream os) throws IOException {
copy(is, os, 512 * 1024);
}
public static void copy(InputStream is, OutputStream os, int size) throws IOException {
byte[] buffer = new byte[512 * 1024];
int bytesRead;
while((bytesRead = is.read(buffer)) !=-1)
os.write(buffer, 0, bytesRead);
is.close();
os.flush();
os.close();
buffer = null;
}
public static final int BITMAP = 0x0;
public static final int MOVIE = 0x1;
public static int getResourcesType(String url) {
int type = BITMAP;
int index = url.lastIndexOf('.');
if (index != -1 && getExtension(url).equals("gif"))
type = MOVIE;
return type;
}
public static String getExtension(String url) {
int index = url.lastIndexOf('.');
if (index != -1)
return url.substring(index + 1).toLowerCase();
else
return "png";
}
public static String getName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index != -1)
return fileName.substring(0, index).toLowerCase();
else
return "png";
}
public static boolean isNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch < '0' || ch > '9')
return false;
}
return true;
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte element : b) {
int v = element & 0xFF;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length()/2*2;
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[(i / 2)] = ((byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
.digit(s.charAt(i + 1), 16)));
}
return data;
}
public static String InputStream2String(InputStream is) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String inputLine;
while ((inputLine = br.readLine()) != null)
sb.append(inputLine + "\n");
br.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
int length = sb.length();
if (length != 0)
sb.delete(length - 1, length);
return sb.toString();
}
public static String[] getStrings(SharedPreferences shaper, String key) {
String str = shaper.getString(key, null);
if (str == null || str.length() == 0)
return null;
return new String(Util.hexStringToByteArray(str)).split("\n");
}
public static void putStrings(SharedPreferences shaper, String key, List<String> strs) {
StringBuffer sb = new StringBuffer();
for (String item : strs) {
sb.append(item);
sb.append('\n');
}
int length = sb.length();
if (length != 0)
sb.delete(length - 1, length);
shaper.edit().putString(key, byteArrayToHexString(sb.toString().getBytes())).apply();
}
public static void closeStreamQuietly (Closeable is) {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
}
public 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);
}
}
}
}
package com.hippo.ehviewer.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import com.hippo.ehviewer.DiskCache;
import com.hippo.ehviewer.ListUrls;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.view.OlImageView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Movie;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
public class Util {
private static String TAG = "Util";
/**
* Put InputStream to File, default bufferSize is 512 * 1024
*
* @param is
* @param file
* @throws IOException
*/
public static void inputStream2File(InputStream is, File file) throws IOException {
OutputStream os = new FileOutputStream(file);
copy(is, os);
}
public static void copy(InputStream is, OutputStream os) throws IOException {
copy(is, os, 512 * 1024);
}
public static void copy(InputStream is, OutputStream os, int size) throws IOException {
byte[] buffer = new byte[size];
int bytesRead;
while((bytesRead = is.read(buffer)) !=-1)
os.write(buffer, 0, bytesRead);
is.close();
os.flush();
os.close();
buffer = null;
}
public static final int BITMAP = 0x0;
public static final int MOVIE = 0x1;
public static int getResourcesType(String url) {
int type = BITMAP;
int index = url.lastIndexOf('.');
if (index != -1 && getExtension(url).equals("gif"))
type = MOVIE;
return type;
}
public static String getExtension(String url) {
int index = url.lastIndexOf('.');
if (index != -1)
return url.substring(index + 1).toLowerCase();
else
return "png";
}
public static String getName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index != -1)
return fileName.substring(0, index).toLowerCase();
else
return "png";
}
public static boolean isNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch < '0' || ch > '9')
return false;
}
return true;
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte element : b) {
int v = element & 0xFF;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.getDefault());
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length()/2*2;
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[(i / 2)] = ((byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
.digit(s.charAt(i + 1), 16)));
}
return data;
}
/**
* Convernt context in stream to string
*
* @param is
* @param charset
* @return
*/
public static String InputStream2String(InputStream is, String charset) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String str = null;
try {
Util.copy(is, baos, 1024);
str = baos.toString(charset);
} catch (IOException e) {
e.printStackTrace();
} finally {
Util.closeStreamQuietly(baos);
}
return str;
}
public static String getFileForUrl(String url) {
String file = null;
int index = url.lastIndexOf("/");
if (index == -1)
return url;
else
return url.substring(index + 1);
}
public static String[] getStrings(SharedPreferences shaper, String key) {
String str = shaper.getString(key, null);
if (str == null || str.length() == 0)
return null;
return new String(Util.hexStringToByteArray(str)).split("\n");
}
public static void putStrings(SharedPreferences shaper, String key, List<String> strs) {
StringBuffer sb = new StringBuffer();
for (String item : strs) {
sb.append(item);
sb.append('\n');
}
int length = sb.length();
if (length != 0)
sb.delete(length - 1, length);
shaper.edit().putString(key, byteArrayToHexString(sb.toString().getBytes())).apply();
}
public static void closeStreamQuietly (Closeable is) {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
}
/**
* Delete dir and it child file and dir
*
* @param dir
* The dir to deleted
* @throws IOException
*/
public 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);
}
}
}
@SuppressLint("SimpleDateFormat")
public static int getDate() {
int time = 0;
try {
time = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
} catch (NumberFormatException e) {}
return time;
}
}
+156 -34
View File
@@ -3,82 +3,184 @@ package com.hippo.ehviewer.widget;
import java.util.ArrayList;
import java.util.List;
import com.hippo.ehviewer.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
/**
* A ViewGroup that can layout views in line and auto wrap
*
* @author Hippo
*
*/
public class AutoWrapLayout extends ViewGroup {
@SuppressWarnings("unused")
private final static String TAG = "AutoWrapLayout";
private List<Rect> rectList = new ArrayList<Rect>();
private BaseLine mBaseLine;
private static final BaseLine[] sBaseLineArray = { BaseLine.TOP,
BaseLine.CENTER, BaseLine.BOTTOM };
public enum BaseLine {
TOP(0),
CENTER(1),
BOTTOM(2);
BaseLine(int ni) {
nativeInt = ni;
}
final int nativeInt;
}
public AutoWrapLayout(Context context) {
super(context);
}
public AutoWrapLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this(context, attrs, 0);
}
public AutoWrapLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
static int adjust(int measureSpec, int delta) {
return MeasureSpec.makeMeasureSpec(
MeasureSpec.getSize(measureSpec + delta), MeasureSpec.getMode(measureSpec));
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.AutoWrapLayout, defStyle, 0);
int index = a.getInt(R.styleable.AutoWrapLayout_baseLine, -1);
if (index >= 0)
setBaseLine(sBaseLineArray[index]);
a.recycle();
}
public void setBaseLine(BaseLine baseLine) {
if (baseLine == null)
return;
if (mBaseLine != baseLine) {
mBaseLine = baseLine;
requestLayout();
invalidate();
}
}
public BaseLine getScaleType() {
return mBaseLine;
}
private void adjustBaseLine(int lineHeight, int startIndex, int endIndex) {
if (mBaseLine == BaseLine.TOP)
return;
for (int index = startIndex; index < endIndex; index++) {
final View child = getChildAt(index);
final AutoWrapLayout.LayoutParams lp =
(AutoWrapLayout.LayoutParams)child.getLayoutParams();
Rect rect = rectList.get(index);
int offsetRaw = lineHeight - rect.height() - lp.topMargin - lp.bottomMargin;
if (mBaseLine == BaseLine.CENTER)
rect.offset(0, offsetRaw/2);
else if (mBaseLine == BaseLine.BOTTOM)
rect.offset(0, offsetRaw);
}
}
// TODO Take vertical mode
/**
* each row or line at least show one child
*
* horizontal only show child can show or partly show in parent
*/
@SuppressLint("DrawAllocation")
@Override
protected void onMeasure(int widthMeasureSpec, int heightSpec) {
final int mWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
final int childCount = getChildCount();
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
int maxHeight = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.UNSPECIFIED)
maxWidth = Integer.MAX_VALUE;
if (heightMode == MeasureSpec.UNSPECIFIED)
maxHeight = Integer.MAX_VALUE;
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int maxRightBound = maxWidth - paddingRight;
int maxBottomBound = maxHeight - paddingBottom;
int left;
int top;
int right;
int bottom;
int rightBound = 0;
int rightBound = paddingLeft;
int maxRightNoPadding = rightBound;
int bottomBound;
int lastMaxBottom = 0;
int maxBottom = lastMaxBottom;
int width;
int height;
int lastMaxBottom = paddingTop;
int maxBottom = lastMaxBottom; // maxBottom is maxBottomNoPadding
//int maxBottomNoPadding = maxBottom;
int childWidth;
int childHeight;
int lineStartIndex = 0;
int lineEndIndex = 0; // endIndex + 1
rectList.clear();
for(int i = 0; i < childCount; i++){
final View child = this.getChildAt(i);
int childCount = getChildCount();
for (int index = 0; index < childCount; index++) {
final View child = getChildAt(index);
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
if (child.getVisibility() == View.GONE)
continue;
final AutoWrapLayout.LayoutParams lp =
(AutoWrapLayout.LayoutParams)child.getLayoutParams();
width = child.getMeasuredWidth();
height = child.getMeasuredHeight();
childWidth = child.getMeasuredWidth();
childHeight = child.getMeasuredHeight();
left = rightBound + lp.leftMargin;
right = left + width;
right = left + childWidth;
rightBound = right + lp.rightMargin;
//if it can't drawing on a same line , skip to next line
if(rightBound > mWidth) {
left = 0 + lp.leftMargin;
right = left + width;
if (rightBound > maxRightBound) { // Go to next row
lineEndIndex = index;
// Adjust child position base on baseline
adjustBaseLine(maxBottom - lastMaxBottom, lineStartIndex, lineEndIndex);
// If child can't show in parent begin this line
if (maxBottom >= maxBottomBound)
break;
left = paddingLeft + lp.leftMargin;
right = left + childWidth;
rightBound = right + lp.rightMargin;
lastMaxBottom = maxBottom;
top = lastMaxBottom + lp.topMargin;
bottom = top + height;
bottom = top + childHeight;
bottomBound = bottom + lp.bottomMargin;
maxBottom = bottomBound;
lineStartIndex = index;
} else {
top = lastMaxBottom + lp.topMargin;
bottom = top + height;
bottom = top + childHeight;
bottomBound = bottom + lp.bottomMargin;
}
// Update max bottom
// Update max
if (rightBound > maxRightNoPadding)
maxRightNoPadding = rightBound;
if (bottomBound > maxBottom)
maxBottom = bottomBound;
Rect rect = new Rect();
@@ -88,15 +190,35 @@ public class AutoWrapLayout extends ViewGroup {
rect.bottom = bottom;
rectList.add(rect);
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), maxBottom + getPaddingTop() + getPaddingBottom());
// Handle last line baseline
adjustBaseLine(maxBottom - lastMaxBottom, lineStartIndex, rectList.size());
int measuredWidth;
int measuredHeight;
if (widthMode == MeasureSpec.EXACTLY)
measuredWidth = maxWidth;
else
measuredWidth = maxRightNoPadding + paddingRight;
if (heightMode == MeasureSpec.EXACTLY)
measuredHeight = maxHeight;
else {
measuredHeight = maxBottom + paddingBottom;
if (heightMode == MeasureSpec.AT_MOST)
measuredHeight = measuredHeight > maxHeight ? maxHeight : measuredHeight;
}
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount() > rectList.size() ? rectList.size() : getChildCount();
final int count = rectList.size();
for(int i = 0; i < count; i++){
final View child = this.getChildAt(i);
if (child.getVisibility() == View.GONE)
continue;
Rect rect = rectList.get(i);
child.layout(rect.left, rect.top, rect.right, rect.bottom);
}
@@ -523,7 +523,9 @@ public final class DiskLruCache implements Closeable {
throws IOException {
Entry entry = editor.entry;
if (entry.currentEditor != editor) {
throw new IllegalStateException();
// throw new IllegalStateException();
// TODO I add, It may error when call delete()
return;
}
// If this edit is creating the entry for the first time, every index
@@ -670,57 +672,12 @@ public final class DiskLruCache implements Closeable {
* the cache.
*/
public synchronized void delete() throws IOException {
// Close
if (journalWriter == null) {
return; // Already closed.
}
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
close();
Util.deleteContents(directory);
// TODO I add
size = 0;
lruEntries.clear();
// rebuildJournal
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFileTmp), Util.US_ASCII));
try {
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for (Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key + '\n');
} else {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths()
+ '\n');
}
}
} finally {
writer.close();
}
if (journalFile.exists()) {
renameTo(journalFile, journalFileBackup, true);
}
renameTo(journalFileTmp, journalFile, false);
journalFileBackup.delete();
journalWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFile, true), Util.US_ASCII));
rebuildJournal();
}
private void validateKey(String key) {