Compare commits

..
29 Commits
Author SHA1 Message Date
seven332 d1cac3c1ac Merge branch 'axlecho-master' into dict 2016-04-14 20:49:03 +08:00
seven332 3924de80b7 Add DictActivity 2016-04-07 16:27:36 +08:00
seven332 dc1e327caa Add busy flag to protect dict db when importing 2016-04-05 23:16:08 +08:00
seven332 84808429cf Clean up 2016-04-05 16:45:37 +08:00
seven332 766c265cd6 Use utf4 table to speed up 2016-04-05 16:45:15 +08:00
seven332 4cce07e0aa Control import dict log with DEBUG variable 2016-04-05 15:23:03 +08:00
seven332 e56467dd4d Add missing icon 2016-04-05 15:21:32 +08:00
seven332 90c0d832d7 Add missing string 2016-04-05 15:21:05 +08:00
seven332 729bef38fb Improve import dict notification 2016-04-05 15:16:14 +08:00
seven332 59aab0498e Make import dict safer 2016-04-05 14:43:00 +08:00
seven332 863170e013 Fix typo and clean up Import Dict 2016-04-05 14:36:25 +08:00
seven332 e62b86bf7d Improve importing dict speed 2016-04-05 14:29:03 +08:00
seven332 0e018581a0 Fix cancel import dict Null error 2016-04-05 14:18:25 +08:00
seven332 a19f1e2d6d Improve dict import layout 2016-04-05 14:16:06 +08:00
seven332 987ef9ecf4 Improve dict import intent-filter and text 2016-04-05 13:58:16 +08:00
seven332 3de272ae5e Merge branch 'master' of https://github.com/axlecho/EhViewer into axlecho-master 2016-04-05 13:12:07 +08:00
axlecho 247bbec87d merge fix 2016-04-04 14:16:52 +08:00
axlecho e839c1e9b5 change the proxy 2016-04-04 14:01:16 +08:00
axlecho d756b0e451 delete test file 2016-04-04 13:47:57 +08:00
axlecho 663cb2b5b6 do the refactoring 2016-04-04 13:47:57 +08:00
axlecho 3e16c02e50 change the file associations 2016-04-04 13:47:57 +08:00
axlecho 80ca110702 add en pattern 2016-04-04 13:47:57 +08:00
axlecho 5f6a589dd8 when task done or abort,service will go to die 2016-04-04 13:47:57 +08:00
axlecho 342028eef1 add background notification 2016-04-04 13:47:57 +08:00
axlecho 0e96ee7eeb dict function ok 2016-04-04 13:47:57 +08:00
axlecho 3bd52e00d9 add async task for import dict 2016-04-04 13:47:57 +08:00
axlecho f612c912a7 add dict import service 2016-04-04 13:47:57 +08:00
axlecho 5dee677ce3 add dict test 2016-04-04 13:46:24 +08:00
axlecho 19ab3adc9a for my setting 2016-04-04 13:42:28 +08:00
739 changed files with 148804 additions and 17766 deletions

No files matched your search

