Compare commits

..
348 Commits
Author SHA1 Message Date
seven332 b44fdcfeec 添加下载链接 2014-09-06 21:26:22 +08:00
seven332 51f050ae7e Release 时 LOG 不显示 2014-09-06 20:53:17 +08:00
seven332 d59685588b 更新 string.xml 2014-09-06 20:15:00 +08:00
seven332 2e188a2cc3 添加解码选择 2014-09-06 19:40:18 +08:00
seven332 b562ec2b50 调整图标 2014-09-06 18:53:53 +08:00
seven332 dab0b0cbfb 添加下载项全部开始下载或停止 2014-09-06 16:17:52 +08:00
seven332 68aea866e1 将部分字符串移动至 string.xml 2014-09-06 14:22:15 +08:00
seven332 82c0208ac8 添加 EH 站点连接最小间隔设置 2014-09-06 03:37:42 +08:00
seven332 0285f82f52 添加 Http 设置 2014-09-06 03:01:14 +08:00
seven332 3d88928ed3 添加下载线程数设置 2014-09-06 02:20:08 +08:00
seven332 f05d123da7 添加 UrlBuilder,release 时不显示 Log 2014-09-03 20:23:58 +08:00
seven332 dcc45c5d81 修正可能出现的除数为零 2014-09-02 01:22:49 +08:00
seven332 d25caafc8b 修正 g 的解析错误 2014-08-30 00:12:59 +08:00
seven332 290c60adab 添加日志文件输出 2014-08-29 21:50:52 +08:00
seven332 3c7a61a863 添加 mips 支持,修正解析判断错误 2014-08-29 11:24:58 +08:00
seven332 5a3b152110 添加 libjpeg-turbo 解码 2014-08-29 00:03:27 +08:00
seven332 446e0aadd1 添加 libpng 解码 2014-08-28 10:40:50 +08:00
seven332 62675a3dd2 gif 解码添加文件路径入口 2014-08-27 15:39:40 +08:00
seven332 6e97c23dda 阅读界面添加电量显示 2014-08-26 16:09:16 +08:00
seven332 d08598ab71 修正由于图片宽度而导致的错位 2014-08-26 09:59:54 +08:00
seven332 007330112e 添加 GL_RGBA GL_LUMINANCE_ALPHA 2014-08-26 00:00:07 +08:00
seven332 eb33529980 update 2014-08-25 22:27:42 +08:00
seven332 22ff864844 update 2014-08-25 16:19:58 +08:00
seven332 51f2ea5bf8 使用 giflib 对 gif 解码 2014-08-25 16:09:39 +08:00
seven332 8f611c5a27 update 2014-08-24 21:06:46 +08:00
seven332 5413b8e40e update 2014-08-24 21:04:23 +08:00
seven332 b1cf11e2bc 修正一些错误 2014-08-24 12:05:44 +08:00
seven332 fb8bc2c364 更新 Gallery2 部分 2014-08-23 13:39:48 +08:00
seven332 570796a610 fix date 2014-08-23 12:00:16 +08:00
seven332 3a1fe8da1d 修正可能的布局错误 2014-08-23 11:32:15 +08:00
seven332 5259f2173d 重用 Notification.Builder 避免可能的闪烁 2014-08-22 23:26:40 +08:00
seven332 5b6f458c60 update 2014-08-22 19:55:43 +08:00
seven332 1998af3d0b update 2014-08-22 19:54:47 +08:00
seven332 e3b5ed840e 详情界面的 Activity 跳转不关闭自身 2014-08-22 16:53:47 +08:00
seven332 e96d91184f string.xml 2014-08-22 16:03:00 +08:00
seven332 5822e58984 完善下载界面 2014-08-22 13:52:08 +08:00
seven332 da90150233 够快关闭免费外链了... 2014-08-20 23:44:54 +08:00
seven332 62d6609b15 添加双击缩放 2014-08-20 22:24:54 +08:00
seven332 e451db6032 完善阅读界面 2014-08-20 17:16:43 +08:00
seven332 a2bbe855e8 完善阅读下载策略 2014-08-19 16:24:36 +08:00
seven332 374ed3a515 新的阅读下载策略 2014-08-17 22:20:43 +08:00
seven332 6f0af8b6ec 允许 Http 请求重试 2014-08-14 15:19:38 +08:00
seven332 a98cd0bc79 使用原生 Toast 样式 2014-08-13 23:06:20 +08:00
seven332 0e125738e2 优化列表 2014-08-12 21:28:05 +08:00
seven332 055fd5e8ae 调整网页分析 2014-08-11 12:14:06 +08:00
seven332 10ba81f5cc 完善详情界面 2014-08-10 22:00:01 +08:00
seven332 08d79aa204 根据网页调整分析方法 2014-08-09 23:05:04 +08:00
seven332 d0e1b4cfee 添加 ResponedScrollView 2014-08-09 00:00:08 +08:00
seven332 90d95c6552 完善详情界面 2014-08-08 16:10:21 +08:00
seven332 53a7cc84a2 完善详情界面 2014-08-08 00:15:13 +08:00
seven332 129b70e15c 修正屏幕转动后 padding 错误 2014-08-07 16:12:58 +08:00
seven332 80282ffd04 完善详情界面 2014-08-06 22:56:46 +08:00
seven332 e3209cd2c0 为 WindowsAnimate 添加 Sprite 2014-08-06 14:39:31 +08:00
seven332 3681bd1dd4 利用 Bitmap 显示过渡动画 2014-08-06 00:35:10 +08:00
seven332 a6fea77b15 完善详情界面与 Ripple 效果 2014-08-05 23:18:21 +08:00
seven332 e08a9bfdfa 部分改善详情界面,添加 Ripple 效果 2014-08-04 22:38:31 +08:00
seven332 ee229b11da 更新 CardView 2014-08-02 11:49:43 +08:00
seven332 dfa5998483 修正 AutoWrapLayout 不完全显示问题 2014-08-01 10:11:41 +08:00
seven332 b743bdb581 添加 SuperButton 2014-07-31 21:28:48 +08:00
seven332 fa5d8380c9 添加图片搜索入口 2014-07-30 14:55:56 +08:00
seven332 79ffce2f3e 添加文件搜索 2014-07-29 23:21:06 +08:00
seven332 d89db7754f 尝试在列表缩略图上显示语言 2014-07-29 11:28:18 +08:00
seven332 ef154867a6 添加快速搜索提示 2014-07-29 09:24:01 +08:00
seven332 8abe21c536 NumberOfColumnsPreference 添加 summary 2014-07-28 23:43:37 +08:00
seven332 333c783a0d 添加列表缩略图与预览图列数设置 2014-07-28 20:24:10 +08:00
seven332 eae2375560 更新感谢 2014-07-28 10:34:06 +08:00
seven332 0a3adfb06b 添加 FixedAspectImageView 与 SimpleGridLayout 2014-07-28 10:28:43 +08:00
seven332 5fda8b792c 添加列表缩略图模式 2014-07-27 13:17:46 +08:00
seven332 0ea49f593b 横屏时移除 WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION 2014-07-26 13:11:10 +08:00
seven332 6331c3c86d 修正拼写错误 2014-07-26 11:34:54 +08:00
seven332 99df5be760 修正 FilterDialog 未关闭问题 2014-07-26 10:25:54 +08:00
seven332 53f8f6defc 移除 CardViewDelegate 2014-07-26 10:08:03 +08:00
seven332 c1d39de57c 更愉快的 CardView 2014-07-26 10:02:48 +08:00
seven332 f0c8c14918 调整 CardView 2014-07-25 23:33:06 +08:00
seven332 5b0b1b1614 使用 CardView 2014-07-25 16:29:59 +08:00
seven332 8ffa54dc25 调整代码 2014-07-25 15:54:01 +08:00
seven332 ae4714aa48 不显示 count 2014-07-25 14:30:43 +08:00
seven332 802c11bed1 重命名 2014-07-25 14:26:34 +08:00
seven332 ff2ed3205d 使用预设颜色,避免随机生成的奇怪颜色 2014-07-24 23:06:11 +08:00
seven332 ba7f1a5aed 添加 API 源选择 2014-07-24 17:13:18 +08:00
seven332 43903adcc4 修正 lofi 时收藏夹解析错误 2014-07-24 15:43:13 +08:00
seven332 703fc5f44d 更新翻译 2014-07-24 13:14:31 +08:00
seven332 485f4ba9f2 添加 exclude language 2014-07-24 13:11:25 +08:00
seven332 1d6e6277d8 添加 Exculde Tag Group 2014-07-24 10:19:54 +08:00
seven332 2ed2c08183 添加列表默认分类显示 2014-07-23 17:26:24 +08:00
seven332 eaae310f05 添加 CategoryTable 2014-07-23 16:06:09 +08:00
seven332 ab9b7e59d9 添加 lofi 列表分析 2014-07-23 11:15:22 +08:00
seven332 07614fecef AppHandler 2014-07-20 23:12:09 +08:00
seven332 fae86c1782 显示纯文本错误提示 2014-07-20 23:04:43 +08:00
seven332 b0fc8f4c58 添加 RefreshTextView 2014-07-20 16:58:47 +08:00
seven332 5cdc004829 不显示 tag value 2014-07-13 18:09:25 +08:00
seven332 7efed23ddf 修正横屏下新建 Activity 出现卡顿的问题 2014-07-13 18:04:53 +08:00
seven332 251ed9b687 调整布局 2014-07-13 17:42:19 +08:00
seven332 1b017250a5 使用 AppHandler 2014-07-13 17:25:37 +08:00
seven332 5e9097b1bf 添加 zh-rHK zh-rTW 翻译 2014-07-13 11:47:06 +08:00
seven332 62858aa5d2 添加圆角矩形背景 2014-07-13 11:15:30 +08:00
seven332 8ceb7ca912 允许查看 gallery 上传者的其他上传 2014-07-12 11:06:44 +08:00
seven332 4ce0a60397 由 url 进入详情页,初始仅显示加载等待控件 2014-07-12 00:27:03 +08:00
seven332 75731d5600 修正详情页面切换 gallery 时 title 无变化的问题 2014-07-11 23:48:07 +08:00
seven332 7ddeef682a 调整 user panel 2014-07-11 23:07:34 +08:00
seven332 da076be7fb 第一次启动显示左侧栏 2014-07-11 22:34:06 +08:00
seven332 7235e3abd5 完善下载功能 2014-07-11 21:41:36 +08:00
seven332 05cfabae10 添加 gid token 错误识别 2014-06-29 02:37:26 +08:00
seven332 32e345f9f0 修正 ListActivity 未启动时由 DetailActivity 跳至其会出现的错误 2014-06-28 21:44:33 +08:00
seven332 6b7f314e9f 完善 Activity 跳转 2014-06-28 20:24:18 +08:00
seven332 db3fe7e446 完善 HttpHelper 2014-06-28 02:36:15 +08:00
seven332 d7e42a760c 添加注释,修改函数名 2014-06-26 13:59:15 +08:00
seven332 f90588e79e SetMinimumWidth for modeSpinner 2014-06-26 13:51:20 +08:00
seven332 deefd9b9e3 移除错误的提示 2014-06-26 02:45:46 +08:00
seven332 e01ef1abff 添加默认 cookie,默认模式改为EX 2014-06-26 01:48:51 +08:00
seven332 facb17eac2 修正由于没有显式 host 而导致的头像获取错误 2014-06-25 23:04:38 +08:00
seven332 151c16ad83 修正带有链接的评论无选中反应,长按仍会打开链接的问题 2014-06-25 21:12:13 +08:00
seven332 07d1cc6bf6 Dialog 添加 setMessageAutoLink 2014-06-25 19:16:32 +08:00
seven332 e9bb78ebfc preview num per row 可以被禁用,限制文件名长度 2014-06-25 16:19:45 +08:00
seven332 c154f9b73a 添加 ' 至 ‘ 的转换 2014-06-23 23:12:22 +08:00
seven332 51266d4c3b 移除 OlScollView, OnLayoutListener, 使用 addOnLayoutChangeListener 2014-06-23 23:06:15 +08:00
seven332 f02998b917 添加 StableBitmapDrawable 避免预览图加载后位置大幅变化 2014-06-23 22:49:36 +08:00
seven332 b6f89741ee 添加大预览图模式 2014-06-23 22:13:28 +08:00
seven332 2498be6850 gallery list 使用简易 RatingView 以便更快加载 2014-06-23 02:02:19 +08:00
seven332 ce2907610a 更换 cache,更换图片获取方式,建立 previewlist 类,移除不需要的类 2014-06-23 00:44:20 +08:00
seven332 4e266c160c 获取并显示登陆时的错误 2014-06-22 01:45:53 +08:00
seven332 3e76680aeb 调整 Gallery Detail 获取 2014-06-22 01:28:03 +08:00
seven332 8ad331af60 移除 commons-lang 包 2014-06-22 00:55:30 +08:00
seven332 90a41a1d6b 更改登陆登出方式,可以显示头像 2014-06-22 00:21:46 +08:00
seven332 ce786f4e41 重新 HttpHelper 2014-06-21 18:20:43 +08:00
seven332 3f099969d1 调整 popular 获取与显示 2014-06-19 01:58:01 +08:00
seven332 e0acfa55eb 调整 Analytics 2014-06-18 15:06:49 +08:00
seven332 f4472005b5 修正点击次数显示错误 2014-06-17 18:42:56 +08:00
seven332 1c2263c001 添加列表模式选择 2014-06-16 21:19:41 +08:00
seven332 6f93bb5b88 添加热门点击数显示 2014-06-15 22:42:56 +08:00
seven332 1d2978952b 添加更新时间显示 2014-06-15 21:15:24 +08:00
seven332 937fc619dd 移除不必要的资源 2014-06-15 03:51:17 +08:00
seven332 30c46bd0a2 调整类别识别 2014-06-15 02:46:08 +08:00
seven332 ae90c1b2b1 changlog 2014-06-15 02:28:18 +08:00
seven332 e6e85dc8d4 添加收藏统计 2014-06-15 02:24:43 +08:00
seven332 1a1242cc47 修正翻译 2014-06-15 02:03:34 +08:00
seven332 9b34b561d8 修正时间显示 2014-06-15 02:01:20 +08:00
seven332 ee5cc24a4d 添加 popular 提示 2014-06-15 01:59:04 +08:00
seven332 6ebc172783 Add popular 2014-06-14 23:43:16 +08:00
seven332 a6237f0dc5 规范统计 2014-06-14 20:20:10 +08:00
seven332 66e2727acb 添加阅读信息获取 2014-06-14 02:14:27 +08:00
seven332 78bcb037ac 添加 Google Analytics 2014-06-14 01:49:40 +08:00
seven332 9aecbf9e66 添加默认收藏设置 2014-06-14 00:29:31 +08:00
seven332 bcba2f556b 字符串移至 string.xml 2014-06-13 22:47:24 +08:00
seven332 148f03a175 添加主题颜色设定 2014-06-13 22:01:37 +08:00
seven332 f39cfc7875 随机主题配色 2014-06-13 18:14:41 +08:00
seven332 5bc166d3da Translucent 移至 themes.xml 2014-06-13 00:15:25 +08:00
seven332 7e5a844246 修正收藏切换显示问题 2014-06-12 23:17:53 +08:00
seven332 8cecf200eb 完成账户收藏管理 2014-06-12 23:12:32 +08:00
seven332 535a6297af 注释掉关闭应用时删除文件 2014-06-11 20:19:17 +08:00
seven332 5ea2fdb651 抽象 AbstractGalleryActivity 2014-06-11 20:12:32 +08:00
seven332 bfe9044fda 更名 2014-06-10 23:41:39 +08:00
seven332 d277066d34 更改 Toast 颜色 2014-06-10 23:39:45 +08:00
seven332 cbbe1478ae 收藏界面添加返回键隐藏 ActionableToastBar 2014-06-10 22:52:22 +08:00
seven332 8848e712cc 调整 SuperToast 布局,使其不会横向占满屏幕 2014-06-10 12:50:15 +08:00
seven332 ed693d1742 更新 SuperSwipeRefreshLayout 对 paddingTop 判断方式,并修正其对滑动判断错误 2014-06-10 11:18:04 +08:00
seven332 626def198c 修正以匹配服务器的 json 格式 2014-06-10 08:31:43 +08:00
seven332 b9fc9b054b 更新检查地址改为 http://www.ehviewer.com/API 2014-06-10 08:23:59 +08:00
seven332 602f68e88b dialog 中 message 居中 2014-06-10 00:45:04 +08:00
seven332 dfa00b7605 将 Toast 换为 SuperToast 2014-06-10 00:34:58 +08:00
seven332 27cb0aa260 添加 SuperToast 2014-06-07 02:57:09 +08:00
seven332 416d080eb4 添加 ActionableToastBar 2014-06-07 02:03:26 +08:00
seven332 386c98575d 允许 HfListView 启用或禁用 Header 或 Footer 2014-06-05 23:06:09 +08:00
seven332 84f9aef856 使 SwipeProgressBar 在 paddingTop 不为 0 时正确显示 2014-06-05 20:17:25 +08:00
seven332 13cbb7507e 初步完成收藏 2014-06-05 19:18:59 +08:00
seven332 4a1594f982 调整 list 获取 2014-05-30 20:10:05 +08:00
seven332 761ce507f1 简化字符串 2014-05-30 15:27:01 +08:00
seven332 67884ed9d3 修正媒体扫描错误 2014-05-30 14:40:16 +08:00
seven332 12412d67fb 添加新的缓存管理 2014-05-30 12:29:25 +08:00
seven332 2c58f6c9ae 添加收藏夹批处理 2014-05-30 00:22:57 +08:00
seven332 65e908546b 修正 sad panda 识别 2014-05-29 22:01:40 +08:00
seven332 ea18b8c090 调整 List 获取 2014-05-29 20:39:03 +08:00
seven332 6c182f3bba 添加 ex test 2014-05-28 23:28:52 +08:00
seven332 807c49eea1 Detail Activity ActionBar Translucent 2014-05-28 22:33:38 +08:00
seven332 50dd19222e 添加 Detail Info 显示 2014-05-28 21:33:32 +08:00
seven332 b5bbf19a65 扩充 DetailParser 2014-05-28 20:43:46 +08:00
seven332 9ed06be68b 预先获取 density 2014-05-28 01:19:26 +08:00
seven332 9da0c76da6 调整 preview panel button 背景 2014-05-26 18:01:58 +08:00
seven332 1b06d19059 增加添加至服务器收藏 2014-05-25 23:30:05 +08:00
seven332 e258617c23 Add idear 2014-05-25 22:29:15 +08:00
seven332 839a7227ab 移除可能产生卡顿的不必要操作 2014-05-25 20:27:39 +08:00
seven332 f49b111e15 调整 action bar tag 背景 2014-05-25 17:12:51 +08:00
seven332 d5d6b6fb4c 添加一种列表搜索方式 2014-05-25 15:03:45 +08:00
seven332 7cc794d614 修正 changelog 错误 2014-05-25 14:46:03 +08:00
seven332 f209f5f157 解决 Custom Dialog 标题过长时与 Action Drawable 的冲突 2014-05-24 22:12:54 +08:00
seven332 ca4be438c5 changelog 2014-05-24 22:06:36 +08:00
seven332 d9411b190c 修正无法取消内容警告的错误 2014-05-24 21:49:09 +08:00
seven332 ec2cb356c1 添加 AbstractActivity 2014-05-24 17:55:59 +08:00
seven332 15a2db978c 添加自动更新设置 2014-05-24 17:44:26 +08:00
seven332 a9506b1f53 修正设置中检查更新的 key 错误 2014-05-24 16:32:23 +08:00
seven332 1a8f6752c7 SettingActivity actionbar 添加返回 2014-05-24 01:50:34 +08:00
seven332 637579db5c SettingActivity 为不同 fragment 设置不同 actionbar icon 2014-05-24 00:52:45 +08:00
seven332 534c5506e6 com.hippo.ehviewer.activity 改为 com.hippo.ehviewer.ui 2014-05-23 23:44:08 +08:00
seven332 a2182e0f05 添加 AbstractActivity 2014-05-23 23:34:27 +08:00
seven332 0d0153c6e8 添加 github 入口 2014-05-23 20:17:40 +08:00
seven332 ca6281bf72 调整 SettingActivity 中 padding bottom 2014-05-23 19:06:50 +08:00
seven332 a50df7308f 添加 Copyright 2014-05-23 18:43:48 +08:00
seven332 d31a51ab9a 添加 Copyright 2014-05-23 16:38:32 +08:00
seven332 91aa31503b 删除历史代码 2014-05-23 15:28:21 +08:00
seven332 a5e07a0ebe 选择路径中允许添加路径 2014-05-23 15:02:25 +08:00
seven332 cfa51276bd 调整 FileExplorerView item 布局 2014-05-23 14:25:50 +08:00
seven332 148470e4be SettingsActivity 使用 fragment 2014-05-23 14:18:40 +08:00
seven332 fd72fbf9bd 调整搜索面板类别选择布局 2014-05-21 21:14:32 +08:00
seven332 b37087a69d FileExplorerView 排序忽略大小写 2014-05-20 12:57:56 +08:00
seven332 ec1694347a 部分完成下载路径设置 2014-05-20 12:52:23 +08:00
seven332 a89b001370 替换 settings 图标 2014-05-19 22:43:55 +08:00
seven332 867a0f4ef7 修正标签存储错误 2014-05-19 17:09:20 +08:00
seven332 fee7d87a21 添加小尺寸图标 2014-05-18 21:40:55 +08:00
seven332 ffd0ca0cec change log 2014-05-18 16:17:18 +08:00
seven332 7d819d4ac6 完善 strings.xml 2014-05-18 16:15:54 +08:00
seven332 e08ee26991 change log 2014-05-18 16:10:22 +08:00
seven332 599649200c 未完成的功能添加提示 2014-05-18 16:05:57 +08:00
seven332 4e4c670c97 完成由 comment 搜索发言用户上传 2014-05-18 16:01:48 +08:00
seven332 1def607a80 添加标签跳转搜索 2014-05-18 15:47:31 +08:00
seven332 5bee5d6663 换行符总出错 2014-05-18 15:09:55 +08:00
seven332 834b9b7a2a 修正 GalleryView 中在 onLayout 之前触摸可产生的错误 2014-05-18 14:52:12 +08:00
seven332 4e7bb7aec3 修正登陆窗口弹出 2014-05-18 14:39:41 +08:00
seven332 f4c73e3b32 完善 Detail 界面下载 2014-05-18 14:25:01 +08:00
seven332 bb6f8ded7f 完成 Data 中对 ListUrls tag 模式的支持 2014-05-18 03:27:48 +08:00
seven332 e7753fddec 修正 ModifyTag 时新加 advance 时显示错误 2014-05-18 03:04:05 +08:00
seven332 29e77faec9 DialogBuild 添加 Action,ListUrls 添加 tag 模式 2014-05-18 02:42:23 +08:00
seven332 e0cc198d96 添加更加 uploader 搜索 2014-05-17 23:53:03 +08:00
seven332 cc9d194ddd 修正预览图翻页错误 2014-05-17 21:13:37 +08:00
seven332 0735fa2425 comment 使用 Linkify 2014-05-17 16:04:38 +08:00
seven332 d8fc3f0a51 移动部分 String 至 strings.xml 2014-05-17 15:18:39 +08:00
seven332 c47f124854 完善模式选择 2014-05-17 15:06:12 +08:00
seven332 7dba58b1aa 调整列表界面菜单 2014-05-16 22:50:52 +08:00
seven332 5f34b5aeb0 完善用户面板 2014-05-16 22:27:48 +08:00
seven332 7470a25cbe CheckTextView 替换 CheckImage 2014-05-16 21:12:26 +08:00
seven332 28b31d3439 AutoWrapLayout 的 baseline 属性改名为 alignment 2014-05-16 16:55:39 +08:00
seven332 97d855b546 移除不必要的文件 2014-05-16 16:43:59 +08:00
seven332 711564a0ab 将 FswView 的 visibility 默认设为 gone 2014-05-15 22:13:56 +08:00
seven332 f20bc2c954 修改换行符为 LF 2014-05-15 20:23:11 +08:00
seven332 ed0702068c 调整 refresh color 顺序,使其更自然 2014-05-15 20:15:17 +08:00
seven332 b568082c2d 将 ActionBarPullToRefresh 替换为 SwipRefreshLayout 2014-05-15 19:59:51 +08:00
seven332 f89ae0d1b1 调整 ActionBarPull 参数,更便于操作 2014-05-15 13:49:47 +08:00
seven332 d2c4cf598a 添加 README.md 2014-05-14 21:41:45 +08:00
seven332 f9ceddfabf just fix 2014-05-14 20:18:07 +08:00
seven332 cec40a8f89 更新 changelog 2014-05-12 22:42:15 +08:00
seven332 4a4ec2312a 部分完善用户面板 2014-05-12 20:38:39 +08:00
seven332 5417918382 使用 TextSwitcher 替代 ProgressiveTextView 2014-05-12 02:17:19 +08:00
seven332 f8b2b46172 删除不必要的文件 2014-05-12 01:02:49 +08:00
seven332 d0f07ae62b 修正 preview 自动 2014-05-11 23:24:39 +08:00
seven332 5d7b99e328 修正返回图标 2014-05-11 16:56:13 +08:00
seven332 ae563a7950 comment dialog 中使用更好的 layout 2014-05-11 02:15:49 +08:00
seven332 1f6668cd8c 当 preview 信息已有时也跳至 preview 顶部 2014-05-11 01:08:04 +08:00
seven332 24a384eed7 当获取新 preview 大小时,自动使其最大显示 2014-05-11 00:17:57 +08:00
seven332 b5eeee9b73 完善 ActionBarTab style 2014-05-10 23:27:14 +08:00
seven332 1bd32d97de 初步完成 detail url 接管 2014-05-10 14:52:44 +08:00
seven332 5e6d771dad 调整菜单 2014-05-10 02:58:04 +08:00
seven332 9b80be453c 添加评论查看与发送功能,评论按发布时间排序 2014-05-10 00:08:34 +08:00
seven332 7d0bfc1aa7 添加评论显示 2014-05-09 17:07:50 +08:00
seven332 3d31c32d40 修正由于 Activity 正在关闭后再对 view 修改可能造成的错误 2014-05-09 11:20:27 +08:00
seven332 087a6ee305 添加 详情 tab 2014-05-09 11:17:21 +08:00
seven332 9056d7ced0 搜索标签移至右侧栏 2014-05-08 23:41:40 +08:00
seven332 4a8e01caec 修正语言搜索,完善 search bar 资源 2014-05-08 21:55:59 +08:00
seven332 1088729269 优化 list_item 布局 2014-05-08 20:42:29 +08:00
seven332 21ac176f5f 改用及时响应的 ratingbar,初步添加用户面板 2014-05-08 19:33:50 +08:00
seven332 b3cc1dec4b 创建 ProgressiveTextView,用来简易的显示 TextView 的字符串替换效果 2014-05-08 00:18:15 +08:00
seven332 3da180beb0 添加 tag 投票数显示 2014-05-07 21:41:54 +08:00
seven332 acec30ae5a 完善 vote 功能 2014-05-07 20:29:44 +08:00
seven332 8229007710 完善 gallery 评分 view 2014-05-07 19:16:04 +08:00
seven332 80e0432c73 修正 ratingbar 2014-05-07 16:59:03 +08:00
seven332 c97dccaf04 添加 vote 2014-05-07 01:23:46 +08:00
seven332 f4bdbe1ed1 修正 search bar style 2014-05-07 01:01:49 +08:00
seven332 75a67ae54e 修正列表 2014-05-06 18:28:20 +08:00
seven332 61c3144a48 修正列表 2014-05-06 18:26:09 +08:00
seven332 8158bae9d5 优化列表 2014-05-06 16:45:09 +08:00
seven332 9615aa0b7c 完善界面,修正列表显示 2014-05-06 00:41:35 +08:00
seven332 870153ef88 Just project 2014-05-05 20:00:56 +08:00
seven332 741203ab81 Remove duplicated directory 2014-05-05 19:56:26 +08:00
seven332 0b74bf3fc3 完善界面 2014-05-05 19:28:29 +08:00
seven332 f5f7489093 改用 ActionBar Pull 2014-05-04 22:24:23 +08:00
seven332 05dae37a28 修正 pullListView 2014-05-03 13:48:31 +08:00
seven332 1384a05830 部分优化 2014-05-03 00:10:49 +08:00
seven332 256b4896cb 完善界面 2014-05-01 20:05:09 +08:00
seven332 c44011402f 部分调整详情界面 2014-04-30 00:37:20 +08:00
seven332 eff24ca4b3 部分规范化界面 2014-04-28 22:37:32 +08:00
seven332 8f16044c6b check curShowItem null 2014-04-26 16:02:06 +08:00
seven332 7c46027bd6 dev 2014-04-26 15:47:15 +08:00
seven332 5f7b677db7 wocaocao 2014-04-26 15:45:15 +08:00
seven332 b27e02fed1 unknown 2014-04-26 15:28:42 +08:00
seven332 abe2189acd 调整文件位置 2014-04-14 22:37:07 +08:00
seven332 721659d959 Download sql 2014-04-14 22:32:45 +08:00
seven332 d2e083922e 使用数据库存储 local favourite 2014-04-13 15:49:23 +08:00
seven332 34181ce370 略 2014-04-12 14:13:21 +08:00
seven332 a939c505f9 添加 ActionBar 效果 2014-04-10 23:28:39 +08:00
seven332 5de9fc8134 添加封面图片渐进效果显示 2014-04-08 22:51:40 +08:00
seven332 0c45ddf04d 添加 够快 更新服务器 2014-04-08 22:03:39 +08:00
seven332 74e37ea72d 修改手势,字符串 2014-04-07 11:23:46 +08:00
seven332 c6c060b5e2 0.4.4 2014-04-06 13:49:54 +08:00
seven332 def283de08 添加 charset 识别 2014-04-06 13:45:52 +08:00
seven332 be3d3189ec 学习使用 ProGuard 2014-04-06 11:30:40 +08:00
seven332 0581b7cc53 使用更安全的 Log 2014-04-06 11:11:57 +08:00
seven332 79b75e5de1 0.4.3 2014-04-05 23:57:52 +08:00
seven332 f7be9dec18 添加更新服务器选择 2014-04-05 23:51:48 +08:00
seven332 566226958f 临时解决 endIndex 大于 size 的问题 2014-04-05 23:15:07 +08:00
seven332 e45db97a54 用 json 检查更新 2014-04-05 22:28:45 +08:00
seven332 ea58ffed74 用 json 检查更新 2014-04-05 22:28:11 +08:00
seven332 eb1e49e7c7 更丰富的错误提示 2014-04-05 00:08:10 +08:00
seven332 b69c71a54b 0.4.2 2014-04-04 23:26:37 +08:00
seven332 3aff219639 修正由于 gif 格式图片导致的崩溃 2014-04-04 23:13:33 +08:00
seven332 e1edd00fb0 继续 2014-04-03 20:16:34 +08:00
seven332 70e0aada25 调整EhClient 2014-04-03 19:28:57 +08:00
seven332 1c11ac38ea 添加内置存储空间或 Sd Card 检测 2014-04-02 19:56:49 +08:00
seven332 7ac8878f83 修正网络错误时进入详情界面应用崩溃 2014-04-02 13:05:22 +08:00
seven332 a48a18ba84 0.4.1 2014-04-02 12:54:21 +08:00
seven332 8a2a2061a9 添加断点下载 2014-04-01 21:37:27 +08:00
seven332 b1f772eb2f 修正单点触控缩放错误 2014-04-01 11:39:02 +08:00
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
seven332 ab4b4ad598 修正图片多次加载错误 2014-03-23 23:12:15 +08:00
seven332 626f7141e9 添加漫画TAG显示 2014-03-23 22:43:30 +08:00
seven332 30c7ac5100 使用自己写的换行控件,onMeasure 有必要修改 2014-03-23 20:50:37 +08:00
seven332 b30489785f 上个保存有错误 2014-03-23 16:48:55 +08:00
seven332 22e042d11d 修正选择发送方式会被下个 Activity 掩盖错误。 2014-03-23 16:48:28 +08:00
seven332 6137e851cd 添加检测登陆状态按钮 2014-03-23 16:26:04 +08:00
seven332 57419fd8d1 添加列表图片加载栈,添加 httpHelper 类,以后完善 2014-03-23 16:00:27 +08:00
seven332 471962e664 自动更新 2014-03-23 10:14:47 +08:00
seven332 7254d9d7a7 修正由于没有上锁导致的disklru清除错误 2014-03-23 10:13:59 +08:00
seven332 ea2418b981 改用 drawerlayout 修改版的侧边栏 2014-03-22 23:03:14 +08:00
seven332 5c4009e435 完成启动界面,自己写的下拉控件 2014-03-21 23:43:51 +08:00
seven332 89c7beda26 添加启动界面,使用自己的滑动控件,完成一大半,明天继续。 2014-03-21 00:51:47 +08:00
seven332 c6109bd0d4 非 ongoing 通知栏点击后消除 2014-03-14 21:14:13 +08:00
seven332 15d6e4f87c 修复点击状态栏不显示下载界面 2014-03-14 14:04:48 +08:00
seven332 7cfd910122 dev download almost completed 2014-03-14 13:04:10 +08:00
seven332 c67619d54c dev 2014.03.13 2014-03-13 23:33:42 +08:00
seven332 38ec446130 dev 2014.03.12 2014-03-12 00:11:11 +08:00
seven332 60a5fd2443 dev download manager 2014-03-11 22:19:02 +08:00
seven332 f8907c6e8f 修正搜索标签重命名错误 2014-03-11 12:54:22 +08:00
seven332 61e318fb6e add other 2014-03-11 11:11:23 +08:00
seven332 1382a83648 add lib 2014-03-11 11:10:32 +08:00
1141 changed files with 26003 additions and 47264 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="com.android.toolchain.gcc.1322280913">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="com.android.toolchain.gcc.1322280913" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.VCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="${ProjName}" buildProperties="" description="" id="com.android.toolchain.gcc.1322280913" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="com.android.toolchain.gcc.1322280913.1369823253" name="/" resourcePath="">
<toolChain id="com.android.toolchain.gcc.803500692" name="Android GCC" superClass="com.android.toolchain.gcc">
<targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="com.android.targetPlatform.1260474165" isAbstract="false" superClass="com.android.targetPlatform"/>
<builder arguments="NDK_DEBUG=0" command="ndk-build" enableCleanBuild="false" id="com.android.builder.2127875218" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Android Builder" superClass="com.android.builder">
<outputEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="outputPath" name="obj"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="outputPath" name="libs"/>
</outputEntries>
</builder>
<tool id="com.android.gcc.compiler.877935514" name="Android GCC Compiler" superClass="com.android.gcc.compiler">
<inputType id="com.android.gcc.inputType.68370901" superClass="com.android.gcc.inputType"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="jni"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="EhViewer.null.1834465747" name="EhViewer"/>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
<scannerConfigBuildInfo instanceId="com.android.toolchain.gcc.1322280913;com.android.toolchain.gcc.1322280913.1369823253;com.android.gcc.compiler.877935514;com.android.gcc.inputType.68370901">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="com.android.AndroidPerProjectProfile"/>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/EhViewer"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
</cproject>
-8
View File
@@ -1,8 +0,0 @@
.gradle
/local.properties
.DS_Store
/build
/src
*.iml
.idea
/captures
+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>EhViewer</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
@@ -14,9 +14,14 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer"
android:versionCode="24"
android:versionName="0.6.3" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -28,17 +33,15 @@
android:allowBackup="true"
android:hardwareAccelerated="true"
android:largeHeap="true"
android:supportsRtl="true"
android:icon="@mipmap/ic_launcher"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme.Normal">
android:theme="@style/AppTheme.Normal" >
<activity
android:name=".StartActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar.Transparent.Translucent" >
android:theme="@style/AppTheme.NoActionBar.Transparent" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -47,7 +50,7 @@
<activity
android:name=".ui.GalleryListActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:label="@string/app_name"
android:launchMode="singleTop"
android:screenOrientation="behind"
@@ -60,18 +63,9 @@
android:resource="@xml/searchable" />
</activity>
<activity
android:name=".ui.WebViewLoginActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/login"
android:screenOrientation="behind"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
android:theme="@style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".ui.GalleryDetailActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:screenOrientation="behind"
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden" >
<intent-filter>
@@ -79,7 +73,6 @@
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="exhentai.org" />
<data android:host="g.e-hentai.org" />
<data android:host="lofi.e-hentai.org" />
@@ -89,37 +82,32 @@
<activity
android:name=".ui.GalleryActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:screenOrientation="behind"
android:theme="@style/AppTheme.Dark.NoActionBar" >
android:theme="@style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".ui.SettingsActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:icon="@drawable/ic_action_settings"
android:label="@string/preference_settings_title"
android:screenOrientation="behind" >
</activity>
<activity
android:name=".ui.FavouriteActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:icon="@drawable/ic_action_favorite"
android:label="@string/favourite"
android:screenOrientation="behind"
android:theme="@style/AppTheme.ListActivity" >
</activity>
<activity
android:name=".ui.HistoryActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/history"
android:screenOrientation="behind"
android:theme="@style/AppTheme.ListActivity" >
</activity>
<activity
android:name=".ui.DownloadActivity"
android:configChanges="orientation|screenSize|uiMode"
android:configChanges="orientation|screenSize"
android:icon="@drawable/ic_setting_download"
android:label="@string/download"
android:launchMode="singleTask"
android:screenOrientation="behind"
@@ -129,45 +117,9 @@
android:value=".ui.GalleryListActivity" />
</activity>
<activity
android:name=".ui.SecretActivity"
android:configChanges="orientation|screenSize|uiMode"
android:screenOrientation="behind"
android:theme="@style/AppTheme.NoActionBar.Transparent" >
</activity>
<activity
android:name=".ui.PatternProtectionActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" >
</activity>
<activity
android:name=".ui.EnterPatternActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" >
</activity>
<service
android:name=".service.DownloadService"
android:label="DownloadService" />
<provider
android:name=".SimpleSuggestionProvider"
android:authorities="com.hippo.ehviewer.SimpleSuggestionProvider"
android:exported="false" />
<receiver android:name=".receiver.RestPatternReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SECRET_CODE"/>
<data android:scheme="android_secret_code" android:host="110722"/>
</intent-filter>
</receiver>
</application>
</manifest>
</manifest>
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="EhViewer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="java-gradle" name="Java-Gradle">
<configuration>
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
<option name="BUILDABLE" value="false" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+4 -61
View File
@@ -1,70 +1,13 @@
# EhViewer
这是一个 Android 平台上的 E-Hentai 阅读应用。访问 [EhViewer](http://www.ehviewer.com/) 网站以获取更多信息。<br>
EhViewer is an E-Hentai Application for Android. Visit [EhViewer](http://www.ehviewer.com/)(Chinese Only) website for more information.
# Build
导入 Android Studio 即可。<br>
Just import into Android Studio.
# Thanks
- [android-gif-drawable](https://github.com/koral--/android-gif-drawable)
- 参考 gif 解码
- [ActionBar-PullToRefresh](https://github.com/chrisbanes/ActionBar-PullToRefresh)
- 曾作为刷新控件
- [ActionBarSherlocke](https://github.com/JakeWharton/ActionBarSherlock)
- 曾用来对 4.0 一些系统兼容
- [Android-PullToRefresh](https://github.com/chrisbanes/Android-PullToRefresh)
- 曾作为刷新控件
- [AndroidStaggeredGrid](https://github.com/etsy/AndroidStaggeredGrid)
- 列表控件
- [Apollo-CM](https://github.com/adneal/Apollo-CM)
- 缓存机制
- [DiskLruCache](https://github.com/JakeWharton/DiskLruCache)
- 缓存机制
- [FloatingActionButton](https://github.com/FaizMalkani/FloatingActionButton)
- 按钮控件
- [GIFLIB](http://giflib.sourceforge.net)
- gif 解码
- [Gloria Hallelujah](https://www.google.com/fonts/specimen/Gloria+Hallelujah)
- 启动界面字体
- [ImageLoadingPattern](https://github.com/rnrneverdies/ImageLoadingPattern)
- 图片过渡效果
- [libjpeg-turbo](http://www.libjpeg-turbo.org)
- jpge 解码
- [libpng](http://www.libpng.org/pub/png/libpng.html)
- png 解码
- [material-menu](https://github.com/balysv/material-menu)
- 抽屉指示器
- [OpenCC](https://github.com/BYVoid/OpenCC)
- 繁化工作
- [Slabo](https://github.com/TiroTypeworks/Slabo)
- 图标字体
- [SlidingMenu](https://github.com/jfeinstein10/SlidingMenu)
- 曾作为抽屉控件
- [source-code-pro](https://github.com/adobe/source-code-pro)
- 刷新控件字体
- [svg-android](https://code.google.com/p/svg-android/)
- svg 解析
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
- 状态栏背景设置
- [twoway-view](https://github.com/lucasr/twoway-view)
- RecyclerView 使用方法
- [zlib](http://www.zlib.net)
- 辅助 png 解码
- [Android Open Source Project](http://source.android.com)
- 很多很多
- [commons-lang](http://commons.apache.org/proper/commons-lang)
- 很多很多
这是一个 Android 平台上的 E-Hentai 阅读应用。<br>
E-Hentai Application for Android.
# License
本项目内容采用 [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) 授权,
部分文件采用 [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) 授权([列表](rc/list1)),
部分文件采用 [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) 授权([列表](rc/list2))。
<br>
部分文件可随意使用([列表](rc/list2))。<br>
The content of this project itself is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0),
some files are licensed under the [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) ([list](rc/list1)),
some files are licensed under the [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) ([list](rc/list2)).
some files are free to use ([list](rc/list2)).
-3
View File
@@ -1,3 +0,0 @@
/build
/src/main/obj
/src/main/libs
-111
View File
@@ -1,111 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EhViewer" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":app" />
</configuration>
</facet>
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<afterSyncTasks>
<task>generateDebugSources</task>
</afterSyncTasks>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/recyclerview-v7/22.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/22.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-safeguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/instant-run-support" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
<orderEntry type="library" exported="" name="support-v4-22.2.1" level="project" />
<orderEntry type="library" exported="" name="recyclerview-v7-22.2.1" level="project" />
<orderEntry type="library" exported="" name="support-annotations-22.2.1" level="project" />
<orderEntry type="module" module-name="vector" exported="" />
</component>
</module>
-72
View File
@@ -1,72 +0,0 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 22
versionCode 47
versionName "0.6.16.3"
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
// Disable default NdkCompile task
// Set new jni lib dir
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDir 'src/main/libs'
}
// noinspection GroovyAssignabilityCheck
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
def ndkBuilder
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
ndkBuilder = 'ndk-build.cmd'
} else {
ndkBuilder = 'ndk-build'
}
commandLine "$ndkDir\\$ndkBuilder",
'-C', file('src/main').absolutePath,
'NDK_DEBUG=0',
'NDK_TOOLCHAIN_VERSION=clang',
'-j4'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
clean {
delete file('src/main/obj').absolutePath
delete file('src/main/libs').absolutePath
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':vector')
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:recyclerview-v7:22.2.1'
}
Binary file not shown.
-55
View File
@@ -1,55 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in E:\Android\android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keepattributes SourceFile,LineNumberTable
-keep class com.hippo.ehviewer.widget.SearchView {*;}
-keep class com.hippo.ehviewer.gallery.image.Image {*;}
-keep class com.hippo.ehviewer.gallery.image.GifImage {*;}
-keepclassmembers class com.hippo.ehviewer.drawable.MaterialProgressDrawable$Ring {
void set*(***);
*** get*();
}
-keepclassmembers class * extends com.hippo.ehviewer.windowsanimate.Sprite {
void set*(***);
*** get*();
}
-keepclassmembers class * extends android.graphics.drawable.Drawable {
void set*(***);
*** get*();
}
-keepclassmembers class com.hippo.ehviewer.effect.ripple.Ripple {
void set*(***);
*** get*();
}
-keepclassmembers class com.hippo.ehviewer.effect.ripple.RippleBackground {
void set*(***);
*** get*();
}
# For VectorResources
-keep class android.content.res.VectorResources {*;}
# I want to track the error in them
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
@@ -1,13 +0,0 @@
package com.hippo.ehviewer;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
Binary file not shown.
Binary file not shown.
@@ -1,179 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.view.ContextThemeWrapper;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.ehclient.EhClient;
import com.hippo.ehviewer.ehclient.EhInfo;
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.util.EhUtils;
import com.hippo.ehviewer.util.Log;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.Utils;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.MaterialToast;
import com.hippo.ehviewer.widget.SlidingDrawerLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
public class AppContext extends Application implements UncaughtExceptionHandler {
@SuppressWarnings("unused")
private static final String TAG = AppContext.class.getSimpleName();
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Typeface mFaceTypeface;
@Override
public void onCreate() {
super.onCreate();
// Do catch error prepare
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
Context mContextThemeWrapper = new ContextThemeWrapper(this, R.style.AppTheme);
ViewUtils.initDialogViewInflater(this);
// Init everything
Ui.init(mContextThemeWrapper);
Config.init(mContextThemeWrapper);
Log.init(mContextThemeWrapper);
Crash.init(mContextThemeWrapper);
EhClient.createInstance(mContextThemeWrapper);
FavoriteHelper.init(mContextThemeWrapper);
Data.createInstance(mContextThemeWrapper);
ExDownloaderManager.createInstance(mContextThemeWrapper);
MaterialToast.setContext(mContextThemeWrapper);
mFaceTypeface = Typeface.createFromAsset(getAssets(),"fonts/face.ttf");
// Set drawer margin
SlidingDrawerLayout.setDefaultMinDrawerMargin(Ui.ACTION_BAR_HEIGHT * 2);
// Add .nomedia or delete it
File nomedia = new File(Config.getDownloadPath(), ".nomedia");
if (Config.getMediaScan()) {
nomedia.delete();
} else {
try {
new FileOutputStream(nomedia).close();
} catch (IOException e) {}
}
// Update proxy urls
HttpHelper.updateProxyUrls(mContextThemeWrapper);
String keyVersionCode = "version_code";
int oldVersion = Config.getInt(keyVersionCode, Integer.MAX_VALUE);
// Fix <=22 login error
if (oldVersion <= 22)
EhInfo.getInstance(mContextThemeWrapper).logout();
// Fix <=25 Update
if (oldVersion <= 25) {
File downloadDir = new File(Config.getDownloadPath());
String cachePath = getExternalCacheDir() != null
? getExternalCacheDir().getPath()
: getCacheDir().getPath();
File oldEdInfoDir = new File(cachePath, "ExDownloaderManager");
String[] list = downloadDir.list();
if (list != null && list.length != 0) {
for (String str : list) {
int index = str.indexOf('-');
if (index == -1)
continue;
String gid = str.substring(0, index);
File gDir = new File(downloadDir, str);
// Move download info file
File oldInfoFile = new File(oldEdInfoDir, gid);
File newInfoFile = new File(gDir, EhUtils.EH_DOWNLOAD_FILENAME);
if (!oldInfoFile.exists())
continue;
try {
FileOutputStream fos = new FileOutputStream(newInfoFile);
// Add last page
byte[] bs = {'0', '0', '0', '0', '0', '0', '0', '0', '\n'};
fos.write(bs);
Utils.copy(new FileInputStream(oldInfoFile), fos);
} catch (Throwable e) {
continue;
}
}
}
// Delete old exdownload info dir
Utils.deleteDirInThread(oldEdInfoDir);
}
// Update version code
try {
PackageInfo pi= getPackageManager().getPackageInfo(getPackageName(), 0);
Config.setInt(keyVersionCode, pi.versionCode);
} catch (NameNotFoundException e) {}
}
/**
* {@inheritDoc}
*/
@Override
public void onLowMemory() {
ImageCache.getImageCache(this).clearMemory();
super.onLowMemory();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
try {
Crash.saveCrashInfo2File(ex);
return true;
} catch (Throwable tr) {
return false;
}
}
public Typeface getFaceTypeface() {
return mFaceTypeface;
}
}
@@ -1,28 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.content.SearchRecentSuggestionsProvider;
public class SimpleSuggestionProvider extends SearchRecentSuggestionsProvider {
public final static String AUTHORITY = "com.hippo.ehviewer.SimpleSuggestionProvider";
public final static int MODE = DATABASE_MODE_QUERIES;
public SimpleSuggestionProvider() {
setupSuggestions(AUTHORITY, MODE);
}
}
@@ -1,281 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
import com.hippo.ehviewer.network.Network;
import com.hippo.ehviewer.ui.AbsActivity;
import com.hippo.ehviewer.ui.EnterPatternActivity;
import com.hippo.ehviewer.ui.GalleryListActivity;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.util.Secret;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.LockPatternUtils;
import com.hippo.ehviewer.widget.SimpleImageView;
import com.hippo.vector.VectorDrawable;
public class StartActivity extends AbsActivity {
@SuppressWarnings("unused")
private static final String TAG = StartActivity.class.getSimpleName();
private static final int REQUEST_CODE_PATTERN = 0;
private static final int CHECK_WARING = 0;
private static final int CHECK_ANALYTICS = 1;
private static final int CHECK_NETWORK = 2;
private static final int CHECK_CRASH = 3;
private static final String KEY_ALLOWED = "allowed";
private static final String KEY_SET_ANALYTICS = "set_analyics";
private String lastCrash;
private boolean isEnterPattern = false;
private boolean isAnimationOver = false;
private boolean isCheckOver = false;
private MaterialAlertDialog createWarningDialog() {
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dailog_waring_title)
.setMessage(R.string.dailog_waring_plain)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
Config.setBoolean(KEY_ALLOWED, true);
check(CHECK_ANALYTICS);
break;
case MaterialAlertDialog.NEGATIVE:
finish();
break;
}
return true;
}
}).create();
}
private AlertDialog createAllowAnalyicsDialog() {
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dailog_analyics_title)
.setMessageAutoLink(Linkify.WEB_URLS)
.setMessage(R.string.dailog_analyics_plain)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
Config.setAllowAnalyics(true);
check(CHECK_NETWORK);
break;
case MaterialAlertDialog.NEGATIVE:
Config.setAllowAnalyics(false);
check(CHECK_NETWORK);
break;
}
return true;
}
}).create();
}
private AlertDialog createNetworkDialog(int state) {
int mesgId;
switch (state) {
case Network.NETWORK_STATE_MOBILE:
mesgId = R.string.dailog_network_mobile_title;
break;
case Network.NETWORK_STATE_NONE:
default:
mesgId = R.string.dailog_network_none_title;
break;
}
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.warning).setMessage(mesgId)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
check(CHECK_CRASH);
break;
case MaterialAlertDialog.NEGATIVE:
finish();
break;
}
return true;
}
}).create();
}
private AlertDialog createSendCrashDialog() {
View view = ViewUtils.inflateDialogView(R.layout.send_crash, false);
final EditText et = (EditText) view.findViewById(R.id.description_of_user);
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dialog_send_crash_title)
.setView(view, true)
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
// A wait dialog
new MaterialAlertDialog.Builder(StartActivity.this)
.setCancelable(false)
.setTitle(R.string.wait)
.setMessage(R.string.dialog_wait_send_crash_msg)
.setPositiveButton(android.R.string.ok)
.setButtonListener(
new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
checkOver();
return true;
}
}).show();
ActivityHelper.sendEmail(StartActivity.this, "ehviewersu@gmail.com", "I found a bug in EhViewer !", lastCrash + "======== Description ========\n" + et.getText().toString());
lastCrash = null;
break;
case MaterialAlertDialog.NEGATIVE:
lastCrash = null;
checkOver();
break;
}
return true;
}
}).create();
}
@Override
public void onCreate(Bundle savedInstanceState) {
// Disable animate
overridePendingTransition(0, 0);
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
TextView text = (TextView) findViewById(R.id.text);
text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/GloriaHallelujah.ttf"));
SimpleImageView image = (SimpleImageView) findViewById(R.id.image);
image.setDrawable(VectorDrawable.create(this, R.drawable.sad_pandroid));
// Update secret image here
int state = Network.getNetworkState(this);
if (state == Network.NETWORK_STATE_WIFI) {
Secret.updateSecretImage(this);
}
AppHandler.getInstance().postDelayed(new Runnable() {
@Override
public void run() {
if (!StartActivity.this.isFinishing()) {
if (isCheckOver && isEnterPattern)
redirectTo();
isAnimationOver = true;
}
}
}, 3000);
check(CHECK_WARING);
// Enter Pattern
String pattern = Config.getPatternProtection();
if (LockPatternUtils.isPatternVaild(pattern)) {
// Start activity to enter pattern
Intent intent = new Intent(this, EnterPatternActivity.class);
startActivityForResult(intent, REQUEST_CODE_PATTERN);
} else {
isEnterPattern = true;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PATTERN) {
if (resultCode == RESULT_OK) {
if (isAnimationOver && isCheckOver)
redirectTo();
isEnterPattern = true;
} else {
finish();
}
}
}
/**
* Order is 1. check waring 2. check analyics 3. check network 4. check
* crash 5. check external storage
*
* @param order
*/
private void check(int order) {
switch (order) {
case CHECK_WARING:
if (!Config.getBoolean(KEY_ALLOWED, false)) {
createWarningDialog().show();
return;
}
case CHECK_ANALYTICS:
if (!Config.getBoolean(KEY_SET_ANALYTICS, false)) {
Config.setBoolean(KEY_SET_ANALYTICS, true);
createAllowAnalyicsDialog().show();
return;
}
case CHECK_NETWORK:
int state = Network.getNetworkState(this);
if (state != Network.NETWORK_STATE_WIFI) {
createNetworkDialog(state).show();
return;
}
case CHECK_CRASH:
if ((lastCrash = Crash.getLastCrash()) != null) {
createSendCrashDialog().show();
return;
}
}
checkOver();
}
private void checkOver() {
if (isAnimationOver && isEnterPattern)
redirectTo();
isCheckOver = true;
}
private void redirectTo() {
Intent intent = new Intent(this, GalleryListActivity.class);
startActivity(intent);
finish();
}
}
@@ -1,82 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.app;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.FileExplorerView;
public class DirSelectDialog extends MaterialAlertDialog {
private final FileExplorerView mFileExplorerView;
protected DirSelectDialog(Builder builder, FileExplorerView fileExplorerView) {
super(builder);
mFileExplorerView = fileExplorerView;
}
public static DirSelectDialog create(Builder builder, String path) {
View view = ViewUtils.inflateDialogView(R.layout.dir_selection, builder.mDarkTheme);
final FileExplorerView fileExplorerView = (FileExplorerView) view.findViewById(R.id.file_list);
final TextView warningTextView = (TextView) view.findViewById(R.id.warning);
final TextView pathTextView = (TextView) view.findViewById(R.id.path);
if (path != null)
fileExplorerView.setPath(path);
fileExplorerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
fileExplorerView.onItemClick(parent, view, position, id);
pathTextView.setText(fileExplorerView.getCurPath());
if (fileExplorerView.canWrite())
warningTextView.setVisibility(View.GONE);
else
warningTextView.setVisibility(View.VISIBLE);
}
});
pathTextView.setText(fileExplorerView.getCurPath());
if (fileExplorerView.canWrite())
warningTextView.setVisibility(View.GONE);
else
warningTextView.setVisibility(View.VISIBLE);
builder.setView(view, false,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Ui.dp2pix(360)));
return new DirSelectDialog(builder, fileExplorerView);
}
public String getCurrentPath() {
return mFileExplorerView.getCurPath();
}
public void refresh() {
mFileExplorerView.refresh();
}
public boolean canWrite() {
return mFileExplorerView.canWrite();
}
}
@@ -1,504 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.app;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.ViewUtils;
public class MaterialAlertDialog extends AlertDialog implements
View.OnClickListener, AdapterView.OnItemClickListener {
public final static int ACTION = 0x1;
public final static int POSITIVE = 0x2;
public final static int NEGATIVE = 0x4;
public final static int NEUTRAL = 0x8;
private final Context mContext;
private final Builder mBuilder;
private View mRootView;
private TextView mTitle;
private Button mActionButton;
private Button mPositiveButton;
private Button mNegativeButton;
private Button mNeutralButton;
protected MaterialAlertDialog(Builder builder) {
super(builder.mContext);
mContext = builder.mContext;
mBuilder = builder;
init();
}
@SuppressLint("InflateParams")
private void init() {
LayoutInflater inflater = LayoutInflater.from(mContext);
mRootView = inflater.inflate(R.layout.alert_dialog_material, null);
// Check in scroll view or not
boolean inScrollView;
if (mBuilder.mCustomView != null)
inScrollView = mBuilder.mInScrollView;
else if (mBuilder.mAdapter != null)
inScrollView = false;
else
inScrollView = true;
// Get widget
LinearLayout topPanel;
TextView message = null;
ListView list = null;
if (inScrollView) {
mRootView.findViewById(R.id.top_panel_noscroll).setVisibility(
View.GONE);
mTitle = (TextView) mRootView.findViewById(R.id.title);
topPanel = (LinearLayout) mRootView.findViewById(R.id.top_panel);
message = (TextView) mRootView.findViewById(R.id.message);
} else {
mRootView.findViewById(R.id.scroll_view).setVisibility(View.GONE);
mTitle = (TextView) mRootView.findViewById(R.id.title2);
topPanel = (LinearLayout) mRootView
.findViewById(R.id.top_panel_noscroll);
list = (ListView) mRootView.findViewById(R.id.list);
}
// Title
if (mBuilder.mTitle == null)
mTitle.setVisibility(View.GONE);
else
mTitle.setText(mBuilder.mTitle);
// Content
if (mBuilder.mCustomView != null) {
// CustomView
if (message != null)
message.setVisibility(View.GONE);
if (list != null)
list.setVisibility(View.GONE);
LinearLayout.LayoutParams lp = mBuilder.mCustomLp;
if (lp == null)
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mBuilder.mCustomView.setId(R.id.custom);
topPanel.addView(mBuilder.mCustomView, lp);
} else if (mBuilder.mAdapter != null) {
// List
if (message != null)
message.setVisibility(View.GONE);
list.setAdapter(mBuilder.mAdapter);
list.setOnItemClickListener(this);
if (mBuilder.mIsSingleChoice) {
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (mBuilder.mCheckedItem > -1) {
list.setItemChecked(mBuilder.mCheckedItem, true);
list.setSelection(mBuilder.mCheckedItem);
}
}
} else {
// Message
if (list != null)
list.setVisibility(View.GONE);
if (mBuilder.mAutoLinkMask != -1)
message.setAutoLinkMask(mBuilder.mAutoLinkMask);
message.setText(mBuilder.mMessage);
}
// Buttons
View buttonPanel = mRootView.findViewById(R.id.button_panel);
View nonActionPanel = mRootView.findViewById(R.id.non_action_panel);
mActionButton = (Button) mRootView.findViewById(R.id.button_action);
mPositiveButton = (Button) mRootView.findViewById(R.id.button_positive);
mNegativeButton = (Button) mRootView.findViewById(R.id.button_negative);
mNeutralButton = (Button) mRootView.findViewById(R.id.button_neutral);
boolean hasAction = mBuilder.mActionButtonText != null;
boolean hasNonAction = mBuilder.mPositiveButtonText != null
|| mBuilder.mNegativeButtonText != null
|| mBuilder.mNeutralButtonText != null;
boolean hasButton = hasAction || hasNonAction;
if (hasButton) {
if (hasAction) {
mActionButton.setText(mBuilder.mActionButtonText);
mActionButton.setOnClickListener(this);
} else {
mActionButton.setVisibility(View.GONE);
}
if (hasNonAction) {
// Positive
if (mBuilder.mPositiveButtonText != null) {
mPositiveButton.setText(mBuilder.mPositiveButtonText);
mPositiveButton.setOnClickListener(this);
} else {
mPositiveButton.setVisibility(View.GONE);
}
// Negative
if (mBuilder.mNegativeButtonText != null) {
mNegativeButton.setText(mBuilder.mNegativeButtonText);
mNegativeButton.setOnClickListener(this);
} else {
mNegativeButton.setVisibility(View.GONE);
}
// Neutral
if (mBuilder.mNeutralButtonText != null) {
mNeutralButton.setText(mBuilder.mNeutralButtonText);
mNeutralButton.setOnClickListener(this);
} else {
mNeutralButton.setVisibility(View.GONE);
}
} else {
nonActionPanel.setVisibility(View.GONE);
}
} else {
buttonPanel.setVisibility(View.GONE);
}
setView(mRootView);
setCancelable(mBuilder.mCancelable);
if (mBuilder.mOnCancelListener != null)
setOnCancelListener(mBuilder.mOnCancelListener);
if (mBuilder.mOnDismissListener != null)
setOnDismissListener(mBuilder.mOnDismissListener);
}
@Override
public void setTitle(CharSequence title) {
mTitle.setText(title);
}
@Override
public void setTitle(int resId) {
setTitle(getContext().getString(resId));
}
public void setView(View view, boolean inScrollView) {
setView(view, inScrollView, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
public void setView(View view, boolean inScrollView,
LinearLayout.LayoutParams lp) {
mRootView.findViewById(inScrollView ? R.id.top_panel_noscroll : R.id.scroll_view).setVisibility(View.GONE);
mRootView.findViewById(inScrollView ? R.id.scroll_view : R.id.top_panel_noscroll).setVisibility(View.VISIBLE);
mRootView.findViewById(R.id.message).setVisibility(View.GONE);
mRootView.findViewById(R.id.list).setVisibility(View.GONE);
LinearLayout topPanel = (LinearLayout) mRootView.findViewById(inScrollView ? R.id.top_panel : R.id.top_panel_noscroll);
topPanel.addView(view, lp);
// Title
TextView oldTitle = mTitle;
mTitle = (TextView) mRootView.findViewById(inScrollView ? R.id.title : R.id.title2);
if (mTitle != oldTitle && oldTitle != null)
mTitle.setText(oldTitle.getText());
}
@Override
public void onClick(View v) {
boolean close = true;
if (mBuilder.mButtonListener != null) {
if (v == mActionButton)
close = mBuilder.mButtonListener.onClick(this, ACTION);
else if (v == mPositiveButton)
close = mBuilder.mButtonListener.onClick(this, POSITIVE);
else if (v == mNegativeButton)
close = mBuilder.mButtonListener.onClick(this, NEGATIVE);
else if (v == mNeutralButton)
close = mBuilder.mButtonListener.onClick(this, NEUTRAL);
}
if (close)
dismiss();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
boolean close = false;
if (mBuilder.mOnClickListener != null)
close = mBuilder.mOnClickListener.onClick(this, position);
if (close)
dismiss();
}
public static interface OnClickListener {
public boolean onClick(MaterialAlertDialog dialog, int which);
}
public static class Builder {
protected Context mContext;
protected boolean mDarkTheme = false;
protected CharSequence mTitle;
protected CharSequence mMessage;
protected CharSequence mActionButtonText;
protected CharSequence mPositiveButtonText;
protected CharSequence mNegativeButtonText;
protected CharSequence mNeutralButtonText;
protected OnClickListener mButtonListener;
protected View mCustomView;
protected LinearLayout.LayoutParams mCustomLp;
protected boolean mInScrollView = true;
protected boolean mCancelable = true;
protected int mAutoLinkMask = -1;
protected OnCancelListener mOnCancelListener;
protected ListAdapter mAdapter;
protected OnClickListener mOnClickListener;
protected int mCheckedItem;
protected boolean mIsSingleChoice;
protected DialogInterface.OnDismissListener mOnDismissListener;
public Builder(Context context) {
mContext = context;
}
public Builder setDrakTheme(boolean darkTheme) {
mDarkTheme = darkTheme;
return this;
}
public Builder setTitle(CharSequence title) {
mTitle = title;
return this;
}
public Builder setTitle(int resId) {
return setTitle(mContext.getString(resId));
}
public Builder setMessage(CharSequence message) {
mMessage = message;
return this;
}
public Builder setMessage(int resId) {
return setMessage(mContext.getString(resId));
}
public Builder setActionButton(CharSequence text) {
mActionButtonText = text;
return this;
}
public Builder setActionButton(int resId) {
return setActionButton(mContext.getString(resId));
}
public Builder setPositiveButton(CharSequence text) {
mPositiveButtonText = text;
return this;
}
public Builder setPositiveButton(int resId) {
return setPositiveButton(mContext.getString(resId));
}
public Builder setNegativeButton(CharSequence text) {
mNegativeButtonText = text;
return this;
}
public Builder setNegativeButton(int resId) {
return setNegativeButton(mContext.getString(resId));
}
public Builder setNeutralButton(CharSequence text) {
mNeutralButtonText = text;
return this;
}
public Builder setNeutralButton(int resId) {
return setNeutralButton(mContext.getString(resId));
}
public Builder setDefaultButton(int b) {
if ((b & POSITIVE) == POSITIVE)
mPositiveButtonText = mContext.getString(android.R.string.ok);
if ((b & NEGATIVE) == NEGATIVE)
mNegativeButtonText = mContext.getString(android.R.string.cancel);
return this;
}
public Builder setButtonListener(OnClickListener l) {
mButtonListener = l;
return this;
}
/**
* Custom view id will be R.id.custom
*
* @param view
* @param inScrollView
* @return
*/
public Builder setView(View view, boolean inScrollView) {
mCustomView = view;
mInScrollView = inScrollView;
return this;
}
/**
* Custom view id will be R.id.custom
*
* @param view
* @param inScrollView
* @param lp
* @return
*/
public Builder setView(View view, boolean inScrollView,
LinearLayout.LayoutParams lp) {
mCustomView = view;
mInScrollView = inScrollView;
mCustomLp = lp;
return this;
}
public Builder setView(int resId, boolean inScrollView, ViewHolder vh) {
mCustomView = ViewUtils.inflateDialogView(resId, mDarkTheme);
mInScrollView = inScrollView;
if (vh != null)
vh.setView(mCustomView);
return this;
}
public Builder setCancelable(boolean cancelable) {
mCancelable = cancelable;
return this;
}
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
mOnCancelListener = onCancelListener;
return this;
}
public Builder setMessageAutoLink(int mask) {
mAutoLinkMask = mask;
return this;
}
public Builder setItems(int itemsId, final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_item, android.R.id.text1, mContext
.getResources().getTextArray(itemsId));
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setItems(CharSequence[] items,
final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_item, android.R.id.text1, items);
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setAdapter(final ListAdapter adapter,
final OnClickListener listener) {
mAdapter = adapter;
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_singlechoice, android.R.id.text1,
mContext.getResources().getTextArray(itemsId));
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(CharSequence[] items,
int checkedItem, final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_singlechoice, android.R.id.text1,
items);
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(ListAdapter adapter,
int checkedItem, final OnClickListener listener) {
mAdapter = adapter;
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setOnDismissListener(DialogInterface.OnDismissListener l) {
mOnDismissListener = l;
return this;
}
public MaterialAlertDialog create() {
mContext = new ContextThemeWrapper(mContext, mDarkTheme ?
R.style.AppTheme_Dark_Dialog : R.style.AppTheme_Dialog);
return new MaterialAlertDialog(this);
}
public MaterialAlertDialog show() {
MaterialAlertDialog dialog = create();
dialog.show();
return dialog;
}
}
public static class ViewHolder {
private View mView;
private void setView(View v) {
mView = v;
}
public View getView() {
return mView;
}
}
}
-501
View File
@@ -1,501 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import com.hippo.ehviewer.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public abstract class AnyCache<V> {
private static final String TAG = AnyCache.class.getSimpleName();
private LruCache<String, V> mMemoryCache;
private @Nullable DiskCache<V> mDiskCache;
private final boolean mHasMemoryCache;
private final boolean mHasDiskCache;
/**
* Used to temporarily pause the disk cache while scrolling
*/
public boolean mPauseDiskAccess = false;
private final Object mPauseLock = new Object();
private final Object mDiskCacheLock = new Object();
public AnyCache(AnyCacheParams params) {
params.isValid();
mHasMemoryCache = params.hasMemoryCache;
mHasDiskCache = params.hasDiskCache;
if (mHasMemoryCache) {
initMemoryCache(params.memoryCacheMaxSize);
}
if (mHasDiskCache) {
initDiskCache(params.diskCacheDir, params.diskCacheMaxSize);
}
}
private void initMemoryCache(int maxSize) {
mMemoryCache = new MemoryCahce<>(maxSize, this);
}
private void initDiskCache(File cacheDir, int maxSize) {
// Set up disk cache
synchronized (mDiskCacheLock) {
try {
mDiskCache = new DiskCache<>(cacheDir, maxSize, this);
} catch (IOException e) {
Log.e(TAG, "Can't create disk cache", e);
}
}
}
protected abstract int sizeOf(String key, V value);
protected abstract V read(InputStream is);
protected abstract boolean write(OutputStream os, V value);
/**
* Check if have memory cache
*
* @return true if have memory cache
*/
public boolean hasMemoryCache() {
return mHasMemoryCache;
}
/**
* Check if have disk cache
*
* @return true if have disk cache
*/
public boolean hasDiskCache() {
return mHasDiskCache;
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache
*/
public V getFromMemory(String key) {
if (mHasMemoryCache) {
return mMemoryCache.get(key);
} else {
return null;
}
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache or get error
*/
public V getFromDisk(String key) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
return mDiskCache.get(diskKey);
} else {
return null;
}
}
} else {
return null;
}
}
/**
* Get value from memory cache and disk cache. If miss in memory cache and
* get in disk cache, it will put value from disk cache to memory cache.
*
* @param key the key to get value
* @return the value you get
*/
public V get(String key) {
V value = getFromMemory(key);
if (value != null) {
// Get it in memory cache
return value;
}
value = getFromDisk(key);
if (value != null) {
// Get it in disk cache
putToMemory(key, value);
return value;
}
return null;
}
/**
* Put value to memory cache
*
* @param key the key
* @param value the value
* @return false if no memory cache
*/
public boolean putToMemory(String key, V value) {
if (mHasMemoryCache) {
mMemoryCache.put(key, value);
return true;
} else {
return false;
}
}
/**
* Put value to disk cache
*
* @param key the key
* @param value the value
* @return false if no disk cache or get error
*/
public boolean putToDisk(String key, V value) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
mDiskCache.put(diskKey, value);
return true;
} else {
return false;
}
}
} else {
return false;
}
}
/**
* Put value to memory cache and disk cache
*
* @param key the key
* @param value the value
*/
public void put(String key, V value) {
putToMemory(key, value);
putToDisk(key, value);
}
/**
* Used to temporarily pause the disk cache while the user is scrolling to
* improve scrolling.
*
* @param pause True to temporarily pause the disk cache, false otherwise.
*/
public void setPauseDiskCache(final boolean pause) {
synchronized (mPauseLock) {
if (mPauseDiskAccess != pause) {
mPauseDiskAccess = pause;
if (!pause) {
mPauseLock.notify();
}
}
}
}
private void waitUntilUnpaused() {
synchronized (mPauseLock) {
if (Looper.myLooper() != Looper.getMainLooper()) {
while (mPauseDiskAccess) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// ignored, we'll start waiting again
}
}
}
}
}
/**
* Evicts all of the items from the memory cache
*/
public void clearMemory() {
if (mHasMemoryCache) {
mMemoryCache.evictAll();
}
}
/**
* Clear disk cache
*/
public void clearDisk() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null && !mDiskCache.isClosed()) {
try {
mDiskCache.delete();
} catch (IOException e) {
Log.e(TAG, "AnyCache clearCache", e);
}
File cacheDir = mDiskCache.getCacheDir();
int maxSize = mDiskCache.getMaxSize();
mDiskCache = null;
initDiskCache(cacheDir, maxSize);
}
}
}
}
public void flush() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
try {
mDiskCache.flush();
} catch (IOException e) {
Log.e(TAG, "AnyCache flush", e);
}
}
}
}
}
/**
* Evicts all of the items from the memory cache and lets the system know
* now would be a good time to garbage collect
*/
public void clear() {
clearMemory();
clearDisk();
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable
* for using as a disk filename.
*
* @param key The key used to store the file
*/
private static String hashKeyForDisk(final String key) {
String cacheKey;
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(key.getBytes());
cacheKey = bytesToHexString(digest.digest());
} catch (final NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* http://stackoverflow.com/questions/332079
*
* @param bytes The bytes to convert.
* @return A {@link String} converted from the bytes of a hashable key used
* to store a filename on the disk, to hex digits.
*/
private static String bytesToHexString(final byte[] bytes) {
final StringBuilder builder = new StringBuilder();
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
builder.append('0');
}
builder.append(hex);
}
return builder.toString();
}
/**
* A holder class that contains cache parameters.
*/
public static class AnyCacheParams {
public boolean hasMemoryCache = false;
public int memoryCacheMaxSize = 0;
public boolean hasDiskCache = false;
public File diskCacheDir = null;
public int diskCacheMaxSize = 0;
/**
* Check AnyCacheParams is valid
*
* @throws IllegalStateException
*/
public void isValid() throws IllegalStateException {
if (!hasMemoryCache && !hasDiskCache) {
throw new IllegalStateException("No memory cache and no disk cache. What can I do for you?");
}
if (hasMemoryCache && memoryCacheMaxSize <= 0) {
throw new IllegalStateException("Memory cache max size must be bigger than 0.");
}
if (hasDiskCache) {
if (diskCacheDir == null) {
throw new IllegalStateException("Disk cache dir can't be null.");
}
if (diskCacheMaxSize <= 0) {
throw new IllegalStateException("Disk cache max size must be bigger than 0.");
}
}
}
}
public class MemoryCahce<E> extends LruCache<String, E> {
public AnyCache<E> mParent;
public MemoryCahce(int maxSize, AnyCache<E> parent) {
super(maxSize);
mParent = parent;
}
@Override
protected int sizeOf(String key, E value) {
return mParent.sizeOf(key, value);
}
}
public static class DiskCache<E> {
private static final int IO_BUFFER_SIZE = 8 * 1024;
private DiskLruCache mDiskLruCache;
private AnyCache<E> mParent;
private File mCacheDir;
private int mMaxSize;
public DiskCache(File cacheDir, int size, AnyCache<E> parent) throws IOException {
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
mParent = parent;
mCacheDir = cacheDir;
mMaxSize = size;
}
public File getCacheDir() {
return mCacheDir;
}
public int getMaxSize() {
return mMaxSize;
}
public boolean isClosed() {
return mDiskLruCache.isClosed();
}
public void delete() throws IOException {
mDiskLruCache.delete();
}
public void flush() throws IOException {
mDiskLruCache.flush();
}
public E get(String key) {
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskLruCache.get(key);
if ( snapshot == null ) {
// Miss
return null;
}
final InputStream in = snapshot.getInputStream(0);
if (in != null) {
final BufferedInputStream buffIn =
new BufferedInputStream(in, IO_BUFFER_SIZE);
return mParent.read(buffIn);
} else {
// Can't get InputStream
return null;
}
} catch (IOException e) {
// e.printStackTrace();
return null;
} finally {
Util.closeQuietly(snapshot);
}
}
public boolean put(String key, E value) {
DiskLruCache.Editor editor = null;
OutputStream os = null;
boolean completeEdit = false;
try {
editor = mDiskLruCache.edit(key);
if (editor == null) {
// The editor is in progress
return false;
}
os = editor.newOutputStream(0);
if (os != null) {
final BufferedOutputStream buffOut =
new BufferedOutputStream(os, IO_BUFFER_SIZE);
boolean result = mParent.write(buffOut, value);
completeEdit = true;
editor.commit();
return result;
} else {
// Can't get OutputStream
completeEdit = true;
editor.abort();
return false;
}
} catch (IOException e) {
Util.closeQuietly(os);
try {
if (!completeEdit && editor != null) {
editor.abort();
}
} catch (IOException ignored) {
}
return false;
}
}
}
}
@@ -1,943 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A cache that uses a bounded amount of space on a filesystem. Each cache
* entry has a string key and a fixed number of values. Each key must match
* the regex <strong>[a-z0-9_-]{1,120}</strong>. Values are byte sequences,
* accessible as streams or files. Each value must be between {@code 0} and
* {@code Integer.MAX_VALUE} bytes in length.
*
* <p>The cache stores its data in a directory on the filesystem. This
* directory must be exclusive to the cache; the cache may delete or overwrite
* files from its directory. It is an error for multiple processes to use the
* same cache directory at the same time.
*
* <p>This cache limits the number of bytes that it will store on the
* filesystem. When the number of stored bytes exceeds the limit, the cache will
* remove entries in the background until the limit is satisfied. The limit is
* not strict: the cache may temporarily exceed it while waiting for files to be
* deleted. The limit does not include filesystem overhead or the cache
* journal so space-sensitive applications should set a conservative limit.
*
* <p>Clients call {@link #edit} to create or update the values of an entry. An
* entry may have only one editor at one time; if a value is not available to be
* edited then {@link #edit} will return null.
* <ul>
* <li>When an entry is being <strong>created</strong> it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* <li>When an entry is being <strong>edited</strong>, it is not necessary
* to supply data for every value; values default to their previous
* value.
* </ul>
* Every {@link #edit} call must be matched by a call to {@link Editor#commit}
* or {@link Editor#abort}. Committing is atomic: a read observes the full set
* of values as they were before or after the commit, but never a mix of values.
*
* <p>Clients call {@link #get} to read a snapshot of an entry. The read will
* observe the value at the time that {@link #get} was called. Updates and
* removals after the call do not impact ongoing reads.
*
* <p>This class is tolerant of some I/O errors. If files are missing from the
* filesystem, the corresponding entries will be dropped from the cache. If
* an error occurs while writing a cache value, the edit will fail silently.
* Callers should handle other problems by catching {@code IOException} and
* responding appropriately.
*/
public final class DiskLruCache implements Closeable {
static final String JOURNAL_FILE = "journal";
static final String JOURNAL_FILE_TEMP = "journal.tmp";
static final String JOURNAL_FILE_BACKUP = "journal.bkp";
static final String MAGIC = "libcore.io.DiskLruCache";
static final String VERSION_1 = "1";
static final long ANY_SEQUENCE_NUMBER = -1;
static final String STRING_KEY_PATTERN = "[a-z0-9_-]{1,120}";
static final Pattern LEGAL_KEY_PATTERN = Pattern.compile(STRING_KEY_PATTERN);
private static final String CLEAN = "CLEAN";
private static final String DIRTY = "DIRTY";
private static final String REMOVE = "REMOVE";
private static final String READ = "READ";
/*
* This cache uses a journal file named "journal". A typical journal file
* looks like this:
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the
* constant string "libcore.io.DiskLruCache", the disk cache's version,
* the application's version, the value count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a
* cache entry. Each line contains space-separated values: a state, a key,
* and optional state-specific values.
* o DIRTY lines track that an entry is actively being created or updated.
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
* temporary files may need to be deleted.
* o CLEAN lines track a cache entry that has been successfully published
* and may be read. A publish line is followed by the lengths of each of
* its values.
* o READ lines track accesses for LRU.
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may
* occasionally be compacted by dropping redundant lines. A temporary file named
* "journal.tmp" will be used during compaction; that file should be deleted if
* it exists when the cache is opened.
*/
private final File directory;
private final File journalFile;
private final File journalFileTmp;
private final File journalFileBackup;
private final int appVersion;
private long maxSize;
private final int valueCount;
private long size = 0;
private Writer journalWriter;
private final LinkedHashMap<String, Entry> lruEntries =
new LinkedHashMap<String, Entry>(0, 0.75f, true);
private int redundantOpCount;
/**
* To differentiate between old and current snapshots, each entry is given
* a sequence number each time an edit is committed. A snapshot is stale if
* its sequence number is not equal to its entry's sequence number.
*/
private long nextSequenceNumber = 0;
/** This cache uses a single background thread to evict entries. */
final ThreadPoolExecutor executorService =
new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Callable<Void> cleanupCallable = new Callable<Void>() {
public Void call() throws Exception {
synchronized (DiskLruCache.this) {
if (journalWriter == null) {
return null; // Closed.
}
trimToSize();
if (journalRebuildRequired()) {
rebuildJournal();
redundantOpCount = 0;
}
}
return null;
}
};
private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
this.directory = directory;
this.appVersion = appVersion;
this.journalFile = new File(directory, JOURNAL_FILE);
this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP);
this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP);
this.valueCount = valueCount;
this.maxSize = maxSize;
}
/**
* Opens the cache in {@code directory}, creating a cache if none exists
* there.
*
* @param directory a writable directory
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// If a bkp file exists, use it instead.
File backupFile = new File(directory, JOURNAL_FILE_BACKUP);
if (backupFile.exists()) {
File journalFile = new File(directory, JOURNAL_FILE);
// If journal file also exists just delete backup file.
if (journalFile.exists()) {
backupFile.delete();
} else {
renameTo(backupFile, journalFile, false);
}
}
// Prefer to pick up where we left off.
DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
return cache;
} catch (IOException journalIsCorrupt) {
System.out
.println("DiskLruCache "
+ directory
+ " is corrupt: "
+ journalIsCorrupt.getMessage()
+ ", removing");
cache.delete();
}
}
// Create a new empty cache.
directory.mkdirs();
cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
cache.rebuildJournal();
return cache;
}
private void readJournal() throws IOException {
StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
try {
String magic = reader.readLine();
String version = reader.readLine();
String appVersionString = reader.readLine();
String valueCountString = reader.readLine();
String blank = reader.readLine();
if (!MAGIC.equals(magic)
|| !VERSION_1.equals(version)
|| !Integer.toString(appVersion).equals(appVersionString)
|| !Integer.toString(valueCount).equals(valueCountString)
|| !"".equals(blank)) {
throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
+ valueCountString + ", " + blank + "]");
}
int lineCount = 0;
while (true) {
try {
readJournalLine(reader.readLine());
lineCount++;
} catch (EOFException endOfJournal) {
break;
}
}
redundantOpCount = lineCount - lruEntries.size();
// If we ended on a truncated line, rebuild the journal before appending to it.
if (reader.hasUnterminatedLine()) {
rebuildJournal();
} else {
journalWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFile, true), Util.US_ASCII));
}
} finally {
Util.closeQuietly(reader);
}
}
private void readJournalLine(String line) throws IOException {
int firstSpace = line.indexOf(' ');
if (firstSpace == -1) {
throw new IOException("unexpected journal line: " + line);
}
int keyBegin = firstSpace + 1;
int secondSpace = line.indexOf(' ', keyBegin);
final String key;
if (secondSpace == -1) {
key = line.substring(keyBegin);
if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) {
lruEntries.remove(key);
return;
}
} else {
key = line.substring(keyBegin, secondSpace);
}
Entry entry = lruEntries.get(key);
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
}
if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) {
String[] parts = line.substring(secondSpace + 1).split(" ");
entry.readable = true;
entry.currentEditor = null;
entry.setLengths(parts);
} else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) {
entry.currentEditor = new Editor(entry);
} else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) {
// This work was already done by calling lruEntries.get().
} else {
throw new IOException("unexpected journal line: " + line);
}
}
/**
* Computes the initial size and collects garbage as a part of opening the
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
*/
private void processJournal() throws IOException {
deleteIfExists(journalFileTmp);
for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
Entry entry = i.next();
if (entry.currentEditor == null) {
for (int t = 0; t < valueCount; t++) {
size += entry.lengths[t];
}
} else {
entry.currentEditor = null;
for (int t = 0; t < valueCount; t++) {
deleteIfExists(entry.getCleanFile(t));
deleteIfExists(entry.getDirtyFile(t));
}
i.remove();
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the
* current journal if it exists.
*/
private synchronized void rebuildJournal() throws IOException {
if (journalWriter != null) {
journalWriter.close();
}
Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
try {
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for (Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key + '\n');
} else {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
}
}
} finally {
writer.close();
}
if (journalFile.exists()) {
renameTo(journalFile, journalFileBackup, true);
}
renameTo(journalFileTmp, journalFile, false);
journalFileBackup.delete();
journalWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
}
private static void deleteIfExists(File file) throws IOException {
if (file.exists() && !file.delete()) {
throw new IOException();
}
}
private static void renameTo(File from, File to, boolean deleteDestination) throws IOException {
if (deleteDestination) {
deleteIfExists(to);
}
if (!from.renameTo(to)) {
throw new IOException();
}
}
/**
* Returns a snapshot of the entry named {@code key}, or null if it doesn't
* exist is not currently readable. If a value is returned, it is moved to
* the head of the LRU queue.
*/
public synchronized Snapshot get(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
// Open all streams eagerly to guarantee that we see a single published
// snapshot. If we opened streams lazily then the streams could come
// from different edits.
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch (FileNotFoundException e) {
// A file must have been deleted manually!
for (int i = 0; i < valueCount; i++) {
if (ins[i] != null) {
Util.closeQuietly(ins[i]);
} else {
break;
}
}
return null;
}
redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths);
}
/**
* Returns an editor for the entry named {@code key}, or null if another
* edit is in progress.
*/
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
}
private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
|| entry.sequenceNumber != expectedSequenceNumber)) {
return null; // Snapshot is stale.
}
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
} else if (entry.currentEditor != null) {
return null; // Another edit is in progress.
}
Editor editor = new Editor(entry);
entry.currentEditor = editor;
// Flush the journal before creating files to prevent file leaks.
journalWriter.write(DIRTY + ' ' + key + '\n');
journalWriter.flush();
return editor;
}
/** Returns the directory where this cache stores its data. */
public File getDirectory() {
return directory;
}
/**
* Returns the maximum number of bytes that this cache should use to store
* its data.
*/
public synchronized long getMaxSize() {
return maxSize;
}
/**
* Changes the maximum number of bytes the cache can store and queues a job
* to trim the existing store, if necessary.
*/
public synchronized void setMaxSize(long maxSize) {
this.maxSize = maxSize;
executorService.submit(cleanupCallable);
}
/**
* Returns the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
public synchronized long size() {
return size;
}
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
Entry entry = editor.entry;
if (entry.currentEditor != editor) {
throw new IllegalStateException();
}
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (int i = 0; i < valueCount; i++) {
if (!editor.written[i]) {
editor.abort();
throw new IllegalStateException("Newly created entry didn't create value for index " + i);
}
if (!entry.getDirtyFile(i).exists()) {
editor.abort();
return;
}
}
}
for (int i = 0; i < valueCount; i++) {
File dirty = entry.getDirtyFile(i);
if (success) {
if (dirty.exists()) {
File clean = entry.getCleanFile(i);
dirty.renameTo(clean);
long oldLength = entry.lengths[i];
long newLength = clean.length();
entry.lengths[i] = newLength;
size = size - oldLength + newLength;
}
} else {
deleteIfExists(dirty);
}
}
redundantOpCount++;
entry.currentEditor = null;
if (entry.readable | success) {
entry.readable = true;
journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
if (success) {
entry.sequenceNumber = nextSequenceNumber++;
}
} else {
lruEntries.remove(entry.key);
journalWriter.write(REMOVE + ' ' + entry.key + '\n');
}
journalWriter.flush();
if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
}
/**
* We only rebuild the journal when it will halve the size of the journal
* and eliminate at least 2000 ops.
*/
private boolean journalRebuildRequired() {
final int redundantOpCompactThreshold = 2000;
return redundantOpCount >= redundantOpCompactThreshold //
&& redundantOpCount >= lruEntries.size();
}
/**
* Drops the entry for {@code key} if it exists and can be removed. Entries
* actively being edited cannot be removed.
*
* @return true if an entry was removed.
*/
public synchronized boolean remove(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null || entry.currentEditor != null) {
return false;
}
for (int i = 0; i < valueCount; i++) {
File file = entry.getCleanFile(i);
if (file.exists() && !file.delete()) {
throw new IOException("failed to delete " + file);
}
size -= entry.lengths[i];
entry.lengths[i] = 0;
}
redundantOpCount++;
journalWriter.append(REMOVE + ' ' + key + '\n');
lruEntries.remove(key);
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return true;
}
/** Returns true if this cache has been closed. */
public synchronized boolean isClosed() {
return journalWriter == null;
}
private void checkNotClosed() {
if (journalWriter == null) {
throw new IllegalStateException("cache is closed");
}
}
/** Force buffered operations to the filesystem. */
public synchronized void flush() throws IOException {
checkNotClosed();
trimToSize();
journalWriter.flush();
}
/** Closes this cache. Stored values will remain on the filesystem. */
public synchronized void close() throws IOException {
if (journalWriter == null) {
return; // Already closed.
}
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
}
private void trimToSize() throws IOException {
while (size > maxSize) {
Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
remove(toEvict.getKey());
}
}
/**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/
public void delete() throws IOException {
close();
Util.deleteContents(directory);
}
private void validateKey(String key) {
Matcher matcher = LEGAL_KEY_PATTERN.matcher(key);
if (!matcher.matches()) {
throw new IllegalArgumentException("keys must match regex "
+ STRING_KEY_PATTERN + ": \"" + key + "\"");
}
}
private static String inputStreamToString(InputStream in) throws IOException {
return Util.readFully(new InputStreamReader(in, Util.UTF_8));
}
/** A snapshot of the values for an entry. */
public final class Snapshot implements Closeable {
private final String key;
private final long sequenceNumber;
private final InputStream[] ins;
private final long[] lengths;
private Snapshot(String key, long sequenceNumber, InputStream[] ins, long[] lengths) {
this.key = key;
this.sequenceNumber = sequenceNumber;
this.ins = ins;
this.lengths = lengths;
}
/**
* Returns an editor for this snapshot's entry, or null if either the
* entry has changed since this snapshot was created or if another edit
* is in progress.
*/
public Editor edit() throws IOException {
return DiskLruCache.this.edit(key, sequenceNumber);
}
/** Returns the unbuffered stream with the value for {@code index}. */
public InputStream getInputStream(int index) {
return ins[index];
}
/** Returns the string value for {@code index}. */
public String getString(int index) throws IOException {
return inputStreamToString(getInputStream(index));
}
/** Returns the byte length of the value for {@code index}. */
public long getLength(int index) {
return lengths[index];
}
public void close() {
for (InputStream in : ins) {
Util.closeQuietly(in);
}
}
}
private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
@Override
public void write(int b) throws IOException {
// Eat all writes silently. Nom nom.
}
};
/** Edits the values for an entry. */
public final class Editor {
private final Entry entry;
private final boolean[] written;
private boolean hasErrors;
private boolean committed;
private Editor(Entry entry) {
this.entry = entry;
this.written = (entry.readable) ? null : new boolean[valueCount];
}
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
public InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
try {
return new FileInputStream(entry.getCleanFile(index));
} catch (FileNotFoundException e) {
return null;
}
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
public String getString(int index) throws IOException {
InputStream in = newInputStream(index);
return in != null ? inputStreamToString(in) : null;
}
/**
* Returns a new unbuffered output stream to write the value at
* {@code index}. If the underlying output stream encounters errors
* when writing to the filesystem, this edit will be aborted when
* {@link #commit} is called. The returned output stream does not throw
* IOExceptions.
*/
public OutputStream newOutputStream(int index) throws IOException {
if (index < 0 || index >= valueCount) {
throw new IllegalArgumentException("Expected index " + index + " to "
+ "be greater than 0 and less than the maximum value count "
+ "of " + valueCount);
}
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
written[index] = true;
}
File dirtyFile = entry.getDirtyFile(index);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dirtyFile);
} catch (FileNotFoundException e) {
// Attempt to recreate the cache directory.
directory.mkdirs();
try {
outputStream = new FileOutputStream(dirtyFile);
} catch (FileNotFoundException e2) {
// We are unable to recover. Silently eat the writes.
return NULL_OUTPUT_STREAM;
}
}
return new FaultHidingOutputStream(outputStream);
}
}
/** Sets the value at {@code index} to {@code value}. */
public void set(int index, String value) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
writer.write(value);
} finally {
Util.closeQuietly(writer);
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
public void commit() throws IOException {
if (hasErrors) {
completeEdit(this, false);
remove(entry.key); // The previous entry is stale.
} else {
completeEdit(this, true);
}
committed = true;
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
public void abort() throws IOException {
completeEdit(this, false);
}
public void abortUnlessCommitted() {
if (!committed) {
try {
abort();
} catch (IOException ignored) {
}
}
}
private class FaultHidingOutputStream extends FilterOutputStream {
private FaultHidingOutputStream(OutputStream out) {
super(out);
}
@Override public void write(int oneByte) {
try {
out.write(oneByte);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void write(byte[] buffer, int offset, int length) {
try {
out.write(buffer, offset, length);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void close() {
try {
out.close();
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void flush() {
try {
out.flush();
} catch (IOException e) {
hasErrors = true;
}
}
}
}
private final class Entry {
private final String key;
/** Lengths of this entry's files. */
private final long[] lengths;
/** True if this entry has ever been published. */
private boolean readable;
/** The ongoing edit or null if this entry is not being edited. */
private Editor currentEditor;
/** The sequence number of the most recently committed edit to this entry. */
private long sequenceNumber;
private Entry(String key) {
this.key = key;
this.lengths = new long[valueCount];
}
public String getLengths() throws IOException {
StringBuilder result = new StringBuilder();
for (long size : lengths) {
result.append(' ').append(size);
}
return result.toString();
}
/** Set lengths using decimal numbers like "10123". */
private void setLengths(String[] strings) throws IOException {
if (strings.length != valueCount) {
throw invalidLengths(strings);
}
try {
for (int i = 0; i < strings.length; i++) {
lengths[i] = Long.parseLong(strings[i]);
}
} catch (NumberFormatException e) {
throw invalidLengths(strings);
}
}
private IOException invalidLengths(String[] strings) throws IOException {
throw new IOException("unexpected journal line: " + java.util.Arrays.toString(strings));
}
public File getCleanFile(int i) {
return new File(directory, key + "." + i);
}
public File getDirtyFile(int i) {
return new File(directory, key + "." + i + ".tmp");
}
}
}
@@ -1,113 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public class ImageCache extends AnyCache<Bitmap>{
private static final String TAG = "ImageCache";
/**
* Default memory cache size as a percent of device memory class
*/
private static final float MEM_CACHE_DIVIDER = 0.25f;
/**
* Compression settings when writing images to disk cache
*/
private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
/**
* Image compression quality
*/
private static final int COMPRESS_QUALITY = 98;
private static ImageCache sImageCache;
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
if (sImageCache == null) {
final ActivityManager activityManager = (ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
* 1024 * 1024);
AnyCacheParams params = new AnyCacheParams();
params.hasMemoryCache = true;
params.memoryCacheMaxSize = memoryCacheMax;
params.hasDiskCache = true;
params.diskCacheDir = getDiskCacheDir(context, TAG);
params.diskCacheMaxSize = 20 * 1024 * 1024;
sImageCache = new ImageCache(params);
}
return sImageCache;
}
public ImageCache(AnyCacheParams params) {
super(params);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
@Override
protected Bitmap read(InputStream is) {
return BitmapFactory.decodeStream(is);
}
@Override
protected boolean write(OutputStream os, Bitmap value) {
return value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
}
/**
* Get the external app cache directory
*
* @param context The {@link Context} to use
* @return The external cache directory
*/
private static File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
/**
* Get a usable cache directory (external if available, internal otherwise)
*
* @param context The {@link Context} to use
* @param uniqueName A unique directory name to append to the cache
* directory
* @return The cache directory
*/
private static File getDiskCacheDir(final Context context, final String uniqueName) {
// getExternalCacheDir(context) returns null if external storage is not ready
final String cachePath = getExternalCacheDir(context) != null
? getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
return new File(cachePath, uniqueName);
}
}
@@ -1,196 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* Buffers input from an {@link InputStream} for reading lines.
*
* <p>This class is used for buffered reading of lines. For purposes of this class, a line ends
* with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated
* line at end of input is invalid and will be ignored, the caller may use {@code
* hasUnterminatedLine()} to detect it after catching the {@code EOFException}.
*
* <p>This class is intended for reading input that strictly consists of lines, such as line-based
* cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
* with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
* end-of-input reporting and a more restrictive definition of a line.
*
* <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
* and 10, respectively, and the representation of no other character contains these values.
* We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
* The default charset is US_ASCII.
*/
class StrictLineReader implements Closeable {
private static final byte CR = (byte) '\r';
private static final byte LF = (byte) '\n';
private final InputStream in;
private final Charset charset;
/*
* Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
* and the data in the range [pos, end) is buffered for reading. At end of input, if there is
* an unterminated line, we set end == -1, otherwise end == pos. If the underlying
* {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
*/
private byte[] buf;
private int pos;
private int end;
/**
* Constructs a new {@code LineReader} with the specified charset and the default capacity.
*
* @param in the {@code InputStream} to read data from.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if the specified charset is not supported.
*/
public StrictLineReader(InputStream in, Charset charset) {
this(in, 8192, charset);
}
/**
* Constructs a new {@code LineReader} with the specified capacity and charset.
*
* @param in the {@code InputStream} to read data from.
* @param capacity the capacity of the buffer.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if {@code capacity} is negative or zero
* or the specified charset is not supported.
*/
public StrictLineReader(InputStream in, int capacity, Charset charset) {
if (in == null || charset == null) {
throw new NullPointerException();
}
if (capacity < 0) {
throw new IllegalArgumentException("capacity <= 0");
}
if (!(charset.equals(Util.US_ASCII))) {
throw new IllegalArgumentException("Unsupported encoding");
}
this.in = in;
this.charset = charset;
buf = new byte[capacity];
}
/**
* Closes the reader by closing the underlying {@code InputStream} and
* marking this reader as closed.
*
* @throws IOException for errors when closing the underlying {@code InputStream}.
*/
public void close() throws IOException {
synchronized (in) {
if (buf != null) {
buf = null;
in.close();
}
}
}
/**
* Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
* this end of line marker is not included in the result.
*
* @return the next line from the input.
* @throws IOException for underlying {@code InputStream} errors.
* @throws EOFException for the end of source stream.
*/
public String readLine() throws IOException {
synchronized (in) {
if (buf == null) {
throw new IOException("LineReader is closed");
}
// Read more data if we are at the end of the buffered data.
// Though it's an error to read after an exception, we will let {@code fillBuf()}
// throw again if that happens; thus we need to handle end == -1 as well as end == pos.
if (pos >= end) {
fillBuf();
}
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
String res = new String(buf, pos, lineEnd - pos, charset.name());
pos = i + 1;
return res;
}
}
// Let's anticipate up to 80 characters on top of those already read.
ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
@Override
public String toString() {
int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
try {
return new String(buf, 0, length, charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e); // Since we control the charset this will never happen.
}
}
};
while (true) {
out.write(buf, pos, end - pos);
// Mark unterminated line in case fillBuf throws EOFException or IOException.
end = -1;
fillBuf();
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
if (i != pos) {
out.write(buf, pos, i - pos);
}
pos = i + 1;
return out.toString();
}
}
}
}
}
public boolean hasUnterminatedLine() {
return end == -1;
}
/**
* Reads new input data into the buffer. Call only with pos == end or end == -1,
* depending on the desired outcome if the function throws.
*/
private void fillBuf() throws IOException {
int result = in.read(buf, 0, buf.length);
if (result == -1) {
throw new EOFException();
}
pos = 0;
end = result;
}
}
-77
View File
@@ -1,77 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.cache;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
/** Junk drawer of utility methods. */
final class Util {
static final Charset US_ASCII = Charset.forName("US-ASCII");
static final Charset UTF_8 = Charset.forName("UTF-8");
private Util() {
}
static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
/**
* Deletes the contents of {@code dir}. Throws an IOException if any file
* could not be deleted, or if {@code dir} is not a readable directory.
*/
static void deleteContents(File dir) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IOException("not a readable directory: " + dir);
}
for (File file : files) {
if (file.isDirectory()) {
deleteContents(file);
}
if (!file.delete()) {
throw new IOException("failed to delete file: " + file);
}
}
}
static void closeQuietly(/*Auto*/Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
}
@@ -1,82 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.data;
import android.os.Parcel;
import android.os.Parcelable;
import com.hippo.ehviewer.util.Utils;
public class ApiGalleryInfo extends GalleryInfo{
public String archiver_key;
public String title_jpn;
public String filecount;
public long filesize;
public boolean expunged;
public String torrentcount;
public String[] apiTags;
public static final Parcelable.Creator<ApiGalleryInfo> CREATOR =
new Parcelable.Creator<ApiGalleryInfo>() {
@Override
public ApiGalleryInfo createFromParcel(Parcel source) {
ApiGalleryInfo p = new ApiGalleryInfo();
p.gid = source.readInt();
p.token = source.readString();
p.title = source.readString();
p.posted = source.readString();
p.category = source.readInt();
p.thumb = source.readString();
p.uploader = source.readString();
p.rating = source.readFloat();
p.simpleLanguage = source.readString();
p.archiver_key = source.readString();
p.title_jpn = source.readString();
p.filecount = source.readString();
p.filesize = source.readLong();
p.expunged = Utils.int2boolean(source.readInt());
p.torrentcount = source.readString();
int apiTagsLength = source.readInt();
p.apiTags = new String[apiTagsLength];
for (int i = 0; i < apiTagsLength; i++)
p.apiTags[i] = source.readString();
return p;
}
@Override
public ApiGalleryInfo[] newArray(int size) {
return new ApiGalleryInfo[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(archiver_key);
dest.writeString(title_jpn);
dest.writeString(filecount);
dest.writeLong(filesize);
dest.writeInt(Utils.boolean2int(expunged));
dest.writeString(torrentcount);
dest.writeInt(apiTags.length);
for (String str : apiTags)
dest.writeString(str);
}
}
@@ -1,73 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.data;
import android.os.Parcel;
import android.os.Parcelable;
public class HistoryItem extends GalleryInfo {
public int mode;
public long date;
public static final Parcelable.Creator<HistoryItem> CREATOR =
new Parcelable.Creator<HistoryItem>() {
@Override
public HistoryItem createFromParcel(Parcel source) {
HistoryItem p = new HistoryItem();
p.gid = source.readInt();
p.token = source.readString();
p.title = source.readString();
p.posted = source.readString();
p.category = source.readInt();
p.thumb = source.readString();
p.uploader = source.readString();
p.rating = source.readFloat();
p.simpleLanguage = source.readString();
p.mode = source.readInt();
p.date = source.readLong();
return p;
}
@Override
public HistoryItem[] newArray(int size) {
return new HistoryItem[size];
}
};
public HistoryItem() {
// Empty
}
public HistoryItem(GalleryInfo gi, int m, long d) {
super(gi);
mode = m;
date = d;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(mode);
dest.writeLong(date);
}
}
@@ -1,187 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.drawable;
import java.util.Arrays;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import com.hippo.ehviewer.util.MathUtils;
import com.hippo.ehviewer.util.Ui;
public class FreeMaterialDrawable extends Drawable {
private static final String TAG = FreeMaterialDrawable.class.getSimpleName();
private static final int MAX_SPRITE_NUM = 6;
private static final int SPRITE_SHAPE_RECTANGLE = 0;
private static final int SPRITE_SHAPE_ROUND = 1;
private static final int SPRITE_SHAPE_MAX = 2;
private boolean mKeepTop;
private int mBgIndex;
private int mBgColor;
private final Paint mPaint;
private int mSpriteNum;
private final Sprite[] mSpriteArray = new Sprite[MAX_SPRITE_NUM];
private static final int[] sColorArray = new int[] {
0xff9c27b0, 0xff673ab7,
0xff3f51b5, 0xff2196f3, 0xff03a9f4, 0xff00bcd4,
0xff4caf50
};
public FreeMaterialDrawable () {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setShadowLayer(Ui.dp2pix(3), 0, 0, 0x8a000000);
}
public FreeMaterialDrawable setBgIndex(int bgIndex) {
mBgIndex = bgIndex;
return this;
}
public FreeMaterialDrawable setKeepTop(boolean keepTop) {
mKeepTop = keepTop;
return this;
}
private int getColor(int[] copyOfColorArray) {
int index = MathUtils.random(0, copyOfColorArray.length);
int color = copyOfColorArray[index];
while (color == -1)
color = copyOfColorArray[++index < copyOfColorArray.length ? index : (index = 0)];
copyOfColorArray[index] = -1;
return color;
}
@Override
protected void onBoundsChange(Rect bounds) {
int w = bounds.width();
int h = bounds.height();
Sprite s;
int[] copyOfColorArray = Arrays.copyOf(sColorArray, sColorArray.length);
if (mBgIndex >= 0) {
mBgColor = copyOfColorArray[mBgIndex];
copyOfColorArray[mBgIndex] = -1;
} else {
mBgColor = getColor(copyOfColorArray);
}
mSpriteNum = MathUtils.random(4, MAX_SPRITE_NUM + 1);
for (int i = 0; i < mSpriteNum; i++) {
switch (SPRITE_SHAPE_ROUND) {//MathUtils.random(0, SPRITE_SHAPE_MAX)) {
case SPRITE_SHAPE_RECTANGLE:
s = new Rectangle(w, h, getColor(copyOfColorArray));
break;
default:
case SPRITE_SHAPE_ROUND:
s = new Round(w, h, getColor(copyOfColorArray));
break;
}
mSpriteArray[i] = s;
}
}
@Override
public void draw(Canvas canvas) {
canvas.drawColor(mBgColor);
for (int i = 0; i < mSpriteNum; i++)
mSpriteArray[i].draw(canvas, mPaint);
}
@Override
public void setAlpha(int alpha) {
// Empty
}
@Override
public void setColorFilter(ColorFilter cf) {
// Empty
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
private abstract class Sprite {
private final int mColor;
public Sprite(int w, int h, int color) {
mColor = color;
}
public void draw(Canvas canvas, Paint paint) {
paint.setColor(mColor);
doDraw(canvas, paint);
}
public abstract void doDraw(Canvas canvas, Paint paint);
}
private class Rectangle extends Sprite {
private final int left;
private final int top;
private final int right;
private final int bottom;
public Rectangle(int w, int h, int color) {
super(w, h, color);
int width = MathUtils.random(w / 4, w / 2);
int height = MathUtils.random(h / 4, h / 2);
left = MathUtils.random(w - width / 2);
top = MathUtils.random(h - height / 2);
right = left + width;
bottom = top + height;
}
@Override
public void doDraw(Canvas canvas, Paint paint) {
canvas.drawRect(left, top, right, bottom, paint);
}
}
private class Round extends Sprite {
int mX, mY, mRadius;
public Round(int w, int h, int color) {
super(w, h, color);
int t = (w + h) / 2;
mRadius = MathUtils.random(t / 8, t / 4);
mX = MathUtils.random(w);
mY = MathUtils.random(mKeepTop ? mRadius + 10 : 0, h);
}
@Override
public void doDraw(Canvas canvas, Paint paint) {
canvas.drawCircle(mX, mY, mRadius, paint);
}
}
}
@@ -1,695 +0,0 @@
/*
* Copyright (C) 2014 Balys Valentukevicius
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.drawable;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Property;
import android.util.TypedValue;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
public class MaterialIndicatorDrawable extends Drawable implements Animatable {
private static final String STATE_KEY = "material_menu_icon_state";
public enum IconState {
BURGER, ARROW
}
public enum AnimationState {
BURGER_ARROW;
public IconState getFirstState() {
switch (this) {
case BURGER_ARROW:
return IconState.BURGER;
default:
return null;
}
}
public IconState getSecondState() {
switch (this) {
case BURGER_ARROW:
return IconState.ARROW;
default:
return null;
}
}
}
public enum Stroke {
/**
* 3 dip
*/
REGULAR(3),
/**
* 2 dip
*/
THIN(2),
/**
* 1 dip
*/
EXTRA_THIN(1);
private final int strokeWidth;
Stroke(int strokeWidth) {
this.strokeWidth = strokeWidth;
}
protected static Stroke valueOf(int strokeWidth) {
switch (strokeWidth) {
case 3:
return REGULAR;
case 2:
return THIN;
case 1:
return EXTRA_THIN;
default:
return THIN;
}
}
}
public static final int DEFAULT_COLOR = Color.WHITE;
public static final int DEFAULT_SCALE = 1;
public static final int DEFAULT_TRANSFORM_DURATION = 800;
public static final int DEFAULT_PRESSED_DURATION = 400;
private static final int BASE_DRAWABLE_WIDTH = 40;
private static final int BASE_DRAWABLE_HEIGHT = 40;
private static final int BASE_ICON_WIDTH = 20;
private static final int BASE_CIRCLE_RADIUS = 18;
private static final float ARROW_MID_LINE_ANGLE = 180;
private static final float ARROW_TOP_LINE_ANGLE = 135;
private static final float ARROW_BOT_LINE_ANGLE = 225;
private static final float TRANSFORMATION_START = 0;
private static final float TRANSFORMATION_MID = 1.0f;
private static final float TRANSFORMATION_END = 2.0f;
private static final int DEFAULT_CIRCLE_ALPHA = 200;
private final float diph;
private final float dip1;
private final float dip2;
private final float dip3;
private final float dip4;
private final int width;
private final int height;
private final float strokeWidth;
private final float iconWidth;
private final float topPadding;
private final float sidePadding;
private final float circleRadius;
private final Stroke stroke;
private final Object lock = new Object();
private final Paint gridPaint = new Paint();
private final Paint iconPaint = new Paint();
private final Paint circlePaint = new Paint();
private float transformationValue = 0f;
private float pressedProgressValue = 0f;
private boolean transformationRunning = false;
private IconState currentIconState = IconState.BURGER;
private AnimationState animationState = AnimationState.BURGER_ARROW;
private IconState animatingIconState;
private boolean drawTouchCircle;
private boolean neverDrawTouch;
private boolean rtlEnabled;
private ObjectAnimator transformation;
private ObjectAnimator pressedCircle;
private MaterialMenuState materialMenuState;
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke) {
this(context, color, stroke, DEFAULT_SCALE, DEFAULT_TRANSFORM_DURATION, DEFAULT_PRESSED_DURATION);
}
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke, int transformDuration, int pressedDuration) {
this(context, color, stroke, DEFAULT_SCALE, transformDuration, pressedDuration);
}
public MaterialIndicatorDrawable(Context context, int color, Stroke stroke, int scale, int transformDuration, int pressedDuration) {
Resources resources = context.getResources();
// convert each separately due to various densities
this.dip1 = dpToPx(resources, 1) * scale;
this.dip2 = dpToPx(resources, 2) * scale;
this.dip3 = dpToPx(resources, 3) * scale;
this.dip4 = dpToPx(resources, 4) * scale;
this.diph = dip1 / 2;
this.stroke = stroke;
this.width = (int) (dpToPx(resources, BASE_DRAWABLE_WIDTH) * scale);
this.height = (int) (dpToPx(resources, BASE_DRAWABLE_HEIGHT) * scale);
this.iconWidth = dpToPx(resources, BASE_ICON_WIDTH) * scale;
this.circleRadius = dpToPx(resources, BASE_CIRCLE_RADIUS) * scale;
this.strokeWidth = dpToPx(resources, stroke.strokeWidth) * scale;
this.sidePadding = (width - iconWidth) / 2;
this.topPadding = (height - 5 * dip3) / 2;
initPaint(color);
initAnimations(transformDuration, pressedDuration);
materialMenuState = new MaterialMenuState();
}
private MaterialIndicatorDrawable(int color, Stroke stroke, long transformDuration, long pressedDuration,
int width, int height, float iconWidth, float circleRadius, float strokeWidth, float dip1
) {
this.dip1 = dip1;
this.dip2 = dip1 * 2;
this.dip3 = dip1 * 3;
this.dip4 = dip1 * 4;
this.diph = dip1 / 2;
this.stroke = stroke;
this.width = width;
this.height = height;
this.iconWidth = iconWidth;
this.circleRadius = circleRadius;
this.strokeWidth = strokeWidth;
this.sidePadding = (width - iconWidth) / 2;
this.topPadding = (height - 5 * dip3) / 2;
initPaint(color);
initAnimations((int) transformDuration, (int) pressedDuration);
materialMenuState = new MaterialMenuState();
}
private void initPaint(int color) {
gridPaint.setAntiAlias(false);
gridPaint.setColor(Color.GREEN);
gridPaint.setStrokeWidth(1);
iconPaint.setAntiAlias(true);
iconPaint.setStyle(Style.STROKE);
iconPaint.setStrokeWidth(strokeWidth);
iconPaint.setColor(color);
circlePaint.setAntiAlias(true);
circlePaint.setStyle(Style.FILL);
circlePaint.setColor(color);
circlePaint.setAlpha(DEFAULT_CIRCLE_ALPHA);
setBounds(0, 0, width, height);
}
/*
* Drawing
*/
@Override public void draw(Canvas canvas) {
final float ratio = transformationValue <= 1 ? transformationValue : 2 - transformationValue;
if (rtlEnabled) {
canvas.save();
canvas.scale(-1, 1, 0, 0);
canvas.translate(-getIntrinsicWidth(), 0);
}
drawTopLine(canvas, ratio);
drawMiddleLine(canvas, ratio);
drawBottomLine(canvas, ratio);
if (rtlEnabled) {
canvas.restore();
}
if (drawTouchCircle) drawTouchCircle(canvas);
}
private void drawTouchCircle(Canvas canvas) {
canvas.restore();
canvas.drawCircle(width / 2, height / 2, pressedProgressValue, circlePaint);
}
private void drawMiddleLine(Canvas canvas, float ratio) {
canvas.restore();
canvas.save();
float rotation = 0;
float pivotX = width / 2;
float pivotY = width / 2;
float startX = sidePadding;
float startY = topPadding + dip3 / 2 * 5;
float stopX = width - sidePadding;
float stopY = topPadding + dip3 / 2 * 5;
int alpha = 255;
switch (animationState) {
case BURGER_ARROW:
// rotate by 180
if (isMorphingForward()) {
rotation = ratio * ARROW_MID_LINE_ANGLE;
} else {
rotation = ARROW_MID_LINE_ANGLE + (1 - ratio) * ARROW_MID_LINE_ANGLE;
}
// shorten one end
stopX -= ratio * resolveStrokeModifier(ratio) / 2;
break;
}
iconPaint.setAlpha(alpha);
canvas.rotate(rotation, pivotX, pivotY);
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
iconPaint.setAlpha(255);
}
private void drawTopLine(Canvas canvas, float ratio) {
canvas.save();
float rotation = 0, pivotX = 0, pivotY = 0;
float rotation2 = 0;
// pivot at center of line
float pivotX2 = width / 2 + dip3 / 2;
float pivotY2 = topPadding + dip2;
float startX = sidePadding;
float startY = topPadding + dip2;
float stopX = width - sidePadding;
float stopY = topPadding + dip2;
int alpha = 255;
switch (animationState) {
case BURGER_ARROW:
if (isMorphingForward()) {
// rotate until required angle
rotation = ratio * ARROW_BOT_LINE_ANGLE;
} else {
// rotate back to start doing a 360
rotation = ARROW_BOT_LINE_ANGLE + (1 - ratio) * ARROW_TOP_LINE_ANGLE;
}
// rotate by middle
pivotX = width / 2;
pivotY = height / 2;
// shorten both ends
stopX -= resolveStrokeModifier(ratio);
startX += dip3 * ratio;
break;
}
iconPaint.setAlpha(alpha);
canvas.rotate(rotation, pivotX, pivotY);
canvas.rotate(rotation2, pivotX2, pivotY2);
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
iconPaint.setAlpha(255);
}
private void drawBottomLine(Canvas canvas, float ratio) {
canvas.restore();
canvas.save();
float rotation = 0, pivotX = 0, pivotY = 0;
float rotation2 = 0;
// pivot at center of line
float pivotX2 = width / 2 + dip3 / 2;
float pivotY2 = height - topPadding - dip2;
float startX = sidePadding;
float startY = height - topPadding - dip2;
float stopX = width - sidePadding;
float stopY = height - topPadding - dip2;
switch (animationState) {
case BURGER_ARROW:
if (isMorphingForward()) {
// rotate to required angle
rotation = ARROW_TOP_LINE_ANGLE * ratio;
} else {
// rotate back to start doing a 360
rotation = ARROW_TOP_LINE_ANGLE + (1 - ratio) * ARROW_BOT_LINE_ANGLE;
}
// pivot center of canvas
pivotX = width / 2;
pivotY = height / 2;
// shorten both ends
stopX = width - sidePadding - resolveStrokeModifier(ratio);
startX = sidePadding + dip3 * ratio;
break;
}
canvas.rotate(rotation, pivotX, pivotY);
canvas.rotate(rotation2, pivotX2, pivotY2);
canvas.drawLine(startX, startY, stopX, stopY, iconPaint);
}
private boolean isMorphingForward() {
return transformationValue <= TRANSFORMATION_MID;
}
private float resolveStrokeModifier(float ratio) {
switch (stroke) {
case REGULAR:
return ratio * dip3;
case THIN:
return ratio * (dip3 + diph);
case EXTRA_THIN:
return ratio * dip4;
}
return 0;
}
@Override public void setAlpha(int alpha) {
iconPaint.setAlpha(alpha);
}
@Override public void setColorFilter(ColorFilter cf) {
iconPaint.setColorFilter(cf);
}
@Override public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
/*
* Accessor methods
*/
public void setColor(int color) {
iconPaint.setColor(color);
circlePaint.setColor(color);
invalidateSelf();
}
public void setTransformationDuration(int duration) {
transformation.setDuration(duration);
}
public void setPressedDuration(int duration) {
pressedCircle.setDuration(duration);
}
public void setInterpolator(Interpolator interpolator) {
transformation.setInterpolator(interpolator);
}
public void setNeverDrawTouch(boolean neverDrawTouch) {
this.neverDrawTouch = neverDrawTouch;
}
public void setIconState(IconState iconState) {
synchronized (lock) {
if (transformationRunning) {
transformation.cancel();
transformationRunning = false;
}
if (currentIconState == iconState) return;
switch (iconState) {
case BURGER:
animationState = AnimationState.BURGER_ARROW;
transformationValue = TRANSFORMATION_START;
break;
case ARROW:
animationState = AnimationState.BURGER_ARROW;
transformationValue = TRANSFORMATION_MID;
break;
}
currentIconState = iconState;
invalidateSelf();
}
}
public void animateIconState(IconState state, boolean drawTouch) {
synchronized (lock) {
if (transformationRunning) {
transformation.end();
pressedCircle.end();
}
drawTouchCircle = drawTouch;
animatingIconState = state;
start();
}
}
public IconState setTransformationOffset(AnimationState animationState, float offset) {
if (offset < TRANSFORMATION_START || offset > TRANSFORMATION_END) {
throw new IllegalArgumentException(
String.format("Value must be between %s and %s", TRANSFORMATION_START, TRANSFORMATION_END)
);
}
this.animationState = animationState;
final boolean isFirstIcon = offset < TRANSFORMATION_MID || offset == TRANSFORMATION_END;
currentIconState = isFirstIcon ? animationState.getFirstState() : animationState.getSecondState();
animatingIconState = isFirstIcon ? animationState.getSecondState() : animationState.getFirstState();
setTransformationValue(offset);
return currentIconState;
}
public void setRTLEnabled(boolean rtlEnabled) {
this.rtlEnabled = rtlEnabled;
invalidateSelf();
}
public IconState getIconState() {
return currentIconState;
}
/*
* Animations
*/
private final Property<MaterialIndicatorDrawable, Float> transformationProperty
= new Property<MaterialIndicatorDrawable, Float>(Float.class, "transformation") {
@Override
public Float get(MaterialIndicatorDrawable object) {
return object.getTransformationValue();
}
@Override
public void set(MaterialIndicatorDrawable object, Float value) {
object.setTransformationValue(value);
}
};
private final Property<MaterialIndicatorDrawable, Float> pressedProgressProperty
= new Property<MaterialIndicatorDrawable, Float>(Float.class, "pressedProgress") {
@Override
public Float get(MaterialIndicatorDrawable object) {
return object.getPressedProgress();
}
@Override
public void set(MaterialIndicatorDrawable object, Float value) {
object.setPressedProgress(value);
}
};
public Float getTransformationValue() {
return transformationValue;
}
public void setTransformationValue(Float value) {
this.transformationValue = value;
invalidateSelf();
}
public Float getPressedProgress() {
return pressedProgressValue;
}
public void setPressedProgress(Float value) {
this.pressedProgressValue = value;
circlePaint.setAlpha((int) (DEFAULT_CIRCLE_ALPHA * (1 - value / (circleRadius * 1.22f))));
invalidateSelf();
}
private void initAnimations(int transformDuration, int pressedDuration) {
transformation = ObjectAnimator.ofFloat(this, transformationProperty, 0);
transformation.setInterpolator(new DecelerateInterpolator(3));
transformation.setDuration(transformDuration);
transformation.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationEnd(Animator animation) {
transformationRunning = false;
setIconState(animatingIconState);
}
});
pressedCircle = ObjectAnimator.ofFloat(this, pressedProgressProperty, 0, 0);
pressedCircle.setDuration(pressedDuration);
pressedCircle.setInterpolator(new DecelerateInterpolator());
pressedCircle.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationEnd(Animator animation) {
pressedProgressValue = 0;
}
@Override public void onAnimationCancel(Animator animation) {
pressedProgressValue = 0;
}
});
}
private boolean resolveTransformation() {
boolean isCurrentBurger = currentIconState == IconState.BURGER;
boolean isCurrentArrow = currentIconState == IconState.ARROW;
boolean isAnimatingBurger = animatingIconState == IconState.BURGER;
boolean isAnimatingArrow = animatingIconState == IconState.ARROW;
if ((isCurrentBurger && isAnimatingArrow) || (isCurrentArrow && isAnimatingBurger)) {
animationState = AnimationState.BURGER_ARROW;
return isCurrentBurger;
}
throw new IllegalStateException(
String.format("Animating from %s to %s is not supported", currentIconState, animatingIconState)
);
}
@Override public void start() {
if (transformationRunning || animatingIconState == null || animatingIconState == currentIconState) return;
transformationRunning = true;
final boolean direction = resolveTransformation();
transformation.setFloatValues(
direction ? TRANSFORMATION_START : TRANSFORMATION_MID,
direction ? TRANSFORMATION_MID : TRANSFORMATION_END
);
transformation.start();
if (pressedCircle.isRunning()) {
pressedCircle.cancel();
}
if (drawTouchCircle && !neverDrawTouch) {
pressedCircle.setFloatValues(0, circleRadius * 1.22f);
pressedCircle.start();
}
invalidateSelf();
}
@Override public void stop() {
if (isRunning() && transformation.isRunning()) {
transformation.end();
} else {
transformationRunning = false;
invalidateSelf();
}
}
@Override public boolean isRunning() {
return transformationRunning;
}
@Override
public int getIntrinsicWidth() {
return width;
}
@Override
public int getIntrinsicHeight() {
return height;
}
@Override
public ConstantState getConstantState() {
materialMenuState.changingConfigurations = getChangingConfigurations();
return materialMenuState;
}
@Override
public Drawable mutate() {
materialMenuState = new MaterialMenuState();
return this;
}
/**
* Call from {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)} to store current icon state
*
* @param outState outState
*/
public void onSaveInstanceState(Bundle outState) {
outState.putString(STATE_KEY, currentIconState.name());
}
/**
* Call from {@link android.app.Activity#onPostCreate(android.os.Bundle)} to restore icon state
*
* @param state state
*/
public void syncState(Bundle state) {
if (state != null) {
String iconStateName = state.getString(STATE_KEY);
if (iconStateName == null) {
iconStateName = MaterialIndicatorDrawable.IconState.BURGER.name();
}
setIconState(MaterialIndicatorDrawable.IconState.valueOf(iconStateName));
}
}
private final class MaterialMenuState extends ConstantState {
private int changingConfigurations;
private MaterialMenuState() {
}
@Override
public Drawable newDrawable() {
MaterialIndicatorDrawable drawable = new MaterialIndicatorDrawable(
circlePaint.getColor(), stroke, transformation.getDuration(),
pressedCircle.getDuration(), width, height, iconWidth, circleRadius, strokeWidth, dip1
);
drawable.setIconState(animatingIconState != null ? animatingIconState : currentIconState);
drawable.setRTLEnabled(rtlEnabled);
return drawable;
}
@Override
public int getChangingConfigurations() {
return changingConfigurations;
}
}
static float dpToPx(Resources resources, float dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics());
}
}
@@ -1,87 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect;
import android.animation.ValueAnimator;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
public class DrawableTransition {
public static void transit(final Drawable drawable, boolean fromDark, long duration) {
final AlphaSatColorMatrixEvaluator evaluator = new AlphaSatColorMatrixEvaluator(fromDark);
evaluator.setFraction(0.0f);
drawable.setColorFilter(new ColorMatrixColorFilter(evaluator.getColorMatrix()));
ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 1.0f);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float f = (Float) animation.getAnimatedValue();
evaluator.setFraction(f);
drawable.setColorFilter(new ColorMatrixColorFilter(evaluator.getColorMatrix()));
}
});
animator.setDuration(duration);
animator.start();
}
// From rnr.tests.imageloadingpattern.AlphaSatColorMatrixEvaluator
// with modification
private static class AlphaSatColorMatrixEvaluator {
private final ColorMatrix colorMatrix;
private final float[] elements = new float[20];
private final boolean mFromDark;
public AlphaSatColorMatrixEvaluator(boolean fromDark) {
colorMatrix = new ColorMatrix ();
mFromDark = fromDark;
}
public ColorMatrix getColorMatrix() {
return colorMatrix;
}
public void setFraction(float fraction) {
// There are 4 phases so we multiply fraction by that amount
float phase = fraction * 4;
// Compute the alpha change over period [0, 2]
float alpha = Math.min(phase, 2.0f) / 2.0f;
elements [19] = Math.round(alpha * 255);
// We substract to make the picture look darker, it will automatically clamp
// This is spread over period [0, 3]
final int MaxBlacker = 50;
float blackening = Math.round((1 - Math.min(phase, 3.0f) / 3.0f) * MaxBlacker);
elements [4] = elements [9] = elements [14] = mFromDark ? -blackening : blackening;
// Finally we desaturate over [0, 4], taken from ColorMatrix.SetSaturation
float invSat = 1 - Math.max(0.2f, fraction);
float R = 0.213f * invSat;
float G = 0.715f * invSat;
float B = 0.072f * invSat;
elements[0] = R + fraction; elements[1] = G; elements[2] = B;
elements[5] = R; elements[6] = G + fraction; elements[7] = B;
elements[10] = R; elements[11] = G; elements[12] = B + fraction;
colorMatrix.set(elements);
}
}
}
@@ -1,423 +0,0 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect.ripple;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.os.Build;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.hippo.ehviewer.util.MathUtils;
/**
* Draws a Material ripple.
*/
class Ripple {
@SuppressWarnings("unused")
private static final String TAG = Ripple.class.getSimpleName();
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator DECEL_INTERPOLATOR = new LogInterpolator();
private static final float GLOBAL_SPEED = 1.0f;
private static final float WAVE_TOUCH_DOWN_ACCELERATION = 1024.0f * GLOBAL_SPEED;
private static final float WAVE_TOUCH_UP_ACCELERATION = 3400.0f * GLOBAL_SPEED;
private static final float WAVE_OPACITY_DECAY_VELOCITY = 3.0f / GLOBAL_SPEED;
private static final long RIPPLE_ENTER_DELAY = 80;
private final RippleOwner mOwner;
/** Bounds used for computing max radius. */
private final Rect mBounds;
/** Full-opacity color for drawing this ripple. */
private int mColorOpaque;
/** Maximum ripple radius. */
private float mOuterRadius;
/** Screen density used to adjust pixel-based velocities. */
private float mDensity;
private float mStartingX;
private float mStartingY;
private float mClampedStartingX;
private float mClampedStartingY;
// Software animators.
private ObjectAnimator mAnimRadius;
private ObjectAnimator mAnimOpacity;
private ObjectAnimator mAnimX;
private ObjectAnimator mAnimY;
// Software rendering properties.
private float mOpacity = 1;
private float mOuterX;
private float mOuterY;
// Values used to tween between the start and end positions.
private float mTweenRadius = 0;
private float mTweenX = 0;
private float mTweenY = 0;
/** Whether we have an explicit maximum radius. */
private boolean mHasMaxRadius;
/** Whether we were canceled externally and should avoid self-removal. */
private boolean mCanceled;
/**
* Creates a new ripple.
*/
public Ripple(RippleOwner owner, Rect bounds, float startingX, float startingY) {
mOwner = owner;
mBounds = bounds;
mStartingX = startingX;
mStartingY = startingY;
}
public void setup(int maxRadius, int color, float density) {
mColorOpaque = color | 0xFF000000;
mOpacity = Color.alpha(color) / 2 / 255.0f;
if (maxRadius != RippleOwner.RADIUS_AUTO) {
mHasMaxRadius = true;
mOuterRadius = maxRadius;
} else {
final float halfWidth = mBounds.width() / 2.0f;
final float halfHeight = mBounds.height() / 2.0f;
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
}
mOuterX = 0;
mOuterY = 0;
mDensity = density;
clampStartingPosition();
}
private void clampStartingPosition() {
final float cX = mBounds.exactCenterX();
final float cY = mBounds.exactCenterY();
final float dX = mStartingX - cX;
final float dY = mStartingY - cY;
final float r = mOuterRadius;
if (dX * dX + dY * dY > r * r) {
// Point is outside the circle, clamp to the circumference.
final double angle = Math.atan2(dY, dX);
mClampedStartingX = cX + (float) (Math.cos(angle) * r);
mClampedStartingY = cY + (float) (Math.sin(angle) * r);
} else {
mClampedStartingX = mStartingX;
mClampedStartingY = mStartingY;
}
}
public void onHotspotBoundsChanged() {
if (!mHasMaxRadius) {
final float halfWidth = mBounds.width() / 2.0f;
final float halfHeight = mBounds.height() / 2.0f;
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
clampStartingPosition();
}
}
public void setOpacity(float a) {
mOpacity = a;
invalidateSelf();
}
public float getOpacity() {
return mOpacity;
}
public void setRadiusGravity(float r) {
mTweenRadius = r;
invalidateSelf();
}
public float getRadiusGravity() {
return mTweenRadius;
}
public void setXGravity(float x) {
mTweenX = x;
invalidateSelf();
}
public float getXGravity() {
return mTweenX;
}
public void setYGravity(float y) {
mTweenY = y;
invalidateSelf();
}
public float getYGravity() {
return mTweenY;
}
/**
* Draws the ripple centered at (0,0) using the specified paint.
*/
public boolean draw(Canvas c, Paint p) {
return drawSoftware(c, p);
}
private boolean drawSoftware(Canvas c, Paint p) {
boolean hasContent = false;
p.setColor(mColorOpaque);
final int alpha = MathUtils.clamp((int) (255 * mOpacity + 0.5f), 0, 255);
final float radius = MathUtils.lerp(0, mOuterRadius, mTweenRadius);
if (alpha > 0 && radius > 0) {
final float x = MathUtils.lerp(
mClampedStartingX - mBounds.exactCenterX(), mOuterX, mTweenX);
final float y = MathUtils.lerp(
mClampedStartingY - mBounds.exactCenterY(), mOuterY, mTweenY);
p.setAlpha(alpha);
p.setStyle(Style.FILL);
c.drawCircle(x, y, radius, p);
hasContent = true;
}
return hasContent;
}
/**
* Returns the maximum bounds of the ripple relative to the ripple center.
*/
public void getBounds(Rect bounds) {
final int outerX = (int) mOuterX;
final int outerY = (int) mOuterY;
final int r = (int) mOuterRadius + 1;
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
}
/**
* Specifies the starting position relative to the drawable bounds. No-op if
* the ripple has already entered.
*/
public void move(float x, float y) {
mStartingX = x;
mStartingY = y;
clampStartingPosition();
}
/**
* Starts the enter animation.
*/
public void enter() {
cancel();
final int radiusDuration = (int)
(1000 * Math.sqrt(mOuterRadius / WAVE_TOUCH_DOWN_ACCELERATION * mDensity) + 0.5);
final ObjectAnimator radius = ObjectAnimator.ofFloat(this, "radiusGravity", 1);
radius.setDuration(radiusDuration);
radius.setInterpolator(LINEAR_INTERPOLATOR);
radius.setStartDelay(RIPPLE_ENTER_DELAY);
final ObjectAnimator cX = ObjectAnimator.ofFloat(this, "xGravity", 1);
cX.setDuration(radiusDuration);
cX.setInterpolator(LINEAR_INTERPOLATOR);
cX.setStartDelay(RIPPLE_ENTER_DELAY);
final ObjectAnimator cY = ObjectAnimator.ofFloat(this, "yGravity", 1);
cY.setDuration(radiusDuration);
cY.setInterpolator(LINEAR_INTERPOLATOR);
cY.setStartDelay(RIPPLE_ENTER_DELAY);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
radius.setAutoCancel(true);
cX.setAutoCancel(true);
cY.setAutoCancel(true);
}
mAnimRadius = radius;
mAnimX = cX;
mAnimY = cY;
// Enter animations always run on the UI thread, since it's unlikely
// that anything interesting is happening until the user lifts their
// finger.
radius.start();
cX.start();
cY.start();
}
/**
* Starts the exit animation.
*/
public void exit() {
cancel();
final float radius = MathUtils.lerp(0, mOuterRadius, mTweenRadius);
final float remaining;
if (mAnimRadius != null && mAnimRadius.isRunning()) {
remaining = mOuterRadius - radius;
} else {
remaining = mOuterRadius;
}
final int radiusDuration = (int) (1000 * Math.sqrt(remaining / (WAVE_TOUCH_UP_ACCELERATION
+ WAVE_TOUCH_DOWN_ACCELERATION) * mDensity) + 0.5);
final int opacityDuration = (int) (1000 * 1 / WAVE_OPACITY_DECAY_VELOCITY + 0.5f);
exitSoftware(radiusDuration, opacityDuration);
}
/**
* Jump all animations to their end state. The caller is responsible for
* removing the ripple from the list of animating ripples.
*/
public void jump() {
mCanceled = true;
endSoftwareAnimations();
mCanceled = false;
}
private void endSoftwareAnimations() {
if (mAnimRadius != null) {
mAnimRadius.end();
mAnimRadius = null;
}
if (mAnimOpacity != null) {
mAnimOpacity.end();
mAnimOpacity = null;
}
if (mAnimX != null) {
mAnimX.end();
mAnimX = null;
}
if (mAnimY != null) {
mAnimY.end();
mAnimY = null;
}
}
private void exitSoftware(int radiusDuration, int opacityDuration) {
final ObjectAnimator radiusAnim = ObjectAnimator.ofFloat(this, "radiusGravity", 1);
radiusAnim.setDuration(radiusDuration);
radiusAnim.setInterpolator(DECEL_INTERPOLATOR);
final ObjectAnimator xAnim = ObjectAnimator.ofFloat(this, "xGravity", 1);
xAnim.setDuration(radiusDuration);
xAnim.setInterpolator(DECEL_INTERPOLATOR);
final ObjectAnimator yAnim = ObjectAnimator.ofFloat(this, "yGravity", 1);
yAnim.setDuration(radiusDuration);
yAnim.setInterpolator(DECEL_INTERPOLATOR);
final ObjectAnimator opacityAnim = ObjectAnimator.ofFloat(this, "opacity", 0);
opacityAnim.setDuration(opacityDuration);
opacityAnim.setInterpolator(LINEAR_INTERPOLATOR);
opacityAnim.addListener(mAnimationListener);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
radiusAnim.setAutoCancel(true);
xAnim.setAutoCancel(true);
yAnim.setAutoCancel(true);
opacityAnim.setAutoCancel(true);
}
mAnimRadius = radiusAnim;
mAnimOpacity = opacityAnim;
mAnimX = xAnim;
mAnimY = yAnim;
radiusAnim.start();
opacityAnim.start();
xAnim.start();
yAnim.start();
}
/**
* Cancels all animations. The caller is responsible for removing
* the ripple from the list of animating ripples.
*/
public void cancel() {
mCanceled = true;
cancelSoftwareAnimations();
mCanceled = false;
}
private void cancelSoftwareAnimations() {
if (mAnimRadius != null) {
mAnimRadius.cancel();
mAnimRadius = null;
}
if (mAnimOpacity != null) {
mAnimOpacity.cancel();
mAnimOpacity = null;
}
if (mAnimX != null) {
mAnimX.cancel();
mAnimX = null;
}
if (mAnimY != null) {
mAnimY.cancel();
mAnimY = null;
}
}
private void removeSelf() {
// The owner will invalidate itself.
if (!mCanceled) {
mOwner.removeRipple(this);
}
}
private void invalidateSelf() {
mOwner.invalidateSelf();
}
private final AnimatorListenerAdapter mAnimationListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
removeSelf();
}
};
/**
* Interpolator with a smooth log deceleration
*/
private static final class LogInterpolator implements Interpolator {
@Override
public float getInterpolation(float input) {
return 1 - (float) Math.pow(400, -input * 1.4);
}
}
}
@@ -1,285 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect.ripple;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.os.Build;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.hippo.ehviewer.util.MathUtils;
/**
* Draws a Material ripple.
*/
class RippleBackground {
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final float GLOBAL_SPEED = 1.0f;
private static final float WAVE_OPACITY_DECAY_VELOCITY = 3.0f / GLOBAL_SPEED;
private static final float WAVE_OUTER_OPACITY_EXIT_VELOCITY_MAX = 4.5f * GLOBAL_SPEED;
private static final float WAVE_OUTER_OPACITY_EXIT_VELOCITY_MIN = 1.5f * GLOBAL_SPEED;
private static final float WAVE_OUTER_OPACITY_ENTER_VELOCITY = 10.0f * GLOBAL_SPEED;
private static final float WAVE_OUTER_SIZE_INFLUENCE_MAX = 200f;
private static final float WAVE_OUTER_SIZE_INFLUENCE_MIN = 40f;
private final RippleOwner mOwner;
/** Bounds used for computing max radius. */
private final Rect mBounds;
/** Full-opacity color for drawing this ripple. */
private int mColorOpaque;
/** Maximum alpha value for drawing this ripple. */
private int mColorAlpha;
/** Maximum ripple radius. */
private float mOuterRadius;
/** Screen density used to adjust pixel-based velocities. */
private float mDensity;
// Software animators.
private ObjectAnimator mAnimOuterOpacity;
// Software rendering properties.
private float mOuterOpacity = 0;
private float mOuterX;
private float mOuterY;
/** Whether we have an explicit maximum radius. */
private boolean mHasMaxRadius;
/**
* Creates a new ripple.
*/
public RippleBackground(RippleOwner owner, Rect bounds) {
mOwner = owner;
mBounds = bounds;
}
public void setup(int maxRadius, int color, float density) {
mColorOpaque = color | 0xFF000000;
mColorAlpha = Color.alpha(color) / 2;
if (maxRadius != RippleOwner.RADIUS_AUTO) {
mHasMaxRadius = true;
mOuterRadius = maxRadius;
} else {
final float halfWidth = mBounds.width() / 2.0f;
final float halfHeight = mBounds.height() / 2.0f;
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
}
mOuterX = 0;
mOuterY = 0;
mDensity = density;
}
public void onHotspotBoundsChanged() {
if (!mHasMaxRadius) {
final float halfWidth = mBounds.width() / 2.0f;
final float halfHeight = mBounds.height() / 2.0f;
mOuterRadius = (float) Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
}
}
public void setOuterOpacity(float a) {
mOuterOpacity = a;
invalidateSelf();
}
public float getOuterOpacity() {
return mOuterOpacity;
}
/**
* Draws the ripple centered at (0,0) using the specified paint.
*/
public boolean draw(Canvas c, Paint p) {
return drawSoftware(c, p);
}
public boolean shouldDraw() {
final int outerAlpha = (int) (mColorAlpha * mOuterOpacity + 0.5f);
return outerAlpha > 0 && mOuterRadius > 0;
}
private boolean drawSoftware(Canvas c, Paint p) {
boolean hasContent = false;
p.setColor(mColorOpaque);
final int outerAlpha = (int) (mColorAlpha * mOuterOpacity + 0.5f);
if (outerAlpha > 0 && mOuterRadius > 0) {
p.setAlpha(outerAlpha);
p.setStyle(Style.FILL);
c.drawCircle(mOuterX, mOuterY, mOuterRadius, p);
hasContent = true;
}
return hasContent;
}
/**
* Returns the maximum bounds of the ripple relative to the ripple center.
*/
public void getBounds(Rect bounds) {
final int outerX = (int) mOuterX;
final int outerY = (int) mOuterY;
final int r = (int) mOuterRadius + 1;
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
}
/**
* Starts the enter animation.
*/
public void enter() {
cancel();
final int outerDuration = (int) (1000 * 1.0f / WAVE_OUTER_OPACITY_ENTER_VELOCITY);
final ObjectAnimator outer = ObjectAnimator.ofFloat(this, "outerOpacity", 0, 1);
outer.setDuration(outerDuration);
outer.setInterpolator(LINEAR_INTERPOLATOR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
outer.setAutoCancel(true);
}
mAnimOuterOpacity = outer;
// Enter animations always run on the UI thread, since it's unlikely
// that anything interesting is happening until the user lifts their
// finger.
outer.start();
}
/**
* Starts the exit animation.
*/
public void exit() {
cancel();
// Scale the outer max opacity and opacity velocity based
// on the size of the outer radius.
final int opacityDuration = (int) (1000 / WAVE_OPACITY_DECAY_VELOCITY + 0.5f);
final float outerSizeInfluence = MathUtils.clamp(
(mOuterRadius - WAVE_OUTER_SIZE_INFLUENCE_MIN * mDensity)
/ (WAVE_OUTER_SIZE_INFLUENCE_MAX * mDensity), 0, 1);
final float outerOpacityVelocity = MathUtils.lerp(WAVE_OUTER_OPACITY_EXIT_VELOCITY_MIN,
WAVE_OUTER_OPACITY_EXIT_VELOCITY_MAX, outerSizeInfluence);
// Determine at what time the inner and outer opacity intersect.
// inner(t) = mOpacity - t * WAVE_OPACITY_DECAY_VELOCITY / 1000
// outer(t) = mOuterOpacity + t * WAVE_OUTER_OPACITY_VELOCITY / 1000
final int inflectionDuration = Math.max(0, (int) (1000 * (1 - mOuterOpacity)
/ (WAVE_OPACITY_DECAY_VELOCITY + outerOpacityVelocity) + 0.5f));
final int inflectionOpacity = (int) (mColorAlpha * (mOuterOpacity
+ inflectionDuration * outerOpacityVelocity * outerSizeInfluence / 1000) + 0.5f);
exitSoftware(opacityDuration, inflectionDuration, inflectionOpacity);
}
/**
* Jump all animations to their end state. The caller is responsible for
* removing the ripple from the list of animating ripples.
*/
public void jump() {
endSoftwareAnimations();
}
private void endSoftwareAnimations() {
if (mAnimOuterOpacity != null) {
mAnimOuterOpacity.end();
mAnimOuterOpacity = null;
}
}
private void exitSoftware(int opacityDuration, int inflectionDuration, int inflectionOpacity) {
final ObjectAnimator outerOpacityAnim;
if (inflectionDuration > 0) {
// Outer opacity continues to increase for a bit.
outerOpacityAnim = ObjectAnimator.ofFloat(this,
"outerOpacity", inflectionOpacity / 255.0f);
outerOpacityAnim.setDuration(inflectionDuration);
outerOpacityAnim.setInterpolator(LINEAR_INTERPOLATOR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
outerOpacityAnim.setAutoCancel(true);
}
// Chain the outer opacity exit animation.
final int outerDuration = opacityDuration - inflectionDuration;
if (outerDuration > 0) {
outerOpacityAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
final ObjectAnimator outerFadeOutAnim = ObjectAnimator.ofFloat(
RippleBackground.this, "outerOpacity", 0);
outerFadeOutAnim.setDuration(outerDuration);
outerFadeOutAnim.setInterpolator(LINEAR_INTERPOLATOR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
outerFadeOutAnim.setAutoCancel(true);
}
mAnimOuterOpacity = outerFadeOutAnim;
outerFadeOutAnim.start();
}
@Override
public void onAnimationCancel(Animator animation) {
animation.removeListener(this);
}
});
}
} else {
outerOpacityAnim = ObjectAnimator.ofFloat(this, "outerOpacity", 0);
outerOpacityAnim.setDuration(opacityDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
outerOpacityAnim.setAutoCancel(true);
}
}
mAnimOuterOpacity = outerOpacityAnim;
outerOpacityAnim.start();
}
/**
* Cancel all animations. The caller is responsible for removing
* the ripple from the list of animating ripples.
*/
public void cancel() {
cancelSoftwareAnimations();
}
private void cancelSoftwareAnimations() {
if (mAnimOuterOpacity != null) {
mAnimOuterOpacity.cancel();
mAnimOuterOpacity = null;
}
}
private void invalidateSelf() {
mOwner.invalidateSelf();
}
}
@@ -1,579 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect.ripple;
import android.annotation.TargetApi;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import com.hippo.ehviewer.widget.Hotspotable;
import java.util.Arrays;
/**
* Drawable that shows a ripple effect in response to state changes. The
* anchoring position of the ripple for a given state may be specified by
* calling {@link #setHotspot(float, float)} with the corresponding state
* attribute identifier.
* <p>
* A touch feedback drawable may contain multiple child layers, including a
* special mask layer that is not drawn to the screen. A single layer may be set
* as the mask by specifying its android:id value as {@link android.R.id#mask}.
* <pre>
* <code>&lt!-- A red ripple masked against an opaque rectangle. --/>
* &ltripple android:color="#ffff0000">
* &ltitem android:id="@android:id/mask"
* android:drawable="@android:color/white" />
* &ltripple /></code>
* </pre>
* <p>
* If a mask layer is set, the ripple effect will be masked against that layer
* before it is drawn over the composite of the remaining child layers.
* <p>
* If no mask layer is set, the ripple effect is masked against the composite
* of the child layers.
* <pre>
* <code>&lt!-- A blue ripple drawn atop a black rectangle. --/>
* &ltripple android:color="#ff00ff00">
* &ltitem android:drawable="@android:color/black" />
* &ltripple />
*
* &lt!-- A red ripple drawn atop a drawable resource. --/>
* &ltripple android:color="#ff00ff00">
* &ltitem android:drawable="@drawable/my_drawable" />
* &ltripple /></code>
* </pre>
* <p>
* If no child layers or mask is specified and the ripple is set as a View
* background, the ripple will be drawn atop the first available parent
* background within the View's hierarchy. In this case, the drawing region
* may extend outside of the Drawable bounds.
* <pre>
* <code>&lt!-- An unbounded green ripple. --/>
* &ltripple android:color="#ff0000ff" /></code>
* </pre>
*
* @attr ref android.R.styleable#RippleDrawable_color
*/
public class RippleDrawable extends Drawable implements RippleOwner, Hotspotable {
@SuppressWarnings("unused")
private static final String TAG = RippleDrawable.class.getSimpleName();
/** The maximum number of ripples supported. */
private static final int MAX_RIPPLES = 10;
/** Current ripple effect bounds, used to constrain ripple effects. */
private final Rect mHotspotBounds = new Rect();
/** The current background. May be actively animating or pending entry. */
private RippleBackground mBackground;
/** Whether we expect to draw a background when visible. */
private boolean mBackgroundActive;
/** The current ripple. May be actively animating or pending entry. */
private Ripple mRipple;
/** Whether we expect to draw a ripple when visible. */
private boolean mRippleActive;
// Hotspot coordinates that are awaiting activation.
private float mPendingX;
private float mPendingY;
private boolean mHasPending;
/**
* Lazily-created array of actively animating ripples. Inactive ripples are
* pruned during draw(). The locations of these will not change.
*/
private Ripple[] mExitingRipples;
private int mExitingRipplesCount = 0;
/** Paint used to control appearance of ripples. */
private Paint mRipplePaint;
/** Target density of the display into which ripples are drawn. */
private final float mDensity = 1.0f;
/** Whether bounds are being overridden. */
private boolean mOverrideBounds;
/**
* Whether the next draw MUST draw something to canvas. Used to work around
* a bug in hardware invalidation following a render thread-accelerated
* animation.
*/
private boolean mNeedsDraw;
private ColorStateList mColor = ColorStateList.valueOf(Color.MAGENTA);
private int mMaxRadius = RADIUS_AUTO;
private final Drawable mContent;
RippleDrawable(ColorStateList color, Drawable content) {
setColor(color);
mContent = content;
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void jumpToCurrentState() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
super.jumpToCurrentState();
}
boolean needsDraw = false;
if (mRipple != null) {
mRipple.jump();
}
if (mBackground != null) {
mBackground.jump();
}
needsDraw |= cancelExitingRipples();
mNeedsDraw = needsDraw;
invalidateSelf();
}
private boolean cancelExitingRipples() {
final int count = mExitingRipplesCount;
final Ripple[] ripples = mExitingRipples;
for (int i = 0; i < count; i++) {
ripples[i].cancel();
}
if (ripples != null) {
Arrays.fill(ripples, 0, count, null);
}
mExitingRipplesCount = 0;
return false;
}
@Override
public void setAlpha(int alpha) {
mColor.withAlpha(alpha);
}
@Override
public int getAlpha() {
return Color.alpha(mColor.getDefaultColor());
}
@Override
public void setColorFilter(ColorFilter cf) {
//TODO Paint.setColorFilter(filter) ?
}
@Override
public int getOpacity() {
// Worst-case scenario.
return PixelFormat.TRANSLUCENT;
}
@Override
protected boolean onStateChange(int[] stateSet) {
boolean changed = false;
if (mContent != null)
changed |= mContent.setState(stateSet);
boolean enabled = false;
boolean pressed = false;
boolean focused = false;
for (int state : stateSet) {
if (state == android.R.attr.state_enabled) {
enabled = true;
}
if (state == android.R.attr.state_focused) {
focused = true;
}
if (state == android.R.attr.state_pressed) {
pressed = true;
}
}
setRippleActive(enabled && pressed);
setBackgroundActive(focused || (enabled && pressed));
return changed;
}
private void setRippleActive(boolean active) {
if (mRippleActive != active) {
mRippleActive = active;
if (active) {
tryRippleEnter();
} else {
tryRippleExit();
}
}
}
private void setBackgroundActive(boolean active) {
if (mBackgroundActive != active) {
mBackgroundActive = active;
if (active) {
tryBackgroundEnter();
} else {
tryBackgroundExit();
}
}
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
if (!mOverrideBounds) {
mHotspotBounds.set(bounds);
onHotspotBoundsChanged();
}
if (mContent != null)
mContent.setBounds(bounds);
invalidateSelf();
}
@Override
public boolean setVisible(boolean visible, boolean restart) {
final boolean changed = super.setVisible(visible, restart);
if (!visible) {
clearHotspots();
} else if (changed) {
// If we just became visible, ensure the background and ripple
// visibilities are consistent with their internal states.
if (mRippleActive) {
tryRippleEnter();
}
if (mBackgroundActive) {
tryBackgroundEnter();
}
}
return changed;
}
@Override
public boolean isStateful() {
return true;
}
public void setColor(ColorStateList color) {
int alpha = Color.alpha(color.getDefaultColor());
mColor = color.withAlpha((int) (alpha * (1 - 0.001f * alpha)));
invalidateSelf();
}
@Override
public void setHotspot(float x, float y) {
if (mRipple == null || mBackground == null) {
mPendingX = x;
mPendingY = y;
mHasPending = true;
}
if (mRipple != null) {
mRipple.move(x, y);
}
}
/**
* Creates an active hotspot at the specified location.
*/
private void tryBackgroundEnter() {
if (mBackground == null) {
mBackground = new RippleBackground(this, mHotspotBounds);
}
final int color = mColor.getColorForState(getState(), Color.TRANSPARENT);
mBackground.setup(mMaxRadius, color, mDensity);
mBackground.enter();
}
private void tryBackgroundExit() {
if (mBackground != null) {
// Don't null out the background, we need it to draw!
mBackground.exit();
}
}
/**
* Attempts to start an enter animation for the active hotspot. Fails if
* there are too many animating ripples.
*/
private void tryRippleEnter() {
if (mExitingRipplesCount >= MAX_RIPPLES) {
// This should never happen unless the user is tapping like a maniac
// or there is a bug that's preventing ripples from being removed.
return;
}
if (mRipple == null) {
final float x;
final float y;
if (mHasPending) {
mHasPending = false;
x = mPendingX;
y = mPendingY;
} else {
x = mHotspotBounds.exactCenterX();
y = mHotspotBounds.exactCenterY();
}
mRipple = new Ripple(this, mHotspotBounds, x, y);
}
final int color = mColor.getColorForState(getState(), Color.TRANSPARENT);
mRipple.setup(mMaxRadius, color, mDensity);
mRipple.enter();
}
/**
* Attempts to start an exit animation for the active hotspot. Fails if
* there is no active hotspot.
*/
private void tryRippleExit() {
if (mRipple != null) {
if (mExitingRipples == null) {
mExitingRipples = new Ripple[MAX_RIPPLES];
}
mExitingRipples[mExitingRipplesCount++] = mRipple;
mRipple.exit();
mRipple = null;
}
}
/**
* Cancels and removes the active ripple, all exiting ripples, and the
* background. Nothing will be drawn after this method is called.
*/
private void clearHotspots() {
boolean needsDraw = false;
if (mRipple != null) {
mRipple.cancel();
mRipple = null;
}
if (mBackground != null) {
mBackground.cancel();
mBackground = null;
}
needsDraw |= cancelExitingRipples();
mNeedsDraw = needsDraw;
invalidateSelf();
}
@Override
public void setHotspotBounds(int left, int top, int right, int bottom) {
mOverrideBounds = true;
mHotspotBounds.set(left, top, right, bottom);
onHotspotBoundsChanged();
}
/** @hide */
public void getHotspotBounds(Rect outRect) {
outRect.set(mHotspotBounds);
}
/**
* Notifies all the animating ripples that the hotspot bounds have changed.
*/
private void onHotspotBoundsChanged() {
final int count = mExitingRipplesCount;
final Ripple[] ripples = mExitingRipples;
for (int i = 0; i < count; i++) {
ripples[i].onHotspotBoundsChanged();
}
if (mRipple != null) {
mRipple.onHotspotBoundsChanged();
}
if (mBackground != null) {
mBackground.onHotspotBoundsChanged();
}
}
@Override
public void draw(@NonNull Canvas canvas) {
final boolean drawNonMaskContent = mContent != null;
final Rect bounds = getDirtyBounds();
final int saveCount = canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(bounds);
// If we have content, draw it into a layer first.
if (drawNonMaskContent) {
drawContentLayer(canvas, bounds);
}
// If we have a background and a non-opaque mask, draw the masking layer.
drawBackgroundLayer(canvas, bounds);
// If we have ripples and a non-opaque mask, draw the masking layer.
drawRippleLayer(canvas, bounds);
// If we failed to draw anything and we just canceled animations, at
// least draw a color so that hardware invalidation works correctly.
if (mNeedsDraw) {
canvas.drawColor(Color.TRANSPARENT);
// Request another draw so we can avoid adding a transparent layer
// during the next display list refresh.
invalidateSelf();
}
mNeedsDraw = false;
canvas.restoreToCount(saveCount);
}
/**
* Removes a ripple from the exiting ripple list.
*
* @param ripple the ripple to remove
*/
@Override
public void removeRipple(Ripple ripple) {
// Ripple ripple ripple ripple. Ripple ripple.
final Ripple[] ripples = mExitingRipples;
final int count = mExitingRipplesCount;
final int index = getRippleIndex(ripple);
if (index >= 0) {
System.arraycopy(ripples, index + 1, ripples, index, count - (index + 1));
ripples[count - 1] = null;
mExitingRipplesCount--;
invalidateSelf();
}
}
private int getRippleIndex(Ripple ripple) {
final Ripple[] ripples = mExitingRipples;
final int count = mExitingRipplesCount;
for (int i = 0; i < count; i++) {
if (ripples[i] == ripple) {
return i;
}
}
return -1;
}
private void drawContentLayer(Canvas canvas, Rect bounds) {
mContent.draw(canvas);
}
private void drawBackgroundLayer(
Canvas canvas, Rect bounds) {
if (mBackground != null && mBackground.shouldDraw()) {
final float x = mHotspotBounds.exactCenterX();
final float y = mHotspotBounds.exactCenterY();
canvas.translate(x, y);
mBackground.draw(canvas, getRipplePaint());
canvas.translate(-x, -y);
}
}
private void drawRippleLayer(Canvas canvas, Rect bounds) {
int restoreTranslate = -1;
// Translate the canvas to the current hotspot bounds.
restoreTranslate = canvas.save();
canvas.translate(mHotspotBounds.exactCenterX(), mHotspotBounds.exactCenterY());
// Draw ripples and update the animating ripples array.
final int count = mExitingRipplesCount;
final Ripple[] ripples = mExitingRipples;
for (int i = 0; i <= count; i++) {
final Ripple ripple;
if (i < count) {
ripple = ripples[i];
} else if (mRipple != null) {
ripple = mRipple;
} else {
continue;
}
ripple.draw(canvas, getRipplePaint());
}
// Always restore the translation.
if (restoreTranslate >= 0) {
canvas.restoreToCount(restoreTranslate);
}
}
private Paint getRipplePaint() {
if (mRipplePaint == null) {
mRipplePaint = new Paint();
mRipplePaint.setAntiAlias(true);
}
return mRipplePaint;
}
@Override
public Rect getDirtyBounds() {
return getBounds();
}
/**
* Sets the maximum ripple radius in pixels. The default value of
* {@link #RADIUS_AUTO} defines the radius as the distance from the center
* of the drawable bounds (or hotspot bounds, if specified) to a corner.
*
* @param maxRadius the maximum ripple radius in pixels or
* {@link #RADIUS_AUTO} to automatically determine the maximum
* radius based on the bounds
* @see #getMaxRadius()
* @see #setHotspotBounds(int, int, int, int)
* @hide
*/
public void setMaxRadius(int maxRadius) {
if (maxRadius != RADIUS_AUTO && maxRadius < 0) {
throw new IllegalArgumentException("maxRadius must be RADIUS_AUTO or >= 0");
}
mMaxRadius = maxRadius;
}
/**
* @return the maximum ripple radius in pixels, or {@link #RADIUS_AUTO} if
* the radius is determined automatically
* @see #setMaxRadius(int)
* @hide
*/
public int getMaxRadius() {
return mMaxRadius;
}
}
@@ -1,29 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect.ripple;
public interface RippleOwner {
/**
* Constant for automatically determining the maximum ripple radius.
*/
public static final int RADIUS_AUTO = -1;
public void removeRipple(Ripple ripple);
public void invalidateSelf();
}
@@ -1,55 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.effect.ripple;
import android.annotation.TargetApi;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import com.hippo.ehviewer.widget.HotspotTouchHelper;
public final class RippleSalon {
private static final boolean USE_OLD_RIPPLE =
Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP;
private static final Drawable MASK = new ColorDrawable(Color.BLACK);
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void addRipple(View v, ColorStateList color) {
addRipple(v, color, v.getBackground());
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void addRipple(View v, ColorStateList color, Drawable content) {
if (USE_OLD_RIPPLE) {
RippleDrawable rippleDrawable = new RippleDrawable(color, content);
v.setOnTouchListener(new HotspotTouchHelper(rippleDrawable));
v.setBackgroundDrawable(rippleDrawable);
} else {
android.graphics.drawable.RippleDrawable rippleDrawable = new android.graphics.drawable.RippleDrawable(color, content, MASK);
v.setBackgroundDrawable(rippleDrawable);
}
}
}
@@ -1,77 +0,0 @@
package com.hippo.ehviewer.ehclient;
import android.support.annotation.Nullable;
import android.util.Pair;
import com.hippo.ehviewer.util.Utils;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TorrentParser {
/**
*
* @return the param or new instance if size changed
*/
public static Pair<String, String>[] parse(String body, @Nullable Pair<String, String>[] torrents) {
List<Pair<String, String>> torrentList;
int arrayLength;
int size = 0;
if (torrents == null) {
arrayLength = 0;
torrentList = new LinkedList<>();
} else {
arrayLength = torrents.length;
torrentList = null;
}
Pattern p = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\">([^<>]*)</a></td>");
Matcher m = p.matcher(body);
while (m.find()) {
size++;
if (size > arrayLength && torrentList == null) {
torrentList = new LinkedList<>();
// Copy data
int copySize = size - 1;
for (int i = 0; i < copySize; i++) {
torrentList.add(torrents[i]);
}
}
// Remove ?p= to make torrent redistributable
String url = m.group(1);
if (url == null) {
size--;
continue;
}
int index = url.indexOf("?p=");
if (index != -1) {
url = url.substring(0, index);
}
Pair<String, String> newItem = new Pair<>(url, Utils.unescapeXml(m.group(2)));
if (torrentList != null) {
torrentList.add(newItem);
} else {
torrents[size - 1] = newItem;
}
}
if (torrentList != null) {
//noinspection unchecked,SuspiciousToArrayCall
return (Pair<String, String>[]) torrentList.toArray(new Pair[torrentList.size()]);
} else if (size == arrayLength){
return torrents;
} else {
//noinspection unchecked
Pair<String, String>[] result = new Pair[size];
System.arraycopy(torrents, 0, result, 0, size);
return result;
}
}
}
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.ui;
import android.os.Handler;
import android.os.Message;
import com.hippo.ehviewer.util.Utils;
public class SynchronizedHandler extends Handler {
private final GLRoot mRoot;
public SynchronizedHandler(GLRoot root) {
mRoot = Utils.checkNotNull(root);
}
@Override
public void dispatchMessage(Message message) {
mRoot.lockRenderThread();
try {
super.dispatchMessage(message);
} finally {
mRoot.unlockRenderThread();
}
}
}
@@ -1,65 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.miscellaneous;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.widget.MaterialToast;
public final class ActivityHelper {
public static boolean sendEmail(@NonNull Activity from, @NonNull String address,
@Nullable String subject, @Nullable String text) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:" + address));
if (subject != null) {
i.putExtra(Intent.EXTRA_SUBJECT, subject);
}
if (text != null) {
i.putExtra(Intent.EXTRA_TEXT, text);
}
try {
from.startActivity(i);
return true;
} catch (ActivityNotFoundException e) {
MaterialToast.showToast(R.string.em_cant_find_activity);
return false;
}
}
public static boolean share(@NonNull Activity from, String text) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.setType("text/plain");
try {
from.startActivity(sendIntent);
return true;
} catch (ActivityNotFoundException e) {
MaterialToast.showToast(R.string.em_cant_find_activity);
return false;
}
}
}
@@ -1,92 +0,0 @@
package com.hippo.ehviewer.miscellaneous;
import android.content.Context;
import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.util.BgThread;
import com.hippo.ehviewer.widget.MaterialToast;
import java.io.File;
public class Downloader implements Runnable, HttpHelper.OnDownloadListener {
private Context mContext;
private String mUrl;
private File mDir;
private String mFilename;
private boolean mIsRunning = false;
public Downloader(Context context, String url, File dir, String filename) {
mContext = context.getApplicationContext();
mUrl = url;
mDir = dir;
mFilename = filename;
}
public boolean isRunning() {
return mIsRunning;
}
public void startDownload() {
if (mIsRunning) {
return;
}
mIsRunning = true;
new BgThread(this).start();
MaterialToast.showToast(R.string.start_saving_torrent);
}
public void post(Runnable runnable) {
AppHandler.getInstance().post(runnable);
}
@Override
public void run() {
HttpHelper.DownloadOption dOpt = new HttpHelper.DownloadOption();
dOpt.setUseProxy(false);
dOpt.setAllowFixingExtension(true);
dOpt.setAllowFixingName(true);
HttpHelper hh = new HttpHelper(mContext);
final boolean ok = HttpHelper.DOWNLOAD_OK_STR.equals(
hh.download(mUrl, mDir, mFilename, null, null, this));
post(new Runnable() {
@Override
public void run() {
MaterialToast.showToast(ok ?
String.format(mContext.getString(R.string.save_torrent_successful),
mDir.getAbsolutePath() + File.separatorChar + mFilename) :
mContext.getString(R.string.save_torrent_failed));
}
});
mIsRunning = false;
}
@Override
public void onDownloadStartConnect() {
// Empty
}
@Override
public void onDownloadStartDownload(int totalSize) {
// Empty
}
@Override
public void onDownloadStatusUpdate(int downloadSize, int totalSize) {
// Empty
}
@Override
public void onDownloadOver(int status, String eMsg) {
// Empty
}
@Override
public void onUpdateFilename(String newFilename) {
mFilename = newFilename;
}
}
@@ -1,4 +0,0 @@
/**
* com.hippo.ehviewer.miscellaneous is a group of stuff combine more than one scopes
*/
package com.hippo.ehviewer.miscellaneous;
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class Network {
public static final int NETWORK_STATE_NONE = 0x0;
public static final int NETWORK_STATE_MOBILE = 0x1;
public static final int NETWORK_STATE_WIFI = 0x2;
public static int getNetworkState(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi != null && mWifi.isConnected())
return NETWORK_STATE_WIFI;
else if (mMobile != null && mMobile.isConnected())
return NETWORK_STATE_MOBILE;
else
return NETWORK_STATE_NONE;
}
}
@@ -1,246 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.ColorPickerView;
public class ColorPreference extends DialogPreference implements ColorPickerView.OnColorChangedListener, View.OnClickListener {
private View mColorBrick;
public ColorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setColor(int color) {
if (mColorBrick != null)
mColorBrick.setBackgroundColor(color);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
View ll = view.findViewById(android.R.id.widget_frame);
if (ll != null && ll instanceof LinearLayout) {
LinearLayout widgetFrame = (LinearLayout)ll;
widgetFrame.setVisibility(View.VISIBLE);
mColorBrick = new View(getContext());
if (isEnabled())
setColor(Config.getThemeColor());
else
setColor(getContext().getResources().getColor(R.color.disabled_mask));
widgetFrame.addView(mColorBrick, new LinearLayout.LayoutParams(Ui.dp2pix(24), Ui.dp2pix(24)));
}
}
@Override
protected boolean inScrollView() {
return true;
}
@Override
@SuppressLint("InflateParams")
protected View onCreateDialogView() {
return ViewUtils.inflateDialogView(R.layout.color_scheme_dialog, false);
}
private void setUpPresets(View view, final int which) {
final Button preset = (Button) view.findViewById(which);
if (preset != null)
preset.setOnClickListener(this);
}
@Override
protected void onBindDialogView(View view) {
int curColor = Config.getThemeColor();
final ColorPickerView colorPicker = (ColorPickerView) view.findViewById(R.id.color_picker_view);
ViewUtils.removeHardwareAccelerationSupport(colorPicker);
Button oldColor = (Button) view.findViewById(R.id.color_scheme_dialog_old_color);
oldColor.setOnClickListener(this);
final Button newColor = (Button) view.findViewById(R.id.color_scheme_dialog_new_color);
setUpPresets(view, R.id.color_scheme_dialog_preset_one);
setUpPresets(view, R.id.color_scheme_dialog_preset_two);
setUpPresets(view, R.id.color_scheme_dialog_preset_three);
setUpPresets(view, R.id.color_scheme_dialog_preset_four);
setUpPresets(view, R.id.color_scheme_dialog_preset_five);
setUpPresets(view, R.id.color_scheme_dialog_preset_six);
setUpPresets(view, R.id.color_scheme_dialog_preset_seven);
setUpPresets(view, R.id.color_scheme_dialog_preset_eight);
final EditText hexValue = (EditText) view.findViewById(R.id.color_scheme_dialog_hex_value);
hexValue.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(final CharSequence s, final int start, final int before,
final int count) {
try {
int color = Color.parseColor("#"
+ hexValue.getText().toString().toUpperCase(Locale.getDefault()));
colorPicker.setColor(color);
newColor.setBackgroundColor(color);
} catch (final Exception ignored) {
}
}
@Override
public void beforeTextChanged(final CharSequence s, final int start, final int count,
final int after) {
/* Nothing to do */
}
@Override
public void afterTextChanged(final Editable s) {
/* Nothing to do */
}
});
colorPicker.setOnColorChangedListener(this);
oldColor.setBackgroundColor(curColor);
colorPicker.setColor(curColor, true);
}
@Override
protected void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder) {
// Empty
}
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
super.onClick(dialog, which);
if (which == MaterialAlertDialog.POSITIVE) {
ColorPickerView colorPicker = (ColorPickerView) dialog.findViewById(R.id.color_picker_view);
if (colorPicker == null)
return true;
int color = colorPicker.getColor() | 0xff000000;
if (callChangeListener(color)) {
Config.setThemeColor(color);
setColor(color);
return true;
} else {
return false;
}
} else {
return true;
}
}
private String padLeft(final String string, final char padChar, final int size) {
if (string.length() >= size) {
return string;
}
final StringBuilder result = new StringBuilder();
for (int i = string.length(); i < size; i++) {
result.append(padChar);
}
result.append(string);
return result.toString();
}
@Override
public void onColorChanged(View view, int color) {
try {
View p = (View) view.getParent();
EditText hexValue = (EditText) p.findViewById(R.id.color_scheme_dialog_hex_value);
Button newColor = (Button) view.findViewById(R.id.color_scheme_dialog_new_color);
if (hexValue != null)
hexValue.setText(padLeft(Integer.toHexString(color).toUpperCase(Locale.getDefault()),
'0', 8));
if (newColor != null)
newColor.setBackgroundColor(color);
} catch (Throwable e) {
}
}
private int getColor(final int color) {
return getContext().getResources().getColor(color);
}
@Override
public void onClick(View v) {
View view = ViewUtils.getAncestor(v, R.id.main);
if (view == null)
return;
ColorPickerView colorPicker = (ColorPickerView) view.findViewById(R.id.color_picker_view);
if (colorPicker == null)
return;
switch (v.getId()) {
case R.id.color_scheme_dialog_preset_one:
colorPicker.setColor(getColor(R.color.theme_red));
break;
case R.id.color_scheme_dialog_preset_two:
colorPicker.setColor(getColor(R.color.theme_orange));
break;
case R.id.color_scheme_dialog_preset_three:
colorPicker.setColor(getColor(R.color.theme_lime));
break;
case R.id.color_scheme_dialog_preset_four:
colorPicker.setColor(getColor(R.color.theme_green));
break;
case R.id.color_scheme_dialog_preset_five:
colorPicker.setColor(getColor(R.color.theme_teal));
break;
case R.id.color_scheme_dialog_preset_six:
colorPicker.setColor(getColor(R.color.theme_blue));
break;
case R.id.color_scheme_dialog_preset_seven:
colorPicker.setColor(getColor(R.color.theme_purple));
break;
case R.id.color_scheme_dialog_preset_eight:
colorPicker.setColor(getColor(R.color.theme_brown));
break;
case R.id.color_scheme_dialog_old_color:
colorPicker.setColor(Config.getThemeColor());
break;
default:
break;
}
onColorChanged(colorPicker, colorPicker.getColor());
}
@Override
protected void onDialogCreate(Dialog dialog) {
dialog.getWindow().setFormat(PixelFormat.RGBA_8888);
}
}
@@ -1,113 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import com.hippo.ehviewer.app.MaterialAlertDialog;
public abstract class DialogPreference extends android.preference.DialogPreference implements MaterialAlertDialog.OnClickListener {
private MaterialAlertDialog.Builder mBuilder;
/** The dialog, if it is showing. */
private Dialog mDialog;
/** Which button was clicked. */
private int mWhichButtonClicked;
public DialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DialogPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onClick() {
if (mDialog != null && mDialog.isShowing()) return;
showDialog(null);
}
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
mWhichButtonClicked = which;
return true;
}
protected abstract void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder);
protected abstract boolean inScrollView();
@Override
protected void showDialog(Bundle state) {
Context context = getContext();
mWhichButtonClicked = MaterialAlertDialog.POSITIVE;
mBuilder = new MaterialAlertDialog.Builder(context)
.setTitle(getDialogTitle())
//.setIcon(mDialogIcon) // TODO Not support now
.setPositiveButton(getPositiveButtonText())
.setNegativeButton(getNegativeButtonText())
.setButtonListener(this);
View contentView = onCreateDialogView();
if (contentView != null) {
onBindDialogView(contentView);
mBuilder.setView(contentView, inScrollView());
} else {
mBuilder.setMessage(getDialogMessage());
}
onPrepareDialogBuilder(mBuilder);
// Create the dialog
final Dialog dialog = mDialog = mBuilder.create();
onDialogCreate(dialog);
if (state != null) {
dialog.onRestoreInstanceState(state);
}
dialog.setOnDismissListener(this);
dialog.show();
}
protected void onDialogCreate(Dialog dialog) {
}
@Override
protected abstract void onBindDialogView(View view);
@Override
public void onDismiss(DialogInterface dialog) {
mDialog = null;
onDialogClosed(mWhichButtonClicked == MaterialAlertDialog.POSITIVE);
}
@Override
public Dialog getDialog() {
return mDialog;
}
}
@@ -1,139 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.EditText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.widget.MaterialToast;
public class EditTextPreference extends DialogPreference {
private EditText mEditText;
private int mMax;
private int mMin;
public EditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public EditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
mEditText = new EditText(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.EditTextPreference, defStyle, 0);
mMax = a.getInt(R.styleable.EditTextPreference_etpMax, Integer.MAX_VALUE);
mMin = a.getInt(R.styleable.EditTextPreference_etpMin, Integer.MIN_VALUE);
a.recycle();
}
@Override
protected boolean inScrollView() {
return true;
}
@Override
protected View onCreateDialogView() {
// Make sure mEditText is an orphan
ViewParent oldParent = mEditText.getParent();
if (oldParent != null)
((ViewGroup) oldParent).removeView(mEditText);
mEditText.setTextColor(getContext().getResources().getColor(
R.color.secondary_text_dark));
return mEditText;
}
@Override
protected void onBindDialogView(View view) {
mEditText.setText(getPersistedString(null));
}
@Override
protected void onPrepareDialogBuilder(MaterialAlertDialog.Builder builder) {
// Empty
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
setSummary(restorePersistedValue ? getPersistedString((String) defaultValue)
: (String) defaultValue);
if (!restorePersistedValue)
persistString((String) defaultValue);
}
// Return true for close and save
private boolean checkBorder(String value) {
boolean re;
if (mMax == Integer.MAX_VALUE && mMin == Integer.MIN_VALUE) {
return true;
} else {
try {
int intValue = Integer.parseInt(value);
if (intValue > mMax || intValue < mMin)
re = false;
else
re = true;
} catch (Throwable e) {
re = false;
}
}
// Show Toast
if (!re)
MaterialToast.showToast(R.string.invalid_input);
return re;
}
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
super.onClick(dialog, which);
if (which == MaterialAlertDialog.POSITIVE) {
String value = mEditText.getText().toString();
if (checkBorder(value) && callChangeListener(value)) {
persistString(value);
setSummary(value);
return true;
} else {
return false;
}
} else {
return true;
}
}
}
@@ -1,261 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.app.MaterialAlertDialog.Builder;
public class ListPreference extends DialogPreference {
private CharSequence[] mEntries;
private CharSequence[] mEntryValues;
private String mValue;
private String mSummary;
private int mClickedDialogEntryIndex;
private boolean mValueSet;
public ListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public ListPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs,
new int[]{ 16842930, 16843256 }, 0, 0);
mEntries = a.getTextArray(0);
mEntryValues = a.getTextArray(1);
a.recycle();
a = context.obtainStyledAttributes(attrs,
new int[]{ 16842754, 16842765, 16842766,
16842994, 16843233, 16843238, 16843240,
16843241, 16843242, 16843243, 16843244,
16843245, 16843246, 16843491 }, 0, 0);
mSummary = a.getString(7);
a.recycle();
}
public void setEntries(CharSequence[] entries) {
mEntries = entries;
}
public void setEntries(int entriesResId) {
setEntries(getContext().getResources().getTextArray(entriesResId));
}
public CharSequence[] getEntries() {
return mEntries;
}
public void setEntryValues(CharSequence[] entryValues) {
mEntryValues = entryValues;
}
public void setEntryValues(int entryValuesResId) {
setEntryValues(getContext().getResources().getTextArray(entryValuesResId));
}
public CharSequence[] getEntryValues() {
return mEntryValues;
}
public void setValue(String value) {
// Always persist/notify the first time.
final boolean changed = !TextUtils.equals(mValue, value);
if (changed || !mValueSet) {
mValue = value;
mValueSet = true;
persistString(value);
if (changed) {
notifyChanged();
}
}
}
@Override
public CharSequence getSummary() {
final CharSequence entry = getEntry();
if (entry == null) {
return super.getSummary();
} else if (mSummary == null) {
return entry;
} else {
return String.format(mSummary, entry);
}
}
@Override
public void setSummary(CharSequence summary) {
super.setSummary(summary);
if (summary == null && mSummary != null) {
mSummary = null;
} else if (summary != null && !summary.equals(mSummary)) {
mSummary = summary.toString();
}
}
public void setValueIndex(int index) {
if (mEntryValues != null) {
setValue(mEntryValues[index].toString());
}
}
public String getValue() {
return mValue;
}
public CharSequence getEntry() {
int index = getValueIndex();
return index >= 0 && mEntries != null ? mEntries[index] : null;
}
public int findIndexOfValue(String value) {
if (value != null && mEntryValues != null) {
for (int i = mEntryValues.length - 1; i >= 0; i--) {
if (mEntryValues[i].equals(value)) {
return i;
}
}
}
return -1;
}
private int getValueIndex() {
return findIndexOfValue(mValue);
}
@Override
protected boolean inScrollView() {
return false;
}
@Override
protected void onBindDialogView(View view) {
// Empty
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
mClickedDialogEntryIndex = getValueIndex();
builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
mClickedDialogEntryIndex = which;
ListPreference.this.onClick(dialog, MaterialAlertDialog.POSITIVE);
return true;
}
});
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
final SavedState myState = new SavedState(superState);
myState.value = getValue();
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setValue(myState.value);
}
private static class SavedState extends BaseSavedState {
String value;
public SavedState(Parcel source) {
super(source);
value = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(value);
}
public SavedState(Parcelable superState) {
super(superState);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
@@ -1,106 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.SeekBar;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.app.MaterialAlertDialog.Builder;
import com.hippo.ehviewer.util.Utils;
public class SeekBarDialogPreference extends DialogPreference {
private SeekBar mSeekBar;
public SeekBarDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public SeekBarDialogPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
mSeekBar = new SeekBar(context, attrs);
}
@Override
protected boolean inScrollView() {
return true;
}
@Override
protected View onCreateDialogView() {
// Make sure mEditText is an orphan
ViewParent oldParent = mSeekBar.getParent();
if (oldParent != null)
((ViewGroup) oldParent).removeView(mSeekBar);
return mSeekBar;
}
@Override
protected void onBindDialogView(View view) {
mSeekBar.setProgress(Utils.parseIntSafely(getPersistedString(null), 120));
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
// Empty
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
setSummary(restorePersistedValue ? getPersistedString((String) defaultValue)
: (String) defaultValue);
if (!restorePersistedValue)
persistString((String) defaultValue);
}
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
super.onClick(dialog, which);
if (which == MaterialAlertDialog.POSITIVE) {
String value = Integer.toString(mSeekBar.getProgress());
if (callChangeListener(value)) {
persistString(value);
setSummary(value);
return true;
} else {
return false;
}
} else {
return true;
}
}
}
@@ -1,18 +0,0 @@
package com.hippo.ehviewer.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.widget.MaterialToast;
public class RestPatternReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Config.setPatternProtection("");
MaterialToast.showToast(R.string.reset_pattern_protection);
}
}
@@ -1,489 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.service;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.data.DownloadInfo;
import com.hippo.ehviewer.data.GalleryInfo;
import com.hippo.ehviewer.ehclient.ExDownloader;
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
import com.hippo.ehviewer.ui.DownloadActivity;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Utils;
import java.util.ArrayList;
import java.util.List;
public class DownloadService extends Service
implements ExDownloader.ListenerForDownload {
@SuppressWarnings("unused")
private static final String TAG = DownloadService.class.getSimpleName();
private static final int DOWNLOADING_NOTIFY_ID = -1;
private static final int DOWNLOAD_NOTIFY_ID = -2;
public static final String ACTION_UPDATE = "com.hippo.ehviewer.service.DownloadService.UPDATE";
public static final String ACTION_ADD = "com.hippo.ehviewer.service.DownloadService.ADD";
public static final String ACTION_START = "com.hippo.ehviewer.service.DownloadService.START";
public static final String ACTION_START_ALL = "com.hippo.ehviewer.service.DownloadService.START_ALL";
public static final String ACTION_STOP = "com.hippo.ehviewer.service.DownloadService.STOP";
public static final String ACTION_STOP_CURRENT = "com.hippo.ehviewer.service.DownloadService.STOP_CURRENT";
public static final String ACTION_STOP_ALL = "com.hippo.ehviewer.service.DownloadService.STOP_ALL";
public static final String ACTION_DELETE = "com.hippo.ehviewer.service.DownloadService.DELETE";
public static final String ACTION_CLEAR = "com.hippo.ehviewer.service.DownloadService.ACTION_CLEAR";
public static final String KEY_GID = "gid";
public static final String KEY_GALLERY_INFO = "gallery_info";
private Context mContext;
private Data mData;
private ExDownloaderManager mEdManager;
private volatile DownloadInfo mCurDownloadInfo = null;
private volatile ExDownloader mCurExDownloader = null;
private Binder mBinder = null;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
private String mSpeedStr = null;
private final List<Integer> mDownloadOk = new ArrayList<Integer>();
private final List<Integer> mDownloadFailed = new ArrayList<Integer>();
@Override
public void onCreate() {
super.onCreate();
mContext = getApplication();
mData = Data.getInstance();
mEdManager = ExDownloaderManager.getInstance();
mBinder = new Binder();
mNotifyManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
}
private synchronized void handleIntent(Intent intent) {
boolean startDownload = false;
if (intent == null) {
if (!Config.getKeepDownloadService()) {
stopForeground(true);
stopSelf();
return;
} else {
startDownload = true;
}
} else {
String action = intent.getAction();
if (ACTION_ADD.equals(action)) {
GalleryInfo gi = intent.getParcelableExtra(KEY_GALLERY_INFO);
if (gi != null)
add(gi);
else
startDownload = true;
} else if (ACTION_START.equals(action)) {
int gid = intent.getIntExtra(KEY_GID, -1);
if (gid != -1)
start(gid);
else
startDownload = true;
} else if (ACTION_START_ALL.equals(action)) {
startAll();
} else if (ACTION_STOP.equals(action)) {
int gid = intent.getIntExtra(KEY_GID, -1);
if (gid != -1)
stop(gid);
else
startDownload = true;
} else if (ACTION_STOP_CURRENT.equals(action)) {
stopCurrentTask();
} else if (ACTION_STOP_ALL.equals(action)) {
stopAll();
} else if (ACTION_DELETE.equals(action)) {
int gid = intent.getIntExtra(KEY_GID, -1);
if (gid != -1)
delete(gid);
else
startDownload = true;
} else if (ACTION_CLEAR.equals(action)) {
mDownloadOk.clear();
mDownloadFailed.clear();
startDownload = true;
} else {
startDownload = true;
}
}
if (startDownload)
tryToStartDownload();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
mBinder = null;
mNotifyManager = null;
}
/**
* Try to start download, if there is no item to start, stop itself
*/
private synchronized void tryToStartDownload() {
if (mCurDownloadInfo != null || mCurExDownloader != null)
return;
mCurDownloadInfo = mData.getFirstWaitDownloadInfo();
if (mCurDownloadInfo == null) {
stopSelf();
return;
}
mCurDownloadInfo.state = DownloadInfo.STATE_DOWNLOAD;
mCurDownloadInfo.download = -1;
mCurDownloadInfo.total = -1;
// To update download state
mData.addDownload(mCurDownloadInfo);
GalleryInfo gi = mCurDownloadInfo.galleryInfo;
mCurExDownloader = mEdManager.getExDownloader(gi.gid,
gi.token, gi.title, mCurDownloadInfo.mode);
mCurExDownloader.setListenerDownload(this);
// setDownloadMode will start download thread
mCurExDownloader.setDownloadMode(true);
}
/**
* notify download info has changed
*/
private void notifyUpdate() {
Intent it = new Intent(ACTION_UPDATE);
sendBroadcast(it);
}
/**
* If task is in list, reture false
* @param galleryInfo
* @return
*/
private boolean add(GalleryInfo galleryInfo) {
int gid = galleryInfo.gid;
DownloadInfo di;
if ((di = mData.getDownload(gid)) != null) {
if (di.state != DownloadInfo.STATE_DOWNLOAD) {
mData.setDownloadState(gid, DownloadInfo.STATE_WAIT);
tryToStartDownload();
notifyUpdate();
}
return false;
} else {
di = new DownloadInfo(galleryInfo, Config.getMode());
di.state = DownloadInfo.STATE_WAIT;
mData.addDownload(di);
tryToStartDownload();
notifyUpdate();
return true;
}
}
private synchronized void start(int gid) {
DownloadInfo di = mData.getDownload(gid);
if (di != null)
start(di);
}
private synchronized void start(DownloadInfo di) {
if (mCurDownloadInfo != di && di.state != DownloadInfo.STATE_WAIT) {
mData.setDownloadState(di, DownloadInfo.STATE_WAIT);
notifyUpdate();
}
tryToStartDownload();
}
public void startAll() {
mData.startAllDownload();
tryToStartDownload();
notifyUpdate();
}
private synchronized void stop(int gid) {
DownloadInfo di = mData.getDownload(gid);
if (di != null)
stop(di);
}
private synchronized void stop(DownloadInfo di) {
if (mCurDownloadInfo == di) {
// Cancel download notification
stopForeground(true);
// Target downloadinfo is downloading
mData.setDownloadState(mCurDownloadInfo, DownloadInfo.STATE_NONE);
mCurDownloadInfo = null;
mCurExDownloader.setListenerDownload(null);
mCurExDownloader.setDownloadMode(false);
mEdManager.freeExDownloader(mCurExDownloader);
mCurExDownloader = null;
tryToStartDownload();
notifyUpdate();
} else {
di.state = DownloadInfo.STATE_NONE;
tryToStartDownload();
notifyUpdate();
}
}
public void stopCurrentTask() {
if (mCurDownloadInfo != null)
stop(mCurDownloadInfo);
else
tryToStartDownload();
}
public synchronized void stopAll() {
mData.stopAllDownload();
stopCurrentTask();
}
private synchronized void delete(int gid) {
DownloadInfo di = mData.getDownload(gid);
if (di != null)
delete(di);
}
public void delete(DownloadInfo di) {
stop(di);
mData.deleteDownload(di.galleryInfo.gid);
notifyUpdate();
}
private void ensureNotification() {
if (mBuilder != null)
return;
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
mBuilder.setOngoing(true).setAutoCancel(false);
// Add action
Intent stopIntent = new Intent(this, DownloadService.class);
stopIntent.setAction(ACTION_STOP_CURRENT);
PendingIntent piStop = PendingIntent.getService(this, 0, stopIntent, 0);
mBuilder.addAction(R.drawable.ic_action_stop, getString(R.string.stop), piStop);
Intent stopAllIntent = new Intent(this, DownloadService.class);
stopAllIntent.setAction(ACTION_STOP_ALL);
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
mBuilder.addAction(R.drawable.ic_action_close, getString(R.string.stop_all), piStopAll);
}
private void setPendingIntent() {
Intent intent = new Intent(DownloadService.this, DownloadActivity.class);
intent.setAction(DownloadActivity.ACTION_SPECIFIC_GALLERY);
intent.putExtra(DownloadActivity.KEY_SPECIFIC_GALLERY_GID, mCurDownloadInfo.galleryInfo.gid);
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
}
@Override
public void onStart(int gid) {
if (mCurDownloadInfo == null)
return;
mCurDownloadInfo.download = -1;
mCurDownloadInfo.total = -1;
ensureNotification();
setPendingIntent();
mBuilder.setContentTitle(getString(R.string.start_download) + " " + gid)
.setContentText(null)
.setProgress(0, 0, true);
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
notifyUpdate();
}
@Override
public void onGetSum(int gid, int sum) {
if (mCurDownloadInfo == null)
return;
mCurDownloadInfo.download = 0;
mCurDownloadInfo.total = sum;
ensureNotification();
setPendingIntent();
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
.setContentText(null)
.setProgress(mCurDownloadInfo.total, mCurDownloadInfo.download, false);
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
notifyUpdate();
}
private long mLastStartForegroundTime = 0;
@Override
public void onDownload(int gid, int downloadSize, int totalSize) {
if (mCurDownloadInfo == null)
return;
mCurDownloadInfo.download = downloadSize;
mCurDownloadInfo.total = totalSize;
ensureNotification();
setPendingIntent();
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
.setContentText(mSpeedStr)
.setProgress(totalSize, downloadSize, false);
long now = System.currentTimeMillis();
if (now - mLastStartForegroundTime > 500) {
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
mLastStartForegroundTime = now;
}
notifyUpdate();
}
@Override
public void onUpdateSpeed(int gid, int speed) {
if (mCurDownloadInfo == null)
return;
mCurDownloadInfo.speed = speed;
mSpeedStr = Utils.sizeToString(speed) + "/S";
ensureNotification();
setPendingIntent();
mBuilder.setContentTitle(getString(R.string.downloading) + " " + gid)
.setContentText(mSpeedStr)
.setProgress(mCurDownloadInfo.total, mCurDownloadInfo.download, false);
startForeground(DOWNLOADING_NOTIFY_ID, mBuilder.build());
notifyUpdate();
}
private synchronized String getDownloadNotificationText() {
int ok = mDownloadOk.size();
int failed = mDownloadFailed.size();
if (ok == 0 && failed == 0) {
return "null";
} else if (ok == 1 && failed == 0) {
return String.format(getString(R.string.download_1), mDownloadOk.get(0));
} else if (failed == 0) {
return String.format(getString(R.string.download_2), mDownloadOk.size());
} else if (ok == 0 && failed == 1) {
return String.format(getString(R.string.download_3), mDownloadFailed.get(0));
} else if (ok == 0) {
return String.format(getString(R.string.download_4), mDownloadFailed.size());
} else if (ok == 1 && failed == 1){
return String.format(getString(R.string.download_5), mDownloadOk.get(0), mDownloadFailed.get(0));
} else {
return String.format(getString(R.string.download_6), mDownloadOk.size(), mDownloadFailed.size());
}
}
@Override
public synchronized void onDownloadOver(int gid, int legacy) {
if (mCurDownloadInfo == null)
return;
mCurDownloadInfo.legacy = legacy;
if (mCurDownloadInfo.legacy == 0) {
// Download ok
if (!mDownloadOk.contains(gid))
mDownloadOk.add(gid);
mDownloadFailed.remove((Integer) gid);
} else {
// Download failed
if (!mDownloadFailed.contains(gid))
mDownloadFailed.add(gid);
mDownloadOk.remove((Integer) gid);
}
Intent clearIntent = new Intent(this, DownloadService.class);
clearIntent.setAction(ACTION_CLEAR);
PendingIntent piClear = PendingIntent.getService(this, 0, clearIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
Intent intent = new Intent(DownloadService.this,DownloadActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setContentTitle(getString(R.string.download_over))
.setContentText(getDownloadNotificationText())
.setDeleteIntent(piClear)
.setOngoing(false).setAutoCancel(true);
mNotifyManager.notify(DOWNLOAD_NOTIFY_ID, builder.build());
stopForeground(true);
mCurDownloadInfo.legacy = legacy;
mCurDownloadInfo.state = DownloadInfo.STATE_FINISH;
mData.addDownload(mCurDownloadInfo);
mCurDownloadInfo = null;
mCurExDownloader.setListenerDownload(null);
mCurExDownloader.setDownloadMode(false);
mEdManager.freeExDownloader(mCurExDownloader);
mCurExDownloader = null;
tryToStartDownload();
notifyUpdate();
}
}
@@ -1,57 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.app.Activity;
import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
public abstract class AbsActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
Ui.adjustOrientation(this);
}
@Override
protected void onPause() {
super.onPause();
ImageCache.getImageCache(this).flush();
}
@Override
protected void onStart() {
super.onStart();
if (Config.getAllowAnalyics())
EasyTracker.getInstance(this).activityStart(this);
}
@Override
protected void onStop() {
super.onStop();
if (Config.getAllowAnalyics())
EasyTracker.getInstance(this).activityStop(this);
}
}
@@ -1,95 +0,0 @@
package com.hippo.ehviewer.ui;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.widget.LockPatternUtils;
import com.hippo.ehviewer.widget.LockPatternView;
import java.util.List;
public class EnterPatternActivity extends AbsActivity {
private static final String KEY_LAST_BAD_PATTERN_RETRY = "last_bad_pattern_retry";
private static final int MAX_RETRY_TIMES = 5;
private int mRetryTimes = 0;
@SuppressWarnings("ConstantConditions")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_pattern);
// Set random color
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
Ui.colorStatusBarL(this, themeColor);
// Menu
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
// Can't try if bad retry happened in 10 mins
long lastBadRetry = Config.getLong(KEY_LAST_BAD_PATTERN_RETRY, 0);
if (System.currentTimeMillis() - lastBadRetry < 1000 * 60 * 10) {
mRetryTimes = 10;
}
final TextView textView = (TextView) findViewById(R.id.text);
LockPatternView patternView = (LockPatternView) findViewById(R.id.pattern_view);
patternView.setOnPatternListener(new LockPatternView.OnPatternListener() {
@Override
public void onPatternStart() {
}
@Override
public void onPatternCleared() {
}
@Override
public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
}
@Override
public void onPatternDetected(List<LockPatternView.Cell> pattern) {
if (mRetryTimes > MAX_RETRY_TIMES) {
textView.setText(R.string.no_more_retries);
Config.setLong(KEY_LAST_BAD_PATTERN_RETRY, System.currentTimeMillis());
} else {
String enterPatter = LockPatternUtils.patternToString(pattern);
if (enterPatter.equals(Config.getPatternProtection())) {
setResult(RESULT_OK);
finish();
} else {
textView.setText(R.string.error_pattern);
}
}
mRetryTimes++;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
@@ -1,596 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.DirSelectDialog;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.data.GalleryInfo;
import com.hippo.ehviewer.ehclient.ExDownloader;
import com.hippo.ehviewer.gallery.GalleryView;
import com.hippo.ehviewer.gallery.data.ImageSet;
import com.hippo.ehviewer.gallery.ui.GLRootView;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.FullScreenHelper;
import com.hippo.ehviewer.util.MathUtils;
import com.hippo.ehviewer.util.Messenger;
import com.hippo.ehviewer.util.Utils;
import com.hippo.ehviewer.widget.ColorView;
import com.hippo.ehviewer.widget.MaterialToast;
import com.hippo.ehviewer.widget.SlidingLayout;
import java.io.File;
public class GalleryActivity extends StatsActivity
implements GalleryView.GalleryViewListener, SeekBar.OnSeekBarChangeListener,
FullScreenHelper.OnFullScreenBrokenListener, CompoundButton.OnCheckedChangeListener,
SlidingLayout.OnChildHideListener, AdapterView.OnItemSelectedListener,
View.OnClickListener, Utils.OnCopyOverListener, Messenger.Receiver {
@SuppressWarnings("unused")
private final static String TAG = GalleryActivity.class.getSimpleName();
public final static String KEY_GALLERY_INFO = "gallery_info";
public final static String KEY_START_INDEX = "start_index";
public final static String KEY_LIGHTNESS = "lightness";
public final static float DEFAULT_LIGHTNESS = 0.5f;
public final static String KEY_FIRST_READ_CONFIG_V1 = "first_read_config_v1";
public final static boolean DEFAULT_FIRST_READ_CONFIG_V1 = true;
public final static String KEY_LAST_SAVE_IMAGE_FILE_PATH = "last_save_image_file_path";
public final static String DEFAULT_LAST_SAVE_IMAGE_FILE_PATH = null;
private View mClock;
private View mBattery;
private SlidingLayout mConfigSliding;
/** It store index, start from 0, so max is samller than size **/
private TextView mCurrentPage;
private TextView mPageSum;
private SeekBar mPageSeeker;
private TextView mRefresh;
private TextView mSend;
private TextView mMoreSettings;
private Spinner mReadingDirection;
private Spinner mPageScaling;
private Spinner mStartPosition;
private CheckBox mKeepScreenOn;
private CheckBox mShowClock;
private CheckBox mShowBattery;
private CheckBox mCustomLightness;
private SeekBar mCustomLightnessValue;
private CheckBox mCustomCodec;
private Spinner mDecodeFormat;
private ImageSet mImageSet;
private GalleryView mGalleryView;
private ColorView mMaskView;
private GalleryInfo mGi;
private FullScreenHelper mFullScreenHelper;
private File mCurImageFile;
private Dialog mSendDialog;
private boolean mVolumePage;
private final Runnable mFullScreenTask = new Runnable() {
@Override public void run() {
mFullScreenHelper.setFullScreen(true);
}
};
private void startFullScreenTask() {
AppHandler.getInstance().postDelayed(mFullScreenTask, 2000);
}
private void cancelFullScreenTask() {
AppHandler.getInstance().removeCallbacks(mFullScreenTask);
}
@Override
public void onCopyOver(boolean success, File src, File dst) {
MaterialToast.showToast(success ? String.format(getString(R.string.save_successful), dst.getPath()) : getString(R.string.save_failed));
if (success)
Config.setString(KEY_LAST_SAVE_IMAGE_FILE_PATH, dst.getParent());
}
private Dialog createSaveImageDialog() {
return DirSelectDialog.create(
new MaterialAlertDialog.Builder(GalleryActivity.this)
.setDrakTheme(true).setTitle(R.string.select_save_dir)
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
if (which == MaterialAlertDialog.POSITIVE) {
String targetPath = ((DirSelectDialog) dialog).getCurrentPath();
StringBuilder sb = new StringBuilder();
sb.append(mImageSet.getTitle()).append("-").append(mGalleryView.getCurIndex() + 1)
.append(".").append(Utils.getExtension(mCurImageFile.getName(), "jpg"));
Utils.copyInNewThread(mCurImageFile, new File(targetPath, Utils.standardizeFilename(sb.toString())),
GalleryActivity.this);
}
return true;
}
}),
Config.getString(KEY_LAST_SAVE_IMAGE_FILE_PATH, null));
}
private Dialog createSendDialog() {
return new MaterialAlertDialog.Builder(this).setDrakTheme(true).setTitle(R.string.send)
.setItems(R.array.send_entries, new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
// Check current image file again
if (mCurImageFile == null || !mCurImageFile.exists()) {
MaterialToast.showToast(R.string.current_image_not_downloaded);
return false;
}
switch (which) {
case 0:
createSaveImageDialog().show();
break;
case 1:
Uri uri = Uri.fromFile(mCurImageFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType(Utils.getMimeType(uri.toString()));
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_image)));
break;
}
return true;
}
}).setNegativeButton(android.R.string.cancel).create();
}
@Override
public void onFullScreenBroken(boolean fullScreen) {
// TODO For some MIUI system, onSystemUiVisibilityChange() do not work fine
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
protected void onResume() {
super.onResume();
updateState();
mFullScreenHelper.setFullScreen(!mConfigSliding.isShowing());
}
private void setScreenLightness(boolean enable, int lightness) {
Window w = getWindow();
WindowManager.LayoutParams lp = w.getAttributes();
if (enable) {
lightness = MathUtils.clamp(lightness, 0, 200);
if (lightness > 100) {
mMaskView.setColor(0);
// Avoid BRIGHTNESS_OVERRIDE_OFF,
// screen may be off when lp.screenBrightness is 0.0f
lp.screenBrightness = Math.max((lightness - 100) / 100.0f, 0.05f);
} else {
mMaskView.setColor(MathUtils.lerp(0xde, 0x00, lightness / 100.0f) << 24);
lp.screenBrightness = 0.05f;
}
} else {
mMaskView.setColor(0);
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
}
w.setAttributes(lp);
}
private void updateState() {
mReadingDirection.setSelection(Config.getReadingDirection());
mPageScaling.setSelection(Config.getPageScaling());
mStartPosition.setSelection(Config.getStartPosition());
mGalleryView.setReadingDirection(Config.getReadingDirection());
mGalleryView.setPageScaling(Config.getPageScaling());
mGalleryView.setStartPosition(Config.getStartPosition());
mKeepScreenOn.setChecked(Config.getKeepSreenOn());
if (Config.getKeepSreenOn())
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mShowClock.setChecked(Config.getShowClock());
mShowBattery.setChecked(Config.getShowBattery());
mClock.setVisibility(Config.getShowClock() ? View.VISIBLE : View.GONE);
mBattery.setVisibility(Config.getShowBattery() ? View.VISIBLE : View.GONE);
mCustomLightness.setChecked(Config.getCustomLightness());
if (mCustomLightness.isChecked())
mCustomLightnessValue.setEnabled(true);
else
mCustomLightnessValue.setEnabled(false);
mCustomLightnessValue.setProgress(Config.getCustomLightnessValue());
setScreenLightness(mCustomLightness.isChecked(), mCustomLightnessValue.getProgress());
if (Utils.SUPPORT_IMAGE)
mCustomCodec.setEnabled(true);
else
mCustomCodec.setEnabled(false);
mCustomCodec.setChecked(Config.getCustomCodec());
if (Utils.SUPPORT_IMAGE && mCustomCodec.isChecked())
mDecodeFormat.setEnabled(true);
else
mDecodeFormat.setEnabled(false);
mDecodeFormat.setSelection(Config.getDecodeFormatIndex());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gl_root_group);
mVolumePage = Config.getVolumePage();
Messenger.getInstance().register(Config.MESSENGER_ID_VOLUME_PAGE, this);
mFullScreenHelper = new FullScreenHelper(this);
mFullScreenHelper.setOnFullScreenBrokenListener(this);
mFullScreenHelper.setFullScreen(true);
mMaskView = (ColorView)findViewById(R.id.mask);
mClock = findViewById(R.id.clock);
mBattery = findViewById(R.id.battery);
mConfigSliding = (SlidingLayout) findViewById(R.id.config_sliding);
mCurrentPage = (TextView) mConfigSliding.findViewById(R.id.current_page);
mPageSum = (TextView) mConfigSliding.findViewById(R.id.page_sum);
mPageSeeker = (SeekBar) mConfigSliding.findViewById(R.id.page_seeker);
mRefresh = (TextView) mConfigSliding.findViewById(R.id.refresh);
mSend = (TextView) mConfigSliding.findViewById(R.id.send);
mMoreSettings = (TextView) mConfigSliding.findViewById(R.id.more_settings);
mReadingDirection = (Spinner) mConfigSliding.findViewById(R.id.reading_direction);
mPageScaling = (Spinner) mConfigSliding.findViewById(R.id.page_scaling);
mStartPosition = (Spinner) mConfigSliding.findViewById(R.id.start_position);
mKeepScreenOn = (CheckBox) mConfigSliding.findViewById(R.id.keep_screen_on);
mShowClock = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_clock);
mShowBattery = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_battery);
mCustomLightness = (CheckBox) mConfigSliding.findViewById(R.id.custom_lightness);
mCustomLightnessValue = (SeekBar) mConfigSliding.findViewById(R.id.custom_lightness_value);
mCustomCodec = (CheckBox) mConfigSliding.findViewById(R.id.custom_codec);
mDecodeFormat = (Spinner) mConfigSliding.findViewById(R.id.decode_format);
mConfigSliding.hide();
mSendDialog = createSendDialog();
Intent intent = getIntent();
mGi = intent.getParcelableExtra(KEY_GALLERY_INFO);
if (mGi == null) {
// Get error force finish
new MaterialAlertDialog.Builder(this).setTitle(R.string.error)
.setMessage(R.string.ga_data_error)
.setPositiveButton(R.string.close)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
finish();
return true;
}
}).show();
} else {
Data.getInstance().addHistory(mGi, Data.READ);
int startIndex = intent.getIntExtra(KEY_START_INDEX, 0);
if (startIndex == -1)
startIndex = ExDownloader.readCurReadIndex(mGi.gid, mGi.title);
mImageSet = new ImageSet(mGi.gid, mGi.token, mGi.title, startIndex);
mGalleryView = new GalleryView(getApplicationContext(), mImageSet, startIndex);
GLRootView glrv= (GLRootView)findViewById(R.id.gl_root_view);
glrv.setContentPane(mGalleryView);
// Set listener
mConfigSliding.setOnChildHideListener(this);
mGalleryView.setGalleryViewListener(this);
mPageSeeker.setOnSeekBarChangeListener(this);
mRefresh.setOnClickListener(this);
mSend.setOnClickListener(this);
mMoreSettings.setOnClickListener(this);
mReadingDirection.setOnItemSelectedListener(this);
mPageScaling.setOnItemSelectedListener(this);
mStartPosition.setOnItemSelectedListener(this);
mDecodeFormat.setOnItemSelectedListener(this);
mKeepScreenOn.setOnCheckedChangeListener(this);
mShowClock.setOnCheckedChangeListener(this);
mShowBattery.setOnCheckedChangeListener(this);
mCustomLightness.setOnCheckedChangeListener(this);
mCustomLightnessValue.setOnSeekBarChangeListener(this);
mCustomCodec.setOnCheckedChangeListener(this);
mKeepScreenOn = (CheckBox) mConfigSliding.findViewById(R.id.keep_screen_on);
mShowClock = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_clock);
mShowBattery = (CheckBox) mConfigSliding.findViewById(R.id.gallery_show_battery);
mCustomCodec = (CheckBox) mConfigSliding.findViewById(R.id.custom_codec);
mPageSeeker.setMax(mGalleryView.getSize() - 1);
mPageSeeker.setProgress(startIndex);
mCurrentPage.setText(Integer.toString(startIndex + 1));
mPageSum.setText(Integer.toString(mGalleryView.getSize()));
onRightToLeftChanged(mGalleryView.isRightToLeft());
// Show first tip
String keyGalleryFirst = "gallery_first";
if (Config.getBoolean(keyGalleryFirst, true)) {
Config.setBoolean(keyGalleryFirst, false);
new MaterialAlertDialog.Builder(this).setDrakTheme(true).setTitle(R.string.tip)
.setMessage(R.string.gallery_tip)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
mFullScreenHelper.setFullScreen(true);
return true;
}
}).show();
}
// Update state
updateState();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Messenger.getInstance().unregister(Config.MESSENGER_ID_VOLUME_PAGE, this);
if (mImageSet != null)
mImageSet.free();
if (mGalleryView != null)
mGalleryView.free();
}
@Override
public void onBackPressed() {
if (mConfigSliding.isInHideAnimate())
return;
if (mConfigSliding.isShowing())
mConfigSliding.toBaseLevel();
else
finish();
}
@Override
public void onClick(View v) {
if (v == mRefresh) {
mImageSet.redownload(mGalleryView.getCurIndex());
} else if (v == mSend) {
mCurImageFile = mImageSet.getImageFile(mGalleryView.getCurIndex());
if (mCurImageFile == null || !mCurImageFile.exists())
MaterialToast.showToast(R.string.current_image_not_downloaded);
else
mSendDialog.show();
} else if (v == mMoreSettings) {
Intent intent = new Intent(GalleryActivity.this, SettingsActivity.class);
startActivity(intent);
}
}
@Override
public boolean onKeyDown (int keyCode, @NonNull KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (mVolumePage) {
mGalleryView.showNextPage();
return true;
} else {
break;
}
case KeyEvent.KEYCODE_VOLUME_UP:
if (mVolumePage) {
mGalleryView.showPreviousPage();
return true;
} else {
break;
}
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_PAGE_UP:
mGalleryView.showPreviousPage();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_PAGE_DOWN:
mGalleryView.showNextPage();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onReceive(int id, Object obj) {
if (obj instanceof Boolean) {
mVolumePage = (Boolean) obj;
}
}
@Override
public void onTapCenter() {
if (!mConfigSliding.isShowing()) {
if (mFullScreenHelper.willHideNavBar())
cancelFullScreenTask();
mFullScreenHelper.setFullScreen(false);
boolean firstTime = Config.getBoolean(KEY_FIRST_READ_CONFIG_V1, DEFAULT_FIRST_READ_CONFIG_V1);
mConfigSliding.toReservedLevel(firstTime);
if (firstTime)
Config.setBoolean(KEY_FIRST_READ_CONFIG_V1, false);
}
}
@Override
public void onPageChanged(int index) {
mPageSeeker.setProgress(index);
mCurrentPage.setText(Integer.toString(index + 1));
}
@Override
public void onSizeUpdate(int size) {
mPageSeeker.setMax(size - 1);
mPageSeeker.setProgress(mGalleryView.getCurIndex() + 1);
mCurrentPage.setText(Integer.toString(mGalleryView.getCurIndex() + 1));
mPageSum.setText(Integer.toString(size));
}
@Override
public void onSlideBottom(float dx) {
// Empty
}
@Override
public void onSlideBottomOver() {
// Empty
}
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void onRightToLeftChanged(boolean value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
int nevLd = value ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR;
if (mPageSeeker.getLayoutDirection() != nevLd) {
mPageSeeker.setLayoutDirection(nevLd);
}
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar == mPageSeeker) {
mCurrentPage.setText(Integer.toString(progress + 1));
} else if (seekBar == mCustomLightnessValue) {
setScreenLightness(mCustomLightness.isChecked(), progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Empty
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (seekBar == mPageSeeker) {
mGalleryView.goToPage(seekBar.getProgress());
} else if (seekBar == mCustomLightnessValue) {
Config.setCustomLightnessValue(seekBar.getProgress());
}
}
@Override
public void onChildHide() {
if (mFullScreenHelper.willHideNavBar())
startFullScreenTask();
else
mFullScreenHelper.setFullScreen(true);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if (parent == mReadingDirection) {
Config.setReadingDirection(mReadingDirection.getSelectedItemPosition());
mGalleryView.setReadingDirection(position);
} else if (parent == mPageScaling) {
Config.setPageScaling(mPageScaling.getSelectedItemPosition());
mGalleryView.setPageScaling(position);
} else if (parent == mStartPosition) {
Config.setStartPosition(mStartPosition.getSelectedItemPosition());
mGalleryView.setStartPosition(position);
} else if (parent == mDecodeFormat) {
Config.setDecodeFormatFromIndex(mDecodeFormat.getSelectedItemPosition());
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Empty
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView == mShowClock) {
Config.setShowClock(isChecked);
mClock.setVisibility(isChecked ? View.VISIBLE : View.GONE);
} else if (buttonView == mShowBattery) {
Config.setShowBattery(isChecked);
mBattery.setVisibility(isChecked ? View.VISIBLE : View.GONE);
} else if (buttonView == mKeepScreenOn) {
Config.setKeepSreenOn(isChecked);
if (isChecked)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else if (buttonView == mCustomLightness) {
Config.setCustomLightness(isChecked);
if (isChecked)
mCustomLightnessValue.setEnabled(true);
else
mCustomLightnessValue.setEnabled(false);
setScreenLightness(isChecked, mCustomLightnessValue.getProgress());
} else if (buttonView == mCustomCodec) {
Config.setCustomCodec(isChecked);
if (Utils.SUPPORT_IMAGE && mCustomCodec.isChecked())
mDecodeFormat.setEnabled(true);
else
mDecodeFormat.setEnabled(false);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,271 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.data.GalleryInfo;
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable.Stroke;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.FitWindowView;
import com.hippo.ehviewer.widget.GalleryListView;
import com.hippo.ehviewer.widget.GalleryListView.OnGetListListener;
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
import com.hippo.ehviewer.widget.recyclerview.SwipeToDismissTouchListener;
import java.util.ArrayList;
import java.util.List;
public class HistoryActivity extends AbsTranslucentActivity
implements EasyRecyclerView.OnItemClickListener, MaterialAlertDialog.OnClickListener,
GalleryListView.GalleryListViewHelper, FitWindowView.OnFitSystemWindowsListener {
private static final String TAG = HistoryActivity.class.getSimpleName();
public static final int LIST_MODE_DETAIL = 0;
public static final int LIST_MODE_THUMB = 1;
private Data mData;
private int mThemeColor;
private FitWindowView mStandard;
private GalleryListView mGalleryListView;
private int mFilterMode;
private Dialog mFilterDialog;
private CheckBox mJustBrowse;
private CheckBox mHaveRead;
private Dialog mClearDialog;
private static final String HISTORY_URL = "ehviewer://history";
private static final String KEY_HISTORY_FILTER = "history_filter";
private void setFilterDialogMode(int filterMode) {
if ((filterMode & Data.BROWSE) == 0)
mJustBrowse.setChecked(false);
else
mJustBrowse.setChecked(true);
if ((filterMode & Data.READ) == 0)
mHaveRead.setChecked(false);
else
mHaveRead.setChecked(true);
}
private int getFilterDialogMode() {
int filterMode = 0;
filterMode |= mJustBrowse.isChecked() ? Data.BROWSE : 0;
filterMode |= mHaveRead.isChecked() ? Data.READ : 0;
return filterMode;
}
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
if (dialog == mFilterDialog) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
int newFilterMode = getFilterDialogMode();
if (newFilterMode != mFilterMode) {
mFilterMode = newFilterMode;
Config.setInt(KEY_HISTORY_FILTER, mFilterMode);
mGalleryListView.refresh();
}
}
return true;
} else if (dialog == mClearDialog) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
Data.getInstance().clearHistory();
mGalleryListView.refresh();
}
return true;
}
return true;
}
@SuppressLint("InflateParams")
private void createFilterDialog() {
View view = ViewUtils.inflateDialogView(R.layout.history_filter, false);
mJustBrowse = (CheckBox) view.findViewById(R.id.just_browse);
mHaveRead = (CheckBox) view.findViewById(R.id.have_read);
mFilterDialog = new MaterialAlertDialog.Builder(this).setTitle(R.string.filter)
.setView(view, true)
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
.setButtonListener(this).create();
}
private void createClearDialog() {
mClearDialog = new MaterialAlertDialog.Builder(this).setTitle(R.string.attention)
.setMessage(R.string.clear_history_message)
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
.setButtonListener(this).create();
}
@Override
public void onFitSystemWindows(int l, int t, int r, int b) {
mGalleryListView.setPaddingTopAndBottom(t, b);
Ui.colorStatusBarKK(this, mThemeColor, t - Ui.ACTION_BAR_HEIGHT);
}
@Override
protected void onResume() {
super.onResume();
mGalleryListView.refresh();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
mData = Data.getInstance();
mFilterMode = Config.getInt(KEY_HISTORY_FILTER, Data.BROWSE | Data.READ);
// Menu
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, Stroke.THIN);
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
// Theme
mThemeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
getActionBar().setBackgroundDrawable(new ColorDrawable(mThemeColor));
Ui.colorStatusBarL(this, mThemeColor);
mStandard = (FitWindowView) findViewById(R.id.standard);
mGalleryListView = (GalleryListView) findViewById(R.id.gallery_list);
mGalleryListView.setGalleryListViewHelper(this);
mStandard.addOnFitSystemWindowsListener(this);
// Do not need header an footer
mGalleryListView.setEnabledHeader(false);
mGalleryListView.setEnabledFooter(false);
mGalleryListView.setOnItemClickListener(this);
SwipeToDismissTouchListener.DismissCallbacks callbacks = new SwipeToDismissTouchListener.DismissCallbacks() {
@Override
public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) {
return SwipeToDismissTouchListener.SwipeDirection.BOTH;
}
@Override
public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) {
for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) {
// TODO After delete all show NONE tip
int position = data.position;
mData.deleteHistory(mGalleryListView.getGalleryInfo(position).gid);
mGalleryListView.removeGalleryInfo(position);
mGalleryListView.getGalleryAdapter().notifyItemRemoved(data.position);
}
}
@Override
public void onResetMotion() {
}
@Override
public void onTouchDown() {
}
};
mGalleryListView.addOnItemTouchListener(
new SwipeToDismissTouchListener(mGalleryListView.getEasyRecyclerView(), callbacks));
createFilterDialog();
createClearDialog();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.history, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_filter:
if (!mFilterDialog.isShowing()) {
setFilterDialogMode(mFilterMode);
mFilterDialog.show();
}
return true;
case R.id.action_clear:
if (!mClearDialog.isShowing())
mClearDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public String getTargetUrl(int targetPage) {
return HISTORY_URL;
}
@Override
public void doGetGallerys(String url, long taskStamp,
OnGetListListener listener) {
if (url.equals(HISTORY_URL)) {
List<GalleryInfo> giList = new ArrayList<GalleryInfo>(mData.getHistory(mFilterMode, true));
if (giList.size() == 0)
listener.onSuccess(taskStamp, giList, 0);
else
listener.onSuccess(taskStamp, giList, 1);
}
}
@Override
public boolean onItemClick(EasyRecyclerView parent, View view,
int position, long id) {
Intent intent = new Intent(this, GalleryDetailActivity.class);
GalleryInfo gi = mGalleryListView.getGalleryInfo(position);
intent.putExtra(GalleryDetailActivity.KEY_G_INFO, gi);
startActivity(intent);
return true;
}
}
@@ -1,82 +0,0 @@
package com.hippo.ehviewer.ui;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.drawable.MaterialIndicatorDrawable;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.widget.LockPatternUtils;
import com.hippo.ehviewer.widget.LockPatternView;
public class PatternProtectionActivity extends AbsActivity implements View.OnClickListener{
private TextView mTextView;
private LockPatternView mPatternView;
private View mCancel;
private View mOK;
@SuppressWarnings("ConstantConditions")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pattern_protection);
// Set random color
int themeColor = Config.getCustomThemeColor() ? Config.getThemeColor() : Ui.THEME_COLOR;
getActionBar().setBackgroundDrawable(new ColorDrawable(themeColor));
Ui.colorStatusBarL(this, themeColor);
// Menu
MaterialIndicatorDrawable materialIndicator = new MaterialIndicatorDrawable(this, Color.WHITE, MaterialIndicatorDrawable.Stroke.THIN);
materialIndicator.setIconState(MaterialIndicatorDrawable.IconState.ARROW);
Ui.setMaterialIndicator(getActionBar(), materialIndicator);
mTextView = (TextView) findViewById(R.id.text);
mPatternView = (LockPatternView) findViewById(R.id.pattern_view);
mCancel = findViewById(R.id.cancel);
mOK = findViewById(R.id.ok);
mOK.setOnClickListener(this);
mCancel.setOnClickListener(this);
String pattern = Config.getPatternProtection();
boolean setPattern = LockPatternUtils.isPatternVaild(pattern);
Resources resources = getResources();
int patternProtectionStateId = setPattern ?
R.string.pattern_protection_set : R.string.pattern_protection_not_set;
mTextView.setText(resources.getString(patternProtectionStateId) + "\n\n" +
getString(R.string.pattern_protection_warning));
if (setPattern) {
mPatternView.setPattern(LockPatternView.DisplayMode.Correct, LockPatternUtils.stringToPattern(pattern));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
if (v == mOK) {
Config.setPatternProtection(mPatternView.getPatternString());
finish();
} else if (v == mCancel) {
finish();
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.ImageView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.effect.DrawableTransition;
import com.hippo.ehviewer.util.Secret;
import com.hippo.ehviewer.widget.MaterialToast;
import java.util.Arrays;
public class SecretActivity extends AbsActivity implements View.OnClickListener {
private final long[] mHits = new long[3];
private Bitmap mBmp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBmp = Secret.getSecretImage(this);
if (mBmp == null) {
finish();
return;
}
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageBitmap(mBmp);
iv.setOnClickListener(this);
iv.setSoundEffectsEnabled(false);
setContentView(iv);
DrawableTransition.transit(iv.getDrawable(), false, 3000);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBmp != null) {
mBmp.recycle();
mBmp = null;
}
}
@Override
public void onClick(View v) {
System.arraycopy(mHits, 1, mHits, 0, mHits.length-1);
mHits[mHits.length-1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
Arrays.fill(mHits, 0);
MaterialToast.showToast(R.string.photo_footnotes);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,159 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Constants;
import com.hippo.ehviewer.util.Messenger;
import java.util.Locale;
public abstract class StatsActivity extends AbsActivity {
private static final int DEFAULT_MESSAGE_SIZE = 128;
private static final long STATS_CLOCK_INTERVAL_MS = 1000;
private static final int BYTES_IN_MEGABYTE = 1024 * 1024;
private TextView mStatsTextView;
private boolean mShowStats;
private Runnable mStatsClockTickRunnable;
private Handler mHandler;
private Messenger.Receiver mReceiver = new Messenger.Receiver() {
@Override
public void onReceive(int id, Object obj) {
if (obj instanceof Boolean) {
boolean showStats = (Boolean) obj;
if (mShowStats != showStats) {
mShowStats = showStats;
ViewGroup vg = (ViewGroup) getWindow().getDecorView();
if (showStats) {
vg.addView(mStatsTextView, generateLayoutParams());
updateStats();
scheduleNextStatsClockTick();
} else {
vg.removeView(mStatsTextView);
cancelNextStatsClockTick();
}
}
}
}
};
@SuppressLint("RtlHardcoded")
private ViewGroup.LayoutParams generateLayoutParams() {
Resources resources = getResources();
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.TOP | Gravity.RIGHT;
lp.topMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_top);
lp.rightMargin = resources.getDimensionPixelOffset(R.dimen.stats_text_view_padding_right);
return lp;
}
private boolean isShowStats() {
return Config.getShowApplicationStats();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStatsTextView = new TextView(this);
mHandler = AppHandler.getInstance();
mStatsClockTickRunnable = new Runnable() {
@Override
public void run() {
updateStats();
scheduleNextStatsClockTick();
}
};
Messenger.getInstance().register(
Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
if (isShowStats()) {
mShowStats = true;
((ViewGroup) getWindow().getDecorView()).addView(mStatsTextView,
generateLayoutParams());
} else {
mShowStats = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Messenger.getInstance().unregister(Constants.MESSENGER_ID_SHOW_APP_STATUS, mReceiver);
}
@Override
protected void onResume() {
super.onResume();
if (mShowStats) {
updateStats();
scheduleNextStatsClockTick();
}
}
@Override
protected void onPause() {
super.onPause();
if (mShowStats) {
cancelNextStatsClockTick();
}
}
private void scheduleNextStatsClockTick() {
mHandler.postDelayed(mStatsClockTickRunnable, STATS_CLOCK_INTERVAL_MS);
}
private void cancelNextStatsClockTick() {
mHandler.removeCallbacks(mStatsClockTickRunnable);
}
private void updateStats() {
final Runtime runtime = Runtime.getRuntime();
final long heapMemory = runtime.totalMemory() - runtime.freeMemory();
final StringBuilder sb = new StringBuilder(DEFAULT_MESSAGE_SIZE);
appendSize(sb, "Java heap size: ", heapMemory, "\n");
appendSize(sb, "Native heap size: ", Debug.getNativeHeapAllocatedSize(), "\n");
mStatsTextView.setText(sb.toString());
}
private static void appendSize(StringBuilder sb, String prefix, long bytes, String suffix) {
String value = String.format(Locale.getDefault(), "%.2f", (float) bytes / BYTES_IN_MEGABYTE);
appendValue(sb, prefix, value + " MB", suffix);
}
private static void appendValue(StringBuilder sb, String prefix, String value, String suffix) {
sb.append(prefix).append(value).append(suffix);
}
}
@@ -1,65 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.hippo.ehviewer.ehclient.EhClient;
import com.hippo.ehviewer.ehclient.EhInfo;
public class WebViewLoginActivity extends AbsActivity {
private static final String TITLE_LOGIN_SUCCESS = "Please stand by...";
public static final String KEY_ERROR = "error";
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView wv = new WebView(this);
CookieManager.getInstance().removeAllCookie();
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new LoginWebViewClient());
wv.loadUrl(EhClient.LOGIN_URL);
setContentView(wv);
}
private class LoginWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
if (TITLE_LOGIN_SUCCESS.equals(view.getTitle())) {
// Login OK
String cookies = CookieManager.getInstance().getCookie(url);
if (cookies != null) {
// Store cookie
EhInfo ehInfo = EhInfo.getInstance(WebViewLoginActivity.this);
ehInfo.setCookie(cookies);
ehInfo.login("User", "User");
setResult(RESULT_OK);
} else {
setResult(RESULT_CANCELED);
}
finish();
}
}
}
}
@@ -1,30 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.animation.Animator;
import android.animation.ValueAnimator;
public final class AnimatorUtils {
public static Animator createDelayAnimator(long delay) {
Animator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(delay);;
return anim;
}
}
@@ -1,62 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.os.Environment;
import android.support.annotation.Nullable;
import java.io.File;
/**
* Something about this app
*/
public final class AppConfig {
private static final String APP_DIRNAME = "EhViewer";
private static final String CRASH_DIRNAME = "crash";
private static final String DOWNLOAD_DIRNAME = "download";
private static final String TORRENT_DIRNAME = "torrent";
public static @Nullable File getAppDir() {
if (Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED)) {
return new File(Environment.getExternalStorageDirectory(), APP_DIRNAME);
} else {
return null;
}
}
public static @Nullable File getFileInAppDir(String filename) {
File appFolder = getAppDir();
if (appFolder != null) {
return new File(appFolder, filename);
} else {
return null;
}
}
public static @Nullable File getCrashDir() {
return getFileInAppDir(CRASH_DIRNAME);
}
public static @Nullable File getDownloadDir() {
return getFileInAppDir(DOWNLOAD_DIRNAME);
}
public static @Nullable File getTorrentDir() {
return getFileInAppDir(TORRENT_DIRNAME);
}
}
@@ -1,731 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Environment;
import android.preference.PreferenceManager;
import com.hippo.ehviewer.data.ListUrls;
import com.hippo.ehviewer.ehclient.EhClient;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public final class Config {
@SuppressWarnings("unused")
private static final String TAG = Config.class.getSimpleName();
public static final String EXTERANL_DIR_NAME = "EhViewer";
public static File sExternalDir;
private static final String KEY_UPDATE_DATE = "update_date";
private static boolean mInit = false;
private static SharedPreferences mConfigPre;
public static final int MESSENGER_ID_VOLUME_PAGE;
static {
Messenger messenger = Messenger.getInstance();
MESSENGER_ID_VOLUME_PAGE = messenger.newId();
}
/**
* Init Config
*
* @param context Application context
*/
public static void init(Context context) {
if (mInit)
return;
mInit = true;
mConfigPre = PreferenceManager.getDefaultSharedPreferences(context);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
sExternalDir = new File(Environment.getExternalStorageDirectory(), EXTERANL_DIR_NAME);
Utils.ensureDir(sExternalDir, true);
} else {
sExternalDir = null;
}
}
/**
* Is init
* @return True if init
*/
public static boolean isInit() {
return mInit;
}
public static boolean getBoolean(String key, boolean defValue) {
return mConfigPre.getBoolean(key, defValue);
}
public static void setBoolean(String key, boolean value) {
mConfigPre.edit().putBoolean(key, value).apply();
}
public static int getInt(String key, int defValue) {
return mConfigPre.getInt(key, defValue);
}
public static void setInt(String key, int value) {
mConfigPre.edit().putInt(key, value).apply();
}
public static long getLong(String key, long defValue) {
return mConfigPre.getLong(key, defValue);
}
public static void setLong(String key, long value) {
mConfigPre.edit().putLong(key, value).apply();
}
public static String getString(String key, String defValue) {
return mConfigPre.getString(key, defValue);
}
public static void setString(String key, String value) {
mConfigPre.edit().putString(key, value).apply();
}
public static int getIntFromStr(String key, int defValue) {
return Utils.parseIntSafely(mConfigPre.getString(key, Integer.toString(defValue)), defValue);
}
public static void setIntToStr(String key, int value) {
mConfigPre.edit().putString(key, Integer.toString(value)).apply();
}
public static float getFloat(String key, float defValue) {
return mConfigPre.getFloat(key, defValue);
}
public static void setFloat(String key, float value) {
mConfigPre.edit().putFloat(key, value).apply();
}
/****** Display ******/
private static final String KEY_CUSTOM_THEME_COLOR = "custom_theme_color";
private static final boolean DEFAULT_CUSTOM_THEME_COLOR = false;
private static final String KEY_THEME_COLOR = "theme_color";
private static final int DEFAULT_THEME_COLOR = Ui.THEME_COLOR;
private static final String KEY_SCREEN_ORIENTATION = "screen_orientation";
private static final int DEFAULT_SCREEN_ORIENTATION = 0;
private static final String KEY_LIST_MODE = "list_mode";
private static final int DEFAULT_LIST_MODE = 0;
private static final String KEY_LIST_THUMB_COLUMNS_PORTRAIT = "list_thumb_columns_portrait";
private static final int DEFAULT_LIST_THUMB_COLUMNS_PORTRAIT = 3;
private static final String KEY_LIST_THUMB_COLUMNS_LANDSCAPE = "list_thumb_columns_landscape";
private static final int DEFAULT_LIST_THUMB_COLUMNS_LANDSCAPE = 5;
private static final String KEY_PREVIEW_COLUMNS_PORTRAIT = "preview_columns_portrait";
private static final int DEFAULT_PREVIEW_COLUMNS_PORTRAIT = 3;
private static final String KEY_PREVIEW_COLUMNS_LANDSCAPE = "preview_columns_landscape";
private static final int DEFAULT_PREVIEW_COLUMNS_LANDSCAPE = 5;
private static final String KEY_SHOW_POPULAR_UPDATE_TIME = "show_popular_update_time";
private static final boolean DEFAULT_SHOW_POPULAR_UPDATE_TIME = false;
public static boolean getCustomThemeColor() {
return getBoolean(KEY_CUSTOM_THEME_COLOR, DEFAULT_CUSTOM_THEME_COLOR);
}
public static int getThemeColor() {
return getInt(KEY_THEME_COLOR, DEFAULT_THEME_COLOR);
}
public static void setThemeColor(int color) {
setInt(KEY_THEME_COLOR, color);
}
public static int getScreenOriMode() {
return screenOriPre2Value(getIntFromStr(KEY_SCREEN_ORIENTATION, DEFAULT_SCREEN_ORIENTATION));
}
public static int screenOriPre2Value(int screenOriModePre) {
switch (screenOriModePre) {
case 0:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
case 1:
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
case 2:
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
default:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}
public static int getListMode() {
return getIntFromStr(KEY_LIST_MODE, DEFAULT_LIST_MODE);
}
public static void setListMode(int listMode) {
setIntToStr(KEY_LIST_MODE, listMode);
}
public static int getListThumbColumnsPortrait() {
return getInt(KEY_LIST_THUMB_COLUMNS_PORTRAIT, DEFAULT_LIST_THUMB_COLUMNS_PORTRAIT);
}
public static int getListThumbColumnsLandscape() {
return getInt(KEY_LIST_THUMB_COLUMNS_LANDSCAPE, DEFAULT_LIST_THUMB_COLUMNS_LANDSCAPE);
}
public static int getPreviewColumnsPortrait() {
return getInt(KEY_PREVIEW_COLUMNS_PORTRAIT, DEFAULT_PREVIEW_COLUMNS_PORTRAIT);
}
public static int getPreviewColumnsLandscape() {
return getInt(KEY_PREVIEW_COLUMNS_LANDSCAPE, DEFAULT_PREVIEW_COLUMNS_LANDSCAPE);
}
public static boolean getShowPopularUpdateTime() {
return getBoolean(KEY_SHOW_POPULAR_UPDATE_TIME, DEFAULT_SHOW_POPULAR_UPDATE_TIME);
}
/****** Eh Config ******/
private static final String KEY_DEFAULT_CAT = "default_cat";
private static final int DEFAULT_DEFAULT_CAT = ListUrls.ALL_CATEGORT;
// m for normal, l for large
public static final String KEY_PREVIEW_MODE = "preview_mode";
public static final String PREVIEW_MODE_NORMAL = "m";
public static final String PREVIEW_MODE_LARGE = "l";
private static final String DEFAULT_PREVIEW_MODE = PREVIEW_MODE_LARGE;
/**
* reclass 0x1
* language 0x2
* parody 0x4
* character 0x8
* group 0x10
* artist 0x20
* male 0x40
* female 0x80
*/
private static final String KEY_EXCLUDE_TAG_GROUP = "exculde_tag_group";
private static final int DEFAULT_EXCLUDE_TAG_GROUP = 0;
/**
* Original Translated Rewrite All
* Japanese 1024 2048
* English 1 1025 2049
* Chinese 10 1034 2058
* Dutch 20 1044 2068
* French 30 1054 2078
* German 40 1064 2088
* Hungarian 50 1074 2098
* Italian 60 1084 2108
* Korean 70 1094 2118
* Polish 80 1104 2128
* Portuguese 90 1114 2138
* Russian 100 1124 2148
* Spanish 110 1134 2158
* Thai 120 1144 2168
* Vietnamese 130 1154 2178
* Other 255 1279 2303
*/
private static final String KEY_EXCLUDE_LANGUAGE = "exculde_language";
private static final String DEFAULT_EXCLUDE_LANGUAGE = "";
private static final String KEY_DEFAULT_FAVORITE = "default_favorite";
private static final int DEFAULT_DEFAULT_FAVORITE = -2;
private static final String KEY_MAX_HISTORY_COUNT = "max_history_count";
private static final int DEFAULT_MAX_HISTORY_COUNT = 100;
private static final String KEY_HAH_PROXY = "hah_proxy";
private static final boolean DEFAULT_HAH_PROXY = false;
private static final String KEY_HAH_IP = "hah_ip";
private static final String DEFAULT_HAH_IP = "";
private static final String KEY_HAH_PORT = "hah_port";
private static final String DEFAULT_HAH_PORT = "";
private static final String KEY_HAH_PASSKEY = "hah_passkey";
private static final String DEFAULT_HAH_PASSKEY = "";
public static int getDefaultCat() {
return getInt(KEY_DEFAULT_CAT, DEFAULT_DEFAULT_CAT);
}
public static void setDefaultCat(int defaultCat) {
setInt(KEY_DEFAULT_CAT, defaultCat);
}
public static String getPreviewMode() {
return getString(KEY_PREVIEW_MODE, DEFAULT_PREVIEW_MODE);
}
public static int getExculdeTagGroup() {
return getInt(KEY_EXCLUDE_TAG_GROUP, DEFAULT_EXCLUDE_TAG_GROUP);
}
public static void setExculdeTagGroup(int exculdeTagGroup) {
setInt(KEY_EXCLUDE_TAG_GROUP, exculdeTagGroup);
}
public static String getExculdeLanguage() {
return getString(KEY_EXCLUDE_LANGUAGE, DEFAULT_EXCLUDE_LANGUAGE);
}
public static void setExculdeLanguage(String exculdeLanguage) {
setString(KEY_EXCLUDE_LANGUAGE, exculdeLanguage);
}
public static int getDefaultFavorite() {
return getIntFromStr(KEY_DEFAULT_FAVORITE, DEFAULT_DEFAULT_FAVORITE);
}
public static void setDefaultFavorite(int defaultFavorite) {
setIntToStr(KEY_DEFAULT_FAVORITE, defaultFavorite);
}
public static int getMaxHistoryCount() {
return getIntFromStr(KEY_MAX_HISTORY_COUNT, DEFAULT_MAX_HISTORY_COUNT);
}
public static boolean getHAHProxy() {
return getBoolean(KEY_HAH_PROXY, DEFAULT_HAH_PROXY);
}
public static void setHAHIp(String hahIp) {
setString(KEY_HAH_IP, hahIp);
}
public static String getHAHIp() {
return getString(KEY_HAH_IP, DEFAULT_HAH_IP);
}
public static void setHAHPort(String hahPort) {
setString(KEY_HAH_PORT, hahPort);
}
public static String getHAHPort() {
return getString(KEY_HAH_PORT, DEFAULT_HAH_PORT);
}
public static void setHAHPasskey(String hahPasskey) {
setString(KEY_HAH_PASSKEY, hahPasskey);
}
public static String getHAHPasskey() {
return getString(KEY_HAH_PASSKEY, DEFAULT_HAH_PASSKEY);
}
/****** Read ******/
private static final String KEY_READING_DIRECTION = "reading_direction";
private static final int DEFAULT_READING_DIRECTION = 0;
private static final String KEY_PAGE_SCALING = "page_scaling";
private static final int DEFAULT_PAGE_SCALING = 3;
private static final String KEY_START_POSITION = "start_position";
private static final int DEFAULT_START_POSITION = 1;
private static final String KEY_VOLUME_PAGE = "volume_page";
private static final boolean DEFAULT_VOLUME_PAGE = false;
private static final String KEY_GALLERY_SHOW_CLOCK = "gallery_show_clock";
private static final boolean DEFAULT_GALLERY_SHOW_CLOCK = true;
private static final String KEY_KEEP_SCREEN_ON = "keep_screen_on";
private static final boolean DEFAULT_KEEP_SCREEN_ON = false;
private static final String KEY_GALLERY_SHOW_BATTERY = "gallery_show_battery";
private static final boolean DEFAULT_GALLERY_SHOW_BATTERY = true;
private static final String KEY_CUSTOM_LIGHTNESS = "custom_lightness";
private static final boolean DEFAULT_CUSTOM_LIGHTNESS = false;
private static final String KEY_CUSTOM_LIGHTNESS_VALUE = "custom_lightness_value";
private static final int DEFAULT_CUSTOM_LIGHTNESS_VALUE = 120;
private static final String KEY_CUSTOM_CODEC = "custom_codec";
private static final String KEY_DECODE_FORMAT = "decode_format";
private static final int DEFAULT_DECODE_FORMAT = 0;
public static int getReadingDirection() {
return getIntFromStr(KEY_READING_DIRECTION, DEFAULT_READING_DIRECTION);
}
public static void setReadingDirection(int value) {
setIntToStr(KEY_READING_DIRECTION, value);
}
public static int getPageScaling() {
return getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING);
}
public static void setPageScaling(int value) {
setIntToStr(KEY_PAGE_SCALING, value);
}
public static int getStartPosition() {
return getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION);
}
public static void setStartPosition(int value) {
setIntToStr(KEY_START_POSITION, value);
}
public static boolean getKeepSreenOn() {
return getBoolean(KEY_KEEP_SCREEN_ON, DEFAULT_KEEP_SCREEN_ON);
}
public static void setKeepSreenOn(boolean value) {
setBoolean(KEY_KEEP_SCREEN_ON, value);
}
public static void setVolumePage(boolean value) {
setBoolean(KEY_VOLUME_PAGE, value);
}
public static boolean getVolumePage() {
return getBoolean(KEY_VOLUME_PAGE, DEFAULT_VOLUME_PAGE);
}
public static boolean getShowClock() {
return getBoolean(KEY_GALLERY_SHOW_CLOCK, DEFAULT_GALLERY_SHOW_CLOCK);
}
public static void setShowClock(boolean value) {
setBoolean(KEY_GALLERY_SHOW_CLOCK, value);
}
public static boolean getShowBattery() {
return getBoolean(KEY_GALLERY_SHOW_BATTERY, DEFAULT_GALLERY_SHOW_BATTERY);
}
public static void setShowBattery(boolean value) {
setBoolean(KEY_GALLERY_SHOW_BATTERY, value);
}
public static boolean getCustomLightness() {
return getBoolean(KEY_CUSTOM_LIGHTNESS, DEFAULT_CUSTOM_LIGHTNESS);
}
public static void setCustomLightness(boolean value) {
setBoolean(KEY_CUSTOM_LIGHTNESS, value);
}
public static int getCustomLightnessValue() {
return getIntFromStr(KEY_CUSTOM_LIGHTNESS_VALUE, DEFAULT_CUSTOM_LIGHTNESS_VALUE);
}
public static void setCustomLightnessValue(int value) {
setIntToStr(KEY_CUSTOM_LIGHTNESS_VALUE, value);
}
public static boolean getCustomCodec() {
return getBoolean(KEY_CUSTOM_CODEC, Utils.SUPPORT_IMAGE);
}
public static void setCustomCodec(boolean value) {
setBoolean(KEY_CUSTOM_CODEC, value);
}
public static int getDecodeFormat() {
return getIntFromStr(KEY_DECODE_FORMAT, DEFAULT_DECODE_FORMAT);
}
public static int getDecodeFormatIndex() {
int index = getIntFromStr(KEY_DECODE_FORMAT, DEFAULT_DECODE_FORMAT);
switch (index) {
case 6409:
index = 1;
break;
case 6410:
index = 2;
break;
case 6407:
index = 3;
break;
case 6408:
index = 4;
break;
case 0:
default:
index = 0;
break;
}
return index;
}
public static void setDecodeFormatFromIndex(int index) {
switch (index) {
case 1:
index = 6409;
break;
case 2:
index = 6410;
break;
case 3:
index = 6407;
break;
case 4:
index = 6408;
break;
case 0:
default:
index = 0;
break;
}
setIntToStr(KEY_DECODE_FORMAT, index);
}
/****** Download ******/
private static final String KEY_DOWNLOAD_PATH = "download_path";
private static final String DEFAULT_DOWNLOAD_PATH =
Environment.getExternalStorageDirectory() + "/EhViewer/download/";
private static final String KEY_MEDIA_SCAN = "media_scan";
private static final boolean DEFAULT_MEDIA_SCAN = false;
private static final String KEY_DOWNLOAD_THREAD = "download_thread";
private static final int DEFAULT_DOWNLOAD_THREAD = 3;
private static final String KEY_DOWNLOAD_ORIGIN_IMAGE = "download_origin_image";
private static final boolean DEFAULT_DOWNLOAD_ORIGIN_IMAGE = false;
private static final String KEY_KEEP_DOWNLOAD_SERVICE = "keep_download_service";
private static final boolean DEFAULT_KEEP_DOWNLOAD_SERVICE = true;
public static String getDownloadPath() {
return getString(KEY_DOWNLOAD_PATH, DEFAULT_DOWNLOAD_PATH);
}
public static void setDownloadPath(String path) {
setString(KEY_DOWNLOAD_PATH, path);
}
public static boolean getMediaScan() {
return getBoolean(KEY_MEDIA_SCAN, DEFAULT_MEDIA_SCAN);
}
public static int getDownloadThread() {
return getIntFromStr(KEY_DOWNLOAD_THREAD, DEFAULT_DOWNLOAD_THREAD);
}
public static boolean getDownloadOriginImage() {
return getBoolean(KEY_DOWNLOAD_ORIGIN_IMAGE, DEFAULT_DOWNLOAD_ORIGIN_IMAGE);
}
public static boolean getKeepDownloadService() {
return getBoolean(KEY_KEEP_DOWNLOAD_SERVICE, DEFAULT_KEEP_DOWNLOAD_SERVICE);
}
/****** Advanced ******/
private static final String KEY_HTTP_RETRY = "http_retry";
private static final int DEFAULT_HTTP_RETRY = 3;
private static final String KEY_HTTP_CONNECT_TIMEOUT = "http_connect_timeout";
private static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 5000;
private static final String KEY_HTTP_READ_TIMEOUT = "http_read_timeout";
private static final int DEFAULT_HTTP_READ_TIMEOUT = 5000;
private static final String KEY_EH_MIN_INTERVAL = "eh_min_interval";
private static final int DEFAULT_EH_MIN_INTERVAL = 0;
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
private static final String DEFAULT_PATTERN_PROTECTION = "";
private static final String KEY_SHOW_APPLICATION_STATS = "show_application_stats";
private static final boolean DEFAULT_SHOW_APPLICATION_STATS = false;
public static int getHttpRetry() {
return getIntFromStr(KEY_HTTP_RETRY, DEFAULT_HTTP_RETRY);
}
public static int getHttpConnectTimeout() {
return getIntFromStr(KEY_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_CONNECT_TIMEOUT);
}
public static int getHttpReadTimeout() {
return getIntFromStr(KEY_HTTP_READ_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT);
}
public static int getEhMinInterval() {
return getIntFromStr(KEY_EH_MIN_INTERVAL, DEFAULT_EH_MIN_INTERVAL);
}
public static String getPatternProtection() {
return getString(KEY_PATTERN_PROTECTION, DEFAULT_PATTERN_PROTECTION);
}
public static void setPatternProtection(String value) {
setString(KEY_PATTERN_PROTECTION, value);
}
public static boolean getShowApplicationStats() {
return getBoolean(KEY_SHOW_APPLICATION_STATS, DEFAULT_SHOW_APPLICATION_STATS);
}
public static void setShowApplicationStats(boolean value) {
setBoolean(KEY_SHOW_APPLICATION_STATS, value);
}
/****** About ******/
private static final String KEY_AUTO_CHECK_FOR_UPDATE = "auto_check_for_update";
private static final boolean DEFAULT_AUTO_CHECK_FOR_UPDATE = true;
private static final String KEY_UPDATE_SERVER = "update_server";
private static final int DEFAULT_UPDATE_SERVER = 1;
private static final String KEY_ALLOW_ANALYTICS = "allow_analyics";
private static final boolean DEFAULT_ALLOW_ANALYTICS = false;
public static boolean isAutoCheckForUpdate() {
return getBoolean(KEY_AUTO_CHECK_FOR_UPDATE, DEFAULT_AUTO_CHECK_FOR_UPDATE);
}
public static void setAutoCheckForUpdate(boolean autoCheckForUpdate) {
setBoolean(KEY_AUTO_CHECK_FOR_UPDATE, autoCheckForUpdate);
}
public static int getUpdateDate() {
return getInt(KEY_UPDATE_DATE, 0);
}
public static void setUpdateDate() {
setUpdateDate(Utils.getDate());
}
public static void setUpdateDate(int date) {
setInt(KEY_UPDATE_DATE, date);
}
public static String getUpdateServer() {
int value = getIntFromStr(KEY_UPDATE_SERVER, DEFAULT_UPDATE_SERVER);
switch (value) {
case 1:
return "qiniu";
case 0:
default:
return "google";
}
}
public static boolean getAllowAnalyics() {
return getBoolean(KEY_ALLOW_ANALYTICS, DEFAULT_ALLOW_ANALYTICS);
}
public static void setAllowAnalyics(boolean setAnalyics) {
setBoolean(KEY_ALLOW_ANALYTICS, setAnalyics);
}
/****** Mode an API Mode ******/
private static final String KEY_MODE = "mode";
private static final int DEFAULT_MODE = EhClient.MODE_G;
private static final String KEY_API_MODE = "api_mode";
private static final int DEFAULT_API_MODE = EhClient.MODE_G;
private static final String KEY_LOFI_RESOLUTION = "lofi_resolution";
private static final int DEFAULT_LOFI_RESOLUTION = 1;
public static int getMode() {
return getInt(KEY_MODE, DEFAULT_MODE);
}
public static void setMode(int mode) {
setInt(KEY_MODE, mode);
}
public static int getApiMode() {
return getInt(KEY_API_MODE, DEFAULT_API_MODE);
}
public static void setApiMode(int apiMode) {
setInt(KEY_API_MODE, apiMode);
}
public static int getLofiResolution() {
return getInt(KEY_LOFI_RESOLUTION, DEFAULT_LOFI_RESOLUTION);
}
public static void setLofiResolution(int lofiResolution) {
setInt(KEY_LOFI_RESOLUTION, lofiResolution);
}
// Proxy urls
private static final String PROXY_URLS_KEY = "proxy_urls";
public static final String[] DEFAULT_PROXY_URLS = {
"http://proxyy0000.appsp0t.com/proxy",
"http://proxyy0001.appsp0t.com/proxy",
"http://proxyy0002.appsp0t.com/proxy",
"http://proxyy0003.appsp0t.com/proxy",
"http://proxyy0004.appsp0t.com/proxy",
"http://proxyy0005.appsp0t.com/proxy",
"http://proxyy0006.appsp0t.com/proxy",
"http://proxyy0007.appsp0t.com/proxy",
"http://proxyy0008.appsp0t.com/proxy",
"http://proxyy0009.appsp0t.com/proxy",
"http://proxyy000a.appsp0t.com/proxy",
"http://proxyy000b.appsp0t.com/proxy",
"http://proxyy000c.appsp0t.com/proxy",
"http://proxyy000d.appsp0t.com/proxy",
"http://proxyy000e.appsp0t.com/proxy",
"http://proxyy000f.appsp0t.com/proxy"
};
public static String[] getProxyUrls() {
Set<String> re = mConfigPre.getStringSet(PROXY_URLS_KEY, null);
if (re != null && re.size() > 0)
return re.toArray(new String[re.size()]);
else
return DEFAULT_PROXY_URLS;
}
public static void setProxyUrls(String[] urls) {
mConfigPre.edit().putStringSet(PROXY_URLS_KEY, new HashSet<String>(Arrays.asList(urls))).apply();
}
}
@@ -1,33 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.content.Context;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.app.MaterialAlertDialog;
public class DialogUtils {
public static MaterialAlertDialog.Builder createUpdateDialog(Context context, String version, String size,
String info, MaterialAlertDialog.OnClickListener l) {
return new MaterialAlertDialog.Builder(context).setTitle(R.string.update).setCancelable(false)
.setMessage(String.format(context.getString(R.string.update_message), version, size, info))
.setPositiveButton(android.R.string.ok).setNegativeButton(android.R.string.cancel).setButtonListener(l);
}
}
@@ -1,124 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import java.io.File;
import com.hippo.ehviewer.data.ListUrls;
public final class EhUtils {
public static final String EH_DOWNLOAD_FILENAME = ".ehviewer";
private static final int[] CATEGORY_VALUES = { ListUrls.MISC, ListUrls.DOUJINSHI, ListUrls.MANGA,
ListUrls.ARTIST_CG, ListUrls.GAME_CG, ListUrls.IMAGE_SET, ListUrls.COSPLAY, ListUrls.ASIAN_PORN,
ListUrls.NON_H, ListUrls.WESTERN, ListUrls.UNKNOWN };
// TODO How about "Private"
private static final String[][] CATEGORY_STRINGS = { new String[] { "misc" }, new String[] { "doujinshi" },
new String[] { "manga" }, new String[] { "artistcg", "Artist CG Sets" },
new String[] { "gamecg", "Game CG Sets" }, new String[] { "imageset", "Image Sets" },
new String[] { "cosplay" }, new String[] { "asianporn", "Asian Porn" }, new String[] { "non-h" },
new String[] { "western" }, new String[] { "unknown" } };
public static int getCategory(String type) {
int i;
for (i = 0; i < CATEGORY_STRINGS.length - 1; i++) {
for (String str : CATEGORY_STRINGS[i])
if (str.equalsIgnoreCase(type))
return CATEGORY_VALUES[i];
}
return CATEGORY_VALUES[i];
}
public static String getCategory(int type) {
int i;
for (i = 0; i < CATEGORY_VALUES.length - 1; i++) {
if (CATEGORY_VALUES[i] == type)
break;
}
return CATEGORY_STRINGS[i][0];
}
/**
* Get gallery for read and download Gid is constant, but title may be
* changed
*
* @param gid
* @param title
* @return
*/
public static File getGalleryDir(int gid, String title) {
File downloadDir = new File(Config.getDownloadPath());
File gDir = new File(downloadDir, Utils.standardizeFilename(Integer.toString(gid)));
File defaultDir = generateGalleryDir(gid, title);
if (gDir.exists()) {
if (gDir.renameTo(defaultDir))
return defaultDir;
else
return gDir;
} else {
// TODO I need a better way or only call it in non-UI thread
String[] fileList = downloadDir.list();
if (fileList != null) {
for (String str : fileList) {
// For title changed
if (str.startsWith(gid + "-") && (gDir = new File(downloadDir, str)) != null && gDir.isDirectory())
return gDir;
}
}
return defaultDir;
}
}
public static File generateGalleryDir(int gid, String title) {
return new File(Config.getDownloadPath(), Utils.standardizeFilename(gid + "-" + title));
}
/**
* Index start from 0
*
* @param index
* @param extension
* @return
*/
public static String getImageFilename(int index, String extension) {
return String.format("%08d.%s", index + 1, extension);
}
public static String[] POSSIBLE_IMAGE_EXTENSION_ARRAY = new String[] {
"jpg", "jpeg", "png", "gif"
};
public static String DEFAULT_IMAGE_EXTENSION = POSSIBLE_IMAGE_EXTENSION_ARRAY[0];
public static String[] getPossibleImageFilenames(int index) {
String prefix = String.format("%08d.", index + 1);
int length = POSSIBLE_IMAGE_EXTENSION_ARRAY.length;
String[] strs = new String[length];
for (int i = 0; i < length; i++)
strs[i] = prefix + POSSIBLE_IMAGE_EXTENSION_ARRAY[i];
return strs;
}
}
@@ -1,156 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
@SuppressLint("InlinedApi")
public final class FullScreenHelper implements View.OnSystemUiVisibilityChangeListener {
private static final String TAG = FullScreenHelper.class.getSimpleName();
private final int NOT_FULL_SCREEN_JELLY_BEAN =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
private final int FULL_SCREEN_JELLY_BEAN =
NOT_FULL_SCREEN_JELLY_BEAN |
View.SYSTEM_UI_FLAG_LOW_PROFILE |
View.SYSTEM_UI_FLAG_FULLSCREEN;
private final int FULL_SCREEN_FLAG_JELLY_BEAN =
View.SYSTEM_UI_FLAG_LOW_PROFILE |
View.SYSTEM_UI_FLAG_FULLSCREEN;
private final int NOT_FULL_SCREEN_KITKAT =
NOT_FULL_SCREEN_JELLY_BEAN |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
private final int FULL_SCREEN_KITKAT =
NOT_FULL_SCREEN_KITKAT |
View.SYSTEM_UI_FLAG_LOW_PROFILE |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
private boolean mFullScreen;
private final Activity mActivity;
private final Window mWindow;
private final View mDecorView;
private boolean mHasNavBar;
private OnFullScreenBrokenListener mListener;
private final int TEST_SDK = Build.VERSION.SDK_INT;
public interface OnFullScreenBrokenListener {
/**
* FullScreen state should be fullScreen or not,
* but user or system broke it
*
* @param fullScreen support to be
*/
public void onFullScreenBroken(boolean fullScreen);
}
public FullScreenHelper(Activity activity) {
mFullScreen = false;
mActivity = activity;
mWindow = mActivity.getWindow();
mDecorView = mWindow.getDecorView();
mDecorView.setOnSystemUiVisibilityChangeListener(this);
String mainKey = Utils.getSystemProperties("qemu.hw.mainkeys");
int resourceId = activity.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
if (resourceId != 0) {
mHasNavBar = activity.getResources().getBoolean(resourceId);
// check override flag (see static block)
if ("1".equals(mainKey)) {
mHasNavBar = false;
} else if ("0".equals(mainKey)) {
mHasNavBar = true;
}
} else {
mHasNavBar = !ViewConfiguration.get(activity).hasPermanentMenuKey();
}
}
public boolean willHideNavBar() {
if (TEST_SDK >= Build.VERSION_CODES.KITKAT && mHasNavBar)
return true;
else
return false;
}
@Override
public void onSystemUiVisibilityChange(int visibility) {
if (TEST_SDK >= Build.VERSION_CODES.JELLY_BEAN &&
TEST_SDK < Build.VERSION_CODES.KITKAT) {
if ((mFullScreen && visibility != FULL_SCREEN_FLAG_JELLY_BEAN) ||
(!mFullScreen && visibility != 0)) {
// User or system change visibility
if (mListener != null)
mListener.onFullScreenBroken(mFullScreen);
}
}
}
public void setOnFullScreenBrokenListener(OnFullScreenBrokenListener l) {
mListener = l;
}
public boolean getFullScreen() {
return mFullScreen;
}
public void setFullScreen(boolean fullScreen) {
mFullScreen = fullScreen;
if (fullScreen) {
if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// Empty
} else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) {
mWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else if (TEST_SDK < Build.VERSION_CODES.KITKAT) {
mDecorView.setSystemUiVisibility(FULL_SCREEN_JELLY_BEAN);
} else {
mDecorView.setSystemUiVisibility(FULL_SCREEN_KITKAT);
}
} else {
if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// Empty
} else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) {
mWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else if (TEST_SDK < Build.VERSION_CODES.KITKAT) {
mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_JELLY_BEAN);
} else {
mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_KITKAT);
}
}
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
public final class IntIdGenerator {
private int mId = 0;
private IntIdGenerator() {
// Empty
}
public synchronized int nextId() {
return mId++;
}
public static IntIdGenerator create() {
return new IntIdGenerator();
}
}
@@ -1,87 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.util.SparseArray;
import com.hippo.ehviewer.AppHandler;
import java.util.HashSet;
import java.util.Set;
public class Messenger {
private IntIdGenerator mIdGenerator;
private SparseArray<Set<Receiver>> mReceiverSetMap;
private static Messenger sInstance;
public static Messenger getInstance() {
if (sInstance == null) {
sInstance = new Messenger();
}
return sInstance;
}
private Messenger() {
mIdGenerator = IntIdGenerator.create();
mReceiverSetMap = new SparseArray<>();
}
public int newId() {
return mIdGenerator.nextId();
}
public void notify(final int id, final Object obj) {
// Make sure do it in UI thread
AppHandler.getInstance().post(new Runnable() {
@Override
public void run() {
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
if (receiverSet != null) {
for (Receiver receiver : receiverSet) {
receiver.onReceive(id, obj);
}
}
}
});
}
public void register(int id, Receiver receiver) {
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
if (receiverSet == null) {
receiverSet = new HashSet<>();
mReceiverSetMap.put(id, receiverSet);
}
receiverSet.add(receiver);
}
public void unregister(int id, Receiver receiver) {
Set<Receiver> receiverSet = mReceiverSetMap.get(id);
if (receiverSet != null) {
receiverSet.remove(receiver);
if (receiverSet.isEmpty()) {
mReceiverSetMap.remove(id);
}
}
}
public interface Receiver {
void onReceive(final int id, final Object obj);
}
}
@@ -1,28 +0,0 @@
package com.hippo.ehviewer.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
public final class PackageUtils {
private static final String TAG = PackageUtils.class.getSimpleName();
public static String getSignature(Context context, String packageName) {
try {
@SuppressLint("PackageManagerGetSignatures")
PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
Signature[] ss = pi.signatures;
if (ss != null && ss.length >= 1) {
return Utils.computeSHA1(ss[0].toByteArray());
} else {
Log.e(TAG, "Can't find signature in package " + packageName);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Can't find package " + packageName, e);
}
return null;
}
}
@@ -1,89 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.hippo.ehviewer.network.HttpHelper;
import java.io.File;
public final class Secret {
private static final String DIR_NAME = "images";
private static final String IMAGE_NAME = "sercet.jpg";
private static final String SERCET_IMAGE_URL = "http://www.ehviewer.com/static/images/pandas.jpg";
private static volatile boolean sIsGetSecretImage = false;
public static void updateSecretImage(Context context) {
if (sIsGetSecretImage)
return;
sIsGetSecretImage = true;
new UpdateSercetImageThread(context).start();
}
public static boolean hasSecretImage(Context context) {
if (sIsGetSecretImage)
return false;
File dir = context.getExternalFilesDir(DIR_NAME);
File image = new File(dir, IMAGE_NAME);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
return opts.outWidth > 0 && opts.outHeight > 0;
}
public static Bitmap getSecretImage(Context context) {
if (sIsGetSecretImage)
return null;
File dir = context.getExternalFilesDir(DIR_NAME);
File image = new File(dir, IMAGE_NAME);
return BitmapFactory.decodeFile(image.getAbsolutePath(), null);
}
private static class UpdateSercetImageThread extends BgThread {
private final Context mContext;
public UpdateSercetImageThread(Context context) {
mContext = context;
}
@Override
public void run() {
// TODO check usable space
File dir = mContext.getExternalFilesDir(DIR_NAME);
File image = new File(dir, IMAGE_NAME);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
if (opts.outWidth <= 0 || opts.outHeight <= 0) {
// Get image error, try to get image from internet
HttpHelper hh = new HttpHelper(mContext);
hh.download(SERCET_IMAGE_URL, mContext.getExternalFilesDir(DIR_NAME),
IMAGE_NAME, null, null, null);
}
sIsGetSecretImage = false;
}
}
}
@@ -1,210 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.hippo.ehviewer.R;
public final class ViewUtils {
public static ContextThemeWrapper sContextThemeWrapper;
public static ContextThemeWrapper sDarkContextThemeWrapper;
private static LayoutInflater sDialogViewInflater;
private static LayoutInflater sDarkDialogViewInflater;
public static final void initDialogViewInflater(Context context) {
sContextThemeWrapper = new ContextThemeWrapper(context, R.style.AppTheme_Dialog);
sDarkContextThemeWrapper = new ContextThemeWrapper(context, R.style.AppTheme_Dark_Dialog);
sDialogViewInflater = LayoutInflater.from(sContextThemeWrapper);
sDarkDialogViewInflater = LayoutInflater.from(sDarkContextThemeWrapper);
}
public static final View inflateDialogView(int resId, boolean dark) {
LayoutInflater inflater = dark ? sDarkDialogViewInflater : sDialogViewInflater;
return inflater.inflate(resId, null);
}
/**
* Get view center location in window
*
* @param view
* @param location
*/
public static void getCenterInWindows(View view, int[] location) {
getLocationInWindow(view, location);
location[0] += view.getWidth() / 2;
location[1] += view.getHeight() / 2;
}
/**
* Get view location in window
*
* @param view
* @param location
*/
public static void getLocationInWindow(View view, int[] location) {
if (location == null || location.length < 2) {
throw new IllegalArgumentException(
"location must be an array of two integers");
}
float[] position = new float[2];
position[0] = view.getLeft();
position[1] = view.getTop();
ViewParent viewParent = view.getParent();
while (viewParent instanceof View) {
view = (View) viewParent;
if (view.getId() == android.R.id.content) {
break;
}
position[0] -= view.getScrollX();
position[1] -= view.getScrollY();
position[0] += view.getLeft();
position[1] += view.getTop();
viewParent = view.getParent();
}
location[0] = (int) (position[0] + 0.5f);
location[1] = (int) (position[1] + 0.5f);
}
public static View getAncestor(View view, int id) {
ViewParent viewParent = view.getParent();
while (viewParent instanceof View) {
view = (View) viewParent;
if (view.getId() == id)
return view;
viewParent = view.getParent();
}
return null;
}
/**
* Returns a bitmap showing a screenshot of the view passed in.
*
* @param v
* @return
*/
public static Bitmap getBitmapFromView(View v) {
int width = v.getWidth();
int height = v.getHeight();
if (width == 0 && height == 0) {
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// TODO I need to know why I need it, when ScrollView
canvas.translate(-v.getScrollX(), -v.getScrollY());
v.draw(canvas);
return bitmap;
}
public static boolean isClickAction(MotionEvent event) {
// TODO bad idea to check click
return event.getAction() == MotionEvent.ACTION_UP
&& System.nanoTime() / 1000000 - event.getDownTime() < 200;
}
public static void removeFromParent(View view) {
ViewParent vp = view.getParent();
if (vp instanceof ViewGroup)
((ViewGroup) vp).removeView(view);
}
/**
* Method that removes the support for HardwareAcceleration from a
* {@link View}.<br/>
* <br/>
* Check AOSP notice:<br/>
*
* <pre>
* 'ComposeShader can only contain shaders of different types (a BitmapShader and a
* LinearGradient for instance, but not two instances of BitmapShader)'. But, 'If your
* application is affected by any of these missing features or limitations, you can turn
* off hardware acceleration for just the affected portion of your application by calling
* setLayerType(View.LAYER_TYPE_SOFTWARE, null).'
* </pre>
*
* @param v
* The view
*/
public static void removeHardwareAccelerationSupport(View v) {
if (v.getLayerType() != View.LAYER_TYPE_SOFTWARE) {
v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public static void measureView(View v, int width, int height) {
int widthMeasureSpec;
int heightMeasureSpec;
if (width == ViewGroup.LayoutParams.WRAP_CONTENT)
widthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
else
widthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(width, 0),
MeasureSpec.EXACTLY);
if (height == ViewGroup.LayoutParams.WRAP_CONTENT)
heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
else
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(height, 0),
MeasureSpec.EXACTLY);
v.measure(widthMeasureSpec, heightMeasureSpec);
}
/**
* Determine if the supplied view is under the given point in the
* parent view's coordinate system.
*
* @param view Child view of the parent to hit test
* @param x X position to test in the parent's coordinate system
* @param y Y position to test in the parent's coordinate system
* @return true if the supplied view is under the given point, false otherwise
*/
public static boolean isViewUnder(View view, int x, int y) {
if (view == null || view.getVisibility() != View.VISIBLE) {
return false;
}
return x >= view.getLeft() &&
x < view.getRight() &&
y >= view.getTop() &&
y < view.getBottom();
}
public static void transformPointToViewLocal(float[] point, View parent, View child) {
point[0] += parent.getScrollX() - child.getLeft();
point[1] += parent.getScrollY() - child.getTop();
}
}
@@ -1,59 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
public class ColorView extends View {
private int mColor;
public ColorView(Context context) {
super(context);
}
public ColorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ColorView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setColor(int color) {
if (mColor != color) {
mColor = color;
invalidate();
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(mColor);
}
}
@@ -1,115 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Ui;
public class DrawerListView extends ListView {
private Context mContext;
private DrawerListAdapter mAdapter;
private static final int DRAWABLE_SIDE = Ui.dp2pix(24);
public DrawerListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public DrawerListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DrawerListView(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
mContext = context;
mAdapter = new DrawerListAdapter();
setAdapter(mAdapter);
}
public void setData(Drawable[] drawableArray, CharSequence[] titleArray) {
mAdapter.setData(drawableArray, titleArray);
}
private class DrawerListAdapter extends BaseAdapter {
private Drawable[] mDrawableArray;
private CharSequence[] mTitleArray;
private void setData(Drawable[] drawableArray, CharSequence[] titleArray) {
if (drawableArray != null && titleArray != null) {
if (drawableArray.length != titleArray.length)
throw new java.lang.IllegalStateException("drawableArray.length != titleArray.length");
} else if (drawableArray == null && titleArray == null) {
throw new java.lang.IllegalStateException("drawableArray and titleArray should be all null or not null");
}
mDrawableArray = drawableArray;
mTitleArray = titleArray;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTitleArray == null ? 0 : mTitleArray.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from(mContext).inflate(R.layout.drawer_list_item, parent, false);
TextView tv = (TextView) convertView;
Drawable d = mDrawableArray[position];
CharSequence t = mTitleArray[position];
tv.setText(t);
d.setBounds(0, 0, DRAWABLE_SIDE, DRAWABLE_SIDE);
tv.setCompoundDrawables(d, null, null, null);
return convertView;
}
}
}
@@ -1,563 +0,0 @@
/*
* Copyright (C) 2013 The Android Open Source Project
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.graphics.Canvas;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* A custom listview which supports the preview of extra content corresponding to each cell
* by clicking on the cell to hide and show the extra content.
*/
public class ExpandingListView extends ListView {
@SuppressWarnings("unused")
private static final String TAG = ExpandingListView.class.getSimpleName();
private int mExpandingId;
private boolean mShouldRemoveObserver = false;
private boolean mAnimating = false;
private final List<View> mViewsToDraw = new ArrayList<View>();
private int[] mTranslate;
public ExpandingListView(Context context) {
super(context);
init();
}
public ExpandingListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ExpandingListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setOnItemClickListener(mItemClickListener);
}
public void setExpandingId(int id) {
mExpandingId = id;
}
public boolean isAnimating() {
return mAnimating;
}
/**
* Listens for item clicks and expands or collapses the selected view depending on
* its current state.
*/
private final AdapterView.OnItemClickListener mItemClickListener = new AdapterView
.OnItemClickListener() {
@Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
if (view.findViewById(mExpandingId).getVisibility() == View.GONE) {
expandView(view);
} else {
collapseView(view);
}
}
};
private int[] getTopAndBottomTranslationsE(int top, int bottom, int yDelta) {
int yTranslateTop = 0;
int yTranslateBottom = yDelta;
int height = bottom - top;
int bottomLine = getHeight() - getPaddingBottom();
boolean isOverTop = top < getPaddingTop();
boolean isBelowBottom = (top + height + yDelta) > bottomLine;
if (isOverTop) {
yTranslateTop = top - getPaddingTop();
yTranslateBottom = yDelta - yTranslateTop;
} else if (isBelowBottom){
int deltaBelow = top + height + yDelta - bottomLine;
yTranslateTop = top - deltaBelow < getPaddingTop() ? (top - getPaddingTop()) : deltaBelow;
yTranslateBottom = yDelta - yTranslateTop;
}
return new int[] {yTranslateTop, yTranslateBottom};
}
private int[] getTopAndBottomTranslationsC(int top, int bottom, int yDelta, int firstTop, View view) {
int yTranslateTop = 0;
int yTranslateBottom = yDelta;
int bottomLine = getHeight() - getPaddingBottom();
int index = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
if (getChildAt(i).equals(view)) {
index = i;
break;
}
}
int maxBottom = bottom;
for (int i = index + 1; i < getChildCount(); i++) {
View v = getChildAt(i);
maxBottom += v.getVisibility() != View.GONE ? v.getHeight() + getDividerHeight() : 0;
}
int newMaxBottom = maxBottom - yDelta;
int maxYTranslateTop = getPaddingTop() - firstTop;
boolean isCollapsingAboveBottom = maxBottom >= bottomLine && newMaxBottom < bottomLine;
if (isCollapsingAboveBottom) {
yTranslateTop = bottomLine - newMaxBottom;
if (yTranslateTop > maxYTranslateTop)
yTranslateTop = maxYTranslateTop;
yTranslateBottom = yDelta - yTranslateTop;
}
return new int[] {yTranslateTop, yTranslateBottom};
}
/**
* This method expands the view that was clicked and animates all the views
* around it to make room for the expanding view. There are several steps required
* to do this which are outlined below.
*
* 1. Store the current top and bottom bounds of each visible item in the listview.
* 2. Update the layout parameters of the selected view. In the context of this
* method, the view should be originally collapsed and set to some custom height.
* The layout parameters are updated so as to wrap the content of the additional
* text that is to be displayed.
*
* After invoking a layout to take place, the listview will order all the items
* such that there is space for each view. This layout will be independent of what
* the bounds of the items were prior to the layout so two pre-draw passes will
* be made. This is necessary because after the layout takes place, some views that
* were visible before the layout may now be off bounds but a reference to these
* views is required so the animation completes as intended.
*
* 3. The first predraw pass will set the bounds of all the visible items to
* their original location before the layout took place and then force another
* layout. Since the bounds of the cells cannot be set directly, the method
* setSelectionFromTop can be used to achieve a very similar effect.
* 4. The expanding view's bounds are animated to what the final values should be
* from the original bounds.
* 5. The bounds above the expanding view are animated upwards while the bounds
* below the expanding view are animated downwards.
* 6. The extra text is faded in as its contents become visible throughout the
* animation process.
*
* It is important to note that the listview is disabled during the animation
* because the scrolling behaviour is unpredictable if the bounds of the items
* within the listview are not constant during the scroll.
*/
private void expandView(final View view) {
mAnimating = true;
final ExpandableListItem viewObject = (ExpandableListItem)getItemAtPosition
(getPositionForView(view));
/* Store the original top and bottom bounds of all the cells.*/
final int oldTop = view.getTop();
final int oldBottom = view.getBottom();
final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
ViewCompat.setHasTransientState(v, true);
oldCoordinates.put(v, new int[] {v.getTop(), v.getBottom()});
}
/* Update the layout so the extra content becomes visible.*/
final View expandingLayout = view.findViewById(mExpandingId);
expandingLayout.setVisibility(View.VISIBLE);
/* Add an onPreDraw Listener to the listview. onPreDraw will get invoked after onLayout
* and onMeasure have run but before anything has been drawn. This
* means that the final post layout properties for all the items have already been
* determined, but still have not been rendered onto the screen.*/
final ViewTreeObserver observer = getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
/* Determine if this is the first or second pass.*/
if (!mShouldRemoveObserver) {
mShouldRemoveObserver = true;
/* Calculate what the parameters should be for setSelectionFromTop.
* The ListView must be offset in a way, such that after the animation
* takes place, all the cells that remain visible are rendered completely
* by the ListView.*/
int newTop = view.getTop();
int newBottom = view.getBottom();
int newHeight = newBottom - newTop;
int oldHeight = oldBottom - oldTop;
int delta = newHeight - oldHeight;
mTranslate = getTopAndBottomTranslationsE(oldTop, oldBottom, delta);
int currentTop = view.getTop();
int futureTop = oldTop - mTranslate[0];
int firstChildStartTop = getChildAt(0).getTop();
int firstVisiblePosition = getFirstVisiblePosition();
int deltaTop = currentTop - futureTop;
int i;
int childCount = getChildCount();
for (i = 0; i < childCount; i++) {
View v = getChildAt(i);
int height = v.getBottom() - Math.max(0, v.getTop());
if (deltaTop - height > 0) {
firstVisiblePosition++;
deltaTop -= height;
} else {
break;
}
}
if (i > 0) {
firstChildStartTop = 0;
}
setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop - getPaddingTop());
/* Request another layout to update the layout parameters of the cells.*/
requestLayout();
/* Return false such that the ListView does not redraw its contents on
* this layout but only updates all the parameters associated with its
* children.*/
return false;
}
/* Remove the predraw listener so this method does not keep getting called. */
mShouldRemoveObserver = false;
observer.removeOnPreDrawListener(this);
int yTranslateTop = mTranslate[0];
int yTranslateBottom = mTranslate[1];
ArrayList <Animator> animations = new ArrayList<Animator>();
int index = indexOfChild(view);
/* Loop through all the views that were on the screen before the cell was
* expanded. Some cells will still be children of the ListView while
* others will not. The cells that remain children of the ListView
* simply have their bounds animated appropriately. The cells that are no
* longer children of the ListView also have their bounds animated, but
* must also be added to a list of views which will be drawn in dispatchDraw.*/
for (View v: oldCoordinates.keySet()) {
int[] old = oldCoordinates.get(v);
v.setTop(old[0]);
v.setBottom(old[1]);
if (v.getParent() == null) {
mViewsToDraw.add(v);
int delta = old[0] < oldTop ? -yTranslateTop : yTranslateBottom;
animations.add(getAnimation(v, delta, delta));
} else {
int i = indexOfChild(v);
if (v != view) {
int delta = i > index ? yTranslateBottom : -yTranslateTop;
animations.add(getAnimation(v, delta, delta));
}
ViewCompat.setHasTransientState(v, false);
}
}
/* Adds animation for expanding the cell that was clicked. */
animations.add(getAnimation(view, -yTranslateTop, yTranslateBottom));
/* Adds an animation for fading in the extra content. */
animations.add(ObjectAnimator.ofFloat(view.findViewById(mExpandingId),
View.ALPHA, 0, 1));
/* Disabled the ListView for the duration of the animation.*/
setEnabled(false);
setClickable(false);
/* Play all the animations created above together at the same time. */
AnimatorSet s = new AnimatorSet();
s.playTogether(animations);
s.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimating = false;
viewObject.setExpanded(true);
setEnabled(true);
setClickable(true);
if (mViewsToDraw.size() > 0) {
for (View v : mViewsToDraw) {
ViewCompat.setHasTransientState(v, false);
}
}
mViewsToDraw.clear();
}
});
s.start();
return true;
}
});
}
/**
* By overriding dispatchDraw, we can draw the cells that disappear during the
* expansion process. When the cell expands, some items below or above the expanding
* cell may be moved off screen and are thus no longer children of the ListView's
* layout. By storing a reference to these views prior to the layout, and
* guaranteeing that these cells do not get recycled, the cells can be drawn
* directly onto the canvas during the animation process. After the animation
* completes, the references to the extra views can then be discarded.
*/
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mViewsToDraw.size() == 0) {
return;
}
for (View v: mViewsToDraw) {
canvas.translate(0, v.getTop());
v.draw(canvas);
canvas.translate(0, -v.getTop());
}
}
/**
* This method collapses the view that was clicked and animates all the views
* around it to close around the collapsing view. There are several steps required
* to do this which are outlined below.
*
* 1. Update the layout parameters of the view clicked so as to minimize its height
* to the original collapsed (default) state.
* 2. After invoking a layout, the listview will shift all the cells so as to display
* them most efficiently. Therefore, during the first predraw pass, the listview
* must be offset by some amount such that given the custom bound change upon
* collapse, all the cells that need to be on the screen after the layout
* are rendered by the listview.
* 3. On the second predraw pass, all the items are first returned to their original
* location (before the first layout).
* 4. The collapsing view's bounds are animated to what the final values should be.
* 5. The bounds above the collapsing view are animated downwards while the bounds
* below the collapsing view are animated upwards.
* 6. The extra text is faded out as its contents become visible throughout the
* animation process.
*/
private void collapseView(final View view) {
mAnimating = true;
final ExpandableListItem viewObject = (ExpandableListItem)getItemAtPosition
(getPositionForView(view));
/* Store the original top and bottom bounds of all the cells.*/
final int oldTop = view.getTop();
final int oldBottom = view.getBottom();
final int firstTop = getChildAt(0).getTop();
final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
ViewCompat.setHasTransientState(v, true);
oldCoordinates.put(v, new int [] {v.getTop(), v.getBottom()});
}
/* Update the layout so the extra content becomes gone.*/
final View expandingLayout = view.findViewById(mExpandingId);
expandingLayout.setVisibility(View.GONE);
/* Add an onPreDraw listener. */
final ViewTreeObserver observer = getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (!mShouldRemoveObserver) {
/*Same as for expandingView, the parameters for setSelectionFromTop must
* be determined such that the necessary cells of the ListView are rendered
* and added to it.*/
mShouldRemoveObserver = true;
expandingLayout.setVisibility(View.VISIBLE);
int newTop = view.getTop();
int newBottom = view.getBottom();
int newHeight = newBottom - newTop;
int oldHeight = oldBottom - oldTop;
int deltaHeight = oldHeight - newHeight;
mTranslate = getTopAndBottomTranslationsC(oldTop, oldBottom, deltaHeight, firstTop, view);
int currentTop = view.getTop();
int futureTop = oldTop + mTranslate[0];
int firstChildStartTop = getChildAt(0).getTop();
int firstVisiblePosition = getFirstVisiblePosition();
int deltaTop = currentTop - futureTop;
int i;
int childCount = getChildCount();
for (i = 0; i < childCount; i++) {
View v = getChildAt(i);
int height = v.getBottom() - Math.max(0, v.getTop());
if (deltaTop - height > 0) {
firstVisiblePosition++;
deltaTop -= height;
} else {
break;
}
}
if (i > 0) {
firstChildStartTop = 0;
}
setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop - getPaddingTop());
requestLayout();
return false;
}
mShouldRemoveObserver = false;
observer.removeOnPreDrawListener(this);
int yTranslateTop = mTranslate[0];
int yTranslateBottom = mTranslate[1];
int index = indexOfChild(view);
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
int [] old = oldCoordinates.get(v);
if (old != null) {
/* If the cell was present in the ListView before the collapse and
* after the collapse then the bounds are reset to their old values.*/
v.setTop(old[0]);
v.setBottom(old[1]);
ViewCompat.setHasTransientState(v, false);
} else {
/* If the cell is present in the ListView after the collapse but
* not before the collapse then the bounds are calculated using
* the bottom and top translation of the collapsing cell.*/
int delta = i > index ? yTranslateBottom : -yTranslateTop;
v.setTop(v.getTop() + delta);
v.setBottom(v.getBottom() + delta);
}
}
final View expandingLayout = view.findViewById(mExpandingId);
/* Animates all the cells present on the screen after the collapse. */
ArrayList <Animator> animations = new ArrayList<Animator>();
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
if (v != view) {
float diff = i > index ? -yTranslateBottom : yTranslateTop;
animations.add(getAnimation(v, diff, diff));
}
}
/* Adds animation for collapsing the cell that was clicked. */
animations.add(getAnimation(view, yTranslateTop, -yTranslateBottom));
/* Adds an animation for fading out the extra content. */
animations.add(ObjectAnimator.ofFloat(expandingLayout, View.ALPHA, 1, 0));
/* Disabled the ListView for the duration of the animation.*/
setEnabled(false);
setClickable(false);
/* Play all the animations created above together at the same time. */
AnimatorSet s = new AnimatorSet();
s.playTogether(animations);
s.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimating = false;
expandingLayout.setVisibility(View.GONE);
view.setLayoutParams(new AbsListView.LayoutParams(AbsListView
.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
viewObject.setExpanded(false);
setEnabled(true);
setClickable(true);
/* Note that alpha must be set back to 1 in case this view is reused
* by a cell that was expanded, but not yet collapsed, so its state
* should persist in an expanded state with the extra content visible.*/
expandingLayout.setAlpha(1);
}
});
s.start();
return true;
}
});
}
/**
* This method takes some view and the values by which its top and bottom bounds
* should be changed by. Given these params, an animation which will animate
* these bound changes is created and returned.
*/
private Animator getAnimation(final View view, float translateTop, float translateBottom) {
int top = view.getTop();
int bottom = view.getBottom();
int endTop = (int)(top + translateTop);
int endBottom = (int)(bottom + translateBottom);
PropertyValuesHolder translationTop = PropertyValuesHolder.ofInt("top", top, endTop);
PropertyValuesHolder translationBottom = PropertyValuesHolder.ofInt("bottom", bottom,
endBottom);
return ObjectAnimator.ofPropertyValuesHolder(view, translationTop, translationBottom);
}
}
@@ -1,151 +0,0 @@
package com.hippo.ehviewer.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.hippo.ehviewer.R;
public class FloatingActionButton extends View {
@SuppressWarnings("unused")
private static final String TAG = FloatingActionButton.class.getSimpleName();
private final Paint mButtonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint mDrawablePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Bitmap mBitmap;
private int mColor;
private final int mDrawableSide;
private final float mShadowRadius;
private final float mShadowDx;
private final float mShadowDy;
private int mCircleX;
private int mCircleY;
private int mCircleRadius;
private final Rect mSrc = new Rect();
private final RectF mDst = new RectF();
public FloatingActionButton(Context context) {
this(context, null);
}
public FloatingActionButton(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatingActionButton);
mDrawableSide = a.getDimensionPixelSize(R.styleable.FloatingActionButton_fabDrawableSide, 72);
mColor = a.getColor(R.styleable.FloatingActionButton_fabColor, Color.WHITE);
mButtonPaint.setStyle(Paint.Style.FILL);
mButtonPaint.setColor(mColor);
mShadowRadius = a.getDimension(R.styleable.FloatingActionButton_fabShadowRadius, 10.0f);
mShadowDx = a.getDimension(R.styleable.FloatingActionButton_fabShadowDx, 0.0f);
mShadowDy = a.getDimension(R.styleable.FloatingActionButton_fabShadowDy, 3.0f);
int shadowColor = a.getColor(R.styleable.FloatingActionButton_fabShadowColor, 0x8a000000);
mButtonPaint.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy, shadowColor);
Drawable drawable = a.getDrawable(R.styleable.FloatingActionButton_fabDrawable);
if (drawable != null && drawable instanceof BitmapDrawable)
mBitmap = ((BitmapDrawable) drawable).getBitmap();
a.recycle();
setWillNotDraw(false);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public void setColor(int color) {
mColor = color;
mButtonPaint.setColor(mColor);
invalidate();
}
public void setDrawable(Drawable drawable) {
mBitmap = ((BitmapDrawable) drawable).getBitmap();
updateValue();
invalidate();
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
case MeasureSpec.AT_MOST:
result = size;
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
private void updateValue() {
float half = Math.min(getWidth(), getHeight()) / 2;
mCircleX = (int) (half - mShadowDx);
mCircleY = (int) (half - mShadowDy);
mCircleRadius = (int) (half - mShadowRadius);
float halfDrawableSide = mDrawableSide / 2.0f;
if (mBitmap != null) {
mSrc.set(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
mDst.set(mCircleX - halfDrawableSide, mCircleY - halfDrawableSide, mCircleX + halfDrawableSide, mCircleY + halfDrawableSide);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
updateValue();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(mCircleX, mCircleY, mCircleRadius, mButtonPaint);
if (null != mBitmap)
canvas.drawBitmap(mBitmap, mSrc, mDst, mDrawablePaint);
}
@Override
@SuppressLint("ClickableViewAccessibility")
public boolean onTouchEvent(MotionEvent event) {
int color;
if (event.getAction() == MotionEvent.ACTION_UP) {
color = mColor;
} else {
color = darkenColor(mColor);
}
mButtonPaint.setColor(color);
invalidate();
return super.onTouchEvent(event);
}
public static int darkenColor(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f;
return Color.HSVToColor(hsv);
}
}
@@ -1,826 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.hippo.ehviewer.AppHandler;
import com.hippo.ehviewer.ImageLoader;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.cardview.CardViewSalon;
import com.hippo.ehviewer.data.GalleryInfo;
import com.hippo.ehviewer.ehclient.ListParser;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.recyclerview.EasyRecyclerView;
import com.hippo.ehviewer.widget.recyclerview.MarginItemDecoration;
import com.hippo.ehviewer.widget.refreshlayout.RefreshLayout;
import java.util.ArrayList;
import java.util.List;
public class GalleryListView extends FrameLayout implements RefreshLayout.OnHeaderRefreshListener,
RefreshLayout.OnFooterRefreshListener {
private static final String TAG = GalleryListView.class.getSimpleName();
public static final int LIST_MODE_DETAIL = 0;
public static final int LIST_MODE_THUMB = 1;
private static final int MODE_REFRESH = 0;
private static final int MODE_NEXT_PAGE = 1;
private static final int MODE_PRE_PAGE = 2;
private static final int MODE_SOMEWHERE = 3;
private Context mContext;
private GalleryListViewHelper mHelper;
private List<GalleryInfo> mGiList;
private RefreshLayout mRefreshLayout;
private EasyRecyclerView mEasyRecyclerView;
private RefreshTextView mRefreshTextView;
private int mListMode = LIST_MODE_DETAIL;
private GalleryAdapter mAdapter;
private StaggeredGridLayoutManager mLayoutManager;
private MarginItemDecoration mItemDecoration;
private final int[] mFirstPositionTemp = new int[50]; // TODO
private long mTaskStamp;
/**
* First index of current page
*/
private int mFirstIndex;
/**
* Last index of current page
*/
private int mLastIndex;
private int mCurPage;
private int mFirstPage = 0;
private int mLastPage = 0;
/**
* The number of page in sum
*/
private int mPageNum;
private int mItemPerPage;
private int mGetMode;
private OnGetListListener mListener;
/**
* If true, list will make showed item not changed after get
*/
private boolean mIsKeepPosition;
private int mTargetPage;
private String mTargetUrl;
private boolean isFootRefresh = false;
private LayoutInflater mInflater;
private int mListDetailThumbWidth;
private int mListDetailThumbHeight;
private int mOldPaddingBottom;
public GalleryListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public GalleryListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public GalleryListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
mContext = context;
mGiList = new ArrayList<>();
mListener = new OnGetGalleryListListener();
LayoutInflater.from(mContext).inflate(R.layout.gallery_list_view, this);
mRefreshLayout = (RefreshLayout) findViewById(R.id.refresh_layout);
mEasyRecyclerView = (EasyRecyclerView) mRefreshLayout.findViewById(R.id.easy_recycler_view);
mRefreshTextView = (RefreshTextView) findViewById(R.id.refresh_text);
mAdapter = new GalleryAdapter(mContext, mGiList);
mLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mItemDecoration = new MarginItemDecoration();
mEasyRecyclerView.setOnScrollListener(new OnScrollListener());
mEasyRecyclerView.setClipToPadding(false);
mEasyRecyclerView.setAdapter(mAdapter);
mEasyRecyclerView.setLayoutManager(mLayoutManager);
mEasyRecyclerView.addItemDecoration(mItemDecoration);
mEasyRecyclerView.setItemAnimator(new DefaultItemAnimator());
mEasyRecyclerView.setHasFixedSize(true);
setItemMargin(Ui.dp2pix(8)); // TODO for tablet margin should be greater
mRefreshTextView.setDefaultRefresh(R.string.click_retry, new RefreshTextView.OnRefreshListener() {
@Override
public void onRefresh() {
retry();
}
});
mRefreshLayout.setHeaderEnable(true);
mRefreshLayout.setFooterEnable(true);
mRefreshLayout.setHeaderColorSchemeResources(
R.color.refresh_color_1,
R.color.refresh_color_2,
R.color.refresh_color_3,
R.color.refresh_color_4
);
mRefreshLayout.setFooterColorSchemeResources(
R.color.refresh_color_1,
R.color.refresh_color_2,
R.color.refresh_color_3,
R.color.refresh_color_4
);
mRefreshLayout.setOnHeaderRefreshListener(this);
mRefreshLayout.setOnFooterRefreshListener(this);
mOldPaddingBottom = mEasyRecyclerView.getPaddingBottom();
// Caculate gallery detail height
mInflater = LayoutInflater.from(mContext);
View v = mInflater.inflate(R.layout.test_gallery_list_detail_thumb, null);
((TextView) v.findViewById(R.id.title)).setText("haha\nhaha");
((TextView) v.findViewById(R.id.uploader)).setText("haha");
((RatingView) v.findViewById(R.id.rate)).setRating(2.3f);
((TextView) v.findViewById(R.id.category)).setText("haha");
ViewUtils.measureView(v, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mListDetailThumbHeight = Math.max(v.getMeasuredHeight(), Ui.dp2pix(120));
mListDetailThumbWidth = mListDetailThumbHeight * 2 / 3;
}
public int getListMode() {
return mListMode;
}
public void setListMode(int listMode) {
if (mListMode != listMode) {
mListMode = listMode;
// Update span
updateSpanCount();
mAdapter.notifyDataSetChanged();
}
}
private boolean isLandscape() {
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
private static final String[] KEY_SPAN_COUNT_ARRAY = {
"list_detail_columns_portrait", "list_detail_columns_landscape",
"list_thumb_columns_portrait", "list_thumb_columns_landscape"
};
private static final int[] DEFAULT_SPAN_COUNT_ARRAY = {
1, 2, 3, 5
};
public void updateSpanCount() {
int index = mListMode * 2 + (isLandscape() ? 1 : 0);
try {
mLayoutManager.setSpanCount(Config.getInt(KEY_SPAN_COUNT_ARRAY[index],
DEFAULT_SPAN_COUNT_ARRAY[index]));
} catch (Throwable e) {
e.printStackTrace();
}
}
public EasyRecyclerView getEasyRecyclerView() {
return mEasyRecyclerView;
}
public GalleryAdapter getGalleryAdapter() {
return mAdapter;
}
public void setGalleryListViewHelper(GalleryListViewHelper h) {
mHelper = h;
}
public void setPaddingTopAndBottom(int top, int bottom) {
setPadding(getPaddingLeft(), top, getPaddingRight(), getPaddingBottom());
mEasyRecyclerView.setPadding(mEasyRecyclerView.getPaddingLeft(), mEasyRecyclerView.getPaddingTop(),
mEasyRecyclerView.getPaddingRight(), mOldPaddingBottom + bottom);
}
private void setItemMargin(int margin) {
int halfMargin = margin / 2;
mItemDecoration.setMargin(margin);
mEasyRecyclerView.setPadding(halfMargin, halfMargin,
halfMargin, halfMargin);
}
public void setEnabledHeader(boolean enabled) {
mRefreshLayout.setHeaderEnable(enabled);
}
public void setEnabledFooter(boolean enabled) {
mRefreshLayout.setFooterEnable(enabled);
}
public void setHeaderRefreshing(boolean refreshing) {
mRefreshLayout.setHeaderRefreshing(refreshing);
}
public void setOnItemClickListener(EasyRecyclerView.OnItemClickListener l) {
mEasyRecyclerView.setOnItemClickListener(l);
}
public void setOnItemLongClickListener(EasyRecyclerView.OnItemLongClickListener l) {
mEasyRecyclerView.setOnItemLongClickListener(l);
}
public void setChoiceMode(int choiceMode) {
mEasyRecyclerView.setChoiceMode(choiceMode);
}
public void setMultiChoiceModeListener(EasyRecyclerView.MultiChoiceModeListener listener) {
mEasyRecyclerView.setMultiChoiceModeListener(listener);
}
public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
mEasyRecyclerView.addOnItemTouchListener(listener);
}
public void notifyDataSetChanged() {
mAdapter.notifyDataSetChanged();
}
public void setNoneText(CharSequence text) {
mRefreshTextView.setVisibility(View.VISIBLE);
mRefreshTextView.setEmesg(text, false);
}
public void onlyShowList() {
mRefreshLayout.setVisibility(View.VISIBLE);
mRefreshTextView.setRefreshing(false);
mRefreshTextView.setVisibility(View.GONE);
}
public void onlyShowNone() {
mRefreshLayout.setVisibility(View.GONE);
mRefreshTextView.setVisibility(View.VISIBLE);
mRefreshTextView.setEmesg(R.string.none, false);
}
private void getGallerys() {
setGallerysLayout();
mTaskStamp = System.currentTimeMillis();
mHelper.doGetGallerys(mTargetUrl, mTaskStamp, mListener);
}
@Override
public void onHeaderRefresh() {
// It is invokened by user pull, so no need to
if (mFirstPage > 0) {
getPrePage(true);
} else {
refresh();
}
}
@Override
public boolean onFooterRefresh() {
if (!isRefreshing() && mLastPage < mPageNum - 1) {
isFootRefresh = true;
getNextPage(true);
isFootRefresh = false;
return true;
} else {
return false;
}
}
public void firstTimeRefresh() {
// set mPullViewGroup gone, make wait view show
mRefreshLayout.setVisibility(View.GONE);
mRefreshTextView.setVisibility(View.VISIBLE);
mRefreshTextView.setRefreshing(true);
refresh();
}
private void setGallerysLayout() {
if (mRefreshLayout.getVisibility() == View.VISIBLE) {
if (!isFootRefresh)
mRefreshLayout.setHeaderRefreshing(true);
mRefreshTextView.setVisibility(View.GONE);
} else {
mRefreshLayout.setVisibility(View.GONE);
mRefreshTextView.setVisibility(View.VISIBLE);
mRefreshTextView.setRefreshing(true);
}
}
protected boolean retry() {
// Need to update url, because mode may be changed
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
getGallerys();
return true;
}
/**
* Go to page 0.<br>
* You should know you can refresh or not.
*/
public void refresh() {
mGetMode = MODE_REFRESH;
mTargetPage = 0;
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
mIsKeepPosition = false;
getGallerys();
}
/**
* Get previous page.<br>
* You should know you can get previous page or not
*
* @param isKeepPosition
*/
protected void getPrePage(boolean isKeepPosition) {
mGetMode = MODE_PRE_PAGE;
mTargetPage = mFirstPage - 1;
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
mIsKeepPosition = isKeepPosition;
getGallerys();
}
/**
* Get next page.<br>
* You should know you can get next page or not
*
* @param isKeepPosition
*/
protected void getNextPage(boolean isKeepPosition) {
mGetMode = MODE_NEXT_PAGE;
mTargetPage = mLastPage + 1;
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
mIsKeepPosition = isKeepPosition;
getGallerys();
}
/**
* Get some page.<br>
* You should know you can get that page or not
*
* @param page
*/
protected void getSomewhere(int page) {
mGetMode = MODE_SOMEWHERE;
mTargetPage = page;
mTargetUrl = mHelper.getTargetUrl(mTargetPage);
mIsKeepPosition = false;
getGallerys();
}
public void jumpTo(int page) {
if (page >= mFirstPage && page <= mLastPage) {
int position = (page - mFirstPage) * mItemPerPage;
mLayoutManager.scrollToPosition(position);
} else if (page == mFirstPage - 1) {
getPrePage(false);
} else if (page == mLastPage + 1) {
getNextPage(false);
} else {
getSomewhere(page);
}
}
/**
* @return True if actionbar or footer is refreshing
*/
public boolean isRefreshing() {
return mRefreshLayout.isRefreshing();
}
public boolean isGetGalleryOk() {
return mRefreshLayout.getVisibility() == View.VISIBLE;
}
public int getPageNum() {
return mPageNum;
}
public int getCurPage() {
return mCurPage;
}
public List<GalleryInfo> getGalleryList() {
return mGiList;
}
public GalleryInfo getGalleryInfo(int position) {
return mGiList.get(position);
}
public GalleryInfo removeGalleryInfo(int position) {
return mGiList.remove(position);
}
public static interface OnGetListListener {
public void onSuccess(long taskStamp, List<GalleryInfo> gis, int maxPage);
public void onFailure(long taskStamp, String eMsg);
}
private class OnGetGalleryListListener implements OnGetListListener, Runnable {
@Override
public void run() {
int preIndex = mLayoutManager.findFirstVisibleItemPositions(mFirstPositionTemp)[0] - 1;
if (preIndex >= 0)
mEasyRecyclerView.smoothScrollToPosition(preIndex);
}
public void smoothScrollToPrePosition() {
AppHandler.getInstance().post(this);
}
@Override
public void onSuccess(long taskStamp, List<GalleryInfo> gis, int pageNum) {
if (mTaskStamp != taskStamp)
return;
if (pageNum == ListParser.TARGET_PAGE_IS_LAST)
mPageNum = mTargetPage + 1;
else
mPageNum = pageNum;
int itemPerPage = gis == null ? 0 : gis.size();
if (mItemPerPage < itemPerPage)
mItemPerPage = itemPerPage;
if (mPageNum == 0) { // Get none
onlyShowNone();
mFirstPage = 0;
mLastPage = 0;
mGiList.clear();
mAdapter.notifyDataSetChanged();
} else {
onlyShowList();
int start;
switch (mGetMode) {
case MODE_REFRESH:
mFirstPage = 0;
mLastPage = 0;
mGiList.clear();
mGiList.addAll(gis);
mAdapter.notifyDataSetChanged();
// For current page
mFirstIndex = 0;
mLastIndex = gis.size() - 1;
mCurPage = 0;
mLayoutManager.scrollToPosition(0);
break;
case MODE_PRE_PAGE:
mFirstPage--;
mGiList.addAll(0, gis);
mAdapter.notifyItemRangeInserted(0, gis.size());
if (mIsKeepPosition) {
mFirstIndex += gis.size();
mLastIndex += gis.size();
smoothScrollToPrePosition();
} else {
mFirstIndex = 0;
mLastIndex = gis.size()-1;
mCurPage = mTargetPage;
mLayoutManager.scrollToPosition(0);
}
break;
case MODE_NEXT_PAGE:
mLastPage++;
start = mGiList.size();
mGiList.addAll(gis);
mAdapter.notifyItemRangeInserted(start, gis.size());
if (!mIsKeepPosition) {
mFirstIndex = mGiList.size() - gis.size();
mLastIndex = mGiList.size() - 1;
mCurPage = mTargetPage;
mLayoutManager.scrollToPosition(0);
}
break;
case MODE_SOMEWHERE:
mFirstPage = mTargetPage;
mLastPage = mTargetPage;
mGiList.clear();
mGiList.addAll(gis);
mAdapter.notifyDataSetChanged();
// For current page
mFirstIndex = 0;
mLastIndex = gis.size() - 1;
mCurPage = mTargetPage;
mLayoutManager.scrollToPosition(0);
}
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
@Override
public void onFailure(long taskStamp, String eMsg) {
if (mTaskStamp != taskStamp)
return;
switch (mGetMode) {
case MODE_REFRESH:
case MODE_SOMEWHERE:
mRefreshLayout.setVisibility(View.GONE);
mRefreshTextView.setVisibility(View.VISIBLE);
if (eMsg.equals(mContext.getString(R.string.em_index_error))) {
mRefreshTextView.setEmesg(eMsg, mContext.getString(R.string.click_first_page),
new RefreshTextView.OnRefreshListener() {
@Override
public void onRefresh() {
mRefreshTextView.setRefreshing(true);
refresh();
}
});
} else {
mRefreshTextView.setEmesg(eMsg, true);
}
break;
default:
mRefreshTextView.setRefreshing(false);
mRefreshTextView.setVisibility(View.GONE);
MaterialToast.showToast(eMsg);
}
mRefreshLayout.setHeaderRefreshing(false);
mRefreshLayout.setFooterRefreshing(false);
}
}
public static interface GalleryListViewHelper {
/**
* Get url string for very page
*
* @param targetPage
* @return
*/
public String getTargetUrl(int targetPage);
/**
* Do get gallarys here, you shuold invoke the onSuccess or onFailure of
* listener when over
*
* @param url
* @param taskStamp
* @param listener
*/
public void doGetGallerys(String url, long taskStamp, OnGetListListener listener);
}
public class OnScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
/*
switch (newState) {
case RecyclerView.SCROLL_STATE_DRAGGING:
ImageCache.getImageCache(mContext).setPauseDiskCache(true);
break;
case RecyclerView.SCROLL_STATE_IDLE:
ImageCache.getImageCache(mContext).setPauseDiskCache(false);
break;
}
*/
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// mRefreshLayout.onScrolled(recyclerView, dx, dy);
int itemCount = mLayoutManager.getChildCount();
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPositions(mFirstPositionTemp)[0];
// itemCount might include some view can't be seen
// Just check top line child and bottom line child
int visibleItemCount = itemCount;
int height = mEasyRecyclerView.getHeight();
int span = mLayoutManager.getSpanCount();
// Top line
int start = 0;
int end = Math.min(span, itemCount);
for (int i = start; i < end; i++) {
View view = mLayoutManager.getChildAt(i);
if (view.getBottom() <= 0 || view.getTop() > height)
visibleItemCount--;
}
// Bottom line
start = Math.max(itemCount - 1 - span, 0);
end = itemCount;
for (int i = start; i < end; i++) {
View view = mLayoutManager.getChildAt(i);
if (view.getBottom() <= 0 || view.getTop() > height)
visibleItemCount--;
}
if (mItemPerPage == 0)
return;
if (mLastIndex == 0)
mLastIndex = mItemPerPage - 1;
int pageChanged = (firstVisibleItem - mFirstIndex) / mItemPerPage;
if (pageChanged == 0)
pageChanged = (firstVisibleItem + visibleItemCount - mLastIndex - 1) / mItemPerPage;
if (pageChanged != 0) {
mCurPage = mCurPage + pageChanged;
mFirstIndex += pageChanged * mItemPerPage;
mLastIndex += pageChanged * mItemPerPage;
}
}
}
private class GalleryViewHolder extends RecyclerView.ViewHolder {
public int viewType;
public LoadImageView thumb;
public TextView title;
public TextView uploader;
public TextView category;
public RatingView rate;
public TextView posted;
public TextView simpleLanguage;
public GalleryViewHolder(View itemView, int viewType) {
super(itemView);
this.viewType = viewType;
switch (viewType) {
case LIST_MODE_DETAIL:
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
title = (TextView) itemView.findViewById(R.id.title);
category = (TextView) itemView.findViewById(R.id.category);
uploader = (TextView) itemView.findViewById(R.id.uploader);
rate = (RatingView) itemView.findViewById(R.id.rate);
posted = (TextView) itemView.findViewById(R.id.posted);
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
ViewGroup.LayoutParams lp = thumb.getLayoutParams();
lp.width = mListDetailThumbWidth;
lp.height = mListDetailThumbHeight;
break;
case LIST_MODE_THUMB:
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
category = (TextView) itemView.findViewById(R.id.category);
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
}
}
}
public class GalleryAdapter extends RecyclerView.Adapter<GalleryViewHolder> {
private final Context mContext;
private final List<GalleryInfo> mGiList;
private final ImageLoader mImageLoader;
public GalleryAdapter(Context context, List<GalleryInfo> gilist) {
mContext = context;
mGiList = gilist;
mImageLoader = ImageLoader.getInstance(mContext);
}
@Override
public GalleryViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
int resId;
if (viewType == LIST_MODE_DETAIL)
resId = R.layout.gallery_list_detail_item;
else
resId = R.layout.gallery_list_thumb_item;
View view = mInflater.inflate(resId, parent, false);
CardViewSalon.reformWithShadow(view, new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{android.R.attr.state_activated},
new int[]{}},
new int[]{0xff84cae4, 0xff33b5e5, 0xFFFAFAFA}, null, false);
return new GalleryViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(GalleryViewHolder holder,
int position) {
mEasyRecyclerView.checkItemCheckedState(holder.itemView, position);
GalleryInfo gi = mGiList.get(position);
final LoadImageView thumb = holder.thumb;
final String key = String.valueOf(gi.gid);
if (!key.equals(thumb.getKey())) {
// Set new thumb
thumb.setImageDrawable(null);
thumb.setLoadInfo(gi.thumb, key);
Bitmap b = ImageCache.getImageCache(getContext()).getFromMemory(key);
if (b != null) {
thumb.setContextImage(b, true, false);
} else {
mImageLoader.add(gi.thumb, String.valueOf(gi.gid),
new LoadImageView.SimpleImageGetListener(thumb).setFixScaleType(true));
}
}
// Set simple language
TextView simpleLanguage = holder.simpleLanguage;
if (gi.simpleLanguage == null) {
simpleLanguage.setVisibility(View.GONE);
} else {
simpleLanguage.setVisibility(View.VISIBLE);
simpleLanguage.setText(gi.simpleLanguage);
}
// For detail mode
if (holder.viewType == LIST_MODE_DETAIL) {
// Set category
TextView category = holder.category;
String newText = Ui.getCategoryText(gi.category);
if (!newText.equals(category.getText())) {
category.setText(newText);
category.setBackgroundColor(Ui.getCategoryColor(gi.category));
}
// Set manga title
TextView title = holder.title;
title.setText(gi.title);
// Set uploder
TextView uploader = holder.uploader;
uploader.setText(gi.uploader);
// Set star
RatingView rate = holder.rate;
rate.setRating(gi.rating);
// set posted
TextView posted = holder.posted;
posted.setText(gi.posted);
} else {
// Set category
TextView category = holder.category;
String newText = Ui.getCategoryText(gi.category);
if (!newText.equals(category.getText())) {
category.setText(newText);
category.setBackgroundColor(Ui.getCategoryColor(gi.category)
& 0x00ffffff | 0xca000000);
}
}
}
@Override
public int getItemViewType(int position) {
return mListMode;
}
@Override
public int getItemCount() {
return mGiList.size();
}
}
}
@@ -1,299 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewConfiguration;
public class HotspotTouchHelper implements View.OnTouchListener {
private final Hotspotable mOwner;
private boolean mPrePressed = false;
private boolean mHasPerformedLongPress = false;
private CheckForLongPress mPendingCheckForLongPress = null;
private CheckForTap mPendingCheckForTap = null;
private PerformClick mPerformClick = null;
private UnsetPressedState mUnsetPressedState = null;
/**
* Cache the touch slop from the context that created the view.
*/
private int mTouchSlop = -1;
public HotspotTouchHelper(Hotspotable owner){
mOwner = owner;
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onTouch(View v, MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN ||
event.getAction() == MotionEvent.ACTION_MOVE)
mOwner.setHotspot(x, y);
if (!v.isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_UP && v.isPressed()) {
v.setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (v.isClickable() || v.isLongClickable());
}
TouchDelegate touchDelegate = v.getTouchDelegate();
if (touchDelegate != null) {
if (touchDelegate.onTouchEvent(event)) {
return true;
}
}
if (v.isClickable() || v.isLongClickable()) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (v.isPressed() || mPrePressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (v.isFocusable() && v.isFocusableInTouchMode() && !v.isFocused()) {
focusTaken = v.requestFocus();
}
if (mPrePressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(v, true, x, y);
}
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
removeLongPressCallback(v);
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick(v);
}
if (!v.post(mPerformClick)) {
v.performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState(v);
}
if (mPrePressed) {
v.postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!v.post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback(v);
}
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(v, event)) {
break;
}
mPrePressed = true;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap(v);
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
v.postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
break;
case MotionEvent.ACTION_CANCEL:
v.setPressed(false);
removeTapCallback(v);
removeLongPressCallback(v);
break;
case MotionEvent.ACTION_MOVE:
mOwner.setHotspot(x, y);
if (mTouchSlop == -1)
mTouchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
// Be lenient about moving outside of buttons
if (!pointInView(v, x, y, mTouchSlop)) {
// Outside button
removeTapCallback(v);
if (v.isPressed()) {
// Remove any future long press/tap checks
removeLongPressCallback(v);
v.setPressed(false);
}
}
break;
}
return true;
}
return false;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setPressed(View v, boolean pressed, float x, float y){
v.setPressed(pressed);
mOwner.setHotspot(x, y);
}
/**
* Utility method to determine whether the given point, in local coordinates,
* is inside the view, where the area of the view is expanded by the slop factor.
* This method is called while processing touch-move events to determine if the event
* is still within the view.
*/
public boolean pointInView(View v, float localX, float localY, float slop) {
return localX >= -slop && localY >= -slop && localX < ((v.getRight() - v.getLeft()) + slop) &&
localY < ((v.getBottom() - v.getTop()) + slop);
}
/**
* Performs button-related actions during a touch down event.
*
* @param event The event.
* @return True if the down was consumed.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected boolean performButtonActionOnTouchDown(View v, MotionEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
if (v.showContextMenu()) {
return true;
}
}
}
return false;
}
/**
* Remove the longpress detection timer.
*/
private void removeLongPressCallback(View v) {
if (mPendingCheckForLongPress != null) {
v.removeCallbacks(mPendingCheckForLongPress);
}
}
/**
* Remove the tap detection timer.
*/
private void removeTapCallback(View v) {
if (mPendingCheckForTap != null) {
mPrePressed = false;
v.removeCallbacks(mPendingCheckForTap);
}
}
private void checkForLongClick(View v, int delayOffset) {
if (v.isLongClickable()) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress(v);
}
v.postDelayed(mPendingCheckForLongPress,
ViewConfiguration.getLongPressTimeout() - delayOffset);
}
}
private final class CheckForLongPress implements Runnable {
private final View mView;
public CheckForLongPress(View v) {
mView = v;
}
@Override
public void run() {
if (mView.isPressed() && (mView.getParent() != null)) {
if (mView.performLongClick()) {
mHasPerformedLongPress = true;
}
}
}
}
private final class CheckForTap implements Runnable {
public float x;
public float y;
private final View mView;
public CheckForTap(View v) {
mView = v;
}
@Override
public void run() {
mPrePressed = false;
setPressed(mView, true, x, y);
checkForLongClick(mView, ViewConfiguration.getTapTimeout());
}
}
private final class PerformClick implements Runnable {
private final View mView;
public PerformClick(View v) {
mView = v;
}
@Override
public void run() {
mView.performClick();
}
}
private final class UnsetPressedState implements Runnable {
private final View mView;
public UnsetPressedState(View v) {
mView = v;
}
@Override
public void run() {
mView.setPressed(false);
}
}
}
@@ -1,21 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
public interface Hotspotable {
public void setHotspot(float x, float y);
}
@@ -1,75 +0,0 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import java.util.ArrayList;
import java.util.List;
/**
* Utilities for the lock pattern and its settings.
*/
public class LockPatternUtils {
/**
* Deserialize a pattern.
* @param string The pattern serialized with {@link #patternToString}
* @return The pattern.
*/
public static List<LockPatternView.Cell> stringToPattern(String string) {
List<LockPatternView.Cell> result = new ArrayList<>();
final byte[] bytes = string.getBytes();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
result.add(LockPatternView.Cell.of(b / 3, b % 3));
}
return result;
}
/**
* Serialize a pattern.
* @param pattern The pattern.
* @return The pattern in string form.
*/
public static String patternToString(List<LockPatternView.Cell> pattern) {
if (pattern == null) {
return "";
}
final int patternSize = pattern.size();
byte[] res = new byte[patternSize];
for (int i = 0; i < patternSize; i++) {
LockPatternView.Cell cell = pattern.get(i);
res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
}
return new String(res);
}
public static boolean isPatternVaild(String pattern) {
byte[] bytes = pattern.getBytes();
if (bytes.length <= 9 && bytes.length >= 2) {
for (byte b : bytes) {
if (b >= 9 || b < 0) {
return false;
}
}
return true;
} else {
return false;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,64 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import com.hippo.ehviewer.AppContext;
public class RatingView extends TextView {
private static final char START_EMPTY = '\uFA73';
private static final char START_HALF = '\uFA74';
private static final char START_FULL = '\uFA75';
private int mRating = -1;
public RatingView(Context context) {
super(context);
init(context);
}
public RatingView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RatingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setTypeface(((AppContext)context.getApplicationContext()).getFaceTypeface());
}
public void setRating(float rating) {
mRating = Math.min(10, Math.round(rating * 2));
int fullNum = mRating / 2;
int halfNum = mRating % 2;
int emptyNum = 5 - fullNum - halfNum;
StringBuilder sb = new StringBuilder(5);
for (int i = 0; i < fullNum; i++)
sb.append(START_FULL);
if (halfNum == 1)
sb.append(START_HALF);
for (int i = 0; i < emptyNum; i++)
sb.append(START_EMPTY);
setText(sb.toString());
}
}
@@ -1,64 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
public class SearchView extends android.widget.SearchView {
private static final String TAG = SearchView.class.getSimpleName();
private OnActionViewExpandedListener mListener;
public SearchView(Context context) {
super(context);
}
public SearchView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SearchView(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void onActionViewExpanded() {
super.onActionViewExpanded();
if (mListener != null)
mListener.onActionViewExpanded();
}
public void setOnActionViewExpandedListener(OnActionViewExpandedListener l) {
mListener = l;
}
public interface OnActionViewExpandedListener {
public void onActionViewExpanded();
}
}
@@ -1,137 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
public class SimpleImageView extends View implements Drawable.Callback {
private Drawable mDrawable;
private boolean mKeepAspect = true;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.src
};
public SimpleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public SimpleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setDrawable(a.getDrawable(0));
a.recycle();
// Mostly drawable is VectorDrawable, it has cache already
setWillNotCacheDrawing(true);
}
@SuppressWarnings("deprecation")
public void setDrawable(@DrawableRes int resId) {
setDrawable(getContext().getResources().getDrawable(resId));
}
public void setDrawable(Drawable drawable) {
if (mDrawable != null) {
mDrawable.setCallback(null);
}
mDrawable = drawable;
if (mDrawable != null) {
mDrawable.setCallback(this);
}
requestLayout();
}
@Override
public void invalidateDrawable(@NonNull Drawable who) {
invalidate();
}
@Override
protected int getSuggestedMinimumWidth() {
int superMinWidth = super.getSuggestedMinimumWidth();
return (mDrawable == null) ? superMinWidth :
Math.max(superMinWidth, mDrawable.getMinimumWidth() + getPaddingLeft() + getPaddingRight());
}
@Override
protected int getSuggestedMinimumHeight() {
int superMinHeight = super.getSuggestedMinimumHeight();
return (mDrawable == null) ? superMinHeight :
Math.max(superMinHeight, mDrawable.getMinimumHeight() + getPaddingTop() + getPaddingBottom());
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mDrawable != null) {
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int canvasWidth = right - left - paddingLeft - paddingRight;
int canvasHeight = bottom - top - paddingTop - paddingBottom;
int intrinsicWidth = mDrawable.getIntrinsicWidth();
int intrinsicHeight = mDrawable.getIntrinsicHeight();
if (mKeepAspect && intrinsicWidth > 0 && intrinsicHeight > 0) {
int drawWidth;
int drawHeight;
float canvasAspect = canvasWidth / canvasHeight;
float drawableAspect = intrinsicWidth / intrinsicHeight;
if (drawableAspect > canvasAspect) {
drawWidth = (int) (canvasHeight * drawableAspect);
drawHeight = canvasHeight;
} else {
drawWidth = canvasWidth;
drawHeight = (int) (canvasWidth / drawableAspect);
}
int drawLeft = paddingLeft + ((canvasWidth - drawWidth) / 2);
int drawTop = paddingTop + ((canvasHeight - drawHeight) / 2);
mDrawable.setBounds(drawLeft, drawTop,
drawLeft + drawWidth, drawTop + drawHeight);
} else {
mDrawable.setBounds(paddingLeft, paddingTop,
paddingLeft + canvasWidth, paddingTop + canvasHeight);
}
}
}
@Override
protected void onDraw(Canvas canvas) {
if (mDrawable != null) {
mDrawable.draw(canvas);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,598 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.CycleInterpolator;
import com.hippo.ehviewer.util.AnimatorUtils;
import com.hippo.ehviewer.util.MathUtils;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.util.ZInterpolator;
public class SlidingLayout extends ViewGroup {
private static final String TAG = SlidingLayout.class.getSimpleName();
/*
* There are three level, first is base level, second is reserved level, third is full screen level.
*/
private static final int LEVEL_BASE = 0;
private static final int LEVEL_RESERVED = 1;
private static final int LEVEL_FULL_SCREEN = 2;
private int mLevel = LEVEL_BASE;
private View mChild;
private int mMaxWidth;
private int mSlop;
private float mShowPercent = 0.0f;
private boolean isBottom = true;
private int mPaddingLeft;
private int mPaddingTop;
private int mPaddingRight;
private int mPaddingBottom;
private ValueAnimator mToBaseLevelAnimate;
private ValueAnimator mToReservedLevelAnimate;
private ValueAnimator mToFullScreenLevelAnimate;
private SetYListener mToBaseLevelListener;
private SetYListener mToReservedLevelListener;
private SetYListener mToFullScreenLevelListener;
private float mInitialMotionX;
private float mInitialMotionY;
private float mLastMotionY;
private int mMinTop;
private int mMaxTop;
/*
* ---------------------- mFullScreenTop
*
* ---------------------- m5Top
*
*
* ---------------------- m4Top
*
* ---------------------- mReservedTop
*
* ---------------------- m2Top
*
*
* ---------------------- m1Top
*
* ---------------------- mBaseTop
*/
private int mBaseTop;
private int m1Top;
private int m2Top;
private int mReservedTop;
private int m4Top;
private int m5Top;
private int mFullScreenTop;
private boolean mInHideAnimate = false;
private OnChildHideListener mOnChildHideListener;
private static final ZInterpolator ZINTERPOLATOR = new ZInterpolator();
public interface OnChildHideListener {
public void onChildHide();
}
public SlidingLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SlidingLayout(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SlidingLayout(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
mMaxWidth = Ui.dp2pix(480);
mSlop = Ui.dp2pix(0);
mToBaseLevelAnimate = new ValueAnimator();
mToBaseLevelListener = new SetYListener();
mToBaseLevelAnimate.addUpdateListener(mToBaseLevelListener);
mToBaseLevelAnimate.setDuration(300);
mToBaseLevelAnimate.setInterpolator(ZINTERPOLATOR);
mToBaseLevelAnimate.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
mInHideAnimate = true;
}
@Override
public void onAnimationEnd(Animator animation) {
mLevel = LEVEL_BASE;
if (mChild.getVisibility() != View.INVISIBLE)
mChild.setVisibility(View.INVISIBLE);
if (mOnChildHideListener != null)
mOnChildHideListener.onChildHide();
mInHideAnimate = false;
}
@Override
public void onAnimationCancel(Animator animation) {
mInHideAnimate = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
// Empty
}
});
mToReservedLevelAnimate = new ValueAnimator();
mToReservedLevelListener = new SetYListener();
mToReservedLevelAnimate.addUpdateListener(mToReservedLevelListener);
mToReservedLevelAnimate.setDuration(300);
mToReservedLevelAnimate.setInterpolator(ZINTERPOLATOR);
mToReservedLevelAnimate.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// Empty
}
@Override
public void onAnimationEnd(Animator animation) {
mLevel = LEVEL_RESERVED;
}
@Override
public void onAnimationCancel(Animator animation) {
// Empty
}
@Override
public void onAnimationRepeat(Animator animation) {
// Empty
}
});
mToFullScreenLevelAnimate = new ValueAnimator();
mToFullScreenLevelListener = new SetYListener();
mToFullScreenLevelAnimate.addUpdateListener(mToFullScreenLevelListener);
mToFullScreenLevelAnimate.setDuration(300);
mToFullScreenLevelAnimate.setInterpolator(ZINTERPOLATOR);
mToFullScreenLevelAnimate.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// Empty
}
@Override
public void onAnimationEnd(Animator animation) {
mLevel = LEVEL_FULL_SCREEN;
}
@Override
public void onAnimationCancel(Animator animation) {
// Empty
}
@Override
public void onAnimationRepeat(Animator animation) {
// Empty
}
});
}
private class SetYListener implements ValueAnimator.AnimatorUpdateListener {
private boolean mFirstShow = false;
private int mStartTop;
public void reset() {
mFirstShow = true;
mStartTop = mChild.getTop();
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int offsetY = (int) (float) (Float) animation.getAnimatedValue() - mChild.getTop();
mChild.offsetTopAndBottom(offsetY);
updateShowPercent();
if (mFirstShow && Math.abs(mStartTop - mChild.getTop()) > 5) {
mFirstShow = false;
invalidate();
}
}
}
public void setOnChildHideListener(OnChildHideListener l) {
mOnChildHideListener = l;
}
@Override
protected void onFinishInflate() {
final int childCount = getChildCount();
if (childCount != 1)
throw new IllegalStateException("There must be only one child");
mChild = getChildAt(0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY)
throw new IllegalArgumentException(
"SlidingDrawerLayout must be measured with MeasureSpec.EXACTLY.");
setMeasuredDimension(widthSize, heightSize);
final View child = mChild;
if (child.getVisibility() != GONE) {
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
Math.min(widthSize - getPaddingLeft() - getPaddingRight(), mMaxWidth), MeasureSpec.EXACTLY);
final int childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
child.measure(childWidthSpec, childHeightSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final View child = mChild;
final int width = r - l;
final int height = b - t;
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
mPaddingLeft = getPaddingLeft();
mPaddingTop = getPaddingTop();
mPaddingRight = getPaddingRight();
mPaddingBottom = getPaddingBottom();
// Set mReservedLength and mFullScreenLength
int heightWithoutPadding = height - mPaddingTop - mPaddingBottom;
int defaultReservedLength = Math.min(heightWithoutPadding - Ui.dp2pix(48), Ui.dp2pix(248));
int defaultFullScreenLength = Math.max(heightWithoutPadding, defaultReservedLength);
int reservedLength = Math.min(defaultReservedLength, childHeight);
int fullScreenLength = Math.min(defaultFullScreenLength, childHeight);
int showHeight = MathUtils.lerp(0, childHeight, mShowPercent);
int childLeft = mPaddingLeft + (width - mPaddingLeft - mPaddingRight - childWidth) / 2;
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
final int maxGap = Ui.dp2pix(32);
final int brGap = Math.min(Math.abs((mBaseTop - mReservedTop) / 3), maxGap);
final int rfGap = Math.min(Math.abs((mReservedTop - mFullScreenTop) / 3), maxGap);
switch (vgrav) {
case Gravity.TOP: {
isBottom = false;
mMinTop = mPaddingTop;
mMaxTop = mMinTop + childHeight;
mBaseTop = mMinTop;
mReservedTop = mMinTop + reservedLength;
mFullScreenTop = mMinTop + fullScreenLength;
m1Top = mBaseTop + brGap;
m2Top = mReservedTop - brGap;
m4Top = mReservedTop + rfGap;
m5Top = mFullScreenTop - rfGap;
int childBottom = mMinTop + showHeight;
child.layout(childLeft, childBottom - childHeight, childLeft + childWidth, childBottom);
break;
}
default:
case Gravity.BOTTOM: {
isBottom = true;
mMaxTop = height - mPaddingBottom;
mMinTop = mMaxTop - childHeight;
mBaseTop = mMaxTop;
mReservedTop = mMaxTop - reservedLength;
mFullScreenTop = mMaxTop - fullScreenLength;
m1Top = mBaseTop - brGap;
m2Top = mReservedTop + brGap;
m4Top = mReservedTop - rfGap;
m5Top = mFullScreenTop + rfGap;
int childTop = mMaxTop - showHeight;
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
break;
}
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean getTouchEvent = false;
final int action = MotionEventCompat.getActionMasked(ev);
final float x = ev.getX();
final float y = ev.getY();
final boolean isChildUnder = ViewUtils.isViewUnder(mChild, (int) x, (int) y);
switch (action) {
case MotionEvent.ACTION_DOWN:
mInitialMotionX = x;
mInitialMotionY = y;
mLastMotionY = mInitialMotionY;
break;
case MotionEvent.ACTION_MOVE:
final float adx = Math.abs(x - mInitialMotionX);
final float ady = Math.abs(y - mInitialMotionY);
if (isChildUnder && adx > mSlop && ady > adx)
getTouchEvent = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return getTouchEvent;
}
private void updateShowPercent() {
int top = mChild.getTop();
mShowPercent = (isBottom ? (mMaxTop - top) : (top - mMinTop)) /
(float) mChild.getHeight();
}
private void cancelAnimator() {
if (mToBaseLevelAnimate.isRunning())
mToBaseLevelAnimate.cancel();
if (mToReservedLevelAnimate.isRunning())
mToReservedLevelAnimate.cancel();
if (mToFullScreenLevelAnimate.isRunning())
mToFullScreenLevelAnimate.cancel();
}
@Override
@SuppressLint("ClickableViewAccessibility")
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
final float x = ev.getX();
final float y = ev.getY();
boolean getTouchEvent = false;
cancelAnimator();
int top;
switch (action) {
case MotionEvent.ACTION_DOWN:
mInitialMotionX = x;
mInitialMotionY = y;
mLastMotionY = mInitialMotionY;
if (isShowing())
getTouchEvent = true;
break;
case MotionEvent.ACTION_MOVE:
final float dy = y - mLastMotionY;
mLastMotionY = y;
getTouchEvent = true;
top = mChild.getTop();
int newTop = top + (int) dy;
newTop = MathUtils.clamp(newTop, mMinTop, mMaxTop);
mChild.offsetTopAndBottom(newTop - top);
updateShowPercent();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getTouchEvent = true;
top = mChild.getTop();
if (isBottom) {
switch (mLevel) {
default:
case LEVEL_BASE:
if (top < mFullScreenTop)
;
else if (top < m4Top)
toFullScreenLevel();
else if (top < m1Top)
toReservedLevel(false);
else
toBaseLevel();
break;
case LEVEL_RESERVED:
if (top < mFullScreenTop)
;
else if (top < m4Top)
toFullScreenLevel();
else if (top < m2Top)
toReservedLevel(false);
else
toBaseLevel();
break;
case LEVEL_FULL_SCREEN:
if (top < mFullScreenTop)
;
else if (top < m5Top)
toFullScreenLevel();
else if (top < m2Top)
toReservedLevel(false);
else
toBaseLevel();
break;
}
} else {
// TODO
}
break;
}
return getTouchEvent;
}
public void hide() {
if (mChild.getVisibility() != View.INVISIBLE)
mChild.setVisibility(View.INVISIBLE);
}
public boolean isShowing() {
return mChild.getVisibility() == View.VISIBLE;
}
public boolean isInHideAnimate() {
return mInHideAnimate;
}
public void toReservedLevel(boolean withShake) {
cancelAnimator();
// Show child
if (mChild.getVisibility() != View.VISIBLE)
mChild.setVisibility(View.VISIBLE);
mToReservedLevelListener.reset();
mToReservedLevelAnimate.setFloatValues(mChild.getTop(), mReservedTop);
if (withShake) {
AnimatorSet bouncer = new AnimatorSet();
Animator delayAnimator = AnimatorUtils.createDelayAnimator(200);
ValueAnimator shakeAnimator = ValueAnimator.ofFloat(mReservedTop,
isBottom ? mReservedTop - Ui.dp2pix(8) : mReservedTop + Ui.dp2pix(8));
shakeAnimator.setDuration(500);
shakeAnimator.setInterpolator(new CycleInterpolator(1));
shakeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int offsetY = (int) (float) (Float) animation.getAnimatedValue() - mChild.getTop();
mChild.offsetTopAndBottom(offsetY);
updateShowPercent();
}
});
bouncer.play(mToReservedLevelAnimate).before(delayAnimator);
bouncer.play(delayAnimator).before(shakeAnimator);
bouncer.start();
} else {
mToReservedLevelAnimate.start();
}
}
public void toBaseLevel() {
cancelAnimator();
// Show child
if (mChild.getVisibility() != View.VISIBLE)
mChild.setVisibility(View.VISIBLE);
mToBaseLevelListener.reset();
mToBaseLevelAnimate.setFloatValues(mChild.getTop(), mBaseTop);
mToBaseLevelAnimate.start();
}
public void toFullScreenLevel() {
cancelAnimator();
// Show child
if (mChild.getVisibility() != View.VISIBLE)
mChild.setVisibility(View.VISIBLE);
mToFullScreenLevelListener.reset();
mToFullScreenLevelAnimate.setFloatValues(mChild.getTop(), mFullScreenTop);
mToFullScreenLevelAnimate.start();
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams
? new LayoutParams((LayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
public static class LayoutParams extends ViewGroup.LayoutParams {
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.layout_gravity
};
public int gravity = Gravity.BOTTOM;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
this.gravity = a.getInt(0, Gravity.BOTTOM);
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, int gravity) {
this(width, height);
this.gravity = gravity;
}
public LayoutParams(LayoutParams source) {
super(source);
gravity = source.gravity;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
}
@@ -1,90 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.SearchRecentSuggestions;
public class SuggestionHelper extends SearchRecentSuggestions {
private static final String QUERY = "query";
private static final String ORDER_BY = "date DESC";
private static final int MAX_HISTORY_COUNT = 250;
private final List<String> mQueryList = new ArrayList<String>();
private static Map<String, SuggestionHelper> sInstances = new HashMap<String, SuggestionHelper>();
public static SuggestionHelper getInstance(Context context, String authority, int mode) {
SuggestionHelper s = sInstances.get(authority);
if (s == null) {
s = new SuggestionHelper(context, authority, mode);
sInstances.put(authority, s);
}
return s;
}
private SuggestionHelper(Context context, String authority, int mode) {
super(context, authority, mode);
Uri suggestionsUri = Uri.parse("content://" + authority + "/suggestions");
// Get all suggestion
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(suggestionsUri, new String[]{QUERY}, null, null, ORDER_BY);
while(cursor.moveToNext())
mQueryList.add(cursor.getString(cursor.getColumnIndex(QUERY)));
cursor.close();
}
public List<String> getQueries() {
return mQueryList;
}
@Override
public void saveRecentQuery(final String queryString, final String line2) {
super.saveRecentQuery(queryString, line2);
if (!mQueryList.contains(queryString))
mQueryList.add(0, queryString);
truncateHistory(MAX_HISTORY_COUNT);
}
@Override
public void clearHistory() {
super.clearHistory();
truncateHistory(0);
}
private void truncateHistory(int maxEntries) {
if (maxEntries == 0) {
mQueryList.clear();
} else {
for (int i = mQueryList.size() - 1; i >= maxEntries; i--) {
mQueryList.remove(i);
}
}
}
}
@@ -1,124 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.hippo.ehviewer.util.ViewUtils;
public class SuggestionTextView extends PrefixEditText {
private static final String TAG = SuggestionTextView.class.getSimpleName();
private List<String> mAllSuggestions;
private ArrayAdapter<String> mAdapte;
private boolean mKeyboardIsShowing = true;
public SuggestionTextView(Context context) {
super(context);
}
public SuggestionTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SuggestionTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* We override this method to avoid an extra onItemClick being called on
* the drop-down's OnItemClickListener by
* {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
* clicked with the trackball.
*/
@Override
public void performCompletion() {
}
/**
* We override this method so that we can allow a threshold of zero,
* which ACTV does not.
*/
@Override
public boolean enoughToFilter() {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isPopupShowing())
showDropDown();
return super.onTouchEvent(event);
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// special case for the back key, we do not even try to send it
// to the drop down list but instead, consume it immediately
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.startTracking(event, this);
}
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.handleUpEvent(event);
}
if (event.isTracking() && !event.isCanceled()) {
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && mKeyboardIsShowing) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
mKeyboardIsShowing = false;
} else {
clearFocus();
mKeyboardIsShowing = true;
}
return true;
}
}
}
return super.onKeyPreIme(keyCode, event);
}
public void setSuggestionHelper(SuggestionHelper helper) {
if (helper != null) {
mAllSuggestions = helper.getQueries();
mAdapte = new ArrayAdapter<String>(ViewUtils.sContextThemeWrapper,
android.R.layout.simple_dropdown_item_1line, mAllSuggestions);
setAdapter(mAdapte);
} else {
mAllSuggestions = null;
mAdapte = null;
setAdapter(null);
}
}
}
@@ -1,337 +0,0 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
/**
* Custom progress bar that shows a cycle of colors as widening circles that
* overdraw each other. When finished, the bar is cleared from the inside out as
* the main cycle continues. Before running, this can also indicate how close
* the user is to triggering something (e.g. how far they need to pull down to
* trigger a refresh).
*/
final class SwipeProgressBar {
// Default progress animation colors are grays.
private final static int COLOR1 = 0xB3000000;
private final static int COLOR2 = 0x80000000;
private final static int COLOR3 = 0x4d000000;
private final static int COLOR4 = 0x1a000000;
// The duration of the animation cycle.
private static final int ANIMATION_DURATION_MS = 2000;
// The duration of the animation to clear the bar.
private static final int FINISH_ANIMATION_DURATION_MS = 1000;
// Interpolator for varying the speed of the animation.
private static final Interpolator INTERPOLATOR = BakedBezierInterpolator.getInstance();
private final Paint mPaint = new Paint();
private final RectF mClipRect = new RectF();
private float mTriggerPercentage;
private long mStartTime;
private long mFinishTime;
private boolean mRunning;
// Colors used when rendering the animation,
private int mColor1;
private int mColor2;
private int mColor3;
private int mColor4;
private final View mParent;
private final Rect mBounds = new Rect();
public SwipeProgressBar(View parent) {
mParent = parent;
mColor1 = COLOR1;
mColor2 = COLOR2;
mColor3 = COLOR3;
mColor4 = COLOR4;
}
/**
* Set the four colors used in the progress animation. The first color will
* also be the color of the bar that grows in response to a user swipe
* gesture.
*
* @param color1 Integer representation of a color.
* @param color2 Integer representation of a color.
* @param color3 Integer representation of a color.
* @param color4 Integer representation of a color.
*/
void setColorScheme(int color1, int color2, int color3, int color4) {
mColor1 = color1;
mColor2 = color2;
mColor3 = color3;
mColor4 = color4;
}
/**
* Update the progress the user has made toward triggering the swipe
* gesture. and use this value to update the percentage of the trigger that
* is shown.
*/
void setTriggerPercentage(float triggerPercentage) {
mTriggerPercentage = triggerPercentage;
mStartTime = 0;
ViewCompat.postInvalidateOnAnimation(mParent);
}
/**
* Start showing the progress animation.
*/
void start() {
if (!mRunning) {
mTriggerPercentage = 0;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = true;
mParent.postInvalidate();
}
}
/**
* Stop showing the progress animation.
*/
void stop() {
if (mRunning) {
mTriggerPercentage = 0;
mFinishTime = AnimationUtils.currentAnimationTimeMillis();
mRunning = false;
mParent.postInvalidate();
}
}
/**
* @return Return whether the progress animation is currently running.
*/
boolean isRunning() {
return mRunning || mFinishTime > 0;
}
void draw(Canvas canvas) {
final int width = mBounds.width();
final int height = mBounds.height();
final int cx = width / 2;
final int cy = mBounds.top + height / 2;
boolean drawTriggerWhileFinishing = false;
int restoreCount = canvas.save();
canvas.clipRect(mBounds);
if (mRunning || (mFinishTime > 0)) {
long now = AnimationUtils.currentAnimationTimeMillis();
long elapsed = (now - mStartTime) % ANIMATION_DURATION_MS;
long iterations = (now - mStartTime) / ANIMATION_DURATION_MS;
float rawProgress = (elapsed / (ANIMATION_DURATION_MS / 100f));
// If we're not running anymore, that means we're running through
// the finish animation.
if (!mRunning) {
// If the finish animation is done, don't draw anything, and
// don't repost.
if ((now - mFinishTime) >= FINISH_ANIMATION_DURATION_MS) {
mFinishTime = 0;
return;
}
// Otherwise, use a 0 opacity alpha layer to clear the animation
// from the inside out. This layer will prevent the circles from
// drawing within its bounds.
long finishElapsed = (now - mFinishTime) % FINISH_ANIMATION_DURATION_MS;
float finishProgress = (finishElapsed / (FINISH_ANIMATION_DURATION_MS / 100f));
float pct = (finishProgress / 100f);
// Radius of the circle is half of the screen.
float clearRadius = width / 2 * INTERPOLATOR.getInterpolation(pct);
mClipRect.set(cx - clearRadius, 0, cx + clearRadius, height);
canvas.saveLayerAlpha(mClipRect, 0, 0);
// Only draw the trigger if there is a space in the center of
// this refreshing view that needs to be filled in by the
// trigger. If the progress view is just still animating, let it
// continue animating.
drawTriggerWhileFinishing = true;
}
// First fill in with the last color that would have finished drawing.
if (iterations == 0) {
canvas.drawColor(mColor1);
} else {
if (rawProgress >= 0 && rawProgress < 25) {
canvas.drawColor(mColor4);
} else if (rawProgress >= 25 && rawProgress < 50) {
canvas.drawColor(mColor1);
} else if (rawProgress >= 50 && rawProgress < 75) {
canvas.drawColor(mColor2);
} else {
canvas.drawColor(mColor3);
}
}
// Then draw up to 4 overlapping concentric circles of varying radii, based on how far
// along we are in the cycle.
// progress 0-50 draw mColor2
// progress 25-75 draw mColor3
// progress 50-100 draw mColor4
// progress 75 (wrap to 25) draw mColor1
if ((rawProgress >= 0 && rawProgress <= 25)) {
float pct = (((rawProgress + 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (rawProgress >= 0 && rawProgress <= 50) {
float pct = ((rawProgress * 2) / 100f);
drawCircle(canvas, cx, cy, mColor2, pct);
}
if (rawProgress >= 25 && rawProgress <= 75) {
float pct = (((rawProgress - 25) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor3, pct);
}
if (rawProgress >= 50 && rawProgress <= 100) {
float pct = (((rawProgress - 50) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor4, pct);
}
if ((rawProgress >= 75 && rawProgress <= 100)) {
float pct = (((rawProgress - 75) * 2) / 100f);
drawCircle(canvas, cx, cy, mColor1, pct);
}
if (mTriggerPercentage > 0 && drawTriggerWhileFinishing) {
// There is some portion of trigger to draw. Restore the canvas,
// then draw the trigger. Otherwise, the trigger does not appear
// until after the bar has finished animating and appears to
// just jump in at a larger width than expected.
canvas.restoreToCount(restoreCount);
restoreCount = canvas.save();
canvas.clipRect(mBounds);
drawTrigger(canvas, cx, cy);
}
// Keep running until we finish out the last cycle.
ViewCompat.postInvalidateOnAnimation(mParent);
} else {
// Otherwise if we're in the middle of a trigger, draw that.
if (mTriggerPercentage > 0 && mTriggerPercentage <= 1.0) {
drawTrigger(canvas, cx, cy);
}
}
canvas.restoreToCount(restoreCount);
}
private void drawTrigger(Canvas canvas, int cx, int cy) {
mPaint.setColor(mColor1);
canvas.drawCircle(cx, cy, cx * mTriggerPercentage, mPaint);
}
/**
* Draws a circle centered in the view.
*
* @param canvas the canvas to draw on
* @param cx the center x coordinate
* @param cy the center y coordinate
* @param color the color to draw
* @param pct the percentage of the view that the circle should cover
*/
private void drawCircle(Canvas canvas, float cx, float cy, int color, float pct) {
mPaint.setColor(color);
canvas.save();
canvas.translate(cx, cy);
float radiusScale = INTERPOLATOR.getInterpolation(pct);
canvas.scale(radiusScale, radiusScale);
canvas.drawCircle(0, 0, cx, mPaint);
canvas.restore();
}
/**
* Set the drawing bounds of this SwipeProgressBar.
*/
void setBounds(int left, int top, int right, int bottom) {
mBounds.left = left;
mBounds.top = top;
mBounds.right = right;
mBounds.bottom = bottom;
}
/**
* A pre-baked bezier-curved interpolator for indeterminate progress animations.
*/
final static class BakedBezierInterpolator implements Interpolator {
private static final BakedBezierInterpolator INSTANCE = new BakedBezierInterpolator();
public final static BakedBezierInterpolator getInstance() {
return INSTANCE;
}
/**
* Use getInstance instead of instantiating.
*/
private BakedBezierInterpolator() {
super();
}
/**
* Lookup table values.
* Generated using a Bezier curve from (0,0) to (1,1) with control points:
* P0 (0,0)
* P1 (0.4, 0)
* P2 (0.2, 1.0)
* P3 (1.0, 1.0)
*
* Values sampled with x at regular intervals between 0 and 1.
*/
private static final float[] VALUES = new float[] {
0.0f, 0.0002f, 0.0009f, 0.0019f, 0.0036f, 0.0059f, 0.0086f, 0.0119f, 0.0157f, 0.0209f,
0.0257f, 0.0321f, 0.0392f, 0.0469f, 0.0566f, 0.0656f, 0.0768f, 0.0887f, 0.1033f, 0.1186f,
0.1349f, 0.1519f, 0.1696f, 0.1928f, 0.2121f, 0.237f, 0.2627f, 0.2892f, 0.3109f, 0.3386f,
0.3667f, 0.3952f, 0.4241f, 0.4474f, 0.4766f, 0.5f, 0.5234f, 0.5468f, 0.5701f, 0.5933f,
0.6134f, 0.6333f, 0.6531f, 0.6698f, 0.6891f, 0.7054f, 0.7214f, 0.7346f, 0.7502f, 0.763f,
0.7756f, 0.7879f, 0.8f, 0.8107f, 0.8212f, 0.8326f, 0.8415f, 0.8503f, 0.8588f, 0.8672f,
0.8754f, 0.8833f, 0.8911f, 0.8977f, 0.9041f, 0.9113f, 0.9165f, 0.9232f, 0.9281f, 0.9328f,
0.9382f, 0.9434f, 0.9476f, 0.9518f, 0.9557f, 0.9596f, 0.9632f, 0.9662f, 0.9695f, 0.9722f,
0.9753f, 0.9777f, 0.9805f, 0.9826f, 0.9847f, 0.9866f, 0.9884f, 0.9901f, 0.9917f, 0.9931f,
0.9944f, 0.9955f, 0.9964f, 0.9973f, 0.9981f, 0.9986f, 0.9992f, 0.9995f, 0.9998f, 1.0f, 1.0f
};
private static final float STEP_SIZE = 1.0f / (VALUES.length - 1);
@Override
public float getInterpolation(float input) {
if (input >= 1.0f) {
return 1.0f;
}
if (input <= 0f) {
return 0f;
}
int position = Math.min(
(int)(input * (VALUES.length - 1)),
VALUES.length - 2);
float quantized = position * STEP_SIZE;
float difference = input - quantized;
float weight = difference / STEP_SIZE;
return VALUES[position] + weight * (VALUES[position + 1] - VALUES[position]);
}
}
}
@@ -1,87 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.hippo.ehviewer.effect.DrawableTransition;
public class TransitionLayout extends LinearLayout {
private Bitmap mBmp;
private int mOldWidth;
private int mOldHeight;
private static final String TAG = TransitionLayout.class.getSimpleName();
public TransitionLayout(Context context) {
super(context);
}
public TransitionLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TransitionLayout(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TransitionLayout(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int width = getWidth();
int height = getHeight();
if (mOldWidth != width || mOldHeight != height || mBmp == null) {
mOldWidth = width;
mOldHeight = height;
if (mBmp != null && !mBmp.isRecycled())
mBmp.recycle();
mBmp = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(mBmp);
c.translate(-getScrollX(), -getScrollY());
super.dispatchDraw(c);
BitmapDrawable b = new BitmapDrawable(getResources(), mBmp);
DrawableTransition.transit(b, false, 3000);
setBackgroundDrawable(b);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
setBackgroundDrawable(null);
if (mBmp != null && !mBmp.isRecycled())
mBmp.recycle();
}
}
@@ -1,992 +0,0 @@
/*
* Copyright (C) 2014-2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.recyclerview;
import android.content.Context;
import android.os.Build;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Checkable;
import com.hippo.ehviewer.util.MathUtils;
import com.hippo.ehviewer.util.ViewUtils;
/**
* Add setOnItemClickListener, setOnItemLongClickListener and setChoiceMode for
* RecyclerView
*/
// Get some code from twoway-view and AbsListView.
public class EasyRecyclerView extends RecyclerView {
private static final String STATE_KEY_CHOICE_MODE = "choiceMode";
private static final String STATE_KEY_CHECKED_STATES = "checkedStates";
private static final String STATE_KEY_CHECKED_ID_STATES = "checkedIdStates";
private static final String STATE_KEY_CHECKED_COUNT = "checkedCount";
/**
* Represents an invalid position. All valid positions are in the range 0 to 1 less than the
* number of items in the current adapter.
*/
public static final int INVALID_POSITION = -1;
/**
* Normal list that does not indicate choices
*/
public static final int CHOICE_MODE_NONE = 0;
/**
* The list allows up to one choice
*/
public static final int CHOICE_MODE_SINGLE = 1;
/**
* The list allows multiple choices
*/
public static final int CHOICE_MODE_MULTIPLE = 2;
/**
* The list allows multiple choices in a modal selection mode
*/
public static final int CHOICE_MODE_MULTIPLE_MODAL = 3;
/**
* Controls if/how the user may choose/check items in the list
*/
private int mChoiceMode = CHOICE_MODE_NONE;
/**
* Controls CHOICE_MODE_MULTIPLE_MODAL. null when inactive.
*/
private ActionMode mChoiceActionMode;
/**
* Wrapper for the multiple choice mode callback; AbsListView needs to perform
* a few extra actions around what application code does.
*/
MultiChoiceModeWrapper mMultiChoiceModeCallback;
/**
* Running count of how many items are currently checked
*/
private int mCheckedItemCount;
/**
* Running state of which positions are currently checked
*/
private SparseBooleanArray mCheckStates;
/**
* Running state of which IDs are currently checked.
* If there is a value for a given key, the checked state for that ID is true
* and the value holds the last known position in the adapter for that id.
*/
private LongSparseArray<Integer> mCheckedIdStates;
private Adapter mAdapter;
private float mVerticalScrollFactor = 0;
// For click and long click
private boolean mPrePressed = false;
private boolean mHasPerformedLongPress = false;
private View mMotionView;
private int mMotionPosition;
private CheckForTap mPendingCheckForTap;
private CheckForLongPress mPendingCheckForLongPress;
private UnsetPressedState mUnsetPressedState;
private PerformClick mPerformClick;
private final float[] mTmpPoint = new float[2];
private int mTouchSlop = -1;
private float mStartX;
private float mStartY;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
public EasyRecyclerView(Context context) {
super(context);
}
public EasyRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EasyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* {@inheritDoc}
*/
@Override
public void setAdapter(RecyclerView.Adapter adapter) {
super.setAdapter(adapter);
mAdapter = adapter;
if (adapter != null) {
if (mChoiceMode != CHOICE_MODE_NONE && adapter.hasStableIds() &&
mCheckedIdStates == null) {
mCheckedIdStates = new LongSparseArray<>();
}
}
if (mCheckStates != null) {
mCheckStates.clear();
}
if (mCheckedIdStates != null) {
mCheckedIdStates.clear();
}
}
/**
* Returns the number of items currently selected. This will only be valid
* if the choice mode is not {@link #CHOICE_MODE_NONE} (default).
*
* <p>To determine the specific items that are currently selected, use one of
* the <code>getChecked*</code> methods.
*
* @return The number of items currently selected
*
* @see #getCheckedItemPosition()
* @see #getCheckedItemPositions()
* @see #getCheckedItemIds()
*/
public int getCheckedItemCount() {
return mCheckedItemCount;
}
/**
* Returns the checked state of the specified position. The result is only
* valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
* or {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state to return
* @return The item's checked state or <code>false</code> if choice mode
* is invalid
*
* @see #setChoiceMode(int)
*/
public boolean isItemChecked(int position) {
//noinspection SimplifiableIfStatement
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
return mCheckStates.get(position);
}
return false;
}
/**
* Returns the currently checked item. The result is only valid if the choice
* mode has been set to {@link #CHOICE_MODE_SINGLE}.
*
* @return The position of the currently checked item or
* {@link #INVALID_POSITION} if nothing is selected
*
* @see #setChoiceMode(int)
*/
public int getCheckedItemPosition() {
if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) {
return mCheckStates.keyAt(0);
}
return INVALID_POSITION;
}
/**
* Returns the set of checked items in the list. The result is only valid if
* the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A SparseBooleanArray which will return true for each call to
* get(int position) where position is a checked position in the
* list and false otherwise, or <code>null</code> if the choice
* mode is set to {@link #CHOICE_MODE_NONE}.
*/
public SparseBooleanArray getCheckedItemPositions() {
if (mChoiceMode != CHOICE_MODE_NONE) {
return mCheckStates;
}
return null;
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
* has stable IDs. ({@link android.widget.ListAdapter#hasStableIds()} == {@code true})
*
* @return A new array which contains the id of each checked item in the
* list.
*/
public long[] getCheckedItemIds() {
if (mChoiceMode == CHOICE_MODE_NONE || mCheckedIdStates == null || mAdapter == null) {
return new long[0];
}
final LongSparseArray<Integer> idStates = mCheckedIdStates;
final int count = idStates.size();
final long[] ids = new long[count];
for (int i = 0; i < count; i++) {
ids[i] = idStates.keyAt(i);
}
return ids;
}
/**
* Clear any choices previously set
*/
public void clearChoices() {
if (mCheckStates != null) {
mCheckStates.clear();
}
if (mCheckedIdStates != null) {
mCheckedIdStates.clear();
}
mCheckedItemCount = 0;
updateOnScreenCheckedViews();
}
/**
* Sets the checked state of the specified position. The is only valid if
* the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
* {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state is to be checked
* @param value The new checked state for the item
*/
public void setItemChecked(int position, boolean value) {
if (mChoiceMode == CHOICE_MODE_NONE) {
return;
}
// Start selection mode if needed. We don't need to if we're unchecking something.
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
if (mMultiChoiceModeCallback == null ||
!mMultiChoiceModeCallback.hasWrappedCallback()) {
throw new IllegalStateException("EasyRecyclerView: attempted to start selection mode " +
"for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " +
"supplied. Call setMultiChoiceModeListener to set a callback.");
}
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
}
if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
boolean oldValue = mCheckStates.get(position);
mCheckStates.put(position, value);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
if (value) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
} else {
mCheckedIdStates.delete(mAdapter.getItemId(position));
}
}
if (oldValue != value) {
if (value) {
mCheckedItemCount++;
} else {
mCheckedItemCount--;
}
}
if (mChoiceActionMode != null) {
final long id = mAdapter.getItemId(position);
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
position, id, value);
}
} else {
boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds();
// Clear all values if we're checking something, or unchecking the currently
// selected item
if (value || isItemChecked(position)) {
mCheckStates.clear();
if (updateIds) {
mCheckedIdStates.clear();
}
}
// this may end up selecting the value we just cleared but this way
// we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on
if (value) {
mCheckStates.put(position, true);
if (updateIds) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
}
mCheckedItemCount = 1;
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
mCheckedItemCount = 0;
}
}
updateOnScreenCheckedViews();
}
/**
* @see #setChoiceMode(int)
*
* @return The current choice mode
*/
public int getChoiceMode() {
return mChoiceMode;
}
/**
* Defines the choice behavior for the List. By default, Lists do not have any choice behavior
* ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the
* List allows up to one item to be in a chosen state. By setting the choiceMode to
* {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
*
* @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or
* {@link #CHOICE_MODE_MULTIPLE}
*/
public void setChoiceMode(int choiceMode) {
mChoiceMode = choiceMode;
if (mChoiceActionMode != null) {
mChoiceActionMode.finish();
mChoiceActionMode = null;
}
if (mChoiceMode != CHOICE_MODE_NONE) {
if (mCheckStates == null) {
mCheckStates = new SparseBooleanArray(0);
}
if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) {
mCheckedIdStates = new LongSparseArray<>(0);
}
// Modal multi-choice mode only has choices when the mode is active. Clear them.
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
clearChoices();
setLongClickable(true);
}
}
}
/**
* Set a {@link MultiChoiceModeListener} that will manage the lifecycle of the
* selection {@link ActionMode}. Only used when the choice mode is set to
* {@link #CHOICE_MODE_MULTIPLE_MODAL}.
*
* @param listener Listener that will manage the selection mode
*
* @see #setChoiceMode(int)
*/
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (mMultiChoiceModeCallback == null) {
mMultiChoiceModeCallback = new MultiChoiceModeWrapper();
}
mMultiChoiceModeCallback.setWrapped(listener);
}
/**
* Perform a quick, in-place update of the checked or activated state
* on all visible item views. This should only be called when a valid
* choice mode is active.
*/
private void updateOnScreenCheckedViews() {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
final int position = getChildAdapterPosition(child);
setViewChecked(child, mCheckStates.get(position));
}
}
public static void setViewChecked(View view, boolean checked) {
if (view instanceof Checkable) {
((Checkable) view).setChecked(checked);
} else {
view.setActivated(checked);
}
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL: {
if (getScrollState() != SCROLL_STATE_DRAGGING) {
final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
if (vscroll != 0) {
final int delta = (int) (vscroll * getVerticalScrollFactor());
scrollBy(0, -delta);
}
}
}
}
}
return super.onGenericMotionEvent(event);
}
/**
* Gets a scale factor that determines the distance the view should scroll
* vertically in response to {@link android.view.MotionEvent#ACTION_SCROLL}.
* @return The vertical scroll scale factor.
*/
protected float getVerticalScrollFactor() {
if (mVerticalScrollFactor == 0) {
TypedValue outValue = new TypedValue();
if (!getContext().getTheme().resolveAttribute(
0x0101004d, outValue, true)) {//com.android.internal.R.attr.listPreferredItemHeight
throw new IllegalStateException(
"Expected theme to define listPreferredItemHeight.");
}
mVerticalScrollFactor = outValue.getDimension(
getContext().getResources().getDisplayMetrics());
}
return mVerticalScrollFactor;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!isEnabled()) {
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return isClickable() || isLongClickable();
}
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
onTouchDown(ev);
break;
}
case MotionEvent.ACTION_MOVE: {
onTouchMove(ev);
break;
}
case MotionEvent.ACTION_UP: {
onTouchUp(ev);
break;
}
case MotionEvent.ACTION_CANCEL: {
onTouchCancel();
break;
}
}
super.onTouchEvent(ev);
return true;
}
private void onTouchDown(MotionEvent ev) {
final float x = ev.getX();
final float y = ev.getY();
mStartX = x;
mStartY = y;
mMotionView = findChildViewUnder(x, y);
mMotionPosition = getChildAdapterPosition(mMotionView);
if (mMotionView != null && mMotionPosition >= 0) {
mHasPerformedLongPress = false;
mPrePressed = true;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = x;
mPendingCheckForTap.y = y;
mPendingCheckForTap.v = mMotionView;
mPendingCheckForTap.p = mMotionPosition;
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
mMotionView = null;
}
}
private void onTouchMove(MotionEvent ev) {
if (mTouchSlop == -1)
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
if (mMotionView != null && mMotionPosition >= 0 &&
!MathUtils.near(mStartX, mStartY, ev.getX(), ev.getY(), mTouchSlop)) {
removeTapCallback();
if (mMotionView.isPressed()) {
// Remove any future long press/tap checks
removeLongPressCallback();
mMotionView.setPressed(false);
}
}
}
private void onTouchUp(MotionEvent ev) {
View motionView = mMotionView;
int motionPosition = mMotionPosition;
if (motionView != null && motionPosition >= 0) {
final float x = ev.getX();
final float y = ev.getY();
if (motionView.isPressed() || mPrePressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
final float[] point = mTmpPoint;
point[0] = x;
point[1] = y;
ViewUtils.transformPointToViewLocal(point, EasyRecyclerView.this, motionView);
setPressed(motionView, true, point[0], point[1]);
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
mPerformClick.v = motionView;
mPerformClick.p = motionPosition;
mPerformClick.rememberWindowAttachCount();
if (!post(mPerformClick)) {
mPerformClick.run();
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
mUnsetPressedState.v = motionView;
if (mPrePressed) {
postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
// Release
mMotionView = null;
}
}
private void onTouchCancel() {
if (mMotionView != null && mMotionPosition >= 0) {
mMotionView.setPressed(false);
removeTapCallback();
removeLongPressCallback();
// Release motion view
mMotionView = null;
}
}
private void removeTapCallback() {
if (mPendingCheckForTap != null) {
mPrePressed = false;
removeCallbacks(mPendingCheckForTap);
mPendingCheckForTap.v = null;
}
}
private void removeLongPressCallback() {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
mPendingCheckForLongPress.v = null;
}
}
private void setPressed(View v, boolean pressed, float x, float y){
v.setPressed(pressed);
if (pressed && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
v.drawableHotspotChanged(x, y);
}
}
private boolean performItemClick(View view, int position, long id) {
boolean handled = false;
boolean dispatchItemClick = true;
if (mChoiceMode != CHOICE_MODE_NONE) {
handled = true;
boolean checkedStateChanged = false;
if (mChoiceMode == CHOICE_MODE_MULTIPLE ||
(mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) {
boolean checked = !mCheckStates.get(position, false);
mCheckStates.put(position, checked);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
if (checked) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
} else {
mCheckedIdStates.delete(mAdapter.getItemId(position));
}
}
if (checked) {
mCheckedItemCount++;
} else {
mCheckedItemCount--;
}
if (mChoiceActionMode != null) {
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
position, id, checked);
dispatchItemClick = false;
}
checkedStateChanged = true;
} else if (mChoiceMode == CHOICE_MODE_SINGLE) {
boolean checked = !mCheckStates.get(position, false);
if (checked) {
mCheckStates.clear();
mCheckStates.put(position, true);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
mCheckedIdStates.clear();
mCheckedIdStates.put(mAdapter.getItemId(position), position);
}
mCheckedItemCount = 1;
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
mCheckedItemCount = 0;
}
checkedStateChanged = true;
}
if (checkedStateChanged) {
updateOnScreenCheckedViews();
}
}
if (dispatchItemClick) {
if (mOnItemClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnItemClickListener.onItemClick(this, view, position, id);
if (view != null) {
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
}
handled = true;
}
}
return handled;
}
private boolean performItemLongPress(final View child,
final int longPressPosition, final long longPressId) {
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
if (mChoiceActionMode == null &&
(mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
setItemChecked(longPressPosition, true);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return true;
}
boolean handled = false;
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(this, child,
longPressPosition, longPressId);
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
/**
* Register a callback to be invoked when an item in this AdapterView has
* been clicked.
*
* @param listener The callback that will be invoked.
*/
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
if (!isLongClickable()) {
setLongClickable(true);
}
mOnItemLongClickListener = listener;
}
/**
* If choice mode is set, call it in {@link Adapter#onBindViewHolder}
*/
public void checkItemCheckedState(View view, int position) {
setViewChecked(view, isItemChecked(position));
}
/*
@Override
public Parcelable onSaveInstanceState() {
final Parcelable state = new Bundle(super.onSaveInstanceState());
state.putInt(STATE_KEY_CHOICE_MODE, mChoiceMode);
state.putParcelable(STATE_KEY_CHECKED_STATES, mCheckStates);
state.putParcelable(STATE_KEY_CHECKED_ID_STATES, mCheckedIdStates);
state.putInt(STATE_KEY_CHECKED_COUNT, mCheckedItemCount);
return state;
}
public void onRestoreInstanceState(Bundle state) {
mChoiceMode = ChoiceMode.values()[state.getInt(STATE_KEY_CHOICE_MODE)];
mCheckedStates = state.getParcelable(STATE_KEY_CHECKED_STATES);
mCheckedIdStates = state.getParcelable(STATE_KEY_CHECKED_ID_STATES);
mCheckedCount = state.getInt(STATE_KEY_CHECKED_COUNT);
// TODO confirm ids here
}*/
private final class CheckForTap implements Runnable {
float x;
float y;
View v;
int p;
@Override
public void run() {
View view = v;
int position = p;
if (view != null && position >= 0) {
mPrePressed = false;
final float[] point = mTmpPoint;
point[0] = x;
point[1] = y;
ViewUtils.transformPointToViewLocal(point, EasyRecyclerView.this, view);
setPressed(v, true, point[0], point[1]);
if (isLongClickable()) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.rememberWindowAttachCount();
mPendingCheckForLongPress.v = view;
mPendingCheckForLongPress.p = position;
postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout() -
ViewConfiguration.getTapTimeout());
}
}
// Release
v = null;
}
}
private class CheckForLongPress extends WindowRunnnable implements Runnable {
View v;
int p;
@Override
public void run() {
View view = v;
int position = p;
if (view != null && position >= 0 && view.isPressed() && view.getParent() != null) {
boolean handled = false;
if (sameWindow()) {
handled = performItemLongPress(view, position, getAdapter().getItemId(position));
}
if (handled) {
mHasPerformedLongPress = true;
view.setPressed(false);
}
}
// Release
v = null;
}
}
private final class UnsetPressedState implements Runnable {
View v;
@Override
public void run() {
if (v != null) {
v.setPressed(false);
// Release
v = null;
}
}
}
private class PerformClick extends WindowRunnnable implements Runnable {
View v;
int p;
@Override
public void run() {
View view = v;
int position = p;
if (view != null && position >= 0 && sameWindow()) {
performItemClick(view, position, mAdapter.getItemId(position));
}
// Release
v = null;
}
}
/**
* A base class for Runnables that will check that their view is still attached to
* the original window as when the Runnable was created.
*
*/
private class WindowRunnnable {
private int mOriginalAttachCount;
public void rememberWindowAttachCount() {
mOriginalAttachCount = getWindowAttachCount();
}
public boolean sameWindow() {
return getWindowAttachCount() == mOriginalAttachCount;
}
}
/**
* Interface definition for a callback to be invoked when an item in the
* EasyRecyclerView has been clicked.
*/
public interface OnItemClickListener {
/**
* Callback method to be invoked when an item in the EasyRecyclerView
* has been clicked.
*
* @param parent The EasyRecyclerView where the click happened.
* @param view The view within the EasyRecyclerView that was clicked
* @param position The position of the view in the adapter.
* @param id The row id of the item that was clicked.
*
* @return true if the callback consumed the click, false otherwise
*/
boolean onItemClick(EasyRecyclerView parent, View view, int position, long id);
}
/**
* Interface definition for a callback to be invoked when an item in the
* EasyRecyclerView has been clicked and held.
*/
public interface OnItemLongClickListener {
/**
* Callback method to be invoked when an item in the EasyRecyclerView
* has been clicked and held.
*
* @param parent The EasyRecyclerView where the click happened
* @param view The view within the EasyRecyclerView that was clicked
* @param position The position of the view in the list
* @param id The row id of the item that was clicked
*
* @return true if the callback consumed the long click, false otherwise
*/
boolean onItemLongClick(EasyRecyclerView parent, View view, int position, long id);
}
/**
* A MultiChoiceModeListener receives events for {@link android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
* It acts as the {@link ActionMode.Callback} for the selection mode and also receives
* {@link #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user
* selects and deselects list items.
*/
public interface MultiChoiceModeListener extends ActionMode.Callback {
/**
* Called when an item is checked or unchecked during selection mode.
*
* @param mode The {@link ActionMode} providing the selection mode
* @param position Adapter position of the item that was checked or unchecked
* @param id Adapter ID of the item that was checked or unchecked
* @param checked <code>true</code> if the item is now checked, <code>false</code>
* if the item is now unchecked.
*/
void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked);
}
class MultiChoiceModeWrapper implements MultiChoiceModeListener {
private MultiChoiceModeListener mWrapped;
public void setWrapped(MultiChoiceModeListener wrapped) {
mWrapped = wrapped;
}
public boolean hasWrappedCallback() {
return mWrapped != null;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
if (mWrapped.onCreateActionMode(mode, menu)) {
// Initialize checked graphic state?
setLongClickable(false);
return true;
}
return false;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return mWrapped.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return mWrapped.onActionItemClicked(mode, item);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mWrapped.onDestroyActionMode(mode);
mChoiceActionMode = null;
// Ending selection mode means deselecting everything.
clearChoices();
requestLayout();
setLongClickable(true);
}
@Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
mWrapped.onItemCheckedStateChanged(mode, position, id, checked);
// If there are no items selected we no longer need the selection mode.
if (getCheckedItemCount() == 0) {
mode.finish();
}
}
}
}
@@ -1,162 +0,0 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.recyclerview;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class LinearDividerItemDecoration extends RecyclerView.ItemDecoration {
public static final int HORIZONTAL = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL = LinearLayoutManager.VERTICAL;
private boolean mShowFirstDivider = false;
private boolean mShowLastDivider = false;
private final Rect mRect;
private final Paint mPaint;
private int mOrientation;
private int mThickness;
private int mPaddingStart = 0;
private int mPaddingEnd = 0;
public LinearDividerItemDecoration(int orientation, int color, int thickness) {
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
setOrientation(orientation);
setColor(color);
setThickness(thickness);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL && orientation != VERTICAL) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
public void setColor(int color) {
mPaint.setColor(color);
}
public void setThickness(int thickness) {
mThickness = thickness;
}
public void setShowFirstDivider(boolean showFirstDivider) {
mShowFirstDivider = showFirstDivider;
}
public void setShowLastDivider(boolean showLastDivider) {
mShowLastDivider = showLastDivider;
}
public void setPadding(int padding) {
setPaddingStart(padding);
setPaddingEnd(padding);
}
public void setPaddingStart(int paddingStart) {
mPaddingStart = paddingStart;
}
public void setPaddingEnd(int paddingEnd) {
mPaddingEnd = paddingEnd;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
final int position = parent.getChildPosition(view);
final int itemCount = parent.getAdapter().getItemCount();
if (mOrientation == VERTICAL) {
if (position == 0 && mShowFirstDivider)
outRect.top = mThickness;
outRect.bottom = mThickness;
if (position == itemCount - 1 && !mShowLastDivider)
outRect.bottom = 0;
} else {
if (position == 0 && mShowFirstDivider)
outRect.left = mThickness;
outRect.right = mThickness;
if (position == itemCount - 1 && !mShowLastDivider)
outRect.left = 0;
}
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent,
RecyclerView.State state) {
int itemCount = parent.getAdapter().getItemCount();
if (mOrientation == VERTICAL) {
final int left = parent.getPaddingLeft() + mPaddingStart;
final int right = parent.getWidth() - parent.getPaddingRight() - mPaddingEnd;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
if (i != childCount - 1 || mShowLastDivider
|| parent.getChildPosition(child) != itemCount - 1) {
final int top = child.getBottom() + lp.bottomMargin;
final int bottom = top + mThickness;
mRect.set(left, top, right, bottom);
c.drawRect(mRect, mPaint);
}
if (i == 0 && mShowFirstDivider && parent.getChildPosition(child) == 0) {
final int bottom = child.getTop() + lp.topMargin;
final int top = bottom - mThickness;
mRect.set(left, top, right, bottom);
c.drawRect(mRect, mPaint);
}
}
} else {
final int top = parent.getPaddingTop() + mPaddingStart;
final int bottom = parent.getHeight() - parent.getPaddingBottom() - mPaddingEnd;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
if (i != childCount - 1 || mShowLastDivider
|| parent.getChildPosition(child) != itemCount - 1) {
final int left = child.getRight() + lp.rightMargin;
final int right = left + mThickness;
mRect.set(left, top, right, bottom);
c.drawRect(mRect, mPaint);
}
if (i == 0 && mShowFirstDivider && parent.getChildPosition(child) == 0) {
final int right = child.getLeft() + lp.leftMargin;
final int left = right - mThickness;
mRect.set(left, top, right, bottom);
c.drawRect(mRect, mPaint);
}
}
}
}
}
@@ -1,46 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.recyclerview;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Only work for StaggeredGridLayoutManager, FooterAdapter
*
* @author Hippo
*
*/
public class MarginItemDecoration extends RecyclerView.ItemDecoration {
private int mHalfMargin;
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.set(mHalfMargin, mHalfMargin, mHalfMargin, mHalfMargin);
}
public void setMargin(int margin) {
mHalfMargin = margin / 2;
}
public int getMargin() {
return mHalfMargin * 2;
}
}
@@ -1,376 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.hippo.ehviewer.widget.recyclerview;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Based on Roman Nurik's Android-SwipeToDismiss lib <a href="https://github.com/romannurik/Android-SwipeToDismiss">https://github.com/romannurik/Android-SwipeToDismiss</a>
* <p/>
* RecyclerView.OnItemTouchListener that allows items to be swiped and dismissed.
* <p/>
* Typical usage:
* <p/>
* <pre>
* {@code
* swipeToDismissTouchListener = new SwipeToDismissTouchListener(recyclerView, new SwipeToDismissTouchListener.DismissCallbacks() {
* @Override
* public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) {
* return SwipeToDismissTouchListener.SwipeDirection.RIGHT;
* }
* @Override
* public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) {
* for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) {
* adapter.removeItem(data.position);
* adapter.notifyItemRemoved(data.position);
* }
* }
* });
*
* }
* </pre>
*/
public class SwipeToDismissTouchListener implements RecyclerView.OnItemTouchListener {
private final RecyclerView mRecyclerView;
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private float mTranslationX;
private boolean mPaused = false;
private View mSwipeView;
private int mDismissCount = 0;
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private SwipeDirection mAllowedSwipeDirection = SwipeDirection.NONE;
private int[] notToDismissPositionArray;
/**
* Constructs a new swipe-to-dismiss OnItemTouchListener for RecyclerView
*
* @param recyclerView RecyclerView
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss this view.
*/
public SwipeToDismissTouchListener(RecyclerView recyclerView, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 4;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = recyclerView.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
mRecyclerView = recyclerView;
mCallbacks = callbacks;
}
/**
* Constructs a new swipe-to-dismiss OnItemTouchListener for RecyclerView
*
* @param recyclerView RecyclerView
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss this view.
*/
public SwipeToDismissTouchListener(RecyclerView recyclerView, DismissCallbacks callbacks, int[] notToDismiss) {
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 4;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = recyclerView.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
mRecyclerView = recyclerView;
mCallbacks = callbacks;
notToDismissPositionArray = notToDismiss;
}
public int[] getNotToDismissPositionArray() {
return notToDismissPositionArray;
}
public void setNotToDismissPositionArray(int[] notToDismissPositionArray) {
this.notToDismissPositionArray = notToDismissPositionArray;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
@Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
motionEvent.offsetLocation(mTranslationX, 0);
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_UP: {
up(motionEvent);
break;
}
case MotionEvent.ACTION_CANCEL: {
cancel();
break;
}
case MotionEvent.ACTION_MOVE: {
move(motionEvent);
break;
}
}
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
@Override
public boolean onInterceptTouchEvent(final RecyclerView view, MotionEvent motionEvent) {
if (mPaused) return false;
// offset because the view is translated during swipe
motionEvent.offsetLocation(mTranslationX, 0);
if (mViewWidth < 2) {
mViewWidth = view.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
return down(motionEvent);
}
case MotionEvent.ACTION_MOVE: {
return move(motionEvent);
}
}
return false;
}
private boolean down(MotionEvent motionEvent) {
if (mPaused) return false;
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
mSwipeView = mRecyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (mSwipeView == null) return false;
int pos = mRecyclerView.getChildLayoutPosition(mSwipeView);
if (notToDismissPositionArray != null && notToDismissPositionArray.length > 0) {
for (int notToDismiss : notToDismissPositionArray) {
if (pos == notToDismiss) return false;
}
}
mAllowedSwipeDirection = mCallbacks.dismissDirection(pos);
if (mAllowedSwipeDirection != SwipeDirection.NONE) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
return false;
}
resetMotion();
return false;
}
private void cancel() {
if (mVelocityTracker == null) {
return;
}
mSwipeView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
mSwipeView = null;
}
private void up(MotionEvent motionEvent) {
if (mPaused || mVelocityTracker == null || mSwipeView == null) {
return;
}
mSwipeView.setPressed(false);
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
final int pos = mRecyclerView.getChildLayoutPosition(mSwipeView);
final View swipeViewCopy = mSwipeView;
final SwipeDirection swipeDirection = dismissRight ? SwipeDirection.RIGHT : SwipeDirection.LEFT;
++mDismissCount;
mSwipeView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime);
//this is instead of unreliable onAnimationEnd callback
swipeViewCopy.postDelayed(new Runnable() {
@Override
public void run() {
performDismiss(swipeViewCopy, pos, swipeDirection);
swipeViewCopy.setTranslationX(0);
// swipeViewCopy.setAlpha(1);
}
}, mAnimationTime + 100);
} else if (mSwiping) {
// cancel
mSwipeView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
resetMotion();
}
private boolean move(MotionEvent motionEvent) {
if (mSwipeView == null || mVelocityTracker == null || mPaused) {
return false;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
mSwipeView.setPressed(false);
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mSwipeView.onTouchEvent(cancelEvent);
}
//Prevent swipes to disallowed directions
if ((deltaX < 0 && mAllowedSwipeDirection == SwipeDirection.RIGHT) || (deltaX > 0 && mAllowedSwipeDirection == SwipeDirection.LEFT)) {
resetMotion();
return false;
}
if (mSwiping) {
mCallbacks.onTouchDown();
mTranslationX = deltaX;
mSwipeView.setTranslationX(deltaX - mSwipingSlop);
mSwipeView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
return false;
}
private void resetMotion() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
mCallbacks.onResetMotion();
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
mSwipeView = null;
mAllowedSwipeDirection = SwipeDirection.NONE;
}
private void performDismiss(View dismissView, int pos, SwipeDirection direction) {
--mDismissCount;
mPendingDismisses.add(new PendingDismissData(pos, dismissView, direction));
if (mDismissCount == 0) {
Collections.sort(mPendingDismisses);
List<PendingDismissData> dismissData = new ArrayList<>(mPendingDismisses);
mCallbacks.onDismiss(mRecyclerView, dismissData);
mPendingDismisses.clear();
}
}
public interface DismissCallbacks {
SwipeDirection dismissDirection(int position);
void onDismiss(RecyclerView view, List<PendingDismissData> dismissData);
void onResetMotion();
void onTouchDown();
}
public class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public SwipeDirection direction;
public PendingDismissData(int position, View view, SwipeDirection direction) {
this.position = position;
this.view = view;
this.direction = direction;
}
@Override
public int compareTo(@NonNull PendingDismissData other) {
return other.position - position;
}
}
public enum SwipeDirection {
LEFT, RIGHT, BOTH, NONE
}
}
@@ -1,154 +0,0 @@
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.v4.view.ViewCompat;
import android.view.animation.Animation;
import android.widget.ImageView;
/**
* Private class created to work around issues with AnimationListeners being
* called before the animation is actually complete and support shadows on older
* platforms.
*
* @hide
*/
class CircleImageView extends ImageView {
private static final int KEY_SHADOW_COLOR = 0x1E000000;
private static final int FILL_SHADOW_COLOR = 0x3D000000;
// PX
private static final float X_OFFSET = 0f;
private static final float Y_OFFSET = 1.75f;
private static final float SHADOW_RADIUS = 3.5f;
private static final int SHADOW_ELEVATION = 4;
private Animation.AnimationListener mListener;
private int mShadowRadius;
public CircleImageView(Context context, int color, final float radius) {
super(context);
final float density = getContext().getResources().getDisplayMetrics().density;
final int diameter = (int) (radius * density * 2);
final int shadowYOffset = (int) (density * Y_OFFSET);
final int shadowXOffset = (int) (density * X_OFFSET);
mShadowRadius = (int) (density * SHADOW_RADIUS);
ShapeDrawable circle;
if (elevationSupported()) {
circle = new ShapeDrawable(new OvalShape());
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
} else {
OvalShape oval = new OvalShadow(mShadowRadius, diameter);
circle = new ShapeDrawable(oval);
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint());
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
KEY_SHADOW_COLOR);
final int padding = mShadowRadius;
// set padding so the inner image sits correctly within the shadow.
setPadding(padding, padding, padding, padding);
}
circle.getPaint().setColor(color);
setBackgroundDrawable(circle);
}
private boolean elevationSupported() {
return android.os.Build.VERSION.SDK_INT >= 21;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!elevationSupported()) {
setMeasuredDimension(getMeasuredWidth() + mShadowRadius*2, getMeasuredHeight()
+ mShadowRadius*2);
}
}
public void setAnimationListener(Animation.AnimationListener listener) {
mListener = listener;
}
@Override
public void onAnimationStart() {
super.onAnimationStart();
if (mListener != null) {
mListener.onAnimationStart(getAnimation());
}
}
@Override
public void onAnimationEnd() {
super.onAnimationEnd();
if (mListener != null) {
mListener.onAnimationEnd(getAnimation());
}
}
/**
* Update the background color of the circle image view.
*
* @param colorRes Id of a color resource.
*/
public void setBackgroundColorRes(int colorRes) {
setBackgroundColor(getContext().getResources().getColor(colorRes));
}
@Override
public void setBackgroundColor(int color) {
if (getBackground() instanceof ShapeDrawable) {
((ShapeDrawable) getBackground()).getPaint().setColor(color);
}
}
private class OvalShadow extends OvalShape {
private RadialGradient mRadialGradient;
private int mShadowRadius;
private Paint mShadowPaint;
private int mCircleDiameter;
public OvalShadow(int shadowRadius, int circleDiameter) {
super();
mShadowPaint = new Paint();
mShadowRadius = shadowRadius;
mCircleDiameter = circleDiameter;
mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2,
mShadowRadius, new int[] {
FILL_SHADOW_COLOR, Color.TRANSPARENT
}, null, Shader.TileMode.CLAMP);
mShadowPaint.setShader(mRadialGradient);
}
@Override
public void draw(Canvas canvas, Paint paint) {
final int viewWidth = CircleImageView.this.getWidth();
final int viewHeight = CircleImageView.this.getHeight();
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
mShadowPaint);
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
}
}
}
@@ -1,714 +0,0 @@
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.widget.refreshlayout;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
* Fancy progress indicator for Material theme.
*
* @hide
*/
class MaterialProgressDrawable extends Drawable implements Animatable {
private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
private static final Interpolator END_CURVE_INTERPOLATOR = new EndCurveInterpolator();
private static final Interpolator START_CURVE_INTERPOLATOR = new StartCurveInterpolator();
private static final Interpolator EASE_INTERPOLATOR = new AccelerateDecelerateInterpolator();
@Retention(RetentionPolicy.CLASS)
@IntDef({LARGE, DEFAULT})
public @interface ProgressDrawableSize {}
// Maps to ProgressBar.Large style
static final int LARGE = 0;
// Maps to ProgressBar default style
static final int DEFAULT = 1;
// Maps to ProgressBar default style
private static final int CIRCLE_DIAMETER = 40;
private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width
private static final float STROKE_WIDTH = 2.5f;
// Maps to ProgressBar.Large style
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float CENTER_RADIUS_LARGE = 12.5f;
private static final float STROKE_WIDTH_LARGE = 3f;
private final int[] COLORS = new int[] {
Color.BLACK
};
/** The duration of a single progress spin in milliseconds. */
private static final int ANIMATION_DURATION = 1000 * 80 / 60;
/** The number of points in the progress "star". */
private static final float NUM_POINTS = 5f;
/** The list of animators operating on this drawable. */
private final ArrayList<Animation> mAnimators = new ArrayList<Animation>();
/** The indicator ring, used to manage animation state. */
private final Ring mRing;
/** Canvas rotation in degrees. */
private float mRotation;
/** Layout info for the arrowhead in dp */
private static final int ARROW_WIDTH = 10;
private static final int ARROW_HEIGHT = 5;
private static final float ARROW_OFFSET_ANGLE = 5;
/** Layout info for the arrowhead for the large spinner in dp */
private static final int ARROW_WIDTH_LARGE = 12;
private static final int ARROW_HEIGHT_LARGE = 6;
private static final float MAX_PROGRESS_ARC = .8f;
private Resources mResources;
private View mParent;
private Animation mAnimation;
private float mRotationCount;
private double mWidth;
private double mHeight;
boolean mFinishing;
public MaterialProgressDrawable(Context context, View parent) {
mParent = parent;
mResources = context.getResources();
mRing = new Ring(mCallback);
mRing.setColors(COLORS);
updateSizes(DEFAULT);
setupAnimators();
}
private void setSizeParameters(double progressCircleWidth, double progressCircleHeight,
double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) {
final Ring ring = mRing;
final DisplayMetrics metrics = mResources.getDisplayMetrics();
final float screenDensity = metrics.density;
mWidth = progressCircleWidth * screenDensity;
mHeight = progressCircleHeight * screenDensity;
ring.setStrokeWidth((float) strokeWidth * screenDensity);
ring.setCenterRadius(centerRadius * screenDensity);
ring.setColorIndex(0);
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity);
ring.setInsets((int) mWidth, (int) mHeight);
}
/**
* Set the overall size for the progress spinner. This updates the radius
* and stroke width of the ring.
*
* @param size One of {@link #LARGE} or
* {@link #DEFAULT}
*/
public void updateSizes(@ProgressDrawableSize int size) {
if (size == LARGE) {
setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE,
STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE);
} else {
setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH,
ARROW_WIDTH, ARROW_HEIGHT);
}
}
/**
* @param show Set to true to display the arrowhead on the progress spinner.
*/
public void showArrow(boolean show) {
mRing.setShowArrow(show);
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
mRing.setArrowScale(scale);
}
/**
* Set the start and end trim for the progress spinner arc.
*
* @param startAngle start angle
* @param endAngle end angle
*/
public void setStartEndTrim(float startAngle, float endAngle) {
mRing.setStartTrim(startAngle);
mRing.setEndTrim(endAngle);
}
/**
* Set the amount of rotation to apply to the progress spinner.
*
* @param rotation Rotation is from [0..1]
*/
public void setProgressRotation(float rotation) {
mRing.setRotation(rotation);
}
/**
* Update the background color of the circle image view.
*/
public void setBackgroundColor(int color) {
mRing.setBackgroundColor(color);
}
/**
* Set the colors used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
mRing.setColors(colors);
mRing.setColorIndex(0);
}
@Override
public int getIntrinsicHeight() {
return (int) mHeight;
}
@Override
public int getIntrinsicWidth() {
return (int) mWidth;
}
@Override
public void draw(Canvas c) {
final Rect bounds = getBounds();
final int saveCount = c.save();
c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY());
mRing.draw(c, bounds);
c.restoreToCount(saveCount);
}
@Override
public void setAlpha(int alpha) {
mRing.setAlpha(alpha);
}
public int getAlpha() {
return mRing.getAlpha();
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mRing.setColorFilter(colorFilter);
}
@SuppressWarnings("unused")
void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
private float getRotation() {
return mRotation;
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public boolean isRunning() {
final ArrayList<Animation> animators = mAnimators;
final int N = animators.size();
for (int i = 0; i < N; i++) {
final Animation animator = animators.get(i);
if (animator.hasStarted() && !animator.hasEnded()) {
return true;
}
}
return false;
}
@Override
public void start() {
mAnimation.reset();
mRing.storeOriginals();
// Already showing some part of the ring
if (mRing.getEndTrim() != mRing.getStartTrim()) {
mFinishing = true;
mAnimation.setDuration(ANIMATION_DURATION/2);
mParent.startAnimation(mAnimation);
} else {
mRing.setColorIndex(0);
mRing.resetOriginals();
mAnimation.setDuration(ANIMATION_DURATION);
mParent.startAnimation(mAnimation);
}
}
@Override
public void stop() {
mParent.clearAnimation();
setRotation(0);
mRing.setShowArrow(false);
mRing.setColorIndex(0);
mRing.resetOriginals();
}
private void applyFinishTranslation(float interpolatedTime, Ring ring) {
// shrink back down and complete a full rotation before
// starting other circles
// Rotation goes between [0..1].
float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC)
+ 1f);
final float startTrim = ring.getStartingStartTrim()
+ (ring.getStartingEndTrim() - ring.getStartingStartTrim()) * interpolatedTime;
ring.setStartTrim(startTrim);
final float rotation = ring.getStartingRotation()
+ ((targetRotation - ring.getStartingRotation()) * interpolatedTime);
ring.setRotation(rotation);
}
private void setupAnimators() {
final Ring ring = mRing;
final Animation animation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
if (mFinishing) {
applyFinishTranslation(interpolatedTime, ring);
} else {
// The minProgressArc is calculated from 0 to create an
// angle that
// matches the stroke width.
final float minProgressArc = (float) Math.toRadians(
ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius()));
final float startingEndTrim = ring.getStartingEndTrim();
final float startingTrim = ring.getStartingStartTrim();
final float startingRotation = ring.getStartingRotation();
// Offset the minProgressArc to where the endTrim is
// located.
final float minArc = MAX_PROGRESS_ARC - minProgressArc;
final float endTrim = startingEndTrim + (minArc
* START_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
ring.setEndTrim(endTrim);
final float startTrim = startingTrim + (MAX_PROGRESS_ARC
* END_CURVE_INTERPOLATOR.getInterpolation(interpolatedTime));
ring.setStartTrim(startTrim);
final float rotation = startingRotation + (0.25f * interpolatedTime);
ring.setRotation(rotation);
float groupRotation = ((720.0f / NUM_POINTS) * interpolatedTime)
+ (720.0f * (mRotationCount / NUM_POINTS));
setRotation(groupRotation);
}
}
};
animation.setRepeatCount(Animation.INFINITE);
animation.setRepeatMode(Animation.RESTART);
animation.setInterpolator(LINEAR_INTERPOLATOR);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mRotationCount = 0;
}
@Override
public void onAnimationEnd(Animation animation) {
// do nothing
}
@Override
public void onAnimationRepeat(Animation animation) {
ring.storeOriginals();
ring.goToNextColor();
ring.setStartTrim(ring.getEndTrim());
if (mFinishing) {
// finished closing the last ring from the swipe gesture; go
// into progress mode
mFinishing = false;
animation.setDuration(ANIMATION_DURATION);
ring.setShowArrow(false);
} else {
mRotationCount = (mRotationCount + 1) % (NUM_POINTS);
}
}
});
mAnimation = animation;
}
private final Callback mCallback = new Callback() {
@Override
public void invalidateDrawable(Drawable d) {
invalidateSelf();
}
@Override
public void scheduleDrawable(Drawable d, Runnable what, long when) {
scheduleSelf(what, when);
}
@Override
public void unscheduleDrawable(Drawable d, Runnable what) {
unscheduleSelf(what);
}
};
private static class Ring {
private final RectF mTempBounds = new RectF();
private final Paint mPaint = new Paint();
private final Paint mArrowPaint = new Paint();
private final Callback mCallback;
private float mStartTrim = 0.0f;
private float mEndTrim = 0.0f;
private float mRotation = 0.0f;
private float mStrokeWidth = 5.0f;
private float mStrokeInset = 2.5f;
private int[] mColors;
// mColorIndex represents the offset into the available mColors that the
// progress circle should currently display. As the progress circle is
// animating, the mColorIndex moves by one to the next available color.
private int mColorIndex;
private float mStartingStartTrim;
private float mStartingEndTrim;
private float mStartingRotation;
private boolean mShowArrow;
private Path mArrow;
private float mArrowScale;
private double mRingCenterRadius;
private int mArrowWidth;
private int mArrowHeight;
private int mAlpha;
private final Paint mCirclePaint = new Paint();
private int mBackgroundColor;
public Ring(Callback callback) {
mCallback = callback;
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setAntiAlias(true);
mPaint.setStyle(Style.STROKE);
mArrowPaint.setStyle(Style.FILL);
mArrowPaint.setAntiAlias(true);
}
public void setBackgroundColor(int color) {
mBackgroundColor = color;
}
/**
* Set the dimensions of the arrowhead.
*
* @param width Width of the hypotenuse of the arrow head
* @param height Height of the arrow point
*/
public void setArrowDimensions(float width, float height) {
mArrowWidth = (int) width;
mArrowHeight = (int) height;
}
/**
* Draw the progress spinner
*/
public void draw(Canvas c, Rect bounds) {
final RectF arcBounds = mTempBounds;
arcBounds.set(bounds);
arcBounds.inset(mStrokeInset, mStrokeInset);
final float startAngle = (mStartTrim + mRotation) * 360;
final float endAngle = (mEndTrim + mRotation) * 360;
float sweepAngle = endAngle - startAngle;
mPaint.setColor(mColors[mColorIndex]);
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
drawTriangle(c, startAngle, sweepAngle, bounds);
if (mAlpha < 255) {
mCirclePaint.setColor(mBackgroundColor);
mCirclePaint.setAlpha(255 - mAlpha);
c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2,
mCirclePaint);
}
}
private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) {
if (mShowArrow) {
if (mArrow == null) {
mArrow = new Path();
mArrow.setFillType(Path.FillType.EVEN_ODD);
} else {
mArrow.reset();
}
// Adjust the position of the triangle so that it is inset as
// much as the arc, but also centered on the arc.
float inset = (int) mStrokeInset / 2 * mArrowScale;
float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX());
float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY());
// Update the path each time. This works around an issue in SKIA
// where concatenating a rotation matrix to a scale matrix
// ignored a starting negative rotation. This appears to have
// been fixed as of API 21.
mArrow.moveTo(0, 0);
mArrow.lineTo(mArrowWidth * mArrowScale, 0);
mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight
* mArrowScale));
mArrow.offset(x - inset, y);
mArrow.close();
// draw a triangle
mArrowPaint.setColor(mColors[mColorIndex]);
c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(),
bounds.exactCenterY());
c.drawPath(mArrow, mArrowPaint);
}
}
/**
* Set the colors the progress spinner alternates between.
*
* @param colors Array of integers describing the colors. Must be non-<code>null</code>.
*/
public void setColors(@NonNull int[] colors) {
mColors = colors;
// if colors are reset, make sure to reset the color index as well
setColorIndex(0);
}
/**
* @param index Index into the color array of the color to display in
* the progress spinner.
*/
public void setColorIndex(int index) {
mColorIndex = index;
}
/**
* Proceed to the next available ring color. This will automatically
* wrap back to the beginning of colors.
*/
public void goToNextColor() {
mColorIndex = (mColorIndex + 1) % (mColors.length);
}
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
invalidateSelf();
}
/**
* @param alpha Set the alpha of the progress spinner and associated arrowhead.
*/
public void setAlpha(int alpha) {
mAlpha = alpha;
}
/**
* @return Current alpha of the progress spinner and arrowhead.
*/
public int getAlpha() {
return mAlpha;
}
/**
* @param strokeWidth Set the stroke width of the progress spinner in pixels.
*/
public void setStrokeWidth(float strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(strokeWidth);
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStrokeWidth() {
return mStrokeWidth;
}
@SuppressWarnings("unused")
public void setStartTrim(float startTrim) {
mStartTrim = startTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getStartTrim() {
return mStartTrim;
}
public float getStartingStartTrim() {
return mStartingStartTrim;
}
public float getStartingEndTrim() {
return mStartingEndTrim;
}
@SuppressWarnings("unused")
public void setEndTrim(float endTrim) {
mEndTrim = endTrim;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getEndTrim() {
return mEndTrim;
}
@SuppressWarnings("unused")
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
@SuppressWarnings("unused")
public float getRotation() {
return mRotation;
}
public void setInsets(int width, int height) {
final float minEdge = (float) Math.min(width, height);
float insets;
if (mRingCenterRadius <= 0 || minEdge < 0) {
insets = (float) Math.ceil(mStrokeWidth / 2.0f);
} else {
insets = (float) (minEdge / 2.0f - mRingCenterRadius);
}
mStrokeInset = insets;
}
@SuppressWarnings("unused")
public float getInsets() {
return mStrokeInset;
}
/**
* @param centerRadius Inner radius in px of the circle the progress
* spinner arc traces.
*/
public void setCenterRadius(double centerRadius) {
mRingCenterRadius = centerRadius;
}
public double getCenterRadius() {
return mRingCenterRadius;
}
/**
* @param show Set to true to show the arrow head on the progress spinner.
*/
public void setShowArrow(boolean show) {
if (mShowArrow != show) {
mShowArrow = show;
invalidateSelf();
}
}
/**
* @param scale Set the scale of the arrowhead for the spinner.
*/
public void setArrowScale(float scale) {
if (scale != mArrowScale) {
mArrowScale = scale;
invalidateSelf();
}
}
/**
* @return The amount the progress spinner is currently rotated, between [0..1].
*/
public float getStartingRotation() {
return mStartingRotation;
}
/**
* If the start / end trim are offset to begin with, store them so that
* animation starts from that offset.
*/
public void storeOriginals() {
mStartingStartTrim = mStartTrim;
mStartingEndTrim = mEndTrim;
mStartingRotation = mRotation;
}
/**
* Reset the progress spinner to default rotation, start and end angles.
*/
public void resetOriginals() {
mStartingStartTrim = 0;
mStartingEndTrim = 0;
mStartingRotation = 0;
setStartTrim(0);
setEndTrim(0);
setRotation(0);
}
private void invalidateSelf() {
mCallback.invalidateDrawable(null);
}
}
/**
* Squishes the interpolation curve into the second half of the animation.
*/
private static class EndCurveInterpolator extends AccelerateDecelerateInterpolator {
@Override
public float getInterpolation(float input) {
return super.getInterpolation(Math.max(0, (input - 0.5f) * 2.0f));
}
}
/**
* Squishes the interpolation curve into the first half of the animation.
*/
private static class StartCurveInterpolator extends AccelerateDecelerateInterpolator {
@Override
public float getInterpolation(float input) {
return super.getInterpolation(Math.min(1, input * 2.0f));
}
}
}
File diff suppressed because it is too large. Load diff
-3
View File
@@ -1,3 +0,0 @@
APP_ABI := armeabi armeabi-v7a x86
APP_PLATFORM := android-9
APP_OPTIM := release
-72
View File
@@ -1,72 +0,0 @@
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the <stdarg.h> header file. */
#define HAVE_STDARG_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "giflib"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "esr@thyrsus.com"
/* Define to the full name of this package. */
#define PACKAGE_NAME "giflib"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "giflib 5.1.1"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "giflib"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "5.1.1"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "5.1.1"
-10
View File
@@ -1,10 +0,0 @@
# simd/jsimdext.inc
%define EXTN(name) _ %+ name<br>
to<br>
%define EXTN(name) name<br>
or ld error for x86 and x86_64
# Add cmyk to rgb, cmyk to gray
In jdcolor.c, jdcolext.c
-145
View File
@@ -1,145 +0,0 @@
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* use 8 or 12 */
/* #undef BITS_IN_JSAMPLE */
/* libjpeg-turbo build number */
#define BUILD "20150109"
/* Support arithmetic encoding */
#define C_ARITH_CODING_SUPPORTED 1
/* Support arithmetic decoding */
#define D_ARITH_CODING_SUPPORTED 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <jni.h> header file. */
/* #undef HAVE_JNI_H */
/* Define to 1 if you have the <locale.h> header file. */
#define HAVE_LOCALE_H 1
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the <stddef.h> header file. */
#define HAVE_STDDEF_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if the system has the type `unsigned char'. */
#define HAVE_UNSIGNED_CHAR 1
/* Define to 1 if the system has the type `unsigned short'. */
#define HAVE_UNSIGNED_SHORT 1
/* Compiler does not support pointers to undefined structures. */
/* #undef INCOMPLETE_TYPES_BROKEN */
/* How to obtain function inlining. */
#define INLINE inline __attribute__((always_inline))
/* libjpeg API version */
#define JPEG_LIB_VERSION 62
/* libjpeg-turbo version */
#define LIBJPEG_TURBO_VERSION 1.4.0
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Support in-memory source/destination managers */
#define MEM_SRCDST_SUPPORTED 1
/* Define if you have BSD-like bzero and bcopy in <strings.h> rather than
memset/memcpy in <string.h>. */
/* #undef NEED_BSD_STRINGS */
/* Define if you need to include <sys/types.h> to get size_t. */
#define NEED_SYS_TYPES_H 1
/* Name of package */
#define PACKAGE "libjpeg-turbo"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME "libjpeg-turbo"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libjpeg-turbo 1.4.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libjpeg-turbo"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "1.4.0"
/* Define if your (broken) compiler shifts signed values as if they were
unsigned. */
/* #undef RIGHT_SHIFT_IS_UNSIGNED */
/* The size of `long', as computed by sizeof. */
#define SIZEOF_LONG 8
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "1.4.0"
/* Use accelerated SIMD routines. */
#define WITH_SIMD 1
/* Define to 1 if type `char' is unsigned and you are not using gcc. */
#ifndef __CHAR_UNSIGNED__
/* # undef __CHAR_UNSIGNED__ */
#endif
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* #undef inline */
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
-355
View File
@@ -1,355 +0,0 @@
/*
* jdmrg565.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1994-1996, Thomas G. Lane.
* libjpeg-turbo Modifications:
* Copyright (C) 2013, Linaro Limited.
* Copyright (C) 2014, D. R. Commander.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains code for merged upsampling/color conversion.
*/
INLINE
LOCAL(void)
h2v1_merged_upsample_565_internal (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf,
JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
register int y, cred, cgreen, cblue;
int cb, cr;
register JSAMPROW outptr;
JSAMPROW inptr0, inptr1, inptr2;
JDIMENSION col;
/* copy these pointers into registers if possible */
register JSAMPLE * range_limit = cinfo->sample_range_limit;
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
unsigned int r, g, b;
INT32 rgb;
SHIFT_TEMPS
inptr0 = input_buf[0][in_row_group_ctr];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
outptr = output_buf[0];
/* Loop for each pair of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 2 Y values and emit 2 pixels */
y = GETJSAMPLE(*inptr0++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr0++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr, rgb);
outptr += 4;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr0);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr = rgb;
}
}
INLINE
LOCAL(void)
h2v1_merged_upsample_565D_internal (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf,
JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
register int y, cred, cgreen, cblue;
int cb, cr;
register JSAMPROW outptr;
JSAMPROW inptr0, inptr1, inptr2;
JDIMENSION col;
/* copy these pointers into registers if possible */
register JSAMPLE * range_limit = cinfo->sample_range_limit;
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
INT32 d0 = dither_matrix[cinfo->output_scanline & DITHER_MASK];
unsigned int r, g, b;
INT32 rgb;
SHIFT_TEMPS
inptr0 = input_buf[0][in_row_group_ctr];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
outptr = output_buf[0];
/* Loop for each pair of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 2 Y values and emit 2 pixels */
y = GETJSAMPLE(*inptr0++);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
d0 = DITHER_ROTATE(d0);
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr0++);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
d0 = DITHER_ROTATE(d0);
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr, rgb);
outptr += 4;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr0);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr = rgb;
}
}
INLINE
LOCAL(void)
h2v2_merged_upsample_565_internal (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf,
JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
register int y, cred, cgreen, cblue;
int cb, cr;
register JSAMPROW outptr0, outptr1;
JSAMPROW inptr00, inptr01, inptr1, inptr2;
JDIMENSION col;
/* copy these pointers into registers if possible */
register JSAMPLE * range_limit = cinfo->sample_range_limit;
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
unsigned int r, g, b;
INT32 rgb;
SHIFT_TEMPS
inptr00 = input_buf[0][in_row_group_ctr * 2];
inptr01 = input_buf[0][in_row_group_ctr * 2 + 1];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
outptr0 = output_buf[0];
outptr1 = output_buf[1];
/* Loop for each group of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 4 Y values and emit 4 pixels */
y = GETJSAMPLE(*inptr00++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr00++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr0, rgb);
outptr0 += 4;
y = GETJSAMPLE(*inptr01++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr01++);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr1, rgb);
outptr1 += 4;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr00);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr0 = rgb;
y = GETJSAMPLE(*inptr01);
r = range_limit[y + cred];
g = range_limit[y + cgreen];
b = range_limit[y + cblue];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr1 = rgb;
}
}
INLINE
LOCAL(void)
h2v2_merged_upsample_565D_internal (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf,
JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
register int y, cred, cgreen, cblue;
int cb, cr;
register JSAMPROW outptr0, outptr1;
JSAMPROW inptr00, inptr01, inptr1, inptr2;
JDIMENSION col;
/* copy these pointers into registers if possible */
register JSAMPLE * range_limit = cinfo->sample_range_limit;
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
INT32 d0 = dither_matrix[cinfo->output_scanline & DITHER_MASK];
INT32 d1 = dither_matrix[(cinfo->output_scanline+1) & DITHER_MASK];
unsigned int r, g, b;
INT32 rgb;
SHIFT_TEMPS
inptr00 = input_buf[0][in_row_group_ctr*2];
inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
outptr0 = output_buf[0];
outptr1 = output_buf[1];
/* Loop for each group of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 4 Y values and emit 4 pixels */
y = GETJSAMPLE(*inptr00++);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
d0 = DITHER_ROTATE(d0);
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr00++);
r = range_limit[DITHER_565_R(y + cred, d1)];
g = range_limit[DITHER_565_G(y + cgreen, d1)];
b = range_limit[DITHER_565_B(y + cblue, d1)];
d1 = DITHER_ROTATE(d1);
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr0, rgb);
outptr0 += 4;
y = GETJSAMPLE(*inptr01++);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
d0 = DITHER_ROTATE(d0);
rgb = PACK_SHORT_565(r, g, b);
y = GETJSAMPLE(*inptr01++);
r = range_limit[DITHER_565_R(y + cred, d1)];
g = range_limit[DITHER_565_G(y + cgreen, d1)];
b = range_limit[DITHER_565_B(y + cblue, d1)];
d1 = DITHER_ROTATE(d1);
rgb = PACK_TWO_PIXELS(rgb, PACK_SHORT_565(r, g, b));
WRITE_TWO_PIXELS(outptr1, rgb);
outptr1 += 4;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr00);
r = range_limit[DITHER_565_R(y + cred, d0)];
g = range_limit[DITHER_565_G(y + cgreen, d0)];
b = range_limit[DITHER_565_B(y + cblue, d0)];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr0 = rgb;
y = GETJSAMPLE(*inptr01);
r = range_limit[DITHER_565_R(y + cred, d1)];
g = range_limit[DITHER_565_G(y + cgreen, d1)];
b = range_limit[DITHER_565_B(y + cblue, d1)];
rgb = PACK_SHORT_565(r, g, b);
*(INT16*)outptr1 = rgb;
}
}
Loaded 100 of 1141 files, more files were not shown because too many files have changed in this diff. Show more