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
480 changed files with 145786 additions and 3351 deletions

No files matched your search

+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 -1
View File
@@ -18,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
@@ -39,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
+54 -50
View File
@@ -1,27 +1,19 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "24.0.0 rc4"
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 23
versionCode 65
versionName "1.0.12"
versionCode 59
versionName "1.0.6"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
incremental true
}
lintOptions {
@@ -38,51 +30,63 @@ android {
sourceSets {
main {
java.srcDirs += 'src/main/java-gen'
// Disable default NdkCompile task
jni.srcDirs = []
// Set new jni lib dir
jniLibs.srcDir 'src/main/libs'
}
}
// noinspection GroovyAssignabilityCheck
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
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) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
task copyNotice(type: Copy) {
from '../NOTICE.html'
into './src/main/assets'
finalizedBy ":daogenerator:executeDaoGenerator"
}
tasks.withType(AbstractCompile) {
compileTask -> compileTask.dependsOn copyNotice
}
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 {
compile project(':beerbelly')
compile project(':conaco')
compile project(':easyrecyclerview')
compile project(':okhttp3')
compile project(':yorozuya')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.seven332:animator:0.1.0'
compile 'com.github.seven332:beerbelly:0.1.4'
compile 'com.github.seven332:conaco:0.1.5-eh'
compile 'com.github.seven332:drawerlayout:0.1.0'
compile 'com.github.seven332:easyrecyclerview:0.1.0'
compile 'com.github.seven332:glgallery:0.1.2'
compile 'com.github.seven332:glview:0.1.0'
compile 'com.github.seven332:glview-image:0.1.0'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.9-jpeg-png-gif'
compile 'com.github.seven332:okhttp:3.3.1-eh'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.1'
compile 'com.github.seven332:streampipe:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.2'
compile 'com.github.seven332:unifile:0.1.4'
compile 'com.github.seven332:yorozuya:0.1.2'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.4'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.1'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.greenrobot:greendao:2.2.0'
compile 'org.jsoup:jsoup:1.9.2'
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.
+73
View File
@@ -67,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
@@ -116,6 +178,12 @@
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"
@@ -133,5 +201,10 @@
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<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;
@@ -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);
}
}
@@ -24,9 +24,6 @@ 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;
@@ -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
@@ -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;
}
}
@@ -21,15 +21,12 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.File;
import java.io.FileInputStream;
@@ -38,8 +35,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public final class Crash {
private Crash() {}
public class Crash {
@NonNull
private static String avoidNull(String str) {
@@ -69,17 +65,14 @@ public final class Crash {
}
// Runtime
String topActivityClazzName = "null";
String topSceneClazzName = "null";
String topActivityClazzName = null;
String topSceneClazzName = null;
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
Class<?> clazz = ((StageActivity) topActivity).getTopSceneClass();
if (clazz != null) {
topSceneClazzName = clazz.getName();
}
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
}
}
} catch (Throwable e) {
@@ -114,10 +107,6 @@ public final class Crash {
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("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));fw.write("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
@@ -17,16 +17,20 @@
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.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.ehviewer.client.EhClient;
@@ -37,8 +41,6 @@ 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;
@@ -48,7 +50,6 @@ 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;
@@ -69,9 +70,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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;
@@ -80,8 +79,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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;
@@ -94,6 +93,15 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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();
GetText.initialize(this);
@@ -138,8 +146,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
// Ignore
}
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
if (DEBUG_NATIVE_MEMORY) {
debugNativeMemory();
}
}
@@ -186,7 +194,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public void clearMemoryCache() {
if (null != mConaco) {
mConaco.getBeerBelly().clearMemory();
mConaco.clearMemoryCache();
}
if (null != mGalleryDetailCache) {
mGalleryDetailCache.evictAll();
@@ -202,18 +210,13 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
}
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();
}
@@ -262,9 +265,9 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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))
.build();
}
@@ -272,30 +275,33 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
@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();
}
@@ -47,7 +47,7 @@ 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;
@@ -29,15 +29,15 @@ 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.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import junit.framework.Assert;
import java.io.File;
public class Settings {
@@ -255,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;
@@ -412,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
********************/
@@ -434,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() {
@@ -446,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) {
@@ -458,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) {
@@ -724,7 +699,7 @@ public class Settings {
}
public static void putFavCat(String[] value) {
Assert.assertEquals(10, value.length);
AssertUtils.assertEquals(10, value.length);
sSettingsPre.edit()
.putString(KEY_FAV_CAT_0, value[0])
.putString(KEY_FAV_CAT_1, value[1])
@@ -22,8 +22,8 @@ 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.yorozuya.PriorityThreadFactory;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.File;
import java.util.List;
@@ -45,8 +45,7 @@ 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 junit.framework.Assert;
import com.hippo.yorozuya.AssertUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -502,7 +501,7 @@ public class EhEngine {
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
Assert.assertEquals(gidArray.length, tokenArray.length);
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);
}
@@ -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),
@@ -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;
@@ -22,8 +22,7 @@ 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.JsoupUtils;
import junit.framework.Assert;
import com.hippo.yorozuya.AssertUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@@ -54,7 +53,7 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
Assert.assertEquals(11, fps.size());
AssertUtils.assertEqualsEx(11, fps.size());
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
@@ -28,12 +28,12 @@ import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.image.Image;
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.util.ArrayList;
import java.util.Collections;
@@ -40,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;
@@ -23,13 +23,13 @@ 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.UniFile;
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;
@@ -41,7 +41,7 @@ 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();
@@ -84,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);
@@ -95,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));
}
@@ -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;
@@ -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);
}
@@ -23,11 +23,11 @@ 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.UniFile;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.File;
import java.io.FileNotFoundException;
@@ -43,7 +43,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class ZipGalleryProvider extends GalleryProvider2 implements Runnable {
public class ZipGalleryProvider extends GalleryProvider implements Runnable {
private static final String TAG = ZipGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -85,7 +85,7 @@ public class ZipGalleryProvider 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);
@@ -96,12 +96,7 @@ public class ZipGalleryProvider extends GalleryProvider2 implements Runnable {
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
public void cancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
@@ -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
@@ -31,7 +31,6 @@ 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.yorozuya.IOUtils;
@@ -89,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;
@@ -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();
@@ -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,13 +70,13 @@ 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.OkHttpClient;
@@ -85,12 +84,11 @@ 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)
@@ -108,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 = {
@@ -130,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();
@@ -182,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));
@@ -275,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);
@@ -320,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;
@@ -422,6 +413,7 @@ public final class SpiderQueen implements Runnable {
}
public String getError() {
// TODO
if (mQueenThread == null) {
return "Error";
} else {
@@ -472,9 +464,6 @@ public final class SpiderQueen implements Runnable {
synchronized (mRequestPageQueue) {
mRequestPageQueue.remove(index);
}
synchronized (mDecodeRequestQueue) {
mDecodeRequestQueue.remove(index);
}
}
/**
@@ -493,8 +482,6 @@ public final class SpiderQueen implements Runnable {
// Fix state for force
if (force && (state == STATE_FINISHED || state == STATE_FAILED)) {
// Update state to none at once
updatePageState(index, STATE_NONE);
state = STATE_NONE;
}
@@ -544,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;
@@ -559,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) {
@@ -648,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();
@@ -672,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;
@@ -693,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;
@@ -709,16 +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 ((index >= 0 && index < spiderInfo.pages - 1) || (index == 0 && spiderInfo.pages == 1)) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = Math.max(spiderInfo.previewPerPage, previewSet.size());
}
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) {
@@ -742,7 +710,8 @@ 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 (Exception e) {
return null;
@@ -750,37 +719,27 @@ public final class SpiderQueen implements Runnable {
}
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;
}
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 (Exception e) {
@@ -836,7 +795,7 @@ public final class SpiderQueen implements Runnable {
if (spiderInfo == null) {
return;
}
mSpiderInfo.lazySet(spiderInfo);
mSpiderInfo = spiderInfo;
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
@@ -862,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()) {
@@ -909,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);
}
}
@@ -932,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
@@ -1094,8 +1050,8 @@ public final class SpiderQueen implements Runnable {
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
@@ -1169,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
@@ -1223,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);
}
}
}
@@ -1237,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);
@@ -1311,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) {
@@ -1331,30 +1268,30 @@ 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);
@@ -1362,36 +1299,24 @@ public final class SpiderQueen implements Runnable {
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) {
@@ -1400,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);
@@ -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()));
}
}
@@ -0,0 +1,21 @@
/*
* 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;
// It is a dump activity to make Chrome or maybe other browser to send implicit intent when open eh url.
// Take a look at AndroidManifest to know how it works.
public class DumpBrowsableActivity extends EhActivity {}
@@ -24,7 +24,7 @@ import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public abstract class EhActivity extends AppCompatActivity {
public class EhActivity extends AppCompatActivity {
private boolean mTrackStarted;
@@ -24,7 +24,7 @@ import com.hippo.app.AppCompatPreferenceActivity;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public abstract class EhPreferenceActivity extends AppCompatPreferenceActivity {
public class EhPreferenceActivity extends AppCompatPreferenceActivity {
private boolean mTrackStarted;
@@ -25,7 +25,6 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -53,29 +52,31 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.DirGalleryProvider;
import com.hippo.ehviewer.gallery.EhGalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProviderListener;
import com.hippo.ehviewer.gallery.ZipGalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.ehviewer.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.glgallery.GalleryView;
import com.hippo.glgallery.SimpleAdapter;
import com.hippo.glview.view.GLRootView;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.view.GLRootView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChangeListener,
public class GalleryActivity extends EhActivity
implements GalleryProviderListener, SeekBar.OnSeekBarChangeListener,
GalleryView.Listener {
public static final String ACTION_DIR = "dir";
@@ -98,14 +99,13 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
private GalleryInfo mGalleryInfo;
private int mPage;
@Nullable
private GLRootView mGLRootView;
@Nullable
private GalleryView mGalleryView;
@Nullable
private GalleryProvider2 mGalleryProvider;
private ImageTexture.Uploader mUploader;
@Nullable
private GalleryAdapter mGalleryAdapter;
private GalleryProvider mGalleryProvider;
@Nullable
private SystemUiHelper mSystemUiHelper;
@@ -234,7 +234,6 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
}
@Override
@SuppressWarnings("deprecation")
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (Settings.getReadingFullscreen() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow();
@@ -256,9 +255,14 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
finish();
return;
}
mGalleryProvider.setGalleryProviderListener(this);
mGalleryProvider.start();
// Get start page
setContentView(R.layout.activity_gallery);
GLRootView glRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryProvider.setGLRoot(glRootView);
mUploader = new ImageTexture.Uploader(glRootView);
int startPage;
if (savedInstanceState == null) {
startPage = mPage >= 0 ? mPage : mGalleryProvider.getStartPage();
@@ -266,37 +270,10 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
startPage = mCurrentIndex;
}
setContentView(R.layout.activity_gallery);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryAdapter = new GalleryAdapter(mGLRootView, mGalleryProvider);
Resources resources = getResources();
int primaryColor = ResourcesUtils.getAttrColor(this, R.attr.colorPrimary);
mGalleryView = new GalleryView.Builder(this, mGalleryAdapter)
.setListener(this)
.setLayoutMode(Settings.getReadingDirection())
.setScaleMode(Settings.getPageScaling())
.setStartPosition(Settings.getStartPosition())
.setStartPage(startPage)
.setBackgroundColor(resources.getColor(R.color.gallery_background))
.setEdgeColor(primaryColor & 0xffffff | 0x33000000)
.setPagerInterval(resources.getDimensionPixelOffset(R.dimen.gallery_pager_interval))
.setScrollInterval(resources.getDimensionPixelOffset(R.dimen.gallery_scroll_interval))
.setPageMinHeight(resources.getDimensionPixelOffset(R.dimen.gallery_page_min_height))
.setPageInfoInterval(resources.getDimensionPixelOffset(R.dimen.gallery_page_info_interval))
.setProgressColor(primaryColor)
.setProgressSize(resources.getDimensionPixelOffset(R.dimen.gallery_progress_size))
.setPageTextColor(resources.getColor(R.color.secondary_text_default_dark))
.setPageTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_page_text_size))
.setPageTextTypeface(Typeface.DEFAULT)
.setErrorTextColor(resources.getColor(R.color.red_500))
.setErrorTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_error_text_size))
.setDefaultErrorString(resources.getString(R.string.error_unknown))
.setEmptyString(resources.getString(R.string.error_empty))
.build();
mGLRootView.setContentPane(mGalleryView);
mGalleryProvider.setListener(mGalleryAdapter);
mGalleryProvider.setGLRoot(mGLRootView);
mGalleryView = new GalleryView(this, new GalleryAdapter(), this,
Settings.getReadingDirection(), Settings.getPageScaling(),
Settings.getStartPosition(), startPage);
glRootView.setContentPane(mGalleryView);
// System UI helper
if (Settings.getReadingFullscreen()) {
@@ -366,14 +343,13 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
@Override
protected void onDestroy() {
super.onDestroy();
mGLRootView = null;
mGalleryView = null;
if (mGalleryAdapter != null) {
mGalleryAdapter.clearUploader();
mGalleryAdapter = null;
if (mUploader != null) {
mUploader.clear();
mUploader = null;
}
if (mGalleryProvider != null) {
mGalleryProvider.setListener(null);
mGalleryProvider.setGalleryProviderListener(null);
mGalleryProvider.stop();
mGalleryProvider = null;
}
@@ -390,24 +366,6 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
SimpleHandler.getInstance().removeCallbacks(mHideSliderRunnable);
}
@Override
protected void onPause() {
super.onPause();
if (mGLRootView != null) {
mGLRootView.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mGLRootView != null) {
mGLRootView.onResume();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
@@ -430,14 +388,14 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
// Check volume
if (Settings.getVolumePage()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -450,7 +408,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_DPAD_UP:
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
@@ -461,7 +419,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
return true;
case KeyEvent.KEYCODE_PAGE_DOWN:
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -534,7 +492,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
TextView start;
TextView end;
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
start = mRightText;
end = mLeftText;
mSeekBar.setReverse(true);
@@ -549,11 +507,90 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
mSeekBar.setProgress(mCurrentIndex);
}
@Override
public void onDataChanged() {
if (mGalleryView != null) {
mGalleryView.onDataChanged();
}
if (mGalleryProvider != null) {
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
}
}
@Override
public void onPageWait(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
page.setError(null, null);
}
}
@Override
public void onPagePercent(int index, float percent) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(percent);
page.setError(null, null);
}
}
@Override
public void onPageSucceed(int index, Image image) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
ImageTexture imageTexture = new ImageTexture(image);
if (mUploader != null) {
mUploader.addTexture(imageTexture);
}
page.showImage();
page.setImage(imageTexture);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(null, null);
} else {
image.recycle();
}
}
@Override
public void onPageFailed(int index, String error) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryView != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(error, mGalleryView);
}
}
@Override
public void onDataChanged(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
@Override
@SuppressLint("SetTextI18n")
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView start;
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
start = mRightText;
} else {
start = mLeftText;
@@ -752,8 +789,8 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
public void onClick(DialogInterface dialog, int which) {
int screenRotation = mScreenRotation.getSelectedItemPosition();
int layoutMode = GalleryView.sanitizeLayoutMode(mReadingDirection.getSelectedItemPosition());
int scaleMode = GalleryView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = GalleryView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
int scaleMode = ImageView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = ImageView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
boolean keepScreenOn = mKeepScreenOn.isChecked();
boolean showClock = mShowClock.isChecked();
boolean showProgress = mShowProgress.isChecked();
@@ -975,25 +1012,46 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
}
}
private class GalleryAdapter extends SimpleAdapter {
private class GalleryAdapter extends GalleryView.Adapter {
public GalleryAdapter(@NonNull GLRootView glRootView, @NonNull GalleryProvider provider) {
super(glRootView, provider);
@Override
public String getError() {
if (mGalleryProvider == null) {
return getString(R.string.error_no_provider);
} else if (mGalleryProvider.size() <= GalleryProvider.STATE_ERROR) {
return mGalleryProvider.getError();
}
return null;
}
@Override
public void onDataChanged() {
super.onDataChanged();
if (mGalleryProvider != null) {
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
public int size() {
if (mGalleryProvider == null) {
return GalleryProvider.STATE_ERROR;
} else {
return mGalleryProvider.size();
}
}
@Override
public void onBind(GalleryPageView view, int index) {
if (mGalleryProvider != null && mGalleryView != null) {
mGalleryProvider.request(index);
view.showInfo();
view.setImage(null);
view.setPage(index + 1);
view.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
view.setError(null, null);
}
}
@Override
public void onUnbind(GalleryPageView view, int index) {
if (mGalleryProvider != null) {
mGalleryProvider.cancelRequest(index);
}
view.setImage(null);
view.setError(null, null);
}
}
}
@@ -33,7 +33,7 @@ public class LicenseActivity extends ToolbarActivity {
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
mWebView.loadUrl("file:///android_asset/NOTICE.html");
mWebView.loadUrl("file:///android_asset/NOTICE");
setContentView(mWebView);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
@@ -20,7 +20,6 @@ import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -33,6 +32,7 @@ import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
@@ -66,12 +66,10 @@ import com.hippo.ehviewer.ui.scene.QuickSearchScene;
import com.hippo.ehviewer.ui.scene.SecurityScene;
import com.hippo.ehviewer.ui.scene.SelectSiteScene;
import com.hippo.ehviewer.ui.scene.SignInScene;
import com.hippo.ehviewer.ui.scene.SolidScene;
import com.hippo.ehviewer.ui.scene.WarningScene;
import com.hippo.ehviewer.ui.scene.WebViewSignInScene;
import com.hippo.ehviewer.widget.EhDrawerLayout;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.network.Network;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.scene.StageActivity;
@@ -91,12 +89,24 @@ import java.io.OutputStream;
public final class MainActivity extends StageActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
private static final int REQUEST_CODE_SETTINGS = 0;
private static final String KEY_NAV_CHECKED_ITEM = "nav_checked_item";
public static final int CHECK_STEP_SECURITY = 0;
public static final int CHECK_STEP_WARNING = 1;
public static final int CHECK_STEP_ANALYTICS = 2;
public static final int CHECK_STEP_CRASH = 3;
public static final int CHECK_STEP_SIGN_IN = 4;
public static final int CHECK_STEP_SELECT_SITE = 5;
public static final String KEY_TARGET_SCENE = "target_scene";
public static final String KEY_TARGET_ARGS = "target_args";
/*---------------
Whole life cycle
---------------*/
@@ -135,6 +145,61 @@ public final class MainActivity extends StageActivity
registerLaunchMode(ProgressScene.class, SceneFragment.LAUNCH_MODE_STANDARD);
}
public void startSceneForCheckStep(int checkStep, Bundle args) {
switch (checkStep) {
case CHECK_STEP_SECURITY:
if (Settings.getShowWarning()) {
startScene(new Announcer(WarningScene.class).setArgs(args));
break;
}
case CHECK_STEP_WARNING:
if (Settings.getAskAnalytics()) {
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
break;
}
case CHECK_STEP_ANALYTICS:
if (Crash.hasCrashFile()) {
startScene(new Announcer(CrashScene.class).setArgs(args));
break;
}
case CHECK_STEP_CRASH:
if (EhUtils.needSignedIn(this)) {
startScene(new Announcer(SignInScene.class).setArgs(args));
break;
}
case CHECK_STEP_SIGN_IN:
if (Settings.getSelectSite()) {
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
break;
}
case CHECK_STEP_SELECT_SITE:
String targetScene = null;
Bundle targetArgs = null;
if (null != args) {
targetScene = args.getString(KEY_TARGET_SCENE);
targetArgs = args.getBundle(KEY_TARGET_ARGS);
}
Class<?> clazz = null;
if (targetScene != null) {
try {
clazz = Class.forName(targetScene);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Can't find class with name: " + targetScene);
}
}
if (clazz != null) {
startScene(new Announcer(clazz).setArgs(targetArgs));
} else {
Bundle newArgs = new Bundle();
newArgs.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(new Announcer(GalleryListScene.class).setArgs(newArgs));
}
break;
}
}
@Override
public int getContainerViewId() {
return R.id.fragment_container;
@@ -167,33 +232,33 @@ public final class MainActivity extends StageActivity
if (0 == getSceneCount()) {
if (!TextUtils.isEmpty(Settings.getSecurity())) {
Bundle newArgs = new Bundle();
newArgs.putString(SecurityScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SecurityScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SecurityScene.class).setArgs(newArgs);
} else if (Settings.getShowWarning()) {
Bundle newArgs = new Bundle();
newArgs.putString(WarningScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(WarningScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(WarningScene.class).setArgs(newArgs);
} else if (Settings.getAskAnalytics()) {
Bundle newArgs = new Bundle();
newArgs.putString(AnalyticsScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(AnalyticsScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(AnalyticsScene.class).setArgs(newArgs);
} else if (Crash.hasCrashFile()) {
Bundle newArgs = new Bundle();
newArgs.putString(CrashScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(CrashScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(CrashScene.class).setArgs(newArgs);
} else if (EhUtils.needSignedIn(this)) {
Bundle newArgs = new Bundle();
newArgs.putString(SignInScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SignInScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SignInScene.class).setArgs(newArgs);
} else if (Settings.getSelectSite()) {
Bundle newArgs = new Bundle();
newArgs.putString(SelectSiteScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SelectSiteScene.KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SelectSiteScene.class).setArgs(newArgs);
}
}
@@ -274,12 +339,6 @@ public final class MainActivity extends StageActivity
@Override
protected void onUnrecognizedIntent(@Nullable Intent intent) {
Class<?> clazz = getTopSceneClass();
if (clazz != null && SolidScene.class.isAssignableFrom(clazz)) {
// TODO the intent lost
return;
}
if (!handleIntent(intent)) {
boolean handleUrl = false;
if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
@@ -333,9 +392,6 @@ public final class MainActivity extends StageActivity
onInit();
CommonOperations.checkUpdate(this, false);
checkDownloadLocation();
if (Settings.getCellularNetworkWarning()) {
checkCellularNetwork();
}
} else {
onRestore(savedInstanceState);
}
@@ -354,12 +410,6 @@ public final class MainActivity extends StageActivity
.show();
}
private void checkCellularNetwork() {
if (Network.getActiveNetworkType(this) == ConnectivityManager.TYPE_MOBILE) {
showTip(R.string.cellular_network_warning, BaseScene.LENGTH_SHORT);
}
}
private void onInit() {
// Check permission
PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
@@ -26,7 +26,7 @@ import android.view.ViewGroup;
import com.hippo.ehviewer.R;
public abstract class ToolbarActivity extends EhActivity {
public class ToolbarActivity extends EhActivity {
@Override
public void setContentView(@LayoutRes int layoutResID) {
@@ -16,14 +16,10 @@
package com.hippo.ehviewer.ui.fragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.EhApplication;
@@ -79,10 +75,6 @@ public class AboutFragment extends PreferenceFragment
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, "seven332$163.com".replace('$', '@')));
Toast.makeText(getActivity(), R.string.settings_about_donate_toast, Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_about_donate)
.setMessage(getString(R.string.settings_about_donate_message).replace('$', '@'))
@@ -34,12 +34,10 @@ public class EhFragment extends PreferenceFragment
Preference gallerySite = findPreference(Settings.KEY_GALLERY_SITE);
Preference listMode = findPreference(Settings.KEY_LIST_MODE);
Preference detailSize = findPreference(Settings.KEY_DETAIL_SIZE);
Preference thumbSize = findPreference(Settings.KEY_THUMB_SIZE);
gallerySite.setOnPreferenceChangeListener(this);
listMode.setOnPreferenceChangeListener(this);
detailSize.setOnPreferenceChangeListener(this);
thumbSize.setOnPreferenceChangeListener(this);
}
@@ -52,8 +50,6 @@ public class EhFragment extends PreferenceFragment
} else if (Settings.KEY_LIST_MODE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
return true;
} else if (Settings.KEY_DETAIL_SIZE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
} else if (Settings.KEY_THUMB_SIZE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
}
@@ -32,7 +32,7 @@ import com.hippo.text.Html;
import com.hippo.text.LinkMovementMethod2;
import com.hippo.yorozuya.ViewUtils;
public class AnalyticsScene extends SolidScene implements View.OnClickListener {
public class AnalyticsScene extends BaseScene implements View.OnClickListener {
@Nullable
private View mReject;
@@ -90,7 +90,7 @@ public class AnalyticsScene extends SolidScene implements View.OnClickListener {
// Start new scene and finish it self
MainActivity activity = getActivity2();
if (null != activity) {
startSceneForCheckStep(CHECK_STEP_ANALYTICS, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_ANALYTICS, getArguments());
}
finish();
}
@@ -36,13 +36,12 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import okhttp3.Cookie;
public class CookieSignInScene extends SolidScene implements EditText.OnEditorActionListener,
public class CookieSignInScene extends BaseScene implements EditText.OnEditorActionListener,
View.OnClickListener {
/*---------------
@@ -71,10 +70,10 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
View view = inflater.inflate(R.layout.scene_cookie_sign_in, container, false);
mIpbMemberIdLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_member_id_layout);
mIpbMemberId = mIpbMemberIdLayout.getEditText();
Assert.assertNotNull(mIpbMemberId);
AssertUtils.assertNotNull(mIpbMemberId);
mIpbPassHashLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_pass_hash_layout);
mIpbPassHash = mIpbPassHashLayout.getEditText();
Assert.assertNotNull(mIpbPassHash);
AssertUtils.assertNotNull(mIpbPassHash);
mOk = ViewUtils.$$(view, R.id.ok);
mIpbPassHash.setOnEditorActionListener(this);
@@ -83,7 +82,7 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
// Try to get old version cookie info
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
SharedPreferences sharedPreferences = context.getSharedPreferences("eh_info", 0);
String ipbMemberId = sharedPreferences.getString("ipb_member_id", null);
String ipbPassHash = sharedPreferences.getString("ipb_pass_hash", null);
@@ -30,7 +30,7 @@ import com.hippo.ripple.Ripple;
import com.hippo.util.AppHelper;
import com.hippo.yorozuya.ViewUtils;
public class CrashScene extends SolidScene implements View.OnClickListener {
public class CrashScene extends BaseScene implements View.OnClickListener {
/*---------------
Whole life cycle
@@ -88,7 +88,7 @@ public class CrashScene extends SolidScene implements View.OnClickListener {
// Start new scene and finish it self
if (null != activity) {
startSceneForCheckStep(CHECK_STEP_CRASH, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_CRASH, getArguments());
}
finish();
}
@@ -53,10 +53,9 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public class DownloadLabelsScene extends ToolbarScene {
@@ -101,7 +100,7 @@ public class DownloadLabelsScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_label);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -341,7 +340,7 @@ public class DownloadLabelsScene extends ToolbarScene {
public LabelAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -390,11 +389,6 @@ public class DownloadLabelsScene extends ToolbarScene {
}
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
@Override
public int onGetSwipeReactionType(LabelHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
@@ -56,8 +56,6 @@ import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener;
import com.github.amlcurran.showcaseview.targets.PointTarget;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.hippo.app.CheckBoxDialogBuilder;
import com.hippo.conaco.DataContainer;
import com.hippo.conaco.ProgressNotifier;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
@@ -77,10 +75,8 @@ import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.widget.SimpleRatingView;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.util.ApiHelper;
import com.hippo.util.DrawableManager;
@@ -88,18 +84,13 @@ import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.LongList;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.LongList;
import junit.framework.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@@ -194,7 +185,7 @@ public class DownloadsScene extends ToolbarScene
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mDownloadManager = EhApplication.getDownloadManager(context);
mDownloadManager.addDownloadInfoListener(this);
@@ -287,7 +278,7 @@ public class DownloadsScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
Assert.assertNotNull(content);
AssertUtils.assertNotNull(content);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_download);
@@ -298,7 +289,7 @@ public class DownloadsScene extends ToolbarScene
mAdapter.setHasStableIds(true);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
@@ -509,7 +500,7 @@ public class DownloadsScene extends ToolbarScene
View view = inflater.inflate(R.layout.drawer_list, container, false);
final Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(R.string.download_labels);
@@ -1124,7 +1115,7 @@ public class DownloadsScene extends ToolbarScene
public DownloadAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -1146,8 +1137,7 @@ public class DownloadsScene extends ToolbarScene
return;
}
DownloadInfo info = mList.get(position);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb,
new ThumbDataContainer(info), true);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb);
holder.title.setText(EhUtils.getSuitableTitle(info));
holder.uploader.setText(info.uploader);
holder.rating.setRating(info.rating);
@@ -1208,70 +1198,4 @@ public class DownloadsScene extends ToolbarScene
}
}
}
private class ThumbDataContainer implements DataContainer {
private final DownloadInfo mInfo;
@Nullable
private UniFile mFile;
public ThumbDataContainer(@NonNull DownloadInfo info) {
mInfo = info;
}
private void ensureFile() {
if (mFile == null) {
UniFile dir = SpiderDen.getGalleryDownloadDir(mInfo);
if (dir != null && dir.isDirectory()) {
mFile = dir.createFile(".thumb");
}
}
}
@Override
public boolean isEnabled() {
ensureFile();
return mFile != null;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
@Override
public boolean save(InputStream is, long length, String mediaType, ProgressNotifier notify) {
ensureFile();
if (mFile == null) {
return false;
}
OutputStream os = null;
try {
os = mFile.openOutputStream();
IOUtils.copy(is, os);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
IOUtils.closeQuietly(os);
}
}
@Override
public InputStreamPipe get() {
ensureFile();
if (mFile != null) {
return new UniFileInputStreamPipe(mFile);
} else {
return null;
}
}
@Override
public void remove() {
if (mFile != null) {
mFile.delete();
}
}
}
}
@@ -80,14 +80,13 @@ import com.hippo.util.DrawableManager;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -178,7 +177,7 @@ public class FavoritesScene extends BaseScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
mFavCatArray = Settings.getFavCat();
@@ -243,7 +242,7 @@ public class FavoritesScene extends BaseScene implements
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
@@ -500,7 +499,7 @@ public class FavoritesScene extends BaseScene implements
ListView listView = (ListView) view.findViewById(R.id.list_view);
final Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
toolbar.setTitle(R.string.collections);
toolbar.inflateMenu(R.menu.drawer_favorites);
@@ -95,7 +95,7 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
switch (type) {
default:
case GalleryAdapter.TYPE_LIST: {
int columnWidth = mResources.getDimensionPixelOffset(Settings.getDetailSizeResId());
int columnWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_list_column_width);
mLayoutManager.setColumnSize(columnWidth);
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
if (null != mGirdDecoration) {
@@ -74,16 +74,14 @@ import com.hippo.util.TextUrl;
import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LinkifyTextView;
import com.hippo.widget.ObservedTextView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.IntList;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.List;
@@ -191,7 +189,7 @@ public final class GalleryCommentsScene extends ToolbarScene
mFab = (FloatingActionButton) ViewUtils.$$(view, R.id.fab);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
@@ -455,10 +453,6 @@ public final class GalleryCommentsScene extends ToolbarScene
.setDuration(300L).setListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
if (null == mFab || null == mEditPanel) {
return;
}
mFab.setVisibility(View.INVISIBLE);
mEditPanel.setVisibility(View.VISIBLE);
int halfW = mEditPanel.getWidth() / 2;
@@ -502,10 +496,6 @@ public final class GalleryCommentsScene extends ToolbarScene
animator.addListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator a) {
if (null == mFab || null == mEditPanel) {
return;
}
mEditPanel.setVisibility(View.GONE);
mFab.setVisibility(View.VISIBLE);
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
@@ -618,7 +608,7 @@ public final class GalleryCommentsScene extends ToolbarScene
public CommentAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -626,7 +616,7 @@ public final class GalleryCommentsScene extends ToolbarScene
return new CommentHolder(mInflater.inflate(R.layout.item_gallery_comment, parent, false));
}
public CharSequence generateComment(Context context, ObservedTextView textView, GalleryComment comment) {
public CharSequence generateComment(Context context, TextView textView, GalleryComment comment) {
SpannableStringBuilder ssb = Html.fromHtml(comment.comment, new URLImageGetter(textView,
EhApplication.getConaco(context)), null);
@@ -81,7 +81,6 @@ import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.ehviewer.widget.GalleryRatingBar;
import com.hippo.reveal.ViewAnimationUtils;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
@@ -97,15 +96,14 @@ import com.hippo.util.ReadableTime;
import com.hippo.view.ViewTransition;
import com.hippo.widget.AutoWrapLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.ObservedTextView;
import com.hippo.widget.ProgressView;
import com.hippo.widget.ProgressiveRatingBar;
import com.hippo.widget.SimpleGridAutoSpanLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@@ -401,7 +399,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
long gid = getGid();
if (gid != -1) {
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mDownloadState = EhApplication.getDownloadManager(context).getDownloadState(gid);
} else {
mDownloadState = DownloadInfo.STATE_INVALID;
@@ -416,7 +414,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mViewTransition = new ViewTransition(mainView, progressView, mTip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -532,7 +530,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
super.onDestroyView();
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
EhApplication.getDownloadManager(context).removeDownloadInfoListener(this);
mTip = null;
@@ -588,7 +586,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private boolean prepareData() {
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
if (mGalleryDetail != null) {
return true;
@@ -771,7 +769,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.assertNotNull(resources);
mThumb.load(EhCacheKeyFactory.getThumbKey(gd.gid), gd.thumb);
mTitle.setText(EhUtils.getSuitableTitle(gd));
@@ -871,7 +869,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
user.setText(comment.user);
TextView time = (TextView) v.findViewById(R.id.time);
time.setText(ReadableTime.getTimeAgo(comment.time));
ObservedTextView c = (ObservedTextView) v.findViewById(R.id.comment);
TextView c = (TextView) v.findViewById(R.id.comment);
c.setMaxLines(5);
c.setText(Html.fromHtml(comment.comment,
new URLImageGetter(c, EhApplication.getConaco(context)), null));
@@ -914,7 +912,12 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
private static String getRatingText(float rating, Resources resources) {
int resId;
String undefine = "(´_ゝ`)";
if (-1.0f == rating) {
return undefine;
}
int resId = 0;
switch (Math.round(rating * 2)) {
case 0:
resId = R.string.rating0; break;
@@ -938,16 +941,18 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
resId = R.string.rating9; break;
case 10:
resId = R.string.rating10; break;
default:
resId = R.string.rating_none; break;
}
return resources.getString(resId);
if (resId == 0) {
return undefine;
} else {
return resources.getString(resId);
}
}
private String getAllRatingText(float rating, int ratingCount) {
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.assertNotNull(resources);
return resources.getString(R.string.rating_text, getRatingText(rating, resources), rating, ratingCount);
}
@@ -970,7 +975,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
PopupMenu popup = new PopupMenu(context, mOtherActions, Gravity.TOP);
mPopupMenu = popup;
popup.getMenuInflater().inflate(R.menu.scene_gallery_detail, popup.getMenu());
@@ -1707,17 +1712,17 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
}
private class RateDialogHelper implements GalleryRatingBar.OnUserRateListener,
private class RateDialogHelper implements ProgressiveRatingBar.OnUserRateListener,
DialogInterface.OnClickListener {
@Nullable
private GalleryRatingBar mRatingBar;
private ProgressiveRatingBar mRatingBar;
@Nullable
private TextView mRatingText;
public void setDialog(Dialog dialog, float rating) {
mRatingText = (TextView) ViewUtils.$$(dialog, R.id.rating_text);
mRatingBar = (GalleryRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingBar = (ProgressiveRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingText.setText(getRatingText(rating, getResources2()));
mRatingBar.setRating(rating);
mRatingBar.setOnUserRateListener(this);
@@ -37,11 +37,10 @@ import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
public final class GalleryInfoScene extends ToolbarScene implements EasyRecyclerView.OnItemClickListener {
@@ -85,7 +84,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
}
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.assertNotNull(resources);
mKeys.add(resources.getString(R.string.header_key));
mValues.add(resources.getString(R.string.header_value));
mKeys.add(resources.getString(R.string.key_gid));
@@ -156,7 +155,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
View view = inflater.inflate(R.layout.scene_gallery_info, container, false);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
InfoAdapter adapter = new InfoAdapter();
@@ -231,7 +230,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
public InfoAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -88,13 +88,12 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -257,7 +256,7 @@ public final class GalleryListScene extends BaseScene
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
@@ -386,7 +385,7 @@ public final class GalleryListScene extends BaseScene
View view = inflater.inflate(R.layout.scene_gallery_list, container, false);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
mHideActionFabSlop = ViewConfiguration.get(context).getScaledTouchSlop();
@@ -633,7 +632,7 @@ public final class GalleryListScene extends BaseScene
final ListView listView = (ListView) ViewUtils.$$(view, R.id.list_view);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
final List<QuickSearch> list = EhDB.getAllQuickSearch();
final ArrayAdapter<QuickSearch> adapter = new ArrayAdapter<>(context, R.layout.item_simple_list, list);
@@ -1193,14 +1192,6 @@ public final class GalleryListScene extends BaseScene
}
break;
}
if (newState == STATE_NORMAL || newState == STATE_SIMPLE_SEARCH) {
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
} else {
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
}
}
@Override
@@ -53,11 +53,10 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.Slider;
import com.hippo.widget.recyclerview.AutoGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Locale;
@@ -91,7 +90,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
onInit();
@@ -138,7 +137,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
mRecyclerView = contentLayout.getRecyclerView();
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
mAdapter = new GalleryPreviewAdapter();
@@ -262,7 +261,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
public GalleryPreviewAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -48,7 +48,6 @@ import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
@@ -64,11 +63,10 @@ import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import de.greenrobot.dao.query.LazyList;
public class HistoryScene extends ToolbarScene
@@ -104,7 +102,7 @@ public class HistoryScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_history);
@@ -124,7 +122,7 @@ public class HistoryScene extends ToolbarScene
mRecyclerView.setItemAnimator(animator);
AutoStaggeredGridLayoutManager layoutManager = new AutoStaggeredGridLayoutManager(
0, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
layoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
layoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
@@ -36,10 +36,9 @@ import com.hippo.scene.SceneFragment;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
/**
* Only show a progress with jobs in background
*/
@@ -170,7 +169,7 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
mTip = (TextView) ViewUtils.$$(view, R.id.tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -49,10 +49,9 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public final class QuickSearchScene extends ToolbarScene {
@@ -97,7 +96,7 @@ public final class QuickSearchScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_search);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -198,7 +197,7 @@ public final class QuickSearchScene extends ToolbarScene {
public QuickSearchAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -249,11 +248,6 @@ public final class QuickSearchScene extends ToolbarScene {
notifyItemMoved(fromPosition, toPosition);
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
@Override
public int onGetSwipeReactionType(QuickSearchHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
@@ -31,14 +31,13 @@ import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.hardware.ShakeDetector;
import com.hippo.widget.lockpattern.LockPatternUtils;
import com.hippo.widget.lockpattern.LockPatternView;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public class SecurityScene extends SolidScene implements
public class SecurityScene extends BaseScene implements
LockPatternView.OnPatternListener, ShakeDetector.OnShakeListener {
private static final int MAX_RETRY_TIMES = 5;
@@ -64,7 +63,7 @@ public class SecurityScene extends SolidScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if (null != mSensorManager) {
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
@@ -153,7 +152,7 @@ public class SecurityScene extends SolidScene implements
String targetPatter = Settings.getSecurity();
if (ObjectUtils.equal(enteredPatter, targetPatter)) {
startSceneForCheckStep(CHECK_STEP_SECURITY, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
finish();
} else {
mPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
@@ -172,7 +171,7 @@ public class SecurityScene extends SolidScene implements
return;
}
Settings.putSecurity("");
startSceneForCheckStep(CHECK_STEP_SECURITY, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
finish();
}
}
@@ -30,7 +30,7 @@ import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.yorozuya.ViewUtils;
public class SelectSiteScene extends SolidScene implements View.OnClickListener {
public class SelectSiteScene extends BaseScene implements View.OnClickListener {
private RadioGroup mRadioGroup;
private View mOk;
@@ -75,13 +75,13 @@ public class SelectSiteScene extends SolidScene implements View.OnClickListener
case R.id.site_e:
Settings.putSelectSite(false);
Settings.putGallerySite(EhUrl.SITE_G);
startSceneForCheckStep(CHECK_STEP_SELECT_SITE, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SELECT_SITE, getArguments());
finish();
break;
case R.id.site_ex:
Settings.putSelectSite(false);
Settings.putGallerySite(EhUrl.SITE_EX);
startSceneForCheckStep(CHECK_STEP_SELECT_SITE, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SELECT_SITE, getArguments());
finish();
break;
default:
@@ -42,11 +42,10 @@ import com.hippo.ehviewer.client.parser.ProfileParser;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
public final class SignInScene extends SolidScene implements EditText.OnEditorActionListener,
public final class SignInScene extends BaseScene implements EditText.OnEditorActionListener,
View.OnClickListener {
private static final String KEY_REQUEST_ID = "request_id";
@@ -120,10 +119,10 @@ public final class SignInScene extends SolidScene implements EditText.OnEditorAc
mProgress = ViewUtils.$$(view, R.id.progress);
mUsernameLayout = (TextInputLayout) ViewUtils.$$(loginForm, R.id.username_layout);
mUsername = mUsernameLayout.getEditText();
Assert.assertNotNull(mUsername);
AssertUtils.assertNotNull(mUsername);
mPasswordLayout = (TextInputLayout) ViewUtils.$$(loginForm, R.id.password_layout);
mPassword = mPasswordLayout.getEditText();
Assert.assertNotNull(mPassword);
AssertUtils.assertNotNull(mPassword);
mRegister = ViewUtils.$$(loginForm, R.id.register);
mSignIn = ViewUtils.$$(loginForm, R.id.sign_in);
mSignInViaWebView = (TextView) ViewUtils.$$(loginForm, R.id.sign_in_via_webview);
@@ -143,7 +142,7 @@ public final class SignInScene extends SolidScene implements EditText.OnEditorAc
mSkipSigningIn.setOnClickListener(this);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
EhApplication application = (EhApplication) context.getApplicationContext();
if (application.containGlobalStuff(mRequestId)) {
mSigningIn = true;
@@ -314,7 +313,7 @@ public final class SignInScene extends SolidScene implements EditText.OnEditorAc
Settings.putNeedSignIn(false);
MainActivity activity = getActivity2();
if (null != activity) {
startSceneForCheckStep(CHECK_STEP_SIGN_IN, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SIGN_IN, getArguments());
}
finish();
}
@@ -1,98 +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.ui.scene;
import android.os.Bundle;
import android.util.Log;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.scene.Announcer;
/**
* Scene for safety, can't be covered
*/
public class SolidScene extends BaseScene {
private static final String TAG = SolidScene.class.getSimpleName();
public static final int CHECK_STEP_SECURITY = 0;
public static final int CHECK_STEP_WARNING = 1;
public static final int CHECK_STEP_ANALYTICS = 2;
public static final int CHECK_STEP_CRASH = 3;
public static final int CHECK_STEP_SIGN_IN = 4;
public static final int CHECK_STEP_SELECT_SITE = 5;
public static final String KEY_TARGET_SCENE = "target_scene";
public static final String KEY_TARGET_ARGS = "target_args";
public void startSceneForCheckStep(int checkStep, Bundle args) {
switch (checkStep) {
case CHECK_STEP_SECURITY:
if (Settings.getShowWarning()) {
startScene(new Announcer(WarningScene.class).setArgs(args));
break;
}
case CHECK_STEP_WARNING:
if (Settings.getAskAnalytics()) {
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
break;
}
case CHECK_STEP_ANALYTICS:
if (Crash.hasCrashFile()) {
startScene(new Announcer(CrashScene.class).setArgs(args));
break;
}
case CHECK_STEP_CRASH:
if (EhUtils.needSignedIn(getContext2())) {
startScene(new Announcer(SignInScene.class).setArgs(args));
break;
}
case CHECK_STEP_SIGN_IN:
if (Settings.getSelectSite()) {
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
break;
}
case CHECK_STEP_SELECT_SITE:
String targetScene = null;
Bundle targetArgs = null;
if (null != args) {
targetScene = args.getString(KEY_TARGET_SCENE);
targetArgs = args.getBundle(KEY_TARGET_ARGS);
}
Class<?> clazz = null;
if (targetScene != null) {
try {
clazz = Class.forName(targetScene);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Can't find class with name: " + targetScene);
}
}
if (clazz != null) {
startScene(new Announcer(clazz).setArgs(targetArgs));
} else {
Bundle newArgs = new Bundle();
newArgs.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(new Announcer(GalleryListScene.class).setArgs(newArgs));
}
break;
}
}
}
@@ -28,7 +28,7 @@ import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
import com.hippo.yorozuya.ViewUtils;
public final class WarningScene extends SolidScene implements View.OnClickListener {
public final class WarningScene extends BaseScene implements View.OnClickListener {
@Nullable
private View mReject;
@@ -75,7 +75,7 @@ public final class WarningScene extends SolidScene implements View.OnClickListen
// Start new scene and finish it self
MainActivity activity = getActivity2();
if (null != activity) {
startSceneForCheckStep(CHECK_STEP_WARNING, getArguments());
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_WARNING, getArguments());
}
finish();
}
@@ -33,8 +33,7 @@ import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import junit.framework.Assert;
import com.hippo.yorozuya.AssertUtils;
import java.util.ArrayList;
import java.util.Collections;
@@ -43,7 +42,7 @@ import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class WebViewSignInScene extends SolidScene {
public class WebViewSignInScene extends BaseScene {
/*---------------
View life cycle
@@ -63,7 +62,7 @@ public class WebViewSignInScene extends SolidScene {
public View onCreateView2(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
EhUtils.signOut(context);
@@ -43,6 +43,7 @@ import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.dict.DictManager;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AnimationUtils;
@@ -85,6 +86,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private ViewTransition mViewTransition;
private SearchDatabase mSearchDatabase;
private DictManager mDictManager;
private List<String> mSuggestionList;
private ArrayAdapter mSuggestionAdapter;
@@ -114,6 +116,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
setBackgroundResource(R.drawable.card_white_no_padding_2dp);
mSearchDatabase = SearchDatabase.getInstance(getContext());
mDictManager = new DictManager(getContext());
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.widget_search_bar, this);
@@ -170,8 +173,11 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private void updateSuggestions() {
String prefix = mEditText.getText().toString();
String[] dictSuggestions = mDictManager.getSuggestions(prefix);
String[] suggestions = mSearchDatabase.getSuggestions(prefix);
mSuggestionList.clear();
Collections.addAll(mSuggestionList, dictSuggestions);
Collections.addAll(mSuggestionList, suggestions);
if (mSuggestionList.size() == 0) {
removeListHeader();
@@ -479,10 +485,15 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
public interface Helper {
void onClickTitle();
void onClickLeftIcon();
void onClickRightIcon();
void onSearchEditTextClick();
void onApplySearch(String query);
void onSearchEditTextBackPressed();
}
@@ -22,14 +22,14 @@ import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.Say;
import java.util.LinkedList;
import java.util.List;
public final class SearchDatabase {
public class SearchDatabase {
private static final String TAG = SearchDatabase.class.getSimpleName();
@@ -41,7 +41,7 @@ public final class SearchDatabase {
private static final int MAX_HISTORY = 100;
private final SQLiteDatabase mDatabase;
private SQLiteDatabase mDatabase;
private static SearchDatabase sInstance;
@@ -60,7 +60,6 @@ public final class SearchDatabase {
public String[] getSuggestions(String prefix) {
List<String> queryList = new LinkedList<>();
// TODO add limit
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ").append(TABLE_SUGGESTIONS);
if (!TextUtils.isEmpty(prefix)) {
@@ -127,10 +126,11 @@ public final class SearchDatabase {
}
mDatabase.delete(TABLE_SUGGESTIONS, selection, null);
} catch (RuntimeException e) {
Log.e(TAG, "truncateHistory", e);
Say.e(TAG, "truncateHistory", e);
}
}
/**
* 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
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.yorozuya.MathUtils;
public class AlphaAnimation extends CanvasAnimation {
private final float mStartAlpha;
private final float mEndAlpha;
private float mCurrentAlpha;
public AlphaAnimation(float from, float to) {
mStartAlpha = from;
mEndAlpha = to;
mCurrentAlpha = from;
}
@Override
public void apply(GLCanvas canvas) {
canvas.multiplyAlpha(mCurrentAlpha);
}
@Override
public int getCanvasSaveFlags() {
return GLCanvas.SAVE_FLAG_ALPHA;
}
@Override
protected void onCalculate(float progress) {
mCurrentAlpha = MathUtils.clamp(mStartAlpha +
(mEndAlpha - mStartAlpha) * progress, 0f, 1f);
}
}
@@ -0,0 +1,167 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import android.os.SystemClock;
import android.view.animation.Interpolator;
import com.hippo.yorozuya.MathUtils;
// Animation calculates a value according to the current input time.
//
// 1. First we need to use setDuration(int) to set the duration of the
// animation. The duration is in milliseconds.
// 2. Then we should call start(). The actual start time is the first value
// passed to calculate(long).
// 3. Each time we want to get an animation value, we call
// calculate(long currentTimeMillis) to ask the Animation to calculate it.
// The parameter passed to calculate(long) should be nonnegative.
// 4. Use get() to get that value.
//
// In step 3, onCalculate(float progress) is called so subclasses can calculate
// the value according to progress (progress is a value in [0,1]).
//
// Before onCalculate(float) is called, There is an optional interpolator which
// can change the progress value. The interpolator can be set by
// setInterpolator(Interpolator). If the interpolator is used, the value passed
// to onCalculate may be (for example, the overshoot effect).
//
// The isActive() method returns true after the animation start() is called and
// before calculate is passed a value which reaches the duration of the
// animation.
//
// The start() method can be called again to restart the Animation.
//
abstract public class Animation {
private static final long ANIMATION_START = -1;
private static final long NO_ANIMATION = -2;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation restarts from the beginning.
*/
public static final int RESTART = 1;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation reverses direction on every iteration.
*/
public static final int REVERSE = 2;
/**
* This value used used with the {@link #setRepeatCount(int)} property to repeat
* the animation indefinitely.
*/
public static final int INFINITE = -1;
private long mStartTime = NO_ANIMATION;
private long mDuration;
private Interpolator mInterpolator;
private int mRepeatCount;
private int mRepeatMode;
private int mRunnedCount;
private long mLastFrameTime;
public void setInterpolator(Interpolator interpolator) {
mInterpolator = interpolator;
}
public void setDuration(long duration) {
mDuration = duration;
}
public void setRepeatCount(int repeatCount) {
mRepeatCount = repeatCount;
}
public void setRepeatMode(int repeatMode) {
mRepeatMode = repeatMode;
}
public boolean isRunning() {
return mStartTime > 0 || mStartTime == ANIMATION_START;
}
public long getLastFrameTime() {
return mLastFrameTime;
}
public void start() {
if (mStartTime == NO_ANIMATION) {
mStartTime = ANIMATION_START;
mRunnedCount = 0;
mLastFrameTime = 0;
}
}
public void startAt(long time) {
start();
setStartTime(time);
}
public void startNow() {
start();
setStartTime(SystemClock.uptimeMillis());
}
public void setStartTime(long time) {
mStartTime = time;
}
public void cancel() {
mStartTime = NO_ANIMATION;
}
public void reset() {
mStartTime = ANIMATION_START;
mRunnedCount = 0;
mLastFrameTime = 0;
}
// TODO mRepeatMode
public boolean calculate(long currentTimeMillis) {
if (mStartTime == NO_ANIMATION) {
return false;
}
if (mStartTime == ANIMATION_START) {
mStartTime = currentTimeMillis;
}
mLastFrameTime = currentTimeMillis;
long elapse = currentTimeMillis - mStartTime;
float x = MathUtils.clamp(mDuration == 0.0f ? 1.0f : (float) elapse / mDuration, 0.0f, 1.0f); // Avoid NaN
Interpolator i = mInterpolator;
onCalculate(i != null ? i.getInterpolation(x) : x);
// It is ok to call cancel() in onCalculate()
if (mStartTime != NO_ANIMATION && elapse >= mDuration) {
mRunnedCount++;
if (mRunnedCount >= mRepeatCount && mRepeatCount != INFINITE) {
onFinish();
mStartTime = NO_ANIMATION;
} else {
mStartTime += elapse;
}
}
return mStartTime != NO_ANIMATION;
}
abstract protected void onCalculate(float progress);
protected void onFinish() {
}
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.gl.glrenderer.GLCanvas;
public abstract class CanvasAnimation extends Animation {
public abstract int getCanvasSaveFlags();
public abstract void apply(GLCanvas canvas);
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.yorozuya.MathUtils;
public class FloatAnimation extends Animation {
private float mFrom;
private float mTo;
private float mCurrent;
public void setRange(float from, float to) {
mFrom = from;
mTo = to;
}
@Override
protected void onCalculate(float progress) {
mCurrent = MathUtils.lerp(mFrom, mTo, progress);
}
public float get() {
return mCurrent;
}
}
@@ -0,0 +1,27 @@
/*
* 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.gl.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public @interface RenderThread {
}
@@ -0,0 +1,222 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.util.Log;
import com.hippo.yorozuya.MathUtils;
import java.util.WeakHashMap;
// BasicTexture is a Texture corresponds to a real GL texture.
// The state of a BasicTexture indicates whether its data is loaded to GL memory.
// If a BasicTexture is loaded into GL memory, it has a GL texture id.
public abstract class BasicTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "BasicTexture";
protected static final int UNSPECIFIED = -1;
protected static final int STATE_UNLOADED = 0;
protected static final int STATE_LOADED = 1;
protected static final int STATE_ERROR = -1;
// Log a warning if a texture is larger along a dimension
private static final int MAX_TEXTURE_SIZE = 4096;
protected int mId = -1;
protected int mState;
protected int mWidth = UNSPECIFIED;
protected int mHeight = UNSPECIFIED;
protected int mTextureWidth;
protected int mTextureHeight;
private boolean mHasBorder;
protected GLCanvas mCanvasRef = null;
private final static WeakHashMap<BasicTexture, Object> sAllTextures
= new WeakHashMap<>();
private static ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
protected BasicTexture(GLCanvas canvas, int id, int state) {
setAssociatedCanvas(canvas);
mId = id;
mState = state;
synchronized (sAllTextures) {
sAllTextures.put(this, null);
}
}
protected BasicTexture() {
this(null, 0, STATE_UNLOADED);
}
protected void setAssociatedCanvas(GLCanvas canvas) {
mCanvasRef = canvas;
}
/**
* Sets the content size of this texture. In OpenGL, the actual texture
* size must be of power of 2, the size of the content may be smaller.
*/
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
mTextureWidth = width > 0 ? MathUtils.nextPowerOf2(width) : 0;
mTextureHeight = height > 0 ? MathUtils.nextPowerOf2(height) : 0;
if (mTextureWidth > MAX_TEXTURE_SIZE || mTextureHeight > MAX_TEXTURE_SIZE) {
Log.w(TAG, String.format("texture is too large: %d x %d",
mTextureWidth, mTextureHeight), new Exception());
}
}
public boolean isFlippedVertically() {
return false;
}
public int getId() {
return mId;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
// Returns the width rounded to the next power of 2.
public int getTextureWidth() {
return mTextureWidth;
}
// Returns the height rounded to the next power of 2.
public int getTextureHeight() {
return mTextureHeight;
}
// Returns true if the texture has one pixel transparent border around the
// actual content. This is used to avoid jigged edges.
//
// The jigged edges appear because we use GL_CLAMP_TO_EDGE for texture wrap
// mode (GL_CLAMP is not available in OpenGL ES), so a pixel partially
// covered by the texture will use the color of the edge texel. If we add
// the transparent border, the color of the edge texel will be mixed with
// appropriate amount of transparent.
//
// Currently our background is black, so we can draw the thumbnails without
// enabling blending.
public boolean hasBorder() {
return mHasBorder;
}
protected void setBorder(boolean hasBorder) {
mHasBorder = hasBorder;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
canvas.drawTexture(this, x, y, getWidth(), getHeight());
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.drawTexture(this, x, y, w, h);
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
canvas.drawTexture(this, source, target);
}
// onBind is called before GLCanvas binds this texture.
// It should make sure the data is uploaded to GL memory.
abstract protected boolean onBind(GLCanvas canvas);
// Returns the GL texture target for this texture (e.g. GL_TEXTURE_2D).
abstract protected int getTarget();
public boolean isLoaded() {
return mState == STATE_LOADED;
}
// recycle() is called when the texture will never be used again,
// so it can free all resources.
public void recycle() {
freeResource();
}
// yield() is called when the texture will not be used temporarily,
// so it can free some resources.
// The default implementation unloads the texture from GL memory, so
// the subclass should make sure it can reload the texture to GL memory
// later, or it will have to override this method.
public void yield() {
freeResource();
}
private void freeResource() {
GLCanvas canvas = mCanvasRef;
if (canvas != null && mId != -1) {
canvas.unloadTexture(this);
mId = -1; // Don't free it again.
}
mState = STATE_UNLOADED;
setAssociatedCanvas(null);
}
@Override
protected void finalize() throws Throwable {
try {
sInFinalizer.set(BasicTexture.class);
recycle();
sInFinalizer.set(null);
} finally {
super.finalize();
}
}
// This is for deciding if we can call Bitmap's recycle().
// We cannot call Bitmap's recycle() in finalizer because at that point
// the finalizer of Bitmap may already be called so recycle() will crash.
public static boolean inFinalizer() {
return sInFinalizer.get() != null;
}
public static void yieldAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.yield();
}
}
}
public static void invalidateAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.mState = STATE_UNLOADED;
t.setAssociatedCanvas(null);
}
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import com.hippo.yorozuya.AssertUtils;
// BitmapTexture is a texture whose content is specified by a fixed Bitmap.
//
// The texture does not own the Bitmap. The user should make sure the Bitmap
// is valid during the texture's lifetime. When the texture is recycled, it
// does not free the Bitmap.
public class BitmapTexture extends UploadedTexture {
protected Bitmap mContentBitmap;
public BitmapTexture(Bitmap bitmap) {
this(bitmap, false);
}
public BitmapTexture(Bitmap bitmap, boolean hasBorder) {
super(hasBorder);
AssertUtils.assertTrue(bitmap != null && !bitmap.isRecycled());
mContentBitmap = bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
// Do nothing.
}
@Override
protected Bitmap onGetBitmap() {
return mContentBitmap;
}
public Bitmap getBitmap() {
return mContentBitmap;
}
}
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
// CanvasTexture is a texture whose content is the drawing on a Canvas.
// The subclasses should override onDraw() to draw on the bitmap.
// By default CanvasTexture is not opaque.
abstract class CanvasTexture extends UploadedTexture {
private final Config mConfig;
public CanvasTexture(int width, int height) {
mConfig = Config.ARGB_8888;
setSize(width, height);
setOpaque(false);
}
@Override
protected Bitmap onGetBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, mConfig);
Canvas canvas = new Canvas(bitmap);
onDraw(canvas, bitmap);
return bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
if (!inFinalizer()) {
bitmap.recycle();
}
}
abstract protected void onDraw(Canvas canvas, Bitmap backing);
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import com.hippo.yorozuya.ColorUtils;
// ColorTexture is a texture which fills the rectangle with the specified color.
public class ColorTexture implements Texture {
private final int mColor;
private int mWidth = 0;
private int mHeight = 0;
public ColorTexture(int color) {
mColor = color;
}
private boolean isValidSize() {
return mWidth > 0 && mHeight > 0;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
if (isValidSize()) {
draw(canvas, x, y, mWidth, mHeight);
}
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.fillRect(x, y, w, h, mColor);
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
canvas.fillRect(target.left, target.top, target.width(), target.height(), mColor);
}
@Override
public boolean isOpaque() {
return ColorUtils.isOpaque(mColor);
}
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
// ExtTexture is a texture whose content comes from a external texture.
// Before drawing, setSize() should be called.
public class ExtTexture extends BasicTexture {
private int mTarget;
public ExtTexture(GLCanvas canvas, int target) {
GLId glId = canvas.getGLId();
mId = glId.generateTexture();
mTarget = target;
}
private void uploadToCanvas(GLCanvas canvas) {
canvas.setTextureParameters(this);
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
}
@Override
protected boolean onBind(GLCanvas canvas) {
if (!isLoaded()) {
uploadToCanvas(canvas);
}
return true;
}
@Override
public int getTarget() {
return mTarget;
}
@Override
public boolean isOpaque() {
return true;
}
@Override
public void yield() {
// we cannot free the texture because we have no backup.
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
// FadeInTexture is a texture which begins with a color, then gradually animates
// into a given texture.
public class FadeInTexture extends FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeInTexture";
private final int mColor;
private final TiledTexture mTexture;
public FadeInTexture(int color, TiledTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mColor = color;
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
mTexture.drawMixed(canvas, mColor, getRatio(), x, y, w, h);
} else {
mTexture.draw(canvas, x, y, w, h);
}
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
if (isAnimating()) {
mTexture.drawMixed(canvas, mColor, getRatio(), source, target);
} else {
mTexture.draw(canvas, source, target);
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
// FadeOutTexture is a texture which begins with a given texture, then gradually animates
// into fading out totally.
public class FadeOutTexture extends FadeTexture {
@SuppressWarnings("unused")
private static final String TAG = "FadeOutTexture";
private final BasicTexture mTexture;
public FadeOutTexture(BasicTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
canvas.save(GLCanvas.SAVE_FLAG_ALPHA);
canvas.setAlpha(getRatio());
mTexture.draw(canvas, x, y, w, h);
canvas.restore();
}
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
if (isAnimating()) {
canvas.save(GLCanvas.SAVE_FLAG_ALPHA);
canvas.setAlpha(getRatio());
mTexture.draw(canvas, source, target);
canvas.restore();
}
}
}
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import com.hippo.gl.view.AnimationTime;
import com.hippo.yorozuya.MathUtils;
// FadeTexture is a texture which fades the given texture along the time.
public abstract class FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeTexture";
// The duration of the fading animation in milliseconds
public static final int DURATION = 180;
private final long mStartTime;
private final int mWidth;
private final int mHeight;
private final boolean mIsOpaque;
private boolean mIsAnimating;
public FadeTexture(int width, int height, boolean opaque) {
mWidth = width;
mHeight = height;
mIsOpaque = opaque;
mStartTime = now();
mIsAnimating = true;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public boolean isOpaque() {
return mIsOpaque;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
public boolean isAnimating() {
if (mIsAnimating) {
if (now() - mStartTime >= DURATION) {
mIsAnimating = false;
}
}
return mIsAnimating;
}
protected float getRatio() {
float r = (float)(now() - mStartTime) / DURATION;
return MathUtils.clamp(1.0f - r, 0.0f, 1.0f);
}
private long now() {
return AnimationTime.get();
}
}
@@ -0,0 +1,223 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
//
// GLCanvas gives a convenient interface to draw using OpenGL.
//
// When a rectangle is specified in this interface, it means the region
// [x, x+width) * [y, y+height)
//
public interface GLCanvas {
GLId getGLId();
// Tells GLCanvas the size of the underlying GL surface. This should be
// called before first drawing and when the size of GL surface is changed.
// This is called by GLRoot and should not be called by the clients
// who only want to draw on the GLCanvas. Both width and height must be
// nonnegative.
void setSize(int width, int height);
// Clear the drawing buffers. This should only be used by GLRoot.
void clearBuffer();
void clearBuffer(float[] argb);
// Sets and gets the current alpha, alpha must be in [0, 1].
void setAlpha(float alpha);
float getAlpha();
// (current alpha) = (current alpha) * alpha
void multiplyAlpha(float alpha);
// Change the current transform matrix.
void translate(float x, float y, float z);
void translate(float x, float y);
void scale(float sx, float sy, float sz);
void rotate(float angle, float x, float y, float z);
void multiplyMatrix(float[] mMatrix, int offset);
// Pushes the configuration state (matrix, and alpha) onto
// a private stack.
void save();
// Same as save(), but only save those specified in saveFlags.
void save(int saveFlags);
int SAVE_FLAG_ALL = 0xFFFFFFFF;
int SAVE_FLAG_ALPHA = 0x01;
int SAVE_FLAG_MATRIX = 0x02;
// Pops from the top of the stack as current configuration state (matrix,
// alpha, and clip). This call balances a previous call to save(), and is
// used to remove all modifications to the configuration state since the
// last save call.
void restore();
// Draws a line using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
void drawLine(float x1, float y1, float x2, float y2, GLPaint paint);
// Draws a rectangle using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
void drawRect(float x1, float y1, float x2, float y2, GLPaint paint);
// Draws a oval using the specified paint for (cx, cy, radiusX, radiusY)
// (Both end points are included).
void drawOval(float cx, float cy, float radiusX, float radiusY,
GLPaint paint);
// Draw a arc inside a rect
void drawArc(float cx, float cy, float radiusX, float radiusY,
float sweepAngle, GLPaint paint);
// Fills the specified rectangle with the specified color.
void fillRect(float x, float y, float width, float height, int color);
// Fills the specified oval with the specified color.
void fillOval(float cx, float cy, float radiusX, float radiusY, int color);
// Fills the specified sector with the specified color.
void fillSector(float cx, float cy, float radiusX, float radiusY, float sweepAngle, int color);
// Draws a texture to the specified rectangle.
void drawTexture(BasicTexture texture, int x, int y, int width, int height);
void drawMesh(BasicTexture tex, int x, int y, int xyBuffer, int uvBuffer, int indexBuffer, int indexCount);
// Draws the source rectangle part of the texture to the target rectangle.
void drawTexture(BasicTexture texture, RectF source, RectF target);
// Draw a texture with a specified texture transform.
void drawTexture(BasicTexture texture, float[] mTextureTransform, int x, int y, int w, int h);
// Draw two textures to the specified rectangle. The actual texture used is
// from * (1 - ratio) + to * ratio
// The two textures must have the same size.
void drawMixed(BasicTexture from, int toColor, float ratio, int x, int y, int w, int h);
// Draw a region of a texture and a specified color to the specified
// rectangle. The actual color used is from * (1 - ratio) + to * ratio.
// The region of the texture is defined by parameter "src". The target
// rectangle is specified by parameter "target".
void drawMixed(BasicTexture from, int toColor, float ratio, RectF src, RectF target);
// Unloads the specified texture from the canvas. The resource allocated
// to draw the texture will be released. The specified texture will return
// to the unloaded state. This function should be called only from
// BasicTexture or its descendant
boolean unloadTexture(BasicTexture texture);
// Delete the specified buffer object, similar to unloadTexture.
void deleteBuffer(int bufferId);
// Delete the textures and buffers in GL side. This function should only be
// called in the GL thread.
void deleteRecycledResources();
// Dump statistics information and clear the counters. For debug only.
void dumpStatisticsAndClear();
void beginRenderTarget(RawTexture texture);
void endRenderTarget();
/**
* Sets texture parameters to use GL_CLAMP_TO_EDGE for both
* GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T. Sets texture parameters to be
* GL_LINEAR for GL_TEXTURE_MIN_FILTER and GL_TEXTURE_MAG_FILTER.
* bindTexture() must be called prior to this.
*
* @param texture The texture to set parameters on.
*/
void setTextureParameters(BasicTexture texture);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
void initializeTextureSize(BasicTexture texture, int format, int type);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param bitmap The bitmap to initialize the bitmap with.
*/
void initializeTexture(BasicTexture texture, Bitmap bitmap);
/**
* Calls glTexSubImage2D to upload a bitmap to the texture.
*
* @param texture The target texture to write to.
* @param xOffset Specifies a texel offset in the x direction within the
* texture array.
* @param yOffset Specifies a texel offset in the y direction within the
* texture array.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
void texSubImage2D(BasicTexture texture, int xOffset, int yOffset, Bitmap bitmap, int format, int type);
/**
* Generates buffers and uploads the buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
int uploadBuffer(java.nio.FloatBuffer buffer);
/**
* Generates buffers and uploads the element array buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
int uploadBuffer(java.nio.ByteBuffer buffer);
/**
* After LightCycle makes GL calls, this method is called to restore the GL
* configuration to the one expected by GLCanvas.
*/
void recoverFromLightCycle();
/**
* Gets the bounds given by x, y, width, and height as well as the internal
* matrix state. There is no special handling for non-90-degree rotations.
* It only considers the lower-left and upper-right corners as the bounds.
*
* @param bounds The output bounds to write to.
* @param x The left side of the input rectangle.
* @param y The bottom of the input rectangle.
* @param width The width of the input rectangle.
* @param height The height of the input rectangle.
*/
void getBounds(Rect bounds, int x, int y, int width, int height);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,42 @@
package com.hippo.gl.glrenderer;
import android.opengl.GLES20;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
public class GLES20IdImpl implements GLId {
private final int[] mTempIntArray = new int[1];
@Override
public int generateTexture() {
GLES20.glGenTextures(1, mTempIntArray, 0);
GLES20Canvas.checkError();
return mTempIntArray[0];
}
@Override
public void glGenBuffers(int n, int[] buffers, int offset) {
GLES20.glGenBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset) {
GLES20.glDeleteTextures(n, textures, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset) {
GLES20.glDeleteBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset) {
GLES20.glDeleteFramebuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
}
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
// This mimics corresponding GL functions.
public interface GLId {
int generateTexture();
void glGenBuffers(int n, int[] buffers, int offset);
void glDeleteTextures(GL11 gl, int n, int[] textures, int offset);
void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset);
void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset);
}
@@ -0,0 +1,50 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import junit.framework.Assert;
public class GLPaint {
private float mLineWidth = 1f;
private int mColor = 0;
private int mBackgroundColor = 0;
public void setColor(int color) {
mColor = color;
}
public int getColor() {
return mColor;
}
public void setBackgroundColor(int backgroundColor) {
mBackgroundColor = backgroundColor;
}
public int getBackgroundColor() {
return mBackgroundColor;
}
public void setLineWidth(float width) {
Assert.assertTrue(width >= 0);
mLineWidth = width;
}
public float getLineWidth() {
return mLineWidth;
}
}
@@ -0,0 +1,686 @@
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.yorozuya.PVLock;
import com.hippo.yorozuya.PriorityThreadFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class ImageTexture implements Texture, Animatable {
@IntDef({TILE_SMALL, TILE_LARGE})
@Retention(RetentionPolicy.SOURCE)
private @interface TileType {}
private static final int TILE_SMALL = 0;
private static final int TILE_LARGE = 1;
private static final int SMALL_CONTENT_SIZE = 254;
private static final int SMALL_BORDER_SIZE = 1;
private static final int SMALL_TILE_SIZE = SMALL_CONTENT_SIZE + 2 * SMALL_BORDER_SIZE;
private static final int LARGE_CONTENT_SIZE = SMALL_CONTENT_SIZE * 2;
private static final int LARGE_BORDER_SIZE = SMALL_BORDER_SIZE * 2;
private static final int LARGE_TILE_SIZE = LARGE_CONTENT_SIZE + 2 * LARGE_BORDER_SIZE;
private static final int INIT_CAPACITY = 8;
// We are targeting at 60fps, so we have 16ms for each frame.
// In this 16ms, we use about 4~8 ms to upload tiles.
private static final long UPLOAD_TILE_LIMIT = 4; // ms
private static final PriorityThreadFactory sThreadFactory;
private static final PVLock sPVLock;
private static Tile sSmallFreeTileHead = null;
private static Tile sLargeFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private final Image mImage;
private int mUploadIndex = 0;
private final Tile[] mTiles; // Can be modified in different threads.
// Should be protected by "synchronized."
private final int mWidth;
private final int mHeight;
private final boolean mOpaque;
private final RectF mSrcRect = new RectF();
private final RectF mDestRect = new RectF();
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private boolean mImageBusy = false;
private final AtomicBoolean mNeedRecycle = new AtomicBoolean();
private final AtomicReference<Thread> mAnimateThread = new AtomicReference<>();
private WeakReference<Callback> mCallback;
static {
sThreadFactory = new PriorityThreadFactory("ImageTexture$AnimateTask", android.os.Process.THREAD_PRIORITY_BACKGROUND);
sPVLock = new PVLock(3);
}
public static class Uploader implements GLRoot.OnGLIdleListener {
private final ArrayDeque<ImageTexture> mTextures =
new ArrayDeque<>(INIT_CAPACITY);
private final GLRoot mGlRoot;
private boolean mIsQueued = false;
public Uploader(GLRoot glRoot) {
mGlRoot = glRoot;
}
public synchronized void clear() {
mTextures.clear();
}
public synchronized void addTexture(ImageTexture t) {
if (t.isReady()) return;
mTextures.addLast(t);
if (mIsQueued) return;
mIsQueued = true;
mGlRoot.addOnGLIdleListener(this);
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
ArrayDeque<ImageTexture> deque = mTextures;
synchronized (this) {
long now = SystemClock.uptimeMillis();
long dueTime = now + UPLOAD_TILE_LIMIT;
while (now < dueTime && !deque.isEmpty()) {
ImageTexture t = deque.peekFirst();
if (t.uploadNextTile(canvas)) {
deque.removeFirst();
mGlRoot.requestRender();
}
now = SystemClock.uptimeMillis();
}
mIsQueued = !mTextures.isEmpty();
// return true to keep this listener in the queue
return mIsQueued;
}
}
}
private static class Tile extends NativeTexture {
@TileType
private int mTileType;
public int offsetX;
public int offsetY;
public Image image;
public Tile nextFreeTile;
public int contentWidth;
public int contentHeight;
public int borderSize;
public void setSize(@TileType int tileType, int width, int height) {
mTileType = tileType;
int tileSize;
if (tileType == TILE_SMALL) {
borderSize = SMALL_BORDER_SIZE;
tileSize = SMALL_TILE_SIZE;
} else if (tileType == TILE_LARGE) {
borderSize = LARGE_BORDER_SIZE;
tileSize = LARGE_TILE_SIZE;
} else {
throw new IllegalStateException("Not support tile type: " + tileType);
}
contentWidth = width;
contentHeight = height;
mWidth = width + 2 * borderSize;
mHeight = height + 2 * borderSize;
mTextureWidth = tileSize;
mTextureHeight = tileSize;
}
@Override
protected void texImage(boolean init) {
if (image != null && !image.isRecycled()) {
image.texImage(init, mTileType, offsetX, offsetY);
}
}
private void invalidate() {
invalidateContent();
image = null;
}
public void free() {
switch (mTileType) {
case TILE_SMALL:
freeSmallTile(this);
break;
case TILE_LARGE:
freeLargeTile(this);
break;
default:
throw new IllegalStateException("Not support tile type: " + mTileType);
}
}
private static void freeSmallTile(Tile tile) {
tile.invalidate();
synchronized (sFreeTileLock) {
tile.nextFreeTile = sSmallFreeTileHead;
sSmallFreeTileHead = tile;
}
}
private static void freeLargeTile(Tile tile) {
tile.invalidate();
synchronized (sFreeTileLock) {
tile.nextFreeTile = sLargeFreeTileHead;
sLargeFreeTileHead = tile;
}
}
}
private static Tile obtainSmallTile() {
synchronized (sFreeTileLock) {
Tile result = sSmallFreeTileHead;
if (result == null) {
return new Tile();
} else {
sSmallFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
}
return result;
}
}
private static Tile obtainLargeTile() {
synchronized (sFreeTileLock) {
Tile result = sLargeFreeTileHead;
if (result == null) {
return new Tile();
} else {
sLargeFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
}
return result;
}
}
private class AnimateRunnable implements Runnable {
public void doRun() {
long lastTime = SystemClock.elapsedRealtime();
long lastDelay = -1L;
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
return;
}
// Obtain image
mImageBusy = true;
}
boolean interrupted = Thread.currentThread().isInterrupted();
if (!mImage.isCompleted()) {
if (!interrupted) {
try {
sPVLock.p();
} catch (InterruptedException e) {
interrupted = true;
}
if (!interrupted && !mNeedRecycle.get()) {
mImage.complete();
}
sPVLock.v();
}
}
int frameCount = mImage.getFrameCount();
synchronized (mImage) {
// Release image
mImageBusy = false;
}
if (interrupted || mNeedRecycle.get() || frameCount <= 1) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
// Obtain
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
return;
}
// Obtain image
mImageBusy = true;
}
mImage.advance();
long delay = mImage.getDelay();
long time = SystemClock.elapsedRealtime();
if (-1L != lastDelay) {
delay -= (time - lastTime) - lastDelay;
}
lastTime = time;
lastDelay = delay;
mFrameDirty.lazySet(true);
invalidateSelf();
synchronized (mImage) {
// Release image
mImageBusy = false;
}
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
}
}
}
@Override
public void run() {
doRun();
while (mNeedRecycle.get()) {
// Obtain
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
break;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
break;
}
// Obtain image
mImageBusy = true;
}
mImage.recycle();
synchronized (mImage) {
// Release image
mImageBusy = false;
}
}
mAnimateThread.lazySet(null);
}
}
public ImageTexture(@NonNull Image image) {
mImage = image;
int width = mWidth = image.getWidth();
int height = mHeight = image.getHeight();
boolean opaque = mOpaque = image.isOpaque();
ArrayList<Tile> list = new ArrayList<>();
for (int x = 0; x < width; x += LARGE_CONTENT_SIZE) {
for (int y = 0; y < height; y += LARGE_CONTENT_SIZE) {
int w = Math.min(LARGE_CONTENT_SIZE, width - x);
int h = Math.min(LARGE_CONTENT_SIZE, height - y);
if (w <= SMALL_CONTENT_SIZE) {
Tile tile = obtainSmallTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_SMALL, w, Math.min(SMALL_CONTENT_SIZE, h));
tile.setOpaque(opaque);
list.add(tile);
int nextHeight = h - SMALL_CONTENT_SIZE;
if (nextHeight > 0) {
Tile nextTile = obtainSmallTile();
nextTile.offsetX = x;
nextTile.offsetY = y + SMALL_CONTENT_SIZE;
nextTile.image = image;
nextTile.setSize(TILE_SMALL, w, nextHeight);
nextTile.setOpaque(opaque);
list.add(nextTile);
}
} else if (h <= SMALL_CONTENT_SIZE) {
Tile tile = obtainSmallTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_SMALL, Math.min(SMALL_CONTENT_SIZE, w), h);
tile.setOpaque(opaque);
list.add(tile);
int nextWidth = w - SMALL_CONTENT_SIZE;
if (nextWidth > 0) {
Tile nextTile = obtainSmallTile();
nextTile.offsetX = x + SMALL_CONTENT_SIZE;
nextTile.offsetY = y;
nextTile.image = image;
nextTile.setSize(TILE_SMALL, nextWidth, h);
nextTile.setOpaque(opaque);
list.add(nextTile);
}
} else {
Tile tile = obtainLargeTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_LARGE, w, h);
tile.setOpaque(opaque);
list.add(tile);
}
}
}
mTiles = list.toArray(new Tile[list.size()]);
if (!mImage.isCompleted() || mImage.getFrameCount() > 1) {
Thread thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.lazySet(thread);
thread.start();
}
}
public final void setCallback(Callback cb) {
mCallback = new WeakReference<>(cb);
}
public Callback getCallback() {
if (mCallback != null) {
return mCallback.get();
}
return null;
}
public void invalidateSelf() {
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateImageTexture(this);
}
}
@Override
public void start() {
if (mImage.isRecycled() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
return;
}
Thread thread = mAnimateThread.get();
if (thread == null) {
thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.set(thread);
thread.start();
}
}
@Override
public void stop() {
if (!mImage.isRecycled() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
}
@Override
public boolean isRunning() {
return false;
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
synchronized (mTiles) {
Tile next = mTiles[mUploadIndex++];
// Make sure tile has not already been recycled by the time
// this is called (race condition in onGLIdle)
if (next.image != null) {
boolean hasBeenLoad = next.isLoaded();
next.updateContent(canvas);
// It will take some time for a texture to be drawn for the first
// time. When scrolling, we need to draw several tiles on the screen
// at the same time. It may cause a UI jank even these textures has
// been uploaded.
if (!hasBeenLoad) next.draw(canvas, 0, 0);
}
}
return mUploadIndex == mTiles.length;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
// We want to draw the "source" on the "target".
// This method is to find the "output" rectangle which is
// the corresponding area of the "src".
// (x,y) target
// (x0,y0) source +---------------+
// +----------+ | |
// | src | | output |
// | +--+ | linear map | +----+ |
// | +--+ | ----------> | | | |
// | | by (scaleX, scaleY) | +----+ |
// +----------+ | |
// Texture +---------------+
// Canvas
private static void mapRect(RectF output,
RectF src, float x0, float y0, float x, float y, float scaleX,
float scaleY) {
output.set(x + (src.left - x0) * scaleX,
y + (src.top - y0) * scaleY,
x + (src.right - x0) * scaleX,
y + (src.bottom - y0) * scaleY);
}
@RenderThread
private void syncFrame() {
if (mFrameDirty.getAndSet(false)) {
// invalid tiles
for (Tile tile : mTiles) {
tile.invalidateContent();
}
}
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
// Draws the texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) w / mWidth;
float scaleY = (float) h / mHeight;
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
// Draws a sub region of this texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) {
continue;
}
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
// Draws a mixed color of this texture and a specified color onto the
// a rectangle. The used color is: from * (1 - ratio) + to * ratio.
public void drawMixed(GLCanvas canvas, int color, float ratio,
int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawMixed(t, color, ratio, src, dest);
}
}
public void drawMixed(GLCanvas canvas, int color, float ratio,
RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) {
continue;
}
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawMixed(t, color, ratio, src, dest);
}
}
@Override
public boolean isOpaque() {
return mOpaque;
}
public boolean isReady() {
return mUploadIndex == mTiles.length;
}
public void recycle() {
for (Tile mTile : mTiles) {
mTile.free();
}
boolean recycleNow;
synchronized (mImage) {
if (!mImageBusy) {
recycleNow = true;
mImageBusy = true;
} else {
recycleNow = false;
}
}
if (recycleNow) {
mImage.recycle();
synchronized (mImage) {
mImageBusy = false;
}
} else {
mNeedRecycle.set(true);
}
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
public interface Callback {
void invalidateImageTexture(ImageTexture who);
}
}
@@ -0,0 +1,183 @@
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import java.util.Arrays;
// TODO support multiline
/**
* Works like movable type.<br>
* <br>
* Only support single line now
*/
public class MovableTextTexture extends SpriteTexture {
private char[] mCharacters;
private float[] mWidths;
private float mHeight;
private float mMaxWidth;
private MovableTextTexture(Bitmap bitmap, int count, int[] rects, char[] characters,
float[] widths, float height, float maxWidth) {
super(bitmap, false, count, rects);
mCharacters = characters;
mWidths = widths;
mHeight = height;
mMaxWidth = maxWidth;
}
public int[] getTextIndexes(String text) {
char[] characters = mCharacters;
int length = text.length();
int[] indexes = new int[length];
for (int i = 0; i < length; i++) {
char ch = text.charAt(i);
indexes[i] = Arrays.binarySearch(characters, ch);
}
return indexes;
}
public float getTextWidth(String text) {
char[] characters = mCharacters;
float[] widths = mWidths;
float width = 0.0f;
for (int i = 0, n = text.length(); i < n; i++) {
char ch = text.charAt(i);
int index = Arrays.binarySearch(characters, ch);
if (index >= 0) {
width += widths[index];
} else {
width += mMaxWidth;
}
}
return width;
}
public float getTextWidth(int[] indexes) {
float[] widths = mWidths;
float width = 0.0f;
int length = indexes.length;
for (int i = 0; i < length; i++) {
int index = indexes[i];
if (index >= 0) {
width += widths[index];
} else {
width += mMaxWidth;
}
}
return width;
}
public float getMaxWidth() {
return mMaxWidth;
}
public float getTextHeight() {
return mHeight;
}
public void drawText(GLCanvas canvas, String text, int x, int y) {
char[] characters = mCharacters;
float[] widths = mWidths;
for (int i = 0, n = text.length(); i < n; i++) {
char ch = text.charAt(i);
int index = Arrays.binarySearch(characters, ch);
if (index >= 0) {
drawSprite(canvas, index, x, y);
x += widths[index];
} else {
x += mMaxWidth;
}
}
}
public void drawText(GLCanvas canvas, int[] indexes, int x, int y) {
float[] widths = mWidths;
for (int i = 0, n = indexes.length; i < n; i++) {
int index = indexes[i];
if (index >= 0) {
drawSprite(canvas, index, x, y);
x += widths[index];
} else {
x += mMaxWidth;
}
}
}
/**
* Create a TextTexture to draw text
*
* @param typeface the typeface
* @param size text size
* @param characters all Characters
* @return the TextTexture
*/
public static MovableTextTexture create(Typeface typeface, int size, int color, char[] characters) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(size);
paint.setColor(color);
paint.setTypeface(typeface);
Paint.FontMetricsInt fmi = paint.getFontMetricsInt();
int fixed = fmi.bottom;
int height = fmi.bottom - fmi.top;
int length = characters.length;
float[] widths = new float[length];
paint.getTextWidths(characters, 0, length, widths);
// Caculate bitmap size
float maxWidth = 0.0f;
for (float f : widths) {
maxWidth = Math.max(maxWidth, f);
}
int hCount = (int) Math.ceil(Math.sqrt(height / maxWidth * length));
int vCount = (int) Math.ceil(Math.sqrt(maxWidth / height * length));
if (hCount * (vCount - 1) > length) {
vCount--;
}
if ((hCount - 1) * vCount > length) {
hCount--;
}
Bitmap bitmap = Bitmap.createBitmap((int) Math.ceil(hCount * maxWidth),
(int) Math.ceil(vCount * height), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(0, height - fixed);
// Draw
int[] rects = new int[length * 4];
int x = 0;
int y = 0;
for (int i = 0; i < length; i++) {
int offset = i * 4;
rects[offset + 0] = x;
rects[offset + 1] = y;
rects[offset + 2] = (int) widths[i];
rects[offset + 3] = height;
canvas.drawText(characters, i, 1, x, y, paint);
if (i % hCount == hCount - 1) {
// The end of row
x = 0;
y += height;
} else {
x += maxWidth;
}
}
return new MovableTextTexture(bitmap, length, rects, characters, widths, height, maxWidth);
}
}
Loaded 100 of 480 files, more files were not shown because too many files have changed in this diff. Show more