-30
View File
@@ -1,30 +0,0 @@
感谢您提交 Issue,请在提交前仔细阅读以下信息。
请在阅读完毕后,删除这些文字,并写下对该 Issue 的描述。
若您能熟练使用现代标准汉语,请务必使用该语言描述 Issue。
Issue 的内容仅可为
* Bug 反馈
* 功能申请
若您希望得到使用指导(譬如如何删除快速搜索),请至 [G+ 社区](https://plus.google.com/u/1/communities/103823982034655188459) 发贴。若有其他问题,可在应用内找到开发者的邮箱地址,使用电子邮件与开发者交流。
若内容为 Bug 反馈,请先查看 [release 页面](https://github.com/seven332/EhViewer/releases),以帮助确认该 bug 是否存在于最新版中;同时应详细描述 bug 内容与重现方法,必要时可附加截图,但请确定截图符合风序良俗。
功能申请包括添加新功能与改进现有功能。
一个 Issue 只包含一个 Bug 反馈或者功能申请。若有多个需求,请提交多个 Issue。
尽量不提交重复的 Issue,可先进行搜索。对于重复的 Issue,开发者可能会直接关闭并添加 Duplicate 标签。
Thank you for taking the time to submit an issue. Before you proceed, please consider the following.
An issue can only be about:
* Bug Report
* Feature Request
If you need application instructions, please post your question in [G+ community](https://plus.google.com/u/1/communities/103823982034655188459). If you have other questions, please get the developer's email address in the application, and send him/her an email.
One issue one bug report or feature request.
-2
View File
@@ -6,5 +6,3 @@
*.iml
.idea
/captures
release
google-services.json
+12
View File
@@ -0,0 +1,12 @@
[submodule "yorozuya"]
path = yorozuya
url = https://github.com/seven332/Yorozuya
[submodule "easyrecyclerview"]
path = easyrecyclerview
url = https://github.com/seven332/EasyRecyclerView
[submodule "beerbelly"]
path = beerbelly
url = https://github.com/seven332/BeerBelly
[submodule "conaco"]
path = conaco
url = https://github.com/seven332/Conaco
+843 -4
View File
@@ -1,7 +1,846 @@
======================================================================
EhViewer
Copyright 2014-2016 Hippo Seven
======================================================================
An Unofficial E-Hentai Application for Android.
Copyright (C) 2014-2016 Hippo Seven
香风智乃是最可爱的女孩子。
chino kafuu is the cutest girl.
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.
======================================================================
Library ("Advanced RecyclerView")
======================================================================
Copyright (C) 2015 Haruki Hasegawa
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.
======================================================================
Library ("giflib")
======================================================================
The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
======================================================================
Library ("greenDAO")
======================================================================
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.
======================================================================
Library ("jsoup")
======================================================================
The MIT License
© 2009-2015, Jonathan Hedley <jonathan@hedley.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
======================================================================
Library ("libjpeg-turbo")
======================================================================
libjpeg-turbo Licenses
----------------------
libjpeg-turbo is covered by three compatible BSD-style open source licenses:
-- The IJG (Independent JPEG Group) License, which is listed in README
This license applies to the libjpeg API library and associated programs
(any code inherited from libjpeg, and any modifications to that code.)
-- The Modified (3-clause) BSD License, which is listed in turbojpeg.c
This license covers the TurboJPEG API library and associated programs.
-- The zlib License, which is listed in simd/jsimdext.inc
This license is a subset of the other two, and it covers the libjpeg-turbo
SIMD extensions.
Complying with the libjpeg-turbo Licenses
-----------------------------------------
This section provides a roll-up of the libjpeg-turbo licensing terms, to the
best of our understanding.
1. If you are distributing a modified version of the libjpeg-turbo source,
then:
a. You cannot alter or remove any existing copyright or license notices
from the source.
Origin: Clause 1 of the IJG License
Clause 1 of the Modified BSD License
Clauses 1 and 3 of the zlib License
b. You must add your own copyright notice to the header of each source
file you modified, so others can tell that you modified that file (if
there is not an existing copyright header in that file, then you can
simply add a notice stating that you modified the file.)
Origin: Clause 1 of the IJG License
Clause 2 of the zlib License
c. You must include the IJG README file, and you must not alter any of the
copyright or license text in that file.
Origin: Clause 1 of the IJG License
2. If you are distributing only libjpeg-turbo binaries without the source, or
if you are distributing an application that statically links with
libjpeg-turbo, then:
a. Your product documentation must include a message stating:
This software is based in part on the work of the Independent JPEG
Group.
Origin: Clause 2 of the IJG license
b. If your binary distribution includes or uses the TurboJPEG API, then
your product documentation must include the text of the Modified BSD
License.
Origin: Clause 2 of the Modified BSD License
3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
contributors thereof in advertising, publicity, etc.
Origin: IJG License
Clause 3 of the Modified BSD License
4. The IJG and The libjpeg-turbo Project do not warrant libjpeg-turbo to be
free of defects, nor do we accept any liability for undesirable
consequences resulting from your use of the software.
Origin: IJG License
Modified BSD License
zlib License
======================================================================
Library ("libpng" + "apng")
======================================================================
This copy of the libpng notices is provided for your convenience. In case of
any discrepancy between this copy and the notices in the file png.h that is
included in the libpng distribution, the latter shall prevail.
COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
If you modify libpng you may insert additional notices immediately following
this sentence.
This modified version of libpng code adds animated PNG support and is
released under the libpng license described below. The modifications are
Copyright (c) 2006-2007 Andrew Smith, Copyright (c) 2008-2015 Max Stepin,
and are delimited by "#ifdef PNG_APNG_SUPPORTED / #endif" directives
surrounding them in the modified libpng source files.
This code is released under the libpng license.
libpng versions 1.0.7, July 1, 2000, through 1.6.20, December 3, 2015, are
Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
derived from libpng-1.0.6, and are distributed according to the same
disclaimer and license as libpng-1.0.6 with the following individuals
added to the list of Contributing Authors:
Simon-Pierre Cadieux
Eric S. Raymond
Mans Rullgard
Cosmin Truta
Gilles Vollant
James Yu
and with the following additions to the disclaimer:
There is no warranty against interference with your enjoyment of the
library or against infringement. There is no warranty that our
efforts or the library will fulfill any of your particular purposes
or needs. This library is provided with all faults, and the entire
risk of satisfactory quality, performance, accuracy, and effort is with
the user.
libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
libpng-0.96, and are distributed according to the same disclaimer and
license as libpng-0.96, with the following individuals added to the list
of Contributing Authors:
Tom Lane
Glenn Randers-Pehrson
Willem van Schaik
libpng versions 0.89, June 1996, through 0.96, May 1997, are
Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
and are distributed according to the same disclaimer and license as
libpng-0.88, with the following individuals added to the list of
Contributing Authors:
John Bowler
Kevin Bracey
Sam Bushell
Magnus Holmgren
Greg Roelofs
Tom Tanner
libpng versions 0.5, May 1995, through 0.88, January 1996, are
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
For the purposes of this copyright and license, "Contributing Authors"
is defined as the following set of individuals:
Andreas Dilger
Dave Martindale
Guy Eric Schalnat
Paul Schmidt
Tim Wegner
The PNG Reference Library is supplied "AS IS". The Contributing Authors
and Group 42, Inc. disclaim all warranties, expressed or implied,
including, without limitation, the warranties of merchantability and of
fitness for any purpose. The Contributing Authors and Group 42, Inc.
assume no liability for direct, indirect, incidental, special, exemplary,
or consequential damages, which may result from the use of the PNG
Reference Library, even if advised of the possibility of such damage.
Permission is hereby granted to use, copy, modify, and distribute this
source code, or portions hereof, for any purpose, without fee, subject
to the following restrictions:
1. The origin of this source code must not be misrepresented.
2. Altered versions must be plainly marked as such and must not
be misrepresented as being the original source.
3. This Copyright notice may not be removed or altered from any
source or altered source distribution.
The Contributing Authors and Group 42, Inc. specifically permit, without
fee, and encourage the use of this source code as a component to
supporting the PNG file format in commercial products. If you use this
source code in a product, acknowledgment is not required but would be
appreciated.
END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
A "png_get_copyright" function is available, for convenient use in "about"
boxes and the like:
printf("%s", png_get_copyright(NULL));
Also, the PNG logo (in PNG format, of course) is supplied in the
files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
Libpng is OSI Certified Open Source Software. OSI Certified Open Source is
a certification mark of the Open Source Initiative. OSI has not addressed
the additional disclaimers inserted at version 1.0.7.
Glenn Randers-Pehrson
glennrp at users.sourceforge.net
December 3, 2015
======================================================================
Library ("OkHttp")
======================================================================
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.
======================================================================
Library ("roaster")
======================================================================
Forge Roaster
Copyright 2011-2015 Red Hat Inc. and/or its affiliates.
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
======================================================================
Library ("ShowcaseView")
======================================================================
Copyright Alex Curran (@amlcurran) © 2012-2014. All rights reserved.
This library is distributed under an Apache 2.0 License.
======================================================================
Font ("Slabo")
======================================================================
Copyright (c) 2013, Tiro Typeworks Ltd (www.tiro.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
======================================================================
Library ("TagSoup")
======================================================================
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.
-1840
View File
File diff suppressed because it is too large. Load diff
+16 -3
View File
@@ -1,5 +1,3 @@
[![Telegram](https://img.shields.io/badge/chat-Telegram-blue.svg)](https://t.me/ehviewer)
# EhViewer
![Icon](art/launcher_icon-web.png)
@@ -20,18 +18,34 @@ Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> git submodule update --init
> gradlew app:copyNotice
> gradlew daogenerator:executeDaoGenerator
> gradlew app:assembleDebug
Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ git submodule update --init
$ ./gradlew app:copyNotice
$ ./gradlew daogenerator:executeDaoGenerator
$ ./gradlew app:assembleDebug
生成的 apk 文件在 app\build\outputs\apk 目录下
The apk is in app\build\outputs\apk
**注意**:如果你遇到了下面这样的错误,需要添加系统变量 NDK_HOME 为 android NDK 路径
**Note**: If you get the error below, set NDK_HOME environment variable
* What went wrong:
A problem occurred evaluating project ':app'.
> assert ndkDir != null
| |
null false
# Thanks
@@ -41,7 +55,6 @@ Here is the libraries
- [AOSP](http://source.android.com/)
- [android-advancedrecyclerview](https://github.com/h6ah4i/android-advancedrecyclerview)
- [Apache Commons Lang](https://commons.apache.org/proper/commons-lang/)
- [apng](http://apng.sourceforge.net/)
- [giflib](http://giflib.sourceforge.net)
- [greenDAO](https://github.com/greenrobot/greenDAO)
+1 -1
View File
@@ -1,4 +1,4 @@
/src/main/assets/NOTICE.html
/src/main/assets/NOTICE
/build
/src/main/java-gen
manifest-merger-release-report.txt
+57 -79
View File
@@ -1,114 +1,92 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
apply plugin: 'android-chinese-string'
android {
compileSdkVersion 28
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 28
versionCode 89
versionName "1.3.2"
targetSdkVersion 23
versionCode 59
versionName "1.0.6"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es", "ja", "ko", "fr", "de"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
}
lintOptions {
disable 'MissingTranslation'
abortOnError true
checkReleaseBuilds true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.fileprovider"'
}
debug {
applicationIdSuffix ".debug"
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.debug.fileprovider"'
}
}
sourceSets {
main {
java.srcDirs += 'src/main/java-gen'
// Disable default NdkCompile task
jni.srcDirs = []
// Set new jni lib dir
jniLibs.srcDir 'src/main/libs'
}
}
}
task copyNotice(type: Copy) {
from '../NOTICE.html'
into './src/main/assets'
finalizedBy ":daogenerator:executeDaoGenerator"
}
// noinspection GroovyAssignabilityCheck
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
if (ndkDir == null) {
ndkDir = System.getenv('NDK_HOME')
}
assert ndkDir != null
def ndkBuilder
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
ndkBuilder = 'ndk-build.cmd'
} else {
ndkBuilder = 'ndk-build'
}
commandLine "$ndkDir/$ndkBuilder",
'-C', file('src/main/jni').absolutePath,
'-j', Runtime.runtime.availableProcessors()
}
tasks.withType(JavaCompile) {
task -> task.dependsOn copyNotice
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
clean {
delete file('src/main/assets/NOTICE.html').absolutePath
delete file('src/main/obj').absolutePath
delete file('src/main/libs').absolutePath
}
task copyNotice(type: Copy) {
from '../NOTICE'
into './src/main/assets'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:$supportLibrary"
implementation "com.android.support:cardview-v7:$supportLibrary"
implementation "com.android.support:design:$supportLibrary"
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.7'
implementation 'com.github.amlcurran.showcaseview:library:5.4.3'
implementation 'com.github.seven332:android-recaptcha:2bbb3459a8'
implementation 'com.github.seven332:android-resource:0.1.0'
implementation 'com.github.seven332:animator:0.1.0'
implementation 'com.github.seven332:beerbelly:0.1.4'
implementation 'com.github.seven332.commons-compress:android-lite:464e96d3b4'
implementation 'com.github.seven332:conaco:0.1.5-eh'
implementation 'com.github.seven332:drawerlayout:0.2.1'
implementation 'com.github.seven332:easyrecyclerview:0.1.1'
implementation 'com.github.seven332:glgallery:0.1.2'
implementation 'com.github.seven332:glview:0.1.0'
implementation 'com.github.seven332:glview-image:0.1.0'
implementation 'com.github.seven332:hotspot:0.1.0'
implementation 'com.github.seven332:image:0.1.12'
implementation 'com.github.seven332.junrar:android-lite:46ecc9630a'
implementation 'com.github.seven332:okhttp:3.5.0'
implementation 'com.github.seven332:refreshlayout:0.1.0'
implementation 'com.github.seven332:ripple:0.1.2'
implementation 'com.github.seven332:streampipe:0.1.0'
implementation 'com.github.seven332:tuxiang:0.1.2'
implementation 'com.github.seven332:unifile:a3571536be'
implementation 'com.github.seven332:yorozuya:0.1.2'
implementation 'com.github.seven332:yorozuya-thread:0.1.1'
implementation 'com.github.seven332:yorozuya-collect:0.1.4'
implementation 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.11.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
implementation 'org.greenrobot:greendao:2.2.1'
implementation 'org.jsoup:jsoup:1.11.3'
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:3.8'
testImplementation 'org.jooq:joor:0.9.6'
}
configurations.all {
resolutionStrategy {
force 'com.github.seven332:glgallery:c56b14c6fa'
force 'com.github.seven332:glview-image:4c744db'
force 'com.github.seven332:image:29266a3c7b'
exclude group: 'com.github.seven332', module: 'okhttp'
exclude group: 'com.squareup.okio', module: 'okio'
}
compile project(':beerbelly')
compile project(':conaco')
compile project(':easyrecyclerview')
compile project(':okhttp3')
compile project(':yorozuya')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.1'
compile 'com.github.anrwatchdog:anrwatchdog:1.2.0'
compile 'com.github.seven332:unifile:0.1.2'
compile 'com.github.seven332:drawerLayout:0.1.0'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.0'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.7'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.jsoup:jsoup:1.8.3'
}
Binary file not shown.
Binary file not shown.
-22
View File
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
-22
View File
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
-22
View File
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
-32
View File
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="start_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_start"
android:shortcutShortLabel="@string/download_start_all"
android:shortcutLongLabel="@string/download_start_all"
android:shortcutDisabledMessage="@string/download_start_all">
<intent
android:action="start_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity"/>
<categories android:name="android.shortcut.conversation" />
</shortcut>
<shortcut
android:shortcutId="stop_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_stop"
android:shortcutShortLabel="@string/download_stop_all"
android:shortcutLongLabel="@string/download_stop_all"
android:shortcutDisabledMessage="@string/download_stop_all">
<intent
android:action="stop_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
</shortcuts>
Executable → Regular
+81 -72
View File
@@ -22,22 +22,17 @@
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:name="com.hippo.ehviewer.EhApplication"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_scheme"
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config">
android:largeHeap="true">
<activity
android:name="com.hippo.ehviewer.ui.MainActivity"
@@ -51,17 +46,12 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<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="e-hentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
</intent-filter>
@@ -77,6 +67,68 @@
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter android:priority="-10">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:host="exhentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
<data android:pathPrefix="/g/"/>
</intent-filter>
</activity>
<activity-alias
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity2"
android:targetActivity="com.hippo.ehviewer.ui.DumpBrowsableActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter android:priority="-10">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:host="exhentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
<data android:pathPrefix="/s/"/>
</intent-filter>
</activity-alias>
<activity
android:name="com.hippo.ehviewer.ui.DictImportActivity"
android:configChanges="screenSize|uiMode"
android:icon="@mipmap/ic_launcher"
android:label="@string/dict_import"
android:launchMode="singleTask"
android:theme="@style/AppTheme.Dialog">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
</activity>
<activity
@@ -88,41 +140,17 @@
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="application/octet-stream"/>
<data android:mimeType="application/7z"/>
<data android:mimeType="application/rar"/>
<data android:mimeType="application/zip"/>
<data android:mimeType="application/x-7z-compressed"/>
<data android:mimeType="application/x-rar-compressed"/>
<data android:mimeType="application/x-zip-compressed"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
</activity>
@@ -130,72 +158,53 @@
<activity
android:name="com.hippo.ehviewer.ui.SettingsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Settings"/>
android:theme="@style/AppTheme"/>
<activity
android:name="com.hippo.ehviewer.ui.ExcludedLanguagesActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/excluded_languages"/>
<activity
android:name="com.hippo.ehviewer.ui.DirPickerActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/dir_picker"/>
<activity
android:name="com.hippo.ehviewer.ui.LicenseActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/license"/>
<activity
android:name="com.hippo.ehviewer.ui.DictActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/dict"/>
<activity
android:name="com.hippo.ehviewer.ui.FilterActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/filter"/>
<activity
android:name="com.hippo.ehviewer.ui.SetSecurityActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/set_pattern_protection"/>
<activity
android:name="com.hippo.ehviewer.ui.UConfigActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/u_config"/>
<activity
android:name="com.hippo.ehviewer.ui.HostsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/hosts"/>
<activity
android:name="com.hippo.ehviewer.shortcuts.ShortcutsActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:excludeFromRecents="true"
android:taskAffinity=""
android:launchMode="singleTask">
</activity>
<service
android:name="com.hippo.ehviewer.download.DownloadService"
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<provider
android:name="com.hippo.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
<service
android:name="com.hippo.dict.DictImportService"
android:icon="@mipmap/ic_launcher"
android:label="@string/import_dict_service">
</service>
</application>
</manifest>
@@ -37,7 +37,7 @@ import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
public class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
private AppCompatDelegate mDelegate;
@@ -1,108 +0,0 @@
/*
* Copyright 2018 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.app;
import android.content.Context;
import android.preference.PreferenceActivity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import java.util.ArrayList;
import java.util.List;
public abstract class PrettyPreferenceActivity extends AppCompatPreferenceActivity {
@Override
public void setListAdapter(ListAdapter adapter) {
int count = adapter.getCount();
List<PreferenceActivity.Header> headers = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
headers.add((PreferenceActivity.Header) adapter.getItem(i));
}
super.setListAdapter(new HeaderAdapter(this, headers, R.layout.item_preference_header, true));
}
private static class HeaderAdapter extends ArrayAdapter<PreferenceActivity.Header> {
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
}
private LayoutInflater mInflater;
private int mLayoutResId;
private boolean mRemoveIconIfEmpty;
private HeaderAdapter(Context context, List<PreferenceActivity.Header> objects, int layoutResId,
boolean removeIconBehavior) {
super(context, 0, objects);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayoutResId = layoutResId;
mRemoveIconIfEmpty = removeIconBehavior;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
HeaderViewHolder holder;
View view;
if (convertView == null) {
view = mInflater.inflate(mLayoutResId, parent, false);
holder = new HeaderViewHolder();
holder.icon = view.findViewById(android.R.id.icon);
holder.title = view.findViewById(android.R.id.title);
holder.summary = view.findViewById(android.R.id.summary);
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
PreferenceActivity.Header header = getItem(position);
if (mRemoveIconIfEmpty) {
if (header.iconRes == 0) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
holder.icon.setImageResource(header.iconRes);
}
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
return view;
}
}
}
@@ -1,61 +0,0 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import java.util.Locale;
public class ContextLocalWrapper extends ContextWrapper {
public ContextLocalWrapper(Context base) {
super(base);
}
public static ContextLocalWrapper wrap(Context context, Locale newLocale) {
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(newLocale);
LocaleList localeList = new LocaleList(newLocale);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = newLocale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return new ContextLocalWrapper(context);
}
}
@@ -1,816 +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.content;
import android.content.ClipData;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
* instead of a <code>file:///</code> {@link Uri}.
* <p>
* A content URI allows you to grant read and write access using
* temporary access permissions. When you create an {@link Intent} containing
* a content URI, in order to send the content URI
* to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
* permissions. These permissions are available to the client app for as long as the stack for
* a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
* {@link android.app.Service}, the permissions are available as long as the
* {@link android.app.Service} is running.
* <p>
* In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
* file system permissions of the underlying file. The permissions you provide become available to
* <em>any</em> app, and remain in effect until you change them. This level of access is
* fundamentally insecure.
* <p>
* The increased level of file access security offered by a content URI
* makes FileProvider a key part of Android's security infrastructure.
* <p>
* This overview of FileProvider includes the following topics:
* </p>
* <ol>
* <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
* <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
* <li><a href="#GetUri">Retrieving the Content URI for a File</li>
* <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
* <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
* </ol>
* <h3 id="ProviderDefinition">Defining a FileProvider</h3>
* <p>
* Since the default functionality of FileProvider includes content URI generation for files, you
* don't need to define a subclass in code. Instead, you can include a FileProvider in your app
* by specifying it entirely in XML. To specify the FileProvider component itself, add a
* <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
* element to your app manifest. Set the <code>android:name</code> attribute to
* <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
* attribute to a URI authority based on a domain you control; for example, if you control the
* domain <code>mydomain.com</code> you should use the authority
* <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
* <code>false</code>; the FileProvider does not need to be public. Set the
* <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
* >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
* to grant temporary access to files. For example:
* <pre class="prettyprint">
*&lt;manifest&gt;
* ...
* &lt;application&gt;
* ...
* &lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* ...
* &lt;/provider&gt;
* ...
* &lt;/application&gt;
*&lt;/manifest&gt;</pre>
* <p>
* If you want to override any of the default behavior of FileProvider methods, extend
* the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
* attribute of the <code>&lt;provider&gt;</code> element.
* <h3 id="SpecifyFiles">Specifying Available Files</h3>
* A FileProvider can only generate a content URI for files in directories that you specify
* beforehand. To specify a directory, specify the its storage area and path in XML, using child
* elements of the <code>&lt;paths&gt;</code> element.
* For example, the following <code>paths</code> element tells FileProvider that you intend to
* request content URIs for the <code>images/</code> subdirectory of your private file area.
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* ...
*&lt;/paths&gt;
*</pre>
* <p>
* The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements:
* </p>
* <dl>
* <dt>
* <pre class="prettyprint">
*&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the <code>files/</code> subdirectory of your app's internal storage
* area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
* Context.getFilesDir()}.
* </dd>
* <dt>
* <pre>
*&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* <dt>
* <dd>
* Represents files in the cache subdirectory of your app's internal storage area. The root path
* of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
* getCacheDir()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of the external storage area. The root path of this subdirectory
* is the same as the value returned by
* {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external storage area. The root path of this
* subdirectory is the same as the value returned by
* {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external cache area. The root path of this
* subdirectory is the same as the value returned by
* {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}.
* </dd>
* </dl>
* <p>
* These child elements all use the same attributes:
* </p>
* <dl>
* <dt>
* <code>name="<i>name</i>"</code>
* </dt>
* <dd>
* A URI path segment. To enforce security, this value hides the name of the subdirectory
* you're sharing. The subdirectory name for this value is contained in the
* <code>path</code> attribute.
* </dd>
* <dt>
* <code>path="<i>path</i>"</code>
* </dt>
* <dd>
* The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
* segment, the <code>path</code> value is an actual subdirectory name. Notice that the
* value refers to a <b>subdirectory</b>, not an individual file or files. You can't
* share a single file by its file name, nor can you specify a subset of files using
* wildcards.
* </dd>
* </dl>
* <p>
* You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains
* files for which you want content URIs. For example, these XML elements specify two directories:
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* &lt;files-path name="my_docs" path="docs/"/&gt;
*&lt;/paths&gt;
*</pre>
* <p>
* Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project.
* For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
* To link this file to the FileProvider, add a
* <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element
* as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the
* <code>&lt;meta-data&gt;</code> element's "android:name" attribute to
* <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
* to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
* extension). For example:
* <pre class="prettyprint">
*&lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* &lt;meta-data
* android:name="android.support.FILE_PROVIDER_PATHS"
* android:resource="&#64;xml/file_paths" /&gt;
*&lt;/provider&gt;
*</pre>
* <h3 id="GetUri">Generating the Content URI for a File</h3>
* <p>
* To share a file with another app using a content URI, your app has to generate the content URI.
* To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
* to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
* {@link android.content.Intent}. The client app that receives the content URI can open the file
* and access its contents by calling
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
* <p>
* For example, suppose your app is offering files to other apps with a FileProvider that has the
* authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
* <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
* add the following code:
* <pre class="prettyprint">
*File imagePath = new File(Context.getFilesDir(), "images");
*File newFile = new File(imagePath, "default_image.jpg");
*Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
*</pre>
* As a result of the previous snippet,
* {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
* <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
* <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
* To grant an access permission to a content URI returned from
* {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
* <ul>
* <li>
* Call the method
* {@link Context#grantUriPermission(String, Uri, int)
* Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
* {@link Uri}, using the desired mode flags. This grants temporary access permission for the
* content URI to the specified package, according to the value of the
* the <code>mode_flags</code> parameter, which you can set to
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
* or both. The permission remains in effect until you revoke it by calling
* {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
* reboots.
* </li>
* <li>
* Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
* </li>
* <li>
* Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
* </li>
* <li>
* Finally, send the {@link Intent} to
* another app. Most often, you do this by calling
* {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
* <p>
* Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
* {@link android.app.Activity} is active. When the stack finishes, the permissions are
* automatically removed. Permissions granted to one {@link android.app.Activity} in a client
* app are automatically extended to other components of that app.
* </p>
* </li>
* </ul>
* <h3 id="ServeUri">Serving a Content URI to Another App</h3>
* <p>
* There are a variety of ways to serve the content URI for a file to a client app. One common way
* is for the client app to start your app by calling
* {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
* which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
* In response, your app can immediately return a content URI to the client app or present a user
* interface that allows the user to pick a file. In the latter case, once the user picks the file
* your app can return its content URI. In both cases, your app returns the content URI in an
* {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
* </p>
* <p>
* You can also put the content URI in a {@link android.content.ClipData} object and then add the
* object to an {@link Intent} you send to a client app. To do this, call
* {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
* add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
* content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
* to set temporary access permissions, the same permissions are applied to all of the content
* URIs.
* </p>
* <p class="note">
* <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
* only available in platform version 16 (Android 4.1) and later. If you want to maintain
* compatibility with previous versions, you should send one content URI at a time in the
* {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
* {@link Intent#setData setData()}.
* </p>
* <h3 id="">More Information</h3>
* <p>
* To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p>
*/
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = {
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATA
};
private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path";
private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path";
private static final String TAG_EXTERNAL_FILES = "external-files-path";
private static final String TAG_EXTERNAL_CACHE = "external-cache-path";
private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy;
/**
* The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider.
*/
@Override
public boolean onCreate() {
return true;
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
* {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
* <ul>
* <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (MediaStore.MediaColumns.SIZE.equals(col)) {
cols[i] = MediaStore.MediaColumns.SIZE;
values[i++] = file.length();
} else if (MediaStore.MediaColumns.DATA.equals(col)) {
cols[i] = MediaStore.MediaColumns.DATA;
values[i++] = file.getPath();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
/**
* Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
*
* @param uri A content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @return If the associated file has an extension, the MIME type associated with that
* extension; otherwise <code>application/octet-stream</code>.
*/
@Override
public String getType(Uri uri) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts");
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates");
}
/**
* Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
* method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
*
* @param uri A content URI for a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param selection Ignored. Set to {@code null}.
* @param selectionArgs Ignored. Set to {@code null}.
* @return 1 if the delete succeeds; otherwise, 0.
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0;
}
/**
* By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
* {@link Uri}. To get the {@link ParcelFileDescriptor}, call
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor}.
*
* To override this method, you must provide your own subclass of FileProvider.
*
* @param uri A content URI associated with a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
* write access, or "rwt" for read and write access that truncates any existing file.
* @return A new {@link ParcelFileDescriptor} with which you can access the file.
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode);
}
/**
* Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache.
*/
private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = DEVICE_ROOT;
} else if (TAG_FILES_PATH.equals(tag)) {
target = context.getFilesDir();
} else if (TAG_CACHE_PATH.equals(tag)) {
target = context.getCacheDir();
} else if (TAG_EXTERNAL.equals(tag)) {
target = Environment.getExternalStorageDirectory();
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
if (externalFilesDirs.length > 0) {
target = externalFilesDirs[0];
}
} else if (TAG_EXTERNAL_CACHE.equals(tag)) {
File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
if (externalCacheDirs.length > 0) {
target = externalCacheDirs[0];
}
}
if (target != null) {
strat.addRoot(name, buildPath(target, path));
}
}
}
return strat;
}
/**
* Strategy for mapping between {@link File} and {@link Uri}.
* <p>
* Strategies must be symmetric so that mapping a {@link File} to a
* {@link Uri} and then back to a {@link File} points at the original
* target.
* <p>
* Strategies must remain consistent across app launches, and not rely on
* dynamic state. This ensures that any generated {@link Uri} can still be
* resolved if your process is killed and later restarted.
*
* @see SimplePathStrategy
*/
interface PathStrategy {
/**
* Return a {@link Uri} that represents the given {@link File}.
*/
public Uri getUriForFile(File file);
/**
* Return a {@link File} that represents the given {@link Uri}.
*/
public File getFileForUri(Uri uri);
}
/**
* Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try
* accessing files outside the configured roots.
* <p>
* For example, if configured with
* {@code addRoot("myfiles", context.getFilesDir())}, then
* {@code context.getFileStreamPath("foo.txt")} would map to
* {@code content://myauthority/myfiles/foo.txt}.
*/
static class SimplePathStrategy implements PathStrategy {
private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) {
mAuthority = authority;
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static File buildPath(File base, String... segments) {
File cur = base;
for (String segment : segments) {
if (segment != null) {
cur = new File(cur, segment);
}
}
return cur;
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
}
@@ -1,90 +0,0 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.app.Activity;
import android.os.Bundle;
import com.hippo.scene.SceneApplication;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public abstract class RecordingApplication extends SceneApplication {
private List<WeakReference<Activity>> list = new LinkedList<>();
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
list.add(new java.lang.ref.WeakReference<>(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
Iterator<WeakReference<Activity>> iterator = list.iterator();
while (iterator.hasNext()) {
WeakReference<Activity> reference = iterator.next();
Activity a = reference.get();
// Remove current activity and null
if (a == null || a == activity) {
iterator.remove();
}
}
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
});
}
public void recreate() {
// Copy list
ArrayList<Activity> listCopy = new ArrayList<>(list.size());
for (WeakReference<Activity> reference: list) {
Activity activity = reference.get();
if (activity == null) continue;
listCopy.add(activity);
}
// Finish all activities
for (int i = listCopy.size() - 1; i >= 0; --i) {
listCopy.get(i).recreate();
}
}
}
@@ -1,130 +0,0 @@
/*
* Copyright 2017 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.database;
/*
* Created by Hippo on 2017/9/3.
*/
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MSQLiteBuilder {
public static final String COLUMN_ID = "_id";
private static final Map<Class, String> JAVA_TYPE_TO_SQLITE_TYPE = new HashMap<>();
static {
JAVA_TYPE_TO_SQLITE_TYPE.put(boolean.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(byte.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(short.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(int.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(long.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(float.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(double.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(String.class, "TEXT");
}
private static String javaTypeToSQLiteType(Class clazz) {
String type = JAVA_TYPE_TO_SQLITE_TYPE.get(clazz);
if (type == null) {
throw new IllegalStateException("Unknown type: " + clazz);
}
return type;
}
private int version = 0;
private List<String> statements;
private SparseArray<List<String>> statementsMap = new SparseArray<>();
/**
* Bump database version.
*/
public MSQLiteBuilder version(int version) {
if (version <= this.version) {
throw new IllegalStateException("New version must be bigger than current version. "
+ "current version: " + this.version + ", new version: " + version + ".");
}
this.version = version;
this.statements = new ArrayList<>();
this.statementsMap.put(version, this.statements);
return this;
}
/**
* Creates a table with int {@link #COLUMN_ID} primary key.
*/
public MSQLiteBuilder createTable(String table) {
return createTable(table, COLUMN_ID, int.class);
}
/**
* Creates a table.
*/
public MSQLiteBuilder createTable(String table, String column, Class clazz) {
return statement("CREATE TABLE " + table + " (" + column + " " + javaTypeToSQLiteType(clazz) + " PRIMARY KEY);");
}
/**
* Drops a table.
*/
public MSQLiteBuilder dropTable(String table) {
return statement("DROP TABLE " + table + ";");
}
/**
* Inserts a column to the table.
*/
public MSQLiteBuilder insertColumn(String table, String column, Class clazz) {
return statement("ALTER TABLE " + table + " ADD COLUMN " + column + " " + javaTypeToSQLiteType(clazz) + ";");
}
/**
* Add a statement.
*/
public MSQLiteBuilder statement(String statement) {
if (version == 0 || statements == null) {
throw new IllegalStateException("Call version() first!");
}
statements.add(statement);
return this;
}
/**
* Build a SQLiteOpenHelper from it.
*/
public SQLiteOpenHelper build(Context context, String name, int version) {
return new MSQLiteOpenHelper(context, name, version, this);
}
List<String> getStatements(int oldVersion, int newVersion) {
List<String> result = new ArrayList<>();
for (int i = oldVersion + 1; i <= newVersion; ++i) {
List<String> list = statementsMap.get(i);
if (list != null) {
result.addAll(list);
}
}
return result;
}
}
@@ -1,56 +0,0 @@
/*
* Copyright 2017 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.database;
/*
* Created by Hippo on 2017/9/4.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.hippo.util.SqlUtils;
class MSQLiteOpenHelper extends SQLiteOpenHelper {
private final int version;
private final MSQLiteBuilder builder;
public MSQLiteOpenHelper(Context context, String name, int version, MSQLiteBuilder builder) {
super(context, name, null, version);
this.version = version;
this.builder = builder;
}
@Override
public void onCreate(SQLiteDatabase db) {
onUpgrade(db, 0, version);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String command : builder.getStatements(oldVersion, newVersion)) {
db.execSQL(command);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
SqlUtils.dropAllTable(db);
onCreate(db);
}
}
@@ -0,0 +1,240 @@
package com.hippo.dict;
/*
* 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.
*/
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.text.TextUtils;
import android.util.JsonReader;
import android.util.Log;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.ArrayUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class DictDatabase {
private static final String TAG = DictDatabase.class.getSimpleName();
private static final boolean DEBUG = false;
public static final String COLUMN_PARENT = "parent";
public static final String COLUMN_DATA = "data";
public static final String COLUMN_DICT = "dict_name";
private static final String DATABASE_NAME = "dict_database.db";
private static final String TABLE_DICT = "dictionary";
private static final String SEPARATOR = "@@@";
private final SQLiteDatabase mDatabase;
private static DictDatabase sInstance;
private String mDictName;
private boolean mAbortFlag = false;
private final AtomicBoolean mBusyFlag = new AtomicBoolean();
public static DictDatabase getInstance(Context context) {
if (sInstance == null) {
sInstance = new DictDatabase(context.getApplicationContext());
}
return sInstance;
}
private DictDatabase(Context context) {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
mDatabase = databaseHelper.getWritableDatabase();
}
public String[] getSuggestions(String prefix) {
if (TextUtils.isEmpty(prefix) || mBusyFlag.get()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
String command = "SELECT * FROM " + TABLE_DICT + " WHERE " + COLUMN_DATA +
" MATCH '" + SqlUtils.sqlEscapeString(prefix) + "' LIMIT 5;";
Cursor cursor = mDatabase.rawQuery(command, null);
Set<String> queryList = new HashSet<>();
int queryIndex = cursor.getColumnIndex(COLUMN_DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String datum = cursor.getString(queryIndex);
String data[] = datum.split(SEPARATOR);
for (String item : data) {
if (TextUtils.isEmpty(item) || datum.equals(prefix)) {
continue;
}
queryList.add(item);
}
cursor.moveToNext();
}
}
cursor.close();
return queryList.toArray(new String[queryList.size()]);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener) throws IOException, URISyntaxException {
mAbortFlag = false;
int itemNum = -1;
InputStream inputStream = context.getContentResolver().openInputStream(dictUri);
if (null == inputStream) {
throw new FileNotFoundException("Can't find " + dictUri);
}
JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String field = jsonReader.nextName();
if (field.equals("dict")) {
mDictName = jsonReader.nextString();
if (DEBUG) {
Log.d(TAG, "[importDict] parse the dict name -- " + mDictName);
}
} else if (field.equals("num")) {
if (TextUtils.isEmpty(mDictName)) {
break;
}
itemNum = jsonReader.nextInt();
listener.processTotal(itemNum);
if (DEBUG) {
Log.d(TAG, "[importDict] parse the item number -- " + itemNum);
}
} else if (field.equals("data")) {
if (TextUtils.isEmpty(mDictName) || itemNum <= 0) {
break;
}
deleteDict(mDictName);
parseData(jsonReader, listener);
}
}
jsonReader.endObject();
jsonReader.close();
listener.processComplete();
}
public void deleteDict(String dict) {
if (mBusyFlag.get()) {
return;
}
if (DEBUG) {
Log.d(TAG, "[deleteDict] dict:" + dict);
}
mDatabase.delete(TABLE_DICT, COLUMN_DICT + "=?", new String[]{dict});
}
public void importAbort() {
if (DEBUG) {
Log.d(TAG, "[importAbort] set mAbortFlag true");
}
mAbortFlag = true;
}
/**
* Builds the database. This version has extra support for using the version field
* as a mode flags field, and configures the database columns depending on the mode bits
* (features) requested by the extending class.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE VIRTUAL TABLE " + TABLE_DICT + " USING fts4 (" +
COLUMN_DATA +
", " + COLUMN_PARENT +
", " + COLUMN_DICT +
", tokenize=icu th_ZH" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DICT);
onCreate(db);
}
}
private void parseData(JsonReader jsonReader, final DictImportService.ProcessListener listener) throws IOException {
mBusyFlag.lazySet(true);
int process = 1;
SQLiteStatement insStmt = mDatabase.compileStatement("INSERT INTO " + TABLE_DICT + " VALUES (?, ?, ?);");
mDatabase.beginTransaction();
jsonReader.beginArray();
try {
while (jsonReader.hasNext()) {
synchronized (this) {
if (mAbortFlag) {
if (DEBUG) {
Log.d(TAG, "[parseData] import abort, delete the dict -- " + mDictName);
}
deleteDict(mDictName);
return;
}
}
parseSingleData(jsonReader, insStmt);
listener.process(process);
process++;
}
jsonReader.endArray();
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
mBusyFlag.lazySet(false);
}
}
private void parseSingleData(JsonReader jsonReader, SQLiteStatement insStmt) throws IOException {
StringBuilder sb = new StringBuilder();
String parent = "";
sb.append(SEPARATOR);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
String content = jsonReader.nextString();
if (name.equals("parent")) {
parent = content;
} else {
sb.append(content);
sb.append(SEPARATOR);
}
}
jsonReader.endObject();
if (DEBUG) {
Log.d(TAG, "[parseSingleData] item:" + parent + " " + sb.toString());
}
insStmt.bindString(1, sb.toString());
insStmt.bindString(2, parent);
insStmt.bindString(3, mDictName);
insStmt.executeInsert();
}
}
@@ -0,0 +1,218 @@
package com.hippo.dict;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.hippo.util.TextUrl;
import java.util.ArrayList;
import java.util.List;
public class DictImportService extends Service {
private static final String TAG = "DictImportService";
private static final boolean DEBUG = false;
private DictManager mDictManager;
private final List<ProcessListener> mListeners = new ArrayList<>();
private ProcessListener mDictProcessListener;
private AsyncTask mImportAsyncTask;
private DictNotification mDictNotification;
// current task information
private int mItemNum;
private Uri mDictUri;
private boolean mRunningFlag = false;
public DictImportService() {}
private final Binder serviceBinder = new DictImportServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onCreate() {
super.onCreate();
mDictManager = new DictManager(this);
mDictNotification = new DictNotification(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public interface ProcessListener {
void process(int progress);
void processTotal(int total);
void processComplete();
}
public class DictImportServiceBinder extends Binder {
public DictImportService getService() {
return DictImportService.this;
}
}
public void importDict(Uri dictUri) {
if (dictUri == null) {
// TODO error tip
if (DEBUG) {
Log.e(TAG, "[importDict] dictUri is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[importDict] start import async task");
}
mImportAsyncTask = new ImportAsyncTask(dictUri).execute();
}
public void abortImport() {
if (mImportAsyncTask == null) {
if (DEBUG) {
Log.e(TAG, "[abortImport] mImportAsyncTask is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[abortImport] import abort");
}
// fixme
// this i just set a flag to abort the parse thread,it may cause a exception
// it there may be a elegant way to shut the worker thread down
mDictManager.importAbort();
// just for service go die
mImportAsyncTask.cancel(true);
}
public Uri getUri() {
return mDictUri;
}
public int getItemNum() {
return mItemNum;
}
public boolean isRunning() {
return mRunningFlag;
}
public void setOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.add(onProgressListener);
mListeners.remove(mDictNotification.mNotificationListener);
mDictNotification.stopNotify();
}
}
public void removeOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.remove(onProgressListener);
}
// if there is no listener in listener list,we is in the background mostly
// we post the process progress information to a notification
if (mListeners.size() == 0 && null != mDictUri) {
mDictNotification.setMax(mItemNum);
mDictNotification.setFileName(TextUrl.getFileName(mDictUri.toString()));
mListeners.add(mDictNotification.mNotificationListener);
}
}
class ImportAsyncTask extends AsyncTask<Void, Integer, Void> {
public ImportAsyncTask(Uri dictUri) {
mDictUri = dictUri;
mRunningFlag = true;
mDictProcessListener = new ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.d(TAG, "[process] progress:" + progress);
}
publishProgress(progress);
}
@Override
public void processTotal(int total) {
if (DEBUG) {
Log.d(TAG, "process total " + total);
}
mItemNum = total;
for (ProcessListener listener : mListeners) {
listener.processTotal(total);
}
}
@Override
public void processComplete() {
// we don't do any thing here,let async task handle this
if (DEBUG) {
Log.d(TAG, "processComplete");
}
}
};
}
@Override
protected Void doInBackground(Void... voids) {
try {
mDictManager.importDict(DictImportService.this, mDictUri, mDictProcessListener);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (DEBUG) {
Log.d(TAG, "[onProgressUpdate] process item " + progress[0]);
}
for (ProcessListener listener : mListeners) {
listener.process(progress[0]);
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for (ProcessListener listener : mListeners) {
listener.processComplete();
}
mRunningFlag = false;
DictImportService.this.goDie();
}
@Override
protected void onCancelled() {
super.onCancelled();
DictImportService.this.goDie();
}
}
public void goDie() {
if (DEBUG) {
Log.d(TAG, "[goDie] task done or abort,go to die");
}
this.stopSelf();
}
}
@@ -0,0 +1,57 @@
package com.hippo.dict;
import android.content.Context;
import android.net.Uri;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO Singleton
// TODO Add add-dict callback for DictActivity
public class DictManager {
// pattern for language
private static final String enRegEx = "^[0-9a-zA-Z_\\s]+$";
// private static final String zhRegEx = "";
private final DictDatabase mDictDatabase;
public DictManager(Context context) {
mDictDatabase = DictDatabase.getInstance(context);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener)
throws IOException, URISyntaxException {
mDictDatabase.importDict(context, dictUri, listener);
}
public void deletDict(String dict) {
mDictDatabase.deleteDict(dict);
}
public String[] getSuggestions(String prefix) {
List<String> result = new ArrayList<>();
String databaseResult[] = mDictDatabase.getSuggestions(prefix);
for (String s : databaseResult) {
if (filter(s)) {
result.add(s);
}
}
return result.toArray(new String[result.size()]);
}
public void importAbort() {
mDictDatabase.importAbort();
}
public boolean filter(String item) {
// return true;
Pattern en = Pattern.compile(enRegEx);
Matcher m = en.matcher(item);
return m.matches();
}
}
@@ -0,0 +1,100 @@
package com.hippo.dict;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.support.v7.app.NotificationCompat;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.DictImportActivity;
import com.hippo.ehviewer.ui.MainActivity;
public class DictNotification {
private final Context mContext;
private final NotificationManager mNotifyManager;
private final NotificationCompat.Builder mBuilder;
private int mMax = 100;
private final int mId = 1;
private long mLastUpdateTime;
private final PendingIntent mImportIntent;
private final PendingIntent mDoneIntent;
public DictNotification(Context context) {
mContext = context;
mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(mContext);
mImportIntent = PendingIntent.getActivity(context, 0, new Intent(context, DictImportActivity.class), 0);
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
mDoneIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentTitle(mContext.getResources().getString(R.string.dict_import))
.setContentText("0/" + mMax)
.setSmallIcon(R.drawable.ic_stat_import)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setContentIntent(mImportIntent)
.setOngoing(true);
}
public DictImportService.ProcessListener mNotificationListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
DictNotification.this.notify(progress);
}
@Override
public void processTotal(int total) {
// this may useless
mMax = total;
}
@Override
public void processComplete() {
DictNotification.this.notifyDone();
}
};
public void setMax(int max) {
mMax = max;
mBuilder.setContentText("0/" + mMax);
}
public void setFileName(String fileName) {
mBuilder.setContentTitle(mContext.getString(R.string.dict_import) + " " + fileName);
}
public void notify(int progress) {
// Avoid update frequently
long now = SystemClock.currentThreadTimeMillis();
if (now - mLastUpdateTime < 500L) {
return;
}
mLastUpdateTime = now;
mBuilder.setContentIntent(mImportIntent);
mBuilder.setProgress(mMax, progress, false);
mBuilder.setContentText(progress + "/" + mMax);
mNotifyManager.notify(mId, mBuilder.build());
}
public void notifyDone() {
mBuilder.setContentIntent(mDoneIntent);
mBuilder.setContentTitle(mContext.getString(R.string.dict_import_successfully));
mBuilder.setContentText(mMax + "/" + mMax);
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mNotifyManager.notify(mId, mBuilder.build());
}
public void stopNotify() {
mNotifyManager.cancel(mId);
}
}
@@ -46,13 +46,13 @@ public class AddDeleteDrawable extends Drawable {
/**
* @param context used to get the configuration for the drawable from
*/
public AddDeleteDrawable(Context context, int color) {
public AddDeleteDrawable(Context context) {
Resources resources = context.getResources();
mSize = resources.getDimensionPixelSize(R.dimen.add_size);
float barThickness = Math.round(resources.getDimension(R.dimen.add_thickness));
mPaint.setColor(color);
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.BUTT);
@@ -1,180 +0,0 @@
/*
* Copyright 2018 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.drawable;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.graphics.drawable.DrawableCompat;
public class DrawableWrapper extends Drawable implements Drawable.Callback {
private Drawable mDrawable;
public DrawableWrapper(Drawable drawable) {
this.setWrappedDrawable(drawable);
}
public void draw(@NonNull Canvas canvas) {
this.mDrawable.draw(canvas);
}
protected void onBoundsChange(Rect bounds) {
this.mDrawable.setBounds(bounds);
}
public void setChangingConfigurations(int configs) {
this.mDrawable.setChangingConfigurations(configs);
}
public int getChangingConfigurations() {
return this.mDrawable.getChangingConfigurations();
}
public void setDither(boolean dither) {
this.mDrawable.setDither(dither);
}
public void setFilterBitmap(boolean filter) {
this.mDrawable.setFilterBitmap(filter);
}
public void setAlpha(int alpha) {
this.mDrawable.setAlpha(alpha);
}
public void setColorFilter(ColorFilter cf) {
this.mDrawable.setColorFilter(cf);
}
public boolean isStateful() {
return this.mDrawable.isStateful();
}
public boolean setState(@NonNull int[] stateSet) {
return this.mDrawable.setState(stateSet);
}
@NonNull
public int[] getState() {
return this.mDrawable.getState();
}
public void jumpToCurrentState() {
this.mDrawable.jumpToCurrentState();
}
@NonNull
public Drawable getCurrent() {
return this.mDrawable.getCurrent();
}
public boolean setVisible(boolean visible, boolean restart) {
return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);
}
public int getOpacity() {
return this.mDrawable.getOpacity();
}
public Region getTransparentRegion() {
return this.mDrawable.getTransparentRegion();
}
public int getIntrinsicWidth() {
return this.mDrawable.getIntrinsicWidth();
}
public int getIntrinsicHeight() {
return this.mDrawable.getIntrinsicHeight();
}
public int getMinimumWidth() {
return this.mDrawable.getMinimumWidth();
}
public int getMinimumHeight() {
return this.mDrawable.getMinimumHeight();
}
public boolean getPadding(@NonNull Rect padding) {
return this.mDrawable.getPadding(padding);
}
public void invalidateDrawable(@NonNull Drawable who) {
this.invalidateSelf();
}
public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
this.scheduleSelf(what, when);
}
public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
this.unscheduleSelf(what);
}
protected boolean onLevelChange(int level) {
return this.mDrawable.setLevel(level);
}
public void setAutoMirrored(boolean mirrored) {
DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);
}
public boolean isAutoMirrored() {
return DrawableCompat.isAutoMirrored(this.mDrawable);
}
public void setTint(int tint) {
DrawableCompat.setTint(this.mDrawable, tint);
}
public void setTintList(ColorStateList tint) {
DrawableCompat.setTintList(this.mDrawable, tint);
}
public void setTintMode(@NonNull PorterDuff.Mode tintMode) {
DrawableCompat.setTintMode(this.mDrawable, tintMode);
}
public void setHotspot(float x, float y) {
DrawableCompat.setHotspot(this.mDrawable, x, y);
}
public void setHotspotBounds(int left, int top, int right, int bottom) {
DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);
}
public Drawable getWrappedDrawable() {
return this.mDrawable;
}
public void setWrappedDrawable(Drawable drawable) {
if (this.mDrawable != null) {
this.mDrawable.setCallback(null);
}
this.mDrawable = drawable;
if (drawable != null) {
drawable.setCallback(this);
}
}
}
@@ -28,7 +28,6 @@ import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.MathUtils;
@@ -67,11 +66,11 @@ public class DrawerArrowDrawable extends Drawable {
/**
* @param context used to get the configuration for the drawable from
*/
public DrawerArrowDrawable(Context context, int color) {
public DrawerArrowDrawable(Context context) {
Resources resources = context.getResources();
mPaint.setAntiAlias(true);
mPaint.setColor(color);
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mSize = resources.getDimensionPixelSize(R.dimen.dad_drawable_size);
// round this because having this floating may cause bad measurements
mBarSize = Math.round(resources.getDimension(R.dimen.dad_bar_size));
@@ -145,11 +144,6 @@ public class DrawerArrowDrawable extends Drawable {
canvas.restore();
}
public void setColor(@ColorInt int color) {
mPaint.setColor(color);
invalidateSelf();
}
@Override
public void setAlpha(int i) {
mPaint.setAlpha(i);
@@ -20,12 +20,10 @@ import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.drawable.DrawableWrapper;
import com.hippo.yorozuya.MathUtils;
/**
* Show a part of the original drawable
*/
public class PreciselyClipDrawable extends DrawableWrapper {
private final boolean mClip;
@@ -1,140 +0,0 @@
/*
* Copyright 2017 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.drawable;
/*
* Created by Hippo on 2017/9/6.
*/
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.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
public class TextDrawable extends Drawable {
private static final float STANDARD_TEXT_SIZE = 1000.0f;
private static final Paint STANDARD_PAINT = new Paint();
static {
STANDARD_PAINT.setTextSize(STANDARD_TEXT_SIZE);
}
private String text;
private float contentPercent;
private Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int textColor = Color.BLACK;
private int backgroundColor = Color.BLACK;
private float x = 0.0f;
private float y = 0.0f;
private boolean textSizeDirty = false;
private Rect textBounds = new Rect();
public TextDrawable(String text, float contentPercent) {
this.text = text;
this.contentPercent = contentPercent;
STANDARD_PAINT.getTextBounds(text, 0, text.length(), textBounds);
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
if (this.textColor != textColor) {
this.textColor = textColor;
invalidateSelf();
}
}
public int getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(int backgroundColor) {
if (this.backgroundColor != backgroundColor) {
this.backgroundColor = backgroundColor;
invalidateSelf();
}
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
textSizeDirty = true;
}
private void updateTextSizeIfDirty(Rect bounds) {
if (!textSizeDirty) {
return;
}
textSizeDirty = false;
int contentWidth = (int) (bounds.width() * contentPercent);
int contentHeight = (int) (bounds.height() * contentPercent);
float widthRatio = (float) contentWidth / (float) textBounds.width();
float heightRatio = (float) contentHeight / (float) textBounds.height();
float ratio = Math.min(widthRatio, heightRatio);
float textSize = STANDARD_TEXT_SIZE * ratio;
textPaint.setTextSize(textSize);
x = (bounds.width() - textBounds.width() * ratio) / 2 - textBounds.left * ratio;
y = (bounds.height() - textBounds.height() * ratio) / 2 - textBounds.top * ratio;
}
@Override
public void draw(@NonNull Canvas canvas) {
Rect bounds = getBounds();
if (!bounds.isEmpty()) {
// Draw background
backgroundPaint.setColor(backgroundColor);
canvas.drawRect(bounds, backgroundPaint);
if (!TextUtils.isEmpty(text)) {
// Draw text
updateTextSizeIfDirty(bounds);
textPaint.setColor(textColor);
canvas.drawText(text, x, y, textPaint);
}
}
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
backgroundPaint.setColorFilter(colorFilter);
textPaint.setColorFilter(colorFilter);
invalidateSelf();
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
@@ -16,59 +16,26 @@
package com.hippo.drawable;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.TextView;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.conaco.Unikery;
import com.hippo.image.ImageBitmap;
import com.hippo.image.ImageDrawable;
import com.hippo.image.RecycledException;
import com.hippo.widget.ObservedTextView;
import com.hippo.conaco.ValueHolder;
public class UnikeryDrawable extends WrapDrawable implements Unikery<ImageBitmap>,
ObservedTextView.OnWindowAttachListener {
private static final String TAG = UnikeryDrawable.class.getSimpleName();
public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
private int mTaskId = Unikery.INVALID_ID;
private final ObservedTextView mTextView;
private final Conaco<ImageBitmap> mConaco;
private String mUrl;
private final TextView mTextView;
public UnikeryDrawable(ObservedTextView textView, Conaco<ImageBitmap> conaco) {
private ValueHolder<Bitmap> mHolder;
public UnikeryDrawable(TextView textView) {
mTextView = textView;
mTextView.setOnWindowAttachListener(this);
mConaco = conaco;
}
@Override
public void onAttachedToWindow() {
load(mUrl);
}
@Override
public void onDetachedFromWindow() {
mConaco.cancel(this);
clearDrawable();
}
public void load(String url) {
if (url != null) {
mUrl = url;
mConaco.load(new ConacoTask.Builder<ImageBitmap>().setUnikery(this).setUrl(url).setKey(url));
}
}
private void clearDrawable() {
Drawable drawable = getDrawable();
if (drawable instanceof ImageDrawable) {
((ImageDrawable) drawable).recycle();
}
setDrawable(null);
}
@Override
@@ -87,7 +54,9 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<ImageBitmap
updateBounds();
if (drawable != null) {
invalidateSelf();
// mTextView.requestLayout() not work!
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
}
}
@@ -102,41 +71,49 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<ImageBitmap
}
@Override
public void invalidateSelf() {
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
public void onMiss(Conaco.Source source) {
}
@Override
public void onMiss(int source) {}
public void onRequest() {
}
@Override
public void onRequest() {}
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {
}
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {}
private void removeDrawableAndHolder() {
// Remove drawable
setDrawable(null);
@Override
public void onWait() {}
@Override
public boolean onGetValue(@NonNull ImageBitmap value, int source) {
ImageDrawable drawable;
try {
drawable = new ImageDrawable(value);
} catch (RecycledException e) {
Log.d(TAG, "The ImageBitmap is recycled", e);
return false;
// Remove holder
if (mHolder != null) {
mHolder.release(this);
mHolder = null;
}
}
clearDrawable();
@Override
public boolean onGetObject(@NonNull ValueHolder<Bitmap> holder, Conaco.Source source) {
holder.obtain(this);
removeDrawableAndHolder();
mHolder = holder;
Drawable drawable = new BitmapDrawable(mTextView.getResources(), holder.getValue());
setDrawable(drawable);
drawable.start();
return true;
}
@Override
public void onSetDrawable(Drawable drawable) {
removeDrawableAndHolder();
setDrawable(drawable);
}
@Override
public void onFailure() {
// Empty
@@ -17,32 +17,15 @@
package com.hippo.ehviewer;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.scene.SceneFragment;
import com.google.analytics.tracking.android.EasyTracker;
public final class Analytics {
private static FirebaseAnalytics analytics;
private Analytics() {}
public static void start(Context context) {
analytics = FirebaseAnalytics.getInstance(context);
analytics.setUserId(Settings.getUserID());
}
public static boolean isEnabled() {
return analytics != null && Settings.getEnableAnalytics();
}
public static void onSceneView(SceneFragment scene) {
if (isEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("scene_simple_class", scene.getClass().getSimpleName());
bundle.putString("scene_class", scene.getClass().getName());
analytics.logEvent("scene_view", bundle);
}
EasyTracker.getInstance(context).set("&uid", Settings.getUserID());
}
}
@@ -37,6 +37,7 @@ public class AppConfig {
private static final String DOWNLOAD = "download";
private static final String TEMP = "temp";
private static final String IMAGE = "image";
private static final String CRASH = "crash";
private static final String PARSE_ERROR = "parse_error";
private static final String LOGCAT = "logcat";
private static final String DATA = "data";
@@ -94,6 +95,11 @@ public class AppConfig {
return getDirInExternalAppDir(IMAGE);
}
@Nullable
public static File getExternalCrashDir() {
return getDirInExternalAppDir(CRASH);
}
@Nullable
public static File getExternalParseErrorDir() {
return getDirInExternalAppDir(PARSE_ERROR);
@@ -16,25 +16,25 @@
package com.hippo.ehviewer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.conaco.ValueHelper;
import com.hippo.image.ImageBitmap;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.conaco.ValueHolder;
import com.hippo.yorozuya.io.InputStreamPipe;
import java.io.IOException;
public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
private static final int MAX_CACHE_SIZE = 512 * 512;
public class BitmapHelper implements ValueHelper<Bitmap> {
@Nullable
@Override
public ImageBitmap decode(@NonNull InputStreamPipe isPipe) {
public Bitmap decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
return ImageBitmap.decode(isPipe.open());
return BitmapFactory.decodeStream(isPipe.open());
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
@@ -46,27 +46,15 @@ public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
}
@Override
public int sizeOf(@NonNull String key, @NonNull ImageBitmap value) {
return value.getWidth() * value.getHeight() * 4 /* value.getByteCount() TODO Update Image */;
public int sizeOf(@NonNull String key, @NonNull Bitmap value) {
return value.getByteCount();
}
@Override
public void onAddToMemoryCache(@NonNull ImageBitmap oldValue) {
oldValue.obtain();
}
public void onRemove(@NonNull String key, @NonNull ValueHolder<Bitmap> oldValue) {}
@Override
public void onRemoveFromMemoryCache(@NonNull String key, @NonNull ImageBitmap oldValue) {
oldValue.release();
}
@Override
public boolean useMemoryCache(@NonNull String key, ImageBitmap value) {
if (value != null) {
return value.getWidth() * value.getHeight() <= MAX_CACHE_SIZE
/* value.getByteCount() <= MAX_CACHE_BYTE_COUNT TODO Update Image */;
} else {
return true;
}
public boolean useMemoryCache(@NonNull String key, ValueHolder<Bitmap> holder) {
return true;
}
}
@@ -0,0 +1,194 @@
/*
* Copyright 2016 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.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public class Crash {
@NonNull
private static String avoidNull(String str) {
return null != str ? str : "null";
}
@SuppressWarnings("deprecation")
private static void collectInfo(Context context, FileWriter fw) throws IOException {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = String.valueOf(pi.versionCode);
fw.write("======== PackageInfo ========\r\n");
fw.write("PackageName=");fw.write(pi.packageName);fw.write("\r\n");
fw.write("VersionName=");fw.write(versionName);fw.write("\r\n");
fw.write("VersionCode=");fw.write(versionCode);fw.write("\r\n");
String signature = PackageUtils.getSignature(context, pi.packageName);
fw.write("Signature=");fw.write(null != signature ? signature : "null");fw.write("\r\n");
fw.write("\r\n");
}
} catch (PackageManager.NameNotFoundException e) {
fw.write("======== PackageInfo ========\r\n");
fw.write("Can't get package information\r\n");
fw.write("\r\n");
}
// Runtime
String topActivityClazzName = null;
String topSceneClazzName = null;
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
}
}
} catch (Throwable e) {
// Ignore
}
fw.write("======== Runtime ========\r\n");
fw.write("TopActivity=");fw.write(avoidNull(topActivityClazzName));fw.write("\r\n");
fw.write("TopScene=");fw.write(avoidNull(topSceneClazzName));fw.write("\r\n");
fw.write("\r\n");
// Device info
fw.write("======== DeviceInfo ========\r\n");
fw.write("BOARD=");fw.write(Build.BOARD);fw.write("\r\n");
fw.write("BOOTLOADER=");fw.write(Build.BOOTLOADER);fw.write("\r\n");
fw.write("CPU_ABI=");fw.write(Build.CPU_ABI);fw.write("\r\n");
fw.write("CPU_ABI2=");fw.write(Build.CPU_ABI2);fw.write("\r\n");
fw.write("DEVICE=");fw.write(Build.DEVICE);fw.write("\r\n");
fw.write("DISPLAY=");fw.write(Build.DISPLAY);fw.write("\r\n");
fw.write("FINGERPRINT=");fw.write(Build.FINGERPRINT);fw.write("\r\n");
fw.write("HARDWARE=");fw.write(Build.HARDWARE);fw.write("\r\n");
fw.write("HOST=");fw.write(Build.HOST);fw.write("\r\n");
fw.write("ID=");fw.write(Build.ID);fw.write("\r\n");
fw.write("MANUFACTURER=");fw.write(Build.MANUFACTURER);fw.write("\r\n");
fw.write("MODEL=");fw.write(Build.MODEL);fw.write("\r\n");
fw.write("PRODUCT=");fw.write(Build.PRODUCT);fw.write("\r\n");
fw.write("RADIO=");fw.write(Build.getRadioVersion());fw.write("\r\n");
fw.write("SERIAL=");fw.write(Build.SERIAL);fw.write("\r\n");
fw.write("TAGS=");fw.write(Build.TAGS);fw.write("\r\n");
fw.write("TYPE=");fw.write(Build.TYPE);fw.write("\r\n");
fw.write("USER=");fw.write(Build.USER);fw.write("\r\n");
fw.write("CODENAME=");fw.write(Build.VERSION.CODENAME);fw.write("\r\n");
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("\r\n");
}
public static void getThrowableInfo(Throwable t, FileWriter fw) {
PrintWriter printWriter = new PrintWriter(fw);
t.printStackTrace(printWriter);
Throwable cause = t.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
}
public static void saveCrashInfo2File(Context context, Throwable ex) {
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return;
}
String nowString = ReadableTime.getFilenamableTime(System.currentTimeMillis());
String fileName = "crash-" + nowString + ".log";
File file = new File(dir, fileName);
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write("TIME=");fw.write(nowString);fw.write("\r\n");
fw.write("\r\n");
collectInfo(context, fw);
fw.write("======== CrashInfo ========\r\n");
getThrowableInfo(ex, fw);
fw.write("\r\n");
fw.flush();
Settings.putCrashFilename(fileName);
} catch (Exception e) {
file.delete();
} finally {
IOUtils.closeQuietly(fw);
}
}
public static boolean hasCrashFile() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return false;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return false;
}
return new File(dir, filename).isFile();
}
public static String getCrashContent() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return null;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return null;
}
File file = new File(dir, filename);
InputStream is = null;
try {
is = new FileInputStream(file);
return IOUtils.readString(is, "UTF-8");
} catch (IOException e) {
return null;
} finally {
IOUtils.closeQuietly(is);
}
}
public static void resetCrashFile() {
Settings.putCrashFilename(null);
}
}
@@ -17,83 +17,95 @@
package com.hippo.ehviewer;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.facebook.soloader.SoLoader;
import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.content.RecordingApplication;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhDns;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.network.StatusCodeException;
import com.hippo.okhttp.CookieDB;
import com.hippo.scene.SceneApplication;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
public class EhApplication extends RecordingApplication {
public class EhApplication extends SceneApplication implements Thread.UncaughtExceptionHandler {
private static final String TAG = EhApplication.class.getSimpleName();
public static final boolean BETA = false;
private static final boolean DEBUG_CONACO = false;
private static final boolean DEBUG_PRINT_NATIVE_MEMORY = false;
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
private static final boolean DEBUG_NATIVE_MEMORY = false;
private Thread.UncaughtExceptionHandler mDefaultHandler;
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final HashMap<Integer, Object> mGlobalStuffMap = new HashMap<>();
private final WeakHashMap<Integer, Object> mGlobalStuffMap = new WeakHashMap<>();
private EhCookieStore mEhCookieStore;
private EhClient mEhClient;
private OkHttpClient mOkHttpClient;
private ImageBitmapHelper mImageBitmapHelper;
private Conaco<ImageBitmap> mConaco;
private BitmapHelper mBitmapHelper;
private Conaco<Bitmap> mConaco;
private LruCache<Long, GalleryDetail> mGalleryDetailCache;
private SimpleDiskCache mSpiderInfoCache;
private DownloadManager mDownloadManager;
private Hosts mHosts;
private final List<Activity> mActivityList = new ArrayList<>();
@Override
public void onCreate() {
// Prepare to catch crash
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
// Start anr watch dog
new ANRWatchDog().setANRListener(new ANRWatchDog.ANRListener() {
@Override
public void onAppNotResponding(ANRError error) {
// Throw RuntimeException, let crash handler do it
throw new RuntimeException(error.getCause());
}
}).start();
super.onCreate();
try {
SoLoader.init(this, 0);
} catch (IOException e) {
throw new RuntimeException("Could not initialize SoLoader", e);
}
GetText.initialize(this);
CookieDB.initialize(this);
StatusCodeException.initialize(this);
Settings.initialize(this);
ReadableTime.initialize(this);
@@ -112,14 +124,13 @@ public class EhApplication extends RecordingApplication {
Analytics.start(this);
}
// Disable no media file checker for now. Some devices stuck here.
// // Check no media file
// UniFile downloadLocation = Settings.getDownloadLocation();
// if (Settings.getMediaScan()) {
// CommonOperations.removeNoMediaFile(downloadLocation);
// } else {
// CommonOperations.ensureNoMediaFile(downloadLocation);
// }
// Check no media file
UniFile downloadLocation = Settings.getDownloadLocation();
if (Settings.getMediaScan()) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
// Clear temp dir
clearTempDir();
@@ -135,8 +146,8 @@ public class EhApplication extends RecordingApplication {
// Ignore
}
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
if (DEBUG_NATIVE_MEMORY) {
debugNativeMemory();
}
}
@@ -149,9 +160,6 @@ public class EhApplication extends RecordingApplication {
if (null != dir) {
FileUtils.deleteContent(dir);
}
// Add .nomedia to external temp dir
CommonOperations.ensureNoMediaFile(UniFile.fromFile(AppConfig.getExternalTempDir()));
}
private void update() {
@@ -159,11 +167,34 @@ public class EhApplication extends RecordingApplication {
if (version < 52) {
Settings.putGuideGallery(true);
}
if (version < 56) { // Make cookie long live
HttpUrl eUrl = HttpUrl.parse(EhUrl.HOST_E);
HttpUrl exUrl = HttpUrl.parse(EhUrl.HOST_EX);
EhCookieStore cookieStore = getEhCookieStore(this);
Cookie c;
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
}
}
public void clearMemoryCache() {
if (null != mConaco) {
mConaco.getBeerBelly().clearMemory();
mConaco.clearMemoryCache();
}
if (null != mGalleryDetailCache) {
mGalleryDetailCache.evictAll();
@@ -179,18 +210,13 @@ public class EhApplication extends RecordingApplication {
}
}
private void debugPrint() {
private void debugNativeMemory() {
new Runnable() {
@Override
public void run() {
if (DEBUG_PRINT_NATIVE_MEMORY) {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
}
if (DEBUG_PRINT_IMAGE_COUNT) {
Log.i(TAG, "Image count: " + Image.getImageCount());
}
SimpleHandler.getInstance().postDelayed(this, DEBUG_PRINT_INTERVAL);
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
SimpleHandler.getInstance().postDelayed(this, 3000);
}
}.run();
}
@@ -220,7 +246,7 @@ public class EhApplication extends RecordingApplication {
public static EhCookieStore getEhCookieStore(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mEhCookieStore == null) {
application.mEhCookieStore = new EhCookieStore(context);
application.mEhCookieStore = new EhCookieStore();
}
return application.mEhCookieStore;
}
@@ -239,41 +265,43 @@ public class EhApplication extends RecordingApplication {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mOkHttpClient == null) {
application.mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.cookieJar(getEhCookieStore(application))
.dns(new EhDns(application))
.build();
}
return application.mOkHttpClient;
}
@NonNull
public static ImageBitmapHelper getImageBitmapHelper(@NonNull Context context) {
public static BitmapHelper getBitmapHelper(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mImageBitmapHelper == null) {
application.mImageBitmapHelper = new ImageBitmapHelper();
if (application.mBitmapHelper == null) {
application.mBitmapHelper = new BitmapHelper();
}
return application.mImageBitmapHelper;
return application.mBitmapHelper;
}
private static int getMemoryCacheMaxSize() {
return Math.min(20 * 1024 * 1024, (int) OSUtils.getAppMaxMemory());
private static int getMemoryCacheMaxSize(Context context) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
}
@NonNull
public static Conaco<ImageBitmap> getConaco(@NonNull Context context) {
public static Conaco<Bitmap> getConaco(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mConaco == null) {
Conaco.Builder<ImageBitmap> builder = new Conaco.Builder<>();
Conaco.Builder<Bitmap> builder = new Conaco.Builder<>();
builder.hasMemoryCache = true;
builder.memoryCacheMaxSize = getMemoryCacheMaxSize();
builder.memoryCacheMaxSize = getMemoryCacheMaxSize(context);
builder.hasDiskCache = true;
builder.diskCacheDir = new File(context.getCacheDir(), "thumb");
builder.diskCacheMaxSize = 80 * 1024 * 1024; // 80MB
builder.okHttpClient = getOkHttpClient(context);
builder.objectHelper = getImageBitmapHelper(context);
builder.objectHelper = getBitmapHelper(context);
builder.debug = DEBUG_CONACO;
application.mConaco = builder.build();
}
@@ -309,13 +337,32 @@ public class EhApplication extends RecordingApplication {
return application.mDownloadManager;
}
@NonNull
public static Hosts getHosts(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mHosts == null) {
application.mHosts = new Hosts(application, "hosts.db");
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
return application.mHosts;
try {
ex.printStackTrace();
Crash.saveCrashInfo2File(this, ex);
return true;
} catch (Throwable tr) {
return false;
}
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
Activity activity = getTopActivity();
if (activity != null) {
activity.finish();
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
@NonNull
+12 -40
View File
@@ -43,12 +43,11 @@ import com.hippo.ehviewer.dao.LocalFavoritesDao;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.ehviewer.dao.QuickSearchDao;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
import java.io.File;
import java.io.FileInputStream;
@@ -94,19 +93,6 @@ public class EhDB {
switch (oldVersion) {
case 1: // 1 to 2
FilterDao.createTable(db, true);
break;
case 2: // add ENABLE column to table FILTER
db.execSQL("CREATE TABLE " + "\"FILTER2\" (" +
"\"_id\" INTEGER PRIMARY KEY ," +
"\"MODE\" INTEGER NOT NULL ," +
"\"TEXT\" TEXT," +
"\"ENABLE\" INTEGER);");
db.execSQL("INSERT INTO \"FILTER2\" (" +
"_id, MODE, TEXT, ENABLE)" +
"SELECT _id, MODE, TEXT, 1 FROM FILTER;");
db.execSQL("DROP TABLE FILTER");
db.execSQL("ALTER TABLE FILTER2 RENAME TO FILTER");
break;
}
}
@@ -157,8 +143,7 @@ public class EhDB {
SQLiteDatabase oldDB;
try {
oldDB = oldDBHelper.getReadableDatabase();
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
return;
}
@@ -180,8 +165,7 @@ public class EhDB {
try {
// In 0.6.x version, NaN is stored
gi.rating = cursor.getFloat(7);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
gi.rating = -1.0f;
}
@@ -192,8 +176,7 @@ public class EhDB {
}
cursor.close();
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
@@ -223,8 +206,7 @@ public class EhDB {
}
cursor.close();
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
@@ -260,8 +242,7 @@ public class EhDB {
}
cursor.close();
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
@@ -302,8 +283,7 @@ public class EhDB {
}
cursor.close();
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
@@ -332,15 +312,13 @@ public class EhDB {
}
cursor.close();
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
try {
oldDBHelper.close();
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
}
@@ -471,7 +449,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> getAllLocalFavorites() {
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time).list();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
return result;
@@ -480,7 +458,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> searchLocalFavorites(String query) {
query = SqlUtils.sqlEscapeString("%" + query+ "%");
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time)
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time)
.where(LocalFavoritesDao.Properties.Title.like(query)).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
@@ -628,11 +606,6 @@ public class EhDB {
sDaoSession.getFilterDao().delete(filter);
}
public static synchronized void triggerFilter(Filter filter) {
filter.setEnable(!filter.enable);
sDaoSession.getFilterDao().update(filter);
}
public static synchronized boolean exportDB(Context context, File file) {
File dbFile = context.getDatabasePath("eh.db");
if (null == dbFile || !dbFile.isFile()) {
@@ -735,8 +708,7 @@ public class EhDB {
}
return null;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
return context.getString(R.string.cant_read_the_file);
}
@@ -1,350 +0,0 @@
/*
* Copyright 2018 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;
/*
* Created by Hippo on 2018/3/21.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Pair;
import com.hippo.database.MSQLiteBuilder;
import com.hippo.util.SqlUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class Hosts {
private static final int VERSION_1 = 1;
private static final String TABLE_HOSTS = "HOSTS";
private static final String COLUMN_HOST = "HOST";
private static final String COLUMN_IP = "IP";
private static final int DB_VERSION = VERSION_1;
private final SQLiteOpenHelper helper;
private final SQLiteDatabase db;
public Hosts(Context context, String name) {
helper = new MSQLiteBuilder()
.version(VERSION_1)
.createTable(TABLE_HOSTS)
.insertColumn(TABLE_HOSTS, COLUMN_HOST, String.class)
.insertColumn(TABLE_HOSTS, COLUMN_IP, String.class)
.build(context, name, DB_VERSION);
db = helper.getWritableDatabase();
}
/**
* Gets a InetAddress with the host.
*/
@Nullable
public InetAddress get(String host) {
if (!isValidHost(host)) {
return null;
}
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
if (cursor.moveToNext()) {
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
return toInetAddress(host, ip);
} else {
return null;
}
} finally {
cursor.close();
}
}
private boolean contains(String host) {
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
return cursor.moveToNext();
} finally {
cursor.close();
}
}
/**
* Puts the host-ip pair into this hosts.
*/
public boolean put(String host, String ip) {
if (!isValidHost(host) || !isValidIp(ip)) {
return false;
}
ContentValues values = new ContentValues();
values.put(COLUMN_HOST, host);
values.put(COLUMN_IP, ip);
if (contains(host)) {
db.update(TABLE_HOSTS, values, COLUMN_HOST + " = ?", new String[] { host });
} else {
db.insert(TABLE_HOSTS, null, values);
}
return true;
}
/**
* Puts delete the entry with the host.
*/
public void delete(String host) {
db.delete(TABLE_HOSTS, COLUMN_HOST + " = ?", new String[] { host });
}
/**
* Get all data from this host.
*/
public List<Pair<String, String>> getAll() {
List<Pair<String, String>> result = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + ";", null);
try {
while (cursor.moveToNext()) {
String host = SqlUtils.getString(cursor, COLUMN_HOST, null);
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
InetAddress inetAddress = toInetAddress(host, ip);
if (inetAddress == null) {
continue;
}
result.add(new Pair<>(host, ip));
}
} finally {
cursor.close();
}
return result;
}
@Nullable
public static InetAddress toInetAddress(String host, String ip) {
if (!isValidHost(host)) {
return null;
}
if (ip == null) {
return null;
}
byte[] bytes = parseV4(ip);
if (bytes == null) {
bytes = parseV6(ip);
}
if (bytes == null) {
return null;
}
try {
return InetAddress.getByAddress(host, bytes);
} catch (UnknownHostException e) {
return null;
}
}
/**
* Returns true if the host is valid.
*/
public static boolean isValidHost(String host) {
if (host == null) {
return false;
}
if (host.length() > 253) {
return false;
}
int labelLength = 0;
for (int i = 0, n = host.length(); i < n; i++) {
char ch = host.charAt(i);
if (ch == '.') {
if (labelLength < 1 || labelLength > 63) {
return false;
}
labelLength = 0;
} else {
labelLength++;
}
if ((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' && ch != '.') {
return false;
}
}
if (labelLength < 1 || labelLength > 63) {
return false;
}
return true;
}
/**
* Returns true if the ip is valid.
*/
public static boolean isValidIp(String ip) {
return ip != null && (parseV4(ip) != null || parseV6(ip) != null);
}
// org.xbill.DNS.Address.parseV4
@Nullable
private static byte[] parseV4(String s) {
int numDigits;
int currentOctet;
byte [] values = new byte[4];
int currentValue;
int length = s.length();
currentOctet = 0;
currentValue = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
/* Octets shouldn't start with 0, unless they are 0. */
if (numDigits > 0 && currentValue == 0)
return null;
numDigits++;
currentValue *= 10;
currentValue += (c - '0');
/* 255 is the maximum value for an octet. */
if (currentValue > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
values[currentOctet++] = (byte) currentValue;
currentValue = 0;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
values[currentOctet] = (byte) currentValue;
return values;
}
// org.xbill.DNS.Address.parseV6
@Nullable
private static byte[] parseV6(String s) {
int range = -1;
byte [] data = new byte[16];
String [] tokens = s.split(":", -1);
int first = 0;
int last = tokens.length - 1;
if (tokens[0].length() == 0) {
// If the first two tokens are empty, it means the string
// started with ::, which is fine. If only the first is
// empty, the string started with :, which is bad.
if (last - first > 0 && tokens[1].length() == 0)
first++;
else
return null;
}
if (tokens[last].length() == 0) {
// If the last two tokens are empty, it means the string
// ended with ::, which is fine. If only the last is
// empty, the string ended with :, which is bad.
if (last - first > 0 && tokens[last - 1].length() == 0)
last--;
else
return null;
}
if (last - first + 1 > 8)
return null;
int i, j;
for (i = first, j = 0; i <= last; i++) {
if (tokens[i].length() == 0) {
if (range >= 0)
return null;
range = j;
continue;
}
if (tokens[i].indexOf('.') >= 0) {
// An IPv4 address must be the last component
if (i < last)
return null;
// There can't have been more than 6 components.
if (i > 6)
return null;
byte [] v4addr = parseV4(tokens[i]);
if (v4addr == null)
return null;
for (int k = 0; k < 4; k++)
data[j++] = v4addr[k];
break;
}
try {
for (int k = 0; k < tokens[i].length(); k++) {
char c = tokens[i].charAt(k);
if (Character.digit(c, 16) < 0)
return null;
}
int x = Integer.parseInt(tokens[i], 16);
if (x > 0xFFFF || x < 0)
return null;
data[j++] = (byte)(x >>> 8);
data[j++] = (byte)(x & 0xFF);
}
catch (NumberFormatException e) {
return null;
}
}
if (j < 16 && range < 0)
return null;
if (range >= 0) {
int empty = 16 - j;
System.arraycopy(data, range, data, range + empty, j - range);
for (i = range; i < range + empty; i++)
data[i] = 0;
}
return data;
}
}
+44 -228
View File
@@ -16,6 +16,7 @@
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
@@ -24,17 +25,19 @@ import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
import com.hippo.ehviewer.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.glgallery.GalleryView;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.File;
public class Settings {
@@ -234,28 +237,6 @@ public class Settings {
/********************
****** Eh
********************/
public static final String KEY_THEME = "theme";
public static final int THEME_LIGHT = 0;
public static final int THEME_DARK = 1;
public static final int THEME_BLACK = 2;
private static final int DEFAULT_THEME = THEME_LIGHT;
public static int getTheme() {
return getIntFromStr(KEY_THEME, DEFAULT_THEME);
}
public static void putTheme(int theme) {
putIntToStr(KEY_THEME, theme);
}
public static final String KEY_APPLY_NAV_BAR_THEME_COLOR = "apply_nav_bar_theme_color";
private static final boolean DEFAULT_APPLY_NAV_BAR_THEME_COLOR = false;
public static boolean getApplyNavBarThemeColor() {
return getBoolean(KEY_APPLY_NAV_BAR_THEME_COLOR, DEFAULT_APPLY_NAV_BAR_THEME_COLOR);
}
public static final String KEY_GALLERY_SITE = "gallery_site";
private static final int DEFAULT_GALLERY_SITE = 1;
@@ -274,24 +255,6 @@ public class Settings {
return getIntFromStr(KEY_LIST_MODE, DEFAULT_LIST_MODE);
}
public static final String KEY_DETAIL_SIZE = "detail_size";
private static final int DEFAULT_DETAIL_SIZE = 0;
public static int getDetailSize() {
return getIntFromStr(KEY_DETAIL_SIZE, DEFAULT_DETAIL_SIZE);
}
@DimenRes
public static int getDetailSizeResId() {
switch (getDetailSize()) {
default:
case 0:
return R.dimen.gallery_list_column_width_long;
case 1:
return R.dimen.gallery_list_column_width_short;
}
}
public static final String KEY_THUMB_SIZE = "thumb_size";
private static final int DEFAULT_THUMB_SIZE = 1;
@@ -319,13 +282,6 @@ public class Settings {
return getIntFromStr(KEY_THUMB_RESOLUTION, DEFAULT_THUMB_RESOLUTION);
}
private static final String KEY_FIX_THUMB_URL = "fix_thumb_url";
private static final boolean DEFAULT_FIX_THUMB_URL = false;
public static boolean getFixThumbUrl() {
return getBoolean(KEY_FIX_THUMB_URL, DEFAULT_FIX_THUMB_URL);
}
private static final String KEY_SHOW_JPN_TITLE = "show_jpn_title";
private static final boolean DEFAULT_SHOW_JPN_TITLE = false;
@@ -333,13 +289,6 @@ public class Settings {
return getBoolean(KEY_SHOW_JPN_TITLE, DEFAULT_SHOW_JPN_TITLE);
}
private static final String KEY_SHOW_GALLERY_PAGES = "show_gallery_pages";
private static final boolean DEFAULT_SHOW_GALLERY_PAGES = false;
public static boolean getShowGalleryPages() {
return getBoolean(KEY_SHOW_GALLERY_PAGES, DEFAULT_SHOW_GALLERY_PAGES);
}
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
@@ -445,13 +394,6 @@ public class Settings {
putString(KEY_HATH_PASSKEY, value);
}
private static final String KEY_CELLULAR_NETWORK_WARNING = "cellular_network_warning";
private static final boolean DEFAULT_CELLULAR_NETWORK_WARNING = false;
public static boolean getCellularNetworkWarning() {
return getBoolean(KEY_CELLULAR_NETWORK_WARNING, DEFAULT_CELLULAR_NETWORK_WARNING);
}
/********************
****** Read
********************/
@@ -467,7 +409,7 @@ public class Settings {
}
private static final String KEY_READING_DIRECTION = "reading_direction";
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_RIGHT_TO_LEFT;
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
@GalleryView.LayoutMode
public static int getReadingDirection() {
@@ -479,11 +421,11 @@ public class Settings {
}
private static final String KEY_PAGE_SCALING = "page_scaling";
private static final int DEFAULT_PAGE_SCALING = GalleryView.SCALE_FIT;
private static final int DEFAULT_PAGE_SCALING = ImageView.SCALE_FIT;
@GalleryView.ScaleMode
@ImageView.Scale
public static int getPageScaling() {
return GalleryView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
return ImageView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
}
public static void putPageScaling(int value) {
@@ -491,11 +433,11 @@ public class Settings {
}
private static final String KEY_START_POSITION = "start_position";
private static final int DEFAULT_START_POSITION = GalleryView.START_POSITION_TOP_RIGHT;
private static final int DEFAULT_START_POSITION = ImageView.START_POSITION_TOP_RIGHT;
@GalleryView.StartPosition
@ImageView.StartPosition
public static int getStartPosition() {
return GalleryView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
return ImageView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
}
public static void putStartPosition(int value) {
@@ -546,17 +488,6 @@ public class Settings {
putBoolean(KEY_SHOW_BATTERY, value);
}
private static final String KEY_SHOW_PAGE_INTERVAL = "gallery_show_page_interval";
private static final boolean DEFAULT_SHOW_PAGE_INTERVAL = true;
public static boolean getShowPageInterval() {
return getBoolean(KEY_SHOW_PAGE_INTERVAL, DEFAULT_SHOW_PAGE_INTERVAL);
}
public static void putShowPageInterval(boolean value) {
putBoolean(KEY_SHOW_PAGE_INTERVAL, value);
}
private static final String KEY_VOLUME_PAGE = "volume_page";
private static final boolean DEFAULT_VOLUME_PAGE = false;
@@ -601,19 +532,6 @@ public class Settings {
putInt(KEY_SCREEN_LIGHTNESS, value);
}
/********************
****** Privacy and Security
********************/
public static final String KEY_SEC_SECURITY = "enable_secure";
public static final boolean VALUE_SEC_SECURITY = false;
public static boolean getEnabledSecurity() {
return getBoolean(KEY_SEC_SECURITY, VALUE_SEC_SECURITY);
}
public static void putEnabledSecurity(boolean value) {
putBoolean(KEY_READING_FULLSCREEN, value);
}
/********************
****** Download
********************/
@@ -634,8 +552,7 @@ public class Settings {
builder.encodedQuery(getString(KEY_DOWNLOAD_SAVE_QUERY, null));
builder.encodedFragment(getString(KEY_DOWNLOAD_SAVE_FRAGMENT, null));
dir = UniFile.fromUri(sContext, builder.build());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
return dir != null ? dir : UniFile.fromFile(AppConfig.getDefaultDownloadDir());
@@ -745,42 +662,26 @@ public class Settings {
/********************
****** Favorites
********************/
private static final String KEY_FAV_CAT_0 = "fav_cat_0";
private static final String KEY_FAV_CAT_1 = "fav_cat_1";
private static final String KEY_FAV_CAT_2 = "fav_cat_2";
private static final String KEY_FAV_CAT_3 = "fav_cat_3";
private static final String KEY_FAV_CAT_4 = "fav_cat_4";
private static final String KEY_FAV_CAT_5 = "fav_cat_5";
private static final String KEY_FAV_CAT_6 = "fav_cat_6";
private static final String KEY_FAV_CAT_7 = "fav_cat_7";
private static final String KEY_FAV_CAT_8 = "fav_cat_8";
private static final String KEY_FAV_CAT_9 = "fav_cat_9";
private static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
private static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
private static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
private static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
private static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
private static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
private static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
private static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
private static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
private static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
private static final String KEY_FAV_COUNT_0 = "fav_count_0";
private static final String KEY_FAV_COUNT_1 = "fav_count_1";
private static final String KEY_FAV_COUNT_2 = "fav_count_2";
private static final String KEY_FAV_COUNT_3 = "fav_count_3";
private static final String KEY_FAV_COUNT_4 = "fav_count_4";
private static final String KEY_FAV_COUNT_5 = "fav_count_5";
private static final String KEY_FAV_COUNT_6 = "fav_count_6";
private static final String KEY_FAV_COUNT_7 = "fav_count_7";
private static final String KEY_FAV_COUNT_8 = "fav_count_8";
private static final String KEY_FAV_COUNT_9 = "fav_count_9";
private static final String KEY_FAV_LOCAL = "fav_local";
private static final String KEY_FAV_CLOUD = "fav_cloud";
private static final int DEFAULT_FAV_COUNT = 0;
public static final String KEY_FAV_CAT_0 = "fav_cat_0";
public static final String KEY_FAV_CAT_1 = "fav_cat_1";
public static final String KEY_FAV_CAT_2 = "fav_cat_2";
public static final String KEY_FAV_CAT_3 = "fav_cat_3";
public static final String KEY_FAV_CAT_4 = "fav_cat_4";
public static final String KEY_FAV_CAT_5 = "fav_cat_5";
public static final String KEY_FAV_CAT_6 = "fav_cat_6";
public static final String KEY_FAV_CAT_7 = "fav_cat_7";
public static final String KEY_FAV_CAT_8 = "fav_cat_8";
public static final String KEY_FAV_CAT_9 = "fav_cat_9";
public static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
public static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
public static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
public static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
public static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
public static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
public static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
public static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
public static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
public static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
public static String[] getFavCat() {
String[] favCat = new String[10];
@@ -813,53 +714,6 @@ public class Settings {
.apply();
}
public static int[] getFavCount() {
int[] favCount = new int[10];
favCount[0] = sSettingsPre.getInt(KEY_FAV_COUNT_0, DEFAULT_FAV_COUNT);
favCount[1] = sSettingsPre.getInt(KEY_FAV_COUNT_1, DEFAULT_FAV_COUNT);
favCount[2] = sSettingsPre.getInt(KEY_FAV_COUNT_2, DEFAULT_FAV_COUNT);
favCount[3] = sSettingsPre.getInt(KEY_FAV_COUNT_3, DEFAULT_FAV_COUNT);
favCount[4] = sSettingsPre.getInt(KEY_FAV_COUNT_4, DEFAULT_FAV_COUNT);
favCount[5] = sSettingsPre.getInt(KEY_FAV_COUNT_5, DEFAULT_FAV_COUNT);
favCount[6] = sSettingsPre.getInt(KEY_FAV_COUNT_6, DEFAULT_FAV_COUNT);
favCount[7] = sSettingsPre.getInt(KEY_FAV_COUNT_7, DEFAULT_FAV_COUNT);
favCount[8] = sSettingsPre.getInt(KEY_FAV_COUNT_8, DEFAULT_FAV_COUNT);
favCount[9] = sSettingsPre.getInt(KEY_FAV_COUNT_9, DEFAULT_FAV_COUNT);
return favCount;
}
public static void putFavCount(int[] count) {
AssertUtils.assertEquals(10, count.length);
sSettingsPre.edit()
.putInt(KEY_FAV_COUNT_0, count[0])
.putInt(KEY_FAV_COUNT_1, count[1])
.putInt(KEY_FAV_COUNT_2, count[2])
.putInt(KEY_FAV_COUNT_3, count[3])
.putInt(KEY_FAV_COUNT_4, count[4])
.putInt(KEY_FAV_COUNT_5, count[5])
.putInt(KEY_FAV_COUNT_6, count[6])
.putInt(KEY_FAV_COUNT_7, count[7])
.putInt(KEY_FAV_COUNT_8, count[8])
.putInt(KEY_FAV_COUNT_9, count[9])
.apply();
}
public static int getFavLocalCount() {
return sSettingsPre.getInt(KEY_FAV_LOCAL, DEFAULT_FAV_COUNT);
}
public static void putFavLocalCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_LOCAL, count).apply();
}
public static int getFavCloudCount() {
return sSettingsPre.getInt(KEY_FAV_CLOUD, DEFAULT_FAV_COUNT);
}
public static void putFavCloudCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_CLOUD, count).apply();
}
private static final String KEY_RECENT_FAV_CAT = "recent_fav_cat";
private static final int DEFAULT_RECENT_FAV_CAT = FavListUrlBuilder.FAV_CAT_ALL;
@@ -976,8 +830,6 @@ public class Settings {
********************/
private static final String KEY_BETA_UPDATE_CHANNEL = "beta_update_channel";
private static final boolean DEFAULT_BETA_UPDATE_CHANNEL = EhApplication.BETA;
private static final String KEY_SKIP_UPDATE_VERSION = "skip_update_version";
private static final int DEFAULT_SKIP_UPDATE_VERSION = 0;
public static boolean getBetaUpdateChannel() {
return getBoolean(KEY_BETA_UPDATE_CHANNEL, DEFAULT_BETA_UPDATE_CHANNEL);
@@ -987,12 +839,19 @@ public class Settings {
putBoolean(KEY_BETA_UPDATE_CHANNEL, value);
}
public static int getSkipUpdateVersion() {
return getInt(KEY_SKIP_UPDATE_VERSION, DEFAULT_SKIP_UPDATE_VERSION);
/********************
****** Crash
********************/
private static final String KEY_CRASH_FILENAME = "crash_filename";
private static final String DEFAULT_CRASH_FILENAME = null;
public static String getCrashFilename() {
return getString(KEY_CRASH_FILENAME, DEFAULT_CRASH_FILENAME);
}
public static void putSkipUpdateVersion(int value) {
putInt(KEY_SKIP_UPDATE_VERSION, value);
@SuppressLint("CommitPrefEdits")
public static void putCrashFilename(String value) {
sSettingsPre.edit().putString(KEY_CRASH_FILENAME, value).commit();
}
/********************
@@ -1020,16 +879,6 @@ public class Settings {
putString(KEY_SECURITY, value);
}
public static final String KEY_ENABLE_FINGERPRINT = "enable_fingerprint";
public static boolean getEnableFingerprint() {
return getBoolean(KEY_ENABLE_FINGERPRINT, false);
}
public static void putEnableFingerprint(boolean value) {
putBoolean(KEY_ENABLE_FINGERPRINT, value);
}
public static final String KEY_READ_CACHE_SIZE = "read_cache_size";
public static final int DEFAULT_READ_CACHE_SIZE = 160;
@@ -1037,28 +886,6 @@ public class Settings {
return getIntFromStr(KEY_READ_CACHE_SIZE, DEFAULT_READ_CACHE_SIZE);
}
public static final String KEY_BUILT_IN_HOSTS = "built_in_hosts";
private static final boolean DEFAULT_BUILT_IN_HOSTS = false;
public static boolean getBuiltInHosts() {
return getBoolean(KEY_BUILT_IN_HOSTS, DEFAULT_BUILT_IN_HOSTS);
}
public static void putBuiltInHosts(boolean value) {
putBoolean(KEY_BUILT_IN_HOSTS, value);
}
public static final String KEY_APP_LANGUAGE = "app_language";
private static final String DEFAULT_APP_LANGUAGE = "system";
public static String getAppLanguage() {
return getString(KEY_APP_LANGUAGE, DEFAULT_APP_LANGUAGE);
}
public static void putAppLanguage(String value) {
putString(KEY_APP_LANGUAGE, value);
}
/********************
****** Guide
********************/
@@ -1116,15 +943,4 @@ public class Settings {
public static void putGuideGallery(boolean value) {
putBoolean(KEY_GUIDE_GALLERY, value);
}
private static final String KEY_CLIPBOARD_TEXT_HASH_CODE = "clipboard_text_hash_code";
private static final int DEFAULT_CLIPBOARD_TEXT_HASH_CODE = 0;
public static int getClipboardTextHashCode() {
return getInt(KEY_CLIPBOARD_TEXT_HASH_CODE, DEFAULT_CLIPBOARD_TEXT_HASH_CODE);
}
public static void putClipboardTextHashCode(int value) {
putInt(KEY_CLIPBOARD_TEXT_HASH_CODE, value);
}
}
@@ -18,12 +18,13 @@ package com.hippo.ehviewer.client;
import android.content.Context;
import android.os.AsyncTask;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.PriorityThreadFactory;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
@@ -33,6 +34,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.OkHttpClient;
@@ -57,8 +59,6 @@ public class EhClient {
public static final int METHOD_GET_PROFILE = 14;
public static final int METHOD_VOTE_COMMENT = 15;
public static final int METHOD_IMAGE_SEARCH = 16;
public static final int METHOD_ARCHIVE_LIST = 17;
public static final int METHOD_DOWNLOAD_ARCHIVE = 18;
private final ThreadPoolExecutor mRequestThreadPool;
private final OkHttpClient mOkHttpClient;
@@ -151,7 +151,7 @@ public class EhClient {
try {
switch (mMethod) {
case METHOD_SIGN_IN:
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1], (String) params[2], (String) params[3]);
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1]);
case METHOD_GET_GALLERY_LIST:
return EhEngine.getGalleryList(this, mOkHttpClient, (String) params[0]);
case METHOD_FILL_GALLERY_LIST_BY_API:
@@ -184,15 +184,10 @@ public class EhClient {
return EhEngine.voteComment(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Long) params[4], (Integer) params[5]);
case METHOD_IMAGE_SEARCH:
return EhEngine.imageSearch(this, mOkHttpClient, (File) params[0], (Boolean) params[1], (Boolean) params[2], (Boolean) params[3]);
case METHOD_ARCHIVE_LIST:
return EhEngine.getArchiveList(this, mOkHttpClient, (String) params[0]);
case METHOD_DOWNLOAD_ARCHIVE:
return EhEngine.downloadArchive(this, mOkHttpClient, (Long) params[0], (String) params[1], (String) params[2], (String) params[3]);
default:
return new IllegalStateException("Can't detect method " + mMethod);
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
return e;
}
}
@@ -299,7 +299,6 @@ public class EhConfig implements Cloneable {
public static final int NAMESPACES_MALE = 0x40;
public static final int NAMESPACES_FEMALE = 0x80;
public static final String JAPANESE_ORIGINAL = "0";
public static final String JAPANESE_TRANSLATED = "1024";
public static final String JAPANESE_REWRITE = "2048";
public static final String ENGLISH_ORIGINAL = "1";
@@ -16,9 +16,7 @@
package com.hippo.ehviewer.client;
import android.content.Context;
import com.hippo.network.CookieRepository;
import com.hippo.okhttp.CookieDBStore;
import java.util.ArrayList;
import java.util.Collections;
@@ -26,34 +24,29 @@ import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.Request;
public class EhCookieStore extends CookieRepository {
public class EhCookieStore extends CookieDBStore {
public static final String KEY_IPD_MEMBER_ID = "ipb_member_id";
public static final String KEY_IPD_PASS_HASH = "ipb_pass_hash";
public static final String KEY_IGNEOUS = "igneous";
public static final Cookie sTipsCookie =
new Cookie.Builder()
.name(EhConfig.KEY_CONTENT_WARNING)
.value(EhConfig.CONTENT_WARNING_NOT_SHOW)
.domain(EhUrl.DOMAIN_E)
.domain(EhUrl.DOMAIN_G)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
public EhCookieStore(Context context) {
super(context, "okhttp3-cookie.db");
}
public void signOut() {
clear();
removeAll();
}
public boolean hasSignedIn() {
HttpUrl url = HttpUrl.parse(EhUrl.HOST_E);
return contains(url, KEY_IPD_MEMBER_ID) &&
contains(url, KEY_IPD_PASS_HASH);
return contain(EhUrl.DOMAIN_EX, KEY_IPD_MEMBER_ID) &&
contain(EhUrl.DOMAIN_EX, KEY_IPD_PASS_HASH);
}
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent,
@@ -85,29 +78,66 @@ public class EhCookieStore extends CookieRepository {
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = super.loadForRequest(url);
public List<Cookie> loadForRequest(HttpUrl url, Request request) {
List<Cookie> cookies = super.loadForRequest(url, request);
Object tag = request.tag();
String host = url.host();
boolean checkTips = domainMatch(url, EhUrl.DOMAIN_E);
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_G);
boolean checkUconfig = (domainMatch(host, EhUrl.DOMAIN_E) || domainMatch(host, EhUrl.DOMAIN_EX)) && tag instanceof EhConfig;
if (checkTips) {
if (checkTips || checkUconfig) {
List<Cookie> result = new ArrayList<>(cookies.size() + 1);
// Add all but skip some
for (Cookie cookie: cookies) {
String name = cookie.name();
if (EhConfig.KEY_CONTENT_WARNING.equals(name)) {
if (checkTips && EhConfig.KEY_CONTENT_WARNING.equals(name)) {
continue;
}
if (EhConfig.KEY_UCONFIG.equals(name)) {
if (checkUconfig && EhConfig.KEY_UCONFIG.equals(name)) {
continue;
}
result.add(cookie);
}
// Add some
result.add(sTipsCookie);
if (checkTips) {
result.add(sTipsCookie);
}
if (checkUconfig) {
EhConfig ehConfig = (EhConfig) tag;
Cookie uconfigCookie = new Cookie.Builder()
.name(EhConfig.KEY_UCONFIG)
.value(ehConfig.uconfig())
.domain(host)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
result.add(uconfigCookie);
}
return Collections.unmodifiableList(result);
} else {
return cookies;
}
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
List<Cookie> result = new ArrayList<>(cookies.size() + 2);
for (Cookie cookie: cookies) {
if (EhUrl.DOMAIN_E.equals(cookie.domain())) {
// Save id and hash for exhentai
if (KEY_IPD_MEMBER_ID.equals(cookie.name()) ||
KEY_IPD_PASS_HASH.equals(cookie.name())) {
result.add(newCookie(cookie, EhUrl.DOMAIN_E, true, true, true));
result.add(newCookie(cookie, EhUrl.DOMAIN_EX, true, true, true));
continue;
}
}
result.add(cookie);
}
super.saveFromResponse(url, Collections.unmodifiableList(result));
}
}
@@ -1,85 +0,0 @@
/*
* Copyright 2018 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.client;
/*
* Created by Hippo on 2018/3/23.
*/
import android.content.Context;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Hosts;
import com.hippo.ehviewer.Settings;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Dns;
public class EhDns implements Dns {
private static final Map<String, InetAddress> builtInHosts;
static {
Map<String, InetAddress> map = new HashMap<>();
put(map, "e-hentai.org", "104.24.255.11");
put(map, "forums.e-hentai.org", "94.100.18.243");
builtInHosts = map;
}
private static void put(Map<String, InetAddress> map, String host, String ip) {
InetAddress address = Hosts.toInetAddress(host, ip);
if (address != null) {
map.put(host, address);
}
}
private final Hosts hosts;
public EhDns(Context context) {
hosts = EhApplication.getHosts(context);
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname == null) throw new UnknownHostException("hostname == null");
InetAddress inetAddress = hosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
if (Settings.getBuiltInHosts()) {
inetAddress = builtInHosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
}
try {
return Arrays.asList(InetAddress.getAllByName(hostname));
} catch (NullPointerException e) {
UnknownHostException unknownHostException =
new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
}
@@ -17,9 +17,9 @@
package com.hippo.ehviewer.client;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
@@ -30,9 +30,7 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewSet;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.NoHAtHClientException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ArchiveParser;
import com.hippo.ehviewer.client.parser.FavoritesParser;
import com.hippo.ehviewer.client.parser.ForumsParser;
import com.hippo.ehviewer.client.parser.GalleryApiParser;
@@ -47,13 +45,17 @@ import com.hippo.ehviewer.client.parser.TorrentParser;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.network.StatusCodeException;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
@@ -63,11 +65,6 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class EhEngine {
@@ -80,16 +77,14 @@ public class EhEngine {
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
private static final Pattern PATTERN_NEED_HATH_CLIENT = Pattern.compile("(You must have a H@H client assigned to your account to use this feature\\.)");
public static EhFilter sEhFilter;
public static void initialize() {
sEhFilter = EhFilter.getInstance();
}
private static void doThrowException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Throwable e) throws Throwable {
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
if (call.isCanceled()) {
throw new CancelledException();
}
@@ -115,34 +110,16 @@ public class EhEngine {
if (code >= 400) {
throw new StatusCodeException(code);
}
if (e != null) {
throw e;
}
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Throwable e) throws Throwable {
try {
doThrowException(call, code, headers, body, e);
} catch (Throwable error) {
error.printStackTrace();
throw error;
}
}
public static String signIn(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String username, String password, String recaptchaChallenge, String recaptchaResponse) throws Throwable {
String username, String password) throws Exception {
FormBody.Builder builder = new FormBody.Builder()
.add("UserName", username)
.add("PassWord", password)
.add("submit", "Log me in")
.add("CookieDate", "1")
.add("temporary_https", "off");
if (!TextUtils.isEmpty(recaptchaChallenge) && !TextUtils.isEmpty(recaptchaResponse)) {
builder.add("recaptcha_challenge_field", recaptchaChallenge);
builder.add("recaptcha_response_field", recaptchaResponse);
}
String url = EhUrl.API_SIGN_IN;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
@@ -164,15 +141,14 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return SignInParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryListParser.Result getGalleryList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -192,8 +168,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -209,7 +184,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -224,16 +199,12 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
// At least, GalleryInfo contain valid gid and token
public static List<GalleryInfo> fillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Throwable {
List<GalleryInfo> galleryInfoList) throws Exception {
// We can only request 25 items one time at most
final int MAX_REQUEST_SIZE = 25;
List<GalleryInfo> requestItems = new ArrayList<>(MAX_REQUEST_SIZE);
@@ -248,7 +219,7 @@ public class EhEngine {
}
private static void doFillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Throwable {
List<GalleryInfo> galleryInfoList) throws Exception {
JSONObject json = new JSONObject();
json.put("method", "gdata");
JSONArray ja = new JSONArray();
@@ -282,15 +253,14 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
GalleryApiParser.parse(body, galleryInfoList);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryDetail getGalleryDetail(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -309,8 +279,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryDetailParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -318,7 +287,7 @@ public class EhEngine {
public static Pair<PreviewSet, Integer> getPreviewSet(
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Throwable {
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -338,8 +307,7 @@ public class EhEngine {
body = response.body().string();
return Pair.create(GalleryDetailParser.parsePreviewSet(body),
GalleryDetailParser.parsePreviewPages(body));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -347,7 +315,7 @@ public class EhEngine {
public static RateGalleryParser.Result rateGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, long apiUid, String apiKey, long gid,
String token, float rating) throws Throwable {
String token, float rating) throws Exception {
final JSONObject json = new JSONObject();
json.put("method", "rategallery");
json.put("apiuid", apiUid);
@@ -377,17 +345,17 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return RateGalleryParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment) throws Throwable {
OkHttpClient okHttpClient, String url, String comment) throws Exception {
FormBody.Builder builder = new FormBody.Builder()
.add("commenttext_new", comment);
.add("commenttext", comment)
.add("postcomment", "Post New");
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
.post(builder.build())
@@ -408,22 +376,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
Document document = Jsoup.parse(body);
Elements elements = document.select("#chd + p");
if (elements.size() > 0) {
throw new EhException(elements.get(0).text());
}
return GalleryDetailParser.parseComments(document);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static String getGalleryToken(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String gtoken, int page) throws Throwable {
long gid, String gtoken, int page) throws Exception {
JSONObject json = new JSONObject()
.put("method", "gtoken")
.put("pagelist", new JSONArray().put(
@@ -450,15 +411,14 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryTokenApiParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static FavoritesParser.Result getFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, boolean callApi) throws Throwable {
String url, boolean callApi) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -478,20 +438,13 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
return result;
@@ -502,7 +455,7 @@ public class EhEngine {
* @param note max 250 characters
*/
public static Void addFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, int dstCat, String note) throws Throwable {
long gid, String token, int dstCat, String note) throws Exception {
String catStr;
if (dstCat == -1) {
catStr = "favdel";
@@ -538,8 +491,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -548,8 +500,8 @@ public class EhEngine {
}
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Throwable {
AssertUtils.assertEquals(gidArray.length, tokenArray.length);
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
AssertUtils.assertEqualsEx(gidArray.length, tokenArray.length);
for (int i = 0, n = gidArray.length; i < n; i++) {
addFavorites(task, okHttpClient, gidArray[i], tokenArray[i], dstCat, null);
}
@@ -557,7 +509,7 @@ public class EhEngine {
}
public static FavoritesParser.Result modifyFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, long[] gidArray, int dstCat, boolean callApi) throws Throwable {
String url, long[] gidArray, int dstCat, boolean callApi) throws Exception {
String catStr;
if (dstCat == -1) {
catStr = "delete";
@@ -593,26 +545,20 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
return result;
}
public static Pair<String, String>[] getTorrentList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -632,8 +578,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = TorrentParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -641,84 +586,9 @@ public class EhEngine {
return result;
}
public static Pair<String, Pair<String, String>[]> getArchiveList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
Pair<String, Pair<String, String>[]> result;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
result = ArchiveParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
return result;
}
public static Void downloadArchive(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, String or, String res) throws Throwable {
if (or == null || or.length() == 0) {
throw new EhException("Invalid form param or: " + or);
}
if (res == null || res.length() == 0) {
throw new EhException("Invalid res: " + res);
}
FormBody.Builder builder = new FormBody.Builder();
builder.add("hathdl_xres", res);
String url = EhUrl.getDownloadArchive(gid, token, or);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
Matcher m = PATTERN_NEED_HATH_CLIENT.matcher(body);
if (m.find()) {
throw new NoHAtHClientException("No H@H client");
}
return null;
}
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Throwable {
String url = EhUrl.HOST_E;
OkHttpClient okHttpClient) throws Exception {
String url = EhUrl.HOST_G;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -738,8 +608,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
list = WhatsHotParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -749,15 +618,11 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return list;
}
private static ProfileParser.Result getProfileInternal(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Throwable {
OkHttpClient okHttpClient, String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -776,15 +641,14 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return ProfileParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static ProfileParser.Result getProfile(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Throwable {
OkHttpClient okHttpClient) throws Exception {
String url = EhUrl.URL_FORUMS;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
@@ -804,15 +668,14 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
}
public static VoteCommentParser.Result voteComment(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Throwable {
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Exception {
final JSONObject json = new JSONObject();
json.put("method", "votecomment");
json.put("apiuid", apiUid);
@@ -843,8 +706,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return VoteCommentParser.parse(body, commentVote);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -854,7 +716,7 @@ public class EhEngine {
* @param image Must be jpeg
*/
public static GalleryListParser.Result imageSearch(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
File image, boolean uss, boolean osc, boolean se) throws Throwable {
File image, boolean uss, boolean osc, boolean se) throws Exception {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addPart(
@@ -908,8 +770,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -925,7 +786,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -940,15 +801,11 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
public static GalleryPageParser.Result getGalleryPage(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Throwable {
OkHttpClient okHttpClient, String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -967,8 +824,7 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryPageParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
@@ -92,8 +92,6 @@ public final class EhFilter {
}
public synchronized void addFilter(Filter filter) {
// enable filter by default before it is added to database
filter.enable = true;
EhDB.addFilter(filter);
switch (filter.mode) {
@@ -118,10 +116,6 @@ public final class EhFilter {
}
}
public synchronized void triggerFilter(Filter filter) {
EhDB.triggerFilter(filter);
}
public synchronized void deleteFilter(Filter filter) {
EhDB.deleteFilter(filter);
@@ -159,7 +153,7 @@ public final class EhFilter {
if (null != title && filters.size() > 0) {
title = title.toLowerCase();
for (int i = 0, n = filters.size(); i < n; i++) {
if (filters.get(i).enable && title.contains(filters.get(i).text)) {
if (title.contains(filters.get(i).text)) {
return false;
}
}
@@ -178,7 +172,7 @@ public final class EhFilter {
List<Filter> filters = mUploaderFilterList;
if (null != uploader && filters.size() > 0) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (filters.get(i).enable && uploader.equals(filters.get(i).text)) {
if (uploader.equals(filters.get(i).text)) {
return false;
}
}
@@ -235,7 +229,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (filters.get(i).enable && matchTag(tag, filters.get(i).text)) {
if (matchTag(tag, filters.get(i).text)) {
return false;
}
}
@@ -270,7 +264,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (filters.get(i).enable && matchTagNamespace(tag, filters.get(i).text)) {
if (matchTagNamespace(tag, filters.get(i).text)) {
return false;
}
}
@@ -17,44 +17,35 @@
package com.hippo.ehviewer.client;
import android.support.annotation.NonNull;
import com.hippo.ehviewer.Settings;
import com.hippo.network.UrlBuilder;
import java.util.List;
import java.util.ListIterator;
import okhttp3.HttpUrl;
public class EhUrl {
public static final int SITE_E = 0;
public static final int SITE_G = 0;
public static final int SITE_EX = 1;
public static final String DOMAIN_EX = "exhentai.org";
public static final String DOMAIN_E = "e-hentai.org";
public static final String DOMAIN_G = "g.e-hentai.org";
public static final String DOMAIN_LOFI = "lofi.e-hentai.org";
public static final String HOST_EX = "https://" + DOMAIN_EX + "/";
public static final String HOST_E = "https://" + DOMAIN_E + "/";
public static final String HOST_E = "http://" + DOMAIN_E + "/";
public static final String HOST_EX = "http://" + DOMAIN_EX + "/";
public static final String HOST_G = "http://" + DOMAIN_G + "/";
public static final String API_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_E = HOST_E + "api.php";
public static final String API_G = HOST_G + "api.php";
public static final String API_EX = HOST_EX + "api.php";
public static final String URL_IMAGE_SEARCH_E = "https://upload.e-hentai.org/image_lookup.php";
public static final String URL_IMAGE_SEARCH_EX = "https://exhentai.org/upload/image_lookup.php";
public static final String URL_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "https://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_E = HOST_E + "favorites.php";
public static final String URL_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "http://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_G = HOST_G + "favorites.php";
public static final String URL_FAVORITES_EX = HOST_EX + "favorites.php";
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
public static final String UCONFIG_E = HOST_E + "uconfig.php";
public static final String UCONFIG_EX = HOST_EX + "uconfig.php";
private static final String URL_PREFIX_THUMB_E = "https://ehgt.org/t/";
private static final String URL_PREFIX_THUMB_EX = "https://exhentai.org/t/";
public static String getGalleryDetailUrl(long gid, String token) {
return getGalleryDetailUrl(gid, token, 0, false);
}
@@ -62,8 +53,8 @@ public class EhUrl {
public static String getHost() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return HOST_E;
case SITE_G:
return HOST_G;
case SITE_EX:
return HOST_EX;
}
@@ -72,8 +63,8 @@ public class EhUrl {
public static String getFavoritesUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return URL_FAVORITES_E;
case SITE_G:
return URL_FAVORITES_G;
case SITE_EX:
return URL_FAVORITES_EX;
}
@@ -82,23 +73,13 @@ public class EhUrl {
public static String getApiUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return API_E;
case SITE_G:
return API_G;
case SITE_EX:
return API_EX;
}
}
public static String getUConfigUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return UCONFIG_E;
case SITE_EX:
return UCONFIG_EX;
}
}
public static String getGalleryDetailUrl(long gid, String token, int index, boolean allComment) {
UrlBuilder builder = new UrlBuilder(getHost() + "g/" + gid + '/' + token + '/');
if (index != 0) {
@@ -118,10 +99,6 @@ public class EhUrl {
return getHost() + "gallerypopups.php?gid=" + gid + "&t=" + token + "&act=addfav";
}
public static String getDownloadArchive(long gid, String token, String or) {
return getHost() + "archiver.php?gid=" + gid + "&token=" + token + "&or=" + or;
}
public static String getTagDefinitionUrl(String tag) {
return "https://ehwiki.org/wiki/" + tag.replace(' ', '_');
}
@@ -130,50 +107,10 @@ public class EhUrl {
public static String getImageSearchUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return URL_IMAGE_SEARCH_E;
case SITE_G:
return "http://ul.e-hentai.org/image_lookup.php";
case SITE_EX:
return URL_IMAGE_SEARCH_EX;
}
}
public static String getThumbUrlPrefix() {
switch (Settings.getGallerySite()) {
default:
//case SITE_E:
return URL_PREFIX_THUMB_E;
//case SITE_EX:
// return URL_PREFIX_THUMB_EX;
}
}
public static String getFixedPreviewThumbUrl(String originUrl) {
HttpUrl url = HttpUrl.parse(originUrl);
if (url == null) return originUrl;
List<String> pathSegments = url.pathSegments();
if (pathSegments == null || pathSegments.size() < 3) return originUrl;
ListIterator<String> iterator = pathSegments.listIterator(pathSegments.size());
// The last segments, like
// 317a1a254cd9c3269e71b2aa2671fe8d28c91097-260198-640-480-png_250.jpg
if (!iterator.hasPrevious()) return originUrl;
String lastSegment = iterator.previous();
// The second last segments, like
// 7a
if (!iterator.hasPrevious()) return originUrl;
String secondLastSegment = iterator.previous();
// The third last segments, like
// 31
if (!iterator.hasPrevious()) return originUrl;
String thirdLastSegment = iterator.previous();
// Check path segments
if (lastSegment != null && secondLastSegment != null
&& thirdLastSegment != null
&& lastSegment.startsWith(thirdLastSegment)
&& lastSegment.startsWith(secondLastSegment, thirdLastSegment.length())) {
return getThumbUrlPrefix() + thirdLastSegment + "/" + secondLastSegment + "/" + lastSegment;
} else {
return originUrl;
return "http://ul.exhentai.org/image_lookup.php";
}
}
}
@@ -27,7 +27,6 @@ public class GalleryDetail extends GalleryInfo {
public String apiKey;
public int torrentCount;
public String torrentUrl;
public String archiveUrl;
public String parent;
public String visible;
public String language;
@@ -40,7 +39,6 @@ public class GalleryDetail extends GalleryInfo {
public GalleryComment[] comments;
public int previewPages;
public PreviewSet previewSet;
public String favoriteName;
@Override
public int describeContents() {
@@ -52,7 +50,6 @@ public class GalleryDetail extends GalleryInfo {
super.writeToParcel(dest, flags);
dest.writeInt(this.torrentCount);
dest.writeString(this.torrentUrl);
dest.writeString(this.archiveUrl);
dest.writeString(this.parent);
dest.writeString(this.visible);
dest.writeString(this.language);
@@ -65,7 +62,6 @@ public class GalleryDetail extends GalleryInfo {
dest.writeParcelableArray(this.comments, 0);
dest.writeInt(this.previewPages);
dest.writeParcelable(previewSet, flags);
dest.writeString(this.favoriteName);
}
public GalleryDetail() {
@@ -75,7 +71,6 @@ public class GalleryDetail extends GalleryInfo {
super(in);
this.torrentCount = in.readInt();
this.torrentUrl = in.readString();
this.archiveUrl = in.readString();
this.parent = in.readString();
this.visible = in.readString();
this.language = in.readString();
@@ -98,7 +93,6 @@ public class GalleryDetail extends GalleryInfo {
}
this.previewPages = in.readInt();
this.previewSet = in.readParcelable(PreviewSet.class.getClassLoader());
this.favoriteName = in.readString();
}
public static final Creator<GalleryDetail> CREATOR = new Creator<GalleryDetail>() {
@@ -63,8 +63,7 @@ public class GalleryInfo implements Parcelable {
public static final Pattern[] S_LANG_PATTERNS = {
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
// [((\[]ch(?:inese)?[))\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳
Pattern.compile("[(\uFF08\\[]ch(?:inese)?[)\uFF09\\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]korean?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]", Pattern.CASE_INSENSITIVE),
@@ -79,23 +78,6 @@ public class GalleryInfo implements Parcelable {
Pattern.compile("[(\\[]dutch[)\\]]", Pattern.CASE_INSENSITIVE),
};
public static final String[] S_LANG_TAGS = {
"language:english",
"language:chinese",
"language:spanish",
"language:korean",
"language:russian",
"language:french",
"language:portuguese",
"language:thai",
"language:german",
"language:italian",
"language:vietnamese",
"language:polish",
"language:hungarian",
"language:dutch",
};
public long gid ;
public String token;
public String title;
@@ -107,7 +89,6 @@ public class GalleryInfo implements Parcelable {
public float rating;
@Nullable
public String[] simpleTags;
public int pages;
public int thumbWidth;
public int thumbHeight;
@@ -122,26 +103,6 @@ public class GalleryInfo implements Parcelable {
public String simpleLanguage;
public final void generateSLang() {
if (simpleTags != null) {
generateSLangFromTags();
}
if (simpleLanguage == null && title != null) {
generateSLangFromTitle();
}
}
private void generateSLangFromTags() {
for (String tag : simpleTags) {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_TAGS[i].equals(tag)) {
simpleLanguage = S_LANGS[i];
return;
}
}
}
}
private void generateSLangFromTitle() {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_PATTERNS[i].matcher(title).find()) {
simpleLanguage = S_LANGS[i];
@@ -21,7 +21,7 @@ import android.os.Parcelable;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.widget.LoadImageView;
import com.hippo.yorozuya.collect.IntList;
import com.hippo.yorozuya.IntList;
import java.util.ArrayList;
@@ -19,7 +19,7 @@ package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import com.hippo.widget.LoadImageView;
import com.hippo.yorozuya.collect.IntList;
import com.hippo.yorozuya.IntList;
import java.util.ArrayList;
@@ -1,48 +0,0 @@
/*
* Copyright 2016 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.client.parser;
import android.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArchiveParser {
private static final Pattern PATTERN_FORM = Pattern.compile("<form id=\"hathdl_form\" action=\"[^\"]*?or=([^=\"]*?)\" method=\"post\">");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a href=\"[^\"]*\" onclick=\"return do_hathdl\\('([0-9]+|org)'\\)\">([^<]+)</a>");
@SuppressWarnings("unchecked")
public static Pair<String, Pair<String, String>[]> parse(String body) {
Matcher m = PATTERN_FORM.matcher(body);
if (!m.find()) {
return new Pair<String, Pair<String, String>[]>("", new Pair[0]);
}
String paramOr = m.group(1);
List<Pair<String, String>> archiveList = new ArrayList<>();
m = PATTERN_ARCHIVE.matcher(body);
while (m.find()) {
String res = ParserUtils.trim(m.group(1));
String name = ParserUtils.trim(m.group(2));
Pair<String, String> item = new Pair<>(res, name);
archiveList.add(item);
}
return new Pair<String, Pair<String, String>[]>(paramOr, archiveList.toArray(new Pair[archiveList.size()]));
}
}
@@ -21,15 +21,16 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.AssertUtils;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.List;
public class FavoritesParser {
public static class Result {
@@ -52,15 +53,14 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
AssertUtils.assertEquals(11, fps.size());
AssertUtils.assertEqualsEx(11, fps.size());
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
countArray[i] = ParserUtils.parseInt(fp.child(0).text());
catArray[i] = ParserUtils.trim(fp.child(2).text());
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
throw new ParseException("Parse favorites error", body);
}
@@ -18,7 +18,7 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -31,8 +31,7 @@ public class ForumsParser {
Element userlinks = d.getElementById("userlinks");
Element child = userlinks.child(0).child(0).child(0);
return child.attr("href");
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Parse forums error", body);
}
}
@@ -53,8 +53,6 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = Integer.parseInt(g.getString("filecount"));
gi.generateSLang();
}
}
@@ -19,8 +19,7 @@ package com.hippo.ehviewer.client.parser;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.data.GalleryDetail;
@@ -32,10 +31,15 @@ import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.OffensiveException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.exception.PiningException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -46,18 +50,12 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GalleryDetailParser {
private static final Pattern PATTERN_ERROR = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
private static final Pattern PATTERN_DETAIL = Pattern.compile("var gid = (\\d+);.+?var token = \"([a-f0-9]+)\";.+?var apiuid = ([\\-\\d]+);.+?var apikey = \"([a-f0-9]+)\";", Pattern.DOTALL);
private static final Pattern PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Archive Download</a>");
private static final Pattern PATTERN_COVER = Pattern.compile("width:(\\d+)px; height:(\\d+)px.+?url\\((.+?)\\)");
private static final Pattern PATTERN_TAG_GROUP = Pattern.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
private static final Pattern PATTERN_TAG = Pattern.compile("<div[^<>]+><a[^<>]+>([\\w\\s]+)</a></div>");
private static final Pattern PATTERN_COMMENT = Pattern.compile("<div class=\"c3\">Posted on ([^<>]+) by: &nbsp; <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
@@ -126,22 +124,14 @@ public class GalleryDetailParser {
gd.torrentUrl = "";
}
matcher = PATTERN_ARCHIVE.matcher(body);
if (matcher.find()) {
gd.archiveUrl = StringUtils.unescapeXml(StringUtils.trim(matcher.group(1)));
} else {
gd.archiveUrl = "";
}
try {
Element gm = JsoupUtils.getElementByClass(d, "gm");
// Thumb url
Element gd1 = gm.getElementById("gd1");
try {
gd.thumb = parseCoverStyle(StringUtils.trim(gd1.child(0).attr("style")));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.thumb = EhUtils.handleThumbUrlResolution(StringUtils.trim(gd1.child(0).attr("src")));
} catch (Exception e) {
gd.thumb = "";
}
@@ -164,11 +154,8 @@ public class GalleryDetailParser {
// Category
Element gdc = gm.getElementById("gdc");
try {
String href = gdc.child(0).attr("href");
String category = href.substring(href.lastIndexOf('/') + 1);
gd.category = EhUtils.getCategory(category);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.category = EhUtils.getCategory(gdc.child(0).child(0).attr("alt"));
} catch (Exception e) {
gd.category = EhUtils.UNKNOWN;
}
@@ -193,8 +180,7 @@ public class GalleryDetailParser {
for (int i = 0, n = es.size(); i < n; i++) {
parseDetailInfo(gd, es.get(i), body);
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
@@ -228,30 +214,11 @@ public class GalleryDetailParser {
// isFavorited
Element gdf = gm.getElementById("gdf");
gd.isFavorited = null != gdf && !StringUtils.trim(gdf.text()).equals("Add to Favorites");
if (gdf != null) {
final String favoriteName = StringUtils.trim(gdf.text());
if (favoriteName.equals("Add to Favorites")) {
gd.favoriteName = null;
} else {
gd.favoriteName = StringUtils.trim(gdf.text());
}
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Can't parse gallery detail", body);
}
}
// width:250px; height:356px; background:transparent url(https://exhentai.org/t/fe/1f/fe1fcfa9bf8fba2f03982eda0aa347cc9d6a6372-145921-1050-1492-jpg_250.jpg) 0 0 no-repeat
private static String parseCoverStyle(String str) {
Matcher matcher = PATTERN_COVER.matcher(str);
if (matcher.find()) {
return EhUtils.handleThumbUrlResolution(matcher.group(3));
} else {
return "";
}
}
private static void parseDetailInfo(GalleryDetail gd, Element e, String body) {
Elements es = e.children();
if (es.size() < 2) {
@@ -313,14 +280,13 @@ public class GalleryDetailParser {
// Sometimes parody tag is followed with '|' and english translate, just remove them
int index = tag.indexOf('|');
if (index >= 0) {
tag = tag.substring(0, index).trim();
tag = tag.substring(0, index);
}
group.addTag(tag);
}
return group.size() > 0 ? group : null;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
return null;
}
@@ -343,8 +309,7 @@ public class GalleryDetailParser {
}
}
return list.toArray(new GalleryTagGroup[list.size()]);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
return EMPTY_GALLERY_TAG_GROUP_ARRAY;
}
@@ -409,15 +374,14 @@ public class GalleryDetailParser {
// time
Element c3 = JsoupUtils.getElementByClass(element, "c3");
String temp = c3.ownText();
temp = temp.substring("Posted on ".length(), temp.length() - " by:".length());
temp = temp.substring("Posted on ".length(), temp.length() - " by:  ".length());
comment.time = WEB_COMMENT_DATE_FORMAT.parse(temp).getTime();
// user
comment.user = c3.child(0).text();
// comment
comment.comment = JsoupUtils.getElementByClass(element, "c6").html();
return comment;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
return null;
}
@@ -440,8 +404,7 @@ public class GalleryDetailParser {
}
}
return list.toArray(new GalleryComment[list.size()]);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
return EMPTY_GALLERY_COMMENT_ARRAY;
}
@@ -480,8 +443,7 @@ public class GalleryDetailParser {
try {
Elements elements = document.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(elements.get(elements.size() - 2).text());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
throw new ParseException("Can't parse preview pages", body);
}
@@ -549,15 +511,11 @@ public class GalleryDetailParser {
String pageUrl = element.attr("href");
element = element.child(0);
String imageUrl = element.attr("src");
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
int index = Integer.parseInt(element.attr("alt")) - 1;
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
return largePreviewSet;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
throw new ParseException("Can't parse large preview", body);
}
@@ -571,13 +529,8 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
int index = ParserUtils.parseInt(m.group(2)) - 1;
String imageUrl = ParserUtils.trim(m.group(3));
String pageUrl = ParserUtils.trim(m.group(1));
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
largePreviewSet.addItem(index, imageUrl, pageUrl);
largePreviewSet.addItem(ParserUtils.parseInt(m.group(2)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.trim(m.group(1)));
}
if (largePreviewSet.size() == 0) {
@@ -29,25 +29,16 @@ import java.util.regex.Pattern;
*/
public final class GalleryDetailUrlParser {
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/(?:g|mpv)/(\\d+)/([0-9a-f]{10})");
private static final Pattern URL_PATTERN = Pattern.compile(
"(\\d+)/([0-9a-f]{10})");
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
Matcher m = pattern.matcher(url);
Matcher m = URL_PATTERN.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(1));
@@ -19,22 +19,24 @@ package com.hippo.ehviewer.client.parser;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GalleryListParser {
@@ -52,8 +54,7 @@ public class GalleryListParser {
try {
Elements es = d.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(es.get(es.size() - 2).text().trim());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Can't parse gallery list pages", body);
}
}
@@ -142,18 +143,18 @@ public class GalleryListParser {
// Title (required)
Element it5 = JsoupUtils.getElementByClass(e, "it5");
if (null == it5) {
Log.e(TAG, "Can't parse gallery info title, step 1");
Log.e(TAG, "Can't parse gallery info title");
return null;
}
Elements es = it5.children();
if (null == es || es.size() <= 0) {
Log.e(TAG, "Can't parse gallery info title, step 2");
Log.e(TAG, "Can't parse gallery info title");
return null;
}
Element a = es.get(0);
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (null == result) {
Log.e(TAG, "Can't parse gallery info title, step 3");
Log.e(TAG, "Can't parse gallery info title");
return null;
}
gi.gid = result.gid;
@@ -181,62 +182,6 @@ public class GalleryListParser {
return gi;
}
@Nullable
private static GalleryInfo parseGalleryInfoThumbVersion(Element e) {
GalleryInfo gi = new GalleryInfo();
// Title (required)
Element id2 = JsoupUtils.getElementByClass(e, "id2");
if (id2 == null) {
return null;
}
gi.title = id2.text().trim();
// gid, token (required)
Element a = id2.children().first();
if (a == null) {
return null;
}
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (result == null) {
return null;
}
gi.gid = result.gid;
gi.token = result.token;
// Thumbnail
Element id3 = JsoupUtils.getElementByClass(e, "id3");
if (id3 != null) {
a = id3.children().first();
if (a != null) {
Element img = a.children().first();
if (img != null) {
gi.thumb = EhUtils.handleThumbUrlResolution(img.attr("src"));
}
}
}
// Category
Element id41 = JsoupUtils.getElementByClass(e, "id41");
if (id41 != null) {
gi.category = EhUtils.getCategory(id41.attr("title").trim());
} else {
gi.category = EhUtils.UNKNOWN;
}
// Rating
Element id43 = JsoupUtils.getElementByClass(e, "id43");
if (id43 != null) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(id43.attr("style")), -1.0f);
} else {
gi.rating = -1.0f;
}
gi.generateSLang();
return gi;
}
public static Result parse(@NonNull String body) throws Exception {
Result result = new Result();
Document d = Jsoup.parse(body);
@@ -264,29 +209,10 @@ public class GalleryListParser {
}
}
result.galleryInfoList = list;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Can't parse gallery list", body);
}
// Maybe it's thumbnail version
if (result.galleryInfoList.isEmpty()) {
try {
Elements es = d.getElementsByClass("itg").first().children();
List<GalleryInfo> list = new ArrayList<>(es.size() - 1);
for (int i = 0; i < es.size(); i++) {
GalleryInfo gi = parseGalleryInfoThumbVersion(es.get(i));
if (null != gi) {
list.add(gi);
}
}
result.galleryInfoList = list;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery list", body);
}
}
return result;
}
}
@@ -29,7 +29,7 @@ import java.net.URLDecoder;
public final class GalleryListUrlParser {
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_E, EhUrl.DOMAIN_LOFI};
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_G, EhUrl.DOMAIN_LOFI};
private static final String PATH_NORMAL = "/";
private static final String PATH_UPLOADER = "/uploader/";
@@ -26,7 +26,7 @@ import java.util.regex.Pattern;
public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<img[^>]*src=\"([^\"]+)\" style");
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<(?:/iframe|div id=\"i3\")[^>]*><a[^>]+><img[^>]*src=\"(.+?)\"");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
@@ -16,8 +16,8 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -26,25 +26,15 @@ import java.util.regex.Pattern;
*/
public final class GalleryPageUrlParser {
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/([0-9a-f]{10})/(\\d+)-(\\d+)");
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
private static final Pattern URL_PATTERN = Pattern.compile(
"([0-9a-f]{10})/(\\d+)-(\\d+)");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
Matcher m = pattern.matcher(url);
Matcher m = URL_PATTERN.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(2));
@@ -17,7 +17,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.util.ExceptionUtils;
import org.json.JSONObject;
public class GalleryTokenApiParser {
@@ -36,8 +36,7 @@ public class GalleryTokenApiParser {
JSONObject jo = new JSONObject(body).getJSONArray("tokenlist").getJSONObject(0);
try {
return jo.getString("token");
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new EhException(jo.getString("error"));
}
}
@@ -18,9 +18,10 @@ package com.hippo.ehviewer.client.parser;
import android.text.TextUtils;
import android.util.Log;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -42,13 +43,11 @@ public class ProfileParser {
} else if (!result.avatar.startsWith("http")) {
result.avatar = EhUrl.URL_FORUMS + result.avatar;
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
Log.i(TAG, "No avatar");
}
return result;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Parse forums error", body);
}
}
@@ -25,7 +25,7 @@ import java.util.regex.Pattern;
public class TorrentParser {
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\"[^<]+>([^<]+)</a></td>");
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\">([^<]+)</a></td>");
@SuppressWarnings("unchecked")
public static Pair<String, String>[] parse(String body) {
@@ -19,15 +19,16 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class WhatsHotParser {
@SuppressWarnings("ConstantConditions")
@@ -53,8 +54,7 @@ public class WhatsHotParser {
galleryInfoList.add(galleryInfo);
}
return galleryInfoList;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
throw new ParseException("Parse whats hot error", body);
}
}
@@ -16,9 +16,7 @@
package com.hippo.ehviewer.download;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
@@ -27,20 +25,16 @@ import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadInfo;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.LongList;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseIJArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.sparse.SparseIJArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -566,52 +560,6 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
for (DownloadInfoListener l: mDownloadInfoListeners) {
l.onReload();
}
// Ensure download
ensureDownload();
}
@SuppressLint("StaticFieldLeak")
public void resetAllReadingProgress() {
LinkedList<DownloadInfo> list = new LinkedList<>(mAllInfoList);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
GalleryInfo galleryInfo = new GalleryInfo();
for (DownloadInfo downloadInfo : list) {
galleryInfo.gid = downloadInfo.gid;
galleryInfo.token = downloadInfo.token;
galleryInfo.title = downloadInfo.title;
galleryInfo.thumb = downloadInfo.thumb;
galleryInfo.category = downloadInfo.category;
galleryInfo.posted = downloadInfo.posted;
galleryInfo.uploader = downloadInfo.uploader;
galleryInfo.rating = downloadInfo.rating;
UniFile downloadDir = SpiderDen.getGalleryDownloadDir(galleryInfo);
if (downloadDir == null) {
continue;
}
UniFile file = downloadDir.findFile(".ehviewer");
if (file == null) {
continue;
}
SpiderInfo spiderInfo = SpiderInfo.read(file);
if (spiderInfo == null) {
continue;
}
spiderInfo.startPage = 0;
try {
spiderInfo.write(file.openOutputStream());
} catch (IOException e) {
Log.e(TAG, "Can't write SpiderInfo", e);
}
}
return null;
}
}.execute();
}
// Update in DB
@@ -16,14 +16,12 @@
package com.hippo.ehviewer.download;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
@@ -42,10 +40,10 @@ import com.hippo.ehviewer.ui.scene.DownloadsScene;
import com.hippo.scene.StageActivity;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.LongList;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseJBArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.sparse.SparseJBArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -92,8 +90,6 @@ public class DownloadService extends Service implements DownloadManager.Download
private static int sFinishedCount;
private static int sDownloadedCount;
private String CHANNEL_ID;
public static void clear() {
sFailedCount = 0;
sFinishedCount = 0;
@@ -106,12 +102,7 @@ public class DownloadService extends Service implements DownloadManager.Download
public void onCreate() {
super.onCreate();
CHANNEL_ID = getPackageName()+".download";
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
mNotifyManager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, getString(R.string.download_service),
NotificationManager.IMPORTANCE_LOW));
}
mDownloadManager = EhApplication.getDownloadManager(getApplicationContext());
mDownloadManager.setDownloadListener(this);
}
@@ -217,15 +208,14 @@ public class DownloadService extends Service implements DownloadManager.Download
stopAllIntent.setAction(ACTION_STOP_ALL);
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(android.R.drawable.stat_sys_download)
.setOngoing(true)
.setAutoCancel(false)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setColor(getResources().getColor(R.color.colorPrimary))
.addAction(R.drawable.ic_pause_x24, getString(R.string.stat_download_action_stop_all), piStopAll)
.setShowWhen(false)
.setChannelId(CHANNEL_ID);
.setShowWhen(false);
mDownloadingDelay = new NotificationDelay(this, mNotifyManager, mDownloadingBuilder, ID_DOWNLOADING);
}
@@ -248,15 +238,14 @@ public class DownloadService extends Service implements DownloadManager.Download
PendingIntent piActivity = PendingIntent.getActivity(DownloadService.this, 0,
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(getString(R.string.stat_download_done_title))
.setDeleteIntent(piClear)
.setOngoing(false)
.setAutoCancel(true)
.setContentIntent(piActivity)
.setChannelId(CHANNEL_ID);
.setContentIntent(piActivity);
mDownloadedDelay = new NotificationDelay(this, mNotifyManager, mDownloadedBuilder, ID_DOWNLOADED);
}
@@ -266,15 +255,14 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
m509dBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
m509dBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_stat_alert)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentText(getString(R.string.stat_509_alert_title))
.setContentText(getString(R.string.stat_509_alert_text))
.setAutoCancel(true)
.setOngoing(false)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setChannelId(CHANNEL_ID);
.setCategory(NotificationCompat.CATEGORY_ERROR);
m509Delay = new NotificationDelay(this, mNotifyManager, m509dBuilder, ID_509);
}
@@ -1,218 +0,0 @@
/*
* Copyright 2018 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.gallery;
import android.content.Context;
import android.net.Uri;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.archive.Archive;
import com.hippo.ehviewer.gallery.archive.ArchiveEntry;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.unifile.UniRandomAccessFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = ArchiveGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final UniFile file;
private final Stack<Integer> requests = new Stack<>();
private final AtomicInteger decodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@Nullable
private Thread bgThread;
private volatile int size = STATE_WAIT;
private String error;
public ArchiveGalleryProvider(Context context, Uri uri) {
file = UniFile.fromUri(context, uri);
}
@Override
public void start() {
super.start();
bgThread = new PriorityThread(this, TAG + '-' + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
bgThread.start();
}
@Override
public void stop() {
super.stop();
if (bgThread != null) {
bgThread.interrupt();
bgThread = null;
}
}
@Override
public int size() {
return size;
}
@Override
protected void onRequest(int index) {
synchronized (requests) {
if (!requests.contains(index) && index != decodingIndex.get()) {
requests.add(index);
requests.notify();
}
}
notifyPageWait(index);
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
synchronized (requests) {
requests.remove(Integer.valueOf(index));
}
}
@Override
public String getError() {
return error;
}
@NonNull
@Override
public String getImageFilename(int index) {
// TODO
return Integer.toString(index);
}
@Override
public boolean save(int index, @NonNull UniFile file) {
// TODO
return false;
}
@Nullable
@Override
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
// TODO
return null;
}
@Override
public void run() {
UniRandomAccessFile uraf = null;
if (file != null) {
try {
uraf = file.createRandomAccessFile("r");
} catch (IOException e) {
e.printStackTrace();
}
}
if (uraf == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_reading_failed);
notifyDataChanged();
return;
}
Archive archive = null;
try {
archive = Archive.create(uraf);
} catch (IOException e) {
e.printStackTrace();
}
if (archive == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_invalid_archive);
notifyDataChanged();
return;
}
List<ArchiveEntry> entries = archive.getArchiveEntries();
Collections.sort(entries, naturalComparator);
// Update size and notify changed
size = entries.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (requests) {
if (requests.isEmpty()) {
try {
requests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = requests.pop();
decodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= entries.size()) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
try {
InputStream is = entries.get(index).getInputStream();
Image image = Image.decode(is, true);
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} catch (IOException e) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
}
// Clear
IOUtils.closeQuietly(archive);
}
private static Comparator<ArchiveEntry> naturalComparator = new Comparator<ArchiveEntry>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public int compare(ArchiveEntry o1, ArchiveEntry o2) {
return comparator.compare(o1.getName(), o2.getName());
}
};
}
@@ -20,27 +20,28 @@ import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.FilenameFilter;
import com.hippo.unifile.UniFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
public class DirGalleryProvider extends GalleryProvider implements Runnable {
private static final String TAG = DirGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -83,7 +84,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
}
@Override
protected void onRequest(int index) {
public void request(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
@@ -94,12 +95,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
public void onCancelRequest(int index) {
public void cancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
@@ -172,7 +168,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
@Override
public void run() {
// It may take a long time, so run it in new thread
UniFile[] files = mDir.listFiles(imageFilter);
UniFile[] files = mDir.listFiles();
if (files == null) {
mSize = STATE_ERROR;
@@ -186,7 +182,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
}
// Sort it
Arrays.sort(files, naturalComparator);
Arrays.sort(files);
// Put file list
mFileList.lazySet(files);
@@ -243,14 +239,11 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
Log.i(TAG, "ImageDecoder end");
}
private static FilenameFilter imageFilter =
(dir, name) -> StringUtils.endsWith(name.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
private static class ImageFilter implements FilenameFilter {
private static Comparator<UniFile> naturalComparator = new Comparator<UniFile>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public int compare(UniFile o1, UniFile o2) {
return comparator.compare(o1.getName(), o2.getName());
public boolean accept(File dir, String filename) {
return StringUtils.endsWith(filename.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
}
};
}
}
@@ -22,14 +22,13 @@ import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.SimpleHandler;
import java.util.Locale;
public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.OnSpiderListener {
public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.OnSpiderListener {
private final Context mContext;
private final GalleryInfo mGalleryInfo;
@@ -73,7 +72,7 @@ public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.O
@NonNull
@Override
public String getImageFilename(int index) {
return String.format(Locale.US, "%d-%s-%08d", mGalleryInfo.gid, mGalleryInfo.token, index + 1);
return String.format(Locale.US, "%d-%08d", mGalleryInfo.gid, index + 1);
}
@Override
@@ -112,7 +111,7 @@ public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.O
}
@Override
protected void onRequest(int index) {
public void request(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.request(index);
if (object instanceof Float) {
@@ -126,7 +125,7 @@ public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.O
}
@Override
protected void onForceRequest(int index) {
public void forceRequest(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.forceRequest(index);
if (object instanceof Float) {
@@ -140,7 +139,7 @@ public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.O
}
@Override
protected void onCancelRequest(int index) {
public void cancelRequest(int index) {
if (mSpiderQueen != null) {
mSpiderQueen.cancelRequest(index);
}
@@ -0,0 +1,223 @@
/*
* Copyright 2016 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.gallery;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.OSUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public abstract class GalleryProvider {
public static final int STATE_WAIT = -1;
public static final int STATE_ERROR = -2;
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
private final ConcurrentPool<NotifyTask> mNotifyTaskPool = new ConcurrentPool<>(5);
private volatile GalleryProviderListener mGalleryProviderListener;
private volatile GLRoot mGLRoot;
private boolean mStarted = false;
@UiThread
public void start() {
OSUtils.checkMainLoop();
if (mStarted) {
throw new IllegalStateException("Can't start it twice");
}
mStarted = true;
}
@UiThread
public void stop() {
OSUtils.checkMainLoop();
}
public void setGLRoot(GLRoot glRoot) {
mGLRoot = glRoot;
}
/**
* @return {@link #STATE_WAIT} for wait, 0 for empty
*/
public abstract int size();
public abstract void request(int index);
public void forceRequest(int index) {
request(index);
}
public abstract void cancelRequest(int index);
public abstract String getError();
public int getStartPage() {
return 0;
}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
public void putStartPage(int page) {}
public void setGalleryProviderListener(GalleryProviderListener listener) {
mGalleryProviderListener = listener;
}
public void notifyDataChanged() {
notify(NotifyTask.TYPE_DATA_CHANGED, -1, 0.0f, null, null);
}
public void notifyDataChanged(int index) {
notify(NotifyTask.TYPE_DATA_CHANGED, index, 0.0f, null, null);
}
public void notifyPageWait(int index) {
notify(NotifyTask.TYPE_WAIT, index, 0.0f, null, null);
}
public void notifyPagePercent(int index, float percent) {
notify(NotifyTask.TYPE_PERCENT, index, percent, null, null);
}
public void notifyPageSucceed(int index, Image image) {
notify(NotifyTask.TYPE_SUCCEED, index, 0.0f, image, null);
}
public void notifyPageFailed(int index, String error) {
notify(NotifyTask.TYPE_FAILED, index, 0.0f, null, error);
}
private void notify(@NotifyTask.Type int type, int index, float percent, Image image, String error) {
GalleryProviderListener listener = mGalleryProviderListener;
if (listener == null) {
return;
}
GLRoot glRoot = mGLRoot;
if (glRoot == null) {
return;
}
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask(listener, mNotifyTaskPool);
}
task.setData(type, index, percent, image, error);
glRoot.addOnGLIdleListener(task);
}
private static class NotifyTask implements GLRoot.OnGLIdleListener {
@IntDef({TYPE_DATA_CHANGED, NotifyTask.TYPE_WAIT, TYPE_PERCENT, TYPE_SUCCEED, TYPE_FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {}
public static final int TYPE_DATA_CHANGED = 0;
public static final int TYPE_WAIT = 1;
public static final int TYPE_PERCENT = 2;
public static final int TYPE_SUCCEED = 3;
public static final int TYPE_FAILED = 4;
private final GalleryProviderListener mGalleryProviderListener;
private final ConcurrentPool<NotifyTask> mPool;
@Type
private int mType;
private int mIndex;
private float mPercent;
private Image mImage;
private String mError;
public NotifyTask(GalleryProviderListener galleryProviderListener, ConcurrentPool<NotifyTask> pool) {
mGalleryProviderListener = galleryProviderListener;
mPool = pool;
}
public void setData(@Type int type, int index, float percent, Image image, String error) {
mType = type;
mIndex = index;
mPercent = percent;
mImage = image;
mError = error;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
switch (mType) {
case TYPE_DATA_CHANGED:
if (mIndex < 0) {
mGalleryProviderListener.onDataChanged();
} else {
mGalleryProviderListener.onDataChanged(mIndex);
}
break;
case TYPE_WAIT:
mGalleryProviderListener.onPageWait(mIndex);
break;
case TYPE_PERCENT:
mGalleryProviderListener.onPagePercent(mIndex, mPercent);
break;
case TYPE_SUCCEED:
mGalleryProviderListener.onPageSucceed(mIndex, mImage);
break;
case TYPE_FAILED:
mGalleryProviderListener.onPageFailed(mIndex, mError);
break;
}
// Clean data
mImage = null;
mError = null;
// Push back
mPool.push(this);
return false;
}
}
}
@@ -1,54 +0,0 @@
/*
* Copyright 2016 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.gallery;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.unifile.UniFile;
public abstract class GalleryProvider2 extends GalleryProvider {
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
public int getStartPage() {
return 0;
}
public void putStartPage(int page) {}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
}
@@ -0,0 +1,34 @@
/*
* Copyright 2016 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.gallery;
import com.hippo.image.Image;
public interface GalleryProviderListener {
void onDataChanged();
void onPageWait(int index);
void onPagePercent(int index, float percent);
void onPageSucceed(int index, Image image);
void onPageFailed(int index, String error);
void onDataChanged(int index);
}
@@ -0,0 +1,223 @@
/*
* Copyright 2016 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.gallery;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class ZipGalleryProvider extends GalleryProvider implements Runnable {
private static final String TAG = ZipGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final File mFile;
private final Stack<Integer> mRequests = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@Nullable
private Thread mBgThread;
private volatile int mSize = STATE_WAIT;
private String mError;
public ZipGalleryProvider(File file) {
mFile = file;
}
@Override
public void start() {
super.start();
mBgThread = new PriorityThread(this, TAG + '-' + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
mBgThread.start();
}
@Override
public void stop() {
super.stop();
if (mBgThread != null) {
mBgThread.interrupt();
mBgThread = null;
}
}
@Override
public int size() {
return mSize;
}
@Override
public void request(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
mRequests.notify();
}
}
notifyPageWait(index);
}
@Override
public void cancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
}
@Override
public String getError() {
return mError;
}
@NonNull
@Override
public String getImageFilename(int index) {
// TODO
return Integer.toString(index);
}
@Override
public boolean save(int index, @NonNull UniFile file) {
// TODO
return false;
}
@Nullable
@Override
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
// TODO
return null;
}
@Override
public void run() {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(mFile);
} catch (ZipException e) {
mError = GetText.getString(R.string.error_invalid_zip_file);
} catch (FileNotFoundException e) {
mError = GetText.getString(R.string.error_not_found);
} catch (IOException e) {
mError = GetText.getString(R.string.error_reading_failed);
}
// Check zip file null
if (zipFile == null) {
mSize = STATE_ERROR;
// Notify to to show error
notifyDataChanged();
Log.i(TAG, "ImageDecoder end with error");
return;
}
// Get all image name
List<String> filenames = new ArrayList<>(zipFile.size());
Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = enumeration.nextElement();
String filename = zipEntry.getName();
if (!zipEntry.isDirectory() && StringUtils.endsWith(filename, SUPPORT_IMAGE_EXTENSIONS)) {
filenames.add(filename);
}
}
Collections.sort(filenames);
// Update size and notify changed
mSize = filenames.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (mRequests) {
if (mRequests.isEmpty()) {
try {
mRequests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = mRequests.pop();
mDecodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= filenames.size()) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
try {
ZipEntry zipEntry = zipFile.getEntry(filenames.get(index));
if (zipEntry != null) {
InputStream is = zipFile.getInputStream(zipEntry);
Image image = Image.decode(is, true);
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} else {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
} catch (IOException e) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
}
// Clear
try {
zipFile.close();
} catch (IOException e) {
// Ignore
}
Log.i(TAG, "ImageDecoder end");
}
}
@@ -1,91 +0,0 @@
/*
* Copyright 2018 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.gallery.archive;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
public abstract class Archive implements Closeable {
private static final byte[] FILE_SIGNATURE_SEVEN_Z = { 0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C };
private static final byte[] FILE_SIGNATURE_ZIP = { 0x50, 0x4B };
private static final byte[] FILE_SIGNATURE_RAR = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00 };
public abstract List<ArchiveEntry> getArchiveEntries();
public static Archive create(UniRandomAccessFile file) throws IOException {
byte[] bytes = new byte[8];
readFully(file, bytes, 8);
file.seek(0);
if (equals(bytes, FILE_SIGNATURE_SEVEN_Z, FILE_SIGNATURE_SEVEN_Z.length)) {
return SevenZArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_ZIP, FILE_SIGNATURE_ZIP.length)) {
return ZipArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_RAR, FILE_SIGNATURE_RAR.length)) {
return RarArchive.create(file);
}
return null;
}
static boolean isSupportedFilename(String name) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
private static int readFully(UniRandomAccessFile file, byte[] bytes, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = file.read(bytes, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
private static boolean equals(byte[] b1, byte[] b2, int size) {
if (b1.length < size || b2.length < size) {
return false;
}
for (int i = 0; i < size; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
}
@@ -1,198 +0,0 @@
/*
* Copyright 2018 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.gallery.archive;
import com.github.junrar.Volume;
import com.github.junrar.VolumeManager;
import com.github.junrar.exception.RarException;
import com.github.junrar.io.IReadOnlyAccess;
import com.github.junrar.rarfile.FileHeader;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class RarArchive extends Archive {
private com.github.junrar.Archive file;
private RarArchive(com.github.junrar.Archive file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (FileHeader fileHeader : file.getFileHeaders()) {
if (isSupportedFilename(fileHeader.getFileNameString().toLowerCase())) {
result.add(new RarArchiveEntry(file, fileHeader));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
VolumeManager volumeManager = new UniRandomAccessFileVolumeManager(file);
com.github.junrar.Archive archive;
try {
archive = new com.github.junrar.Archive(volumeManager);
if (archive.getMainHeader().isSolid()) {
throw new IOException("Solid archive is not supported");
}
} catch (RarException e) {
throw new IOException("Invalid rar archive", e);
}
return new RarArchive(archive);
}
public static class RarArchiveEntry extends ArchiveEntry {
private com.github.junrar.Archive file;
private FileHeader header;
private RarArchiveEntry(com.github.junrar.Archive file, FileHeader header) {
this.file = file;
this.header = header;
}
@Override
public String getName() {
return header.getFileNameString();
}
@Override
public InputStream getInputStream() throws IOException {
try {
return file.getInputStream(header);
} catch (RarException e) {
throw new IOException("Can't getInputStream from rar archive", e);
}
}
}
private static class UniRandomAccessFileVolumeManager implements VolumeManager {
private UniRandomAccessFile file;
private UniRandomAccessFileVolumeManager(UniRandomAccessFile file) {
this.file = file;
}
@Override
public Volume nextArchive(com.github.junrar.Archive archive, Volume lastVolume) {
if (lastVolume == null) {
return new UniRandomAccessFileVolume(archive, file);
} else {
return null;
}
}
}
private static class UniRandomAccessFileVolume implements Volume {
private com.github.junrar.Archive archive;
private UniRandomAccessFile file;
private UniRandomAccessFileVolume(com.github.junrar.Archive archive, UniRandomAccessFile file) {
this.archive = archive;
this.file = file;
}
@Override
public IReadOnlyAccess getReadOnlyAccess() {
return new UniReadOnlyAccessFile(file);
}
@Override
public long getLength() throws IOException {
return file.length();
}
@Override
public com.github.junrar.Archive getArchive() {
return archive;
}
}
private static class UniReadOnlyAccessFile implements IReadOnlyAccess {
private UniRandomAccessFile file;
private UniReadOnlyAccessFile(UniRandomAccessFile file) {
this.file = file;
}
@Override
public long getPosition() throws IOException {
return file.getFilePointer();
}
@Override
public void setPosition(long pos) throws IOException {
file.seek(pos);
}
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (file.read(b) == -1) {
return -1;
} else {
return b[0];
}
}
@Override
public int read(byte[] buffer, int off, int count) throws IOException {
return file.read(buffer, off, count);
}
@Override
public int readFully(byte[] buffer, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = read(buffer, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
@Override
public void close() throws IOException {
file.close();
}
}
}
@@ -1,96 +0,0 @@
/*
* Copyright 2018 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.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
public class SevenZArchive extends Archive {
private SevenZFile file;
public SevenZArchive(SevenZFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry archive : file.getEntries()) {
if (archive.getSize() != 0
&& !archive.isDirectory()
&& isSupportedFilename(archive.getName().toLowerCase())) {
result.add(new SevenZArchiveEntry(file, archive));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
SevenZFile sevenZFile = new SevenZFile(store);
// Check whether the archive is solid
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry : sevenZFile.getEntries()) {
if (entry.getSize() != 0
&& !entry.isDirectory()
&& !entry.isFirstInFolder()) {
throw new IOException("Solid archive is not supported");
}
}
return new SevenZArchive(sevenZFile);
}
public static class SevenZArchiveEntry extends ArchiveEntry {
private SevenZFile file;
private org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry;
private SevenZArchiveEntry(
SevenZFile file,
org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
file.setEntry(entry);
return file.getInputStreamForCurrentEntry();
}
}
}
@@ -1,86 +0,0 @@
/*
* Copyright 2018 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.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.zip.ZipFile;
public class ZipArchive extends Archive {
private ZipFile file;
private ZipArchive(ZipFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
Enumeration<org.apache.commons.compress.archivers.zip.ZipArchiveEntry> entries = file.getEntries();
while (entries.hasMoreElements()) {
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry = entries.nextElement();
if (isSupportedFilename(entry.getName().toLowerCase())) {
result.add(new ZipArchiveEntry(file, entry));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
ZipFile zipFile = new ZipFile(store);
return new ZipArchive(zipFile);
}
public static class ZipArchiveEntry extends ArchiveEntry {
private ZipFile file;
private org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry;
private ZipArchiveEntry(
ZipFile file,
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
return file.getInputStream(entry);
}
}
}
@@ -0,0 +1,67 @@
/*
* Copyright 2016 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.gallery.gl;
import android.view.MotionEvent;
public class DownUpDetector {
public interface DownUpListener {
void onDown(MotionEvent e);
void onUp(MotionEvent e);
void onPointerDown(MotionEvent e);
void onPointerUp(MotionEvent e);
}
private boolean mStillDown;
private DownUpListener mListener;
public DownUpDetector(DownUpListener listener) {
mListener = listener;
}
private void setState(boolean down, MotionEvent e) {
if (down == mStillDown) return;
mStillDown = down;
if (down) {
mListener.onDown(e);
} else {
mListener.onUp(e);
}
}
public void onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
setState(true, ev);
break;
case MotionEvent.ACTION_POINTER_DOWN:
mListener.onPointerDown(ev);
break;
case MotionEvent.ACTION_UP:
mListener.onPointerUp(ev);
setState(false, ev);
break;
case MotionEvent.ACTION_CANCEL:
setState(false, ev);
break;
}
}
public boolean isDown() {
return mStillDown;
}
}
@@ -0,0 +1,138 @@
/*
* Copyright 2016 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.gallery.gl;
import android.content.Context;
import android.hardware.SensorManager;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import com.hippo.gl.anim.Animation;
public abstract class Fling extends Animation {
private static final float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));
private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)
private static final float START_TENSION = 0.5f;
private static final float END_TENSION = 1.0f;
private static final float P1 = START_TENSION * INFLEXION;
private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);
private static final float FLING_FRICTION = ViewConfiguration.getScrollFriction();
private static final int NB_SAMPLES = 100;
private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1];
private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1];
private float mPhysicalCoeff;
static {
float x_min = 0.0f;
float y_min = 0.0f;
for (int i = 0; i < NB_SAMPLES; i++) {
final float alpha = (float) i / NB_SAMPLES;
float x_max = 1.0f;
float x, tx, coef;
while (true) {
x = x_min + (x_max - x_min) / 2.0f;
coef = 3.0f * x * (1.0f - x);
tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x;
if (Math.abs(tx - alpha) < 1E-5) break;
if (tx > alpha) x_max = x;
else x_min = x;
}
SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x;
float y_max = 1.0f;
float y, dy;
while (true) {
y = y_min + (y_max - y_min) / 2.0f;
coef = 3.0f * y * (1.0f - y);
dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y;
if (Math.abs(dy - alpha) < 1E-5) break;
if (dy > alpha) y_max = y;
else y_min = y;
}
SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y;
}
SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;
}
private static final Interpolator FLING_INTERPOLATOR = new Interpolator() {
@Override
public float getInterpolation(float input) {
final int index = (int) (NB_SAMPLES * input);
float distanceCoef = 1.f;
float velocityCoef = 0.f;
if (index < NB_SAMPLES) {
final float t_inf = (float) index / NB_SAMPLES;
final float t_sup = (float) (index + 1) / NB_SAMPLES;
final float d_inf = SPLINE_POSITION[index];
final float d_sup = SPLINE_POSITION[index + 1];
velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
distanceCoef = d_inf + (input - t_inf) * velocityCoef;
}
return distanceCoef;
}
};
public Fling(Context context) {
final float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
mPhysicalCoeff = SensorManager.GRAVITY_EARTH // g (m/s^2)
* 39.37f // inch/meter
* ppi
* 0.84f; // look and feel tuning
setInterpolator(FLING_INTERPOLATOR);
}
private double getSplineDeceleration(int velocity) {
return Math.log(INFLEXION * Math.abs(velocity) / (FLING_FRICTION * mPhysicalCoeff));
}
/* Returns the duration, expressed in milliseconds */
protected int getSplineFlingDuration(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return (int) (1000.0 * Math.exp(l / decelMinusOne));
}
protected double getSplineFlingDistance(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return FLING_FRICTION * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * l);
}
/**
* Modifies mDuration to the duration it takes to get from start to newFinal using the
* spline interpolation. The previous duration was needed to get to oldFinal.
**/
protected int adjustDuration(int start, int oldFinal, int newFinal, int duration) {
final int oldDistance = oldFinal - start;
final int newDistance = newFinal - start;
final float x = Math.abs((float) newDistance / oldDistance);
final int index = (int) (NB_SAMPLES * x);
if (index < NB_SAMPLES) {
final float x_inf = (float) index / NB_SAMPLES;
final float x_sup = (float) (index + 1) / NB_SAMPLES;
final float t_inf = SPLINE_TIME[index];
final float t_sup = SPLINE_TIME[index + 1];
final float timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf);
duration *= timeCoef;
}
return duration;
}
}
@@ -0,0 +1,188 @@
/*
* Copyright 2016 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.gallery.gl;
import android.content.Context;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.Gravity;
import com.hippo.gl.widget.GLFrameLayout;
import com.hippo.gl.widget.GLLinearLayout;
import com.hippo.gl.widget.GLMovableTextView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
public class GalleryPageView extends GLFrameLayout {
public static final int INVALID_INDEX = -1;
private static final int INFO_INTERVAL = 24;
public static final float PROGRESS_GONE = -1.0f;
public static final float PROGRESS_INDETERMINATE = -2.0f;
private static final int PAGE_MIN_HEIGHT = 256;
private final ImageView mImage;
private final GLLinearLayout mInfo;
private final GLMovableTextView mPage;
private final GLTextureView mError;
private final GLProgressView mProgress;
private final int mPageMinHeight;
private int mIndex = INVALID_INDEX;
public GalleryPageView(Context context, MovableTextTexture pageTextTexture,
int progressColor, int progressSize) {
// Add image
mImage = new ImageView();
GravityLayoutParams glp = new GravityLayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
addComponent(mImage, glp);
// Add other panel
mInfo = new GLLinearLayout();
mInfo.setOrientation(GLLinearLayout.VERTICAL);
mInfo.setInterval(LayoutUtils.dp2pix(context, INFO_INTERVAL));
glp = new GravityLayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
glp.gravity = Gravity.CENTER;
addComponent(mInfo, glp);
// Add page
mPage = new GLMovableTextView();
mPage.setTextTexture(pageTextTexture);
GLLinearLayout.LayoutParams lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mPage, lp);
// Add error
mError = new GLTextureView();
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mError, lp);
// Add progress
mProgress = new GLProgressView();
mProgress.setBgColor(GalleryView.BACKGROUND_COLOR);
mProgress.setColor(progressColor);
mProgress.setMinimumWidth(progressSize);
mProgress.setMinimumHeight(progressSize);
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mProgress, lp);
mPageMinHeight = LayoutUtils.dp2pix(context, PAGE_MIN_HEIGHT);
}
@Override
protected int getSuggestedMinimumHeight() {
// The height of the actual image may be smaller than mPageMinHeight.
// Set min height as 0 when the image is visible.
// For PageLayoutManager, min height is useless.
if (mImage.getVisibility() == VISIBLE) {
return 0;
} else {
return mPageMinHeight;
}
}
int getIndex() {
return mIndex;
}
void setIndex(int index) {
mIndex = index;
}
public void showImage() {
mImage.setVisibility(VISIBLE);
mInfo.setVisibility(GONE);
}
public void showInfo() {
// For image valid rect
mImage.setVisibility(INVISIBLE);
mInfo.setVisibility(VISIBLE);
}
private void unbindImage() {
ImageTexture texture = mImage.getImageTexture();
if (texture != null) {
mImage.setImageTexture(null);
texture.recycle();
}
}
public void setImage(ImageTexture imageTexture) {
unbindImage();
if (imageTexture != null) {
mImage.setImageTexture(imageTexture);
}
}
public void setPage(int page) {
mPage.setText(Integer.toString(page));
}
public void setProgress(float progress) {
if (progress == PROGRESS_GONE) {
mProgress.setVisibility(GONE);
} else if (progress == PROGRESS_INDETERMINATE) {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(true);
} else {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(false);
mProgress.setProgress(progress);
}
}
private void unbindError() {
Texture texture = mError.getTexture();
if (texture != null) {
mError.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
public void setError(String error, GalleryView galleryView) {
unbindError();
if (error == null) {
mError.setVisibility(GONE);
} else {
mError.setVisibility(VISIBLE);
galleryView.bindErrorView(mError, error);
}
}
public ImageView getImageView() {
return mImage;
}
public boolean isLoaded() {
return mImage.getVisibility() == VISIBLE;
}
}
@@ -0,0 +1,993 @@
/*
* Copyright 2016 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.gallery.gl;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import com.hippo.ehviewer.R;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.StringTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.util.GalleryUtils;
import com.hippo.gl.view.AnimationTime;
import com.hippo.gl.view.GLRoot;
import com.hippo.gl.view.GLView;
import com.hippo.gl.widget.GLEdgeView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Pool;
import com.hippo.yorozuya.ResourcesUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class GalleryView extends GLView implements GestureRecognizer.Listener {
@IntDef({LAYOUT_MODE_LEFT_TO_RIGHT, LAYOUT_MODE_RIGHT_TO_LEFT, LAYOUT_MODE_TOP_TO_BOTTOM})
@Retention(RetentionPolicy.SOURCE)
public @interface LayoutMode {}
public static final int BACKGROUND_COLOR = 0xff212121;
private static final int PROGRESS_SIZE_IN_DP = 48;
public static final int LAYOUT_MODE_LEFT_TO_RIGHT = 0;
public static final int LAYOUT_MODE_RIGHT_TO_LEFT = 1;
public static final int LAYOUT_MODE_TOP_TO_BOTTOM = 2;
private static final float[] LEFT_AREA = {0.0f, 0.0f, 1.0f / 3.0f, 1f};
private static final float[] RIGHT_AREA = {2.0f / 3.0f, 0.0f, 1.0f, 1f};
private static final float[] MENU_AREA = {1.0f / 3.0f, 0.0f, 2.0f / 3.0f, 1.0f / 2.0f};
private static final float[] SLIDER_AREA = {1.0f / 3.0f, 1.0f / 2.0f, 2.0f / 3.0f, 1.0f};
private static final int METHOD_ON_SINGLE_TAP_UP = 0;
private static final int METHOD_ON_SINGLE_TAP_CONFIRMED = 1;
private static final int METHOD_ON_DOUBLE_TAP = 2;
private static final int METHOD_ON_DOUBLE_TAP_CONFIRMED = 3;
private static final int METHOD_ON_LONG_PRESS = 4;
private static final int METHOD_ON_SCROLL = 5;
private static final int METHOD_ON_FLING = 6;
private static final int METHOD_ON_SCALE_BEGIN = 7;
private static final int METHOD_ON_SCALE = 8;
private static final int METHOD_ON_SCALE_END = 9;
private static final int METHOD_ON_DOWN = 10;
private static final int METHOD_ON_UP = 11;
private static final int METHOD_ON_POINTER_DOWN = 12;
private static final int METHOD_ON_POINTER_UP = 13;
private static final int METHOD_SET_LAYOUT_MODE = 14;
private static final int METHOD_SET_CURRENT_PAGE = 15;
private static final int METHOD_PAGE_LEFT = 16;
private static final int METHOD_PAGE_RIGHT = 17;
private static final int METHOD_SET_SCALE_MODE = 18;
private static final int METHOD_SET_START_POSITION = 19;
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private final Context mContext;
private MovableTextTexture mPageTextTexture;
private final GestureRecognizer mGestureRecognizer;
private Adapter mAdapter;
private PagerLayoutManager mPagerLayoutManager;
private ScrollLayoutManager mScrollLayoutManager;
@Nullable
private LayoutManager mLayoutManager;
private final Pool<GalleryPageView> mGalleryPageViewPool = new Pool<>(5);
private final GLEdgeView mEdgeView;
private GLProgressView mProgressCache;
private GLTextureView mErrorViewCache;
private final int mProgressColor;
private final int mProgressSize;
private final float mErrorSize;
private final int mErrorColor;
private boolean mEnableRequestFill = true;
private boolean mRequestFill = false;
private boolean mWillFill = false;
private boolean mScale = false;
private boolean mScroll = false;
private boolean mFirstScroll = false;
private boolean mTouched = false;
private final Rect mLeftArea = new Rect();
private final Rect mRightArea = new Rect();
private final Rect mMenuArea = new Rect();
private final Rect mSliderArea = new Rect();
private final String mDefaultErrorStr;
private final String mEmptyStr;
@LayoutMode
private int mLayoutMode = LAYOUT_MODE_RIGHT_TO_LEFT;
@ImageView.Scale
private int mScaleMode = ImageView.SCALE_FIT;
@ImageView.StartPosition
private int mStartPosition = ImageView.START_POSITION_TOP_LEFT;
private int mIndex;
private final Listener mListener;
private final List<Integer> mMethodList = new ArrayList<>(5);
private final List<Object[]> mArgsList = new ArrayList<>(5);
private final List<Integer> mMethodListTemp = new ArrayList<>(5);
private final List<Object[]> mArgsListTemp = new ArrayList<>(5);
private final AtomicInteger mCurrentIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private boolean mPause;
@SuppressWarnings("deprecation")
public GalleryView(@NonNull Context context, @NonNull Adapter adapter,
Listener listener, @LayoutMode int layoutMode, @ImageView.Scale int scaleMode,
@ImageView.StartPosition int startPosition, int startPage) {
mContext = context;
mAdapter = adapter;
mListener = listener;
mEdgeView = new GLEdgeView(context);
mGestureRecognizer = new GestureRecognizer(context, this);
adapter.setGalleryView(this);
mLayoutMode = layoutMode;
mScaleMode = scaleMode;
mStartPosition = startPosition;
mIndex = MathUtils.clamp(startPage, 0, Integer.MAX_VALUE);
mProgressColor = ResourcesUtils.getAttrColor(context, R.attr.colorPrimary);
mProgressSize = LayoutUtils.dp2pix(context, PROGRESS_SIZE_IN_DP);
mErrorSize = context.getResources().getDimension(R.dimen.text_large);
mErrorColor = context.getResources().getColor(R.color.red_500);
mDefaultErrorStr = context.getResources().getString(R.string.error_unknown);
mEmptyStr = context.getResources().getString(R.string.error_empty);
setBackgroundColor(BACKGROUND_COLOR);
}
private void ensurePagerLayoutManager() {
if (mPagerLayoutManager == null) {
mPagerLayoutManager = new PagerLayoutManager(mContext, this, mScaleMode, mStartPosition, 1.0f);
}
}
private void ensureScrollLayoutManager() {
if (mScrollLayoutManager == null) {
mScrollLayoutManager = new ScrollLayoutManager(mContext, this);
}
}
private void attachLayoutManager() {
if (null != mLayoutManager) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
mScrollLayoutManager.onAttach(mAdapter);
mScrollLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void detachLayoutManager() {
if (null == mLayoutManager) {
return;
}
mIndex = mLayoutManager.getInternalCurrentIndex();
mAdapter = mLayoutManager.onDetach();
mLayoutManager = null;
}
@SuppressWarnings("deprecation")
private void onAttachToRootInternal() {
if (null == mPageTextTexture) {
mPageTextTexture = MovableTextTexture.create(Typeface.DEFAULT,
mContext.getResources().getDimensionPixelSize(R.dimen.gallery_page_text),
mContext.getResources().getColor(R.color.secondary_text_dark),
new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
}
attachLayoutManager();
}
@Override
public void onAttachToRoot(GLRoot root) {
super.onAttachToRoot(root);
mEdgeView.onAttachToRoot(root);
postMethod(METHOD_ON_ATTACH_TO_ROOT);
}
@Override
public void onDetachFromRoot() {
// When detached, render() will not be called. So do it here
detachLayoutManager();
if (null != mPageTextTexture) {
mPageTextTexture.recycle();
mPageTextTexture = null;
}
super.onDetachFromRoot();
mEdgeView.onDetachFromRoot();
}
@LayoutMode
public static int sanitizeLayoutMode(int layoutMode) {
if (layoutMode != GalleryView.LAYOUT_MODE_LEFT_TO_RIGHT &&
layoutMode != GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT &&
layoutMode != GalleryView.LAYOUT_MODE_TOP_TO_BOTTOM) {
return GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
} else {
return layoutMode;
}
}
public int getLayoutMode() {
return mLayoutMode;
}
public int getCurrentIndex() {
return mCurrentIndex.get();
}
@Override
public void requestLayout() {
// Do not need requestLayout, because the size will not change
requestFill();
}
public void requestFill() {
if (mEnableRequestFill) {
mRequestFill = true;
if (!mWillFill) {
invalidate();
}
}
}
@Override
protected boolean dispatchTouchEvent(MotionEvent event) {
// Do not pass event to component, so handle event here
mGestureRecognizer.onTouchEvent(event);
return true;
}
GLEdgeView getEdgeView() {
return mEdgeView;
}
String getDefaultErrorStr() {
return mDefaultErrorStr;
}
String getEmptyStr() {
return mEmptyStr;
}
boolean isFirstScroll() {
boolean firstScroll = mFirstScroll;
mFirstScroll = false;
return firstScroll;
}
// Make sure method run in render thread to ensure thread safe
private void postMethod(int method, Object... args) {
synchronized (this) {
mMethodList.add(method);
mArgsList.add(args);
}
invalidate();
}
public void setLayoutMode(@LayoutMode int layoutMode) {
postMethod(METHOD_SET_LAYOUT_MODE, layoutMode);
}
public void setCurrentPage(int page) {
postMethod(METHOD_SET_CURRENT_PAGE, page);
}
public void pageLeft() {
postMethod(METHOD_PAGE_LEFT);
}
public void pageRight() {
postMethod(METHOD_PAGE_RIGHT);
}
public void setScaleMode(@ImageView.Scale int scaleMode) {
postMethod(METHOD_SET_SCALE_MODE, scaleMode);
}
public void setStartPosition(@ImageView.StartPosition int startPosition) {
postMethod(METHOD_SET_START_POSITION, startPosition);
}
@Override
public boolean onSingleTapUp(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_UP, x, y);
return true;
}
@Override
public boolean onSingleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public boolean onDoubleTap(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP, x, y);
return true;
}
@Override
public boolean onDoubleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public void onLongPress(float x, float y) {
if (mLayoutManager != null && !mLayoutManager.isTapOrPressEnable()) {
return;
}
postMethod(METHOD_ON_LONG_PRESS, x, y);
}
@Override
public boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y) {
postMethod(METHOD_ON_SCROLL, dx, dy, totalX, totalY, x, y);
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
postMethod(METHOD_ON_FLING, velocityX, velocityY);
return true;
}
@Override
public boolean onScaleBegin(float focusX, float focusY) {
postMethod(METHOD_ON_SCALE_BEGIN, focusX, focusY);
return true;
}
@Override
public boolean onScale(float focusX, float focusY, float scale) {
postMethod(METHOD_ON_SCALE, focusX, focusY, scale);
return true;
}
@Override
public void onScaleEnd() {
postMethod(METHOD_ON_SCALE_END);
}
@Override
public void onDown(float x, float y) {
postMethod(METHOD_ON_DOWN, x, y);
}
@Override
public void onUp() {
postMethod(METHOD_ON_UP);
}
@Override
public void onPointerDown(float x, float y) {
postMethod(METHOD_ON_POINTER_DOWN, x, y);
}
@Override
public void onPointerUp() {
postMethod(METHOD_ON_POINTER_UP);
}
@Override
protected void onLayout(boolean changeSize, int left, int top, int right, int bottom) {
mEdgeView.layout(left, top, right, bottom);
fill();
if (changeSize) {
int width = right - left;
int height = bottom - top;
mLeftArea.set((int) (LEFT_AREA[0] * width), (int) (LEFT_AREA[1] * height),
(int) (LEFT_AREA[2] * width), (int) (LEFT_AREA[3] * height));
mRightArea.set((int) (RIGHT_AREA[0] * width), (int) (RIGHT_AREA[1] * height),
(int) (RIGHT_AREA[2] * width), (int) (RIGHT_AREA[3] * height));
mMenuArea.set((int) (MENU_AREA[0] * width), (int) (MENU_AREA[1] * height),
(int) (MENU_AREA[2] * width), (int) (MENU_AREA[3] * height));
mSliderArea.set((int) (SLIDER_AREA[0] * width), (int) (SLIDER_AREA[1] * height),
(int) (SLIDER_AREA[2] * width), (int) (SLIDER_AREA[3] * height));
}
}
@RenderThread
public void onDataChanged() {
GalleryUtils.assertInRenderThread();
if (mLayoutManager != null){
mLayoutManager.onDataChanged();
}
}
private void onSingleTapUpInternal(float x, float y) {
}
private void onSingleTapConfirmedInternal(float x, float y) {
if (mLayoutManager == null || !mLayoutManager.isTapOrPressEnable()) {
return;
}
if (mSliderArea.contains((int) x, (int) y)) {
mListener.onTapSliderArea();
} else if (mMenuArea.contains((int) x, (int) y)) {
mListener.onTapMenuArea();
} else if (mLeftArea.contains((int) x, (int) y)) {
mLayoutManager.onPageLeft();
} else if (mRightArea.contains((int) x, (int) y)) {
mLayoutManager.onPageRight();
}
}
private void onDoubleTapInternal(float x, float y) {
}
private void onDoubleTapConfirmedInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager != null) {
mLayoutManager.onDoubleTapConfirmed(x, y);
}
}
private void onLongPressInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager == null) {
return;
}
int index = mLayoutManager.getIndexUnder(x, y);
if (index == GalleryPageView.INVALID_INDEX) {
return;
}
mListener.onLongPressPage(index);
}
private void onScrollInternal(float dx, float dy, float totalX, float totalY, float x, float y) {
if (mScale) {
return;
}
mScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onScroll(dx, dy, totalX, totalY, x, y);
}
}
private void onFlingInternal(float velocityX, float velocityY) {
if (mLayoutManager != null) {
mLayoutManager.onFling(velocityX, velocityY);
}
}
private void onScaleBeginInternal(float focusX, float focusY) {
onScaleInternal(focusX, focusY, 1.0f);
}
private void onScaleInternal(float focusX, float focusY, float scale) {
if (mScroll || (mLayoutManager != null && !mLayoutManager.canScale())) {
return;
}
mScale = true;
if (mLayoutManager != null) {
mLayoutManager.onScale(focusX, focusY, scale);
}
}
private void onScaleEndInternal() {
}
private void onDownInternal(float x, float y) {
mTouched = true;
mScale = false;
mScroll = false;
mFirstScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onDown();
}
}
private void onUpInternal() {
mTouched = false;
if (mLayoutManager != null) {
mLayoutManager.onUp();
}
}
private void onPointerDownInternal(float x, float y) {
if (!mScroll && (mLayoutManager != null && mLayoutManager.canScale())) {
mScale = true;
}
}
private void onPointerUpInternal() {
}
private void setLayoutModeInternal(int layoutMode) {
if (mLayoutMode == layoutMode) {
return;
}
mLayoutMode = layoutMode;
if (mLayoutManager == null) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
int index = mLayoutManager.getInternalCurrentIndex();
mScrollLayoutManager.onAttach(mLayoutManager.onDetach());
mScrollLayoutManager.setCurrentIndex(index);
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void setCurrentPageInternal(int page) {
if (mLayoutManager != null) {
mLayoutManager.setCurrentIndex(page);
} else {
mIndex = page;
}
}
private void pageLeftInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageLeft();
}
}
private void pageRightInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageRight();
}
}
private void setScaleModeInternal(int scaleMode) {
mScaleMode = scaleMode;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setScaleMode(scaleMode);
}
}
private void setStartPositionInternal(int startPosition) {
mStartPosition = startPosition;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setStartPosition(startPosition);
}
}
@RenderThread
void forceFill() {
mRequestFill = true;
fill();
}
@RenderThread
private void fill() {
GalleryUtils.assertInRenderThread();
if (!mRequestFill) {
return;
}
// Disable request layout
mEnableRequestFill = false;
if (mLayoutManager != null) {
mLayoutManager.onFill();
}
mEnableRequestFill = true;
mRequestFill = false;
}
private void dispatchMethod() {
List<Integer> methodListTemp = mMethodListTemp;
List<Object[]> argsListTemp = mArgsListTemp;
synchronized (this) {
if (mMethodList.isEmpty()) {
return;
}
methodListTemp.addAll(mMethodList);
argsListTemp.addAll(mArgsList);
mMethodList.clear();
mArgsList.clear();
}
for (int i = 0, n = methodListTemp.size(); i < n; i++) {
int method = methodListTemp.get(i);
Object[] args = argsListTemp.get(i);
switch (method) {
case METHOD_ON_SINGLE_TAP_UP:
onSingleTapUpInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SINGLE_TAP_CONFIRMED:
onSingleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP:
onDoubleTapInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP_CONFIRMED:
onDoubleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_LONG_PRESS:
onLongPressInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCROLL:
onScrollInternal((Float) args[0], (Float) args[1], (Float) args[2],
(Float) args[3], (Float) args[4], (Float) args[5]);
break;
case METHOD_ON_FLING:
onFlingInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE_BEGIN:
onScaleBeginInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE:
onScaleInternal((Float) args[0], (Float) args[1], (Float) args[2]);
break;
case METHOD_ON_SCALE_END:
onScaleEndInternal();
break;
case METHOD_ON_DOWN:
onDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_UP:
onUpInternal();
break;
case METHOD_ON_POINTER_DOWN:
onPointerDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_POINTER_UP:
onPointerUpInternal();
break;
case METHOD_SET_LAYOUT_MODE:
setLayoutModeInternal((Integer) args[0]);
break;
case METHOD_SET_CURRENT_PAGE:
setCurrentPageInternal((Integer) args[0]);
break;
case METHOD_PAGE_LEFT:
pageLeftInternal();
break;
case METHOD_PAGE_RIGHT:
pageRightInternal();
break;
case METHOD_SET_SCALE_MODE:
setScaleModeInternal((Integer) args[0]);
break;
case METHOD_SET_START_POSITION:
setStartPositionInternal((Integer) args[0]);
break;
case METHOD_ON_ATTACH_TO_ROOT:
onAttachToRootInternal();
break;
}
}
methodListTemp.clear();
argsListTemp.clear();
}
@Override
public void render(GLCanvas canvas) {
mWillFill = true;
int oldCurrentIndex = mCurrentIndex.get();
// Dispatch method
dispatchMethod();
long time = AnimationTime.get();
if (mLayoutManager != null && mLayoutManager.onUpdateAnimation(time)) {
invalidate();
}
fill();
mWillFill = false;
super.render(canvas);
mEdgeView.render(canvas);
int newCurrentIndex;
if (mLayoutManager != null) {
newCurrentIndex = mLayoutManager.getCurrentIndex();
} else {
newCurrentIndex = GalleryPageView.INVALID_INDEX;
}
mCurrentIndex.lazySet(newCurrentIndex);
if (oldCurrentIndex != newCurrentIndex) {
mListener.onUpdateCurrentIndex(newCurrentIndex);
}
}
@RenderThread
public GalleryPageView findPageByIndex(int id) {
if (!mPause && mLayoutManager != null) {
return mLayoutManager.findPageByIndex(id);
} else {
return null;
}
}
GalleryPageView obtainPage() {
GalleryPageView page = mGalleryPageViewPool.pop();
if (page == null) {
page = new GalleryPageView(mContext, mPageTextTexture, mProgressColor, mProgressSize);
}
return page;
}
void releasePage(GalleryPageView page) {
mGalleryPageViewPool.push(page);
}
/**
* Indeterminate GLProgressView
*/
GLProgressView obtainProgress() {
GLProgressView progress;
if (mProgressCache != null) {
progress = mProgressCache;
mProgressCache = null;
} else {
progress = new GLProgressView();
progress.setColor(mProgressColor);
progress.setBgColor(BACKGROUND_COLOR);
progress.setIndeterminate(true);
progress.setMinimumWidth(mProgressSize);
progress.setMinimumHeight(mProgressSize);
}
return progress;
}
/**
* @param progress Indeterminate GLProgressView
*/
void releaseProgress(GLProgressView progress) {
mProgressCache = progress;
}
GLTextureView obtainErrorView() {
GLTextureView errorView;
if (mErrorViewCache != null) {
errorView = mErrorViewCache;
mErrorViewCache = null;
} else {
errorView = new GLTextureView();
}
return errorView;
}
void unbindErrorView(GLTextureView errorView) {
Texture texture = errorView.getTexture();
if (texture != null) {
errorView.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
void bindErrorView(GLTextureView errorView, String error) {
unbindErrorView(errorView);
Texture texture = StringTexture.newInstance(error, mErrorSize, mErrorColor);
errorView.setTexture(texture);
}
void releaseErrorView(GLTextureView errorView) {
unbindErrorView(errorView);
mErrorViewCache = errorView;
}
public static abstract class Adapter {
protected GalleryView mGalleryView;
private void setGalleryView(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public void bind(GalleryPageView view, int index) {
onBind(view, index);
view.setIndex(index);
}
public void unbind(GalleryPageView view) {
onUnbind(view, view.getIndex());
view.setIndex(GalleryPageView.INVALID_INDEX);
}
public abstract void onBind(GalleryPageView view, int index);
public abstract void onUnbind(GalleryPageView view, int index);
/**
* @return Null for no error
*/
public abstract String getError();
public abstract int size();
}
public static abstract class LayoutManager {
protected GalleryView mGalleryView;
public LayoutManager(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public abstract void onAttach(Adapter iterator);
public abstract Adapter onDetach();
public abstract void onFill();
public abstract void onDown();
public abstract void onUp();
public abstract void onDoubleTapConfirmed(float x, float y);
public abstract void onLongPress(float x, float y);
public abstract void onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
public abstract void onFling(float velocityX, float velocityY);
public abstract boolean canScale();
public abstract void onScale(float focusX, float focusY, float scale);
public abstract boolean onUpdateAnimation(long time);
public abstract void onDataChanged();
public abstract void onPageLeft();
public abstract void onPageRight();
public abstract boolean isTapOrPressEnable();
public abstract GalleryPageView findPageByIndex(int index);
/**
* @return {@link GalleryPageView#INVALID_INDEX} for error
*/
public abstract int getCurrentIndex();
public abstract void setCurrentIndex(int index);
public abstract int getIndexUnder(float x, float y);
abstract int getInternalCurrentIndex();
protected void placeCenter(GLView view) {
int spec = GLView.MeasureSpec.makeMeasureSpec(GLView.LayoutParams.WRAP_CONTENT,
GLView.LayoutParams.WRAP_CONTENT);
view.measure(spec, spec);
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
int viewLeft = mGalleryView.getWidth() / 2 - viewWidth / 2;
int viewTop = mGalleryView.getHeight() / 2 - viewHeight / 2;
view.layout(viewLeft, viewTop, viewLeft + viewWidth, viewTop + viewHeight);
}
}
public interface Listener {
@RenderThread
void onUpdateCurrentIndex(int index);
@RenderThread
void onTapSliderArea();
@RenderThread
void onTapMenuArea();
@RenderThread
void onLongPressPage(int index);
}
}
@@ -0,0 +1,174 @@
/*
* Copyright 2016 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.gallery.gl;
import android.content.Context;
import android.os.SystemClock;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
// This class aggregates three gesture detectors: GestureDetector,
// ScaleGestureDetector, and DownUpDetector.
public class GestureRecognizer {
@SuppressWarnings("unused")
private static final String TAG = "GestureRecognizer";
public interface Listener {
boolean onSingleTapUp(float x, float y);
boolean onSingleTapConfirmed(float x, float y);
boolean onDoubleTap(float x, float y);
boolean onDoubleTapConfirmed(float x, float y);
void onLongPress(float x, float y);
boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
/**
* @param velocityX Finger from top to bottom is positive
* @param velocityY Finger from left to right is positive
*/
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
boolean onScaleBegin(float focusX, float focusY);
boolean onScale(float focusX, float focusY, float scale);
void onScaleEnd();
void onDown(float x, float y);
void onUp();
void onPointerDown(float x, float y);
void onPointerUp();
}
private final GestureDetectorCompat mGestureDetector;
private final ScaleGestureDetector mScaleDetector;
private final DownUpDetector mDownUpDetector;
private final Listener mListener;
public GestureRecognizer(Context context, Listener listener) {
mListener = listener;
MyGestureListener gestureListener = new MyGestureListener();
mGestureDetector = new GestureDetectorCompat(context, gestureListener,
null /* ignoreMultitouch */);
mGestureDetector.setOnDoubleTapListener(gestureListener);
mScaleDetector = new ScaleGestureDetector(
context, new MyScaleListener());
mDownUpDetector = new DownUpDetector(new MyDownUpListener());
}
public void onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
mDownUpDetector.onTouchEvent(event);
}
public boolean isDown() {
return mDownUpDetector.isDown();
}
public void cancelScale() {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mScaleDetector.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
private class MyGestureListener
extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return mListener.onSingleTapUp(e.getX(), e.getY());
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return mListener.onSingleTapConfirmed(e.getX(), e.getY());
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
return mListener.onDoubleTapConfirmed(e.getX(), e.getY());
} else {
return true;
}
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return mListener.onDoubleTap(e.getX(), e.getY());
}
@Override
public void onLongPress(MotionEvent e) {
mListener.onLongPress(e.getX(), e.getY());
}
@Override
public boolean onScroll(
MotionEvent e1, MotionEvent e2, float dx, float dy) {
return mListener.onScroll(
dx, dy, e2.getX() - e1.getX(), e2.getY() - e1.getY(), e2.getX(), e2.getY());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return mListener.onFling(e1, e2, velocityX, velocityY);
}
}
private class MyScaleListener
extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return mListener.onScaleBegin(
detector.getFocusX(), detector.getFocusY());
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
return mListener.onScale(detector.getFocusX(),
detector.getFocusY(), detector.getScaleFactor());
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mListener.onScaleEnd();
}
}
private class MyDownUpListener implements DownUpDetector.DownUpListener {
@Override
public void onDown(MotionEvent e) {
mListener.onDown(e.getX(), e.getY());
}
@Override
public void onUp(MotionEvent e) {
mListener.onUp();
}
@Override
public void onPointerDown(MotionEvent e) {
mListener.onPointerDown(e.getX(), e.getY());
}
@Override
public void onPointerUp(MotionEvent e) {
mListener.onPointerUp();
}
}
}
@@ -0,0 +1,618 @@
/*
* Copyright 2016 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.gallery.gl;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.IntDef;
import com.hippo.gl.anim.AlphaAnimation;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.GLView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.MathUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
public class ImageView extends GLView implements ImageTexture.Callback {
@IntDef({SCALE_ORIGIN, SCALE_FIT_WIDTH, SCALE_FIT_HEIGHT, SCALE_FIT, SCALE_FIXED})
@Retention(RetentionPolicy.SOURCE)
public @interface Scale {}
@IntDef({START_POSITION_TOP_LEFT, START_POSITION_TOP_RIGHT, START_POSITION_BOTTOM_LEFT,
START_POSITION_BOTTOM_RIGHT, START_POSITION_CENTER})
@Retention(RetentionPolicy.SOURCE)
public @interface StartPosition {}
// TODO adjust scale max and min according to image size and screen size
private static final float SCALE_MIN = 1 / 10.0f;
private static final float SCALE_MAX = 10.0f;
public static final int SCALE_ORIGIN = 0;
public static final int SCALE_FIT_WIDTH = 1;
public static final int SCALE_FIT_HEIGHT = 2;
public static final int SCALE_FIT = 3;
public static final int SCALE_FIXED = 4;
public static final int START_POSITION_TOP_LEFT = 0;
public static final int START_POSITION_TOP_RIGHT = 1;
public static final int START_POSITION_BOTTOM_LEFT = 2;
public static final int START_POSITION_BOTTOM_RIGHT = 3;
public static final int START_POSITION_CENTER = 4;
private static final long ALPHA_ANIMATION_DURING = 300L;
private ImageTexture mImageTexture;
private int mTextureWidth;
private int mTextureHeight;
private final RectF mDst = new RectF();
private final RectF mSrcActual = new RectF();
private final RectF mDstActual = new RectF();
private final Rect mValidRect = new Rect();
private int mScaleMode = SCALE_FIT;
private int mStartPosition = START_POSITION_TOP_RIGHT;
private float mScaleValue = 1.0f;
private float mScale = 1.0f;
private boolean mScaleOffsetDirty = true;
private boolean mPositionInRootDirty = true;
private final AlphaAnimation mAlphaAnimation;
public ImageView() {
mAlphaAnimation = new AlphaAnimation(0.0f, 1.0f);
mAlphaAnimation.setDuration(ALPHA_ANIMATION_DURING);
mAlphaAnimation.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
}
@Scale
public static int sanitizeScaleMode(int scaleMode) {
if (scaleMode != SCALE_ORIGIN &&
scaleMode != SCALE_FIT_WIDTH &&
scaleMode != SCALE_FIT_HEIGHT &&
scaleMode != SCALE_FIT &&
scaleMode != SCALE_FIXED) {
return SCALE_FIT;
} else {
return scaleMode;
}
}
@StartPosition
public static int sanitizeStartPosition(int startPosition) {
if (startPosition != START_POSITION_TOP_LEFT &&
startPosition != START_POSITION_TOP_RIGHT &&
startPosition != START_POSITION_BOTTOM_LEFT &&
startPosition != START_POSITION_BOTTOM_RIGHT &&
startPosition != START_POSITION_CENTER) {
return START_POSITION_TOP_RIGHT;
} else {
return startPosition;
}
}
@Override
protected int getSuggestedMinimumWidth() {
return Math.max(super.getSuggestedMinimumWidth(),
mImageTexture == null ? 0 : mTextureWidth);
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max(super.getSuggestedMinimumHeight(),
mImageTexture == null ? 0 : mTextureHeight);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mImageTexture == null) {
super.onMeasure(widthSpec, heightSpec);
} else {
float ratio = (float) mTextureWidth / mTextureHeight;
int widthSize = MeasureSpec.getSize(widthSpec);
int heightSize = MeasureSpec.getSize(heightSpec);
int widthMode = MeasureSpec.getMode(widthSpec);
int heightMode = MeasureSpec.getMode(heightSpec);
int measureWidth = -1;
int measureHeight = -1;
if (widthMode == MeasureSpec.EXACTLY) {
measureWidth = widthSize;
if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
} else {
measureHeight = (int) (widthSize / ratio);
if (heightMode == MeasureSpec.AT_MOST) {
measureHeight = Math.min(measureHeight, heightSize);
}
}
} else if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
measureWidth = (int) (heightSize * ratio);
if (widthMode == MeasureSpec.AT_MOST) {
measureWidth = Math.min(measureWidth, widthSize);
}
}
if (measureWidth == -1 || measureHeight == -1) {
super.onMeasure(widthSpec, heightSpec);
} else {
setMeasuredSize(measureWidth, measureHeight);
}
}
}
@Override
protected void onSizeChanged(int newW, int newH, int oldW, int oldH) {
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
}
@Override
protected void onPositionInRootChanged(int x, int y, int oldX, int oldY) {
mPositionInRootDirty = true;
if (mImageTexture != null) {
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
mImageTexture.start();
} else {
mImageTexture.stop();
}
}
}
public void getScaleDefault(float[] scaleDefault) {
if (mImageTexture == null) {
return;
}
scaleDefault[0] = 1.0f;
scaleDefault[1] = (float) getWidth() / mTextureWidth;
scaleDefault[2] = (float) getHeight() / mTextureHeight;
scaleDefault[3] = Math.max(scaleDefault[1], scaleDefault[2]) * 2;
scaleDefault[0] = MathUtils.clamp(scaleDefault[0], SCALE_MIN, SCALE_MAX);
scaleDefault[1] = MathUtils.clamp(scaleDefault[1], SCALE_MIN, SCALE_MAX);
scaleDefault[2] = MathUtils.clamp(scaleDefault[2], SCALE_MIN, SCALE_MAX);
scaleDefault[3] = MathUtils.clamp(scaleDefault[3], SCALE_MIN, SCALE_MAX);
Arrays.sort(scaleDefault);
}
public void setImageTexture(ImageTexture imageTexture) {
// Remove callback
if (mImageTexture != null) {
mImageTexture.setCallback(null);
}
int oldTextureWidth = mTextureWidth;
int oldTextureHeight = mTextureHeight;
mImageTexture = imageTexture;
if (imageTexture != null) {
imageTexture.setCallback(this);
mTextureWidth = imageTexture.getWidth();
mTextureHeight = imageTexture.getHeight();
// Avoid zero and negative
if (mTextureWidth <= 0) {
mTextureWidth = 1;
}
if (mTextureHeight <= 0) {
mTextureHeight = 1;
}
// Start alpha animation, do not show animation for image has no valid rect
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
}
} else {
mTextureWidth = 1;
mTextureHeight = 1;
}
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
if (oldTextureWidth != mTextureWidth || oldTextureHeight != mTextureHeight) {
requestLayout();
}
}
public ImageTexture getImageTexture() {
return mImageTexture;
}
public boolean isLoaded() {
return mImageTexture != null;
}
public boolean canFlingVertically() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.top < 0.0f || mDst.bottom > getHeight();
}
public boolean canFlingHorizontally() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.right > getWidth();
}
public boolean canFling() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.top < 0.0f || mDst.right > getWidth() || mDst.bottom > getHeight();
}
public int getMaxDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.left);
}
public int getMinDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getWidth() - (int) mDst.right);
}
public int getMaxDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.top);
}
public int getMinDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getHeight() - (int) mDst.bottom);
}
public float getScale() {
return mScale;
}
/**
* If target is shorter then screen, make it in screen center. If target is
* longer then parent, make sure target fill parent over
*/
private void adjustPosition() {
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
}
} else {
float left = (screenWidth - targetWidth) / 2;
dst.offsetTo(left, dst.top);
}
if (targetHeight > screenHeight) {
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
}
} else {
float top = (screenHeight - targetHeight) / 2;
dst.offsetTo(dst.left, top);
}
}
public void setScaleOffset(@Scale int scaleMode, @StartPosition int startPosition, float scaleValue) {
mScaleMode = scaleMode;
mStartPosition = startPosition;
mScaleValue = scaleValue;
int screenWidth = getWidth();
int screenHeight = getHeight();
if (mImageTexture == null || screenWidth == 0 || screenHeight == 0) {
mScaleOffsetDirty = true;
return;
}
int textureWidth = mTextureWidth;
int textureHeight = mTextureHeight;
// Set scale
float targetWidth;
float targetHeight;
switch (scaleMode) {
case SCALE_ORIGIN:
mScale = 1.0f;
targetWidth = textureWidth;
targetHeight = textureHeight;
break;
case SCALE_FIT_WIDTH:
mScale = (float) screenWidth / textureWidth;
targetWidth = screenWidth;
targetHeight = textureHeight * mScale;
break;
case SCALE_FIT_HEIGHT:
mScale = (float) screenHeight / textureHeight;
targetWidth = textureWidth * mScale;
targetHeight = screenHeight;
break;
case SCALE_FIT:
float scaleX = (float) screenWidth / textureWidth;
float scaleY = (float) screenHeight / textureHeight;
if (scaleX < scaleY) {
mScale = scaleX;
targetWidth = screenWidth;
targetHeight = textureHeight * scaleX;
} else {
mScale = scaleY;
targetWidth = textureWidth * scaleY;
targetHeight = screenHeight;
break;
}
break;
case SCALE_FIXED:
default:
mScale = scaleValue;
targetWidth = textureWidth * scaleValue;
targetHeight = textureHeight * scaleValue;
break;
}
// adjust scale, not too big, not too small
if (mScale < SCALE_MIN) {
mScale = SCALE_MIN;
targetWidth = textureWidth * SCALE_MIN;
targetHeight = textureHeight * SCALE_MIN;
} else if (mScale > SCALE_MAX) {
mScale = SCALE_MAX;
targetWidth = textureWidth * SCALE_MAX;
targetHeight = textureHeight * SCALE_MAX;
}
// Set mDst.left and mDst.right
RectF dst = mDst;
switch (startPosition) {
case START_POSITION_TOP_LEFT:
dst.left = 0;
dst.top = 0;
break;
case START_POSITION_TOP_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = 0;
break;
case START_POSITION_BOTTOM_LEFT:
dst.left = 0;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_BOTTOM_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_CENTER:
default:
dst.left = (screenWidth - targetWidth) / 2;
dst.top = (screenHeight - targetHeight) / 2;
break;
}
// Set mDst.right and mDst.bottom
dst.right = dst.left + targetWidth;
dst.bottom = dst.top + targetHeight;
// adjust position
adjustPosition();
mScaleOffsetDirty = false;
mPositionInRootDirty = true;
}
public void scroll(int dx, int dy, int[] remain) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
remain[0] = dx;
remain[1] = dy;
return;
}
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
dst.left -= dx;
dst.right -= dx;
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
remain[0] = -(int) fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
remain[0] = (int) fixXOffset;
} else {
remain[0] = 0;
}
} else {
remain[0] = dx;
}
if (targetHeight > screenHeight) {
dst.top -= dy;
dst.bottom -= dy;
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
remain[1] = -(int) fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
remain[1] = (int) fixYOffset;
} else {
remain[1] = 0;
}
} else {
remain[1] = dy;
}
if (dx != remain[0] || dy != remain[1]) {
mPositionInRootDirty = true;
invalidate();
}
}
public void scale(float focusX, float focusY, float scale) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
return;
}
if ((mScale == SCALE_MAX && scale >= 1.0f) || (mScale == SCALE_MIN && scale < 1.0f)) {
return;
}
float newScale = mScale * scale;
newScale = MathUtils.clamp(newScale, SCALE_MIN, SCALE_MAX);
mScale = newScale;
RectF dst = mDst;
float left = (focusX - ((focusX - dst.left) * scale));
float top = (focusY - ((focusY - dst.top) * scale));
dst.set(left, top,
(left + (mImageTexture.getWidth() * newScale)),
(top + (mImageTexture.getHeight() * newScale)));
// adjust position
adjustPosition();
mPositionInRootDirty = true;
invalidate();
}
private void applyPositionInRoot() {
int width = mImageTexture.getWidth();
int height = mImageTexture.getHeight();
RectF dst = mDst;
RectF dstActual = mDstActual;
RectF srcActual = mSrcActual;
dstActual.set(dst);
getValidRect(mValidRect);
if (dstActual.intersect(mValidRect.left, mValidRect.top, mValidRect.right, mValidRect.bottom)) {
srcActual.left = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.left));
srcActual.right = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.right));
srcActual.top = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.top));
srcActual.bottom = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.bottom));
} else {
// Can't be seen, set src and dst empty
srcActual.setEmpty();
dstActual.setEmpty();
}
mPositionInRootDirty = false;
}
@Override
public void onRender(GLCanvas canvas) {
Texture texture = mImageTexture;
if (texture == null) {
return;
}
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mPositionInRootDirty) {
applyPositionInRoot();
}
if (!mSrcActual.isEmpty()) {
texture.draw(canvas, mSrcActual, mDstActual);
}
}
@Override
public void invalidateImageTexture(ImageTexture who) {
invalidate();
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -62,9 +62,6 @@ public class CleanRedundancyPreference extends TaskPreference {
// True for cleared
private boolean clearFile(UniFile file) {
String name = file.getName();
if (name == null) {
return false;
}
int index = name.indexOf('-');
if (index >= 0) {
name = name.substring(0, index);
@@ -1,105 +0,0 @@
/*
* Copyright 2018 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.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.preference.MessagePreference;
import com.hippo.text.Html;
import java.util.LinkedList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class IdentityCookiePreference extends MessagePreference {
private String message;
public IdentityCookiePreference(Context context) {
super(context);
init();
}
public IdentityCookiePreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IdentityCookiePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
EhCookieStore store = EhApplication.getEhCookieStore(getContext());
List<Cookie> eCookies = store.getCookies(HttpUrl.get(EhUrl.HOST_E));
List<Cookie> exCookies = store.getCookies(HttpUrl.get(EhUrl.HOST_EX));
List<Cookie> cookies = new LinkedList<>(eCookies);
cookies.addAll(exCookies);
String ipbMemberId = null;
String ipbPassHash = null;
String igneous = null;
for (int i = 0, n = cookies.size(); i < n; i++) {
Cookie cookie = cookies.get(i);
switch (cookie.name()) {
case EhCookieStore.KEY_IPD_MEMBER_ID:
ipbMemberId = cookie.value();
break;
case EhCookieStore.KEY_IPD_PASS_HASH:
ipbPassHash = cookie.value();
break;
case EhCookieStore.KEY_IGNEOUS:
igneous = cookie.value();
break;
}
}
if (ipbMemberId != null || ipbPassHash != null || igneous != null) {
message = EhCookieStore.KEY_IPD_MEMBER_ID + ": " + ipbMemberId + "<br>"
+ EhCookieStore.KEY_IPD_PASS_HASH + ": " + ipbPassHash + "<br>"
+ EhCookieStore.KEY_IGNEOUS + ": " + igneous;
setDialogMessage(Html.fromHtml(getContext().getString(R.string.settings_eh_identity_cookies_signed, message)));
message = message.replace("<br>", "\n");
} else {
setDialogMessage(getContext().getString(R.string.settings_eh_identity_cookies_tourist));
}
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
if (message != null) {
builder.setPositiveButton(R.string.settings_eh_identity_cookies_copy, (dialog, which) -> {
ClipboardManager cmb = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, message));
Toast.makeText(getContext(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
IdentityCookiePreference.this.onClick(dialog, which);
});
}
}
}
@@ -23,6 +23,7 @@ import android.preference.Preference;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
@@ -30,16 +31,16 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import okhttp3.OkHttpClient;
public class RestoreDownloadPreference extends TaskPreference {
@@ -87,15 +88,13 @@ public class RestoreDownloadPreference extends TaskPreference {
InputStream is = null;
try {
is = siFile.openInputStream();
SpiderInfo spiderInfo = SpiderInfo.read(is);
if (spiderInfo == null) {
return null;
}
long gid = spiderInfo.gid;
// Skip start page
IOUtils.readAsciiLine(is);
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
if (mManager.containDownloadInfo(gid)) {
return null;
}
String token = spiderInfo.token;
String token = IOUtils.readAsciiLine(is);
RestoreItem restoreItem = new RestoreItem();
restoreItem.gid = gid;
restoreItem.token = token;
@@ -131,8 +130,7 @@ public class RestoreDownloadPreference extends TaskPreference {
try {
return EhEngine.fillGalleryListByApi(null, mHttpClient, new ArrayList<GalleryInfo>(restoreItemList));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
e.printStackTrace();
return null;
}
@@ -1,57 +0,0 @@
/*
* Copyright 2016 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.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.Preference;
import android.util.AttributeSet;
import com.hippo.ehviewer.R;
public class VersionPreference extends Preference {
public VersionPreference(Context context) {
super(context);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setTitle(R.string.settings_about_version);
String version;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
version = context.getString(R.string.error_unknown);
}
setSummary(version);
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2018 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.shortcuts;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.hippo.ehviewer.download.DownloadService;
/**
* Created by onlymash on 3/25/18.
*/
public class ShortcutsActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = null;
Intent intent = getIntent();
if (intent != null){
action = intent.getAction();
if (action != null && (action.equals(DownloadService.ACTION_START_ALL) ||
action.equals(DownloadService.ACTION_STOP_ALL))){
startService(new Intent(this, DownloadService.class).setAction(action));
}
}
finish();
}
}
@@ -27,17 +27,17 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.io.UniFileOutputStreamPipe;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.unifile.FilenameFilter;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Utilities;
import com.hippo.yorozuya.io.InputStreamPipe;
import com.hippo.yorozuya.io.OutputStreamPipe;
import java.io.File;
import java.io.IOException;
@@ -169,7 +169,7 @@ public final class SpiderDen {
@Nullable
private static UniFile findImageFile(UniFile dir, int index) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
for (String extension : GalleryProvider.SUPPORT_IMAGE_EXTENSIONS) {
String filename = generateImageFilename(index, extension);
UniFile file = dir.findFile(filename);
if (file != null) {
@@ -193,10 +193,10 @@ public final class SpiderDen {
* @param extension with dot
*/
private String fixExtension(String extension) {
if (Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
if (Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
return extension;
} else {
return GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
return GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
}
}
@@ -275,8 +275,8 @@ public final class SpiderDen {
}
boolean result = false;
for (int i = 0, n = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[i]);
for (int i = 0, n = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[i]);
UniFile file = dir.subFile(filename);
if (file != null) {
result |= file.delete();
@@ -323,12 +323,7 @@ public final class SpiderDen {
@Nullable
public OutputStreamPipe openOutputStreamPipe(int index, @Nullable String extension) {
if (mMode == SpiderQueen.MODE_READ) {
// Return the download pipe is the gallery has been downloaded
OutputStreamPipe pipe = openDownloadOutputStreamPipe(index, extension);
if (pipe == null) {
pipe = openCacheOutputStreamPipe(index);
}
return pipe;
return openCacheOutputStreamPipe(index);
} else if (mMode == SpiderQueen.MODE_DOWNLOAD) {
return openDownloadOutputStreamPipe(index, extension);
} else {
@@ -24,7 +24,6 @@ import android.util.SparseArray;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.IOException;
import java.io.InputStream;
@@ -35,18 +34,16 @@ public class SpiderInfo {
private static final String TAG = SpiderInfo.class.getSimpleName();
private static final String VERSION_STR = "VERSION";
private static final int VERSION = 2;
static final String TOKEN_FAILED = "failed";
public int startPage = 0;
public long gid = -1;
public String token = null;
public int pages = -1;
public int previewPages = -1;
public int previewPerPage = -1;
public SparseArray<String> pTokenMap = null;
int startPage = 0;
long gid = -1;
String token = null;
int pages = -1;
int previewPages = -1;
int previewPerPage = -1;
SparseArray<String> pTokenMap = null;
public static SpiderInfo read(@Nullable UniFile file) {
if (file == null) {
@@ -83,18 +80,6 @@ public class SpiderInfo {
return startPage >= 0 ? startPage : 0;
}
private static int getVersion(String str) {
if (null == str) {
return -1;
}
if (str.startsWith(VERSION_STR)) {
return NumberUtils.parseIntSafely(str.substring(VERSION_STR.length()), -1);
} else {
return 1;
}
}
@Nullable
@SuppressWarnings("InfiniteLoopStatement")
public static SpiderInfo read(@Nullable InputStream is) {
if (null == is) {
@@ -104,20 +89,8 @@ public class SpiderInfo {
SpiderInfo spiderInfo = null;
try {
spiderInfo = new SpiderInfo();
// Get version
String line = IOUtils.readAsciiLine(is);
int version = getVersion(line);
if (version == VERSION) {
// Read next line
line = IOUtils.readAsciiLine(is);
} else if (version == 1) {
// pass
} else {
// Invalid version
return null;
}
// Start page
spiderInfo.startPage = getStartPage(line);
spiderInfo.startPage = getStartPage(IOUtils.readAsciiLine(is));
// Gid
spiderInfo.gid = Long.parseLong(IOUtils.readAsciiLine(is));
// Token
@@ -127,12 +100,7 @@ public class SpiderInfo {
// Preview pages
spiderInfo.previewPages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Preview pre page
line = IOUtils.readAsciiLine(is);
if (version == 1) {
// Skip it
} else {
spiderInfo.previewPerPage = Integer.parseInt(line);
}
spiderInfo.previewPerPage = Integer.parseInt(IOUtils.readAsciiLine(is));
// Pages
spiderInfo.pages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Check pages
@@ -142,9 +110,9 @@ public class SpiderInfo {
// PToken
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
while (true) { // EOFException will raise
line = IOUtils.readAsciiLine(is);
String line = IOUtils.readAsciiLine(is);
int pos = line.indexOf(" ");
if (pos > 0) {
if (pos > 0 || pos < line.length() - 1) {
int index = Integer.parseInt(line.substring(0, pos));
String pToken = line.substring(pos + 1);
if (!TextUtils.isEmpty(pToken)) {
@@ -159,6 +127,7 @@ public class SpiderInfo {
}
if (spiderInfo == null || spiderInfo.gid == -1 || spiderInfo.token == null ||
spiderInfo.previewPages == -1 || spiderInfo.previewPerPage == -1 ||
spiderInfo.pages == -1 || spiderInfo.pTokenMap == null) {
return null;
} else {
@@ -170,9 +139,6 @@ public class SpiderInfo {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(os);
writer.write(VERSION_STR);
writer.write(Integer.toString(VERSION));
writer.write("\n");
writer.write(String.format("%08x", startPage >= 0 ? startPage : 0)); // Avoid negative
writer.write("\n");
writer.write(Long.toString(gid));
@@ -45,22 +45,21 @@ import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.PriorityThreadFactory;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.Utilities;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.thread.PriorityThread;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import com.hippo.yorozuya.io.InputStreamPipe;
import com.hippo.yorozuya.io.OutputStreamPipe;
import com.hippo.yorozuya.sparse.SparseJLArray;
import java.io.IOException;
import java.io.InputStream;
@@ -71,27 +70,25 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public final class SpiderQueen implements Runnable {
public class SpiderQueen implements Runnable {
private static final String TAG = SpiderQueen.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private static final boolean DEBUG_LOG = false;
private static final boolean DEBUG_PTOKEN = true;
@IntDef({MODE_READ, MODE_DOWNLOAD})
@Retention(RetentionPolicy.SOURCE)
@@ -109,8 +106,6 @@ public final class SpiderQueen implements Runnable {
public static final int STATE_FINISHED = 2;
public static final int STATE_FAILED = 3;
public static final int DECODE_THREAD_NUM = 1;
public static final String SPIDER_INFO_FILENAME = ".ehviewer";
private static final String[] URL_509_SUFFIX_ARRAY = {
@@ -131,22 +126,25 @@ public final class SpiderQueen implements Runnable {
private int mReadReference = 0;
private int mDownloadReference = 0;
@Mode
private int mMode;
// It mQueenThread is null, failed or stopped
@Nullable
private volatile Thread mQueenThread;
private final Object mQueenLock = new Object();
private final Thread[] mDecodeThreadArray = new Thread[DECODE_THREAD_NUM];
private final int[] mDecodeIndexArray = new int[DECODE_THREAD_NUM];
private final Queue<Integer> mDecodeRequestQueue = new LinkedList<>();
@Nullable
private Thread mDecoderThread;
private final Stack<Integer> mDecodeRequestStack = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final Object mWorkerLock = new Object();
private ThreadPoolExecutor mWorkerPoolExecutor;
private int mWorkerCount;
private final Object mPTokenLock = new Object();
private final AtomicReference<SpiderInfo> mSpiderInfo = new AtomicReference<>();
private volatile SpiderInfo mSpiderInfo;
private final Queue<Integer> mRequestPTokenQueue = new ConcurrentLinkedQueue<>();
private final Object mPageStateLock = new Object();
@@ -183,10 +181,6 @@ public final class SpiderQueen implements Runnable {
mWorkerMaxCount = MathUtils.clamp(Settings.getMultiThreadDownload(), 1, 10);
mPreloadNumber = MathUtils.clamp(Settings.getPreloadImage(), 0, 100);
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
mDecodeIndexArray[i] = GalleryPageView.INVALID_INDEX;
}
mWorkerPoolExecutor = new ThreadPoolExecutor(mWorkerMaxCount, mWorkerMaxCount,
0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(),
new PriorityThreadFactory(SpiderWorker.class.getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND));
@@ -276,9 +270,6 @@ public final class SpiderQueen implements Runnable {
}
private void notifyGetImageFailure(int index, String error) {
if (error == null) {
error = GetText.getString(R.string.error_unknown);
}
synchronized (mSpiderListeners) {
for (OnSpiderListener listener : mSpiderListeners) {
listener.onGetImageFailure(index, error);
@@ -321,19 +312,18 @@ public final class SpiderQueen implements Runnable {
}
private void updateMode() {
int mode;
if (mDownloadReference > 0) {
mode = MODE_DOWNLOAD;
mMode = MODE_DOWNLOAD;
} else {
mode = MODE_READ;
mMode = MODE_READ;
}
mSpiderDen.setMode(mode);
mSpiderDen.setMode(mMode);
// Update download page
boolean intoDownloadMode = false;
synchronized (mRequestPageQueue) {
if (mode == MODE_DOWNLOAD) {
if (mMode == MODE_DOWNLOAD) {
if (mDownloadPage < 0) {
mDownloadPage = 0;
intoDownloadMode = true;
@@ -423,6 +413,7 @@ public final class SpiderQueen implements Runnable {
}
public String getError() {
// TODO
if (mQueenThread == null) {
return "Error";
} else {
@@ -431,11 +422,11 @@ public final class SpiderQueen implements Runnable {
}
public Object forceRequest(int index) {
return request(index, true, true, false);
return request(index, true, false);
}
public Object request(int index) {
return request(index, true, false, true);
return request(index, false, true);
}
private int getPageState(int index) {
@@ -473,9 +464,6 @@ public final class SpiderQueen implements Runnable {
synchronized (mRequestPageQueue) {
mRequestPageQueue.remove(index);
}
synchronized (mDecodeRequestQueue) {
mDecodeRequestQueue.remove(index);
}
}
/**
@@ -484,7 +472,7 @@ public final class SpiderQueen implements Runnable {
* Float for download percent<br>
* null for wait
*/
private Object request(int index, boolean ignoreError, boolean force, boolean addNeighbor) {
private Object request(int index, boolean force, boolean addNeighbor) {
if (mQueenThread == null) {
return null;
}
@@ -493,10 +481,7 @@ public final class SpiderQueen implements Runnable {
int state = getPageState(index);
// Fix state for force
if ((force && (state == STATE_FINISHED || state == STATE_FAILED)) ||
(ignoreError && state == STATE_FAILED)) {
// Update state to none at once
updatePageState(index, STATE_NONE);
if (force && (state == STATE_FINISHED || state == STATE_FAILED)) {
state = STATE_NONE;
}
@@ -520,7 +505,7 @@ public final class SpiderQueen implements Runnable {
} else {
size = Integer.MAX_VALUE;
}
for (int i = index + 1, n = index + 1 + mPreloadNumber; i < n && i < size; i++) {
for (int i = index + 1, n = index + i + mPreloadNumber; i < n && i < size; i++) {
if (STATE_NONE == getPageState(i)) {
mRequestPageQueue2.add(i);
}
@@ -546,10 +531,10 @@ public final class SpiderQueen implements Runnable {
result = error;
break;
case STATE_FINISHED:
synchronized (mDecodeRequestQueue) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestQueue.contains(index)) {
mDecodeRequestQueue.add(index);
mDecodeRequestQueue.notify();
synchronized (mDecodeRequestStack) {
if (!mDecodeRequestStack.contains(index) && index != mDecodingIndex.get()) {
mDecodeRequestStack.add(index);
mDecodeRequestStack.notify();
}
}
result = null;
@@ -561,15 +546,6 @@ public final class SpiderQueen implements Runnable {
return result;
}
public static boolean contain(int[] array, int value) {
for (int v: array) {
if (v == value) {
return true;
}
}
return false;
}
private void ensureWorkers() {
synchronized (mWorkerLock) {
if (null == mWorkerPoolExecutor) {
@@ -650,23 +626,21 @@ public final class SpiderQueen implements Runnable {
}
public int getStartPage() {
SpiderInfo spiderInfo = readSpiderInfoFromLocal();
if (spiderInfo != null) {
mSpiderInfo.lazySet(spiderInfo);
return spiderInfo.startPage;
mSpiderInfo = readSpiderInfoFromLocal();
if (mSpiderInfo != null) {
return mSpiderInfo.startPage;
} else {
return 0;
}
}
public void putStartPage(int page) {
final SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
spiderInfo.startPage = page;
if (mSpiderInfo != null) {
mSpiderInfo.startPage = page;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
writeSpiderInfoToLocal(spiderInfo);
writeSpiderInfoToLocal(mSpiderInfo);
return null;
}
}.execute();
@@ -674,16 +648,15 @@ public final class SpiderQueen implements Runnable {
}
private synchronized SpiderInfo readSpiderInfoFromLocal() {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
return spiderInfo;
if (null != mSpiderInfo) {
return mSpiderInfo;
}
// Read from download dir
UniFile downloadDir = mSpiderDen.getDownloadDir();
if (downloadDir != null) {
UniFile file = downloadDir.findFile(SPIDER_INFO_FILENAME);
spiderInfo = SpiderInfo.read(file);
SpiderInfo spiderInfo = SpiderInfo.read(file);
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -695,7 +668,7 @@ public final class SpiderQueen implements Runnable {
if (null != pipe) {
try {
pipe.obtain();
spiderInfo = SpiderInfo.read(pipe.open());
SpiderInfo spiderInfo = SpiderInfo.read(pipe.open());
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -711,19 +684,9 @@ public final class SpiderQueen implements Runnable {
return null;
}
private void readPreviews(String body, int index, SpiderInfo spiderInfo) throws ParseException {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
private void readPreviews(String body, SpiderInfo spiderInfo) throws ParseException {
PreviewSet previewSet = GalleryDetailParser.parsePreviewSet(body);
if (previewSet.size() > 0) {
if (index == 0) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = previewSet.getPosition(0) / index;
}
}
spiderInfo.previewPerPage = previewSet.size();
for (int i = 0, n = previewSet.size(); i < n; i++) {
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
if (result != null) {
@@ -747,53 +710,39 @@ public final class SpiderQueen implements Runnable {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
readPreviews(body, 0, spiderInfo);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, spiderInfo);
return spiderInfo;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
return null;
}
}
private String getPTokenFromInternet(int index, EhConfig config) {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return null;
}
// Check previewIndex
int previewIndex;
if (spiderInfo.previewPerPage >= 0) {
previewIndex = index / spiderInfo.previewPerPage;
} else {
previewIndex = 0;
}
if (spiderInfo.previewPages > 0) {
previewIndex = Math.min(previewIndex, spiderInfo.previewPages - 1);
}
int previewIndex = index / mSpiderInfo.previewPerPage;
try {
String url = EhUrl.getGalleryDetailUrl(
mGalleryInfo.gid, mGalleryInfo.token, previewIndex, false);
if (DEBUG_PTOKEN) {
Log.d(TAG, "index " + index + ", previewIndex " + previewIndex +
", previewPerPage " + spiderInfo.previewPerPage+ ", url " + url);
if (DEBUG_LOG) {
Log.d(TAG, url);
}
Request request = new EhRequestBuilder(url, config).build();
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
readPreviews(body, previewIndex, spiderInfo);
mSpiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, mSpiderInfo);
// Save to local
writeSpiderInfoToLocal(spiderInfo);
writeSpiderInfoToLocal(mSpiderInfo);
String pToken;
synchronized (mPTokenLock) {
pToken = spiderInfo.pTokenMap.get(index);
pToken = mSpiderInfo.pTokenMap.get(index);
}
return pToken;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
return null;
}
}
@@ -805,8 +754,7 @@ public final class SpiderQueen implements Runnable {
UniFile file = downloadDir.createFile(SPIDER_INFO_FILENAME);
try {
spiderInfo.write(file.openOutputStream());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
// Ignore
}
}
@@ -847,7 +795,7 @@ public final class SpiderQueen implements Runnable {
if (spiderInfo == null) {
return;
}
mSpiderInfo.lazySet(spiderInfo);
mSpiderInfo = spiderInfo;
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
@@ -873,13 +821,11 @@ public final class SpiderQueen implements Runnable {
// Ensure worker
tryToEnsureWorkers();
// Start decoder
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
Thread decoderThread = new PriorityThread(new SpiderDecoder(i),
"SpiderDecoder-" + i, Process.THREAD_PRIORITY_DEFAULT);
mDecodeThreadArray[i] = decoderThread;
decoderThread.start();
}
// Start spider decoder
Thread decoderThread = new PriorityThread(new SpiderDecoder(), "SpiderDecoder-" + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
mDecoderThread = decoderThread;
decoderThread.start();
// handle pToken request
while (!Thread.currentThread().isInterrupted()) {
@@ -920,7 +866,7 @@ public final class SpiderQueen implements Runnable {
if (null == pToken) {
// If failed, set the pToken "failed"
synchronized (mPTokenLock) {
spiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
mSpiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
}
}
@@ -943,10 +889,9 @@ public final class SpiderQueen implements Runnable {
mQueenThread = null;
// Interrupt decoder
for (Thread decoderThread : mDecodeThreadArray) {
if (decoderThread != null) {
decoderThread.interrupt();
}
Thread decoderThread = mDecoderThread;
if (decoderThread != null) {
decoderThread.interrupt();
}
// Interrupt all workers
@@ -1018,27 +963,14 @@ public final class SpiderQueen implements Runnable {
mGid = mGalleryInfo.gid;
}
private String getPageUrl(long gid, int index, String pToken,
String oldPageUrl, String skipHathKey) {
String pageUrl;
if (oldPageUrl != null) {
pageUrl = oldPageUrl;
} else {
pageUrl = EhUrl.getPageUrl(gid, index, pToken);
}
// Add skipHathKey
private GalleryPageParser.Result getImageUrl(long gid, int index, String pToken,
String skipHathKey) throws Exception {
String url = EhUrl.getPageUrl(gid, index, pToken);
if (skipHathKey != null) {
if (pageUrl.contains("?")) {
pageUrl += "&nl=" + skipHathKey;
} else {
pageUrl += "?nl=" + skipHathKey;
}
url = url + "?nl=" + skipHathKey;
}
return pageUrl;
}
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Throwable {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl);
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, url);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
@@ -1051,31 +983,24 @@ public final class SpiderQueen implements Runnable {
// false for stop
private boolean downloadImage(long gid, int index, String pToken, boolean force) {
List<String> skipHathKeys = new ArrayList<>(5);
String skipHathKey = null;
String imageUrl;
String error = null;
String pageUrl = null;
boolean interrupt = false;
boolean leakSkipHathKey = false;
Log.d("TAG", "index = " + index);
// Try twice
for (int i = 0; i < 5; i++) {
if (leakSkipHathKey) {
for (int i = 0; i < 2; i++) {
if (i > 0 && TextUtils.isEmpty(skipHathKey)) {
// No need to get image url twice without skip hath key
break;
}
pageUrl = getPageUrl(gid, index, pToken, pageUrl, skipHathKey);
GalleryPageParser.Result result = null;
try {
result = getImageUrl(index, pageUrl);
result = getImageUrl(gid, index, pToken, skipHathKey);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
} catch (Exception e) {
error = ExceptionUtils.getReadableString(e);
}
if (result == null) {
@@ -1084,7 +1009,6 @@ public final class SpiderQueen implements Runnable {
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
@@ -1095,22 +1019,11 @@ public final class SpiderQueen implements Runnable {
imageUrl = result.imageUrl;
}
skipHathKey = result.skipHathKey;
if (!TextUtils.isEmpty(skipHathKey)) {
if (skipHathKeys.contains(skipHathKey)) {
// Duplicate skip hath key, don't run next turn
leakSkipHathKey = true;
} else {
skipHathKeys.add(skipHathKey);
}
} else {
// No skip hath key, don't run next turn
leakSkipHathKey = true;
}
// If it is force request, skip first image
//if (force && i == 0) {
// continue;
//}
if (force && i == 0) {
continue;
}
if (DEBUG_LOG) {
Log.d(TAG, imageUrl);
@@ -1126,29 +1039,19 @@ public final class SpiderQueen implements Runnable {
Call call = mHttpClient.newCall(new EhRequestBuilder(imageUrl).build());
Response response = call.execute();
ResponseBody responseBody = response.body();
if (response.code() >= 400) {
// Maybe 404
response.close();
error = "Bad code: " + response.code();
continue;
}
if (responseBody == null) {
error = "Empty response body";
response.body().close();
continue;
}
ResponseBody responseBody = response.body();
// Get extension
String extension = null;
MediaType mediaType = responseBody.contentType();
if (mediaType != null) {
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mediaType.toString());
}
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(
responseBody.contentType().toString());
// Ensure extension
if (!Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
if (!Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
}
// Get out put pipe
@@ -1156,7 +1059,7 @@ public final class SpiderQueen implements Runnable {
if (null == pipe) {
// Can't get pipe
error = GetText.getString(R.string.error_write_failed);
response.close();
response.body().close();
break;
}
@@ -1171,7 +1074,7 @@ public final class SpiderQueen implements Runnable {
while (!Thread.currentThread().isInterrupted()) {
int bytesRead = is.read(data);
if (bytesRead == -1) {
response.close();
response.body().close();
break;
}
os.write(data, 0, bytesRead);
@@ -1185,21 +1088,9 @@ public final class SpiderQueen implements Runnable {
}
os.flush();
// check download size
if (contentLength >= 0) {
if (receivedSize < contentLength) {
Log.e(TAG, "Can't download all of image data");
error = "Incomplete";
continue;
} else if (receivedSize > contentLength) {
Log.w(TAG, "Received data is more than contentLength");
}
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
interrupt = true;
error = "Interrupted";
break;
}
@@ -1211,7 +1102,6 @@ public final class SpiderQueen implements Runnable {
updatePageState(index, STATE_FINISHED);
return true;
} catch (IOException e) {
e.printStackTrace();
error = GetText.getString(R.string.error_socket);
} finally {
IOUtils.closeQuietly(is);
@@ -1235,11 +1125,6 @@ public final class SpiderQueen implements Runnable {
// false for stop
private boolean runInternal() {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return false;
}
int size = mPageStateArray.length;
// Get request index
@@ -1289,12 +1174,10 @@ public final class SpiderQueen implements Runnable {
// Clear TOKEN_FAILED for force request
if (force) {
synchronized (mPTokenLock) {
int i = spiderInfo.pTokenMap.indexOfKey(index);
if (i >= 0) {
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
spiderInfo.pTokenMap.remove(i);
}
int i = mSpiderInfo.pTokenMap.indexOfKey(index);
String pToken = mSpiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
mSpiderInfo.pTokenMap.remove(i);
}
}
}
@@ -1303,7 +1186,7 @@ public final class SpiderQueen implements Runnable {
// Get token
while (!Thread.currentThread().isInterrupted()) {
synchronized (mPTokenLock) {
pToken = spiderInfo.pTokenMap.get(index);
pToken = mSpiderInfo.pTokenMap.get(index);
}
if (pToken == null) {
mRequestPTokenQueue.add(index);
@@ -1331,7 +1214,7 @@ public final class SpiderQueen implements Runnable {
if (pToken == null) {
// Interrupted
// Get token failed
updatePageState(index, STATE_FAILED, "Interrupted");
updatePageState(index, STATE_FAILED, null);
return false;
}
@@ -1377,18 +1260,6 @@ public final class SpiderQueen implements Runnable {
private class SpiderDecoder implements Runnable {
private final int mThreadIndex;
public SpiderDecoder(int index) {
mThreadIndex = index;
}
private void resetDecodeIndex() {
synchronized (mDecodeRequestQueue) {
mDecodeIndexArray[mThreadIndex] = GalleryPageView.INVALID_INDEX;
}
}
@Override
public void run() {
if (DEBUG_LOG) {
@@ -1397,67 +1268,55 @@ public final class SpiderQueen implements Runnable {
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (mDecodeRequestQueue) {
if (mDecodeRequestQueue.isEmpty()) {
synchronized (mDecodeRequestStack) {
if (mDecodeRequestStack.isEmpty()) {
try {
mDecodeRequestQueue.wait();
mDecodeRequestStack.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = mDecodeRequestQueue.remove();
mDecodeIndexArray[mThreadIndex] = index;
index = mDecodeRequestStack.pop();
mDecodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= mPageStateArray.length) {
resetDecodeIndex();
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_out_of_range));
continue;
}
InputStreamPipe pipe = mSpiderDen.openInputStreamPipe(index);
if (pipe == null) {
resetDecodeIndex();
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
// Can't find the file, it might be removed from cache,
// Reset it state and request it
updatePageState(index, STATE_NONE, null);
request(index, false, false, false);
request(index, false, false);
continue;
}
Image image = null;
String error = null;
InputStream is;
pipe.obtain();
try {
is = new AutoCloseInputStream(pipe, pipe.open());
pipe.obtain();
// TODO how to keep stream open
Image image = Image.decode(pipe.open(), false);
if (image != null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageSuccess(index, image);
} else {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_decoding_failed));
}
} catch (IOException e) {
// Can't open pipe
error = GetText.getString(R.string.error_reading_failed);
is = null;
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_reading_failed));
} finally {
pipe.close();
pipe.release();
}
if (is != null) {
image = Image.decode(is, true);
if (image == null) {
error = GetText.getString(R.string.error_decoding_failed);
}
}
// Notify
if (image != null) {
notifyGetImageSuccess(index, image);
} else {
notifyGetImageFailure(index, error);
}
resetDecodeIndex();
}
if (DEBUG_LOG) {
@@ -1466,33 +1325,6 @@ public final class SpiderQueen implements Runnable {
}
}
private class AutoCloseInputStream extends InputStream {
private final InputStreamPipe mPipe;
private final InputStream mIs;
public AutoCloseInputStream(InputStreamPipe pipe, InputStream is) {
mPipe = pipe;
mIs = is;
}
@Override
public int read() throws IOException {
return mIs.read();
}
@Override
public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
return mIs.read(buffer, byteOffset, byteCount);
}
@Override
public void close() throws IOException {
mPipe.close();
mPipe.release();
}
}
public interface OnSpiderListener {
void onGetPages(int pages);
@@ -33,7 +33,6 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.UrlOpener;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhRequest;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.download.DownloadManager;
@@ -101,13 +100,17 @@ public final class CommonOperations {
}
private void showUpToDateDialog() {
if (!mFeedback) {
return;
}
new AlertDialog.Builder(mActivity)
.setMessage(R.string.update_to_date)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void showUpdateDialog(String versionName, int versionCode, String size, CharSequence info, final String url) {
private void showUpdateDialog(String versionName, String size, CharSequence info, final String url) {
new AlertDialog.Builder(mActivity)
.setTitle(R.string.update)
.setMessage(mActivity.getString(R.string.update_plain, versionName, size, info))
@@ -116,22 +119,16 @@ public final class CommonOperations {
public void onClick(DialogInterface dialog, int which) {
UrlOpener.openUrl(mActivity, url, false);
}
})
.setNegativeButton(R.string.update_ignore, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Settings.putSkipUpdateVersion(versionCode);
}
}).show();
}
private void handleResult(JSONObject jo) {
if (null == jo || mActivity.isFinishing()) {
return;
}
String versionName;
int versionCode;
String size;
CharSequence info;
String url;
@@ -140,12 +137,10 @@ public final class CommonOperations {
PackageManager pm = mActivity.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mActivity.getPackageName(), PackageManager.GET_ACTIVITIES);
int currentVersionCode = pi.versionCode;
versionCode = jo.getInt("version_code");
if (currentVersionCode >= versionCode) {
int newVersionCode = jo.getInt("version_code");
if (currentVersionCode >= newVersionCode) {
// Update to date
if (mFeedback) {
showUpToDateDialog();
}
showUpToDateDialog();
return;
}
@@ -157,9 +152,7 @@ public final class CommonOperations {
return;
}
if (mFeedback || versionCode != Settings.getSkipUpdateVersion()) {
showUpdateDialog(versionName, versionCode, size, info, url);
}
showUpdateDialog(versionName, size, info, url);
}
@Override
@@ -192,31 +185,27 @@ public final class CommonOperations {
public static void addToFavorites(final Activity activity, final GalleryInfo galleryInfo,
final EhClient.Callback<Void> listener) {
int slot = Settings.getDefaultFavSlot();
String[] items = new String[11];
items[0] = activity.getString(R.string.local_favorites);
String[] favCat = Settings.getFavCat();
System.arraycopy(favCat, 0, items, 1, 10);
if (slot >= -1 && slot <= 9) {
String newFavoriteName = slot >= 0 ? items[slot + 1] : null;
doAddToFavorites(activity, galleryInfo, slot, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
doAddToFavorites(activity, galleryInfo, slot, listener);
} else {
String[] items = new String[11];
items[0] = activity.getString(R.string.local_favorites);
String[] favCat = Settings.getFavCat();
System.arraycopy(favCat, 0, items, 1, 10);
new ListCheckBoxDialogBuilder(activity, items,
(builder, dialog, position) -> {
int slot1 = position - 1;
String newFavoriteName = (slot1 >= 0 && slot1 <= 9) ? items[slot1+1] : null;
doAddToFavorites(activity, galleryInfo, slot1, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
if (builder.isChecked()) {
Settings.putDefaultFavSlot(slot1);
} else {
Settings.putDefaultFavSlot(Settings.INVALID_DEFAULT_FAV_SLOT);
new ListCheckBoxDialogBuilder.OnItemClickListener() {
@Override
public void onItemClick(ListCheckBoxDialogBuilder builder, AlertDialog dialog, int position) {
int slot = position - 1;
doAddToFavorites(activity, galleryInfo, slot, listener);
if (builder.isChecked()) {
Settings.putDefaultFavSlot(slot);
} else {
Settings.putDefaultFavSlot(Settings.INVALID_DEFAULT_FAV_SLOT);
}
}
}, activity.getString(R.string.remember_favorite_collection), false)
.setTitle(R.string.add_favorites_dialog_title)
.setOnCancelListener(dialog -> listener.onCancel())
.show();
}
}
@@ -227,42 +216,10 @@ public final class CommonOperations {
EhRequest request = new EhRequest();
request.setMethod(EhClient.METHOD_ADD_FAVORITES);
request.setArgs(galleryInfo.gid, galleryInfo.token, -1, "");
request.setCallback(galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, null)
: listener);
request.setCallback(listener);
client.execute(request);
}
private static class UpdateFavoriteNameCallback implements EhClient.Callback<Void> {
private final EhClient.Callback<Void> delegate;
private final GalleryDetail detail;
private final String newFavoriteName;
UpdateFavoriteNameCallback(EhClient.Callback<Void> delegate, GalleryDetail detail,
String newFavoriteName) {
this.delegate = delegate;
this.detail = detail;
this.newFavoriteName = newFavoriteName;
}
@Override
public void onSuccess(Void result) {
detail.favoriteName = newFavoriteName;
delegate.onSuccess(result);
}
@Override
public void onFailure(Exception e) {
delegate.onFailure(e);
}
@Override
public void onCancel() {
delegate.onCancel();
}
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
final DownloadManager dm = EhApplication.getDownloadManager(activity);
@@ -0,0 +1,106 @@
/*
* Copyright 2016 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 android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.ViewUtils;
public class DictActivity extends ToolbarActivity {
private static final int REQUEST_CODE_SELECT_DICT_FILE = 0;
@Nullable
private EasyRecyclerView mRecyclerView;
@Nullable
private ViewTransition mViewTransition;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(this, R.id.recycler_view);
TextView tip = (TextView) ViewUtils.$$(this, R.id.tip);
mViewTransition = new ViewTransition(mRecyclerView, tip);
}
@Override
protected void onDestroy() {
super.onDestroy();
mRecyclerView = null;
mViewTransition = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_dict, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_import:
Intent intent = new Intent();
intent.setType("application/octet-stream");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getString(R.string.select_dict_file)), REQUEST_CODE_SELECT_DICT_FILE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (REQUEST_CODE_SELECT_DICT_FILE == requestCode) {
if (Activity.RESULT_OK != resultCode) {
return;
}
Uri uri = data.getData();
if (null == uri) {
return;
}
Intent intent = new Intent(this, DictImportActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
@@ -0,0 +1,213 @@
package com.hippo.ehviewer.ui;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hippo.dict.DictImportService;
import com.hippo.ehviewer.R;
import com.hippo.util.TextUrl;
public class DictImportActivity extends EhActivity {
private final static String TAG = "DictImportActivity";
private static final boolean DEBUG = false;
private DictImportService serviceBinder;
private int mItemNum = 0;
private Button mConfirmBtn;
private Button mCancelBtn;
private Button mHideBtn;
private ProgressBar mProgressBar;
private TextView mProgressTipView;
private TextView mTipView;
private Uri mDictUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict_improt);
Intent intent = new Intent(DictImportActivity.this, DictImportService.class);
if (DEBUG) {
Log.d(TAG, "[onCreate] bind service");
}
bindService(intent, conn, Context.BIND_AUTO_CREATE);
startService(intent);
mConfirmBtn = (Button) findViewById(R.id.btn_confirm);
mCancelBtn = (Button) findViewById(R.id.btn_cancel);
mHideBtn = (Button) findViewById(R.id.btn_hide);
mProgressBar = (ProgressBar) findViewById(R.id.bar_import);
mProgressTipView = (TextView) findViewById(R.id.tv_progress);
mTipView = (TextView) findViewById(R.id.tv_tip);
mConfirmBtn.setOnClickListener(confirmListener);
mCancelBtn.setOnClickListener(cancelListener);
mHideBtn.setOnClickListener(hideListener);
}
private final ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG) {
Log.w(TAG, "[onServiceConnected] disconnect to service");
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceBinder = ((DictImportService.DictImportServiceBinder) service).getService();
serviceBinder.setOnProgressListener(importListener);
// if we are doing a task,we load improt infomation from service
// and ignore the newer import task
if (serviceBinder.isRunning()) {
initFromService();
} else {
initFromIntent();
}
if (DEBUG) {
Log.d(TAG, "[onServiceConnected] connect to service");
}
}
};
private final DictImportService.ProcessListener importListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.i(TAG, "[process] " + progress);
}
mProgressBar.setProgress(progress);
mProgressTipView.setText(progress + "/" + mItemNum);
}
@Override
public void processTotal(int total) {
mItemNum = total;
mProgressBar.setMax(mItemNum);
}
@Override
public void processComplete() {
mCancelBtn.setText(getResources().getString(R.string.done));
mHideBtn.setVisibility(View.GONE);
}
};
private final View.OnClickListener cancelListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
DictImportActivity.this.finish();
}
};
private final View.OnClickListener abortListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] abort");
}
if (serviceBinder != null) {
serviceBinder.abortImport();
}
DictImportActivity.this.finish();
}
};
private final View.OnClickListener confirmListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] confirm");
}
if (serviceBinder == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] service is not connected");
}
return;
}
if (mDictUri == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] mDictUri is not be init");
}
return;
}
serviceBinder.importDict(mDictUri);
view.setVisibility(View.GONE);
mCancelBtn.setOnClickListener(abortListener);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
}
};
private final View.OnClickListener hideListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] hide");
}
DictImportActivity.this.finish();
}
};
@Override
protected void onDestroy() {
serviceBinder.removeOnProgressListener(importListener);
unbindService(conn);
super.onDestroy();
}
private void initFromService() {
mDictUri = serviceBinder.getUri();
if (mDictUri == null) {
if (DEBUG) {
Log.e(TAG, "[initFromService] error use of initFromService,you may use initFromIntent instead");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[initFromService] " + mDictUri.toString());
}
mItemNum = serviceBinder.getItemNum();
mProgressBar.setMax(mItemNum);
mConfirmBtn.setVisibility(View.GONE);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
mCancelBtn.setOnClickListener(abortListener);
}
private void initFromIntent() {
mDictUri = getIntent().getData();
if (DEBUG) {
Log.d(TAG, "[initFromIntent] " + mDictUri.toString());
}
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
}
}
Loaded 100 of 739 files, more files were not shown because too many files have changed in this diff. Show more